Debian Codegraph @

brian2/stateupdaters/exponential_euler.py

raw
1 import sympy as sp
2
3 from brian2.parsing.sympytools import str_to_sympy, sympy_to_str
4
5 from .base import (
6 StateUpdateMethod,
7 UnsupportedEquationsException,
8 extract_method_options,
9 )
10
11 __all__ = ["exponential_euler"]
12
13
14 def get_conditionally_linear_system(eqs, variables=None):
15 """
16 Convert equations into a linear system using sympy.
17
18 Parameters
19 ----------
20 eqs : `Equations`
21 The model equations.
22
23 Returns
24 -------
25 coefficients : dict of (sympy expression, sympy expression) tuples
26 For every variable x, a tuple (M, B) containing the coefficients M and
27 B (as sympy expressions) for M * x + B
28
29 Raises
30 ------
31 ValueError
32 If one of the equations cannot be converted into a M * x + B form.
33
34 Examples
35 --------
36 >>> from brian2 import Equations
37 >>> eqs = Equations('''
38 ... dv/dt = (-v + w**2.0) / tau : 1
39 ... dw/dt = -w / tau : 1
40 ... ''')
41 >>> system = get_conditionally_linear_system(eqs)
42 >>> print(system['v'])
43 (-1/tau, w**2.0/tau)
44 >>> print(system['w'])
45 (-1/tau, 0)
46
47 """
48 diff_eqs = eqs.get_substituted_expressions(variables)
49
50 coefficients = {}
51
52 for name, expr in diff_eqs:
53 var = sp.Symbol(name, real=True)
54
55 s_expr = str_to_sympy(expr.code, variables).expand()
56 if s_expr.has(var):
57 # Factor out the variable
58 s_expr = sp.collect(s_expr, var, evaluate=False)
59
60 if len(s_expr) > 2 or var not in s_expr:
61 raise ValueError(
62 f"The expression '{expr}', defining the variable "
63 f"'{name}', could not be separated into linear "
64 "components."
65 )
66 coefficients[name] = (s_expr[var], s_expr.get(1, 0))
67 else:
68 coefficients[name] = (0, s_expr)
69
70 return coefficients
71
72
73 class ExponentialEulerStateUpdater(StateUpdateMethod):
74 """
75 A state updater for conditionally linear equations, i.e. equations where
76 each variable only depends linearly on itself (but possibly non-linearly
77 on other variables). Typical Hodgkin-Huxley equations fall into this
78 category, it is therefore the default integration method used in the
79 GENESIS simulator, for example.
80 """
81
82 def __call__(self, equations, variables=None, method_options=None):
83 extract_method_options(method_options, {})
84 if equations.is_stochastic:
85 raise UnsupportedEquationsException(
86 "Cannot solve stochastic equations with this state updater."
87 )
88
89 # Try whether the equations are conditionally linear
90 try:
91 system = get_conditionally_linear_system(equations, variables)
92 except ValueError:
93 raise UnsupportedEquationsException(
94 "Can only solve conditionally linear systems with this state updater."
95 ) from None
96
97 code = []
98 for var, (A, B) in system.items():
99 s_var = sp.Symbol(var)
100 s_dt = sp.Symbol("dt")
101 if A == 0:
102 update_expression = s_var + s_dt * B
103 elif B != 0:
104 BA = B / A
105 # Avoid calculating B/A twice
106 BA_name = f"_BA_{var}"
107 s_BA = sp.Symbol(BA_name)
108 code += [f"{BA_name} = {sympy_to_str(BA)}"]
109 update_expression = (s_var + s_BA) * sp.exp(A * s_dt) - s_BA
110 else:
111 update_expression = s_var * sp.exp(A * s_dt)
112
113 # The actual update step
114 code += [f"_{var} = {sympy_to_str(update_expression)}"]
115
116 # Replace all the variables with their updated value
117 for var in system:
118 code += [f"{var} = _{var}"]
119
120 return "\n".join(code)
121
122 # Copy doc from parent class
123 __call__.__doc__ = StateUpdateMethod.__call__.__doc__
124
125
126 exponential_euler = ExponentialEulerStateUpdater()