File: exact.py

package info (click to toggle)
brian 2.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,872 kB
  • sloc: python: 51,820; cpp: 2,033; makefile: 108; sh: 72
file content (260 lines) | stat: -rw-r--r-- 10,118 bytes parent folder | download | duplicates (2)
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
"""
Exact integration for linear equations.
"""

import itertools

import sympy as sp
from sympy import I, Symbol, Wild, im, re

from brian2.equations.codestrings import is_constant_over_dt
from brian2.parsing.sympytools import str_to_sympy, sympy_to_str
from brian2.stateupdaters.base import (
    StateUpdateMethod,
    UnsupportedEquationsException,
    extract_method_options,
)
from brian2.utils.caching import cached
from brian2.utils.logger import get_logger

__all__ = ["linear", "exact", "independent"]

logger = get_logger(__name__)


def get_linear_system(eqs, variables):
    """
    Convert equations into a linear system using sympy.

    Parameters
    ----------
    eqs : `Equations`
        The model equations.

    Returns
    -------
    (diff_eq_names, coefficients, constants) : (list of str, `sympy.Matrix`, `sympy.Matrix`)
        A tuple containing the variable names (`diff_eq_names`) corresponding
        to the rows of the matrix `coefficients` and the vector `constants`,
        representing the system of equations in the form M * X + B

    Raises
    ------
    ValueError
        If the equations cannot be converted into an M * X + B form.
    """
    diff_eqs = eqs.get_substituted_expressions(variables)
    diff_eq_names = [name for name, _ in diff_eqs]

    symbols = [Symbol(name, real=True) for name in diff_eq_names]

    coefficients = sp.zeros(len(diff_eq_names))
    constants = sp.zeros(len(diff_eq_names), 1)

    for row_idx, (name, expr) in enumerate(diff_eqs):
        s_expr = str_to_sympy(expr.code, variables).expand()

        current_s_expr = s_expr
        for col_idx, symbol in enumerate(symbols):
            current_s_expr = current_s_expr.collect(symbol)
            constant_wildcard = Wild("c", exclude=[symbol])
            factor_wildcard = Wild(f"c_{name}", exclude=symbols)
            one_pattern = factor_wildcard * symbol + constant_wildcard
            matches = current_s_expr.match(one_pattern)
            if matches is None:
                raise UnsupportedEquationsException(
                    f"The expression '{expr}', "
                    "defining the variable "
                    f"'{name}', could not be "
                    "separated into linear "
                    "components."
                )

            coefficients[row_idx, col_idx] = matches[factor_wildcard]
            current_s_expr = matches[constant_wildcard]

        # The remaining constant should be a true constant
        constants[row_idx] = current_s_expr

    return (diff_eq_names, coefficients, constants)


class IndependentStateUpdater(StateUpdateMethod):
    """
    A state update for equations that do not depend on other state variables,
    i.e. 1-dimensional differential equations. The individual equations are
    solved by sympy.

    .. deprecated:: 2.1
        This method might be removed from future versions of Brian.
    """

    def __call__(self, equations, variables=None, method_options=None):
        logger.warn(
            "The 'independent' state updater is deprecated and might be "
            "removed in future versions of Brian.",
            "deprecated_independent",
            once=True,
        )
        extract_method_options(method_options, {})
        if equations.is_stochastic:
            raise UnsupportedEquationsException(
                "Cannot solve stochastic equations with this state updater"
            )
        if variables is None:
            variables = {}

        diff_eqs = equations.get_substituted_expressions(variables)

        t = Symbol("t", real=True, positive=True)
        dt = Symbol("dt", real=True, positive=True)
        t0 = Symbol("t0", real=True, positive=True)

        code = []
        for name, expression in diff_eqs:
            rhs = str_to_sympy(expression.code, variables)

            # We have to be careful and use the real=True assumption as well,
            # otherwise sympy doesn't consider the symbol a match to the content
            # of the equation
            var = Symbol(name, real=True)
            f = sp.Function(name)
            rhs = rhs.subs(var, f(t))
            derivative = sp.Derivative(f(t), t)
            diff_eq = sp.Eq(derivative, rhs)
            # TODO: simplify=True sometimes fails with 0.7.4, see:
            # https://github.com/sympy/sympy/issues/2666
            try:
                general_solution = sp.dsolve(diff_eq, f(t), simplify=True)
            except RuntimeError:
                general_solution = sp.dsolve(diff_eq, f(t), simplify=False)
            # Check whether this is an explicit solution
            if not getattr(general_solution, "lhs", None) == f(t):
                raise UnsupportedEquationsException(
                    f"Cannot explicitly solve: {str(diff_eq)}"
                )
            # Solve for C1 (assuming "var" as the initial value and "t0" as time)
            if general_solution.has(Symbol("C1")):
                if general_solution.has(Symbol("C2")):
                    raise UnsupportedEquationsException(
                        f"Too many constants in solution: {str(general_solution)}"
                    )
                constant_solution = sp.solve(general_solution, Symbol("C1"))
                if len(constant_solution) != 1:
                    raise UnsupportedEquationsException(
                        "Couldn't solve for the constant C1 in : %s "
                        % str(general_solution)
                    )
                constant = constant_solution[0].subs(t, t0).subs(f(t0), var)
                solution = general_solution.rhs.subs("C1", constant)
            else:
                solution = general_solution.rhs.subs(t, t0).subs(f(t0), var)
            # Evaluate the expression for one timestep
            solution = solution.subs(t, t + dt).subs(t0, t)
            # only try symplifying it -- it sometimes raises an error
            try:
                solution = solution.simplify()
            except ValueError:
                pass

            code.append(f"{name} = {sympy_to_str(solution)}")

        return "\n".join(code)


