chempy package¶
ChemPy is a Python package useful for solving problems in chemistry.
Subpackages¶
- chempy.electrochemistry package
- chempy.kinetics package
- chempy.printing package
- chempy.properties package
- Submodules
- chempy.properties.debye_huckel_radii module
- chempy.properties.gas_sol_electrolytes_schumpe_1993 module
- chempy.properties.sulfuric_acid_density_myhre_1998 module
- chempy.properties.water_density_tanaka_2001 module
- chempy.properties.water_diffusivity_holz_2000 module
- chempy.properties.water_permittivity_bradley_pitzer_1979 module
- chempy.properties.water_viscosity_korson_1969 module
- chempy.thermodynamics package
- chempy.util package
- Submodules
- chempy.util.arithmeticdict module
- chempy.util.bkh module
- chempy.util.deprecation module
- chempy.util.graph module
- chempy.util.numutil module
- chempy.util.parsing module
- chempy.util.periodic module
- chempy.util.pyutil module
- chempy.util.regression module
- chempy.util.rendering module
- chempy.util.stoich module
- chempy.util.table module
- chempy.util.terminal module
- chempy.util.testing module
Submodules¶
chempy.arrhenius module¶
chempy.chemistry module¶
-
class
chempy.chemistry.
Equilibrium
(reac, prod, param=None, inact_reac=None, inact_prod=None, name=None, ref=None, data=None, checks=None, dont_check=None)[source]¶ Bases:
chempy.chemistry.Reaction
Represents an equilibrium reaction
See
Reaction
for parametersMethods
K
(\*args, \*\*kwargs)K is deprecated.
Q
(self, substances, concs)Calculates the equilibrium qoutient
active_prod_stoich
(self, substances)Per substance product stoichiometry tuple (active)
active_reac_stoich
(self, substances)Per substance reactant stoichiometry tuple (active)
all_prod_stoich
(self, substances)Per substance product stoichiometry tuple (active & inactive)
all_reac_stoich
(self, substances)Per substance reactant stoichiometry tuple (active & inactive)
as_reactions
(self[, kf, kb, units, …])Creates a forward and backward
Reaction
paircancel
(self, rxn)Multiplier of how many times rxn can be added/subtracted.
charge_neutrality_violation
(self, substances)Net amount of charge produced
check_all_integral
(self[, throw])Checks if all stoichiometric coefficents are integers
check_all_positive
(self[, throw])Checks if all stoichiometric coefficients are positive
check_any_effect
(self[, throw])Checks if the reaction has any effect
composition_violation
(self, substances[, …])Net amount of constituent produced
eliminate
(rxns, wrt)Linear combination coefficients for elimination of a substance
equilibrium_constant
(self[, variables, backend])Return equilibrium constant
equilibrium_expr
(self)Turns self.param into a
EqExpr
instance (if not already)from_string
(string[, substance_keys, globals_])Parses a string into a Reaction instance
html
(self, substances[, with_param, with_name])Returns a HTML representation of the reaction
latex
(self, substances[, with_param, with_name])Returns a LaTeX representation of the reaction
mass_balance_violation
(self, substances)Net amount of mass produced
net_stoich
(self, substance_keys)Per substance net stoichiometry tuple (active & inactive)
non_precipitate_stoich
(self, substances)Only stoichiometry of non-precipitates
order
(self)Sum of (active) reactant stoichiometries
precipitate_stoich
(self, substances)Only stoichiometry of precipitates
rate
(self[, variables, backend, …])Evaluate the rate of a reaction
rate_expr
(self)Turns self.param into a RateExpr instance (if not already)
string
(self[, substances, with_param, with_name])Returns a string representation of the reaction
unicode
(self, substances[, with_param, …])Returns a unicode string representation of the reaction
check_consistent_units
copy
dimensionality
equilibrium_equation
has_precipitates
keys
precipitate_factor
-
as_reactions
(self, kf=None, kb=None, units=None, variables=None, backend=<module 'math' from '/opt/cpython-3.7/lib/python3.7/lib-dynload/math.cpython-37m-x86_64-linux-gnu.so'>, new_name=None, **kwargs)[source]¶ Creates a forward and backward
Reaction
pair- Parameters
- kffloat or RateExpr
- kbfloat or RateExpr
- unitsmodule
- variablesdict, optional
- backendmodule
-
cancel
(self, rxn)[source]¶ Multiplier of how many times rxn can be added/subtracted.
- Parameters
- rxnEquilibrium
Examples
>>> e1 = Equilibrium({'Cd(OH)2(s)': 4, 'H2O': 4}, ... {'Cd4(OH)4+4': 1, 'H+': 4, 'OH-': 8}, 7.94e-91) >>> e2 = Equilibrium({'H2O': 1}, {'H+': 1, 'OH-': 1}, 10**-14) >>> e1.cancel(e2) -4 >>> print(e1 - 4*e2) 4 Cd(OH)2(s) = Cd4(OH)4+4 + 4 OH-; 7.94e-35
-
static
eliminate
(rxns, wrt)[source]¶ Linear combination coefficients for elimination of a substance
- Parameters
- rxnsiterable of Equilibrium instances
- wrtstr (substance key)
Examples
>>> e1 = Equilibrium({'Cd+2': 4, 'H2O': 4}, {'Cd4(OH)4+4': 1, 'H+': 4}, 10**-32.5) >>> e2 = Equilibrium({'Cd(OH)2(s)': 1}, {'Cd+2': 1, 'OH-': 2}, 10**-14.4) >>> Equilibrium.eliminate([e1, e2], 'Cd+2') [1, 4] >>> print(1*e1 + 4*e2) 4 Cd(OH)2(s) + 4 H2O = Cd4(OH)4+4 + 4 H+ + 8 OH-; 7.94e-91
-
equilibrium_constant
(self, variables=None, backend=<module 'math' from '/opt/cpython-3.7/lib/python3.7/lib-dynload/math.cpython-37m-x86_64-linux-gnu.so'>)[source]¶ Return equilibrium constant
- Parameters
- variablesdict, optional
- backendmodule, optional
-
equilibrium_expr
(self)[source]¶ Turns self.param into a
EqExpr
instance (if not already)Examples
>>> r = Equilibrium.from_string('2 A + B = 3 C; 7') >>> eqex = r.equilibrium_expr() >>> eqex.args[0] == 7 True
-
param_char
= 'K'¶
-
-
class
chempy.chemistry.
Reaction
(reac, prod, param=None, inact_reac=None, inact_prod=None, name=None, ref=None, data=None, checks=None, dont_check=None)[source]¶ Bases:
object
Class representing a chemical reaction
Consider for example:
2 R –> A + P; r = k*A*R*R
this would be represented as
Reaction({'A': 1, 'R': 2}, {'A': 2, 'P': 1}, param=k)
. Some reactions have a larger stoichiometric coefficient than what appears in the rate expression, e.g.:5 A + B –> C; r = k*A*B
this can be represented as
Reaction({'C1': 1, 'C2': 1}, {'B': 1}, inact_reac={'C1': 4}, param=k)
.The rate constant information in
param
may be a subclass ofchempy.kinetics.rates.RateExpr
or carry aas_RateExpr()
, if neither: param will be assumed to be a rate constant for a mass-action type of kinetic expression.Additional data may be stored in the
data
dict.- Parameters
- reacdict (str -> int)
If
reac
is aset
, then multiplicities are assumed to be 1.- proddict (str -> int)
If
prod
is aset
, then multiplicities are assumed to be 1.- paramfloat or callable
Special case (side-effect): if param is a subclass of
kinetics.rates.RateExpr
and itsrxn
is None it will be set to self.- inact_reacdict (optional)
- inact_proddict (optional)
- namestr (optional)
- kdeprecated (alias for param)
- refobject
Reference (e.g. a string containing doi number).
- datadict (optional)
- checksiterable of str
Raises
ValueError
if any methodcheck_%s
returns False for all%s
inchecks
. Default:Reaction.default_checks
.
Examples
>>> r = Reaction({'H2': 2, 'O2': 1}, {'H2O': 2}) >>> r.keys() == {'H2', 'O2', 'H2O'} True >>> r.order() 3 >>> r.net_stoich(['H2', 'H2O', 'O2']) (-2, 2, -1) >>> print(r) 2 H2 + O2 -> 2 H2O
- Attributes
- reacOrderedDict
- prodOrderedDict
- paramobject
- inact_reacOrderedDict
- inact_prodOrderedDict
- namestr
- refstr
- datadict
Methods
active_prod_stoich
(self, substances)Per substance product stoichiometry tuple (active)
active_reac_stoich
(self, substances)Per substance reactant stoichiometry tuple (active)
all_prod_stoich
(self, substances)Per substance product stoichiometry tuple (active & inactive)
all_reac_stoich
(self, substances)Per substance reactant stoichiometry tuple (active & inactive)
charge_neutrality_violation
(self, substances)Net amount of charge produced
check_all_integral
(self[, throw])Checks if all stoichiometric coefficents are integers
check_all_positive
(self[, throw])Checks if all stoichiometric coefficients are positive
check_any_effect
(self[, throw])Checks if the reaction has any effect
composition_violation
(self, substances[, …])Net amount of constituent produced
from_string
(string[, substance_keys, globals_])Parses a string into a Reaction instance
html
(self, substances[, with_param, with_name])Returns a HTML representation of the reaction
latex
(self, substances[, with_param, with_name])Returns a LaTeX representation of the reaction
mass_balance_violation
(self, substances)Net amount of mass produced
net_stoich
(self, substance_keys)Per substance net stoichiometry tuple (active & inactive)
non_precipitate_stoich
(self, substances)Only stoichiometry of non-precipitates
order
(self)Sum of (active) reactant stoichiometries
precipitate_stoich
(self, substances)Only stoichiometry of precipitates
rate
(self[, variables, backend, …])Evaluate the rate of a reaction
rate_expr
(self)Turns self.param into a RateExpr instance (if not already)
string
(self[, substances, with_param, with_name])Returns a string representation of the reaction
unicode
(self, substances[, with_param, …])Returns a unicode string representation of the reaction
check_consistent_units
copy
has_precipitates
keys
-
all_prod_stoich
(self, substances)[source]¶ Per substance product stoichiometry tuple (active & inactive)
-
all_reac_stoich
(self, substances)[source]¶ Per substance reactant stoichiometry tuple (active & inactive)
-
charge_neutrality_violation
(self, substances)[source]¶ Net amount of charge produced
- Parameters
- substances: dict
- Returns
- float: amount of net charge produced/consumed
-
check_all_integral
(self, throw=False)[source]¶ Checks if all stoichiometric coefficents are integers
-
check_all_positive
(self, throw=False)[source]¶ Checks if all stoichiometric coefficients are positive
-
composition_violation
(self, substances, composition_keys=None)[source]¶ Net amount of constituent produced
If composition keys correspond to conserved entities e.g. atoms in chemical reactions, this function should return a list of zeros.
- Parameters
- substancesdict
- composition_keysiterable of str,
None
orTrue
When
None
or True: composition keys are taken from substances. WhenTrue
the keys are also return as an extra return value
- Returns
- If
composition_keys == True
: a tuple: (violations, composition_keys)
- If
- Otherwise: violations (list of coefficients)
-
default_checks
= {'all_integral', 'all_positive', 'any_effect', 'consistent_units'}¶
-
classmethod
from_string
(string, substance_keys=None, globals_=None, **kwargs)[source]¶ Parses a string into a Reaction instance
- Parameters
- stringstr
String representation of the reaction.
- substance_keysconvertible to iterable of strings or string or None
Used prevent e.g. misspelling. if str: split is invoked, if None: no checking done.
- globals_dict (optional)
Dictionary for eval for (default: None -> {‘chempy’: chempy}) If
False
: no eval will be called (useful for web-apps).- **kwargs :
Passed on to constructor.
Notes
chempy.util.parsing.to_reaction()
is used which in turn callseval()
which is a severe security concern for untrusted input.Examples
>>> r = Reaction.from_string("H2O -> H+ + OH-; 1e-4", 'H2O H+ OH-') >>> r.reac == {'H2O': 1} and r.prod == {'H+': 1, 'OH-': 1} True >>> r2 = Reaction.from_string("2 H2O -> 2 H2 + O2", 'H2O H2 O2') >>> r2.reac == {'H2O': 2} and r2.prod == {'H2': 2, 'O2': 1} True >>> r3 = Reaction.from_string("A -> B; 1/second", 'A B') >>> from chempy.units import to_unitless, default_units as u >>> to_unitless(r3.param, u.hour**-1) 3600.0 >>> r4 = Reaction.from_string("A -> 2 B; 'k'", 'A B') >>> r4.rate(dict(A=3, B=5, k=7)) == {'A': -3*7, 'B': 2*3*7} True >>> r5 = Reaction.from_string("A -> B; 1/molar/second", 'A B') Traceback (most recent call last): ... ValueError: Unable to convert between units ...
-
html
(self, substances, with_param=False, with_name=False, **kwargs)[source]¶ Returns a HTML representation of the reaction
Examples
>>> keys = 'H2O H+ OH-'.split() >>> subst = {k: Substance.from_formula(k) for k in keys} >>> r = Reaction.from_string("H2O -> H+ + OH-; 1e-4", subst) >>> r.html(subst) 'H<sub>2</sub>O → H<sup>+</sup> + OH<sup>-</sup>' >>> r2 = Reaction.from_string("H+ + OH- -> H2O; 1e8/molar/second", subst) >>> r2.html(subst, with_param=True) 'H<sup>+</sup> + OH<sup>-</sup> → H<sub>2</sub>O; 10<sup>8</sup> 1/(s*M)'
-
latex
(self, substances, with_param=False, with_name=False, **kwargs)[source]¶ Returns a LaTeX representation of the reaction
- Parameters
- substances: dict
mapping substance keys to Substance instances
- with_param: bool
whether to print the parameter (default: False)
- with_name: bool
whether to print the name (default: False)
Examples
>>> keys = 'H2O H+ OH-'.split() >>> subst = {k: Substance.from_formula(k) for k in keys} >>> r = Reaction.from_string("H2O -> H+ + OH-; 1e-4", subst) >>> r.latex(subst) == r'H_{2}O \rightarrow H^{+} + OH^{-}' True >>> r2 = Reaction.from_string("H+ + OH- -> H2O; 1e8/molar/second", subst) >>> ref = r'H^{+} + OH^{-} \rightarrow H_{2}O; 10^{8} $\mathrm{\frac{1}{(s{\cdot}M)}}$' >>> r2.latex(subst, with_param=True) == ref True
-
mass_balance_violation
(self, substances)[source]¶ Net amount of mass produced
- Parameters
- substances: dict
- Returns
- float: amount of net mass produced/consumed
-
param_char
= 'k'¶
-
rate
(self, variables=None, backend=<module 'math' from '/opt/cpython-3.7/lib/python3.7/lib-dynload/math.cpython-37m-x86_64-linux-gnu.so'>, substance_keys=None, ratex=None)[source]¶ Evaluate the rate of a reaction
- Parameters
- variablesdict
- backendmodule, optional
- substance_keysiterable of str, optional
- ratexRateExpr
- Returns
- Dictionary mapping substance keys to the reactions contribution to overall rates.
Examples
>>> rxn1 = Reaction.from_string('2 H2 + O2 -> 2 H2O; 3') >>> ref1 = 3*5*5*7 >>> rxn1.rate({'H2': 5, 'O2': 7}) == {'H2': -2*ref1, 'O2': -ref1, 'H2O': 2*ref1} True >>> from sympy import Symbol >>> k = Symbol('k') >>> rxn2 = Reaction(rxn1.reac, rxn1.prod, k) >>> concentrations = {key: Symbol(key) for key in set.union(set(rxn1.reac), set(rxn1.prod))} >>> import pprint >>> pprint.pprint(rxn2.rate(concentrations)) {'H2': -2*H2**2*O2*k, 'H2O': 2*H2**2*O2*k, 'O2': -H2**2*O2*k}
-
rate_expr
(self)[source]¶ Turns self.param into a RateExpr instance (if not already)
Default is to create a
MassAction
instance. The parameter will be used as single instance inunique_keys
if it is a string, otherwise it will be used asargs
.Examples
>>> r = Reaction.from_string('2 A + B -> 3 C; 7') >>> ratex = r.rate_expr() >>> ratex.args[0] == 7 True
-
string
(self, substances=None, with_param=False, with_name=False, **kwargs)[source]¶ Returns a string representation of the reaction
- Parameters
- substances: dict
mapping substance keys to Substance instances
- with_param: bool
whether to print the parameter (default: False)
- with_name: bool
whether to print the name (default: False)
Examples
>>> r = Reaction({'H+': 1, 'Cl-': 1}, {'HCl': 1}, 1e10) >>> r.string(with_param=False) 'Cl- + H+ -> HCl'
-
unicode
(self, substances, with_param=False, with_name=False, **kwargs)[source]¶ Returns a unicode string representation of the reaction
Examples
>>> keys = 'H2O H+ OH-'.split() >>> subst = {k: Substance.from_formula(k) for k in keys} >>> r = Reaction.from_string("H2O -> H+ + OH-; 1e-4", subst) >>> r.unicode(subst) == u'H₂O → H⁺ + OH⁻' True >>> r2 = Reaction.from_string("H+ + OH- -> H2O; 1e8/molar/second", subst) >>> r2.unicode(subst, with_param=True) == u'H⁺ + OH⁻ → H₂O; 10⁸ 1/(s·M)' True
-
class
chempy.chemistry.
Solute
(*args, **kwargs)[source]¶ Bases:
chempy.chemistry.Solute
Solute is deprecated since (not including) 0.3.0, it will be missing in 0.8.0. Use Species instead.
[DEPRECATED] Use .Species instead
Counter-intuitive to its name Solute has an additional property ‘precipitate’
- Attributes
charge
Convenience property for accessing
composition[0]
mass
Convenience property for accessing
data['mass']
Methods
composition_keys
(substance_iter[, skip_keys])Occuring
composition
keys among a series of substancesfrom_formula
(formula, \*\*kwargs)Creates a
Substance
instance from its formulamolar_mass
(self[, units])Returns the molar mass (with units) of the substance
-
class
chempy.chemistry.
Species
(*args, **kwargs)[source]¶ Bases:
chempy.chemistry.Substance
Substance belonging to a phase
Species extends
Substance
with the new attributephase_idx
- Attributes
- phase_idx: int
Index of the phase (default is 0)
Methods
composition_keys
(substance_iter[, skip_keys])Occuring
composition
keys among a series of substancesfrom_formula
(formula[, phases, …])Create a
Species
instance from its formulamolar_mass
(self[, units])Returns the molar mass (with units) of the substance
-
classmethod
from_formula
(formula, phases=('(s)', '(l)', '(g)'), default_phase_idx=0, **kwargs)[source]¶ Create a
Species
instance from its formulaAnalogous to
Substance.from_formula()
but with the addition that phase_idx is determined from the formula (and a mapping provided byphases
)- Parameters
- formula: str
e.g. ‘H2O’, ‘NaCl(s)’, ‘CO2(aq)’, ‘CO2(g)’
- phases: iterable of str or dict mapping str -> int
if not in **kwargs,
phase_idx
is determined from the suffix offormula
where the suffixes is mapped from phases:- if
phases
is a dictionary: phase_idx = phases[suffix]
- else:
phase_idx = phases.index(suffix) + 1
and if suffixes is missing in phases phase_idx is taken to be 0
- if
- default_phase_idx: int or None (default: 0)
- If
default_phase_idx
isNone
,ValueError
is raised for unkown suffixes.
Else
default_phase_idx
is used asphase_idx
in those cases.- If
- **kwargs:
Keyword arguments passed on.
- Raises
- ValueError:
if
default_phase_idx
isNone
and no suffix found in phases
Examples
>>> water = Species.from_formula('H2O') >>> water.phase_idx 0 >>> NaCl = Species.from_formula('NaCl(s)') >>> NaCl.phase_idx 1 >>> Hg_l = Species.from_formula('Hg(l)') >>> Hg_l.phase_idx 2 >>> CO2g = Species.from_formula('CO2(g)') >>> CO2g.phase_idx 3 >>> CO2aq = Species.from_formula('CO2(aq)', default_phase_idx=None) Traceback (most recent call last): ... ValueError: Could not determine phase_idx >>> CO2aq = Species.from_formula('CO2(aq)') >>> CO2aq.phase_idx 0 >>> CO2aq = Species.from_formula('CO2(aq)', ['(aq)'], ... default_phase_idx=None) >>> CO2aq.phase_idx 1 >>> Species.from_formula('CO2(aq)', {'(aq)': 0}, None).phase_idx 0
-
property
precipitate
¶ precipitate is deprecated since (not including) 0.3.0, it will be missing in 0.8.0.
deprecated attribute, provided for compatibility for now
-
class
chempy.chemistry.
Substance
(name=None, charge=None, latex_name=None, unicode_name=None, html_name=None, composition=None, data=None)[source]¶ Bases:
object
Class representing a chemical substance
- Parameters
- namestr
- chargeint (optional, default: None)
Will be stored in composition[0], prefer composition when possible.
- latex_namestr
- unicode_namestr
- html_namestr
- compositiondict or None (default)
Dictionary (int -> number) e.g. {atomic number: count}, zero has special meaning (net charge). Avoid using the key 0 unless you specifically mean net charge. The motivation behind this is that it is easier to track a net-charge of e.g. 6 for U(VI) than it is to remember that uranium has 92 electrons and use 86 as the value).
- datadict
Free form dictionary. Could be simple such as
{'mp': 0, 'bp': 100}
or considerably more involved, e.g.:{'diffusion_coefficient': { 'water': lambda T: 2.1*m**2/s/K*(T - 273.15*K)}}
.
Examples
>>> ammonium = Substance('NH4+', 1, 'NH_4^+', composition={7: 1, 1: 4}, ... data={'mass': 18.0385, 'pKa': 9.24}) >>> ammonium.name 'NH4+' >>> ammonium.composition == {0: 1, 1: 4, 7: 1} # charge represented by key '0' True >>> ammonium.data['mass'] 18.0385 >>> ammonium.data['pKa'] 9.24 >>> ammonium.mass # mass is a special case (also attribute) 18.0385 >>> ammonium.pKa Traceback (most recent call last): ... AttributeError: 'Substance' object has no attribute 'pKa' >>> nh4p = Substance.from_formula('NH4+') # simpler >>> nh4p.composition == {7: 1, 1: 4, 0: 1} True >>> nh4p.latex_name 'NH_{4}^{+}'
- Attributes
mass
Convenience property for accessing
data['mass']
- attrs
A tuple of attribute names for serialization.
- compositiondict or None
Dictionary mapping fragment key (str) to amount (int).
- data
Free form dictionary.
Methods
composition_keys
(substance_iter[, skip_keys])Occuring
composition
keys among a series of substancesfrom_formula
(formula, \*\*kwargs)Creates a
Substance
instance from its formulamolar_mass
(self[, units])Returns the molar mass (with units) of the substance
-
attrs
= ('name', 'latex_name', 'unicode_name', 'html_name', 'composition', 'data')¶
-
property
charge
¶ Convenience property for accessing
composition[0]
-
static
composition_keys
(substance_iter, skip_keys=())[source]¶ Occuring
composition
keys among a series of substances
-
classmethod
from_formula
(formula, **kwargs)[source]¶ Creates a
Substance
instance from its formula- Parameters
- formula: str
e.g. ‘Na+’, ‘H2O’, ‘Fe(CN)6-4’
- **kwargs:
keyword arguments passed on to .Substance
Examples
>>> NH3 = Substance.from_formula('NH3') >>> NH3.composition == {1: 3, 7: 1} True >>> '%.2f' % NH3.mass '17.03' >>> NH3.charge 0 >>> NH3.latex_name 'NH_{3}'
-
property
mass
¶ Convenience property for accessing
data['mass']
when
data['mass']
is missing the mass is calculated from thecomposition
usingchempy.util.parsing.mass_from_composition()
.
-
chempy.chemistry.
balance_stoichiometry
(reactants, products, substances=None, substance_factory=<bound method Substance.from_formula of <class 'chempy.chemistry.Substance'>>, parametric_symbols=None, underdetermined=True, allow_duplicates=False)[source]¶ Balances stoichiometric coefficients of a reaction
- Parameters
- reactantsiterable of reactant keys
- productsiterable of product keys
- substancesOrderedDict or string or None
Mapping reactant/product keys to instances of
Substance
.- substance_factorycallback
- parametric_symbolsgenerator of symbols
Used to generate symbols for parametric solution for under-determined system of equations. Default is numbered “x-symbols” starting from 1.
- underdeterminedbool
Allows to find a non-unique solution (in addition to a constant factor across all terms). Set to
False
to disallow (raise ValueError) on e.g. “C + O2 -> CO + CO2”. Set toNone
if you want the symbols replaced so that the coefficients are the smallest possible positive (non-zero) integers.- allow_duplicatesbool
If False: raises an excpetion if keys appear in both
reactants
andproducts
.
- Returns
- balanced reactantsdict
- balanced productsdict
Examples
>>> ref = {'C2H2': 2, 'O2': 3}, {'CO': 4, 'H2O': 2} >>> balance_stoichiometry({'C2H2', 'O2'}, {'CO', 'H2O'}) == ref True >>> ref2 = {'H2': 1, 'O2': 1}, {'H2O2': 1} >>> balance_stoichiometry('H2 O2'.split(), ['H2O2'], 'H2 O2 H2O2') == ref2 True >>> reac, prod = 'CuSCN KIO3 HCl'.split(), 'CuSO4 KCl HCN ICl H2O'.split() >>> Reaction(*balance_stoichiometry(reac, prod)).string() '4 CuSCN + 7 KIO3 + 14 HCl -> 4 CuSO4 + 7 KCl + 4 HCN + 7 ICl + 5 H2O' >>> balance_stoichiometry({'Fe', 'O2'}, {'FeO', 'Fe2O3'}, underdetermined=False) Traceback (most recent call last): ... ValueError: The system was under-determined >>> r, p = balance_stoichiometry({'Fe', 'O2'}, {'FeO', 'Fe2O3'}) >>> list(set.union(*[v.free_symbols for v in r.values()])) [x1] >>> b = balance_stoichiometry({'Fe', 'O2'}, {'FeO', 'Fe2O3'}, underdetermined=None) >>> b == ({'Fe': 3, 'O2': 2}, {'FeO': 1, 'Fe2O3': 1}) True >>> d = balance_stoichiometry({'C', 'CO'}, {'C', 'CO', 'CO2'}, underdetermined=None, allow_duplicates=True) >>> d == ({'CO': 2}, {'C': 1, 'CO2': 1}) True
-
chempy.chemistry.
equilibrium_quotient
(concs, stoich)[source]¶ Calculates the equilibrium quotient of an equilbrium
- Parameters
- concs: array_like
per substance concentration
- stoich: iterable of integers
per substance stoichiometric coefficient
Examples
>>> '%.12g' % equilibrium_quotient([1.0, 1e-7, 1e-7], [-1, 1, 1]) '1e-14'
-
chempy.chemistry.
mass_fractions
(stoichiometries, substances=None, substance_factory=<bound method Substance.from_formula of <class 'chempy.chemistry.Substance'>>)[source]¶ Calculates weight fractions of each substance in a stoichiometric dict
- Parameters
- stoichiometriesdict or set
If a
set
: all entries are assumed to correspond to unit multiplicity.- substances: dict or None
Examples
>>> r = mass_fractions({'H2': 1, 'O2': 1}) >>> mH2, mO2 = 1.008*2, 15.999*2 >>> abs(r['H2'] - mH2/(mH2+mO2)) < 1e-4 True >>> abs(r['O2'] - mO2/(mH2+mO2)) < 1e-4 True >>> mass_fractions({'H2O2'}) == {'H2O2': 1.0} True
chempy.debye_huckel module¶
chempy.einstein_smoluchowski module¶
-
chempy.einstein_smoluchowski.
electrical_mobility_from_D
(D, charge, T, constants=None, units=None)[source]¶ Calculates the electrical mobility through Einstein-Smoluchowski relation.
- Parameters
- D: float with unit
Diffusion coefficient
- charge: integer
charge of the species
- T: float with unit
Absolute temperature
- constants: object (optional, default: None)
- if None:
T assumed to be in Kelvin and b0 = 1 mol/kg
- else:
see source code for what attributes are used. Tip: pass quantities.constants
- units: object (optional, default: None)
attributes accessed: meter, Kelvin and mol
- Returns
- Electrical mobility
chempy.electrolytes module¶
This modules collects expressions related to ionic strenght, e.g. the Debye-Hückel expressions.
-
chempy.electrolytes.
A
(eps_r, T, rho, b0=1, constants=None, units=None, backend=None)[source]¶ Debye Huckel constant A
- Parameters
- eps_r: float
relative permittivity
- T: float with unit
Temperature (default: assume Kelvin)
- rho: float with unit
density (default: assume kg/m**3)
- b0: float, optional
Reference molality, optionally with unit (amount / mass) IUPAC defines it as 1 mol/kg. (default: 1).
- units: object (optional, default: None)
attributes accessed: meter, Kelvin and mol
- constants: object (optional, default: None)
- if None:
T assumed to be in Kelvin and b0 = 1 mol/kg
- else:
see source code for what attributes are used. Tip: pass quantities.constants
Notes
Remember to divide by ln(10) if you want to use the constant with log10 based expression.
References
Atkins, De Paula, Physical Chemistry, 8th edition
-
chempy.electrolytes.
B
(eps_r, T, rho, b0=1, constants=None, units=None, backend=None)[source]¶ Extended Debye-Huckel parameter B
- Parameters
- eps_r: float
relative permittivity
- T: float with unit
temperature
- rho: float with unit
density
- b0: float with unit
reference molality
- units: object (optional, default: None)
attributes accessed: meter, Kelvin and mol
- constants: object (optional, default: None)
- if None:
T assumed to be in Kelvin, rho in kg/m**3 and b0 = 1 mol/kg
- else:
attributes accessed: molar_gas_constant, Faraday_constant Tip: pass quantities.constants
- Returns
- Debye Huckel B constant (default in m**-1)
-
class
chempy.electrolytes.
ExtendedDebyeHuckelActivityProduct
(stoich, *args)[source]¶ Bases:
chempy.electrolytes._ActivityProductBase
Methods
__call__
(self, c)Call self as a function.
-
class
chempy.electrolytes.
LimitingDebyeHuckelActivityProduct
(stoich, *args)[source]¶ Bases:
chempy.electrolytes._ActivityProductBase
Methods
__call__
(self, c)Call self as a function.
-
chempy.electrolytes.
davies_activity_product
(I, stoich, z, a, T, eps_r, rho, C=-0.3, backend=None)[source]¶
-
chempy.electrolytes.
extended_activity_product
(I, stoich, z, a, T, eps_r, rho, C=0, backend=None)[source]¶
-
chempy.electrolytes.
extended_log_gamma
(I, z, a, A, B, C=0, I0=1, backend=None)[source]¶ Debye-Huckel extended formula
-
chempy.electrolytes.
ionic_strength
(molalities, charges=None, units=None, substances=None, substance_factory=<bound method Substance.from_formula of <class 'chempy.chemistry.Substance'>>, warn=True)[source]¶ Calculates the ionic strength
- Parameters
- molalities: array_like or dict
Optionally with unit (amount / mass). when dict: mapping substance key to molality.
- charges: array_like
Charge of respective ion, taken for substances when None.
- units: object (optional, default: None)
Attributes accessed: molal.
- substances: dict, optional
Mapping of substance keys to Substance instances (used when molalities is a dict).
- substance_factory: callback
Used if substances is a string.
- warn: bool
Issue a warning if molalities violates net charge neutrality.
Examples
>>> ionic_strength([1e-3, 3e-3], [3, -1]) == .5 * (9 + 3) * 1e-3 True >>> ionic_strength({'Mg+2': 6, 'PO4-3': 4}) 30.0
chempy.equilibria module¶
Module collecting classes and functions for dealing with (multiphase) chemical equilibria.
Note
This module is provisional at the moment, i.e. the API is not stable and may break without a deprecation cycle.
-
class
chempy.equilibria.
EqSystem
(rxns, substances=None, name=None, checks=None, dont_check=None, substance_factory=<class 'chempy.chemistry.Substance'>, missing_substances_from_keys=False, sort_substances=None)[source]¶ Bases:
chempy.reactionsystem.ReactionSystem
- Attributes
nr
Number of reactions
ns
Number of substances
precipitate_rxn_idxs
precipitate_rxn_idxs is deprecated since (not including) 0.3.1, it will be missing in 0.8.0. Use phase_transfer_reaction_idxs instead.
precipitate_substance_idxs
precipitate_substance_idxs is deprecated since (not including) 0.3.1, it will be missing in 0.8.0. Use other_phase_species_idxs instead.
Methods
as_per_substance_array
(self, cont[, dtype, …])Turns a dict into an ordered array
as_substance_index
(self, substance_key)Returns the index of a Substance in the system
bimolecular_html_table
(\*args, \*\*kwargs)bimolecular_html_table is deprecated since (not including) 0.5.7, it will be missing in 0.8.0.
categorize_substances
(self, \*\*kwargs)Returns categories of substance keys (e.g.
check_balance
(self[, strict, throw])Checks if all reactions are balanced.
check_duplicate
(self[, throw])Raies ValueError if there are duplicates in
self.rxns
composition_balance_vectors
(self)Returns a list of lists with compositions and a list of composition keys.
concatenate
(rsystems[, cmp_attrs])Concatenates ReactionSystem instances
dissolved
(self, concs)Return dissolved concentrations
from_string
(s[, substances, …])Create a reaction system from a string
html
(self, \*args, \*\*kwargs)Returns a string with an HTML representation
identify_equilibria
(self)Returns a list of index pairs of reactions forming equilibria.
obeys_charge_neutrality
(self)Returns False if any reaction violate charge neutrality.
obeys_mass_balance
(self)Returns True if all reactions obeys mass balance, else False.
params
(self)Returns list of per reaction
param
valueper_substance_varied
(self, per_substance[, …])Dense nd-array for all combinations of varied levels per substance
rates
(self[, variables, backend, …])Per substance sums of reaction rates rates.
roots
(self, init_concs, varied_data, varied)- Parameters
sort_substances_inplace
(self[, key])Sorts the OrderedDict attribute
substances
split
(self, \*\*kwargs)Splits the reaction system into multiple disjoint reaction systems.
stoichs
(self[, non_precip_rids])Conditional stoichiometries depending on precipitation status
subset
(self, pred[, checks])Creates two new instances with the distinct subsets of reactions
substance_names
(self)Returns a tuple of the substances’ names
substance_participation
(self, substance_key)Returns indices of reactions where substance_key occurs
unimolecular_html_table
(\*args, \*\*kwargs)unimolecular_html_table is deprecated since (not including) 0.5.7, it will be missing in 0.8.0.
upper_conc_bounds
(self, init_concs[, min_, …])Calculates upper concentration bounds per substance based on substance composition.
active_prod_stoichs
active_reac_stoichs
all_prod_stoichs
all_reac_stoichs
as_per_substance_dict
check_duplicate_names
check_substance_keys
composition_conservation
eq_constants
equilibrium_quotients
get_neqsys
get_neqsys_chained_conditional
get_neqsys_conditional_chained
get_neqsys_static_conditions
net_stoichs
non_precip_rids
other_phase_species_idxs
per_reaction_effect_on_substance
phase_transfer_reaction_idxs
plot_errors
root
solve
stoichs_constants
string
substance_labels
-
get_neqsys_chained_conditional
(self, rref_equil=False, rref_preserv=False, NumSys=<class 'chempy._eqsys.NumSysLin'>, **kwargs)[source]¶
-
get_neqsys_conditional_chained
(self, rref_equil=False, rref_preserv=False, NumSys=<class 'chempy._eqsys.NumSysLin'>, **kwargs)[source]¶
-
get_neqsys_static_conditions
(self, rref_equil=False, rref_preserv=False, NumSys=(<class 'chempy._eqsys.NumSysLin'>, ), precipitates=None, **kwargs)[source]¶
-
html
(self, *args, **kwargs)[source]¶ Returns a string with an HTML representation
- Parameters
- with_parambool
- with_namebool
- checkstuple
- color_categoriesbool
- splitbool
- print_fncallable
default:
chempy.printing.html()
-
plot_errors
(self, concs, init_concs, varied_data, varied, axes=None, compositions=True, Q=True, subplot_kwargs=None)[source]¶
-
property
precipitate_rxn_idxs
¶ precipitate_rxn_idxs is deprecated since (not including) 0.3.1, it will be missing in 0.8.0. Use phase_transfer_reaction_idxs instead.
-
property
precipitate_substance_idxs
¶ precipitate_substance_idxs is deprecated since (not including) 0.3.1, it will be missing in 0.8.0. Use other_phase_species_idxs instead.
-
root
(self, init_concs, x0=None, neqsys=None, NumSys=<class 'chempy._eqsys.NumSysLog'>, neqsys_type='chained_conditional', **kwargs)[source]¶
-
roots
(self, init_concs, varied_data, varied, x0=None, NumSys=<class 'chempy._eqsys.NumSysLog'>, plot_kwargs=None, neqsys_type='chained_conditional', **kwargs)[source]¶ - Parameters
- init_concsarray or dict
- varied_dataarray
- varied_idxint or str
- x0array
- NumSys_NumSys subclass
See
NumSysLin
,NumSysLog
, etc.- plot_kwargsdict
See py:meth:pyneqsys.NeqSys.solve. Two additional keys are intercepted here:
latex_names: bool (default: False) conc_unit_str: str (default: ‘M’)
- neqsys_typestr
what method to use for NeqSys construction (get_neqsys_*)
- **kwargs :
Keyword argumetns passed on to py:meth:pyneqsys.NeqSys.solve_series.
chempy.eyring module¶
chempy.henry module¶
Module for dealing with constants Henry’s law.
-
class
chempy.henry.
Henry
[source]¶ Bases:
chempy.util.pyutil.Henry
Henry’s gas constant
Note that the reference temperature is set by the attribute
T0
which defaults to 298.15 (Kelvin).- Parameters
- Hcp: float
Henry’s constant [M/atm]
- Tderiv: float
dln(kH)/d(1/T) [K] Equivalent to $Delta_{soln}H / R$
- ref: object
Reference for origin of parameters
- units: object (optional)
object with attributes: kelvin
Examples
>>> H_H2 = Henry(1.2e-3, 1800, ref='carpenter_1966') >>> '%.2g' % H_H2(298.15) '0.0012'
- Attributes
Hcp
Alias for field number 0
T0
Alias for field number 2
Tderiv
Alias for field number 1
ref
Alias for field number 3
Methods
__call__
(self, T[, units, backend])Evaluates Henry’s constant for provided temperature
count
(self, value, /)Return number of occurrences of value.
get_P_at_T_and_c
(self, T, c, \*\*kwargs)Convenience method for calculating concentration
get_c_at_T_and_P
(self, T, P, \*\*kwargs)Convenience method for calculating concentration
get_kH_at_T
(\*args, \*\*kwargs)get_kH_at_T is deprecated since (not including) 0.3.1, it will be missing in 0.5.0.
index
(self, value[, start, stop])Return first index of value.
-
get_P_at_T_and_c
(self, T, c, **kwargs)[source]¶ Convenience method for calculating concentration
Calculate the partial pressure for given temperature and concentration
- Parameters
- T: float
Temperature
- P: float
Pressure
- **kwargs:
Keyword arguments passed on to
__call__()
-
class
chempy.henry.
HenryWithUnits
[source]¶ Bases:
chempy.henry.Henry
Analogous to
Henry
Examples
>>> from chempy.units import to_unitless, default_units as u >>> H_CO = HenryWithUnits(9.7e-6 * u.mol/u.m**3/u.Pa, 1300*u.K, ref='sander_2015') >>> '%.2g' % to_unitless(H_CO(298.15 * u.K), u.molar/u.bar) '0.00097'
- Attributes
Hcp
Alias for field number 0
T0
Alias for field number 2
Tderiv
Alias for field number 1
ref
Alias for field number 3
Methods
__call__
(self, T[, units, backend])Evaluates Henry’s constant for provided temperature
count
(self, value, /)Return number of occurrences of value.
get_P_at_T_and_c
(self, T, c, \*\*kwargs)Convenience method for calculating concentration
get_c_at_T_and_P
(self, T, P, \*\*kwargs)Convenience method for calculating concentration
get_kH_at_T
(\*args, \*\*kwargs)get_kH_at_T is deprecated since (not including) 0.3.1, it will be missing in 0.5.0.
index
(self, value[, start, stop])Return first index of value.
-
chempy.henry.
Henry_H_at_T
(T, H, Tderiv, T0=None, units=None, backend=None)[source]¶ Evaluate Henry’s constant H at temperature T
- Parameters
- T: float
Temperature (with units), assumed to be in Kelvin if
units == None
- H: float
Henry’s constant
- Tderiv: float (optional)
dln(H)/d(1/T), assumed to be in Kelvin if
units == None
.- T0: float
Reference temperature, assumed to be in Kelvin if
units == None
default: 298.15 K- units: object (optional)
object with attributes: kelvin (e.g. chempy.units.default_units)
- backendmodule (optional)
module with “exp”, default: numpy, math
chempy.reactionsystem module¶
-
class
chempy.reactionsystem.
ReactionSystem
(rxns, substances=None, name=None, checks=None, dont_check=None, substance_factory=<class 'chempy.chemistry.Substance'>, missing_substances_from_keys=False, sort_substances=None)[source]¶ Bases:
object
Collection of reactions forming a system (model).
- Parameters
- rxnssequence
Sequence of
Reaction
instances.- substancesOrderedDict or string or None
Mapping str -> Substance instances, None => deduced from reactions. If a set is passed as substances (or a string which is split), then
substance_factory
will be used to construct substances from the items.- namestring (optional)
Name of ReactionSystem (e.g. model name / citation key).
- checksiterable of str, optional
Raises
ValueError
if any methodcheck_%s
returns False for all%s
inchecks
. Default:ReactionSystem.default_checks
.- substance_factorycallback
Could also be e.g.
Substance.from_formula()
.- sort_substancesbool
Sort keys in substances lexicographically by key? default:
None
implies True unless substances is either one ofOrderedDict
, list, tuple or str.
- Raises
- ValueError
When any reaction occurs more than once
Examples
>>> from chempy import Reaction >>> r1 = Reaction({'R1': 1}, {'P1': 1}, 42.0) >>> rsys = ReactionSystem([r1], 'R1 P1') >>> rsys.as_per_substance_array({'R1': 2, 'P1': 3}) array([2., 3.])
- Attributes
Methods
as_per_substance_array
(self, cont[, dtype, …])Turns a dict into an ordered array
as_substance_index
(self, substance_key)Returns the index of a Substance in the system
bimolecular_html_table
(\*args, \*\*kwargs)bimolecular_html_table is deprecated since (not including) 0.5.7, it will be missing in 0.8.0.
categorize_substances
(self, \*\*kwargs)Returns categories of substance keys (e.g.
check_balance
(self[, strict, throw])Checks if all reactions are balanced.
check_duplicate
(self[, throw])Raies ValueError if there are duplicates in
self.rxns
Returns a list of lists with compositions and a list of composition keys.
concatenate
(rsystems[, cmp_attrs])Concatenates ReactionSystem instances
from_string
(s[, substances, …])Create a reaction system from a string
html
(self[, with_param, with_name, checks, …])Returns a string with an HTML representation
identify_equilibria
(self)Returns a list of index pairs of reactions forming equilibria.
obeys_charge_neutrality
(self)Returns False if any reaction violate charge neutrality.
obeys_mass_balance
(self)Returns True if all reactions obeys mass balance, else False.
params
(self)Returns list of per reaction
param
valueper_substance_varied
(self, per_substance[, …])Dense nd-array for all combinations of varied levels per substance
rates
(self[, variables, backend, …])Per substance sums of reaction rates rates.
sort_substances_inplace
(self[, key])Sorts the OrderedDict attribute
substances
split
(self, \*\*kwargs)Splits the reaction system into multiple disjoint reaction systems.
stoichs
(self[, non_precip_rids])Conditional stoichiometries depending on precipitation status
subset
(self, pred[, checks])Creates two new instances with the distinct subsets of reactions
substance_names
(self)Returns a tuple of the substances’ names
substance_participation
(self, substance_key)Returns indices of reactions where substance_key occurs
unimolecular_html_table
(\*args, \*\*kwargs)unimolecular_html_table is deprecated since (not including) 0.5.7, it will be missing in 0.8.0.
upper_conc_bounds
(self, init_concs[, min_, …])Calculates upper concentration bounds per substance based on substance composition.
active_prod_stoichs
active_reac_stoichs
all_prod_stoichs
all_reac_stoichs
as_per_substance_dict
check_duplicate_names
check_substance_keys
net_stoichs
per_reaction_effect_on_substance
string
-
as_per_substance_array
(self, cont, dtype='float64', unit=None, raise_on_unk=False)[source]¶ Turns a dict into an ordered array
- Parameters
- contarray_like or dict
- dtypestr or numpy.dtype object
- unitunit, optional
- raise_on_unkbool
-
bimolecular_html_table
(*args, **kwargs)[source]¶ bimolecular_html_table is deprecated since (not including) 0.5.7, it will be missing in 0.8.0. Use chempy.printing.tables.BimolecularTable instead.
-
categorize_substances
(self, **kwargs)[source]¶ Returns categories of substance keys (e.g. nonparticipating, unaffected etc.)
Some substances are only accumulated (i.e. irreversibly formed) and are never net reactants in any reactions, others are depleted (they are never net proucts in any reaction). Some substanaces are unaffected since they appear with equal coefficients on both reactant and product side, while some may be nonparticipating (they don’t appear on either side and have thus no effect on the reactionsystem).
- Parameters
- **kwargs:
Keyword arguments passed on to
ReactionSystem
.
- Returns
- dict of sets of substance keys, the dictionary has the following keys:
'accumulated'
: keys only participating as net products.'depleted'
: keys only participating as net reactants.'unaffected'
: keys appearing in reactions but with zero net effect.'nonparticipating'
: keys not appearing in any reactions.
-
check_balance
(self, strict=False, throw=False)[source]¶ Checks if all reactions are balanced.
- Parameters
- strictbool
Puts a requirement on all substances to have their
composition
attribute set.- throwbool
Raies ValueError if there are unbalanecd reactions in self.rxns
-
composition_balance_vectors
(self)[source]¶ Returns a list of lists with compositions and a list of composition keys.
The list of lists can be viewed as a matrix with rows corresponding to composition keys (which are given as the second item in the returned tuple) and columns corresponding to substances. Multiplying the matrix with a vector of concentrations give an equation which is an invariant (corresponds to mass & charge conservation).
- Returns
- A: list of lists
- ck: (sorted) tuple of composition keys
Examples
>>> s = 'Cu+2 + NH3 -> CuNH3+2' >>> import re >>> substances = re.split(r' \+ | -> ', s) >>> rsys = ReactionSystem.from_string(s, substances) >>> rsys.composition_balance_vectors() ([[2, 0, 2], [0, 3, 3], [0, 1, 1], [1, 0, 1]], [0, 1, 7, 29])
-
static
concatenate
(rsystems, cmp_attrs=['reac', 'inact_reac', 'prod', 'inact_prod'])[source]¶ Concatenates ReactionSystem instances
Reactions with identical stoichiometries are added to a separated reactionsystem for “duplicates”
- Parameters
- rsystemsiterable of ReactionSystem instances
- Returns
- pair of ReactionSystem instaces: the “sum” and “duplicates”
-
default_checks
= {'balance', 'duplicate', 'duplicate_names', 'substance_keys'}¶
-
classmethod
from_string
(s, substances=None, rxn_parse_kwargs=None, comment_tokens=('#', ), **kwargs)[source]¶ Create a reaction system from a string
- Parameters
- sstr
Multiline string.
- substancesconvertible to iterable of str
- rxn_parse_kwargsdict
Keyword arguments passed on to the Reaction baseclass’ method
from_string
.- comment_tokensiterable of str instances
Tokens which causes lines to be ignored when prefixed by any of them.
- substance_factorycallable
Defaults to
cls._BaseSubstance.from_formula
. Can be set to e.g.Substance
.- **kwargs:
Keyword arguments passed to the constructor of the class
Examples
>>> rs = ReactionSystem.from_string('\n'.join(['2 HNO2 -> H2O + NO + NO2; 3', '2 NO2 -> N2O4; 4'])) >>> r1, r2 = 5*5*3, 7*7*4 >>> rs.rates({'HNO2': 5, 'NO2': 7}) == {'HNO2': -2*r1, 'H2O': r1, 'NO': r1, 'NO2': r1 - 2*r2, 'N2O4': r2} True
-
html
(self, with_param=True, with_name=True, checks=(), color_categories=True, split=True, print_fn=None)[source]¶ Returns a string with an HTML representation
- Parameters
- with_parambool
- with_namebool
- checkstuple
- color_categoriesbool
- splitbool
- print_fncallable
default:
chempy.printing.html()
-
identify_equilibria
(self)[source]¶ Returns a list of index pairs of reactions forming equilibria.
The pairs are sorted with respect to index (lowest first)
-
property
nr
¶ Number of reactions
-
property
ns
¶ Number of substances
-
per_substance_varied
(self, per_substance, varied=None)[source]¶ Dense nd-array for all combinations of varied levels per substance
- Parameters
- per_substance: dict or array
- varied: dict
- Returns
- ndarraywith len(varied) + 1 number of axes, and with last axis length == self.ns
Examples
>>> rsys = ReactionSystem([], 'A B C') >>> arr, keys = rsys.per_substance_varied({'A': 2, 'B': 3, 'C': 5}, {'C': [5, 7, 9, 11]}) >>> arr.shape, keys ((4, 3), ('C',)) >>> all(arr[1, :] == [2, 3, 7]) True
-
rates
(self, variables=None, backend=<module 'math' from '/opt/cpython-3.7/lib/python3.7/lib-dynload/math.cpython-37m-x86_64-linux-gnu.so'>, substance_keys=None, ratexs=None, cstr_fr_fc=None)[source]¶ Per substance sums of reaction rates rates.
- Parameters
- variablesdict
- backendmodule, optional
- substance_keysiterable of str, optional
- ratexsiterable of RateExpr instances
- cstr_fr_fctuple (str, tuple of str)
Continuously stirred tank reactor conditions. Pair of flow/volume ratio key (feed-rate/tank-volume) and dict mapping feed concentration keys to substance keys.
- Returns
- dict
per substance_key time derivatives of concentrations.
Examples
>>> r = Reaction({'R': 2}, {'P': 1}, 42.0) >>> rsys = ReactionSystem([r]) >>> rates = rsys.rates({'R': 3, 'P': 5}) >>> abs(rates['P'] - 42*3**2) < 1e-14 True
-
sort_substances_inplace
(self, key=<function ReactionSystem.<lambda> at 0x7f8f52962488>)[source]¶ Sorts the OrderedDict attribute
substances
-
stoichs
(self, non_precip_rids=())[source]¶ Conditional stoichiometries depending on precipitation status
-
subset
(self, pred, checks=())[source]¶ Creates two new instances with the distinct subsets of reactions
First ReactionSystem will contain the reactions for which the predicate is True, the second for which it is False.
- Parameters
- predcallable
Signature:
pred(Reaction) -> bool
.- checkstuple
See
ReactionSystem
.
- Returns
- length 2 tuple
-
substance_participation
(self, substance_key)[source]¶ Returns indices of reactions where substance_key occurs
- Parameters
- substance_key: str
- Returns
- List of indices for self.rxns where substance_key participates
Examples
>>> rs = ReactionSystem.from_string('2 H2 + O2 -> 2 H2O\n 2 H2O2 -> 2 H2O + O2') >>> rs.substance_participation('H2') [0] >>> rs.substance_participation('O2') [0, 1] >>> rs.substance_participation('O3') []
-
unimolecular_html_table
(*args, **kwargs)[source]¶ unimolecular_html_table is deprecated since (not including) 0.5.7, it will be missing in 0.8.0. Use chempy.printing.tables.UnimolecularTable instead.
-
upper_conc_bounds
(self, init_concs, min_=<built-in function min>, dtype=None, skip_keys=(0, ))[source]¶ Calculates upper concentration bounds per substance based on substance composition.
- Parameters
- init_concsdict or array_like
Per substance initial conidtions.
- min_callbable
- dtypedtype or None
- skip_keystuple
What composition keys to skip.
- Returns
- numpy.ndarray :
Per substance upper limit (ordered as
substances
).
Notes
The function does not take into account wheter there actually exists a reaction path leading to a substance. Note also that the upper limit is per substance, i.e. the sum of all upper bounds amount to more substance than available in
init_conc
.Examples
>>> rs = ReactionSystem.from_string('2 HNO2 -> H2O + NO + NO2 \n 2 NO2 -> N2O4') >>> from collections import defaultdict >>> c0 = defaultdict(float, HNO2=20) >>> ref = {'HNO2': 20, 'H2O': 10, 'NO': 20, 'NO2': 20, 'N2O4': 10} >>> rs.as_per_substance_dict(rs.upper_conc_bounds(c0)) == ref True
chempy.units module¶
The units module provides the following attributes:
chempy.units.default_units
chempy.units.default_constants
chempy.units.SI_base_registry
together with some functions.
Currently quantities is used as
the underlying package to handle units. If it is possible you should try to
only use the chempy.units
module (since it is likely that ChemPy
will change this backend at some point in the future). Therefore you should not
rely on any attributes of the Quantity
instances (and rather use
getter & setter functions in chempy.units).
-
class
chempy.units.
Backend
(underlying_backend=('numpy', 'math'))[source]¶ Bases:
object
Wrapper around modules such as numpy and math
Instances of Backend wraps a module, e.g. numpy and ensures that arguments passed on are unitless, i.e. it raises an error if a transcendental function is used with quantities with units.
- Parameters
- underlying_backendmodule, str or tuple of str
e.g. ‘numpy’ or (‘sympy’, ‘math’)
Examples
>>> import math >>> km, m = default_units.kilometre, default_units.metre >>> math.exp(3*km) == math.exp(3*m) True >>> be = Backend('math') >>> be.exp(3*km) Traceback (most recent call last): ... ValueError: Unable to convert between units of "km" and "dimensionless" >>> import numpy as np >>> np.sum([1000*pq.metre/pq.kilometre, 1]) 1001.0 >>> be_np = Backend(np) >>> be_np.sum([[1000*pq.metre/pq.kilometre, 1], [3, 4]], axis=1) array([2., 7.])
-
chempy.units.
compare_equality
(a, b)[source]¶ Returns True if two arguments are equal.
Both arguments need to have the same dimensionality.
- Parameters
- aquantity
- bquantity
Examples
>>> km, m = default_units.kilometre, default_units.metre >>> compare_equality(3*km, 3) False >>> compare_equality(3*km, 3000*m) True
-
chempy.units.
concatenate
(arrays, **kwargs)[source]¶ Patched version of numpy.concatenate
Examples
>>> from chempy.units import default_units as u >>> all(concatenate(([2, 3]*u.s, [4, 5]*u.s)) == [2, 3, 4, 5]*u.s) True
-
chempy.units.
format_string
(value, precision='%.5g', tex=False)[source]¶ Formats a scalar with unit as two strings
- Parameters
- value: float with unit
- precision: str
- tex: bool
LaTeX formatted or not? (no ‘$’ signs)
Examples
>>> print(' '.join(format_string(0.42*default_units.mol/default_units.decimetre**3))) 0.42 mol/decimetre**3 >>> print(' '.join(format_string(2/default_units.s, tex=True))) 2 \mathrm{\frac{1}{s}}
-
chempy.units.
get_derived_unit
(registry, key)[source]¶ Get the unit of a physcial quantity in a provided unit system.
- Parameters
- registry: dict (str: unit)
mapping ‘length’, ‘mass’, ‘time’, ‘current’, ‘temperature’, ‘luminous_intensity’, ‘amount’. If registry is
None
the function returns 1.0 unconditionally.- key: str
one of the registry keys or one of: ‘diffusivity’, ‘electricalmobility’, ‘permittivity’, ‘charge’, ‘energy’, ‘concentration’, ‘density’, ‘radiolytic_yield’.
Examples
>>> m, s = default_units.meter, default_units.second >>> get_derived_unit(SI_base_registry, 'diffusivity') == m**2/s True
-
chempy.units.
get_physical_quantity
(*args, **kwargs)[source]¶ get_physical_quantity is deprecated, it will be missing in 0.8.0. Use get_physical_dimensionality instead.
-
chempy.units.
html_of_unit
(quant)[source]¶ Returns HTML reperesentation of the unit of a quantity
Examples
>>> print(html_of_unit(2*default_units.m**2)) m<sup>2</sup>
-
chempy.units.
is_unitless
(expr)[source]¶ Returns
True
ifexpr
is unitless, otherwiseFalse
Examples
>>> is_unitless(42) True >>> is_unitless(42*default_units.kilogram) False
-
chempy.units.
latex_of_unit
(quant)[source]¶ Returns LaTeX reperesentation of the unit of a quantity
Examples
>>> print(latex_of_unit(1/default_units.kelvin)) \mathrm{\frac{1}{K}}
-
chempy.units.
linspace
(start, stop, num=50)[source]¶ Analogous to
numpy.linspace
.Examples
>>> abs(linspace(2, 8, num=3)[1] - 5) < 1e-15 True
-
chempy.units.
logspace_from_lin
(start, stop, num=50)[source]¶ Logarithmically spaced data points
Examples
>>> abs(logspace_from_lin(2, 8, num=3)[1] - 4) < 1e-15 True
-
chempy.units.
tile
(array, *args, **kwargs)[source]¶ Patched version of numpy.tile (with support for units)
-
chempy.units.
to_unitless
(value, new_unit=None)[source]¶ Nondimensionalization of a quantity.
- Parameters
- value: quantity
- new_unit: unit
Examples
>>> '%.1g' % to_unitless(1*default_units.metre, default_units.nm) '1e+09' >>> '%.1g %.1g' % tuple(to_unitless([1*default_units.m, 1*default_units.mm], default_units.nm)) '1e+09 1e+06'
-
chempy.units.
unicode_of_unit
(quant)[source]¶ Returns unicode reperesentation of the unit of a quantity
Examples
>>> print(unicode_of_unit(1/default_units.kelvin)) 1/K
-
chempy.units.
uniform
(container)[source]¶ Turns a list, tuple or dict with mixed units into one with uniform units.
- Parameters
- containertuple, list or dict
Examples
>>> km, m = default_units.kilometre, default_units.metre >>> uniform(dict(a=3*km, b=200*m)) {'b': array(200.0) * m, 'a': array(3000.0) * m}
-
chempy.units.
unit_of
(expr, simplified=False)[source]¶ Returns the unit of a quantity
Examples
>>> unit_of(42*pq.second) == unit_of(12*pq.second) True >>> unit_of(42) 1
-
chempy.units.
unit_registry_from_human_readable
(unit_registry)[source]¶ Deserialization of unit_registry.