Debian Codegraph @

brian2/tests/test_parsing.py

raw
1 """
2 Tests the brian2.parsing package
3 """
4
5 from collections import namedtuple
6
7 import numpy as np
8 import pytest
9
10 from brian2 import Function
11 from brian2.codegen.generators.cpp_generator import CPPCodeGenerator
12 from brian2.core.functions import DEFAULT_FUNCTIONS
13 from brian2.core.preferences import prefs
14 from brian2.core.variables import Constant
15 from brian2.groups.group import Group
16 from brian2.parsing.dependencies import abstract_code_dependencies
17 from brian2.parsing.expressions import (
18 _get_value_from_expression,
19 is_boolean_expression,
20 parse_expression_dimensions,
21 )
22 from brian2.parsing.functions import (
23 abstract_code_from_function,
24 extract_abstract_code_functions,
25 substitute_abstract_code_functions,
26 )
27 from brian2.parsing.rendering import CPPNodeRenderer, NodeRenderer, NumpyNodeRenderer
28 from brian2.parsing.sympytools import str_to_sympy, sympy_to_str
29 from brian2.tests.utils import assert_allclose
30 from brian2.units import (
31 DimensionMismatchError,
32 Unit,
33 amp,
34 get_unit,
35 have_same_dimensions,
36 volt,
37 )
38 from brian2.units.fundamentalunits import DIMENSIONLESS, Dimension
39 from brian2.utils.logger import std_silent
40 from brian2.utils.stringtools import deindent, get_identifiers
41
42
43 # a simple Group for testing
44 class SimpleGroup(Group):
45 def __init__(self, variables, namespace=None):
46 self.variables = variables
47 self.namespace = namespace
48
49
50 TEST_EXPRESSIONS = """
51 a+b+c*d-f+g-(b+d)-(a-c)
52 a**b**2
53 a**(b**2)
54 (a**b)**2
55 a*(b+c*(a+b)*(a-(c*d)))
56 a/b/c-a/(b/c)
57 10//n
58 n//10
59 n//m
60 10/n
61 10.0/n
62 n/10
63 n/10.0
64 n/m
65 a<b
66 a<=b
67 a>b
68 a>=b
69 a==b
70 a!=b
71 a+1
72 1+a
73 1+3
74 a>0.5 and b>0.5
75 a>0.5 and b>0.5 or c>0.5
76 a>0.5 and b>0.5 or not c>0.5
77 2%4
78 -1%4
79 2.3%5.6
80 2.3%5
81 -1.2%3.4
82 17e-12
83 42e17
84 """
85
86
87 def parse_expressions(renderer, evaluator, numvalues=10):
88 exprs = [
89 ([m for m in get_identifiers(l) if len(m) == 1], [], l.strip())
90 for l in TEST_EXPRESSIONS.split("\n")
91 if l.strip()
92 ]
93 i, imod = 1, 33
94 for varids, funcids, expr in exprs:
95 pexpr = renderer.render_expr(expr)
96 n = 0
97 for _ in range(numvalues):
98 # assign some random values
99 ns = {}
100 for v in varids:
101 if v in ["n", "m"]: # integer values
102 ns[v] = i
103 else:
104 ns[v] = float(i) / imod
105 i = i % imod + 1
106 r1 = eval(expr.replace("&", " and ").replace("|", " or "), ns)
107 n += 1
108 r2 = evaluator(pexpr, ns)
109 try:
110 # Use all close because we can introduce small numerical
111 # difference through sympy's rearrangements
112 assert_allclose(r1, r2, atol=1e-8)
113 except AssertionError as e:
114 raise AssertionError(
115 f"In expression {str(expr)} translated to {str(pexpr)} {str(e)}"
116 )
117
118
119 def numpy_evaluator(expr, userns):
120 ns = {}
121 # exec 'from numpy import logical_not' in ns
122 ns["logical_not"] = np.logical_not
123 ns.update(**userns)
124 for k in userns:
125 if not k.startswith("_"):
126 ns[k] = np.array([userns[k]])
127 try:
128 x = eval(expr, ns)
129 except Exception as e:
130 raise ValueError(
131 f"Could not evaluate numpy expression {expr} exception {str(e)}"
132 )
133 if isinstance(x, np.ndarray):
134 return x[0]
135 else:
136 return x
137
138
139 @pytest.mark.codegen_independent
140 def test_parse_expressions_python():
141 parse_expressions(NodeRenderer(), eval)
142
143
144 @pytest.mark.codegen_independent
145 def test_parse_expressions_numpy():
146 parse_expressions(NumpyNodeRenderer(), numpy_evaluator)
147
148
149 @pytest.mark.codegen_independent
150 def test_parse_expressions_sympy():
151 # sympy is about symbolic calculation, the string returned by the renderer
152 # contains "Symbol('a')" etc. so we cannot simply evaluate it in a
153 # namespace.
154 # We therefore use a different approach: Convert the expression to a
155 # sympy expression via str_to_sympy (uses the SympyNodeRenderer internally),
156 # then convert it back to a string via sympy_to_str and evaluate it
157
158 class SympyRenderer:
159 def render_expr(self, expr):
160 return str_to_sympy(expr)
161
162 def evaluator(expr, ns):
163 expr = sympy_to_str(expr)
164 ns = dict(ns)
165 # Add the floor function which is used to implement floor division
166 ns["floor"] = DEFAULT_FUNCTIONS["floor"]
167 return eval(expr, ns)
168
169 parse_expressions(SympyRenderer(), evaluator)
170
171
172 @pytest.mark.codegen_independent
173 def test_abstract_code_dependencies():
174 code = """
175 a = b+c
176 d = b+c
177 a = func_a()
178 a = func_b()
179 a = x+d
180 """
181 known_vars = {"a", "b", "c"}
182 known_funcs = {"func_a"}
183 res = abstract_code_dependencies(code, known_vars, known_funcs)
184 expected_res = dict(
185 all=[
186 "a",
187 "b",
188 "c",
189 "d",
190 "x",
191 "func_a",
192 "func_b",
193 ],
194 read=["b", "c", "d", "x"],
195 write=["a", "d"],
196 funcs=["func_a", "func_b"],
197 known_all=["a", "b", "c", "func_a"],
198 known_read=["b", "c"],
199 known_write=["a"],
200 known_funcs=["func_a"],
201 unknown_read=["d", "x"],
202 unknown_write=["d"],
203 unknown_funcs=["func_b"],
204 undefined_read=["x"],
205 newly_defined=["d"],
206 )
207 for k, v in expected_res.items():
208 if not getattr(res, k) == set(v):
209 raise AssertionError(
210 f"For '{k}' result is {getattr(res, k)} expected {set(v)}"
211 )
212
213
214 @pytest.mark.codegen_independent
215 def test_is_boolean_expression():
216 # dummy "Variable" class
217 Var = namedtuple("Var", ["is_boolean"])
218
219 # dummy function object
220 class Func:
221 def __init__(self, returns_bool=False):
222 self._returns_bool = returns_bool
223
224 # variables / functions
225 a = Constant("a", value=True)
226 b = Constant("b", value=False)
227 c = Constant("c", value=5)
228 f = Func(returns_bool=True)
229 g = Func(returns_bool=False)
230 s1 = Var(is_boolean=True)
231 s2 = Var(is_boolean=False)
232
233 variables = {"a": a, "b": b, "c": c, "f": f, "g": g, "s1": s1, "s2": s2}
234
235 EVF = [
236 (True, "a or b"),
237 (False, "c"),
238 (False, "s2"),
239 (False, "g(s1)"),
240 (True, "s2 > c"),
241 (True, "c > 5"),
242 (True, "True"),
243 (True, "a<b"),
244 (True, "not (a>=b)"),
245 (False, "a+b"),
246 (True, "f(c)"),
247 (False, "g(c)"),
248 (
249 True,
250 "f(c) or a<b and s1",
251 ),
252 ]
253 for expect, expr in EVF:
254 ret_val = is_boolean_expression(expr, variables)
255 if expect != ret_val:
256 raise AssertionError(
257 f"is_boolean_expression({expr!r}) returned 'ret_val', "
258 "but was supposed to return 'expect'."
259 )
260 with pytest.raises(SyntaxError):
261 is_boolean_expression("a<b and c", variables)
262 with pytest.raises(SyntaxError):
263 is_boolean_expression("a or foo", variables)
264 with pytest.raises(SyntaxError):
265 is_boolean_expression("ot a", variables) # typo
266 with pytest.raises(SyntaxError):
267 is_boolean_expression("g(c) and f(a)", variables)
268
269
270 @pytest.mark.codegen_independent
271 @pytest.mark.parametrize(
272 "expect,expr",
273 [
274 (volt * amp, "a+b*c"),
275 (DimensionMismatchError, "a+b"),
276 (DimensionMismatchError, "a<b"),
277 (1, "a<b*c"),
278 (1, "a or b"),
279 (1, "not (a >= b*c)"),
280 (DimensionMismatchError, "a or b<c"),
281 (1, "a/(b*c)<1"),
282 (1, "a/(a-a)"),
283 (1, "a<mV*mA"),
284 (volt**2, "b**2"),
285 (volt * amp, "a%(b*c)"),
286 (volt, "-b"),
287 (1, "(a/a)**(a/a)"),
288 # Expressions involving functions
289 (volt, "rand()*b"),
290 (volt**0.5, "sqrt(b)"),
291 (volt, "ceil(b)"),
292 (volt, "sqrt(randn()*b**2)"),
293 (1, "sin(b/b)"),
294 (DimensionMismatchError, "sin(b)"),
295 (DimensionMismatchError, "sqrt(b) + b"),
296 (SyntaxError, "sqrt(b, b)"),
297 (SyntaxError, "sqrt()"),
298 (SyntaxError, "int(1, 2)"),
299 ],
300 )
301 def test_parse_expression_unit(expect, expr):
302 Var = namedtuple("Var", ["dim", "dtype"])
303 variables = {
304 "a": Var(dim=(volt * amp).dim, dtype=np.float64),
305 "b": Var(dim=volt.dim, dtype=np.float64),
306 "c": Var(dim=amp.dim, dtype=np.float64),
307 }
308 group = SimpleGroup(namespace={}, variables=variables)
309 all_variables = {}
310 for name in get_identifiers(expr):
311 if name in variables:
312 all_variables[name] = variables[name]
313 else:
314 all_variables[name] = group._resolve(name, {})
315
316 if isinstance(expect, type) and issubclass(expect, Exception):
317 with pytest.raises(expect):
318 parse_expression_dimensions(expr, all_variables)
319 else:
320 u = parse_expression_dimensions(expr, all_variables)
321 assert have_same_dimensions(u, expect)
322
323
324 @pytest.mark.codegen_independent
325 @pytest.mark.parametrize("expr", ["a**b", "a << b", "int(True"]) # typo
326 def test_parse_expression_unit_wrong_expressions(expr):
327 Var = namedtuple("Var", ["dim", "dtype"])
328 variables = {
329 "a": Var(dim=(volt * amp).dim, dtype=np.float64),
330 "b": Var(dim=volt.dim, dtype=np.float64),
331 "c": Var(dim=amp.dim, dtype=np.float64),
332 }
333 all_variables = {}
334 group = SimpleGroup(namespace={}, variables=variables)
335 for name in get_identifiers(expr):
336 if name in variables:
337 all_variables[name] = variables[name]
338 else:
339 all_variables[name] = group._resolve(name, {})
340 with pytest.raises(SyntaxError):
341 parse_expression_dimensions(expr, all_variables)
342
343
344 @pytest.mark.codegen_independent
345 @pytest.mark.parametrize(
346 "expr,correct",
347 [
348 ("sin(5)", True),
349 ("3 + sin(5)", True),
350 ("d + sin(5)", True),
351 ("3 + sin(d)", True),
352 ("sin(5*mV)", False),
353 ("sin(a)", False),
354 ("3*mV + sin(5)", False),
355 ("b + sin(5)", False),
356 ("sqrt(b**2) + sqrt(7*mV**2)", True),
357 ("sqrt(d) + sqrt(7*mV**2)", False),
358 ("b + clip(3*mV, 0*mV, 5*mV)", True),
359 ("b + clip(3*mV, 0, 5)", False),
360 ("b + foo(7, 3*mV, 9)", True),
361 ("a + foo(7*nA, 3*mV, 9*nA)", True),
362 ("b + foo(7, 3*mV, 9*mV)", False),
363 ("a + foo(7*nA, 3*mV, 9)", False),
364 ],
365 )
366 def test_parse_expression_unit_functions(expr, correct):
367 Var = namedtuple("Var", ["dim", "dtype"])
368
369 def foo(x, y, z):
370 return (x + z) * y
371
372 variables = {
373 "a": Var(dim=(volt * amp).dim, dtype=np.float64),
374 "b": Var(dim=volt.dim, dtype=np.float64),
375 "c": Var(dim=amp.dim, dtype=np.float64),
376 "d": Var(dim=DIMENSIONLESS, dtype=np.float64),
377 "foo": Function(
378 pyfunc=foo,
379 arg_units=[None, volt, "x"],
380 arg_names=["x", "y", "z"],
381 return_unit=lambda x, y, z: x * y,
382 ),
383 }
384 all_variables = {}
385 group = SimpleGroup(namespace={}, variables=variables)
386 for name in get_identifiers(expr):
387 if name in variables:
388 all_variables[name] = variables[name]
389 else:
390 all_variables[name] = group._resolve(name, {})
391 if correct:
392 assert isinstance(parse_expression_dimensions(expr, all_variables), Dimension)
393 else:
394 with pytest.raises(DimensionMismatchError):
395 parse_expression_dimensions(expr, all_variables)
396
397
398 @pytest.mark.codegen_independent
399 def test_value_from_expression():
400 # This function is used to get the value of an exponent, necessary for unit checking
401
402 constants = {"c": 3}
403
404 # dummy class
405 class C:
406 pass
407
408 variables = {"s_constant_scalar": C(), "s_non_constant": C(), "s_non_scalar": C()}
409 variables["s_constant_scalar"].scalar = True
410 variables["s_constant_scalar"].constant = True
411 variables["s_constant_scalar"].get_value = lambda: 2.0
412 variables["s_non_scalar"].constant = True
413 variables["s_non_constant"].scalar = True
414 variables["c"] = Constant("c", value=3)
415
416 expressions = [
417 "1",
418 "-0.5",
419 "c",
420 "2**c",
421 "(c + 3) * 5",
422 "c + s_constant_scalar",
423 "True",
424 "False",
425 ]
426
427 for expr in expressions:
428 eval_expr = expr.replace("s_constant_scalar", "s_constant_scalar.get_value()")
429 assert float(
430 eval(eval_expr, variables, constants)
431 ) == _get_value_from_expression(expr, variables)
432
433 wrong_expressions = ["s_non_constant", "s_non_scalar", "c or True"]
434 for expr in wrong_expressions:
435 with pytest.raises(SyntaxError):
436 _get_value_from_expression(expr, variables)
437
438
439 @pytest.mark.codegen_independent
440 def test_abstract_code_from_function():
441 # test basic functioning
442 def f(x):
443 y = x + 1
444 return y * y
445
446 ac = abstract_code_from_function(f)
447 assert ac.name == "f"
448 assert ac.args == ["x"]
449 assert ac.code.strip() == "y = x + 1"
450 assert ac.return_expr == "y * y"
451 # Check that unsupported features raise an error
452
453 def f(x):
454 return x[:]
455
456 with pytest.raises(SyntaxError):
457 abstract_code_from_function(f)
458
459 def f(x, **kwarg):
460 return x
461
462 with pytest.raises(SyntaxError):
463 abstract_code_from_function(f)
464
465 def f(x, *args):
466 return x
467
468 with pytest.raises(SyntaxError):
469 abstract_code_from_function(f)
470
471
472 @pytest.mark.codegen_independent
473 def test_extract_abstract_code_functions():
474 code = """
475 def f(x):
476 return x*x
477
478 def g(V):
479 V += 1
480
481 irrelevant_code_here()
482 """
483 funcs = extract_abstract_code_functions(code)
484 assert funcs["f"].return_expr == "x * x"
485 assert funcs["g"].args == ["V"]
486
487
488 @pytest.mark.codegen_independent
489 def test_substitute_abstract_code_functions():
490 def f(x):
491 y = x * x
492 return y
493
494 def g(x):
495 return f(x) + 1
496
497 code = """
498 z = f(x)
499 z = f(x)+f(y)
500 w = f(z)
501 h = f(f(w))
502 p = g(g(x))
503 """
504 funcs = [
505 abstract_code_from_function(f),
506 abstract_code_from_function(g),
507 ]
508 subcode = substitute_abstract_code_functions(code, funcs)
509 for x, y in [(0, 1), (1, 0), (0.124323, 0.4549483)]:
510 ns1 = {"x": x, "y": y, "f": f, "g": g}
511 ns2 = {"x": x, "y": y}
512 exec(deindent(code), ns1)
513 exec(subcode, ns2)
514 for k in ["z", "w", "h", "p"]:
515 assert ns1[k] == ns2[k]
516
517
518 @pytest.mark.codegen_independent
519 def test_sympytools():
520 # sympy_to_str(str_to_sympy(x)) should equal x
521
522 # Note that the test below is quite fragile since sympy might rearrange the
523 # order of symbols
524 expressions = [
525 "randn()", # argumentless function
526 "x + sin(pi*freq*t)", # expression with a constant
527 "c * userfun(t + x)", # non-sympy function
528 "abs(x) + ceil(y)", # functions with a different name in sympy
529 "inf", # constant with a different name in sympy
530 "not(b)", # boolean expression
531 ]
532
533 for expr in expressions:
534 expr2 = sympy_to_str(str_to_sympy(expr))
535 assert expr.replace(" ", "") == expr2.replace(" ", ""), f"{expr} != {expr2}"
536
537
538 @pytest.mark.codegen_independent
539 def test_error_messages():
540 nr = NodeRenderer()
541 expr_expected = [
542 ("3^2", "^", "**"),
543 ("int(not_refractory | (v > 30))", "|", "or"),
544 ("int((v > 30) & (w < 20))", "&", "and"),
545 ("x +* 3", "", ""),
546 ("v[index]", "indexing", ""),
547 ("v.value", "attribute", ""),
548 ("(v, w)", "tuple", ""),
549 ]
550 for expr, expected_1, expected_2 in expr_expected:
551 try:
552 nr.render_expr(expr)
553 raise AssertionError(f"Excepted {expr} to raise a SyntaxError.")
554 except SyntaxError as exc:
555 message = str(exc)
556 assert expected_1 in message
557 assert expected_2 in message
558
559
560 @pytest.mark.codegen_independent
561 def test_sympy_infinity():
562 # See github issue #1061
563 assert sympy_to_str(str_to_sympy("inf")) == "inf"
564 assert sympy_to_str(str_to_sympy("-inf")) == "-inf"
565
566
567 if __name__ == "__main__":
568 from _pytest.outcomes import Skipped
569
570 test_parse_expressions_python()
571 test_parse_expressions_numpy()
572 try:
573 test_parse_expressions_cpp()
574 except Skipped:
575 pass
576 test_parse_expressions_sympy()
577 test_abstract_code_dependencies()
578 test_is_boolean_expression()
579 test_parse_expression_unit()
580 test_value_from_expression()
581 test_abstract_code_from_function()
582 test_extract_abstract_code_functions()
583 test_substitute_abstract_code_functions()
584 test_sympytools()
585 test_error_messages()
586 test_sympy_infinity()