/
chemistry.py
1320 lines (1124 loc) · 45.2 KB
/
chemistry.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from collections import OrderedDict, defaultdict
from functools import reduce
from itertools import chain
from operator import mul, add
import math
import warnings
from .util.arithmeticdict import ArithmeticDict
from .util._expr import Expr
from .util.periodic import mass_from_composition
from .util.parsing import (
formula_to_composition, to_reaction,
formula_to_latex, formula_to_unicode, formula_to_html
)
from .units import default_units, is_quantity, unit_of, to_unitless
from ._util import intdiv
from .util.pyutil import deprecated, DeferredImport, ChemPyDeprecationWarning
ReactionSystem = DeferredImport('chempy.reactionsystem', 'ReactionSystem',
[deprecated(use_instead='chempy.ReactionSystem')])
class Substance(object):
""" Class representing a chemical substance
Parameters
----------
name : str
charge : int (optional, default: None)
Will be stored in composition[0], prefer composition when possible.
latex_name : str
unicode_name : str
html_name : str
composition : dict 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).
data : dict
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)}}``.
Attributes
----------
mass
Maps to data['mass'], and when unavailable looks for ``formula.mass``.
attrs
A tuple of attribute names for serialization.
composition : dict or None
Dictionary mapping fragment key (str) to amount (int).
data
Free form dictionary.
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}^{+}'
"""
attrs = (
'name', 'latex_name', 'unicode_name', 'html_name',
'composition', 'data'
)
def __eq__(self, other):
for attr in self.attrs:
if getattr(self, attr) != getattr(other, attr):
return False
return True
@property
def charge(self):
""" Convenience property for accessing ``composition[0]`` """
return self.composition.get(0, 0) # electron (net) deficiency
@property
def mass(self):
""" Convenience property for accessing ``data['mass']``
when ``data['mass']`` is missing the mass is calculated
from the :attr:`composition` using
:func:`chempy.util.parsing.mass_from_composition`.
"""
try:
return self.data['mass']
except KeyError:
if self.composition is not None:
return mass_from_composition(self.composition)
@mass.setter
def mass(self, value):
self.data['mass'] = value
def molar_mass(self, units=None):
""" Returns the molar mass (with units) of the substance
Examples
--------
>>> nh4p = Substance.from_formula('NH4+') # simpler
>>> from chempy.units import default_units as u
>>> nh4p.molar_mass(u)
array(18.0384511...) * g/mol
"""
if units is None:
units = default_units
return self.mass*units.g/units.mol
def __init__(self, name=None, charge=None, latex_name=None, unicode_name=None,
html_name=None, composition=None, data=None):
self.name = name
self.latex_name = latex_name
self.unicode_name = unicode_name
self.html_name = html_name
self.composition = composition
if self.composition is not None and 0 in self.composition:
if charge is not None:
raise KeyError("Cannot give both charge and composition[0]")
else:
if charge is not None and composition is not None:
self.composition[0] = charge
self.data = data or {}
@classmethod
def from_formula(cls, formula, **kwargs):
""" Creates a :class:`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}'
"""
return cls(formula, latex_name=formula_to_latex(formula),
unicode_name=formula_to_unicode(formula),
html_name=formula_to_html(formula),
composition=formula_to_composition(formula),
**kwargs)
def __repr__(self):
kw = ['name=' + self.name + ', ...'] # Too verbose to print all
return "<{}({})>".format(self.__class__.__name__, ','.join(kw))
def __str__(self):
return str(self.name)
def _repr_html_(self):
return self.html_name
@staticmethod
def composition_keys(substance_iter, skip_keys=()):
""" Occuring :attr:`composition` keys among a series of substances """
keys = set()
for s in substance_iter:
if s.composition is None:
continue
for k in s.composition.keys():
if k in skip_keys:
continue
keys.add(k)
return sorted(keys)
class Species(Substance):
""" Substance belonging to a phase
Species extends :class:`Substance` with the new attribute :attr:`phase_idx`
Attributes
----------
phase_idx: int
Index of the phase (default is 0)
"""
def __init__(self, *args, **kwargs):
phase_idx = kwargs.pop('phase_idx', 0)
super(Species, self).__init__(*args, **kwargs)
self.phase_idx = phase_idx
@property
@deprecated(last_supported_version='0.3.0', will_be_missing_in='0.5.0')
def precipitate(self):
""" deprecated attribute, provided for compatibility for now """
return self.phase_idx > 0
@classmethod
def from_formula(cls, formula, phases=('(s)', '(l)', '(g)'),
default_phase_idx=0, **kwargs):
""" Create a :class:`Species` instance from its formula
Analogous to :meth:`Substance.from_formula` but with the addition that
phase_idx is determined from the formula (and a mapping provided by
``phases``)
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
of ``formula`` 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
default_phase_idx: int or None (default: 0)
If ``default_phase_idx`` is ``None``, ``ValueError`` is raised for
unkown suffixes.
Else ``default_phase_idx`` is used as ``phase_idx`` in those cases.
\\*\\*kwargs:
Keyword arguments passed on.
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
Raises
------
ValueError:
if ``default_phase_idx`` is ``None`` and no suffix found in phases
"""
if 'phase_idx' in kwargs:
p_i = kwargs.pop('phase_idx')
else:
p_i = None
if isinstance(phases, dict):
for k, v in phases.items():
if formula.endswith(k):
p_i = v
break
else:
for idx, phase in enumerate(phases):
if formula.endswith(phase):
p_i = idx + 1
break
if p_i is None:
if default_phase_idx is None:
raise ValueError("Could not determine phase_idx")
else:
p_i = default_phase_idx
return cls(
formula,
latex_name=formula_to_latex(formula, suffixes=phases),
unicode_name=formula_to_unicode(formula, suffixes=phases),
html_name=formula_to_html(formula, suffixes=phases),
composition=formula_to_composition(formula, suffixes=phases),
phase_idx=p_i, **kwargs
)
@deprecated(last_supported_version='0.3.0',
will_be_missing_in='0.7.0', use_instead=Species)
class Solute(Substance):
""" [DEPRECATED] Use `.Species` instead
Counter-intuitive to its name Solute has an additional
property 'precipitate'
"""
def __init__(self, *args, **kwargs):
precipitate = kwargs.pop('precipitate', False)
Substance.__init__(self, *args, **kwargs)
self.precipitate = precipitate
@classmethod
def from_formula(cls, formula, **kwargs):
if formula.endswith('(s)'):
kwargs['precipitate'] = True
return cls(formula, latex_name=formula_to_latex(formula),
unicode_name=formula_to_unicode(formula),
html_name=formula_to_html(formula),
composition=formula_to_composition(formula),
**kwargs)
class Reaction(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 of
:class:`chempy.kinetics.rates.RateExpr` or carry a :meth:`as_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
----------
reac : dict (str -> int)
If ``reac`` is a ``set``, then multiplicities are assumed to be 1.
prod : dict (str -> int)
If ``prod`` is a ``set``, then multiplicities are assumed to be 1.
param : float or callable
Special case (side-effect): if param is a subclass of
:class:`.kinetics.rates.RateExpr` and its :attr:`rxn`
is `None` it will be set to `self`.
inact_reac : dict (optional)
inact_prod : dict (optional)
name : str (optional)
k : deprecated (alias for param)
ref : object
Reference (e.g. a string containing doi number).
data : dict (optional)
checks : iterable of str
Raises ``ValueError`` if any method ``check_%s`` returns False
for all ``%s`` in ``checks``. Default: ``Reaction.default_checks``.
Attributes
----------
reac : OrderedDict
prod : OrderedDict
param : object
inact_reac : OrderedDict
inact_prod : OrderedDict
name : str
ref : str
data : dict
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
"""
_cmp_attr = ('reac', 'prod', 'param', 'inact_reac', 'inact_prod')
_all_attr = _cmp_attr + ('name', 'ref', 'data')
_str_arrow = '->'
param_char = 'k' # convention
default_checks = ('any_effect', 'all_positive', 'all_integral', 'consistent_units')
@staticmethod
def _init_stoich(container):
if isinstance(container, set):
container = {k: 1 for k in container}
container = container or {}
if type(container) == dict: # we don't want isinstance here in case of OrderedDict
container = OrderedDict(sorted(container.items(), key=lambda kv: kv[0]))
return container
def __init__(
self, reac, prod, param=None, inact_reac=None, inact_prod=None,
name=None, ref=None, data=None, checks=None):
self.reac = self._init_stoich(reac)
self.inact_reac = self._init_stoich(inact_reac)
self.prod = self._init_stoich(prod)
self.inact_prod = self._init_stoich(inact_prod)
self.param = param
self.name = name
self.ref = ref
self.data = data or {}
for check in (self.default_checks if checks is None else checks):
if not getattr(self, 'check_'+check)():
raise ValueError("Check failed: '%s'" % check)
@classmethod
def from_string(cls, string, substance_keys=None, globals_=None, **kwargs):
""" Parses a string into a Reaction instance
Parameters
----------
string : str
String representation of the reaction.
substance_keys : convertible 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.
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 -> B; 'k'", 'A B')
>>> r4.param.unique_keys
('k',)
>>> r5 = Reaction.from_string("A -> B; 1/molar/second", 'A B')
Traceback (most recent call last):
...
ValueError: Check failed: 'consistent_units'
Notes
-----
:func:`chempy.util.parsing.to_reaction` is used which in turn calls
:func:`eval` which is a severe security concern for untrusted input.
"""
if isinstance(substance_keys, str):
if ' ' in substance_keys:
substance_keys = substance_keys.split()
return to_reaction(string, substance_keys, cls._str_arrow, cls, globals_, **kwargs)
def copy(self, **kwargs):
if 'checks' not in kwargs:
kwargs['checks'] = ()
for k in self._all_attr:
if k not in kwargs:
kwargs[k] = getattr(self, k)
return self.__class__(**kwargs)
def check_any_effect(self):
""" Checks if the reaction has any effect """
if not any(self.net_stoich(self.keys())):
return False
return True
def check_all_positive(self):
""" Checks if all stoichiometric coefficients are positive """
for cont in (self.reac, self.prod, self.inact_reac, self.inact_prod):
for v in cont.values():
if v < 0:
return False
return True
def check_all_integral(self):
""" Checks if all stoichiometric coefficents are integers """
for cont in (self.reac, self.prod, self.inact_reac, self.inact_prod):
for v in cont.values():
if v != type(v)(int(v)):
return False
return True
def check_consistent_units(self):
if is_quantity(self.param): # This will assume mass action
try:
to_unitless(self.param/(
default_units.molar**(1-self.order())/default_units.s))
except Exception:
return False
else:
return True
else:
return True # the user might not be using ``chempy.units``
def __eq__(lhs, rhs):
if lhs is rhs:
return True
if not isinstance(lhs, Reaction) or not isinstance(rhs, Reaction):
return NotImplemented
for attr in lhs._cmp_attr:
if getattr(lhs, attr) != getattr(rhs, attr):
return False
return True
def __hash__(self):
return sum(map(hash, (getattr(self, k) for k in ['reac', 'prod', 'param', 'inact_reac', 'inact_prod'])))
def order(self):
""" Sum of (active) reactant stoichiometries """
return sum(self.reac.values())
def keys(self):
return set(chain(self.reac.keys(), self.prod.keys(),
self.inact_reac.keys(), self.inact_prod.keys()))
def net_stoich(self, substance_keys):
""" Per substance net stoichiometry tuple (active & inactive) """
return tuple(self.prod.get(k, 0) -
self.reac.get(k, 0) +
self.inact_prod.get(k, 0) -
self.inact_reac.get(k, 0) for k in substance_keys)
def all_reac_stoich(self, substances):
""" Per substance reactant stoichiometry tuple (active & inactive) """
return tuple(self.reac.get(k, 0) + self.inact_reac.get(k, 0) for k in substances)
def active_reac_stoich(self, substances):
""" Per substance reactant stoichiometry tuple (active) """
return tuple(self.reac.get(k, 0) for k in substances)
def all_prod_stoich(self, substances):
""" Per substance product stoichiometry tuple (active & inactive) """
return tuple(self.prod.get(k, 0) + self.inact_prod.get(k, 0) for k in substances)
def active_prod_stoich(self, substances):
""" Per substance product stoichiometry tuple (active) """
return tuple(self.prod.get(k, 0) for k in substances)
def _xprecipitate_stoich(self, substances, xor):
return tuple((
0 if xor ^ (getattr(v, 'phase_idx', 0) > 0) else
self.prod.get(k, 0) + self.inact_prod.get(k, 0) -
self.reac.get(k, 0) - self.inact_reac.get(k, 0)
) for k, v in substances.items())
def precipitate_stoich(self, substances):
""" Only stoichiometry of precipitates """
net = self._xprecipitate_stoich(substances, True)
found1 = -1
for idx in range(len(net)):
if net[idx] != 0:
if found1 == -1:
found1 = idx
else:
raise NotImplementedError("Only one precipitate assumed.")
return net, net[found1], found1
def non_precipitate_stoich(self, substances):
""" Only stoichiometry of non-precipitates """
return self._xprecipitate_stoich(substances, False)
def has_precipitates(self, substances):
for s_name in chain(self.reac.keys(), self.prod.keys(), self.inact_reac.keys(), self.inact_prod.keys()):
if getattr(substances[s_name], 'phase_idx', 0) > 0:
return True
return False
def string(self, substances=None, with_param=False, **kwargs):
""" 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)
Examples
--------
>>> r = Reaction({'H+': 1, 'Cl-': 1}, {'HCl': 1}, 1e10)
>>> r.string(with_param=False)
'Cl- + H+ -> HCl'
"""
from .printing import str_
return str_(self, substances=substances, with_param=with_param, **kwargs)
def __str__(self):
return self.string(with_param=True)
def latex(self, substances, with_param=False, **kwargs):
r""" 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)
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
"""
from .printing import latex
return latex(self, substances=substances, with_param=with_param, **kwargs)
def unicode(self, substances, with_param=False, **kwargs):
u""" 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
"""
from .printing import unicode_
return unicode_(self, substances=substances, with_param=with_param, **kwargs)
def html(self, substances, with_param=False, **kwargs):
""" 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)'
"""
from .printing import html
return html(self, with_param=with_param, substances=substances, **kwargs)
def _repr_html_(self):
return self.html({k: k for k in self.keys()})
def _violation(self, substances, attr):
net = 0.0
for substance, coeff in zip(substances.values(),
self.net_stoich(substances.keys())):
net += getattr(substance, attr) * coeff
return net
def mass_balance_violation(self, substances):
""" Net amount of mass produced
Parameters
----------
substances: dict
Returns
-------
float: amount of net mass produced/consumed
"""
return self._violation(substances, 'mass')
def charge_neutrality_violation(self, substances):
""" Net amount of charge produced
Parameters
----------
substances: dict
Returns
-------
float: amount of net charge produced/consumed
"""
return self._violation(substances, 'charge')
def composition_violation(self, substances, composition_keys=None):
""" 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
----------
substances : dict
composition_keys : iterable of str, ``None`` or ``True``
When ``None`` or True: composition keys are taken from substances.
When ``True`` the keys are also return as an extra return value
Returns
-------
- If ``composition_keys == True``: a tuple: (violations, composition_keys)
- Otherwise: violations (list of coefficients)
"""
keys, values = zip(*substances.items())
ret_comp_keys = composition_keys is True
if composition_keys in (None, True):
composition_keys = Substance.composition_keys(values)
net = [0]*len(composition_keys)
for substance, coeff in zip(values, self.net_stoich(keys)):
for idx, key in enumerate(composition_keys):
net[idx] += substance.composition.get(key, 0) * coeff
if ret_comp_keys:
return net, composition_keys
else:
return net
def rate_expr(self):
""" 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 in ``unique_keys`` if it is a string,
otherwise it will be used as ``args``.
Examples
--------
>>> r = Reaction.from_string('2 A + B -> 3 C; 7')
>>> ratex = r.rate_expr()
>>> ratex.args[0] == 7
True
"""
from .util._expr import Expr
from .kinetics import MassAction
if isinstance(self.param, Expr):
return self.param
else:
try:
convertible = self.param.as_RateExpr
except AttributeError:
if isinstance(self.param, str):
return MassAction.fk(self.param)
else:
return MassAction([self.param])
else:
return convertible()
def rate(self, variables=None, backend=math, substance_keys=None, ratex=None):
""" Evaluate the rate of a reaction
Parameters
----------
variables : dict
backend : module, optional
substance_keys : iterable of str, optional
ratex : RateExpr
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}
"""
if variables is None:
variables = {}
if substance_keys is None:
substance_keys = self.keys()
if ratex is None:
ratex = self.rate_expr()
if isinstance(ratex, Expr):
srat = ratex(variables, backend=backend, reaction=self)
else:
srat = ratex
return {k: srat*v for k, v in zip(substance_keys, self.net_stoich(substance_keys))}
def equilibrium_quotient(concs, stoich):
""" 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'
"""
import numpy as np
if not hasattr(concs, 'ndim') or concs.ndim == 1:
tot = 1
else:
tot = np.ones(concs.shape[0])
concs = concs.T
for nr, conc in zip(stoich, concs):
tot *= conc**nr
return tot
class Equilibrium(Reaction):
""" Represents an equilibrium reaction
See :class:`Reaction` for parameters
"""
_str_arrow = '='
param_char = 'K' # convention
def check_consistent_units(self):
if is_quantity(self.param): # This will assume mass action
exponent = sum(self.prod.values()) - sum(self.reac.values())
return unit_of(self.param, simplified=True) == unit_of(
default_units.molar**exponent, simplified=True)
else:
return True # the user might not be using ``chempy.units``
def as_reactions(self, kf=None, kb=None, units=None, variables=None, backend=math, new_name=None):
""" Creates a forward and backward :class:`Reaction` pair
Parameters
----------
kf : float or RateExpr
kb : float or RateExpr
units : module
variables : dict, optional
backend : module
"""
nb = sum(self.prod.values())
nf = sum(self.reac.values())
if units is None:
if hasattr(kf, 'units') or hasattr(kb, 'units'):
raise ValueError("units missing")
c0 = 1
else:
c0 = 1*units.molar # standard concentration IUPAC
if kf is None:
fw_name = self.name
bw_name = new_name
if kb is None:
try:
kf, kb = self.param
except TypeError:
raise ValueError("Exactly one rate needs to be provided")
else:
kf = kb * self.param * c0**(nb - nf)
elif kb is None:
kb = kf / (self.param * c0**(nb - nf))
fw_name = new_name
bw_name = self.name
else:
raise ValueError("Exactly one rate needs to be provided")
return (
Reaction(self.reac, self.prod, kf, self.inact_reac,
self.inact_prod, ref=self.ref, name=fw_name),
Reaction(self.prod, self.reac, kb, self.inact_prod,
self.inact_reac, ref=self.ref, name=bw_name)
)
def equilibrium_expr(self):
""" Turns self.param into a :class:`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
"""
from .util._expr import Expr
from .thermodynamics import MassActionEq
if isinstance(self.param, Expr):
return self.param
else:
try:
convertible = self.param.as_EqExpr
except AttributeError:
return MassActionEq([self.param])
else:
return convertible()
def equilibrium_constant(self, variables=None, backend=math):
""" Return equilibrium constant
Parameters
----------
variables : dict, optional
backend : module, optional
"""
return self.equilibrium_expr().eq_const(variables, backend=backend)
def equilibrium_equation(self, variables, backend=None, **kwargs):
return self.equilibrium_expr().equilibrium_equation(
variables, equilibrium=self, backend=backend, **kwargs)
@deprecated(use_instead=equilibrium_constant)
def K(self, *args, **kwargs):
return self.equilibrium_constant(*args, **kwargs)
def Q(self, substances, concs):
""" Calculates the equilibrium qoutient """
stoich = self.non_precipitate_stoich(substances)
return equilibrium_quotient(concs, stoich)
def precipitate_factor(self, substances, sc_concs):
factor = 1
for r, n in self.reac.items():
if r.precipitate:
factor *= sc_concs[substances.index(r)]**-n
for p, n in self.prod.items():
if p.precipitate:
factor *= sc_concs[substances.index(p)]**n
return factor
def dimensionality(self, substances):
result = 0
for r, n in self.reac.items():
if getattr(substances[r], 'phase_idx', 0) > 0:
continue
result -= n
for p, n in self.prod.items():
if getattr(substances[p], 'phase_idx', 0) > 0:
continue
result += n
return result
def __rmul__(self, other): # This works on both Py2 and Py3
try: