| 1 |
""" |
| 2 |
Module defining `CodeString`, a class for a string of code together with |
| 3 |
information about its namespace. Only serves as a parent class, its subclasses |
| 4 |
`Expression` and `Statements` are the ones that are actually used. |
| 5 |
""" |
| 6 |
|
| 7 |
from collections.abc import Hashable |
| 8 |
|
| 9 |
import sympy |
| 10 |
|
| 11 |
from brian2.parsing.sympytools import str_to_sympy, sympy_to_str |
| 12 |
from brian2.utils.logger import get_logger |
| 13 |
from brian2.utils.stringtools import get_identifiers |
| 14 |
|
| 15 |
__all__ = ["Expression", "Statements"] |
| 16 |
|
| 17 |
logger = get_logger(__name__) |
| 18 |
|
| 19 |
|
| 20 |
class CodeString(Hashable): |
| 21 |
""" |
| 22 |
A class for representing "code strings", i.e. a single Python expression |
| 23 |
or a sequence of Python statements. |
| 24 |
|
| 25 |
Parameters |
| 26 |
---------- |
| 27 |
code : str |
| 28 |
The code string, may be an expression or a statement(s) (possibly |
| 29 |
multi-line). |
| 30 |
|
| 31 |
""" |
| 32 |
|
| 33 |
def __init__(self, code): |
| 34 |
self._code = code.strip() |
| 35 |
|
| 36 |
# : Set of identifiers in the code string |
| 37 |
self.identifiers = get_identifiers(code) |
| 38 |
|
| 39 |
code = property(lambda self: self._code, doc="The code string") |
| 40 |
|
| 41 |
def __str__(self): |
| 42 |
return self.code |
| 43 |
|
| 44 |
def __repr__(self): |
| 45 |
return f"{self.__class__.__name__}({self.code!r})" |
| 46 |
|
| 47 |
def __eq__(self, other): |
| 48 |
if not isinstance(other, CodeString): |
| 49 |
return NotImplemented |
| 50 |
return self.code == other.code |
| 51 |
|
| 52 |
def __ne__(self, other): |
| 53 |
return not self == other |
| 54 |
|
| 55 |
def __hash__(self): |
| 56 |
return hash(self.code) |
| 57 |
|
| 58 |
|
| 59 |
class Statements(CodeString): |
| 60 |
""" |
| 61 |
Class for representing statements. |
| 62 |
|
| 63 |
Parameters |
| 64 |
---------- |
| 65 |
code : str |
| 66 |
The statement or statements. Several statements can be given as a |
| 67 |
multi-line string or separated by semicolons. |
| 68 |
|
| 69 |
Notes |
| 70 |
----- |
| 71 |
Currently, the implementation of this class does not add anything to |
| 72 |
`~brian2.equations.codestrings.CodeString`, but it should be used instead |
| 73 |
of that class for clarity and to allow for future functionality that is |
| 74 |
only relevant to statements and not to expressions. |
| 75 |
""" |
| 76 |
|
| 77 |
pass |
| 78 |
|
| 79 |
|
| 80 |
class Expression(CodeString): |
| 81 |
""" |
| 82 |
Class for representing an expression. |
| 83 |
|
| 84 |
Parameters |
| 85 |
---------- |
| 86 |
code : str, optional |
| 87 |
The expression. Note that the expression has to be written in a form |
| 88 |
that is parseable by sympy. Alternatively, a sympy expression can be |
| 89 |
provided (in the ``sympy_expression`` argument). |
| 90 |
sympy_expression : sympy expression, optional |
| 91 |
A sympy expression. Alternatively, a plain string expression can be |
| 92 |
provided (in the ``code`` argument). |
| 93 |
""" |
| 94 |
|
| 95 |
def __init__(self, code=None, sympy_expression=None): |
| 96 |
if code is None and sympy_expression is None: |
| 97 |
raise TypeError("Have to provide either a string or a sympy expression") |
| 98 |
if code is not None and sympy_expression is not None: |
| 99 |
raise TypeError( |
| 100 |
"Provide a string expression or a sympy expression, not both" |
| 101 |
) |
| 102 |
|
| 103 |
if code is None: |
| 104 |
code = sympy_to_str(sympy_expression) |
| 105 |
else: |
| 106 |
# Just try to convert it to a sympy expression to get syntax errors |
| 107 |
# for incorrect expressions |
| 108 |
str_to_sympy(code) |
| 109 |
super().__init__(code=code) |
| 110 |
|
| 111 |
stochastic_variables = property( |
| 112 |
lambda self: { |
| 113 |
variable |
| 114 |
for variable in self.identifiers |
| 115 |
if variable == "xi" or variable.startswith("xi_") |
| 116 |
}, |
| 117 |
doc="Stochastic variables in this expression", |
| 118 |
) |
| 119 |
|
| 120 |
def split_stochastic(self): |
| 121 |
""" |
| 122 |
Split the expression into a stochastic and non-stochastic part. |
| 123 |
|
| 124 |
Splits the expression into a tuple of one `Expression` objects f (the |
| 125 |
non-stochastic part) and a dictionary mapping stochastic variables |
| 126 |
to `Expression` objects. For example, an expression of the form |
| 127 |
``f + g * xi_1 + h * xi_2`` would be returned as: |
| 128 |
``(f, {'xi_1': g, 'xi_2': h})`` |
| 129 |
Note that the `Expression` objects for the stochastic parts do not |
| 130 |
include the stochastic variable itself. |
| 131 |
|
| 132 |
Returns |
| 133 |
------- |
| 134 |
(f, d) : (`Expression`, dict) |
| 135 |
A tuple of an `Expression` object and a dictionary, the first |
| 136 |
expression being the non-stochastic part of the equation and |
| 137 |
the dictionary mapping stochastic variables (``xi`` or starting |
| 138 |
with ``xi_``) to `Expression` objects. If no stochastic variable |
| 139 |
is present in the code string, a tuple ``(self, None)`` will be |
| 140 |
returned with the unchanged `Expression` object. |
| 141 |
""" |
| 142 |
stochastic_variables = [] |
| 143 |
for identifier in self.identifiers: |
| 144 |
if identifier == "xi" or identifier.startswith("xi_"): |
| 145 |
stochastic_variables.append(identifier) |
| 146 |
|
| 147 |
# No stochastic variable |
| 148 |
if not len(stochastic_variables): |
| 149 |
return (self, None) |
| 150 |
|
| 151 |
stochastic_symbols = [ |
| 152 |
sympy.Symbol(variable, real=True) for variable in stochastic_variables |
| 153 |
] |
| 154 |
|
| 155 |
# Note that collect only works properly if the expression is expanded |
| 156 |
collected = ( |
| 157 |
str_to_sympy(self.code).expand().collect(stochastic_symbols, evaluate=False) |
| 158 |
) |
| 159 |
|
| 160 |
f_expr = None |
| 161 |
stochastic_expressions = {} |
| 162 |
for var, s_expr in collected.items(): |
| 163 |
expr = Expression(sympy_expression=s_expr) |
| 164 |
if var == 1: |
| 165 |
if any(s_expr.has(s) for s in stochastic_symbols): |
| 166 |
raise AssertionError( |
| 167 |
"Error when separating expression " |
| 168 |
f"'{self.code}' into stochastic and non-" |
| 169 |
"stochastic term: non-stochastic " |
| 170 |
f"part was determined to be '{s_expr}' but " |
| 171 |
"contains a stochastic symbol." |
| 172 |
) |
| 173 |
f_expr = expr |
| 174 |
elif var in stochastic_symbols: |
| 175 |
stochastic_expressions[str(var)] = expr |
| 176 |
else: |
| 177 |
raise ValueError( |
| 178 |
f"Expression '{self.code}' cannot be separated into " |
| 179 |
"stochastic and non-stochastic " |
| 180 |
"term" |
| 181 |
) |
| 182 |
|
| 183 |
if f_expr is None: |
| 184 |
f_expr = Expression("0.0") |
| 185 |
|
| 186 |
return f_expr, stochastic_expressions |
| 187 |
|
| 188 |
def _repr_pretty_(self, p, cycle): |
| 189 |
""" |
| 190 |
Pretty printing for ipython. |
| 191 |
""" |
| 192 |
if cycle: |
| 193 |
raise AssertionError("Cyclical call of 'CodeString._repr_pretty'") |
| 194 |
# Make use of sympy's pretty printing |
| 195 |
p.pretty(str_to_sympy(self.code)) |
| 196 |
|
| 197 |
def __eq__(self, other): |
| 198 |
if not isinstance(other, Expression): |
| 199 |
return NotImplemented |
| 200 |
return self.code == other.code |
| 201 |
|
| 202 |
def __ne__(self, other): |
| 203 |
return not self.__eq__(other) |
| 204 |
|
| 205 |
def __hash__(self): |
| 206 |
return hash(self.code) |
| 207 |
|
| 208 |
|
| 209 |
def is_constant_over_dt(expression, variables, dt_value): |
| 210 |
""" |
| 211 |
Check whether an expression can be considered as constant over a time step. |
| 212 |
This is *not* the case when the expression either: |
| 213 |
|
| 214 |
1. contains the variable ``t`` (except as the argument of a function that |
| 215 |
can be considered as constant over a time step, e.g. a `TimedArray` with |
| 216 |
a dt equal to or greater than the dt used to evaluate this expression) |
| 217 |
2. refers to a stateful function such as ``rand()``. |
| 218 |
|
| 219 |
Parameters |
| 220 |
---------- |
| 221 |
expression : `sympy.Expr` |
| 222 |
The (sympy) expression to analyze |
| 223 |
variables : dict |
| 224 |
The variables dictionary. |
| 225 |
dt_value : float or None |
| 226 |
The length of a timestep (without units), can be ``None`` if the |
| 227 |
time step is not yet known. |
| 228 |
|
| 229 |
Returns |
| 230 |
------- |
| 231 |
is_constant : bool |
| 232 |
Whether the expression can be considered to be constant over a time |
| 233 |
step. |
| 234 |
""" |
| 235 |
t_symbol = sympy.Symbol("t", real=True, positive=True) |
| 236 |
if expression == t_symbol: |
| 237 |
return False # The full expression is simply "t" |
| 238 |
func_name = str(expression.func) |
| 239 |
func_variable = variables.get(func_name, None) |
| 240 |
if func_variable is not None and not func_variable.stateless: |
| 241 |
return False |
| 242 |
for arg in expression.args: |
| 243 |
if arg == t_symbol and dt_value is not None: |
| 244 |
# We found "t" -- if it is not the only argument of a locally |
| 245 |
# constant function we bail out |
| 246 |
if not ( |
| 247 |
func_variable is not None |
| 248 |
and func_variable.is_locally_constant(dt_value) |
| 249 |
): |
| 250 |
return False |
| 251 |
else: |
| 252 |
if not is_constant_over_dt(arg, variables, dt_value): |
| 253 |
return False |
| 254 |
return True |