Debian Codegraph @

brian2/parsing/sympytools.py

raw
1 """
2 Utility functions for parsing expressions and statements.
3 """
4
5 import re
6 from collections import Counter
7
8 import sympy
9 from sympy.printing.precedence import precedence
10 from sympy.printing.str import StrPrinter
11
12 from brian2.core.functions import DEFAULT_CONSTANTS, DEFAULT_FUNCTIONS, Function
13 from brian2.parsing.rendering import SympyNodeRenderer
14 from brian2.utils.caching import cached
15
16
17 def check_expression_for_multiple_stateful_functions(expr, variables):
18 identifiers = re.findall(r"\w+", expr)
19 # Don't bother counting if we don't have any duplicates in the first place
20 if len(identifiers) == len(set(identifiers)):
21 return
22 identifier_count = Counter(identifiers)
23 for identifier, count in identifier_count.items():
24 var = variables.get(identifier, None)
25 if count > 1 and isinstance(var, Function) and not var.stateless:
26 raise NotImplementedError(
27 f"The expression '{expr}' contains "
28 f"more than one call of {identifier}. This "
29 "is currently not supported since "
30 f"{identifier} is a stateful function and "
31 "its multiple calls might be "
32 "treated incorrectly (e.g."
33 "'rand() - rand()' could be "
34 " simplified to "
35 "'0.0')."
36 )
37
38
39 def str_to_sympy(expr, variables=None):
40 """
41 Parses a string into a sympy expression. There are two reasons for not
42 using `sympify` directly: 1) sympify does a ``from sympy import *``,
43 adding all functions to its namespace. This leads to issues when trying to
44 use sympy function names as variable names. For example, both ``beta`` and
45 ``factor`` -- quite reasonable names for variables -- are sympy functions,
46 using them as variables would lead to a parsing error. 2) We want to use
47 a common syntax across expressions and statements, e.g. we want to allow
48 to use `and` (instead of `&`) and function names like `ceil` (instead of
49 `ceiling`).
50
51 Parameters
52 ----------
53 expr : str
54 The string expression to parse.
55 variables : dict, optional
56 Dictionary mapping variable/function names in the expr to their
57 respective `Variable`/`Function` objects.
58
59 Returns
60 -------
61 s_expr
62 A sympy expression
63
64 Raises
65 ------
66 SyntaxError
67 In case of any problems during parsing.
68 """
69 if variables is None:
70 variables = {}
71 check_expression_for_multiple_stateful_functions(expr, variables)
72
73 # We do the actual transformation in a separate function that is cached
74 # If we cached `str_to_sympy` itself, it would also use the contents of the
75 # variables dictionary as the cache key, while it is only used for the check
76 # above and does not affect the translation to sympy
77 return _str_to_sympy(expr)
78
79
80 @cached
81 def _str_to_sympy(expr):
82 try:
83 s_expr = SympyNodeRenderer().render_expr(expr)
84 except (TypeError, ValueError, NameError) as ex:
85 raise SyntaxError(
86 f"Error during evaluation of sympy expression '{expr}'"
87 ) from ex
88
89 return s_expr
90
91
92 class CustomSympyPrinter(StrPrinter):
93 """
94 Printer that overrides the printing of some basic sympy objects. E.g.
95 print "a and b" instead of "And(a, b)".
96 """
97
98 def _print_And(self, expr):
99 return " and ".join([f"({self.doprint(arg)})" for arg in expr.args])
100
101 def _print_Or(self, expr):
102 return " or ".join([f"({self.doprint(arg)})" for arg in expr.args])
103
104 def _print_Not(self, expr):
105 if len(expr.args) != 1:
106 raise AssertionError(f'"Not" with {len(expr.args)} arguments?')
107 return f"not ({self.doprint(expr.args[0])})"
108
109 def _print_Relational(self, expr):
110 return (
111 f"{self.parenthesize(expr.lhs, precedence(expr))} "
112 f"{self._relationals.get(expr.rel_op) or expr.rel_op} "
113 f"{self.parenthesize(expr.rhs, precedence(expr))}"
114 )
115
116 def _print_Function(self, expr):
117 # Special workaround for the int function
118 if expr.func.__name__ == "int_":
119 return f"int({self.stringify(expr.args, ', ')})"
120 elif expr.func.__name__ == "Mod":
121 return f"(({self.doprint(expr.args[0])})%({self.doprint(expr.args[1])}))"
122 else:
123 return f"{expr.func.__name__}({self.stringify(expr.args, ', ')})"
124
125
126 PRINTER = CustomSympyPrinter()
127
128
129 @cached
130 def sympy_to_str(sympy_expr):
131 """
132 sympy_to_str(sympy_expr)
133
134 Converts a sympy expression into a string. This could be as easy as
135 ``str(sympy_exp)`` but it is possible that the sympy expression contains
136 functions like ``Abs`` (for example, if an expression such as
137 ``sqrt(x**2)`` appeared somewhere). We do want to re-translate ``Abs`` into
138 ``abs`` in this case.
139
140 Parameters
141 ----------
142 sympy_expr : sympy.core.expr.Expr
143 The expression that should be converted to a string.
144
145 Returns
146 str_expr : str
147 A string representing the sympy expression.
148 """
149 # replace the standard functions by our names if necessary
150 replacements = {
151 f.sympy_func: sympy.Function(name)
152 for name, f in DEFAULT_FUNCTIONS.items()
153 if f.sympy_func is not None
154 and isinstance(f.sympy_func, sympy.FunctionClass)
155 and str(f.sympy_func) != name
156 }
157 # replace constants with our names as well
158 replacements.update(
159 {
160 c.sympy_obj: sympy.Symbol(name)
161 for name, c in DEFAULT_CONSTANTS.items()
162 if str(c.sympy_obj) != name
163 }
164 )
165
166 # Replace the placeholder argument by an empty symbol
167 replacements[sympy.Symbol("_placeholder_arg")] = sympy.Symbol("")
168 atoms = sympy_expr.atoms() | {f.func for f in sympy_expr.atoms(sympy.Function)}
169 for old, new in replacements.items():
170 if old in atoms:
171 sympy_expr = sympy_expr.subs(old, new)
172 expr = PRINTER.doprint(sympy_expr)
173
174 return expr
175
176
177 def expression_complexity(expr, complexity=None):
178 """
179 Returns the complexity of an expression (either string or sympy)
180
181 The complexity is defined as 1 for each arithmetic operation except divide which is 2,
182 and all other operations are 20. This can be overridden using the complexity
183 argument.
184
185 Note: calling this on a statement rather than an expression is likely to lead to errors.
186
187 Parameters
188 ----------
189 expr: `sympy.Expr` or str
190 The expression.
191 complexity: None or dict (optional)
192 A dictionary mapping expression names to their complexity, to overwrite default behaviour.
193
194 Returns
195 -------
196 complexity: int
197 The complexity of the expression.
198 """
199 if isinstance(expr, str):
200 # we do this because sympy.count_ops doesn't handle inequalities (TODO: handle sympy as well str)
201 for op in ["<=", ">=", "==", "<", ">"]:
202 expr = expr.replace(op, "+")
203 # work around bug with rand() and randn() (TODO: improve this)
204 expr = expr.replace("rand()", "rand(0)")
205 expr = expr.replace("randn()", "randn(0)")
206 subs = {"ADD": 1, "DIV": 2, "MUL": 1, "SUB": 1}
207 if complexity is not None:
208 subs.update(complexity)
209 ops = sympy.count_ops(expr, visual=True)
210 for atom in ops.atoms():
211 if hasattr(atom, "name"):
212 subs[atom.name] = 20 # unknown operations assumed to have a large cost
213 return ops.evalf(subs=subs)