Debian Codegraph @

brian2/stateupdaters/exact.py

raw
1 """
2 Exact integration for linear equations.
3 """
4
5 import itertools
6
7 import sympy as sp
8 from sympy import I, Symbol, Wild, im, re
9
10 from brian2.equations.codestrings import is_constant_over_dt
11 from brian2.parsing.sympytools import str_to_sympy, sympy_to_str
12 from brian2.stateupdaters.base import (
13 StateUpdateMethod,
14 UnsupportedEquationsException,
15 extract_method_options,
16 )
17 from brian2.utils.caching import cached
18 from brian2.utils.logger import get_logger
19
20 __all__ = ["linear", "exact", "independent"]
21
22 logger = get_logger(__name__)
23
24
25 def get_linear_system(eqs, variables):
26 """
27 Convert equations into a linear system using sympy.
28
29 Parameters
30 ----------
31 eqs : `Equations`
32 The model equations.
33
34 Returns
35 -------
36 (diff_eq_names, coefficients, constants) : (list of str, `sympy.Matrix`, `sympy.Matrix`)
37 A tuple containing the variable names (`diff_eq_names`) corresponding
38 to the rows of the matrix `coefficients` and the vector `constants`,
39 representing the system of equations in the form M * X + B
40
41 Raises
42 ------
43 ValueError
44 If the equations cannot be converted into an M * X + B form.
45 """
46 diff_eqs = eqs.get_substituted_expressions(variables)
47 diff_eq_names = [name for name, _ in diff_eqs]
48
49 symbols = [Symbol(name, real=True) for name in diff_eq_names]
50
51 coefficients = sp.zeros(len(diff_eq_names))
52 constants = sp.zeros(len(diff_eq_names), 1)
53
54 for row_idx, (name, expr) in enumerate(diff_eqs):
55 s_expr = str_to_sympy(expr.code, variables).expand()
56
57 current_s_expr = s_expr
58 for col_idx, symbol in enumerate(symbols):
59 current_s_expr = current_s_expr.collect(symbol)
60 constant_wildcard = Wild("c", exclude=[symbol])
61 factor_wildcard = Wild(f"c_{name}", exclude=symbols)
62 one_pattern = factor_wildcard * symbol + constant_wildcard
63 matches = current_s_expr.match(one_pattern)
64 if matches is None:
65 raise UnsupportedEquationsException(
66 f"The expression '{expr}', "
67 "defining the variable "
68 f"'{name}', could not be "
69 "separated into linear "
70 "components."
71 )
72
73 coefficients[row_idx, col_idx] = matches[factor_wildcard]
74 current_s_expr = matches[constant_wildcard]
75
76 # The remaining constant should be a true constant
77 constants[row_idx] = current_s_expr
78
79 return (diff_eq_names, coefficients, constants)
80
81
82 class IndependentStateUpdater(StateUpdateMethod):
83 """
84 A state update for equations that do not depend on other state variables,
85 i.e. 1-dimensional differential equations. The individual equations are
86 solved by sympy.
87
88 .. deprecated:: 2.1
89 This method might be removed from future versions of Brian.
90 """
91
92 def __call__(self, equations, variables=None, method_options=None):
93 logger.warn(
94 "The 'independent' state updater is deprecated and might be "
95 "removed in future versions of Brian.",
96 "deprecated_independent",
97 once=True,
98 )
99 extract_method_options(method_options, {})
100 if equations.is_stochastic:
101 raise UnsupportedEquationsException(
102 "Cannot solve stochastic equations with this state updater"
103 )
104 if variables is None:
105 variables = {}
106
107 diff_eqs = equations.get_substituted_expressions(variables)
108
109 t = Symbol("t", real=True, positive=True)
110 dt = Symbol("dt", real=True, positive=True)
111 t0 = Symbol("t0", real=True, positive=True)
112
113 code = []
114 for name, expression in diff_eqs:
115 rhs = str_to_sympy(expression.code, variables)
116
117 # We have to be careful and use the real=True assumption as well,
118 # otherwise sympy doesn't consider the symbol a match to the content
119 # of the equation
120 var = Symbol(name, real=True)
121 f = sp.Function(name)
122 rhs = rhs.subs(var, f(t))
123 derivative = sp.Derivative(f(t), t)
124 diff_eq = sp.Eq(derivative, rhs)
125 # TODO: simplify=True sometimes fails with 0.7.4, see:
126 # https://github.com/sympy/sympy/issues/2666
127 try:
128 general_solution = sp.dsolve(diff_eq, f(t), simplify=True)
129 except RuntimeError:
130 general_solution = sp.dsolve(diff_eq, f(t), simplify=False)
131 # Check whether this is an explicit solution
132 if not getattr(general_solution, "lhs", None) == f(t):
133 raise UnsupportedEquationsException(
134 f"Cannot explicitly solve: {str(diff_eq)}"
135 )
136 # Solve for C1 (assuming "var" as the initial value and "t0" as time)
137 if general_solution.has(Symbol("C1")):
138 if general_solution.has(Symbol("C2")):
139 raise UnsupportedEquationsException(
140 f"Too many constants in solution: {str(general_solution)}"
141 )
142 constant_solution = sp.solve(general_solution, Symbol("C1"))
143 if len(constant_solution) != 1:
144 raise UnsupportedEquationsException(
145 "Couldn't solve for the constant C1 in : %s "
146 % str(general_solution)
147 )
148 constant = constant_solution[0].subs(t, t0).subs(f(t0), var)
149 solution = general_solution.rhs.subs("C1", constant)
150 else:
151 solution = general_solution.rhs.subs(t, t0).subs(f(t0), var)
152 # Evaluate the expression for one timestep
153 solution = solution.subs(t, t + dt).subs(t0, t)
154 # only try symplifying it -- it sometimes raises an error
155 try:
156 solution = solution.simplify()
157 except ValueError:
158 pass
159
160 code.append(f"{name} = {sympy_to_str(solution)}")
161
162 return "\n".join(code)
163
164
165 class LinearStateUpdater(StateUpdateMethod):
166 """
167 A state updater for linear equations. Derives a state updater step from the
168 analytical solution given by sympy. Uses the matrix exponential (which is
169 only implemented for diagonalizable matrices in sympy).
170 """
171
172 @cached
173 def __call__(self, equations, variables=None, method_options=None):
174 method_options = extract_method_options(method_options, {"simplify": True})
175
176 if equations.is_stochastic:
177 raise UnsupportedEquationsException(
178 "Cannot solve stochastic equations with this state updater."
179 )
180 if variables is None:
181 variables = {}
182
183 # Get a representation of the ODE system in the form of
184 # dX/dt = M*X + B
185 varnames, matrix, constants = get_linear_system(equations, variables)
186
187 # No differential equations, nothing to do (this occurs sometimes in the
188 # test suite where the whole model is nothing more than something like
189 # 'v : 1')
190 if matrix.shape == (0, 0):
191 return ""
192
193 # Make sure that the matrix M is constant, i.e. it only contains
194 # external variables or constant variables
195
196 # Check for time dependence
197 dt_value = variables["dt"].get_value()[0] if "dt" in variables else None
198
199 # This will raise an error if we meet the symbol "t" anywhere
200 # except as an argument of a locally constant function
201 for entry in itertools.chain(matrix, constants):
202 if not is_constant_over_dt(entry, variables, dt_value):
203 raise UnsupportedEquationsException(
204 f"Expression '{sympy_to_str(entry)}' is not guaranteed to be "
205 "constant over a time step."
206 )
207
208 symbols = [Symbol(variable, real=True) for variable in varnames]
209 solution = sp.solve_linear_system(matrix.row_join(constants), *symbols)
210 if solution is None or set(symbols) != set(solution.keys()):
211 raise UnsupportedEquationsException(
212 "Cannot solve the given equations with this stateupdater."
213 )
214 b = sp.ImmutableMatrix([solution[symbol] for symbol in symbols])
215
216 # Solve the system
217 dt = Symbol("dt", real=True, positive=True)
218 try:
219 A = (matrix * dt).exp()
220 except NotImplementedError:
221 raise UnsupportedEquationsException(
222 "Cannot solve the given equations with this stateupdater."
223 ) from None
224 if method_options["simplify"]:
225 A = A.applyfunc(lambda x: sp.factor_terms(sp.cancel(sp.signsimp(x))))
226 C = sp.ImmutableMatrix(A * b) - b
227 _S = sp.MatrixSymbol("_S", len(varnames), 1)
228 updates = A * _S + C
229 updates = updates.as_explicit()
230
231 # The solution contains _S[0, 0], _S[1, 0] etc. for the state variables,
232 # replace them with the state variable names
233 abstract_code = []
234 for variable, update in zip(varnames, updates, strict=True):
235 rhs = update
236 if rhs.has(I, re, im):
237 raise UnsupportedEquationsException(
238 "The solution to the linear system "
239 "contains complex values "
240 "which is currently not implemented."
241 )
242 for row_idx, varname in enumerate(varnames):
243 rhs = rhs.subs(_S[row_idx, 0], varname)
244
245 # Do not overwrite the real state variables yet, the update step
246 # of other state variables might still need the original values
247 abstract_code.append(f"_{variable} = {sympy_to_str(rhs)}")
248
249 # Update the state variables
250 for variable in varnames:
251 abstract_code.append(f"{variable} = _{variable}")
252 return "\n".join(abstract_code)
253
254 def __repr__(self):
255 return f"{self.__class__.__name__}()"
256
257
258 independent = IndependentStateUpdater()
259 linear = LinearStateUpdater()
260 exact = linear