Debian Codegraph @

brian2/equations/equations.py

raw
1 """
2 Differential equations for Brian models.
3 """
4
5 import keyword
6 import re
7 import string
8 from collections import namedtuple
9 from collections.abc import Hashable, Mapping
10
11 import sympy
12 from pyparsing import (
13 CharsNotIn,
14 Combine,
15 Group,
16 LineEnd,
17 OneOrMore,
18 Optional,
19 ParseException,
20 Suppress,
21 Word,
22 ZeroOrMore,
23 restOfLine,
24 )
25
26 from brian2.core.namespace import DEFAULT_CONSTANTS, DEFAULT_FUNCTIONS, DEFAULT_UNITS
27 from brian2.parsing.sympytools import str_to_sympy, sympy_to_str
28 from brian2.units.allunits import second
29 from brian2.units.fundamentalunits import (
30 DIMENSIONLESS,
31 DimensionMismatchError,
32 Quantity,
33 Unit,
34 get_dimensions,
35 get_unit,
36 get_unit_for_display,
37 )
38 from brian2.utils.caching import CacheKey, cached
39 from brian2.utils.logger import get_logger
40 from brian2.utils.stringtools import get_identifiers
41 from brian2.utils.topsort import topsort
42
43 from .codestrings import Expression
44 from .unitcheck import check_dimensions
45
46 __all__ = ["Equations"]
47
48 logger = get_logger(__name__)
49
50 # Equation types (currently simple strings but always use the constants,
51 # this might get refactored into objects, for example)
52 PARAMETER = "parameter"
53 DIFFERENTIAL_EQUATION = "differential equation"
54 SUBEXPRESSION = "subexpression"
55
56 # variable types (FLOAT is the only one that is possible for variables that
57 # have dimensions). These types will be later translated into dtypes, either
58 # using the default values from the preferences, or explicitly given dtypes in
59 # the construction of the `NeuronGroup`, `Synapses`, etc. object
60 FLOAT = "float"
61 INTEGER = "integer"
62 BOOLEAN = "boolean"
63
64 # Definitions of equation structure for parsing with pyparsing
65 # TODO: Maybe move them somewhere else to not pollute the namespace here?
66 # Only IDENTIFIER and EQUATIONS are ever used later
67 ###############################################################################
68 # Basic Elements
69 ###############################################################################
70
71 # identifiers like in C: can start with letter or underscore, then a
72 # combination of letters, numbers and underscores
73 # Note that the check_identifiers function later performs more checks, e.g.
74 # names starting with underscore should only be used internally
75 IDENTIFIER = Word(
76 string.ascii_letters + "_", string.ascii_letters + string.digits + "_"
77 ).set_results_name("identifier")
78
79 # very broad definition here, expression will be analysed by sympy anyway
80 # allows for multi-line expressions, where each line can have comments
81 EXPRESSION = Combine(
82 OneOrMore(
83 (CharsNotIn(":#\n") + Suppress(Optional(LineEnd()))).ignore("#" + restOfLine)
84 ),
85 joinString=" ",
86 ).set_results_name("expression")
87
88 # a unit
89 # very broad definition here, again. Whether this corresponds to a valid unit
90 # string will be checked later
91 UNIT = Word(string.ascii_letters + string.digits + "*/.- ").set_results_name("unit")
92
93 # a single Flag (e.g. "const" or "event-driven")
94 FLAG = Word(string.ascii_letters, string.ascii_letters + "_- " + string.digits)
95
96 # Flags are comma-separated and enclosed in parantheses: "(flag1, flag2)"
97 FLAGS = (
98 Suppress("(") + FLAG + ZeroOrMore(Suppress(",") + FLAG) + Suppress(")")
99 ).set_results_name("flags")
100
101 ###############################################################################
102 # Equations
103 ###############################################################################
104 # Three types of equations
105 # Parameter:
106 # x : volt (flags)
107 PARAMETER_EQ = Group(
108 IDENTIFIER + Suppress(":") + UNIT + Optional(FLAGS)
109 ).set_results_name(PARAMETER)
110
111 # Static equation:
112 # x = 2 * y : volt (flags)
113 STATIC_EQ = Group(
114 IDENTIFIER + Suppress("=") + EXPRESSION + Suppress(":") + UNIT + Optional(FLAGS)
115 ).set_results_name(SUBEXPRESSION)
116
117 # Differential equation
118 # dx/dt = -x / tau : volt
119 DIFF_OP = Suppress("d") + IDENTIFIER + Suppress("/") + Suppress("dt")
120 DIFF_EQ = Group(
121 DIFF_OP + Suppress("=") + EXPRESSION + Suppress(":") + UNIT + Optional(FLAGS)
122 ).set_results_name(DIFFERENTIAL_EQUATION)
123
124 # ignore comments
125 EQUATION = (PARAMETER_EQ | STATIC_EQ | DIFF_EQ).ignore("#" + restOfLine)
126 EQUATIONS = ZeroOrMore(EQUATION)
127
128
129 class EquationError(Exception):
130 """
131 Exception type related to errors in an equation definition.
132 """
133
134 pass
135
136
137 def check_identifier_basic(identifier):
138 """
139 Check an identifier (usually resulting from an equation string provided by
140 the user) for conformity with the rules. The rules are:
141
142 1. Only ASCII characters
143 2. Starts with a character, then mix of alphanumerical characters and
144 underscore
145 3. Is not a reserved keyword of Python
146
147 Parameters
148 ----------
149 identifier : str
150 The identifier that should be checked
151
152 Raises
153 ------
154 SyntaxError
155 If the identifier does not conform to the above rules.
156 """
157
158 # Check whether the identifier is parsed correctly -- this is always the
159 # case, if the identifier results from the parsing of an equation but there
160 # might be situations where the identifier is specified directly
161 parse_result = list(IDENTIFIER.scan_string(identifier))
162
163 # parse_result[0][0][0] refers to the matched string -- this should be the
164 # full identifier, if not it is an illegal identifier like "3foo" which only
165 # matched on "foo"
166 if len(parse_result) != 1 or parse_result[0][0][0] != identifier:
167 raise SyntaxError(f"'{identifier}' is not a valid variable name.")
168
169 if keyword.iskeyword(identifier):
170 raise SyntaxError(
171 f"'{identifier}' is a Python keyword and cannot be used as a variable."
172 )
173
174 if identifier.startswith("_"):
175 raise SyntaxError(
176 f"Variable '{identifier}' starts with an underscore, "
177 "this is only allowed for variables used "
178 "internally"
179 )
180
181
182 def check_identifier_reserved(identifier):
183 """
184 Check that an identifier is not using a reserved special variable name. The
185 special variables are: 't', 'dt', and 'xi', as well as everything starting
186 with `xi_`.
187
188 Parameters
189 ----------
190 identifier: str
191 The identifier that should be checked
192
193 Raises
194 ------
195 SyntaxError
196 If the identifier is a special variable name.
197 """
198 if identifier in (
199 "t",
200 "dt",
201 "t_in_timesteps",
202 "xi",
203 "i",
204 "N",
205 ) or identifier.startswith("xi_"):
206 raise SyntaxError(
207 f"'{identifier}' has a special meaning in equations and "
208 "cannot be used as a variable name."
209 )
210
211
212 def check_identifier_units(identifier):
213 """
214 Make sure that identifier names do not clash with unit names.
215 """
216 if identifier in DEFAULT_UNITS:
217 raise SyntaxError(
218 f"'{identifier}' is the name of a unit, cannot be used as a variable name."
219 )
220
221
222 def check_identifier_functions(identifier):
223 """
224 Make sure that identifier names do not clash with function names.
225 """
226 if identifier in DEFAULT_FUNCTIONS:
227 raise SyntaxError(
228 f"'{identifier}' is the name of a function, cannot be used as "
229 "a variable name."
230 )
231
232
233 def check_identifier_constants(identifier):
234 """
235 Make sure that identifier names do not clash with function names.
236 """
237 if identifier in DEFAULT_CONSTANTS:
238 raise SyntaxError(
239 f"'{identifier}' is the name of a constant, cannot be used as "
240 "a variable name."
241 )
242
243
244 _base_units_with_alternatives = None
245 _base_units = None
246
247
248 def dimensions_and_type_from_string(unit_string):
249 """
250 Returns the physical dimensions that results from evaluating a string like
251 "siemens / metre ** 2", allowing for the special string "1" to signify
252 dimensionless units, the string "boolean" for a boolean and "integer" for
253 an integer variable.
254
255 Parameters
256 ----------
257 unit_string : str
258 The string that should evaluate to a unit
259
260 Returns
261 -------
262 d, type : (`Dimension`, {FLOAT, INTEGER or BOOL})
263 The resulting physical dimensions and the type of the variable.
264
265 Raises
266 ------
267 ValueError
268 If the string cannot be evaluated to a unit.
269 """
270 # Lazy import to avoid circular dependency
271 from brian2.core.namespace import DEFAULT_UNITS
272
273 global _base_units_with_alternatives
274 global _base_units
275 if _base_units_with_alternatives is None:
276 base_units_for_dims = {}
277 for unit_name, unit in reversed(DEFAULT_UNITS.items()):
278 if float(unit) == 1.0 and repr(unit)[-1] not in ["2", "3"]:
279 if unit.dim in base_units_for_dims:
280 if unit_name not in base_units_for_dims[unit.dim]:
281 base_units_for_dims[unit.dim].append(unit_name)
282 else:
283 base_units_for_dims[unit.dim] = [repr(unit)]
284 if unit_name != repr(unit):
285 base_units_for_dims[unit.dim].append(unit_name)
286 alternatives = sorted(
287 [tuple(values) for values in base_units_for_dims.values()]
288 )
289 _base_units = {v: DEFAULT_UNITS[v] for values in alternatives for v in values}
290 # Create a string that lists all allowed base units
291 alternative_strings = []
292 for units in alternatives:
293 string = units[0]
294 if len(units) > 1:
295 other_units = ", ".join(units[1:])
296 string += f" ({other_units})"
297 alternative_strings.append(string)
298 _base_units_with_alternatives = ", ".join(alternative_strings)
299
300 unit_string = unit_string.strip()
301
302 # Special case: dimensionless unit
303 if unit_string == "1":
304 return DIMENSIONLESS, FLOAT
305
306 # Another special case: boolean variable
307 if unit_string == "boolean":
308 return DIMENSIONLESS, BOOLEAN
309 if unit_string == "bool":
310 raise TypeError("Use 'boolean' not 'bool' as the unit for a boolean variable.")
311
312 # Yet another special case: integer variable
313 if unit_string == "integer":
314 return DIMENSIONLESS, INTEGER
315
316 # Check first whether the expression only refers to base units
317 identifiers = get_identifiers(unit_string)
318 for identifier in identifiers:
319 if identifier not in _base_units:
320 if identifier in DEFAULT_UNITS:
321 # A known unit, but not a base unit
322 base_unit = get_unit(DEFAULT_UNITS[identifier].dim)
323 if repr(base_unit) not in _base_units:
324 # Make sure that we don't suggest a unit that is not allowed
325 # (should not happen, normally)
326 base_unit = Unit(1, dim=base_unit.dim)
327 raise ValueError(
328 "Unit specification refers to "
329 f"'{identifier}', but this is not a base "
330 f"unit. Use '{base_unit!r}' instead."
331 )
332 else:
333 # Not a known unit
334 raise ValueError(
335 "Unit specification refers to "
336 f"'{identifier}', but this is not a base "
337 "unit. The following base units are "
338 f"allowed: {_base_units_with_alternatives}."
339 )
340 try:
341 evaluated_unit = eval(unit_string, _base_units)
342 except Exception as ex:
343 raise ValueError(
344 f"Could not interpret '{unit_string}' as a unit specification."
345 ) from ex
346
347 # Check whether the result is a unit
348 if not isinstance(evaluated_unit, Unit):
349 if isinstance(evaluated_unit, Quantity):
350 raise ValueError(
351 f"'{unit_string}' does not evaluate to a unit but to a "
352 "quantity -- make sure to only use units, e.g. "
353 "'siemens/metre**2' and not '1 * siemens/metre**2'"
354 )
355 else:
356 raise ValueError(
357 f"'{unit_string}' does not evaluate to a unit, the result "
358 f"has type {type(evaluated_unit)} instead."
359 )
360
361 # No error has been raised, all good
362 return evaluated_unit.dim, FLOAT
363
364
365 @cached
366 def parse_string_equations(eqns):
367 """
368 parse_string_equations(eqns)
369
370 Parse a string defining equations.
371
372 Parameters
373 ----------
374 eqns : str
375 The (possibly multi-line) string defining the equations. See the
376 documentation of the `Equations` class for details.
377
378 Returns
379 -------
380 equations : dict
381 A dictionary mapping variable names to
382 `~brian2.equations.equations.Equations` objects
383 """
384 equations = {}
385
386 try:
387 parsed = EQUATIONS.parse_string(eqns, parse_all=True)
388 except ParseException as p_exc:
389 raise EquationError(
390 "Parsing failed: \n"
391 + str(p_exc.line)
392 + "\n"
393 + " " * (p_exc.column - 1)
394 + "^\n"
395 + str(p_exc)
396 ) from p_exc
397 for eq in parsed:
398 eq_type = eq.getName()
399 eq_content = dict(eq.items())
400 # Check for reserved keywords
401 identifier = eq_content["identifier"]
402
403 # Convert unit string to Unit object
404 try:
405 dims, var_type = dimensions_and_type_from_string(eq_content["unit"])
406 except ValueError as ex:
407 raise EquationError(
408 f"Error parsing the unit specification for variable '{identifier}'."
409 ) from ex
410
411 expression = eq_content.get("expression")
412 if expression is not None:
413 # Replace multiple whitespaces (arising from joining multiline
414 # strings) with single space
415 p = re.compile(r"\s{2,}")
416 expression = Expression(p.sub(" ", expression))
417 flags = list(eq_content.get("flags", []))
418
419 equation = SingleEquation(
420 eq_type, identifier, dims, var_type=var_type, expr=expression, flags=flags
421 )
422
423 if identifier in equations:
424 raise EquationError(f"Duplicate definition of variable '{identifier}'")
425
426 equations[identifier] = equation
427
428 return equations
429
430
431 class SingleEquation(Hashable, CacheKey):
432 """
433 Class for internal use, encapsulates a single equation or parameter.
434
435 .. note::
436 This class should never be used directly, it is only useful as part of
437 the `Equations` class.
438
439 Parameters
440 ----------
441 type : {PARAMETER, DIFFERENTIAL_EQUATION, SUBEXPRESSION}
442 The type of the equation.
443 varname : str
444 The variable that is defined by this equation.
445 dimensions : `Dimension`
446 The physical dimensions of the variable
447 var_type : {FLOAT, INTEGER, BOOLEAN}
448 The type of the variable (floating point value or boolean).
449 expr : `Expression`, optional
450 The expression defining the variable (or ``None`` for parameters).
451 flags: list of str, optional
452 A list of flags that give additional information about this equation.
453 What flags are possible depends on the type of the equation and the
454 context.
455 """
456
457 _cache_irrelevant_attributes = {"update_order"}
458
459 def __init__(
460 self, type, varname, dimensions, var_type=FLOAT, expr=None, flags=None
461 ):
462 self.type = type
463 self.varname = varname
464 self.dim = get_dimensions(dimensions)
465 self.var_type = var_type
466 if dimensions is not DIMENSIONLESS:
467 if var_type == BOOLEAN:
468 raise TypeError("Boolean variables are necessarily dimensionless.")
469 elif var_type == INTEGER:
470 raise TypeError("Integer variables are necessarily dimensionless.")
471
472 if type == DIFFERENTIAL_EQUATION:
473 if var_type != FLOAT:
474 raise TypeError(
475 "Differential equations can only define floating point variables"
476 )
477 self.expr = expr
478 if flags is None:
479 self.flags = []
480 else:
481 self.flags = list(flags)
482
483 # will be set later in the sort_subexpressions method of Equations
484 self.update_order = -1
485
486 unit = property(lambda self: get_unit(self.dim), doc="The `Unit` of this equation.")
487
488 identifiers = property(
489 lambda self: self.expr.identifiers if self.expr is not None else set(),
490 doc="All identifiers in the RHS of this equation.",
491 )
492
493 stochastic_variables = property(
494 lambda self: {
495 variable
496 for variable in self.identifiers
497 if variable == "xi" or variable.startswith("xi_")
498 },
499 doc="Stochastic variables in the RHS of this equation",
500 )
501
502 def __eq__(self, other):
503 if not isinstance(other, SingleEquation):
504 return NotImplemented
505 return self._state_tuple == other._state_tuple
506
507 def __ne__(self, other):
508 return not self == other
509
510 def __hash__(self):
511 return hash(self._state_tuple)
512
513 def _latex(self, *args):
514 if self.type == DIFFERENTIAL_EQUATION:
515 return (
516 r"\frac{\mathrm{d}"
517 + sympy.latex(sympy.Symbol(self.varname))
518 + r"}{\mathrm{d}t} = "
519 + sympy.latex(str_to_sympy(self.expr.code))
520 )
521 elif self.type == SUBEXPRESSION:
522 return (
523 sympy.latex(sympy.Symbol(self.varname))
524 + " = "
525 + sympy.latex(str_to_sympy(self.expr.code))
526 )
527 elif self.type == PARAMETER:
528 return sympy.latex(sympy.Symbol(self.varname))
529
530 def __str__(self):
531 if self.type == DIFFERENTIAL_EQUATION:
532 s = "d" + self.varname + "/dt"
533 else:
534 s = self.varname
535
536 if self.expr is not None:
537 s += " = " + str(self.expr)
538
539 s += " : " + get_unit_for_display(self.dim)
540
541 if len(self.flags):
542 s += " (" + ", ".join(self.flags) + ")"
543
544 return s
545
546 def __repr__(self):
547 s = "<" + self.type + " " + self.varname
548
549 if self.expr is not None:
550 s += ": " + self.expr.code
551
552 s += " (Unit: " + get_unit_for_display(self.dim)
553
554 if len(self.flags):
555 s += ", flags: " + ", ".join(self.flags)
556
557 s += ")>"
558 return s
559
560 def _repr_pretty_(self, p, cycle):
561 """
562 Pretty printing for ipython.
563 """
564 if cycle:
565 # should never happen
566 raise AssertionError("Cyclical call of SingleEquation._repr_pretty")
567
568 if self.type == DIFFERENTIAL_EQUATION:
569 p.text("d" + self.varname + "/dt")
570 else:
571 p.text(self.varname)
572
573 if self.expr is not None:
574 p.text(" = ")
575 p.pretty(self.expr)
576
577 p.text(" : ")
578 p.pretty(get_unit(self.dim))
579
580 if len(self.flags):
581 p.text(" (" + ", ".join(self.flags) + ")")
582
583 def _repr_latex_(self):
584 return "$" + sympy.latex(self) + "$"
585
586
587 class Equations(Hashable, Mapping):
588 """
589 Container that stores equations from which models can be created.
590
591 String equations can be of any of the following forms:
592
593 1. ``dx/dt = f : unit (flags)`` (differential equation)
594 2. ``x = f : unit (flags)`` (equation)
595 3. ``x : unit (flags)`` (parameter)
596
597 String equations can span several lines and contain Python-style comments
598 starting with ``#``
599
600 Parameters
601 ----------
602 eqs : `str` or list of `SingleEquation` objects
603 A multiline string of equations (see above) -- for internal purposes
604 also a list of `SingleEquation` objects can be given. This is done for
605 example when adding new equations to implement the refractory
606 mechanism. Note that in this case the variable names are not checked
607 to allow for "internal names", starting with an underscore.
608 kwds: keyword arguments
609 Keyword arguments can be used to replace variables in the equation
610 string. Arguments have to be of the form ``varname=replacement``, where
611 `varname` has to correspond to a variable name in the given equation.
612 The replacement can be either a string (replacing a name with a new
613 name, e.g. ``tau='tau_e'``) or a value (replacing the variable name
614 with the value, e.g. ``tau=tau_e`` or ``tau=10*ms``).
615 """
616
617 def __init__(self, eqns, **kwds):
618 if isinstance(eqns, str):
619 self._equations = parse_string_equations(eqns)
620 # Do a basic check for the identifiers
621 self.check_identifiers()
622 else:
623 self._equations = {}
624 for eq in eqns:
625 if not isinstance(eq, SingleEquation):
626 raise TypeError(
627 "The list should only contain "
628 f"SingleEquation objects, not {type(eq)}"
629 )
630 if eq.varname in self._equations:
631 raise EquationError(
632 f"Duplicate definition of variable '{eq.varname}'"
633 )
634 self._equations[eq.varname] = eq
635
636 self._equations = self._substitute(kwds)
637
638 # Check for special symbol xi (stochastic term)
639 uses_xi = None
640 for eq in self._equations.values():
641 if eq.expr is not None and "xi" in eq.expr.identifiers:
642 if not eq.type == DIFFERENTIAL_EQUATION:
643 raise EquationError(
644 f"The equation defining '{eq.varname}' "
645 "contains the symbol 'xi' but is not a "
646 "differential equation."
647 )
648 elif uses_xi is not None:
649 raise EquationError(
650 f"The equation defining {eq.varname} contains "
651 "the symbol 'xi', but it is already used "
652 f"in the equation defining {uses_xi}. Rename "
653 "the variables to 'xi_...' to make "
654 "clear whether they are the same or "
655 "independent random variables. Using "
656 "the same name twice will lead to "
657 "identical noise realizations "
658 "whereas using different names will "
659 "lead to independent noise "
660 "realizations."
661 )
662 else:
663 uses_xi = eq.varname
664
665 # rearrange subexpressions
666 self._sort_subexpressions()
667
668 #: Cache for equations with the subexpressions substituted
669 self._substituted_expressions = None
670
671 def _substitute(self, replacements):
672 if len(replacements) == 0:
673 return self._equations
674
675 new_equations = {}
676 for eq in self.values():
677 # Replace the name of a model variable (works only for strings)
678 if eq.varname in replacements:
679 new_varname = replacements[eq.varname]
680 if not isinstance(new_varname, str):
681 raise ValueError(
682 f"Cannot replace model variable '{eq.varname}' with a value."
683 )
684 if new_varname in self or new_varname in new_equations:
685 raise EquationError(
686 f"Cannot replace model variable '{eq.varname}' "
687 f"with '{new_varname}', duplicate definition "
688 f"of '{new_varname}'."
689 )
690 # make sure that the replacement is a valid identifier
691 Equations.check_identifier(new_varname)
692 else:
693 new_varname = eq.varname
694
695 if eq.type in [SUBEXPRESSION, DIFFERENTIAL_EQUATION]:
696 # Replace values in the RHS of the equation
697 new_code = eq.expr.code
698 for to_replace, replacement in replacements.items():
699 if to_replace in eq.identifiers:
700 if isinstance(replacement, str):
701 # replace the name with another name
702 new_code = re.sub(
703 "\\b" + to_replace + "\\b", replacement, new_code
704 )
705 else:
706 # replace the name with a value
707 new_code = re.sub(
708 "\\b" + to_replace + "\\b",
709 "(" + repr(replacement) + ")",
710 new_code,
711 )
712 try:
713 Expression(new_code)
714 except ValueError as ex:
715 raise ValueError(
716 f"Replacing '{to_replace}' with '{replacement!r} failed."
717 ) from ex
718 new_equations[new_varname] = SingleEquation(
719 eq.type,
720 new_varname,
721 dimensions=eq.dim,
722 var_type=eq.var_type,
723 expr=Expression(new_code),
724 flags=eq.flags,
725 )
726 else:
727 new_equations[new_varname] = SingleEquation(
728 eq.type,
729 new_varname,
730 dimensions=eq.dim,
731 var_type=eq.var_type,
732 flags=eq.flags,
733 )
734
735 return new_equations
736
737 def substitute(self, **kwds):
738 return Equations(list(self._substitute(kwds).values()))
739
740 def __iter__(self):
741 return iter(self._equations)
742
743 def __len__(self):
744 return len(self._equations)
745
746 def __getitem__(self, key):
747 return self._equations[key]
748
749 def __add__(self, other_eqns):
750 if isinstance(other_eqns, str):
751 other_eqns = parse_string_equations(other_eqns)
752 elif not isinstance(other_eqns, Equations):
753 return NotImplemented
754
755 return Equations(list(self.values()) + list(other_eqns.values()))
756
757 def __hash__(self):
758 return hash(frozenset(self._equations.items()))
759
760 #: A set of functions that are used to check identifiers (class attribute).
761 #: Functions can be registered with the static method
762 #: `Equations.register_identifier_check` and will be automatically
763 #: used when checking identifiers
764 identifier_checks = {
765 check_identifier_basic,
766 check_identifier_reserved,
767 check_identifier_functions,
768 check_identifier_constants,
769 check_identifier_units,
770 }
771
772 @staticmethod
773 def register_identifier_check(func):
774 """
775 Register a function for checking identifiers.
776
777 Parameters
778 ----------
779 func : callable
780 The function has to receive a single argument, the name of the
781 identifier to check, and raise a ValueError if the identifier
782 violates any rule.
783
784 """
785 if not callable(func):
786 raise ValueError("Can only register callables.")
787
788 Equations.identifier_checks.add(func)
789
790 @staticmethod
791 def check_identifier(identifier):
792 """
793 Perform all the registered checks. Checks can be registered via
794 `Equations.register_identifier_check`.
795
796 Parameters
797 ----------
798 identifier : str
799 The identifier that should be checked
800
801 Raises
802 ------
803 ValueError
804 If any of the registered checks fails.
805 """
806 for check_func in Equations.identifier_checks:
807 check_func(identifier)
808
809 def check_identifiers(self):
810 """
811 Check all identifiers for conformity with the rules.
812
813 Raises
814 ------
815 ValueError
816 If an identifier does not conform to the rules.
817
818 See also
819 --------
820 Equations.check_identifier : The function that is called for each identifier.
821 """
822 for name in self.names:
823 Equations.check_identifier(name)
824
825 def get_substituted_expressions(self, variables=None, include_subexpressions=False):
826 """
827 Return a list of ``(varname, expr)`` tuples, containing all
828 differential equations (and optionally subexpressions) with all the
829 subexpression variables substituted with the respective expressions.
830
831 Parameters
832 ----------
833 variables : dict, optional
834 A mapping of variable names to `Variable`/`Function` objects.
835 include_subexpressions : bool
836 Whether also to return substituted subexpressions. Defaults to
837 ``False``.
838
839 Returns
840 -------
841 expr_tuples : list of (str, `CodeString`)
842 A list of ``(varname, expr)`` tuples, where ``expr`` is a
843 `CodeString` object with all subexpression variables substituted
844 with the respective expression.
845 """
846 if self._substituted_expressions is None:
847 self._substituted_expressions = []
848 substitutions = {}
849 for eq in self.ordered:
850 # Skip parameters
851 if eq.expr is None:
852 continue
853
854 new_sympy_expr = str_to_sympy(eq.expr.code, variables).xreplace(
855 substitutions
856 )
857 new_str_expr = sympy_to_str(new_sympy_expr)
858 expr = Expression(new_str_expr)
859
860 if eq.type == SUBEXPRESSION:
861 if eq.var_type == INTEGER:
862 sympy_var = sympy.Symbol(eq.varname, integer=True)
863 else:
864 sympy_var = sympy.Symbol(eq.varname, real=True)
865 substitutions.update(
866 {sympy_var: str_to_sympy(expr.code, variables)}
867 )
868 self._substituted_expressions.append((eq.varname, expr))
869 elif eq.type == DIFFERENTIAL_EQUATION:
870 # a differential equation that we have to check
871 self._substituted_expressions.append((eq.varname, expr))
872 else:
873 raise AssertionError(f"Unknown equation type {eq.type}")
874
875 if include_subexpressions:
876 return self._substituted_expressions
877 else:
878 return [
879 (name, expr)
880 for name, expr in self._substituted_expressions
881 if self[name].type == DIFFERENTIAL_EQUATION
882 ]
883
884 def _get_stochastic_type(self):
885 """
886 Returns the type of stochastic differential equations (additivive or
887 multiplicative). The system is only classified as ``additive`` if *all*
888 equations have only additive noise (or no noise).
889
890 Returns
891 -------
892 type : str
893 Either ``None`` (no noise variables), ``'additive'`` (factors for
894 all noise variables are independent of other state variables or
895 time), ``'multiplicative'`` (at least one of the noise factors
896 depends on other state variables and/or time).
897 """
898
899 if not self.is_stochastic:
900 return None
901
902 for _, expr in self.get_substituted_expressions():
903 _, stochastic = expr.split_stochastic()
904 if stochastic is not None:
905 for factor in stochastic.values():
906 if "t" in factor.identifiers:
907 # noise factor depends on time
908 return "multiplicative"
909
910 for identifier in factor.identifiers:
911 if identifier in self.diff_eq_names:
912 # factor depends on another state variable
913 return "multiplicative"
914
915 return "additive"
916
917 ############################################################################
918 # Properties
919 ############################################################################
920
921 # Lists of equations or (variable, expression tuples)
922 ordered = property(
923 lambda self: sorted(
924 self._equations.values(), key=lambda key: (key.update_order, key.varname)
925 ),
926 doc=(
927 "A list of all equations, sorted "
928 "according to the order in which they should "
929 "be updated"
930 ),
931 )
932
933 diff_eq_expressions = property(
934 lambda self: [
935 (varname, eq.expr)
936 for varname, eq in self.items()
937 if eq.type == DIFFERENTIAL_EQUATION
938 ],
939 doc=(
940 "A list of (variable name, expression) "
941 "tuples of all differential equations."
942 ),
943 )
944
945 eq_expressions = property(
946 lambda self: [
947 (varname, eq.expr)
948 for varname, eq in self.items()
949 if eq.type in (SUBEXPRESSION, DIFFERENTIAL_EQUATION)
950 ],
951 doc="A list of (variable name, expression) tuples of all equations.",
952 )
953
954 # Sets of names
955
956 names = property(
957 lambda self: {eq.varname for eq in self.ordered},
958 doc="All variable names defined in the equations.",
959 )
960
961 diff_eq_names = property(
962 lambda self: {
963 eq.varname for eq in self.ordered if eq.type == DIFFERENTIAL_EQUATION
964 },
965 doc="All differential equation names.",
966 )
967
968 subexpr_names = property(
969 lambda self: {eq.varname for eq in self.ordered if eq.type == SUBEXPRESSION},
970 doc="All subexpression names.",
971 )
972
973 eq_names = property(
974 lambda self: {
975 eq.varname
976 for eq in self.ordered
977 if eq.type in (DIFFERENTIAL_EQUATION, SUBEXPRESSION)
978 },
979 doc="All equation names (including subexpressions).",
980 )
981
982 parameter_names = property(
983 lambda self: {eq.varname for eq in self.ordered if eq.type == PARAMETER},
984 doc="All parameter names.",
985 )
986
987 dimensions = property(
988 lambda self: {var: eq.dim for var, eq in self._equations.items()},
989 doc=(
990 "Dictionary of all internal variables and their "
991 "corresponding physical dimensions."
992 ),
993 )
994
995 identifiers = property(
996 lambda self: set().union(*[eq.identifiers for eq in self._equations.values()])
997 - self.names,
998 doc=(
999 "Set of all identifiers used in the equations, "
1000 "excluding the variables defined in the equations"
1001 ),
1002 )
1003
1004 stochastic_variables = property(
1005 lambda self: {
1006 variable
1007 for variable in self.identifiers
1008 if variable == "xi" or variable.startswith("xi_")
1009 }
1010 )
1011
1012 # general properties
1013 is_stochastic = property(
1014 lambda self: len(self.stochastic_variables) > 0,
1015 doc="Whether the equations are stochastic.",
1016 )
1017
1018 stochastic_type = property(fget=_get_stochastic_type)
1019
1020 def _sort_subexpressions(self):
1021 """
1022 Sorts the subexpressions in a way that resolves their dependencies
1023 upon each other. After this method has been run, the subexpressions
1024 returned by the ``ordered`` property are in the order in which
1025 they should be updated
1026 """
1027
1028 # Get a dictionary of all the dependencies on other subexpressions,
1029 # i.e. ignore dependencies on parameters and differential equations
1030 static_deps = {}
1031 for eq in self._equations.values():
1032 if eq.type == SUBEXPRESSION:
1033 static_deps[eq.varname] = [
1034 dep
1035 for dep in eq.identifiers
1036 if dep in self._equations
1037 and self._equations[dep].type == SUBEXPRESSION
1038 ]
1039
1040 try:
1041 sorted_eqs = topsort(static_deps)
1042 except ValueError:
1043 raise ValueError(
1044 "Cannot resolve dependencies between static "
1045 "equations, dependencies contain a cycle."
1046 ) from None
1047
1048 # put the equations objects in the correct order
1049 for order, static_variable in enumerate(sorted_eqs):
1050 self._equations[static_variable].update_order = order
1051
1052 # Sort differential equations and parameters after subexpressions
1053 for eq in self._equations.values():
1054 if eq.type == DIFFERENTIAL_EQUATION:
1055 eq.update_order = len(sorted_eqs)
1056 elif eq.type == PARAMETER:
1057 eq.update_order = len(sorted_eqs) + 1
1058
1059 @property
1060 def dependencies(self):
1061 """
1062 Calculate the dependencies of all differential equations and
1063 subexpressions.
1064 """
1065 # Create a dictionary mapping differential equations and
1066 # subexpressions to a list of their dependencies within the equations
1067 # (ignoring external constants, unit names, etc.)
1068 # Note that a differential equation such as "dv/dt = -v / tau" does not
1069 # mean that the variable "v" depends on itself. To make the distinction between
1070 # a variable and its derivative, we use the variable name + the prime symbol
1071 # in this dictionary.
1072 # As an example, the equations:
1073 # dv/dt = I_m / C_m : volt
1074 # I_m = I_ext + I_pas : amp
1075 # I_ext = 1*nA + sin(2*pi*100*Hz*t)*nA : amp
1076 # I_pas = g_L*(E_L - v) : amp
1077 # would be translated into the following dictionary
1078 # {"v" : [],
1079 # "v'": ["I_m"]
1080 # "I_m": ["I_ext", "I_pas"],
1081 # "I_ext": [],
1082 # "I_pas": ["v"] }
1083 deps = {}
1084 for eq in self._equations.values():
1085 if eq.type == SUBEXPRESSION:
1086 name = eq.varname
1087 elif eq.type == DIFFERENTIAL_EQUATION:
1088 name = eq.varname + "'"
1089 deps[eq.varname] = []
1090 else:
1091 continue
1092 deps[name] = [
1093 dep
1094 for dep in eq.identifiers
1095 if dep in self._equations and self._equations[dep].type != PARAMETER
1096 ]
1097 try:
1098 sorted_eqs = topsort(deps)
1099 except ValueError:
1100 raise ValueError(
1101 "Cannot resolve dependencies between static "
1102 "equations, dependencies contain a cycle."
1103 ) from None
1104 # Remove the dummy entries for differential equations and rename
1105 # x' → x
1106 sorted_eqs = [
1107 x.replace("'", "") for x in sorted_eqs if x not in self.diff_eq_names
1108 ]
1109 # Now recursively fill in the dependencies – this only needs a single
1110 # pass due to the previous sorting
1111 deps = {}
1112 Dependency = namedtuple(
1113 "Dependency", ["equation", "via"], defaults=((),)
1114 ) # default for via is empty tuple
1115 for eq in sorted_eqs:
1116 dep_names = {
1117 dep for dep in self._equations[eq].identifiers if dep in self._equations
1118 }
1119 deps[eq] = [Dependency(equation=self._equations[dep]) for dep in dep_names]
1120 # add all indirect dependencies
1121 for dep in dep_names:
1122 for indirect_dep in deps.get(dep, []):
1123 if indirect_dep.equation.varname == dep:
1124 continue # do not go into recursion if a variable depends on itself
1125 if any(
1126 indirect_dep.equation.varname == existing_dep.equation.varname
1127 for existing_dep in deps[eq]
1128 ):
1129 continue # Do not add indirect dependencies for things we also depend on directly
1130 deps[eq].append(
1131 Dependency(
1132 equation=indirect_dep.equation,
1133 via=(dep,) + indirect_dep.via,
1134 )
1135 )
1136 return deps
1137
1138 def check_units(self, group, run_namespace):
1139 """
1140 Check all the units for consistency.
1141
1142 Parameters
1143 ----------
1144 group : `Group`
1145 The group providing the context
1146 run_namespace : dict-like, optional
1147 An additional namespace that is used for variable lookup (if not
1148 defined, the implicit namespace of local variables is used).
1149 level : int, optional
1150 How much further to go up in the stack to find the calling frame
1151
1152 Raises
1153 ------
1154 DimensionMismatchError
1155 In case of any inconsistencies.
1156 """
1157 all_variables = dict(group.variables)
1158 external = frozenset().union(
1159 *[expr.identifiers for _, expr in self.eq_expressions]
1160 )
1161 external -= set(all_variables.keys())
1162
1163 resolved_namespace = group.resolve_all(
1164 external, run_namespace, user_identifiers=external
1165 ) # all variables are user defined
1166
1167 all_variables.update(resolved_namespace)
1168 for var, eq in self._equations.items():
1169 if eq.type == PARAMETER:
1170 # no need to check units for parameters
1171 continue
1172
1173 if eq.type == DIFFERENTIAL_EQUATION:
1174 try:
1175 check_dimensions(
1176 str(eq.expr), self.dimensions[var] / second.dim, all_variables
1177 )
1178 except DimensionMismatchError as ex:
1179 raise DimensionMismatchError(
1180 "Inconsistent units in "
1181 "differential equation "
1182 f"defining variable '{eq.varname}':"
1183 f"\n{ex.desc}",
1184 *ex.dims,
1185 ) from ex
1186 elif eq.type == SUBEXPRESSION:
1187 try:
1188 check_dimensions(str(eq.expr), self.dimensions[var], all_variables)
1189 except DimensionMismatchError as ex:
1190 raise DimensionMismatchError(
1191 "Inconsistent units in "
1192 f"subexpression {eq.varname}:"
1193 f"\n%{ex.desc}",
1194 *ex.dims,
1195 ) from ex
1196 else:
1197 raise AssertionError(f"Unknown equation type: '{eq.type}'")
1198
1199 def check_flags(self, allowed_flags, incompatible_flags=None):
1200 """
1201 Check the list of flags.
1202
1203 Parameters
1204 ----------
1205 allowed_flags : dict
1206 A dictionary mapping equation types (PARAMETER,
1207 DIFFERENTIAL_EQUATION, SUBEXPRESSION) to a list of strings (the
1208 allowed flags for that equation type)
1209 incompatible_flags : list of tuple
1210 A list of flag combinations that are not allowed for the same
1211 equation.
1212 Notes
1213 -----
1214 Not specifying allowed flags for an equation type is the same as
1215 specifying an empty list for it.
1216
1217 Raises
1218 ------
1219 ValueError
1220 If any flags are used that are not allowed.
1221 """
1222 if incompatible_flags is None:
1223 incompatible_flags = []
1224
1225 for eq in self.values():
1226 for flag in eq.flags:
1227 if eq.type not in allowed_flags or len(allowed_flags[eq.type]) == 0:
1228 raise ValueError(
1229 f"Equations of type '{eq.type}' cannot have any flags."
1230 )
1231 if flag not in allowed_flags[eq.type]:
1232 raise ValueError(
1233 f"Equations of type '{eq.type}' cannot have a "
1234 f"flag '{flag}', only the following flags "
1235 f"are allowed: {allowed_flags[eq.type]}"
1236 )
1237 # Check for incompatibilities
1238 for flag_combinations in incompatible_flags:
1239 if flag in flag_combinations:
1240 remaining_flags = set(flag_combinations) - {flag}
1241 for remaining_flag in remaining_flags:
1242 if remaining_flag in eq.flags:
1243 raise ValueError(
1244 f"Flag '{flag}' cannot be "
1245 "combined with flag "
1246 f"'{remaining_flag}'"
1247 )
1248
1249 ############################################################################
1250 # Representation
1251 ############################################################################
1252
1253 def __str__(self):
1254 strings = [str(eq) for eq in self.ordered]
1255 return "\n".join(strings)
1256
1257 def __repr__(self):
1258 return f"<Equations object consisting of {len(self._equations)} equations>"
1259
1260 def _latex(self, *args):
1261 equations = []
1262 for eq in self._equations.values():
1263 # do not use SingleEquations._latex here as we want nice alignment
1264 varname = sympy.Symbol(eq.varname)
1265 if eq.type == DIFFERENTIAL_EQUATION:
1266 lhs = r"\frac{\mathrm{d}" + sympy.latex(varname) + r"}{\mathrm{d}t}"
1267 else:
1268 # Normal equation or parameter
1269 lhs = varname
1270 if not eq.type == PARAMETER:
1271 rhs = str_to_sympy(eq.expr.code)
1272 if len(eq.flags):
1273 flag_str = ", flags: " + ", ".join(eq.flags)
1274 else:
1275 flag_str = ""
1276 if eq.type == PARAMETER:
1277 eq_latex = rf"{sympy.latex(lhs)} &&& \text{{(unit: ${sympy.latex(get_unit(eq.dim))}${flag_str})}}"
1278 else:
1279 eq_latex = r"{} &= {} && \text{{(unit of ${}$: ${}${})}}".format(
1280 lhs, # already a string
1281 sympy.latex(rhs),
1282 sympy.latex(varname),
1283 sympy.latex(get_unit(eq.dim)),
1284 flag_str,
1285 )
1286 equations.append(eq_latex)
1287 return r"\begin{align*}" + (r"\\" + "\n").join(equations) + r"\end{align*}"
1288
1289 def _repr_latex_(self):
1290 return sympy.latex(self)
1291
1292 def _repr_pretty_(self, p, cycle):
1293 """Pretty printing for ipython"""
1294 if cycle:
1295 # Should never happen
1296 raise AssertionError("Cyclical call of 'Equations._repr_pretty_'")
1297 for eq in self._equations.values():
1298 p.pretty(eq)
1299 p.breakable("\n")
1300
1301
1302 def is_stateful(expression, variables):
1303 """
1304 Whether the given expression refers to stateful functions (and is therefore
1305 not guaranteed to give the same result if called repetively).
1306
1307 Parameters
1308 ----------
1309 expression : `sympy.Expression`
1310 The sympy expression to check.
1311 variables : dict
1312 The dictionary mapping variable names to `Variable` or `Function`
1313 objects.
1314
1315 Returns
1316 -------
1317 stateful : bool
1318 ``True``, if the given expression refers to a stateful function like
1319 ``rand()`` and ``False`` otherwise.
1320 """
1321 func_name = str(expression.func)
1322 func_variable = variables.get(func_name, None)
1323 if func_variable is not None and not func_variable.stateless:
1324 return True
1325 for arg in expression.args:
1326 if is_stateful(arg, variables):
1327 return True
1328 return False
1329
1330
1331 def check_subexpressions(group, equations, run_namespace):
1332 """
1333 Checks the subexpressions in the equations and raises an error if a
1334 subexpression refers to stateful functions without being marked as
1335 "constant over dt".
1336
1337 Parameters
1338 ----------
1339 group : `Group`
1340 The group providing the context.
1341 equations : `Equations`
1342 The equations to check.
1343 run_namespace : dict
1344 The run namespace for resolving variables.
1345
1346 Raises
1347 ------
1348 SyntaxError
1349 For subexpressions not marked as "constant over dt" that refer to
1350 stateful functions.
1351 """
1352 for eq in equations.ordered:
1353 if eq.type == SUBEXPRESSION:
1354 # Check whether the expression is stateful (most commonly by
1355 # referring to rand() or randn()
1356 variables = group.resolve_all(
1357 eq.identifiers,
1358 run_namespace,
1359 # we don't need to raise any warnings
1360 # for the user here, warnings will
1361 # be raised in create_runner_codeobj
1362 user_identifiers=set(),
1363 )
1364 expression = str_to_sympy(eq.expr.code, variables=variables)
1365
1366 # Check whether the expression refers to stateful functions
1367 if is_stateful(expression, variables):
1368 raise SyntaxError(
1369 f"The subexpression '{eq.varname}' refers to a "
1370 "stateful function (e.g. rand()). Such "
1371 "expressions should only be evaluated "
1372 "once per timestep, add the 'constant "
1373 "over dt' flag."
1374 )
1375
1376
1377 def extract_constant_subexpressions(eqs):
1378 without_const_subexpressions = []
1379 const_subexpressions = []
1380 for eq in eqs.ordered:
1381 if eq.type == SUBEXPRESSION and "constant over dt" in eq.flags:
1382 flags = set(eq.flags) - {"constant over dt"}
1383 without_const_subexpressions.append(
1384 SingleEquation(
1385 PARAMETER, eq.varname, eq.dim, var_type=eq.var_type, flags=flags
1386 )
1387 )
1388 const_subexpressions.append(eq)
1389 else:
1390 without_const_subexpressions.append(eq)
1391
1392 return (Equations(without_const_subexpressions), Equations(const_subexpressions))