| 1 |
""" |
| 2 |
Numerical integration functions. |
| 3 |
""" |
| 4 |
|
| 5 |
import operator |
| 6 |
import string |
| 7 |
from functools import reduce |
| 8 |
|
| 9 |
import sympy |
| 10 |
from pyparsing import ( |
| 11 |
Group, |
| 12 |
Literal, |
| 13 |
ParseException, |
| 14 |
Suppress, |
| 15 |
Word, |
| 16 |
ZeroOrMore, |
| 17 |
restOfLine, |
| 18 |
) |
| 19 |
from sympy.core.sympify import SympifyError |
| 20 |
|
| 21 |
from brian2.equations.codestrings import is_constant_over_dt |
| 22 |
from brian2.parsing.sympytools import str_to_sympy, sympy_to_str |
| 23 |
|
| 24 |
from .base import ( |
| 25 |
StateUpdateMethod, |
| 26 |
UnsupportedEquationsException, |
| 27 |
extract_method_options, |
| 28 |
) |
| 29 |
|
| 30 |
__all__ = ["milstein", "heun", "euler", "rk2", "rk4", "ExplicitStateUpdater"] |
| 31 |
|
| 32 |
|
| 33 |
# =============================================================================== |
| 34 |
# Class for simple definition of explicit state updaters |
| 35 |
# =============================================================================== |
| 36 |
|
| 37 |
|
| 38 |
def _symbol(name, positive=None): |
| 39 |
"""Shorthand for ``sympy.Symbol(name, real=True)``.""" |
| 40 |
return sympy.Symbol(name, real=True, positive=positive) |
| 41 |
|
| 42 |
|
| 43 |
#: reserved standard symbols |
| 44 |
SYMBOLS = { |
| 45 |
"__x": _symbol("__x"), |
| 46 |
"__t": _symbol("__t", positive=True), |
| 47 |
"dt": _symbol("dt", positive=True), |
| 48 |
"t": _symbol("t", positive=True), |
| 49 |
"__f": sympy.Function("__f"), |
| 50 |
"__g": sympy.Function("__g"), |
| 51 |
"__dW": _symbol("__dW"), |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
def split_expression(expr): |
| 56 |
""" |
| 57 |
Split an expression into a part containing the function ``f`` and another |
| 58 |
one containing the function ``g``. Returns a tuple of the two expressions |
| 59 |
(as sympy expressions). |
| 60 |
|
| 61 |
Parameters |
| 62 |
---------- |
| 63 |
expr : str |
| 64 |
An expression containing references to functions ``f`` and ``g``. |
| 65 |
|
| 66 |
Returns |
| 67 |
------- |
| 68 |
(non_stochastic, stochastic) : tuple of sympy expressions |
| 69 |
A pair of expressions representing the non-stochastic (containing |
| 70 |
function-independent terms and terms involving ``f``) and the |
| 71 |
stochastic part of the expression (terms involving ``g`` and/or ``dW``). |
| 72 |
|
| 73 |
Examples |
| 74 |
-------- |
| 75 |
>>> split_expression('dt * __f(__x, __t)') |
| 76 |
(dt*__f(__x, __t), None) |
| 77 |
>>> split_expression('dt * __f(__x, __t) + __dW * __g(__x, __t)') |
| 78 |
(dt*__f(__x, __t), __dW*__g(__x, __t)) |
| 79 |
>>> split_expression('1/(2*sqrt(dt))*(__g_support - __g(__x, __t))*(sqrt(__dW))') |
| 80 |
(0, sqrt(__dW)*__g_support/(2*sqrt(dt)) - sqrt(__dW)*__g(__x, __t)/(2*sqrt(dt))) |
| 81 |
""" |
| 82 |
|
| 83 |
f = SYMBOLS["__f"] |
| 84 |
g = SYMBOLS["__g"] |
| 85 |
dW = SYMBOLS["__dW"] |
| 86 |
# Arguments of the f and g functions |
| 87 |
x_f = sympy.Wild("x_f", exclude=[f, g], real=True) |
| 88 |
t_f = sympy.Wild("t_f", exclude=[f, g], real=True) |
| 89 |
x_g = sympy.Wild("x_g", exclude=[f, g], real=True) |
| 90 |
t_g = sympy.Wild("t_g", exclude=[f, g], real=True) |
| 91 |
|
| 92 |
# Reorder the expression so that f(x,t) and g(x,t) are factored out |
| 93 |
sympy_expr = sympy.sympify(expr, locals=SYMBOLS).expand() |
| 94 |
sympy_expr = sympy.collect(sympy_expr, f(x_f, t_f)) |
| 95 |
sympy_expr = sympy.collect(sympy_expr, g(x_g, t_g)) |
| 96 |
|
| 97 |
# Constant part, contains neither f, g nor dW |
| 98 |
independent = sympy.Wild("independent", exclude=[f, g, dW], real=True) |
| 99 |
# The exponent of the random number |
| 100 |
dW_exponent = sympy.Wild("dW_exponent", exclude=[f, g, dW, 0], real=True) |
| 101 |
# The factor for the random number, not containing the g function |
| 102 |
independent_dW = sympy.Wild("independent_dW", exclude=[f, g, dW], real=True) |
| 103 |
# The factor for the f function |
| 104 |
f_factor = sympy.Wild("f_factor", exclude=[f, g], real=True) |
| 105 |
# The factor for the g function |
| 106 |
g_factor = sympy.Wild("g_factor", exclude=[f, g], real=True) |
| 107 |
|
| 108 |
match_expr = ( |
| 109 |
independent |
| 110 |
+ f_factor * f(x_f, t_f) |
| 111 |
+ independent_dW * dW**dW_exponent |
| 112 |
+ g_factor * g(x_g, t_g) |
| 113 |
) |
| 114 |
matches = sympy_expr.match(match_expr) |
| 115 |
|
| 116 |
if matches is None: |
| 117 |
raise ValueError( |
| 118 |
f'Expression "{sympy_expr}" in the state updater description could not be' |
| 119 |
" parsed." |
| 120 |
) |
| 121 |
|
| 122 |
# Non-stochastic part |
| 123 |
if x_f in matches: |
| 124 |
# Includes the f function |
| 125 |
non_stochastic = matches[independent] + ( |
| 126 |
matches[f_factor] * f(matches[x_f], matches[t_f]) |
| 127 |
) |
| 128 |
else: |
| 129 |
# Does not include f, might be 0 |
| 130 |
non_stochastic = matches[independent] |
| 131 |
|
| 132 |
# Stochastic part |
| 133 |
if independent_dW in matches and matches[independent_dW] != 0: |
| 134 |
# includes a random variable term with a non-zero factor |
| 135 |
stochastic = ( |
| 136 |
matches[g_factor] * g(matches[x_g], matches[t_g]) |
| 137 |
+ matches[independent_dW] * dW ** matches[dW_exponent] |
| 138 |
) |
| 139 |
elif x_g in matches: |
| 140 |
# Does not include a random variable but the g function |
| 141 |
stochastic = matches[g_factor] * g(matches[x_g], matches[t_g]) |
| 142 |
else: |
| 143 |
# Contains neither random variable nor g function --> empty |
| 144 |
stochastic = None |
| 145 |
|
| 146 |
return (non_stochastic, stochastic) |
| 147 |
|
| 148 |
|
| 149 |
class ExplicitStateUpdater(StateUpdateMethod): |
| 150 |
""" |
| 151 |
An object that can be used for defining state updaters via a simple |
| 152 |
description (see below). Resulting instances can be passed to the |
| 153 |
``method`` argument of the `NeuronGroup` constructor. As other state |
| 154 |
updater functions the `ExplicitStateUpdater` objects are callable, |
| 155 |
returning abstract code when called with an `Equations` object. |
| 156 |
|
| 157 |
A description of an explicit state updater consists of a (multi-line) |
| 158 |
string, containing assignments to variables and a final "x_new = ...", |
| 159 |
stating the integration result for a single timestep. The assignments |
| 160 |
can be used to define an arbitrary number of intermediate results and |
| 161 |
can refer to ``f(x, t)`` (the function being integrated, as a function of |
| 162 |
``x``, the previous value of the state variable and ``t``, the time) and |
| 163 |
``dt``, the size of the timestep. |
| 164 |
|
| 165 |
For example, to define a Runge-Kutta 4 integrator (already provided as |
| 166 |
`rk4`), use:: |
| 167 |
|
| 168 |
k1 = dt*f(x,t) |
| 169 |
k2 = dt*f(x+k1/2,t+dt/2) |
| 170 |
k3 = dt*f(x+k2/2,t+dt/2) |
| 171 |
k4 = dt*f(x+k3,t+dt) |
| 172 |
x_new = x+(k1+2*k2+2*k3+k4)/6 |
| 173 |
|
| 174 |
Note that for stochastic equations, the function `f` only corresponds to |
| 175 |
the non-stochastic part of the equation. The additional function `g` |
| 176 |
corresponds to the stochastic part that has to be multiplied with the |
| 177 |
stochastic variable xi (a standard normal random variable -- if the |
| 178 |
algorithm needs a random variable with a different variance/mean you have |
| 179 |
to multiply/add it accordingly). Equations with more than one |
| 180 |
stochastic variable do not have to be treated differently, the part |
| 181 |
referring to ``g`` is repeated for all stochastic variables automatically. |
| 182 |
|
| 183 |
Stochastic integrators can also make reference to ``dW`` (a normal |
| 184 |
distributed random number with variance ``dt``) and ``g(x, t)``, the |
| 185 |
stochastic part of an equation. A stochastic state updater could therefore |
| 186 |
use a description like:: |
| 187 |
|
| 188 |
x_new = x + dt*f(x,t) + g(x, t) * dW |
| 189 |
|
| 190 |
For simplicity, the same syntax is used for state updaters that only support |
| 191 |
additive noise, even though ``g(x, t)`` does not depend on ``x`` or ``t`` |
| 192 |
in that case. |
| 193 |
|
| 194 |
There a some restrictions on the complexity of the expressions (but most |
| 195 |
can be worked around by using intermediate results as in the above Runge- |
| 196 |
Kutta example): Every statement can only contain the functions ``f`` and |
| 197 |
``g`` once; The expressions have to be linear in the functions, e.g. you |
| 198 |
can use ``dt*f(x, t)`` but not ``f(x, t)**2``. |
| 199 |
|
| 200 |
Parameters |
| 201 |
---------- |
| 202 |
description : str |
| 203 |
A state updater description (see above). |
| 204 |
stochastic : {None, 'additive', 'multiplicative'} |
| 205 |
What kind of stochastic equations this state updater supports: ``None`` |
| 206 |
means no support of stochastic equations, ``'additive'`` means only |
| 207 |
equations with additive noise and ``'multiplicative'`` means |
| 208 |
supporting arbitrary stochastic equations. |
| 209 |
|
| 210 |
Raises |
| 211 |
------ |
| 212 |
ValueError |
| 213 |
If the parsing of the description failed. |
| 214 |
|
| 215 |
Notes |
| 216 |
----- |
| 217 |
Since clocks are updated *after* the state update, the time ``t`` used |
| 218 |
in the state update step is still at its previous value. Enumerating the |
| 219 |
states and discrete times, ``x_new = x + dt*f(x, t)`` is therefore |
| 220 |
understood as :math:`x_{i+1} = x_i + dt f(x_i, t_i)`, yielding the correct |
| 221 |
forward Euler integration. If the integrator has to refer to the time at |
| 222 |
the end of the timestep, simply use ``t + dt`` instead of ``t``. |
| 223 |
|
| 224 |
See also |
| 225 |
-------- |
| 226 |
euler, rk2, rk4, milstein |
| 227 |
""" |
| 228 |
|
| 229 |
# =========================================================================== |
| 230 |
# Parsing definitions |
| 231 |
# =========================================================================== |
| 232 |
#: Legal names for temporary variables |
| 233 |
TEMP_VAR = ~Literal("x_new") + Word( |
| 234 |
f"{string.ascii_letters}_", f"{string.ascii_letters + string.digits}_" |
| 235 |
).set_results_name("identifier") |
| 236 |
|
| 237 |
#: A single expression |
| 238 |
EXPRESSION = restOfLine.set_results_name("expression") |
| 239 |
|
| 240 |
#: An assignment statement |
| 241 |
STATEMENT = Group(TEMP_VAR + Suppress("=") + EXPRESSION).set_results_name( |
| 242 |
"statement" |
| 243 |
) |
| 244 |
|
| 245 |
#: The last line of a state updater description |
| 246 |
OUTPUT = Group( |
| 247 |
Suppress(Literal("x_new")) + Suppress("=") + EXPRESSION |
| 248 |
).set_results_name("output") |
| 249 |
|
| 250 |
#: A complete state updater description |
| 251 |
DESCRIPTION = ZeroOrMore(STATEMENT) + OUTPUT |
| 252 |
|
| 253 |
def __init__(self, description, stochastic=None, custom_check=None): |
| 254 |
self._description = description |
| 255 |
self.stochastic = stochastic |
| 256 |
self.custom_check = custom_check |
| 257 |
|
| 258 |
try: |
| 259 |
parsed = ExplicitStateUpdater.DESCRIPTION.parse_string( |
| 260 |
description, parse_all=True |
| 261 |
) |
| 262 |
except ParseException as p_exc: |
| 263 |
ex = SyntaxError("Parsing failed.") |
| 264 |
ex.text = str(p_exc.line) |
| 265 |
ex.offset = p_exc.column |
| 266 |
ex.lineno = p_exc.lineno |
| 267 |
raise ex from p_exc |
| 268 |
|
| 269 |
self.statements = [] |
| 270 |
self.symbols = SYMBOLS.copy() |
| 271 |
for element in parsed: |
| 272 |
expression = str_to_sympy(element.expression) |
| 273 |
# Replace all symbols used in state updater expressions by unique |
| 274 |
# names that cannot clash with user-defined variables or functions |
| 275 |
expression = expression.subs(sympy.Function("f"), self.symbols["__f"]) |
| 276 |
expression = expression.subs(sympy.Function("g"), self.symbols["__g"]) |
| 277 |
symbols = list(expression.atoms(sympy.Symbol)) |
| 278 |
unique_symbols = [] |
| 279 |
for symbol in symbols: |
| 280 |
if symbol.name == "dt": |
| 281 |
unique_symbols.append(symbol) |
| 282 |
else: |
| 283 |
unique_symbols.append(_symbol(f"__{symbol.name}")) |
| 284 |
for symbol, unique_symbol in zip(symbols, unique_symbols, strict=True): |
| 285 |
expression = expression.subs(symbol, unique_symbol) |
| 286 |
|
| 287 |
self.symbols.update({symbol.name: symbol for symbol in unique_symbols}) |
| 288 |
if element.getName() == "statement": |
| 289 |
self.statements.append((f"__{element.identifier}", expression)) |
| 290 |
elif element.getName() == "output": |
| 291 |
self.output = expression |
| 292 |
else: |
| 293 |
raise AssertionError(f"Unknown element name: {element.getName()}") |
| 294 |
|
| 295 |
def __repr__(self): |
| 296 |
# recreate a description string |
| 297 |
description = "\n".join([f"{var} = {expr}" for var, expr in self.statements]) |
| 298 |
if len(description): |
| 299 |
description += "\n" |
| 300 |
description += f"x_new = {str(self.output)}" |
| 301 |
classname = self.__class__.__name__ |
| 302 |
return f"{classname}('''{description}''', stochastic={self.stochastic!r})" |
| 303 |
|
| 304 |
def __str__(self): |
| 305 |
s = f"{self.__class__.__name__}\n" |
| 306 |
|
| 307 |
if len(self.statements) > 0: |
| 308 |
s += "Intermediate statements:\n" |
| 309 |
s += "\n".join( |
| 310 |
[f"{var} = {sympy_to_str(expr)}" for var, expr in self.statements] |
| 311 |
) |
| 312 |
s += "\n" |
| 313 |
|
| 314 |
s += "Output:\n" |
| 315 |
s += sympy_to_str(self.output) |
| 316 |
return s |
| 317 |
|
| 318 |
def _latex(self, *args): |
| 319 |
from sympy import Symbol, latex |
| 320 |
|
| 321 |
s = [r"\begin{equation}"] |
| 322 |
for var, expr in self.statements: |
| 323 |
expr = expr.subs(Symbol("x"), Symbol("x_t")) |
| 324 |
s.append(f"{latex(Symbol(var))} = {latex(expr)}\\\\") |
| 325 |
expr = self.output.subs(Symbol("x"), "x_t") |
| 326 |
s.append(f"x_{{t+1}} = {latex(expr)}") |
| 327 |
s.append(r"\end{equation}") |
| 328 |
return "\n".join(s) |
| 329 |
|
| 330 |
def _repr_latex_(self): |
| 331 |
return self._latex() |
| 332 |
|
| 333 |
def replace_func(self, x, t, expr, temp_vars, eq_symbols, stochastic_variable=None): |
| 334 |
""" |
| 335 |
Used to replace a single occurance of ``f(x, t)`` or ``g(x, t)``: |
| 336 |
`expr` is the non-stochastic (in the case of ``f``) or stochastic |
| 337 |
part (``g``) of the expression defining the right-hand-side of the |
| 338 |
differential equation describing `var`. It replaces the variable |
| 339 |
`var` with the value given as `x` and `t` by the value given for |
| 340 |
`t`. Intermediate variables will be replaced with the appropriate |
| 341 |
replacements as well. |
| 342 |
|
| 343 |
For example, in the `rk2` integrator, the second step involves the |
| 344 |
calculation of ``f(k/2 + x, dt/2 + t)``. If `var` is ``v`` and |
| 345 |
`expr` is ``-v / tau``, this will result in ``-(_k_v/2 + v)/tau``. |
| 346 |
|
| 347 |
Note that this deals with only one state variable `var`, given as |
| 348 |
an argument to the surrounding `_generate_RHS` function. |
| 349 |
""" |
| 350 |
|
| 351 |
try: |
| 352 |
s_expr = str_to_sympy(str(expr)) |
| 353 |
except SympifyError as ex: |
| 354 |
raise ValueError(f'Error parsing the expression "{expr}"') from ex |
| 355 |
|
| 356 |
for var in eq_symbols: |
| 357 |
# Generate specific temporary variables for the state variable, |
| 358 |
# e.g. '_k_v' for the state variable 'v' and the temporary |
| 359 |
# variable 'k'. |
| 360 |
if stochastic_variable is None: |
| 361 |
temp_var_replacements = { |
| 362 |
self.symbols[temp_var]: _symbol(f"{temp_var}_{var}") |
| 363 |
for temp_var in temp_vars |
| 364 |
} |
| 365 |
else: |
| 366 |
temp_var_replacements = { |
| 367 |
self.symbols[temp_var]: _symbol( |
| 368 |
f"{temp_var}_{var}_{stochastic_variable}" |
| 369 |
) |
| 370 |
for temp_var in temp_vars |
| 371 |
} |
| 372 |
# In the expression given as 'x', replace 'x' by the variable |
| 373 |
# 'var' and all the temporary variables by their |
| 374 |
# variable-specific counterparts. |
| 375 |
x_replacement = x.subs(self.symbols["__x"], eq_symbols[var]) |
| 376 |
x_replacement = x_replacement.subs(temp_var_replacements) |
| 377 |
|
| 378 |
# Replace the variable `var` in the expression by the new `x` |
| 379 |
# expression |
| 380 |
s_expr = s_expr.subs(eq_symbols[var], x_replacement) |
| 381 |
|
| 382 |
# If the expression given for t in the state updater description |
| 383 |
# is not just "t" (or rather "__t"), then replace t in the |
| 384 |
# equations by it, and replace "__t" by "t" afterwards. |
| 385 |
if t != self.symbols["__t"]: |
| 386 |
s_expr = s_expr.subs(SYMBOLS["t"], t) |
| 387 |
s_expr = s_expr.replace(self.symbols["__t"], SYMBOLS["t"]) |
| 388 |
|
| 389 |
return s_expr |
| 390 |
|
| 391 |
def _non_stochastic_part( |
| 392 |
self, |
| 393 |
eq_symbols, |
| 394 |
non_stochastic, |
| 395 |
non_stochastic_expr, |
| 396 |
stochastic_variable, |
| 397 |
temp_vars, |
| 398 |
var, |
| 399 |
): |
| 400 |
non_stochastic_results = [] |
| 401 |
if stochastic_variable is None or len(stochastic_variable) == 0: |
| 402 |
# Replace the f(x, t) part |
| 403 |
replace_f = lambda x, t: self.replace_func( |
| 404 |
x, t, non_stochastic, temp_vars, eq_symbols |
| 405 |
) |
| 406 |
non_stochastic_result = non_stochastic_expr.replace( |
| 407 |
self.symbols["__f"], replace_f |
| 408 |
) |
| 409 |
# Replace x by the respective variable |
| 410 |
non_stochastic_result = non_stochastic_result.subs( |
| 411 |
self.symbols["__x"], eq_symbols[var] |
| 412 |
) |
| 413 |
# Replace intermediate variables |
| 414 |
temp_var_replacements = { |
| 415 |
self.symbols[temp_var]: _symbol(f"{temp_var}_{var}") |
| 416 |
for temp_var in temp_vars |
| 417 |
} |
| 418 |
non_stochastic_result = non_stochastic_result.subs(temp_var_replacements) |
| 419 |
non_stochastic_results.append(non_stochastic_result) |
| 420 |
elif isinstance(stochastic_variable, str): |
| 421 |
# Replace the f(x, t) part |
| 422 |
replace_f = lambda x, t: self.replace_func( |
| 423 |
x, t, non_stochastic, temp_vars, eq_symbols, stochastic_variable |
| 424 |
) |
| 425 |
non_stochastic_result = non_stochastic_expr.replace( |
| 426 |
self.symbols["__f"], replace_f |
| 427 |
) |
| 428 |
# Replace x by the respective variable |
| 429 |
non_stochastic_result = non_stochastic_result.subs( |
| 430 |
self.symbols["__x"], eq_symbols[var] |
| 431 |
) |
| 432 |
# Replace intermediate variables |
| 433 |
temp_var_replacements = { |
| 434 |
self.symbols[temp_var]: _symbol( |
| 435 |
f"{temp_var}_{var}_{stochastic_variable}" |
| 436 |
) |
| 437 |
for temp_var in temp_vars |
| 438 |
} |
| 439 |
|
| 440 |
non_stochastic_result = non_stochastic_result.subs(temp_var_replacements) |
| 441 |
non_stochastic_results.append(non_stochastic_result) |
| 442 |
else: |
| 443 |
# Replace the f(x, t) part |
| 444 |
replace_f = lambda x, t: self.replace_func( |
| 445 |
x, t, non_stochastic, temp_vars, eq_symbols |
| 446 |
) |
| 447 |
non_stochastic_result = non_stochastic_expr.replace( |
| 448 |
self.symbols["__f"], replace_f |
| 449 |
) |
| 450 |
# Replace x by the respective variable |
| 451 |
non_stochastic_result = non_stochastic_result.subs( |
| 452 |
self.symbols["__x"], eq_symbols[var] |
| 453 |
) |
| 454 |
# Replace intermediate variables |
| 455 |
temp_var_replacements = { |
| 456 |
self.symbols[temp_var]: reduce( |
| 457 |
operator.add, |
| 458 |
[_symbol(f"{temp_var}_{var}_{xi}") for xi in stochastic_variable], |
| 459 |
) |
| 460 |
for temp_var in temp_vars |
| 461 |
} |
| 462 |
|
| 463 |
non_stochastic_result = non_stochastic_result.subs(temp_var_replacements) |
| 464 |
non_stochastic_results.append(non_stochastic_result) |
| 465 |
|
| 466 |
return non_stochastic_results |
| 467 |
|
| 468 |
def _stochastic_part( |
| 469 |
self, |
| 470 |
eq_symbols, |
| 471 |
stochastic, |
| 472 |
stochastic_expr, |
| 473 |
stochastic_variable, |
| 474 |
temp_vars, |
| 475 |
var, |
| 476 |
): |
| 477 |
stochastic_results = [] |
| 478 |
if isinstance(stochastic_variable, str): |
| 479 |
# Replace the g(x, t) part |
| 480 |
replace_f = lambda x, t: self.replace_func( |
| 481 |
x, |
| 482 |
t, |
| 483 |
stochastic.get(stochastic_variable, 0), |
| 484 |
temp_vars, |
| 485 |
eq_symbols, |
| 486 |
stochastic_variable, |
| 487 |
) |
| 488 |
stochastic_result = stochastic_expr.replace(self.symbols["__g"], replace_f) |
| 489 |
# Replace x by the respective variable |
| 490 |
stochastic_result = stochastic_result.subs( |
| 491 |
self.symbols["__x"], eq_symbols[var] |
| 492 |
) |
| 493 |
# Replace dW by the respective variable |
| 494 |
stochastic_result = stochastic_result.subs( |
| 495 |
self.symbols["__dW"], stochastic_variable |
| 496 |
) |
| 497 |
# Replace intermediate variables |
| 498 |
temp_var_replacements = { |
| 499 |
self.symbols[temp_var]: _symbol( |
| 500 |
f"{temp_var}_{var}_{stochastic_variable}" |
| 501 |
) |
| 502 |
for temp_var in temp_vars |
| 503 |
} |
| 504 |
|
| 505 |
stochastic_result = stochastic_result.subs(temp_var_replacements) |
| 506 |
stochastic_results.append(stochastic_result) |
| 507 |
else: |
| 508 |
for xi in stochastic_variable: |
| 509 |
# Replace the g(x, t) part |
| 510 |
replace_f = lambda x, t, xi=xi: self.replace_func( |
| 511 |
x, |
| 512 |
t, |
| 513 |
stochastic.get(xi, 0), |
| 514 |
temp_vars, |
| 515 |
eq_symbols, |
| 516 |
xi, |
| 517 |
) |
| 518 |
stochastic_result = stochastic_expr.replace( |
| 519 |
self.symbols["__g"], replace_f |
| 520 |
) |
| 521 |
# Replace x by the respective variable |
| 522 |
stochastic_result = stochastic_result.subs( |
| 523 |
self.symbols["__x"], eq_symbols[var] |
| 524 |
) |
| 525 |
|
| 526 |
# Replace dW by the respective variable |
| 527 |
stochastic_result = stochastic_result.subs(self.symbols["__dW"], xi) |
| 528 |
|
| 529 |
# Replace intermediate variables |
| 530 |
temp_var_replacements = { |
| 531 |
self.symbols[temp_var]: _symbol(f"{temp_var}_{var}_{xi}") |
| 532 |
for temp_var in temp_vars |
| 533 |
} |
| 534 |
|
| 535 |
stochastic_result = stochastic_result.subs(temp_var_replacements) |
| 536 |
stochastic_results.append(stochastic_result) |
| 537 |
return stochastic_results |
| 538 |
|
| 539 |
def _generate_RHS( |
| 540 |
self, |
| 541 |
eqs, |
| 542 |
var, |
| 543 |
eq_symbols, |
| 544 |
temp_vars, |
| 545 |
expr, |
| 546 |
non_stochastic_expr, |
| 547 |
stochastic_expr, |
| 548 |
stochastic_variable=(), |
| 549 |
): |
| 550 |
""" |
| 551 |
Helper function used in `__call__`. Generates the right hand side of |
| 552 |
an abstract code statement by appropriately replacing f, g and t. |
| 553 |
For example, given a differential equation ``dv/dt = -(v + I) / tau`` |
| 554 |
(i.e. `var` is ``v` and `expr` is ``(-v + I) / tau``) together with |
| 555 |
the `rk2` step ``return x + dt*f(x + k/2, t + dt/2)`` |
| 556 |
(i.e. `non_stochastic_expr` is |
| 557 |
``x + dt*f(x + k/2, t + dt/2)`` and `stochastic_expr` is ``None``), |
| 558 |
produces ``v + dt*(-v - _k_v/2 + I + _k_I/2)/tau``. |
| 559 |
|
| 560 |
""" |
| 561 |
|
| 562 |
# Note: in the following we are silently ignoring the case that a |
| 563 |
# state updater does not care about either the non-stochastic or the |
| 564 |
# stochastic part of an equation. We do trust state updaters to |
| 565 |
# correctly specify their own abilities (i.e. they do not claim to |
| 566 |
# support stochastic equations but actually just ignore the stochastic |
| 567 |
# part). We can't really check the issue here, as we are only dealing |
| 568 |
# with one line of the state updater description. It is perfectly valid |
| 569 |
# to write the euler update as: |
| 570 |
# non_stochastic = dt * f(x, t) |
| 571 |
# stochastic = dt**.5 * g(x, t) * xi |
| 572 |
# return x + non_stochastic + stochastic |
| 573 |
# |
| 574 |
# In the above case, we'll deal with lines which do not define either |
| 575 |
# the stochastic or the non-stochastic part. |
| 576 |
|
| 577 |
non_stochastic, stochastic = expr.split_stochastic() |
| 578 |
|
| 579 |
if non_stochastic_expr is not None: |
| 580 |
# We do have a non-stochastic part in the state updater description |
| 581 |
non_stochastic_results = self._non_stochastic_part( |
| 582 |
eq_symbols, |
| 583 |
non_stochastic, |
| 584 |
non_stochastic_expr, |
| 585 |
stochastic_variable, |
| 586 |
temp_vars, |
| 587 |
var, |
| 588 |
) |
| 589 |
else: |
| 590 |
non_stochastic_results = [] |
| 591 |
|
| 592 |
if not (stochastic is None or stochastic_expr is None): |
| 593 |
# We do have a stochastic part in the state |
| 594 |
# updater description |
| 595 |
stochastic_results = self._stochastic_part( |
| 596 |
eq_symbols, |
| 597 |
stochastic, |
| 598 |
stochastic_expr, |
| 599 |
stochastic_variable, |
| 600 |
temp_vars, |
| 601 |
var, |
| 602 |
) |
| 603 |
else: |
| 604 |
stochastic_results = [] |
| 605 |
|
| 606 |
RHS = sympy.Number(0) |
| 607 |
# All the parts (one non-stochastic and potentially more than one |
| 608 |
# stochastic part) are combined with addition |
| 609 |
for non_stochastic_result in non_stochastic_results: |
| 610 |
RHS += non_stochastic_result |
| 611 |
for stochastic_result in stochastic_results: |
| 612 |
RHS += stochastic_result |
| 613 |
|
| 614 |
return sympy_to_str(RHS) |
| 615 |
|
| 616 |
def __call__(self, eqs, variables=None, method_options=None): |
| 617 |
""" |
| 618 |
Apply a state updater description to model equations. |
| 619 |
|
| 620 |
Parameters |
| 621 |
---------- |
| 622 |
eqs : `Equations` |
| 623 |
The equations describing the model |
| 624 |
variables: dict-like, optional |
| 625 |
The `Variable` objects for the model. Ignored by the explicit |
| 626 |
state updater. |
| 627 |
method_options : dict, optional |
| 628 |
Additional options to the state updater (not used at the moment |
| 629 |
for the explicit state updaters). |
| 630 |
|
| 631 |
Examples |
| 632 |
-------- |
| 633 |
>>> from brian2 import * |
| 634 |
>>> eqs = Equations('dv/dt = -v / tau : volt') |
| 635 |
>>> print(euler(eqs)) |
| 636 |
_v = -dt*v/tau + v |
| 637 |
v = _v |
| 638 |
>>> print(rk4(eqs)) |
| 639 |
__k_1_v = -dt*v/tau |
| 640 |
__k_2_v = -dt*(__k_1_v/2 + v)/tau |
| 641 |
__k_3_v = -dt*(__k_2_v/2 + v)/tau |
| 642 |
__k_4_v = -dt*(__k_3_v + v)/tau |
| 643 |
_v = __k_1_v/6 + __k_2_v/3 + __k_3_v/3 + __k_4_v/6 + v |
| 644 |
v = _v |
| 645 |
""" |
| 646 |
extract_method_options(method_options, {}) |
| 647 |
# Non-stochastic numerical integrators should work for all equations, |
| 648 |
# except for stochastic equations |
| 649 |
if eqs.is_stochastic and self.stochastic is None: |
| 650 |
raise UnsupportedEquationsException( |
| 651 |
"Cannot integrate stochastic equations with this state updater." |
| 652 |
) |
| 653 |
if self.custom_check: |
| 654 |
self.custom_check(eqs, variables) |
| 655 |
# The final list of statements |
| 656 |
statements = [] |
| 657 |
|
| 658 |
stochastic_variables = eqs.stochastic_variables |
| 659 |
|
| 660 |
# The variables for the intermediate results in the state updater |
| 661 |
# description, e.g. the variable k in rk2 |
| 662 |
intermediate_vars = [var for var, expr in self.statements] |
| 663 |
|
| 664 |
# A dictionary mapping all the variables in the equations to their |
| 665 |
# sympy representations |
| 666 |
eq_variables = {var: _symbol(var) for var in eqs.eq_names} |
| 667 |
|
| 668 |
# Generate the random numbers for the stochastic variables |
| 669 |
for stochastic_variable in stochastic_variables: |
| 670 |
statements.append(f"{stochastic_variable} = dt**.5 * randn()") |
| 671 |
|
| 672 |
substituted_expressions = eqs.get_substituted_expressions(variables) |
| 673 |
|
| 674 |
# Process the intermediate statements in the stateupdater description |
| 675 |
for intermediate_var, intermediate_expr in self.statements: |
| 676 |
# Split the expression into a non-stochastic and a stochastic part |
| 677 |
non_stochastic_expr, stochastic_expr = split_expression(intermediate_expr) |
| 678 |
|
| 679 |
# Execute the statement by appropriately replacing the functions f |
| 680 |
# and g and the variable x for every equation in the model. |
| 681 |
# We use the model equations where the subexpressions have |
| 682 |
# already been substituted into the model equations. |
| 683 |
for var, expr in substituted_expressions: |
| 684 |
for xi in stochastic_variables: |
| 685 |
RHS = self._generate_RHS( |
| 686 |
eqs, |
| 687 |
var, |
| 688 |
eq_variables, |
| 689 |
intermediate_vars, |
| 690 |
expr, |
| 691 |
non_stochastic_expr, |
| 692 |
stochastic_expr, |
| 693 |
xi, |
| 694 |
) |
| 695 |
statements.append(f"{intermediate_var}_{var}_{xi} = {RHS}") |
| 696 |
if not stochastic_variables: # no stochastic variables |
| 697 |
RHS = self._generate_RHS( |
| 698 |
eqs, |
| 699 |
var, |
| 700 |
eq_variables, |
| 701 |
intermediate_vars, |
| 702 |
expr, |
| 703 |
non_stochastic_expr, |
| 704 |
stochastic_expr, |
| 705 |
) |
| 706 |
statements.append(f"{intermediate_var}_{var} = {RHS}") |
| 707 |
|
| 708 |
# Process the "return" line of the stateupdater description |
| 709 |
non_stochastic_expr, stochastic_expr = split_expression(self.output) |
| 710 |
|
| 711 |
if eqs.is_stochastic and ( |
| 712 |
self.stochastic != "multiplicative" |
| 713 |
and eqs.stochastic_type == "multiplicative" |
| 714 |
): |
| 715 |
# The equations are marked as having multiplicative noise and the |
| 716 |
# current state updater does not support such equations. However, |
| 717 |
# it is possible that the equations do not use multiplicative noise |
| 718 |
# at all. They could depend on time via a function that is constant |
| 719 |
# over a single time step (most likely, a TimedArray). In that case |
| 720 |
# we can integrate the equations |
| 721 |
dt_value = variables["dt"].get_value()[0] if "dt" in variables else None |
| 722 |
for _, expr in substituted_expressions: |
| 723 |
_, stoch = expr.split_stochastic() |
| 724 |
if stoch is None: |
| 725 |
continue |
| 726 |
# There could be more than one stochastic variable (e.g. xi_1, xi_2) |
| 727 |
for _, stoch_expr in stoch.items(): |
| 728 |
sympy_expr = str_to_sympy(stoch_expr.code) |
| 729 |
# The equation really has multiplicative noise, if it depends |
| 730 |
# on time (and not only via a function that is constant |
| 731 |
# over dt), or if it depends on another variable defined |
| 732 |
# via differential equations. |
| 733 |
if not is_constant_over_dt(sympy_expr, variables, dt_value) or len( |
| 734 |
stoch_expr.identifiers & eqs.diff_eq_names |
| 735 |
): |
| 736 |
raise UnsupportedEquationsException( |
| 737 |
"Cannot integrate " |
| 738 |
"equations with " |
| 739 |
"multiplicative noise with " |
| 740 |
"this state updater." |
| 741 |
) |
| 742 |
|
| 743 |
# Assign a value to all the model variables described by differential |
| 744 |
# equations |
| 745 |
for var, expr in substituted_expressions: |
| 746 |
RHS = self._generate_RHS( |
| 747 |
eqs, |
| 748 |
var, |
| 749 |
eq_variables, |
| 750 |
intermediate_vars, |
| 751 |
expr, |
| 752 |
non_stochastic_expr, |
| 753 |
stochastic_expr, |
| 754 |
stochastic_variables, |
| 755 |
) |
| 756 |
statements.append(f"_{var} = {RHS}") |
| 757 |
|
| 758 |
# Assign everything to the final variables |
| 759 |
for var, _ in substituted_expressions: |
| 760 |
statements.append(f"{var} = _{var}") |
| 761 |
|
| 762 |
return "\n".join(statements) |
| 763 |
|
| 764 |
|
| 765 |
# =============================================================================== |
| 766 |
# Excplicit state updaters |
| 767 |
# =============================================================================== |
| 768 |
|
| 769 |
# these objects can be used like functions because they are callable |
| 770 |
|
| 771 |
#: Forward Euler state updater |
| 772 |
euler = ExplicitStateUpdater( |
| 773 |
"x_new = x + dt * f(x,t) + g(x,t) * dW", stochastic="additive" |
| 774 |
) |
| 775 |
|
| 776 |
#: Second order Runge-Kutta method (midpoint method) |
| 777 |
rk2 = ExplicitStateUpdater( |
| 778 |
""" |
| 779 |
k = dt * f(x,t) |
| 780 |
x_new = x + dt*f(x + k/2, t + dt/2)""" |
| 781 |
) |
| 782 |
|
| 783 |
#: Classical Runge-Kutta method (RK4) |
| 784 |
rk4 = ExplicitStateUpdater( |
| 785 |
""" |
| 786 |
k_1 = dt*f(x,t) |
| 787 |
k_2 = dt*f(x+k_1/2,t+dt/2) |
| 788 |
k_3 = dt*f(x+k_2/2,t+dt/2) |
| 789 |
k_4 = dt*f(x+k_3,t+dt) |
| 790 |
x_new = x+(k_1+2*k_2+2*k_3+k_4)/6 |
| 791 |
""" |
| 792 |
) |
| 793 |
|
| 794 |
|
| 795 |
def diagonal_noise(equations, variables): |
| 796 |
""" |
| 797 |
Checks whether we deal with diagonal noise, i.e. one independent noise |
| 798 |
variable per variable. |
| 799 |
|
| 800 |
Raises |
| 801 |
------ |
| 802 |
UnsupportedEquationsException |
| 803 |
If the noise is not diagonal. |
| 804 |
""" |
| 805 |
if not equations.is_stochastic: |
| 806 |
return |
| 807 |
|
| 808 |
stochastic_vars = [] |
| 809 |
for _, expr in equations.get_substituted_expressions(variables): |
| 810 |
expr_stochastic_vars = expr.stochastic_variables |
| 811 |
if len(expr_stochastic_vars) > 1: |
| 812 |
# More than one stochastic variable --> no diagonal noise |
| 813 |
raise UnsupportedEquationsException( |
| 814 |
"Cannot integrate stochastic " |
| 815 |
"equations with non-diagonal " |
| 816 |
"noise with this state " |
| 817 |
"updater." |
| 818 |
) |
| 819 |
stochastic_vars.extend(expr_stochastic_vars) |
| 820 |
|
| 821 |
# If there's no stochastic variable is used in more than one equation, we |
| 822 |
# have diagonal noise |
| 823 |
if len(stochastic_vars) != len(set(stochastic_vars)): |
| 824 |
raise UnsupportedEquationsException( |
| 825 |
"Cannot integrate stochastic " |
| 826 |
"equations with non-diagonal " |
| 827 |
"noise with this state " |
| 828 |
"updater." |
| 829 |
) |
| 830 |
|
| 831 |
|
| 832 |
#: Derivative-free Milstein method |
| 833 |
milstein = ExplicitStateUpdater( |
| 834 |
""" |
| 835 |
x_support = x + dt*f(x, t) + dt**.5 * g(x, t) |
| 836 |
g_support = g(x_support, t) |
| 837 |
k = 1/(2*dt**.5)*(g_support - g(x, t))*(dW**2) |
| 838 |
x_new = x + dt*f(x,t) + g(x, t) * dW + k |
| 839 |
""", |
| 840 |
stochastic="multiplicative", |
| 841 |
custom_check=diagonal_noise, |
| 842 |
) |
| 843 |
|
| 844 |
#: Stochastic Heun method (for multiplicative Stratonovic SDEs with non-diagonal |
| 845 |
#: diffusion matrix) |
| 846 |
heun = ExplicitStateUpdater( |
| 847 |
""" |
| 848 |
x_support = x + g(x,t) * dW |
| 849 |
g_support = g(x_support,t+dt) |
| 850 |
x_new = x + dt*f(x,t) + .5*dW*(g(x,t)+g_support) |
| 851 |
""", |
| 852 |
stochastic="multiplicative", |
| 853 |
) |