chempy.util package¶
This package collects utility functions used throughout the ChemPy
package.
Submodules¶
chempy.util.arithmeticdict module¶
-
class
chempy.util.arithmeticdict.
ArithmeticDict
[source]¶ Bases:
collections.defaultdict
A dictionary which supports arithmetics
Subclassed from defaultdict, with support for addition, subtraction, multiplication and division. If other term/factor has a
keys()
method the arithmetics are performed on a key per key basis. Ifkeys()
is missing, the operation is broadcasted onto all values. Nonexisting keys are interpreted to signal a zero.Notes
__eq__
ignores values equal toself.default_factory()
Examples
>>> d1 = ArithmeticDict(float, {'a': 2.0, 'b': 3.0}) >>> d2 = ArithmeticDict(float, {'b': 5.0, 'c': 7.0}) >>> (d1 + d2) == {'a': 2., 'b': 8., 'c': 7., 'd': 0.} True >>> (d1 * d1) == {'a': 4.0, 'b': 9.0, 'z': 0} True >>> (d1 * d2) == {'b': 15} True >>> d1*2 == {'a': 4, 'b': 6} True >>> (d1 / {'a': 2, 'b': 11})['b'] == 3./11 True >>> d2/3 == {'b': 5./3, 'c': 7./3} True
- Attributes
default_factory
Factory for default value called by __missing__().
Methods
clear
()copy
(self)fromkeys
(iterable[, value])Create a new dictionary with keys from iterable and values set to value.
get
(self, key[, default])Return the value for key if key is in the dictionary, else default.
items
()keys
()pop
()If key is not found, d is returned if given, otherwise KeyError is raised
popitem
()2-tuple; but raise KeyError if D is empty.
setdefault
(self, key[, default])Insert key with a value of default if key is not in the dictionary.
update
()If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
values
()all_non_negative
isclose
chempy.util.bkh module¶
Utilities for plotting with bokeh.
-
chempy.util.bkh.
integration_with_sliders
(rsys, tend, c0, parameters, fig_kwargs=None, slider_kwargs=None, conc_bounds=None, x_axis_type='linear', y_axis_type='linear', integrate_kwargs=None, odesys_extra=None, get_odesys_kw=None, integrate=None)[source]¶ - Parameters
- rsysReactionSystem
- tendfloat like
- c0dict
Initial concentrations.
- parametersdict
Parameter values.
- fig_kwargsdict
Keyword-arguments passed to bokeh’s
Figure
.- slider_kwargsdict
Keyword-arguments passed to bokeh’s
Slider
.- conc_boundsdict of dicts
Mapping substance key to dict of bounds (‘start’, ‘end’, ‘step’).
- x_axis_typestr
- y_axis_typestr
- integrate_kwargsdict
Keyword-arguments passed to integrate.
- odesys_extratuple
If odesys & extra have already been generated (avoids call to
get_odesys
).- get_odesys_kwdict
Keyword-arguments passed to
get_odesys
.- integratecallback
Defaults to
odesys.integrate
.
chempy.util.deprecation module¶
-
class
chempy.util.deprecation.
Deprecation
(last_supported_version=None, will_be_missing_in=None, use_instead=None, issue=None, issues_url=None, warning=<class 'DeprecationWarning'>)[source]¶ Bases:
object
Decorator factory for deprecating functions or classes.
This class represent deprecations of functions or classes and is designed to be used with the
warnings
library.- Parameters
- last_supported_versionstr, optional
Version string, e.g.
'0.2.1'
.- will_be_missing_instr, optional
Version string, e.g.
'0.3.0'
.- use_insteadobject or str, optional
Function or class to use instead or descriptive string.
- issuestr, optional
- issues_urlcallback, optional
Converts issue to url, e.g.
lambda s: 'https://github.com/user/repo/issues/%s/' % s.lstrip('gh-')
.- warning: DeprecationWarning, optional
Any subclass of DeprecationWarning, tip: you may invoke:
warnings.simplefilter('once', MyWarning)
at module init.
Notes
DeprecationWarning
is ignored by default. Use custom warning and filter appropriately. Alternatively, run python with-W
flag or set the appropriate environment variable:$ python -c 'import warnings as w; w.warn("X", DeprecationWarning)' $ python -Wd -c 'import warnings as w; w.warn("X", DeprecationWarning)' -c:1: DeprecationWarning: X $ export PYTHONWARNINGS=d $ python -c 'import warnings as w; w.warn("X", DeprecationWarning)' -c:1: DeprecationWarning: X
Examples
>>> import warnings >>> warnings.simplefilter("error", DeprecationWarning) >>> @Deprecation() ... def f(): ... return 1 ... >>> f() Traceback (most recent call last): ... DeprecationWarning: f is deprecated. >>> @Deprecation(last_supported_version='0.4.0') ... def some_old_function(x): ... return x*x - x ... >>> Deprecation.inspect(some_old_function).last_supported_version '0.4.0' >>> @Deprecation(will_be_missing_in='1.0') ... class ClumsyClass(object): ... pass ... >>> Deprecation.inspect(ClumsyClass).will_be_missing_in '1.0' >>> warnings.resetwarnings()
Methods
__call__
(self, wrapped)Decorates function to be deprecated
inspect
(obj)Get the
Deprecation
instance of a deprecated function.-
classmethod
inspect
(obj)[source]¶ Get the
Deprecation
instance of a deprecated function.
chempy.util.graph module¶
Convenince functions for representing reaction systems as graphs.
-
chempy.util.graph.
rsys2dot
(rsys, tex=False, rprefix='r', rref0=1, nodeparams='[label="{}", shape=diamond]', colors=('maroon', 'darkgreen'), penwidths=None, include_inactive=True)[source]¶ Returns list of lines of DOT (graph description language) formated graph.
- Parameters
- rsys: ReactionSystem
- tex: bool (default False)
If set True, output will be LaTeX formated
- (Substance need to have latex_name attribute set)
- rprefix: string
Reaction enumeration prefix, default: r
- rref0: integer
Reaction enumeration inital counter value, default: 1
- nodeparams: string
DOT formated param list, default: [label={} shape=diamond]
- Returns
- list of lines of DOT representation of the graph representation.
-
chempy.util.graph.
rsys2graph
(rsys, fname, output_dir=None, prog=None, save=False, **kwargs)[source]¶ Convenience function to call rsys2dot and write output to file and render the graph
- Parameters
- rsysReactionSystem
- fnamestr
filename
- output_dirstr (optional)
path to directory (default: temporary directory)
- progstr (optional)
default: ‘dot’
- savebool
removes temporary directory if False, default: False
- **kwargs :
Keyword arguments passed along to py:func:rsys2dot.
- Returns
- str
Outpath
Examples
>>> rsys2graph(rsys, sbstncs, '/tmp/out.png')
chempy.util.parsing module¶
Functions for chemical formulae and reactions
-
chempy.util.parsing.
formula_to_composition
(formula, prefixes=None, suffixes=('(s)', '(l)', '(g)', '(aq)'))[source]¶ Parse composition of formula representing a chemical formula
Composition is represented as a dict mapping int -> int (atomic number -> multiplicity). “Atomic number” 0 represents net charge.
- Parameters
- formula: str
Chemical formula, e.g. ‘H2O’, ‘Fe+3’, ‘Cl-‘
- prefixes: iterable strings
Prefixes to ignore, e.g. (‘.’, ‘alpha-‘)
- suffixes: tuple of strings
Suffixes to ignore, e.g. (‘(g)’, ‘(s)’)
Examples
>>> formula_to_composition('NH4+') == {0: 1, 1: 4, 7: 1} True >>> formula_to_composition('.NHO-(aq)') == {0: -1, 1: 1, 7: 1, 8: 1} True >>> formula_to_composition('Na2CO3.7H2O') == {11: 2, 6: 1, 8: 10, 1: 14} True
-
chempy.util.parsing.
formula_to_html
(formula, prefixes=None, infixes=None, **kwargs)[source]¶ Convert formula string to html string representation
- Parameters
- formulastr
Chemical formula, e.g. ‘H2O’, ‘Fe+3’, ‘Cl-‘
- prefixesdict
Prefix transformations, default: greek letters and .
- infixesdict
Infix transformations, default: .
- suffixestuple of strings
Suffixes to keep, e.g. (‘(g)’, ‘(s)’)
Examples
>>> formula_to_html('NH4+') 'NH<sub>4</sub><sup>+</sup>' >>> formula_to_html('Fe(CN)6+2') 'Fe(CN)<sub>6</sub><sup>2+</sup>' >>> formula_to_html('Fe(CN)6+2(aq)') 'Fe(CN)<sub>6</sub><sup>2+</sup>(aq)' >>> formula_to_html('.NHO-(aq)') '⋅NHO<sup>-</sup>(aq)' >>> formula_to_html('alpha-FeOOH(s)') 'α-FeOOH(s)'
-
chempy.util.parsing.
formula_to_latex
(formula, prefixes=None, infixes=None, **kwargs)[source]¶ Convert formula string to latex representation
- Parameters
- formula: str
Chemical formula, e.g. ‘H2O’, ‘Fe+3’, ‘Cl-‘
- prefixes: dict
Prefix transofmrations, default: greek letters and .
- infixes: dict
Infix transformations, default: .
- suffixes: iterable of str
What suffixes not to interpret, default: (s), (l), (g), (aq)
Examples
>>> formula_to_latex('NH4+') 'NH_{4}^{+}' >>> formula_to_latex('Fe(CN)6+2') 'Fe(CN)_{6}^{2+}' >>> formula_to_latex('Fe(CN)6+2(aq)') 'Fe(CN)_{6}^{2+}(aq)' >>> formula_to_latex('.NHO-(aq)') '^\\bullet NHO^{-}(aq)' >>> formula_to_latex('alpha-FeOOH(s)') '\\alpha-FeOOH(s)'
-
chempy.util.parsing.
formula_to_unicode
(formula, prefixes=None, infixes=None, **kwargs)[source]¶ Convert formula string to unicode string representation
- Parameters
- formulastr
Chemical formula, e.g. ‘H2O’, ‘Fe+3’, ‘Cl-‘
- prefixesdict
Prefix transofmrations, default: greek letters and .
- infixesdict
Infix transofmrations, default: .
- suffixestuple of strings
Suffixes to keep, e.g. (‘(g)’, ‘(s)’)
Examples
>>> formula_to_unicode('NH4+') == u'NH₄⁺' True >>> formula_to_unicode('Fe(CN)6+2') == u'Fe(CN)₆²⁺' True >>> formula_to_unicode('Fe(CN)6+2(aq)') == u'Fe(CN)₆²⁺(aq)' True >>> formula_to_unicode('.NHO-(aq)') == u'⋅NHO⁻(aq)' True >>> formula_to_unicode('alpha-FeOOH(s)') == u'α-FeOOH(s)' True
-
chempy.util.parsing.
get_parsing_context
()[source]¶ returns the default dictionary for parsing strings in chempy
-
chempy.util.parsing.
to_reaction
(line, substance_keys, token, Cls, globals_=None, **kwargs)[source]¶ Parses a string into a Reaction object and substances
Reac1 + 2 Reac2 + (2 Reac1) -> Prod1 + Prod2; 10**3.7; ref=’doi:12/ab’ Reac1 = Prod1; 2.1;
- Parameters
- line: str
string representation to be parsed
- substance_keys: iterable of strings
Allowed names, e.g. (‘H2O’, ‘H+’, ‘OH-‘)
- tokenstr
delimiter token between reactant and product side
- Clsclass
e.g. subclass of Reaction
- globals_: dict (optional)
Globals passed on to
eval()
, whenNone
: chempy.units.default_units is used with ‘chempy’ and ‘default_units’ extra entries.
Notes
This function calls
eval()
, hence there are severe security concerns with running this on untrusted data.
chempy.util.periodic module¶
-
chempy.util.periodic.
mass_from_composition
(composition)[source]¶ Calculates molecular mass from atomic weights
- Parameters
- composition: dict
Dictionary mapping int (atomic number) to int (coefficient)
- Returns
- float
molecular weight in atomic mass units
Notes
Atomic number 0 denotes charge or “net electron defficiency”
Examples
>>> '%.2f' % mass_from_composition({0: -1, 1: 1, 8: 1}) '17.01'
chempy.util.pyutil module¶
General utilities and exceptions.
-
class
chempy.util.pyutil.
AttrDict
(*args, **kwargs)[source]¶ Bases:
dict
Subclass of dict with attribute access to keys
Methods
clear
()copy
()fromkeys
(iterable[, value])Create a new dictionary with keys from iterable and values set to value.
get
(self, key[, default])Return the value for key if key is in the dictionary, else default.
items
()keys
()pop
()If key is not found, d is returned if given, otherwise KeyError is raised
popitem
()2-tuple; but raise KeyError if D is empty.
setdefault
(self, key[, default])Insert key with a value of default if key is not in the dictionary.
update
()If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
values
()
-
class
chempy.util.pyutil.
AttributeContainer
(**kwargs)[source]¶ Bases:
object
Used to turn e.g. a dictionary to a module-like object.
- Parameters
- **kwargsdictionary
Examples
>>> def RT(T, const): ... return T*const.molar_gas_constant ... >>> from quantities import constants >>> RT(273.15, constants) array(273.15) * R >>> my_constants = AttributeContainer(molar_gas_constant=42) >>> RT(273.15, my_constants) 11472.3
Methods
as_dict
-
class
chempy.util.pyutil.
DeferredImport
(modname, arg=None, decorators=None)[source]¶ Bases:
object
- Attributes
- cache
Methods
__call__
(self, \*args, \*\*kwargs)Call self as a function.
-
property
cache
¶
-
class
chempy.util.pyutil.
NameSpace
(default)[source]¶ Bases:
object
Used to wrap, e.g. modules.
- Parameters
- defaultmodule
The underlying module. Acts as a fallback for attribute access.
Examples
>>> import numpy >>> my_numpy = NameSpace(numpy) >>> my_numpy.array = lambda *args, **kwargs: list(numpy.array(*args, **kwargs)) >>> isinstance(my_numpy.array([2, 3]), list) True >>> isinstance(numpy.array([2, 3]), list) False
Methods
as_dict
-
class
chempy.util.pyutil.
defaultkeydict
[source]¶ Bases:
collections.defaultdict
defaultdict where default_factory should have the signature key -> value
Examples
>>> d = defaultkeydict(lambda k: '[%s]' % k, {'a': '[a]', 'b': '[B]'}) >>> d['a'] '[a]' >>> d['b'] '[B]' >>> d['c'] '[c]'
- Attributes
default_factory
Factory for default value called by __missing__().
Methods
clear
()copy
()fromkeys
(iterable[, value])Create a new dictionary with keys from iterable and values set to value.
get
(self, key[, default])Return the value for key if key is in the dictionary, else default.
items
()keys
()pop
()If key is not found, d is returned if given, otherwise KeyError is raised
popitem
()2-tuple; but raise KeyError if D is empty.
setdefault
(self, key[, default])Insert key with a value of default if key is not in the dictionary.
update
()If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
values
()
-
chempy.util.pyutil.
defaultnamedtuple
(typename, field_names, defaults=())[source]¶ Generates a new subclass of tuple with default values.
- Parameters
- typenamestring
The name of the class.
- field_namesstr or iterable
An iterable of splitable string.
- defaultsiterable
Default values for
field_names
, counting[-len(defaults):]
.
- Returns
- A new tuple subclass named
typename
- A new tuple subclass named
Examples
>>> Body = defaultnamedtuple('Body', 'x y z density', (1.0,)) >>> Body.__doc__ 'Body(x, y, z, density)' >>> b = Body(10, z=3, y=5) >>> b._asdict() == dict(x=10, y=5, z=3, density=1.0) True
-
chempy.util.pyutil.
deprecated
(*args, **kwargs)[source]¶ Helper to
Deprecation
for using ChemPyDeprecationWarning.
-
chempy.util.pyutil.
multi_indexed_cases
(od, *, dict_=<class 'collections.OrderedDict'>, apply_keys=None, apply_values=None, apply_return=<class 'list'>, named_index=False)[source]¶ Returns a list of length-2 tuples
Each tuple consist of a multi-index (tuple of integers) and a dictionary.
- Parameters
- odOrderedDict
Maps each key to a number of values. Instances of
list
,tuple
,types.GeneratorType
,collections.abc.ItemsView
are converted toOrderedDict
.- dict_type, optional
Used in the result (see
Returns
).- apply_keyscallable, optional
Transformation of keys.
- apply_valuescallable, optional
Transformation of values.
- apply_returncallable, optional
Applied on return value.
None
for generator.- named_indexbool
Tuple of indices will be a
namedtuple
(requires all keys to bestr
).
- Returns
- List of length-2 tuples, each consisting of one tuple of indices and one dictionary (of type
dict_
).
- List of length-2 tuples, each consisting of one tuple of indices and one dictionary (of type
Examples
>>> from chempy.util.pyutil import multi_indexed_cases >>> cases = multi_indexed_cases([('a', [1, 2, 3]), ('b', [False, True])]) >>> len(cases) 6 >>> midxs, case_kws = zip(*cases) >>> midxs[0] (0, 0) >>> case_kws[0] == {'a': 1, 'b': False} True >>> d = {'a': 'foo bar'.split(), 'b': 'baz qux'.split()} >>> from chempy.util.pyutil import AttrDict >>> for nidx, case in multi_indexed_cases(d, dict_=AttrDict, named_index=True): ... if case.a == 'bar' and case.b == 'baz': ... print("{} {}".format(nidx.a, nidx.b)) ... 1 0
chempy.util.regression module¶
Contains rudimentary tools for regression: (iteratively) (weighted) least squares and functions for plotting the fit from the regression analysis.
-
chempy.util.regression.
avg_params
(opt_params, cov_params)[source]¶ Calculates the average parameters from a set of regression parameters.
- Parameters
- opt_paramsarray_like
of shape (nfits, nparams)
- cov_paramsarray_like
of shape (nfits, nparams, nparams)
- Returns
- avg_beta: weighted average of parameters
- var_avg_beta: variance-covariance matrix
-
chempy.util.regression.
irls
(x, y, w_cb=<function <lambda> at 0x7f8f52821ea0>, itermax=16, rmsdwtol=1e-08)[source]¶ Iteratively reweighted least squares
- Parameters
- xarray_like
- yarray_like
- w_cbcallbable
Weight callback, signature
(x, y, beta, cov) -> weight
. Predefined:irls.ones
: unit weights (default)irls.exp
: \(\mathrm{e}^{-\beta_2 x}\)irls.gaussian
: \(\mathrm{e}^{-\beta_2 x^2}\)irls.abs_residuals
: \(\lvert \beta_1 + \beta_2 x - y \rvert\)
- itermaxint
- rmsdwtolfloat
- plot_cbcallble
See
least_squares()
- plot_cb_kwargsdict
See
least_squares()
- Returns
- betalength-2 array
parameters
- cov2x2 array
variance-covariance matrix
- infodict
- Contains
success : bool
niter : int
weights : list of weighting arrays
- # Examples
- # ——–
- # beta, cov, info = irls([1, 2, 3], [3, 2.5, 2.1], irls.abs_residuals)
-
chempy.util.regression.
irls_units
(x, y, **kwargs)[source]¶ Units aware version of
irls()
- Parameters
- xarray_like
- yarray_like
- **kwargs
Keyword arguments passed on to
irls()
-
chempy.util.regression.
least_squares
(x, y, w=1)[source]¶ Least-squares (w or w/o weights) fit to data series.
Linear regression (unweighted or weighted).
- Parameters
- xarray_like
- yarray_like
- warray_like, optional
- Returns
- length 2 tuplepair of parameter estimates (intercept and slope)
- 2x2 arrayvariance-covariance matrix
- floatR-squared (goodness of fit)
References
Wikipedia & standard texts on least sqaures method. Comment regarding R2 in WLS:
Willett, John B., and Judith D. Singer. “Another cautionary note about R 2: Its use in weighted least-squares regression analysis.” The American Statistician 42.3 (1988): 236-238.
Examples
>>> import numpy as np >>> beta, vcv, R2 = least_squares([0, 1, 2], [1, 3, 5]) >>> all(abs(beta - np.array([1, 2])) < 1e-14), R2 == 1, (abs(vcv) < 1e-14).all() (True, True, True) >>> b1, v1, r2_1 = least_squares([1, 2, 3], [0, 1, 4], [1, 1, 1]) >>> b2, v2, r2_2 = least_squares([1, 2, 3], [0, 1, 4], [1, 1, .2]) >>> abs(b2[1] - 1) < abs(b1[1] - 1) True
-
chempy.util.regression.
least_squares_units
(x, y, w=1)[source]¶ Units-aware least-squares (w or w/o weights) fit to data series.
- Parameters
- xarray_like
- yarray_like
- warray_like, optional
-
chempy.util.regression.
plot_avg_params
(opt_params, cov_params, avg_params_result, label_cb=None, ax=None, title=False, xlabel=False, ylabel=False, flip=False, nsigma=1)[source]¶ Calculates the average parameters from a set of regression parameters
- Parameters
- opt_paramsarray_like
Of shape
(nfits, nparams)
.- cov_paramsarray_like
of shape (nfits, nparams, nparams)
- avg_params_resultlength-2 tuple
Result from
avg_parrams()
.- label_cbcallable
signature (beta, variance_beta) -> str
- axmatplotlib.axes.Axes
- titlebool or str
- xlabelbool or str
- ylabelbool or str
- flipbool
for plotting: (x, y) -> beta1, beta0
- nsigmaint
Multiplier for error bars
- Returns
- avg_beta: weighted average of parameters
- var_avg_beta: variance-covariance matrix
-
chempy.util.regression.
plot_fit
(x, y, beta, yerr=None, vcv_beta=None, r2=None, kw_data=None, kw_fit=None, fit_label_cb=None, ax=True, x_unit=1, y_unit=1, nsigma=1)[source]¶ Plot the result of a fit
- Parameters
- xarray_like
- yarray_like
- betaarray_like
- yerrarray_like
- vcv_betaarray_like
- kw_datadict
Keyword arguments to
plot
for x, y data- kw_fitdict
Keyword arguments to
plot
for fitted data- fit_label_cb: callable:
signature (beta, variance_beta, r2) -> str
- axmatplotlib.axes.Axes
Alternatively
True
orNone
- x_unitunit
- y_unitunit
- nsigmaint
Multiplier for errorbars when plotting.
-
chempy.util.regression.
plot_least_squares_fit
(x, y, beta_vcv_r2, yerr=None, plot_cb=None, plot_cb_kwargs=None, x_unit=1, y_unit=1)[source]¶ Performs Least-squares fit and plots data and fitted line
- Parameters
- xarray_like
- yarray_like
- beta_vcv_r2tuple
Result from
least_squares_fit()
.- plot_cbcallable
When
None
: usesplot_fit()
, when callable: signature(x, y, beta, yerr=None, fit_label_cb=lambda beta, vcv, r2: 'None') -> str
.- plot_cb_kwargs: dict, optional
Keyword arguments passed on to
plot_cb
(seeplot_fit()
for list of expected kwargs). Ifplot_cb
isTrue
it will be populated with defaults (kw_data, fit_label_cb, x_unit, y_unit).
chempy.util.rendering module¶
chempy.util.stoich module¶
Utility functions related to stoichiometry.
-
chempy.util.stoich.
decompose_yields
(yields, rxns, atol=1e-10)[source]¶ Decomposes yields into mass-action reactions
This function offers a way to express a reaction with non-integer stoichiometric coefficients as a linear combination of production reactions with integer coefficients.
Ak = y
A is (n_species x n_reactions) matrix, k is “rate coefficient”, y is yields
- Parameters
- yieldsOrderedDict
Specie names as keys and yields as values.
- rxnsiterable
Reaction
instances Dict keys must match those of
yields
each pair of dictionaries gives stoichiometry (1st is reactant, 2nd is products).- atolfloat
Absolute tolerance for residuals.
- Returns
- 1-dimensional array of effective rate coefficients.
- Raises
- ValueError
When atol is exceeded
- numpy.LinAlgError
When numpy.linalg.lstsq fails to converge
Examples
>>> from chempy import Reaction >>> h2a = Reaction({'H2O': 1}, {'H2': 1, 'O': 1}) >>> h2b = Reaction({'H2O': 1}, {'H2': 1, 'H2O2': 1}, inact_reac={'H2O': 1}) >>> decompose_yields({'H2': 3, 'O': 2, 'H2O2': 1}, [h2a, h2b]) array([2., 1.])
-
chempy.util.stoich.
get_coeff_mtx
(substances, stoichs)[source]¶ Create a net stoichiometry matrix from reactions described by pairs of dictionaries.
- Parameters
- substancessequence of keys in stoichs dict pairs
- stoichssequence of pairs of dicts
Pairs of reactant and product dicts mapping substance keys to stoichiometric coefficients (integers).
- Returns
- 2 dimensional array of shape (len(substances), len(stoichs))
chempy.util.table module¶
Convenience functions for presenting reaction systems in tables.
-
chempy.util.table.
render_tex_to_pdf
(contents, texfname, pdffname, output_dir, save)[source]¶ Generates a pdf from a tex file by calling pdflatex
- Parameters
- contentsstr
- texfnamepath
- pdffnamepath
- output_dirpath
- savepath or bool or str(bool)
-
chempy.util.table.
rsys2pdf_table
(rsys, output_dir=None, doc_template=None, doc_template_dict=None, save=True, landscape=False, **kwargs)[source]¶ Convenience function to render a ReactionSystem as e.g. a pdf using e.g. pdflatex.
- Parameters
- rsysReactionSystem
- output_dirpath to output directory
(default: system’s temporary folder)
- doc_templatestring
LaTeX boiler plate temlpate including preamble, document environment etc.
- doc_template_dictdict (string -> string)
dict used to render temlpate (excl. ‘table’)
- longtablebool
use longtable in defaults. (default: False)
- **kwargs :
passed on to rsys2table
-
chempy.util.table.
rsys2table
(rsys, table_template=None, table_template_dict=None, param_name='Rate constant', **kwargs)[source]¶ Renders user provided table_template with table_template_dict which also has ‘body’ entry generated from rsys2tablines.
Defaults is LaTeX table requiring booktabs package to be used (add usepackage{booktabs} to preamble).
- Parameters
- rsysReactionSystem
- table_templatestring
- table_tempalte_dictdict used to render table_template (excl. “body”)
- param_namestr
Column header for parameter column
- longtablebool
use longtable in defaults. (default: False)
- **kwargs :
passed onto rsys2tablines
-
chempy.util.table.
rsys2tablines
(rsys, rref0=1, coldelim=' & ', tex=True, ref_fmt=None, unit_registry=None, unit_fmt='{}', k_fmt='%.4g')[source]¶ Generates a table representation of a ReactionSystem.
- Parameters
- rsysReactionSystem
- rref0integer
default start of index counter (default: 1)
- coldelimstring
column delimiter (default: ‘ & ‘)
- texbool
use latex formated output (default: True)
- ref_fmtstring or callable
format string of
ref
attribute of reactions- unit_registryunit registry
optional (default: None)
chempy.util.terminal module¶
-
class
chempy.util.terminal.
Echo
(msg, indent=' ')[source]¶ Bases:
object
Context maganger for echoing variable assignments (in CPython)
-
class
chempy.util.terminal.
Notify
(msg=<function Notify.<lambda>>)[source]¶ Bases:
object
Methods
notify
-
class
chempy.util.terminal.
Timed
(msg=None, timer=<built-in function time>, fmt_s='.1f', out=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]¶ Bases:
object
Utility function for timing portions of your python script
- Parameters
- msgstr
- timercallable
You can switch to e.g.
time.process_time
but note that if other programs are called from e.g.subprocess.Popen
the time spent in those subprocesses will not be included.
Examples
>>> t = Timed("Counting stars...").tic(); stars.count(); t.toc_and_print() Counting stars... (42.0 s) [ ok] >>> with Timed("Counting sheep..."): ... n_sheep = animals.count('sheep') ... Counting sheep... (17.2 s) [ ok]
Methods
tic
toc
-
counting
= False¶
chempy.util.testing module¶
-
class
chempy.util.testing.
requires
(*reqs)[source]¶ Bases:
object
Conditional skipping (on requirements) of tests in pytest
Examples
>>> @requires('numpy', 'scipy') ... def test_sqrt(): ... import numpy as np ... assert np.sqrt(4) == 2 ... from scipy.special import zeta ... assert zeta(2) < 2 ... >>> @requires('numpy>=1.9.0') ... def test_nanmedian(): ... import numpy as np ... a = np.array([[10.0, 7, 4], [3, 2, 1]]) ... a[0, 1] = np.nan ... assert np.nanmedian(a) == 3 ...
Methods
__call__
(self, cb)Call self as a function.