Debian Codegraph @

brian2/tests/test_functions.py

raw
1 import os
2 import shutil
3 import tempfile
4
5 import pytest
6 from numpy.testing import assert_equal
7
8 from brian2 import *
9 from brian2.codegen.codeobject import CodeObject
10 from brian2.codegen.cpp_prefs import compiler_supports_c99
11 from brian2.codegen.generators import CodeGenerator
12 from brian2.core.functions import timestep
13 from brian2.devices import RuntimeDevice
14 from brian2.parsing.sympytools import str_to_sympy, sympy_to_str
15 from brian2.tests.utils import assert_allclose, exc_isinstance
16 from brian2.utils.logger import catch_logs
17
18
19 @pytest.mark.codegen_independent
20 def test_constants_sympy():
21 """
22 Make sure that symbolic constants are understood correctly by sympy
23 """
24 assert sympy_to_str(str_to_sympy("1.0/inf")) == "0"
25 assert sympy_to_str(str_to_sympy("sin(pi)")) == "0"
26 assert sympy_to_str(str_to_sympy("log(e)")) == "1"
27
28
29 @pytest.mark.standalone_compatible
30 def test_constants_values():
31 """
32 Make sure that symbolic constants use the correct values in code
33 """
34 G = NeuronGroup(3, "v : 1")
35 G.v[0] = "pi"
36 G.v[1] = "e"
37 G.v[2] = "inf"
38 run(0 * ms)
39 assert_allclose(G.v[:], [np.pi, np.e, np.inf])
40
41
42 def int_(x):
43 return array(x, dtype=int)
44
45
46 int_.__name__ = "int"
47
48
49 @pytest.mark.parametrize(
50 "func,needs_c99_support",
51 [
52 (cos, False),
53 (tan, False),
54 (sinh, False),
55 (cosh, False),
56 (tanh, False),
57 (arcsin, False),
58 (arccos, False),
59 (arctan, False),
60 (log, False),
61 (log10, False),
62 (log1p, True),
63 (exp, False),
64 (np.sqrt, False),
65 (expm1, True),
66 (exprel, True),
67 (np.ceil, False),
68 (np.floor, False),
69 (np.sign, False),
70 (int_, False),
71 ],
72 )
73 @pytest.mark.standalone_compatible
74 def test_math_functions(func, needs_c99_support):
75 """
76 Test that math functions give the same result, regardless of whether used
77 directly or in generated Python or C++ code.
78 """
79 if not get_device() == RuntimeDevice or prefs.codegen.target != "numpy":
80 if needs_c99_support and not compiler_supports_c99():
81 pytest.skip('Support for function "{}" needs a compiler with C99 support.')
82 test_array = np.array([-1, -0.5, 0, 0.5, 1])
83
84 with catch_logs() as _: # Let's suppress warnings about illegal values
85 # Calculate the result directly
86 numpy_result = func(test_array)
87
88 # Calculate the result in a somewhat complicated way by using a
89 # subexpression in a NeuronGroup
90 if func.__name__ == "absolute":
91 # we want to use the name abs instead of absolute
92 func_name = "abs"
93 else:
94 func_name = func.__name__
95 G = NeuronGroup(
96 len(test_array),
97 f"""func = {func_name}(variable) : 1
98 variable : 1""",
99 )
100 G.variable = test_array
101 mon = StateMonitor(G, "func", record=True)
102 net = Network(G, mon)
103 net.run(defaultclock.dt)
104
105 assert_allclose(
106 numpy_result,
107 mon.func_.flatten(),
108 err_msg=f"Function {func.__name__} did not return the correct values",
109 )
110
111
112 @pytest.mark.standalone_compatible
113 @pytest.mark.parametrize("func,operator", [(np.power, "**"), (np.mod, "%")])
114 def test_math_operators(func, operator):
115 default_dt = defaultclock.dt
116 test_array = np.array([-1, -0.5, 0, 0.5, 1])
117 # Functions/operators
118 scalar = 3
119
120 # Calculate the result directly
121 numpy_result = func(test_array, scalar)
122
123 # Calculate the result in a somewhat complicated way by using a
124 # subexpression in a NeuronGroup
125 G = NeuronGroup(
126 len(test_array),
127 f"""func = variable {operator} scalar : 1
128 variable : 1""",
129 )
130 G.variable = test_array
131 mon = StateMonitor(G, "func", record=True)
132 net = Network(G, mon)
133 net.run(defaultclock.dt)
134
135 assert_allclose(
136 numpy_result,
137 mon.func_.flatten(),
138 err_msg=f"Function {func.__name__} did not return the correct values",
139 )
140
141
142 @pytest.mark.standalone_compatible
143 def test_clip():
144 G = NeuronGroup(
145 4,
146 """
147 clipexpr1 = clip(integer_var1, 0, 1) : integer
148 clipexpr2 = clip(integer_var2, -0.5, 1.5) : integer
149 clipexpr3 = clip(float_var1, 0, 1) : 1
150 clipexpr4 = clip(float_var2, -0.5, 1.5) : 1
151 integer_var1 : integer
152 integer_var2 : integer
153 float_var1 : 1
154 float_var2 : 1
155 """,
156 )
157 G.integer_var1 = [0, 1, -1, 2]
158 G.integer_var2 = [0, 1, -1, 2]
159 G.float_var1 = [0.0, 1.0, -1.0, 2.0]
160 G.float_var2 = [0.0, 1.0, -1.0, 2.0]
161 s_mon = StateMonitor(
162 G, ["clipexpr1", "clipexpr2", "clipexpr3", "clipexpr4"], record=True
163 )
164 run(defaultclock.dt)
165 assert_equal(s_mon.clipexpr1.flatten(), [0, 1, 0, 1])
166 assert_equal(s_mon.clipexpr2.flatten(), [0, 1, 0, 1])
167 assert_allclose(s_mon.clipexpr3.flatten(), [0, 1, 0, 1])
168 assert_allclose(s_mon.clipexpr4.flatten(), [0, 1, -0.5, 1.5])
169
170
171 @pytest.mark.standalone_compatible
172 def test_bool_to_int():
173 # Test that boolean expressions and variables are correctly converted into
174 # integers
175 G = NeuronGroup(
176 2,
177 """
178 intexpr1 = int(bool_var) : integer
179 intexpr2 = int(float_var > 1.0) : integer
180 bool_var : boolean
181 float_var : 1
182 """,
183 )
184 G.bool_var = [True, False]
185 G.float_var = [2.0, 0.5]
186 s_mon = StateMonitor(G, ["intexpr1", "intexpr2"], record=True)
187 run(defaultclock.dt)
188 assert_equal(s_mon.intexpr1.flatten(), [1, 0])
189 assert_equal(s_mon.intexpr2.flatten(), [1, 0])
190
191
192 @pytest.mark.standalone_compatible
193 def test_integer_power():
194 # See github issue #1500
195 G = NeuronGroup(
196 3,
197 """
198 intval1 : integer
199 intval2 : integer
200 k : integer (constant)
201 """,
202 )
203 G.k = [0, 1, 2]
204 G.run_regularly("intval1 = 2**k; intval2 = (-1)**k")
205 run(defaultclock.dt)
206 assert_equal(G.intval1[:], [1, 2, 4])
207 assert_equal(G.intval2[:], [1, -1, 1])
208
209
210 @pytest.mark.codegen_independent
211 def test_timestep_function():
212 dt = defaultclock.dt_
213 # Check that multiples of dt end up in the correct time step
214 t = np.arange(100000) * dt
215 assert_equal(timestep(t, dt), np.arange(100000))
216
217 # Scalar values should stay scalar
218 ts = timestep(0.0005, 0.0001)
219 assert np.isscalar(ts) and ts == 5
220
221 # Length-1 arrays should stay arrays
222 ts = timestep(np.array([0.0005]), 0.0001)
223 assert ts.shape == (1,) and ts == 5
224
225
226 @pytest.mark.standalone_compatible
227 def test_timestep_function_during_run():
228 group = NeuronGroup(
229 2,
230 """ref_t : second
231 ts = timestep(ref_t, dt) + timestep(t, dt) : integer""",
232 )
233 group.ref_t = [-1e4 * second, 5 * defaultclock.dt]
234 mon = StateMonitor(group, "ts", record=True)
235 run(5 * defaultclock.dt)
236 assert all(mon.ts[0] <= -1e4)
237 assert_equal(mon.ts[1], [5, 6, 7, 8, 9])
238
239
240 @pytest.mark.standalone_compatible
241 def test_user_defined_function():
242 @implementation(
243 "cpp",
244 """
245 inline double usersin(double x)
246 {
247 return sin(x);
248 }
249 """,
250 )
251 @implementation(
252 "cython",
253 """
254 cdef double usersin(double x):
255 return sin(x)
256 """,
257 )
258 @check_units(x=1, result=1)
259 def usersin(x):
260 return np.sin(x)
261
262 default_dt = defaultclock.dt
263 test_array = np.array([0, 1, 2, 3])
264 G = NeuronGroup(
265 len(test_array),
266 """
267 func = usersin(variable) : 1
268 variable : 1
269 """,
270 )
271 G.variable = test_array
272 mon = StateMonitor(G, "func", record=True)
273 run(default_dt)
274 assert_allclose(np.sin(test_array), mon.func_.flatten())
275
276
277 def test_user_defined_function_units():
278 """
279 Test the preparation of functions for use in code with check_units.
280 """
281 if prefs.codegen.target != "numpy":
282 pytest.skip("numpy-only test")
283
284 def nothing_specified(x, y, z):
285 return x * (y + z)
286
287 no_result_unit = check_units(x=1, y=second, z=second)(nothing_specified)
288 all_specified = check_units(x=1, y=second, z=second, result=second)(
289 nothing_specified
290 )
291 consistent_units = check_units(x=None, y=None, z="y", result=lambda x, y, z: x * y)(
292 nothing_specified
293 )
294
295 G = NeuronGroup(
296 1,
297 """
298 a : 1
299 b : second
300 c : second
301 """,
302 namespace={
303 "nothing_specified": nothing_specified,
304 "no_result_unit": no_result_unit,
305 "all_specified": all_specified,
306 "consistent_units": consistent_units,
307 },
308 )
309 net = Network(G)
310 net.run(0 * ms) # make sure we have a clock and therefore a t
311 G.c = "all_specified(a, b, t)"
312 G.c = "consistent_units(a, b, t)"
313 with pytest.raises(ValueError):
314 setattr(G, "c", "no_result_unit(a, b, t)")
315 with pytest.raises(KeyError):
316 setattr(G, "c", "nothing_specified(a, b, t)")
317 with pytest.raises(DimensionMismatchError):
318 setattr(G, "a", "all_specified(a, b, t)")
319 with pytest.raises(DimensionMismatchError):
320 setattr(G, "a", "all_specified(b, a, t)")
321 with pytest.raises(DimensionMismatchError):
322 setattr(G, "a", "consistent_units(a, b, t)")
323 with pytest.raises(DimensionMismatchError):
324 setattr(G, "a", "consistent_units(b, a, t)")
325
326
327 def test_simple_user_defined_function():
328 # Make sure that it's possible to use a Python function directly, without
329 # additional wrapping
330 @check_units(x=1, result=1)
331 def usersin(x):
332 return np.sin(x)
333
334 usersin.stateless = True
335
336 default_dt = defaultclock.dt
337 test_array = np.array([0, 1, 2, 3])
338 G = NeuronGroup(
339 len(test_array),
340 """func = usersin(variable) : 1
341 variable : 1""",
342 codeobj_class=NumpyCodeObject,
343 )
344 G.variable = test_array
345 mon = StateMonitor(G, "func", record=True, codeobj_class=NumpyCodeObject)
346 net = Network(G, mon)
347 net.run(default_dt)
348
349 assert_allclose(np.sin(test_array), mon.func_.flatten())
350
351
352 def test_manual_user_defined_function():
353 if prefs.codegen.target != "numpy":
354 pytest.skip("numpy-only test")
355
356 default_dt = defaultclock.dt
357
358 # User defined function without any decorators
359 def foo(x, y):
360 return x + y + 3 * volt
361
362 orig_foo = foo
363 # Since the function is not annotated with check units, we need to specify
364 # both the units of the arguments and the return unit
365 with pytest.raises(ValueError):
366 Function(foo, return_unit=volt)
367 with pytest.raises(ValueError):
368 Function(foo, arg_units=[volt, volt])
369 # If the function uses the string syntax for "same units", it needs to
370 # specify the names of the arguments
371 with pytest.raises(TypeError):
372 Function(foo, arg_units=[volt, "x"])
373 with pytest.raises(TypeError):
374 Function(foo, arg_units=[volt, "x"], arg_names=["x"]) # Needs two entries
375
376 foo = Function(foo, arg_units=[volt, volt], return_unit=volt)
377
378 assert foo(1 * volt, 2 * volt) == 6 * volt
379
380 # a can be any unit, b and c need to be the same unit
381 def bar(a, b, c):
382 return a * (b + c)
383
384 bar = Function(
385 bar,
386 arg_units=[None, None, "b"],
387 arg_names=["a", "b", "c"],
388 return_unit=lambda a, b, c: a * b,
389 )
390 assert bar(2, 3 * volt, 5 * volt) == 16 * volt
391 assert bar(2 * amp, 3 * volt, 5 * volt) == 16 * watt
392 assert bar(2 * volt, 3 * amp, 5 * amp) == 16 * watt
393
394 with pytest.raises(DimensionMismatchError):
395 bar(2, 3 * volt, 5 * amp)
396
397 # Incorrect argument units
398 group = NeuronGroup(
399 1,
400 """
401 dv/dt = foo(x, y)/ms : volt
402 x : 1
403 y : 1
404 """,
405 )
406 net = Network(group)
407 with pytest.raises(BrianObjectException) as exc:
408 net.run(0 * ms, namespace={"foo": foo})
409 assert exc_isinstance(exc, DimensionMismatchError)
410
411 # Incorrect output unit
412 group = NeuronGroup(
413 1,
414 """
415 dv/dt = foo(x, y)/ms : 1
416 x : volt
417 y : volt
418 """,
419 )
420 net = Network(group)
421 with pytest.raises(BrianObjectException) as exc:
422 net.run(0 * ms, namespace={"foo": foo})
423 assert exc_isinstance(exc, DimensionMismatchError)
424
425 G = NeuronGroup(
426 1,
427 """
428 func = foo(x, y) : volt
429 x : volt
430 y : volt
431 """,
432 )
433 G.x = 1 * volt
434 G.y = 2 * volt
435 mon = StateMonitor(G, "func", record=True)
436 net = Network(G, mon)
437 net.run(default_dt)
438
439 assert mon[0].func == [6] * volt
440
441 # discard units
442 foo.implementations.add_numpy_implementation(orig_foo, discard_units=True)
443 G = NeuronGroup(
444 1,
445 """
446 func = foo(x, y) : volt
447 x : volt
448 y : volt
449 """,
450 )
451 G.x = 1 * volt
452 G.y = 2 * volt
453 mon = StateMonitor(G, "func", record=True)
454 net = Network(G, mon)
455 net.run(default_dt)
456
457 assert mon[0].func == [6] * volt
458
459
460 @pytest.mark.cpp_standalone
461 @pytest.mark.standalone_only
462 def test_manual_user_defined_function_cpp_standalone_compiler_args():
463 set_device("cpp_standalone", directory=None)
464
465 @implementation(
466 "cpp",
467 """
468 static inline double foo(const double x, const double y)
469 {
470 return x + y + _THREE;
471 }
472 """, # just check whether we can specify the supported compiler args,
473 # only the define macro is actually used
474 headers=[],
475 sources=[],
476 libraries=[],
477 include_dirs=[],
478 library_dirs=[],
479 runtime_library_dirs=[],
480 define_macros=[("_THREE", "3")],
481 )
482 @check_units(x=volt, y=volt, result=volt)
483 def foo(x, y):
484 return x + y + 3 * volt
485
486 G = NeuronGroup(
487 1,
488 """
489 func = foo(x, y) : volt
490 x : volt
491 y : volt
492 """,
493 )
494 G.x = 1 * volt
495 G.y = 2 * volt
496 mon = StateMonitor(G, "func", record=True)
497 net = Network(G, mon)
498 net.run(defaultclock.dt)
499 assert mon[0].func == [6] * volt
500
501
502 @pytest.mark.cpp_standalone
503 @pytest.mark.standalone_only
504 def test_manual_user_defined_function_cpp_standalone_wrong_compiler_args1():
505 set_device("cpp_standalone", directory=None)
506
507 @implementation(
508 "cpp",
509 """
510 static inline double foo(const double x, const double y)
511 {
512 return x + y + _THREE;
513 }
514 """,
515 some_arg=[],
516 ) # non-existing argument
517 @check_units(x=volt, y=volt, result=volt)
518 def foo(x, y):
519 return x + y + 3 * volt
520
521 G = NeuronGroup(
522 1,
523 """
524 func = foo(x, y) : volt
525 x : volt
526 y : volt
527 """,
528 )
529 mon = StateMonitor(G, "func", record=True)
530 net = Network(G, mon)
531 with pytest.raises(BrianObjectException) as exc:
532 net.run(defaultclock.dt, namespace={"foo": foo})
533 assert exc_isinstance(exc, ValueError)
534
535
536 @pytest.mark.cpp_standalone
537 @pytest.mark.standalone_only
538 def test_manual_user_defined_function_cpp_standalone_wrong_compiler_args2():
539 set_device("cpp_standalone", directory=None)
540
541 @implementation(
542 "cpp",
543 """
544 static inline double foo(const double x, const double y)
545 {
546 return x + y + _THREE;
547 }
548 """,
549 headers="<stdio.h>",
550 ) # existing argument, wrong value type
551 @check_units(x=volt, y=volt, result=volt)
552 def foo(x, y):
553 return x + y + 3 * volt
554
555 G = NeuronGroup(
556 1,
557 """
558 func = foo(x, y) : volt
559 x : volt
560 y : volt
561 """,
562 )
563 mon = StateMonitor(G, "func", record=True)
564 net = Network(G, mon)
565 with pytest.raises(BrianObjectException) as exc:
566 net.run(defaultclock.dt, namespace={"foo": foo})
567 assert exc_isinstance(exc, TypeError)
568
569
570 def test_manual_user_defined_function_cython_compiler_args():
571 if prefs.codegen.target != "cython":
572 pytest.skip("Cython-only test")
573
574 @implementation(
575 "cython",
576 """
577 cdef double foo(double x, const double y):
578 return x + y + 3
579 """, # just check whether we can specify the supported compiler args,
580 libraries=[],
581 include_dirs=[],
582 library_dirs=[],
583 runtime_library_dirs=[],
584 )
585 @check_units(x=volt, y=volt, result=volt)
586 def foo(x, y):
587 return x + y + 3 * volt
588
589 G = NeuronGroup(
590 1,
591 """
592 func = foo(x, y) : volt
593 x : volt
594 y : volt""",
595 )
596 G.x = 1 * volt
597 G.y = 2 * volt
598 mon = StateMonitor(G, "func", record=True)
599 net = Network(G, mon)
600 net.run(defaultclock.dt)
601 assert mon[0].func == [6] * volt
602
603
604 def test_manual_user_defined_function_cython_wrong_compiler_args1():
605 if prefs.codegen.target != "cython":
606 pytest.skip("Cython-only test")
607
608 @implementation(
609 "cython",
610 """
611 cdef double foo(double x, const double y):
612 return x + y + 3
613 """,
614 some_arg=[],
615 ) # non-existing argument
616 @check_units(x=volt, y=volt, result=volt)
617 def foo(x, y):
618 return x + y + 3 * volt
619
620 G = NeuronGroup(
621 1,
622 """
623 func = foo(x, y) : volt
624 x : volt
625 y : volt
626 """,
627 )
628 mon = StateMonitor(G, "func", record=True)
629 net = Network(G, mon)
630 with pytest.raises(BrianObjectException) as exc:
631 net.run(defaultclock.dt, namespace={"foo": foo})
632 assert exc_isinstance(exc, ValueError)
633
634
635 def test_manual_user_defined_function_cython_wrong_compiler_args2():
636 if prefs.codegen.target != "cython":
637 pytest.skip("Cython-only test")
638
639 @implementation(
640 "cython",
641 """
642 cdef double foo(double x, const double y):
643 return x + y + 3
644 """,
645 libraries="cstdio",
646 ) # existing argument, wrong value type
647 @check_units(x=volt, y=volt, result=volt)
648 def foo(x, y):
649 return x + y + 3 * volt
650
651 G = NeuronGroup(
652 1,
653 """
654 func = foo(x, y) : volt
655 x : volt
656 y : volt
657 """,
658 )
659 mon = StateMonitor(G, "func", record=True)
660 net = Network(G, mon)
661 with pytest.raises(BrianObjectException) as exc:
662 net.run(defaultclock.dt, namespace={"foo": foo})
663 assert exc_isinstance(exc, TypeError)
664
665
666 def test_external_function_cython():
667 if prefs.codegen.target != "cython":
668 pytest.skip("Cython-only test")
669
670 this_dir = os.path.abspath(os.path.dirname(__file__))
671
672 @implementation(
673 "cython",
674 "from func_def_cython cimport foo",
675 sources=[os.path.join(this_dir, "func_def_cython.pyx")],
676 )
677 @check_units(x=volt, y=volt, result=volt)
678 def foo(x, y):
679 return x + y + 3 * volt
680
681 G = NeuronGroup(
682 1,
683 """
684 func = foo(x, y) : volt
685 x : volt
686 y : volt
687 """,
688 )
689 G.x = 1 * volt
690 G.y = 2 * volt
691 mon = StateMonitor(G, "func", record=True)
692 net = Network(G, mon)
693 net.run(defaultclock.dt)
694 assert mon[0].func == [6] * volt
695
696
697 @pytest.mark.cpp_standalone
698 @pytest.mark.standalone_only
699 def test_external_function_cpp_standalone():
700 set_device("cpp_standalone", directory=None)
701 this_dir = os.path.abspath(os.path.dirname(__file__))
702 with tempfile.TemporaryDirectory(prefix="brian_testsuite_") as tmpdir:
703 # copy the test function to the temporary directory
704 # this avoids issues with the file being in a directory that is not writable
705 shutil.copy(os.path.join(this_dir, "func_def_cpp.h"), tmpdir)
706 shutil.copy(os.path.join(this_dir, "func_def_cpp.cpp"), tmpdir)
707
708 @implementation(
709 "cpp",
710 "//all code in func_def_cpp.cpp",
711 headers=['"func_def_cpp.h"'],
712 include_dirs=[tmpdir],
713 sources=[os.path.join(tmpdir, "func_def_cpp.cpp")],
714 )
715 @check_units(x=volt, y=volt, result=volt)
716 def foo(x, y):
717 return x + y + 3 * volt
718
719 G = NeuronGroup(
720 1,
721 """
722 func = foo(x, y) : volt
723 x : volt
724 y : volt
725 """,
726 )
727 G.x = 1 * volt
728 G.y = 2 * volt
729 mon = StateMonitor(G, "func", record=True)
730 net = Network(G, mon)
731 net.run(defaultclock.dt)
732 assert mon[0].func == [6] * volt
733
734
735 @pytest.mark.codegen_independent
736 def test_user_defined_function_discarding_units():
737 # A function with units that should discard units also inside the function
738 @implementation("numpy", discard_units=True)
739 @check_units(v=volt, result=volt)
740 def foo(v):
741 return v + 3 * volt # this normally raises an error for unitless v
742
743 assert foo(5 * volt) == 8 * volt
744
745 # Test the function that is used during a run
746 assert foo.implementations[NumpyCodeObject].get_code(None)(5) == 8
747
748
749 @pytest.mark.codegen_independent
750 def test_user_defined_function_discarding_units_2():
751 # Add a numpy implementation explicitly (as in TimedArray)
752 unit = volt
753
754 @check_units(v=volt, result=unit)
755 def foo(v):
756 return v + 3 * unit # this normally raises an error for unitless v
757
758 foo = Function(pyfunc=foo)
759
760 def unitless_foo(v):
761 return v + 3
762
763 foo.implementations.add_implementation("numpy", code=unitless_foo)
764
765 assert foo(5 * volt) == 8 * volt
766
767 # Test the function that is used during a run
768 assert foo.implementations[NumpyCodeObject].get_code(None)(5) == 8
769
770
771 @pytest.mark.codegen_independent
772 def test_function_implementation_container():
773 import brian2.codegen.targets as targets
774
775 class ACodeGenerator(CodeGenerator):
776 class_name = "A Language"
777
778 class BCodeGenerator(CodeGenerator):
779 class_name = "B Language"
780
781 class ACodeObject(CodeObject):
782 generator_class = ACodeGenerator
783 class_name = "A"
784
785 class A2CodeObject(CodeObject):
786 generator_class = ACodeGenerator
787 class_name = "A2"
788
789 class BCodeObject(CodeObject):
790 generator_class = BCodeGenerator
791 class_name = "B"
792
793 # Register the code generation targets
794 _previous_codegen_targets = set(targets.codegen_targets)
795 targets.codegen_targets = {ACodeObject, BCodeObject}
796
797 @check_units(x=volt, result=volt)
798 def foo(x):
799 return x
800
801 f = Function(foo)
802
803 container = f.implementations
804
805 # inserting into the container with a CodeGenerator class
806 container.add_implementation(BCodeGenerator, code="implementation B language")
807 assert container[BCodeGenerator].get_code(None) == "implementation B language"
808
809 # inserting into the container with a CodeObject class
810 container.add_implementation(ACodeObject, code="implementation A CodeObject")
811 assert container[ACodeObject].get_code(None) == "implementation A CodeObject"
812
813 # inserting into the container with a name of a CodeGenerator
814 container.add_implementation("A Language", "implementation A Language")
815 assert container["A Language"].get_code(None) == "implementation A Language"
816 assert container[ACodeGenerator].get_code(None) == "implementation A Language"
817 assert container[A2CodeObject].get_code(None) == "implementation A Language"
818
819 # inserting into the container with a name of a CodeObject
820 container.add_implementation("B", "implementation B CodeObject")
821 assert container["B"].get_code(None) == "implementation B CodeObject"
822 assert container[BCodeObject].get_code(None) == "implementation B CodeObject"
823
824 with pytest.raises(KeyError):
825 container["unknown"]
826
827 # some basic dictionary properties
828 assert len(container) == 4
829 assert {key for key in container} == {
830 "A Language",
831 "B",
832 ACodeObject,
833 BCodeGenerator,
834 }
835
836 # Restore the previous codegeneration targets
837 targets.codegen_targets = _previous_codegen_targets
838
839
840 def test_function_dependencies_cython():
841 if prefs.codegen.target != "cython":
842 pytest.skip("cython-only test")
843
844 @implementation(
845 "cython",
846 """
847 cdef float foo(float x):
848 return 42*0.001
849 """,
850 )
851 @check_units(x=volt, result=volt)
852 def foo(x):
853 return 42 * mV
854
855 # Second function with an independent implementation for numpy and an
856 # implementation for C++ that makes use of the previous function.
857
858 @implementation(
859 "cython",
860 """
861 cdef float bar(float x):
862 return 2*foo(x)
863 """,
864 dependencies={"foo": foo},
865 )
866 @check_units(x=volt, result=volt)
867 def bar(x):
868 return 84 * mV
869
870 G = NeuronGroup(5, "v : volt")
871 G.run_regularly("v = bar(v)")
872 net = Network(G)
873 net.run(defaultclock.dt)
874
875 assert_allclose(G.v_[:], 84 * 0.001)
876
877
878 def test_function_dependencies_cython_rename():
879 if prefs.codegen.target != "cython":
880 pytest.skip("cython-only test")
881
882 @implementation(
883 "cython",
884 """
885 cdef float _foo(float x):
886 return 42*0.001
887 """,
888 name="_foo",
889 )
890 @check_units(x=volt, result=volt)
891 def foo(x):
892 return 42 * mV
893
894 # Second function with an independent implementation for numpy and an
895 # implementation for C++ that makes use of the previous function.
896
897 @implementation(
898 "cython",
899 """
900 cdef float bar(float x):
901 return 2*my_foo(x)
902 """,
903 dependencies={"my_foo": foo},
904 )
905 @check_units(x=volt, result=volt)
906 def bar(x):
907 return 84 * mV
908
909 G = NeuronGroup(5, "v : volt")
910 G.run_regularly("v = bar(v)")
911 net = Network(G)
912 net.run(defaultclock.dt)
913
914 assert_allclose(G.v_[:], 84 * 0.001)
915
916
917 def test_function_dependencies_numpy():
918 if prefs.codegen.target != "numpy":
919 pytest.skip("numpy-only test")
920
921 @implementation(
922 "cpp",
923 """
924 float foo(float x)
925 {
926 return 42*0.001;
927 }""",
928 )
929 @check_units(x=volt, result=volt)
930 def foo(x):
931 return 42 * mV
932
933 # Second function with an independent implementation for C++ and an
934 # implementation for numpy that makes use of the previous function.
935
936 # Note that we don't need to use the explicit dependencies mechanism for
937 # numpy, since the Python function stores a reference to the referenced
938 # function directly
939
940 @implementation(
941 "cpp",
942 """
943 float bar(float x)
944 {
945 return 84*0.001;
946 }""",
947 )
948 @check_units(x=volt, result=volt)
949 def bar(x):
950 return 2 * foo(x)
951
952 G = NeuronGroup(5, "v : volt")
953 G.run_regularly("v = bar(v)")
954 net = Network(G)
955 net.run(defaultclock.dt)
956
957 assert_allclose(G.v_[:], 84 * 0.001)
958
959
960 @pytest.mark.standalone_compatible
961 def test_repeated_function_dependencies():
962 # each of the binomial functions adds randn as a depency, see #988
963 test_neuron = NeuronGroup(
964 1,
965 "x : 1",
966 namespace={
967 "bino_1": BinomialFunction(10, 0.5),
968 "bino_2": BinomialFunction(10, 0.6),
969 },
970 )
971 test_neuron.x = "bino_1()+bino_2()"
972
973 run(0 * ms)
974
975
976 @pytest.mark.standalone_compatible
977 def test_binomial():
978 binomial_f_approximated = BinomialFunction(100, 0.1, approximate=True)
979 binomial_f = BinomialFunction(100, 0.1, approximate=False)
980
981 # Just check that it does not raise an error and that it produces some
982 # values
983 G = NeuronGroup(
984 1,
985 """
986 x : 1
987 y : 1
988 """,
989 )
990 G.run_regularly(
991 """
992 x = binomial_f_approximated()
993 y = binomial_f()
994 """
995 )
996 mon = StateMonitor(G, ["x", "y"], record=0)
997 run(1 * ms)
998 assert np.var(mon[0].x) > 0
999 assert np.var(mon[0].y) > 0
1000
1001
1002 @pytest.mark.standalone_compatible
1003 def test_poisson():
1004 # Just check that it does not raise an error and that it produces some
1005 # values
1006 G = NeuronGroup(
1007 5,
1008 """
1009 l : 1
1010 x : integer
1011 y : integer
1012 z : integer
1013 """,
1014 )
1015 G.l = [0, 1, 5, 15, 25]
1016 G.run_regularly(
1017 """
1018 x = poisson(l)
1019 y = poisson(5)
1020 z = poisson(0)
1021 """
1022 )
1023 mon = StateMonitor(G, ["x", "y", "z"], record=True)
1024 run(100 * defaultclock.dt)
1025 assert_equal(mon.x[0], 0)
1026 assert all(np.var(mon.x[1:], axis=1) > 0)
1027 assert all(np.var(mon.y, axis=1) > 0)
1028 assert_equal(mon.z, 0)
1029
1030
1031 def test_declare_types():
1032 if prefs.codegen.target != "numpy":
1033 pytest.skip("numpy-only test")
1034
1035 @declare_types(a="integer", b="float", result="highest")
1036 def f(a, b):
1037 return a * b
1038
1039 assert f._arg_types == ["integer", "float"]
1040 assert f._return_type == "highest"
1041
1042 @declare_types(b="float")
1043 def f(a, b, c):
1044 return a * b * c
1045
1046 assert f._arg_types == ["any", "float", "any"]
1047 assert f._return_type == "float"
1048
1049 def bad_argtype():
1050 @declare_types(b="floating")
1051 def f(a, b, c):
1052 return a * b * c
1053
1054 with pytest.raises(ValueError):
1055 bad_argtype()
1056
1057 def bad_argname():
1058 @declare_types(d="floating")
1059 def f(a, b, c):
1060 return a * b * c
1061
1062 with pytest.raises(ValueError):
1063 bad_argname()
1064
1065 @check_units(a=volt, b=1)
1066 @declare_types(a="float", b="integer")
1067 def f(a, b):
1068 return a * b
1069
1070 @declare_types(a="float", b="integer")
1071 @check_units(a=volt, b=1)
1072 def f(a, b):
1073 return a * b
1074
1075 def bad_units():
1076 @declare_types(a="integer", b="float")
1077 @check_units(a=volt, b=1, result=volt)
1078 def f(a, b):
1079 return a * b
1080
1081 eqs = """
1082 dv/dt = f(v, 1)/second : 1
1083 """
1084 G = NeuronGroup(1, eqs)
1085 Network(G).run(1 * ms)
1086
1087 with pytest.raises(BrianObjectException) as exc:
1088 bad_units()
1089 assert exc_isinstance(exc, TypeError)
1090
1091 def bad_type():
1092 @implementation("numpy", discard_units=True)
1093 @declare_types(a="float", result="float")
1094 @check_units(a=1, result=1)
1095 def f(a):
1096 return a
1097
1098 eqs = """
1099 a : integer
1100 dv/dt = f(a)*v/second : 1
1101 """
1102 G = NeuronGroup(1, eqs)
1103 Network(G).run(1 * ms)
1104
1105 with pytest.raises(BrianObjectException) as exc:
1106 bad_type()
1107 assert exc_isinstance(exc, TypeError)
1108
1109
1110 def test_multiple_stateless_function_calls():
1111 # Check that expressions such as rand() + rand() (which might be incorrectly
1112 # simplified to 2*rand()) raise an error
1113 G = NeuronGroup(1, "dv/dt = (rand() - rand())/second : 1")
1114 net = Network(G)
1115 with pytest.raises(BrianObjectException) as exc:
1116 net.run(0 * ms)
1117 assert exc_isinstance(exc, NotImplementedError)
1118 G2 = NeuronGroup(1, "v:1", threshold="v>1", reset="v=rand() - rand()")
1119 net2 = Network(G2)
1120 with pytest.raises(BrianObjectException) as exc:
1121 net2.run(0 * ms)
1122 assert exc_isinstance(exc, NotImplementedError)
1123 G3 = NeuronGroup(1, "v:1")
1124 G3.run_regularly("v = rand() - rand()")
1125 net3 = Network(G3)
1126 with pytest.raises(BrianObjectException) as exc:
1127 net3.run(0 * ms)
1128 assert exc_isinstance(exc, NotImplementedError)
1129 G4 = NeuronGroup(1, "x : 1")
1130 # Verify that synaptic equations are checked as well, see #1146
1131 S = Synapses(G4, G4, "dy/dt = (rand() - rand())/second : 1 (clock-driven)")
1132 S.connect()
1133 net = Network(G4, S)
1134 with pytest.raises(BrianObjectException) as exc:
1135 net.run(0 * ms)
1136 assert exc_isinstance(exc, NotImplementedError)
1137
1138
1139 @pytest.mark.codegen_independent
1140 def test_parse_dimension_errors():
1141 from brian2.parsing.expressions import parse_expression_dimensions
1142
1143 @check_units(x=1, result=1)
1144 def foo(x):
1145 return x
1146
1147 # Function call with keyword arguments
1148 with pytest.raises(ValueError):
1149 parse_expression_dimensions("foo(a=1, b=2)", {"foo": foo})
1150 # Unknown function
1151 with pytest.raises(SyntaxError):
1152 parse_expression_dimensions("bar(1, 2)", {"foo": foo})
1153 # Function without unit definition
1154 with pytest.raises(ValueError):
1155 parse_expression_dimensions("bar(1, 2)", {"bar": lambda x, y: x + y})
1156 # Function with wrong number of arguments
1157 with pytest.raises(SyntaxError):
1158 parse_expression_dimensions("foo(1, 2)", {"foo": foo})
1159
1160
1161 if __name__ == "__main__":
1162 # prefs.codegen.target = 'numpy'
1163 import time
1164
1165 from _pytest.outcomes import Skipped
1166
1167 from brian2 import prefs
1168
1169 for f in [
1170 test_constants_sympy,
1171 test_constants_values,
1172 test_math_functions,
1173 test_clip,
1174 test_bool_to_int,
1175 test_timestep_function,
1176 test_timestep_function_during_run,
1177 test_user_defined_function,
1178 test_user_defined_function_units,
1179 test_simple_user_defined_function,
1180 test_manual_user_defined_function,
1181 test_external_function_cython,
1182 test_user_defined_function_discarding_units,
1183 test_user_defined_function_discarding_units_2,
1184 test_function_implementation_container,
1185 test_function_dependencies_numpy,
1186 test_function_dependencies_cython,
1187 test_function_dependencies_cython_rename,
1188 test_repeated_function_dependencies,
1189 test_binomial,
1190 test_poisson,
1191 test_declare_types,
1192 test_multiple_stateless_function_calls,
1193 ]:
1194 try:
1195 start = time.time()
1196 f()
1197 print("Test", f.__name__, "took", time.time() - start)
1198 except Skipped as e:
1199 print("Skipping test", f.__name__, e)