class LinearStateUpdater(StateUpdateMethod):
    """
    A state updater for linear equations. Derives a state updater step from the
    analytical solution given by sympy. Uses the matrix exponential (which is
    only implemented for diagonalizable matrices in sympy).
    """

    @cached
    def __call__(self, equations, variables=None, method_options=None):
        method_options = extract_method_options(method_options, {"simplify": True})

        if equations.is_stochastic:
            raise UnsupportedEquationsException(
                "Cannot solve stochastic equations with this state updater."
            )
        if variables is None:
            variables = {}

        # Get a representation of the ODE system in the form of
        # dX/dt = M*X + B
        varnames, matrix, constants = get_linear_system(equations, variables)

        # No differential equations, nothing to do (this occurs sometimes in the
        # test suite where the whole model is nothing more than something like
        # 'v : 1')
        if matrix.shape == (0, 0):
            return ""

        # Make sure that the matrix M is constant, i.e. it only contains
        # external variables or constant variables

        # Check for time dependence
        dt_value = variables["dt"].get_value()[0] if "dt" in variables else None

        # This will raise an error if we meet the symbol "t" anywhere
        # except as an argument of a locally constant function
        for entry in itertools.chain(matrix, constants):
            if not is_constant_over_dt(entry, variables, dt_value):
                raise UnsupportedEquationsException(
                    f"Expression '{sympy_to_str(entry)}' is not guaranteed to be "
                    "constant over a time step."
                )

        symbols = [Symbol(variable, real=True) for variable in varnames]
        solution = sp.solve_linear_system(matrix.row_join(constants), *symbols)
        if solution is None or set(symbols) != set(solution.keys()):
            raise UnsupportedEquationsException(
                "Cannot solve the given equations with this stateupdater."
            )
        b = sp.ImmutableMatrix([solution[symbol] for symbol in symbols])

        # Solve the system
        dt = Symbol("dt", real=True, positive=True)
        try:
            A = (matrix * dt).exp()
        except NotImplementedError:
            raise UnsupportedEquationsException(
                "Cannot solve the given equations with this stateupdater."
            )
        if method_options["simplify"]:
            A = A.applyfunc(lambda x: sp.factor_terms(sp.cancel(sp.signsimp(x))))
        C = sp.ImmutableMatrix(A * b) - b
        _S = sp.MatrixSymbol("_S", len(varnames), 1)
        updates = A * _S + C
        updates = updates.as_explicit()

        # The solution contains _S[0, 0], _S[1, 0] etc. for the state variables,
        # replace them with the state variable names
        abstract_code = []
        for variable, update in zip(varnames, updates):
            rhs = update
            if rhs.has(I, re, im):
                raise UnsupportedEquationsException(
                    "The solution to the linear system "
                    "contains complex values "
                    "which is currently not implemented."
                )
            for row_idx, varname in enumerate(varnames):
                rhs = rhs.subs(_S[row_idx, 0], varname)

            # Do not overwrite the real state variables yet, the update step
            # of other state variables might still need the original values
            abstract_code.append(f"_{variable} = {sympy_to_str(rhs)}")

        # Update the state variables
        for variable in varnames:
            abstract_code.append(f"{variable} = _{variable}")
        return "\n".join(abstract_code)

    def __repr__(self):
        return f"{self.__class__.__name__}()"


independent = IndependentStateUpdater()
linear = LinearStateUpdater()
exact = linear