desr 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
desr/__init__.py ADDED
@@ -0,0 +1,109 @@
1
+ '''
2
+ desr -- Differential Equation Symmetry Reduction.
3
+
4
+ Reduce the number of parameters in a dynamical system by finding its scaling symmetries,
5
+ after Hubert & Labahn (2013).
6
+
7
+ The names a caller needs are here, so that a whole workflow is one import::
8
+
9
+ from desr import ODESystem, ODETranslator
10
+
11
+ system = ODESystem.from_equations(['dn/dt = r*n*(1 - n/k)'])
12
+ translator = ODETranslator(system)
13
+ reduced = translator.translate()
14
+
15
+ The submodules remain available for the rest -- :mod:`desr.matrix_normal_forms` for the
16
+ integer matrix algorithms, :mod:`desr.sympy_helper` for the parsing convention,
17
+ :mod:`desr.tex_tools` for LaTeX.
18
+ '''
19
+
20
+ #: The one place the version is written. `setup.py` reads it from here without importing
21
+ #: the package, and `docs/source/conf.py` reads it too, so a bump happens once and cannot
22
+ #: leave the three of them disagreeing -- which is what had happened: `setup.py` said
23
+ #: 1.1.0 while the docs said version 1, release 0.
24
+ __version__ = '3.0.0'
25
+
26
+ from . import ode_system
27
+ from . import matrix_normal_forms
28
+ from . import chemical_reaction_network
29
+ from . import ode_translation
30
+ from . import sympy_helper
31
+ from . import tex_tools
32
+
33
+ from .chemical_reaction_network import (ChemicalReactionNetwork, ChemicalSpecies, Complex,
34
+ Reaction)
35
+ from .ode_system import ConflictingParameterValues, ODESystem
36
+ from .ode_translation import ODETranslator, ReductionScheme, scale_action
37
+ from .sympy_helper import sympify_expression, to_symbol
38
+ from .tex_tools import TexParseError
39
+
40
+ # desr.numerics loads numpy, and the reduction itself does not need it. Importing it here
41
+ # would make every `import desr` pay for numpy, so the numeric names are resolved on first
42
+ # access instead: `from desr import NumericTranslator` works, and numpy is loaded only when
43
+ # something reaches for the numeric part.
44
+ _LAZY = {
45
+ 'ConflictingKnownValues': 'numerics',
46
+ 'InsufficientKnownValues': 'numerics',
47
+ 'NumericTranslator': 'numerics',
48
+ 'numerics': None,
49
+ # desr.symbol_graph loads networkx, and its drawing matplotlib. Same bargain as
50
+ # numerics: resolved on first access, so `import desr` loads neither. The
51
+ # submodule only, not its functions: the module and its main function share a name, so
52
+ # a top-level `symbol_graph` would be ambiguous. `ODETranslator.symbol_graph` is the
53
+ # way in, and `from desr.symbol_graph import draw_symbol_graph` gets the drawing.
54
+ 'symbol_graph': None,
55
+ # desr.figures draws with matplotlib, which is not a requirement of desr, and the
56
+ # symbol map reaches networkx through desr.symbol_graph. The same bargain again:
57
+ # `from desr.figures import flowchart_figure` works where matplotlib is installed,
58
+ # and `import desr` works where it is not.
59
+ 'figures': None,
60
+ }
61
+
62
+
63
+ def __getattr__(name):
64
+ module_name = _LAZY.get(name, False)
65
+ if module_name is False:
66
+ raise AttributeError('module {!r} has no attribute {!r}'.format(__name__, name))
67
+
68
+ import importlib
69
+ module = importlib.import_module('.{}'.format(module_name or name), __name__)
70
+ return module if module_name is None else getattr(module, name)
71
+
72
+
73
+ def __dir__():
74
+ return sorted(set(__all__) | set(globals()))
75
+
76
+
77
+ __all__ = [
78
+ # Systems of ODEs
79
+ 'ODESystem',
80
+ # Reduction
81
+ 'ODETranslator',
82
+ 'ReductionScheme',
83
+ 'scale_action',
84
+ # Chemical reaction networks
85
+ 'ChemicalReactionNetwork',
86
+ 'ChemicalSpecies',
87
+ 'Complex',
88
+ 'Reaction',
89
+ # Numerical translation (needs numpy and scipy; imported on first access)
90
+ 'NumericTranslator',
91
+ # Every exception the library defines, so that one can be caught without knowing
92
+ # which module raises it. The two numeric ones are imported on first access.
93
+ 'ConflictingParameterValues',
94
+ 'TexParseError',
95
+ 'InsufficientKnownValues',
96
+ 'ConflictingKnownValues',
97
+ # The one place text becomes sympy
98
+ 'sympify_expression',
99
+ 'to_symbol',
100
+ # Submodules
101
+ 'chemical_reaction_network',
102
+ 'matrix_normal_forms',
103
+ 'numerics',
104
+ 'ode_system',
105
+ 'ode_translation',
106
+ 'symbol_graph',
107
+ 'sympy_helper',
108
+ 'tex_tools',
109
+ ]
@@ -0,0 +1,247 @@
1
+
2
+ from collections.abc import MutableMapping
3
+
4
+ import sympy
5
+
6
+ from desr.ode_system import ODESystem
7
+ from desr.sympy_helper import sympify_expression, to_symbol, unique_array_stable
8
+
9
+ class ChemicalSpecies(object):
10
+ ''' Chemical species, A_i from Harrington paper. Typically represents a single chemical element. '''
11
+ def __init__(self, id_):
12
+ self.id_ = id_
13
+
14
+ def _key(self):
15
+ ''' Return the key of the object for comparison '''
16
+ return str(self.id_)
17
+
18
+ def __eq__(self, other):
19
+ if isinstance(other, ChemicalSpecies):
20
+ return self._key() == other._key()
21
+ return False
22
+
23
+ def __hash__(self):
24
+ return hash(self._key())
25
+
26
+ def __repr__(self):
27
+ return str(self.id_)
28
+
29
+ class Complex(MutableMapping):
30
+ ''' A complex of ChemicalSpecies.
31
+ Represented as a dictionary where the keys are chemical species and the value represents its coefficient in the complex.
32
+ '''
33
+ def __init__(self, *args, **kwargs):
34
+ self._species_dict = dict(*args, **kwargs)
35
+ for key in self._species_dict:
36
+ if not isinstance(key, ChemicalSpecies):
37
+ raise ValueError('{} must be a ChemicalSpecies'.format(key))
38
+
39
+ def __iter__(self):
40
+ return self._species_dict.__iter__()
41
+
42
+ def __len__(self):
43
+ return self._species_dict.__len__()
44
+
45
+ def __getitem__(self, item):
46
+ return self._species_dict.__getitem__(item)
47
+
48
+ def __setitem__(self, key, value):
49
+ if not isinstance(key, ChemicalSpecies):
50
+ raise ValueError('{} must be a ChemicalSpecies'.format(key))
51
+ self._species_dict[key] = value
52
+
53
+ def __repr__(self):
54
+ return ' + '.join(['{}.{}'.format(val, key) for key, val in self.items()])
55
+
56
+ def __delitem__(self, key):
57
+ self._species_dict.__delitem__(key)
58
+
59
+ def as_vector(self, variable_order):
60
+ '''
61
+ Represent the complex as a vector with respect to a given variable order.
62
+
63
+ Args:
64
+ variable_order (iter):
65
+ Iterable of :class:`~ChemicalSpecies`'s.
66
+
67
+ :rtype: tuple
68
+ '''
69
+ return tuple([self._species_dict.get(variable, 0) for variable in variable_order])
70
+
71
+ class Reaction(object):
72
+ ''' Represents a reaction between complexes, from complex1 to complex2 '''
73
+ def __init__(self, complex1, complex2):
74
+ """
75
+ Args:
76
+ complex1 (Complex)
77
+ complex2 (Complex)
78
+ """
79
+ self.complex1 = complex1
80
+ self.complex2 = complex2
81
+
82
+ def __repr__(self):
83
+ return '{} -> {}'.format(self.complex1, self.complex2)
84
+
85
+ class ChemicalReactionNetwork(object):
86
+ ''' Chemical reaction network, made up of Species, Complexes and Reactions. '''
87
+ def __init__(self, chemical_species, complexes, reactions):
88
+ assert all([isinstance(c_s, ChemicalSpecies) for c_s in chemical_species])
89
+
90
+ self.chemical_species = tuple(chemical_species)
91
+ self.complexes = tuple(complexes)
92
+ self.reactions = tuple(reactions)
93
+
94
+ # Check the complexes only involve our species
95
+ set_c_s = set(self.chemical_species)
96
+ for complex in self.complexes:
97
+ assert set(complex.keys()).issubset(set_c_s)
98
+
99
+ # Check our reactions only involve our complexes
100
+ for reaction in self.reactions:
101
+ assert reaction.complex1 in self.complexes
102
+ assert reaction.complex2 in self.complexes
103
+
104
+ @property
105
+ def p(self):
106
+ """
107
+ The number of complexes in the network.
108
+
109
+ Returns:
110
+ int
111
+ """
112
+ return len(self.complexes)
113
+
114
+ @property
115
+ def n(self):
116
+ """
117
+ The number of chemical species in the network.
118
+
119
+ Returns:
120
+ int
121
+ """
122
+ return len(self.chemical_species)
123
+
124
+ @property
125
+ def r(self):
126
+ """
127
+ The number of different chemical reactions in the network.
128
+
129
+ Returns:
130
+ int
131
+ """
132
+ return len(self.reactions)
133
+
134
+ def ode_equations(self):
135
+ '''
136
+ Return a tuple of differential equations for each species.
137
+
138
+ Returns:
139
+ tuple:
140
+ A differential equation, represented by a sympy.Expression, for the dynamics of each species.
141
+ '''
142
+ sympy_chem_spec = [to_symbol(str(species)) for species in self.chemical_species]
143
+
144
+ rate_reaction_function = []
145
+ stochiometric_matrix = []
146
+
147
+ for reaction in self.reactions:
148
+ # Calculate the rate reaction function
149
+ # Create a rate parameter
150
+ i, j = self.complexes.index(reaction.complex1), self.complexes.index(reaction.complex2)
151
+ rate_constant = to_symbol('k_{}_{}'.format(i, j))
152
+
153
+ concentration = [spec ** exponent for spec, exponent in
154
+ zip(sympy_chem_spec, reaction.complex1.as_vector(self.chemical_species))]
155
+
156
+ rate_reaction_function.append(rate_constant * sympy.prod(concentration))
157
+
158
+ # Calculate the stochiometric matrix
159
+ col = (sympy.Matrix(reaction.complex2.as_vector(self.chemical_species)) -
160
+ sympy.Matrix(reaction.complex1.as_vector(self.chemical_species)))
161
+ stochiometric_matrix.append(col.T)
162
+
163
+ rate_reaction_function = sympy.Matrix(rate_reaction_function)
164
+ assert rate_reaction_function.shape == (self.r, 1)
165
+ stochiometric_matrix = sympy.Matrix(stochiometric_matrix).T
166
+ assert stochiometric_matrix.shape == (self.n, self.r)
167
+
168
+ equations = stochiometric_matrix * rate_reaction_function
169
+ assert len(sympy_chem_spec) == len(equations)
170
+ return tuple(equations)
171
+
172
+ def to_ode_system(self):
173
+ '''
174
+ Generate a system of ODEs based on the current network.
175
+
176
+ Returns:
177
+ ODESystem: A system describing the current network.
178
+ '''
179
+ sympy_chem_spec = [to_symbol(str(species)) for species in self.chemical_species]
180
+ equations = self.ode_equations()
181
+ deriv_dict = dict(zip(sympy_chem_spec, equations))
182
+ return ODESystem.from_dict(deriv_dict=deriv_dict)
183
+
184
+ def __repr__(self):
185
+ return '\n'.join([reaction.__repr__() for reaction in self.reactions])
186
+
187
+ @classmethod
188
+ def from_diagram(cls, diagram):
189
+ '''
190
+ Given a text diagram, return an interpreted chemical reaction network.
191
+
192
+
193
+ >>> ChemicalReactionNetwork.from_diagram('x + y -> z \\n y + z -> 2*z')
194
+ 1.x + 1.y -> 1.z
195
+ 1.y + 1.z -> 2.z
196
+
197
+ We can add reversible reactions like so:
198
+
199
+ >>> ChemicalReactionNetwork.from_diagram('x + y -> z \\n z -> x + y')
200
+ 1.x + 1.y -> 1.z
201
+ 1.z -> 1.x + 1.y
202
+ '''
203
+ species = []
204
+ complexes = []
205
+ reactions = []
206
+ complex0 = Complex({})
207
+ for reaction in diagram.strip().split('\n'):
208
+ _complexes = reaction.strip().split('->')
209
+ if len(_complexes) != 2:
210
+ raise ValueError('Invalid reaction: {}'.format(reaction))
211
+
212
+ # Process the left hand side. sympify_expression, not sympy.sympify: a species
213
+ # named E, S, I, N, O, Q or beta is a name like any other, where raw sympify
214
+ # resolves it to a sympy builtin. `E + S -> E + P` used to die with
215
+ # "unsupported operand type(s) for +: 'Exp1' and 'SingletonRegistry'", which is
216
+ # the one diagram an enzyme kineticist is most likely to write first.
217
+ complex_left = _complexes[0].strip()
218
+ if complex_left:
219
+ complex_left = sympify_expression(complex_left)
220
+ complex_left = {ChemicalSpecies(k): v for k, v in complex_left.as_coefficients_dict().items()}
221
+ species.extend(complex_left.keys())
222
+ complex_left = Complex(complex_left)
223
+ else:
224
+ complex_left = complex0
225
+
226
+ complex_right = _complexes[1].strip()
227
+ if complex_right:
228
+ complex_right = sympify_expression(complex_right)
229
+ complex_right = {ChemicalSpecies(k): v for k, v in complex_right.as_coefficients_dict().items()}
230
+ species.extend(complex_right.keys())
231
+ complex_right = Complex(complex_right)
232
+ else:
233
+ complex_right = complex0
234
+
235
+ if complex_left not in complexes:
236
+ complexes.append(complex_left)
237
+ if complex_right not in complexes:
238
+ complexes.append(complex_right)
239
+
240
+ reactions.append(Reaction(complex_left, complex_right))
241
+
242
+ species = unique_array_stable(species)
243
+ return cls(species, complexes, reactions)
244
+
245
+ if __name__ == '__main__':
246
+ import doctest
247
+ doctest.testmod()
@@ -0,0 +1,34 @@
1
+ """
2
+ Figures that explain a reduction, drawn from a system desr has never seen.
3
+
4
+ Two of them, and they are halves of the same explanation:
5
+
6
+ :func:`~desr.figures.symbol_map.symbol_map_figure`
7
+ the reduction as a chain of systems, with the map between each pair drawn out --
8
+ the exponent graphs on the outer maps, and a table of units and values in the
9
+ middle. It holds no matrices.
10
+
11
+ :func:`~desr.figures.flowchart.flowchart_figure`
12
+ the same reduction with the matrices on the page and a step named on every arrow,
13
+ in nine numbered boxes. It holds no equations until the last one.
14
+
15
+ Neither computes anything. Every matrix, monomial, dimension and substitution on
16
+ either page comes from a method of :class:`~desr.ode_system.ODESystem` or
17
+ :class:`~desr.ode_translation.ODETranslator`, so a figure cannot draw a derivation the
18
+ library does not perform, and a figure drawn for a model desr has never met is as
19
+ right as the library is.
20
+
21
+ Both need :mod:`matplotlib`, which desr does not install, and the symbol map needs
22
+ :mod:`networkx` through :mod:`desr.symbol_graph`. Neither is imported by
23
+ ``import desr``.
24
+
25
+ >>> from desr import ODESystem # doctest: +SKIP
26
+ >>> from desr.figures import flowchart_figure # doctest: +SKIP
27
+ >>> figure = flowchart_figure(ODESystem.from_equations([...])) # doctest: +SKIP
28
+ >>> figure.savefig('reduction.pdf') # doctest: +SKIP
29
+ """
30
+
31
+ from desr.figures.flowchart import flowchart_figure
32
+ from desr.figures.symbol_map import symbol_map_figure
33
+
34
+ __all__ = ['flowchart_figure', 'symbol_map_figure']
@@ -0,0 +1,31 @@
1
+ """
2
+ The colours and the face the figures are drawn in, in one place.
3
+
4
+ Colour names a **kind of symbol** and nothing else: rust the auxiliaries, which are
5
+ the units, and blue the invariants, which are the values. Not the steps -- a step is
6
+ grey, because the steps do not divide the way the symbols do. Black is for what is
7
+ neither kind: an expression, a dimension, a count.
8
+ """
9
+
10
+ UNIT_COLOUR, VALUE_COLOUR = '#8a4500', '#1f5c86'
11
+
12
+ #: Black for a statement, grey for a label about the figure rather than about the
13
+ #: system, and the palest grey for a step that does nothing.
14
+ PLAIN, QUIET, INERT = 'black', '#555555', '#aaaaaa'
15
+
16
+ #: The wash behind a highlighted row, and the panel fills.
17
+ PICKED = '#f0e2d2'
18
+ PANEL_FILL, PANEL_EDGE = '#fbfaf8', '#d9d6d0'
19
+
20
+ #: Computer Modern, which matplotlib ships, so a figure sets in the same face as the
21
+ #: paper it belongs in and a kappa is not a k. ``axes.unicode_minus`` is off because
22
+ #: cmr10 has no U+2212 and matplotlib says so, loudly, once per label;
23
+ #: ``axes.formatter.use_mathtext`` silences a second warning about the same font.
24
+ FONT_RC = {
25
+ 'font.family': 'serif',
26
+ 'font.serif': ['cmr10', 'DejaVu Serif'],
27
+ 'mathtext.fontset': 'cm',
28
+ 'mathtext.rm': 'serif',
29
+ 'axes.unicode_minus': False,
30
+ 'axes.formatter.use_mathtext': True,
31
+ }