Debian Codegraph @

brian2/tests/test_stateupdaters.py

raw
1 import logging
2 import re
3
4 import pytest
5 from numpy.testing import assert_equal
6
7 from brian2 import *
8 from brian2.core.variables import ArrayVariable, Constant, Variable
9 from brian2.stateupdaters.base import UnsupportedEquationsException
10 from brian2.tests.utils import assert_allclose, exc_isinstance
11 from brian2.utils.logger import catch_logs
12
13
14 @pytest.mark.codegen_independent
15 def test_explicit_stateupdater_parsing():
16 """
17 Test the parsing of explicit state updater descriptions.
18 """
19 # These are valid descriptions and should not raise errors
20 updater = ExplicitStateUpdater("x_new = x + dt * f(x, t)")
21 updater(Equations("dv/dt = -v / tau : 1"))
22 updater = ExplicitStateUpdater(
23 """
24 x2 = x + dt * f(x, t)
25 x_new = x2
26 """
27 )
28 updater(Equations("dv/dt = -v / tau : 1"))
29 updater = ExplicitStateUpdater(
30 """
31 x1 = g(x, t) * dW
32 x2 = x + dt * f(x, t)
33 x_new = x1 + x2
34 """,
35 stochastic="multiplicative",
36 )
37 updater(Equations("dv/dt = -v / tau + v * xi * tau**-.5: 1"))
38
39 updater = ExplicitStateUpdater(
40 """
41 x_support = x + dt*f(x, t) + dt**.5 * g(x, t)
42 g_support = g(x_support, t)
43 k = 1/(2*dt**.5)*(g_support - g(x, t))*(dW**2)
44 x_new = x + dt*f(x,t) + g(x, t) * dW + k
45 """,
46 stochastic="multiplicative",
47 )
48 updater(Equations("dv/dt = -v / tau + v * xi * tau**-.5: 1"))
49
50 # Examples of failed parsing
51 # No x_new = ... statement
52 with pytest.raises(SyntaxError):
53 ExplicitStateUpdater("x = x + dt * f(x, t)")
54 # Not an assigment
55 with pytest.raises(SyntaxError):
56 ExplicitStateUpdater(
57 """
58 2 * x
59 x_new = x + dt * f(x, t)
60 """
61 )
62
63 # doesn't separate into stochastic and non-stochastic part
64 updater = ExplicitStateUpdater("x_new = x + dt * f(x, t) * g(x, t) * dW")
65 with pytest.raises(ValueError):
66 updater(Equations(""))
67
68
69 @pytest.mark.codegen_independent
70 def test_non_autonomous_equations():
71 # Check that non-autonmous equations are handled correctly in multi-step
72 # updates
73 updater = ExplicitStateUpdater("x_new = f(x, t + 0.5*dt)")
74 update_step = updater(Equations("dv/dt = t : 1")) # Not a valid equation but...
75 # very crude test
76 assert "0.5*dt" in update_step
77
78
79 @pytest.mark.codegen_independent
80 def test_str_repr():
81 """
82 Assure that __str__ and __repr__ do not raise errors
83 """
84 for integrator in [linear, euler, rk2, rk4]:
85 assert len(str(integrator))
86 assert len(repr(integrator))
87
88
89 @pytest.mark.codegen_independent
90 def test_multiple_noise_variables_basic():
91 # Very basic test, only to make sure that stochastic state updaters handle
92 # multiple noise variables at all
93 eqs = Equations(
94 """
95 dv/dt = -v / (10*ms) + xi_1 * ms ** -.5 : 1
96 dw/dt = -w / (10*ms) + xi_2 * ms ** -.5 : 1
97 """
98 )
99 for method in [euler, heun, milstein]:
100 code = method(eqs, {})
101 assert "xi_1" in code
102 assert "xi_2" in code
103
104
105 def test_multiple_noise_variables_extended():
106 # Some actual simulations with multiple noise variables
107 eqs = """
108 dx/dt = y : 1
109 dy/dt = - 1*ms**-1*y - 40*ms**-2*x : Hz
110 """
111 all_eqs_noise = [
112 """
113 dx/dt = y : 1
114 dy/dt = noise_factor*ms**-1.5*xi_1 + noise_factor*ms**-1.5*xi_2
115 - 1*ms**-1*y - 40*ms**-2*x : Hz
116 """,
117 """
118 dx/dt = y + noise_factor*ms**-0.5*xi_1: 1
119 dy/dt = noise_factor*ms**-1.5*xi_2
120 - 1*ms**-1*y - 40*ms**-2*x : Hz
121 """,
122 ]
123 G = NeuronGroup(2, eqs, method="euler")
124 G.x = [0.5, 1]
125 G.y = [0, 0.5] * Hz
126 mon = StateMonitor(G, ["x", "y"], record=True)
127 net = Network(G, mon)
128 net.run(10 * ms)
129 no_noise_x, no_noise_y = mon.x[:], mon.y[:]
130
131 for eqs_noise in all_eqs_noise:
132 for method_name, method in [("euler", euler), ("heun", heun)]:
133 with catch_logs("WARNING"):
134 G = NeuronGroup(2, eqs_noise, method=method)
135 G.x = [0.5, 1]
136 G.y = [0, 0.5] * Hz
137 mon = StateMonitor(G, ["x", "y"], record=True)
138 net = Network(G, mon)
139 # We run it deterministically, but still we'd detect major errors (e.g.
140 # non-stochastic terms that are added twice, see #330
141 net.run(10 * ms, namespace={"noise_factor": 0.0})
142 assert_allclose(
143 mon.x[:],
144 no_noise_x,
145 err_msg=f"Method {method_name} gave incorrect results",
146 )
147 assert_allclose(
148 mon.y[:],
149 no_noise_y,
150 err_msg=f"Method {method_name} gave incorrect results",
151 )
152
153
154 def test_multiple_noise_variables_deterministic_noise(fake_randn_randn_fixture):
155 all_eqs = [
156 """
157 dx/dt = y : 1
158 dy/dt = -y / (10*ms) + dt**-.5*0.5*ms**-1.5 + dt**-.5*0.5*ms**-1.5: Hz
159 """,
160 """
161 dx/dt = y + dt**-.5*0.5*ms**-0.5: 1
162 dy/dt = -y / (10*ms) + dt**-.5*0.5 * ms**-1.5 : Hz
163 """,
164 ]
165 all_eqs_noise = [
166 """
167 dx/dt = y : 1
168 dy/dt = -y / (10*ms) + xi_1 * ms**-1.5 + xi_2 * ms**-1.5: Hz
169 """,
170 """
171 dx/dt = y + xi_1*ms**-0.5: 1
172 dy/dt = -y / (10*ms) + xi_2 * ms**-1.5 : Hz
173 """,
174 ]
175 for eqs, eqs_noise in zip(all_eqs, all_eqs_noise):
176 G = NeuronGroup(2, eqs, method="euler")
177 G.x = [5, 17]
178 G.y = [25, 5] * Hz
179 mon = StateMonitor(G, ["x", "y"], record=True)
180 net = Network(G, mon)
181 net.run(10 * ms)
182 no_noise_x, no_noise_y = mon.x[:], mon.y[:]
183
184 for method_name, method in [("euler", euler), ("heun", heun)]:
185 with catch_logs("WARNING"):
186 G = NeuronGroup(2, eqs_noise, method=method)
187 G.x = [5, 17]
188 G.y = [25, 5] * Hz
189 mon = StateMonitor(G, ["x", "y"], record=True)
190 net = Network(G, mon)
191 net.run(10 * ms)
192 assert_allclose(
193 mon.x[:],
194 no_noise_x,
195 err_msg=f"Method {method_name} gave incorrect results",
196 )
197 assert_allclose(
198 mon.y[:],
199 no_noise_y,
200 err_msg=f"Method {method_name} gave incorrect results",
201 )
202
203
204 @pytest.mark.codegen_independent
205 def test_multiplicative_noise():
206 # Noise is not multiplicative (constant over time step)
207 ta = TimedArray([0, 1], dt=defaultclock.dt * 10)
208 Eq = Equations("dv/dt = ta(t)*xi*(5*ms)**-0.5 :1")
209 group = NeuronGroup(1, Eq, method="euler")
210 net = Network(group)
211 net.run(0 * ms) # no error
212
213 # Noise is multiplicative (multiplied with time-varying variable)
214 Eq1 = Equations("dv/dt = v*xi*(5*ms)**-0.5 :1")
215 group1 = NeuronGroup(1, Eq1, method="euler")
216 net1 = Network(group1)
217 with pytest.raises(BrianObjectException) as exc:
218 net1.run(0 * ms)
219 assert exc_isinstance(exc, UnsupportedEquationsException)
220
221 # Noise is multiplicative (multiplied with time)
222 Eq2 = Equations("dv/dt = (t/ms)*xi*(5*ms)**-0.5 :1")
223 group2 = NeuronGroup(1, Eq2, method="euler")
224 net2 = Network(group2)
225 with pytest.raises(BrianObjectException) as exc:
226 net2.run(0 * ms)
227 assert exc_isinstance(exc, UnsupportedEquationsException)
228
229 # Noise is multiplicative (multiplied with time-varying variable)
230 Eq3 = Equations(
231 """
232 dv/dt = w*xi*(5*ms)**-0.5 :1
233 dw/dt = -w/(10*ms) : 1
234 """
235 )
236 group3 = NeuronGroup(1, Eq3, method="euler")
237 net3 = Network(group3)
238 with pytest.raises(BrianObjectException) as exc:
239 net3.run(0 * ms)
240 assert exc_isinstance(exc, UnsupportedEquationsException)
241
242 # One of the equations has multiplicative noise
243 Eq4 = Equations(
244 """
245 dv/dt = xi_1*(5*ms)**-0.5 : 1
246 dw/dt = (t/ms)*xi_2*(5*ms)**-0.5 :1
247 """
248 )
249 group4 = NeuronGroup(1, Eq4, method="euler")
250 net4 = Network(group4)
251 with pytest.raises(BrianObjectException) as exc:
252 net4.run(0 * ms)
253 assert exc_isinstance(exc, UnsupportedEquationsException)
254
255 # One of the equations has multiplicative noise
256 Eq5 = Equations(
257 """
258 dv/dt = xi_1*(5*ms)**-0.5 : 1
259 dw/dt = v*xi_2*(5*ms)**-0.5 :1
260 """
261 )
262 group5 = NeuronGroup(1, Eq5, method="euler")
263 net5 = Network(group4)
264 with pytest.raises(BrianObjectException) as exc:
265 net5.run(0 * ms)
266 assert exc_isinstance(exc, UnsupportedEquationsException)
267
268
269 def test_pure_noise_deterministic(fake_randn_randn_fixture):
270 sigma = 3.0
271 eqs = Equations("dx/dt = sigma*xi/sqrt(ms) : 1")
272 dt = 0.1 * ms
273 for method in ["euler", "heun", "milstein"]:
274 G = NeuronGroup(1, eqs, dt=dt, method=method)
275 run(10 * dt)
276 assert_allclose(
277 G.x,
278 sqrt(dt) * sigma * 0.5 / sqrt(1 * ms) * 10,
279 err_msg=f"method {method} did not give the expected result",
280 )
281
282
283 @pytest.mark.codegen_independent
284 def test_temporary_variables():
285 """
286 Make sure that the code does the distinction between temporary variables
287 in the state updater description and external variables used in the
288 equations.
289 """
290 # Use a variable name that is used in the state updater description
291 k_2 = 5
292 eqs = Equations("dv/dt = -(v + k_2)/(10*ms) : 1")
293 converted = rk4(eqs)
294
295 # Use a non-problematic name
296 k_var = 5
297 eqs = Equations("dv/dt = -(v + k_var)/(10*ms) : 1")
298 converted2 = rk4(eqs)
299
300 # Make sure that the two formulations result in the same code
301 assert converted == converted2.replace("k_var", "k_2")
302
303
304 @pytest.mark.codegen_independent
305 def test_temporary_variables2():
306 """
307 Make sure that the code does the distinction between temporary variables
308 in the state updater description and external variables used in the
309 equations.
310 """
311 tau = 10 * ms
312 # Use a variable name that is used in the state updater description
313 k = 5
314 eqs = Equations("dv/dt = -v/tau + k*xi*tau**-0.5: 1")
315 converted = milstein(eqs)
316
317 # Use a non-problematic name
318 k_var = 5
319 eqs = Equations("dv/dt = -v/tau + k_var*xi*tau**-0.5: 1")
320 converted2 = milstein(eqs)
321
322 # Make sure that the two formulations result in the same code
323 assert converted == converted2.replace("k_var", "k")
324
325
326 @pytest.mark.codegen_independent
327 def test_integrator_code():
328 """
329 Check whether the returned abstract code is as expected.
330 """
331 # A very simple example where the abstract code should always look the same
332 eqs = Equations("dv/dt = -v / (1 * second) : 1")
333
334 # Only test very basic stuff (expected number of lines and last line)
335 for integrator, lines in zip([linear, euler, rk2, rk4], [2, 2, 3, 6]):
336 code_lines = integrator(eqs).split("\n")
337 err_msg = (
338 f"Returned code for integrator {integrator.__class__.__name__} had"
339 f" {len(code_lines)} lines instead of {int(lines)}"
340 )
341 assert len(code_lines) == lines, err_msg
342 assert code_lines[-1] == "v = _v"
343
344 # Make sure that it isn't a problem to use 'x', 'f' and 'g' as variable
345 # names, even though they are also used in state updater descriptions.
346 # The resulting code should be identical when replacing x by x0 (and ..._x by
347 # ..._x0)
348 for varname in ["x", "f", "g"]:
349 # We use a very similar names here to avoid slightly re-arranged
350 # expressions due to alphabetical sorting of terms in
351 # multiplications, etc.
352 eqs_v = Equations(f"d{varname}0/dt = -{varname}0 / (1 * second) : 1")
353 eqs_var = Equations(f"d{varname}/dt = -{varname} / (1 * second) : 1")
354 for integrator in [linear, euler, rk2, rk4]:
355 code_v = integrator(eqs_v)
356 code_var = integrator(eqs_var)
357 # Re-substitute the variable names in the output
358 code_var = re.sub(rf"\b{varname}\b", f"{varname}0", code_var)
359 code_var = re.sub(rf"\b(\w*)_{varname}\b", rf"\1_{varname}0", code_var)
360 assert code_var == code_v, f"'{code_var}' does not match '{code_v}'"
361
362
363 @pytest.mark.codegen_independent
364 def test_integrator_code2():
365 """
366 Test integration for a simple model with several state variables.
367 """
368 eqs = Equations(
369 """
370 dv/dt=(ge+gi-v)/tau : volt
371 dge/dt=-ge/taue : volt
372 dgi/dt=-gi/taui : volt
373 """
374 )
375 euler_integration = euler(eqs)
376 lines = sorted(euler_integration.split("\n"))
377 # Do a very basic check that the right variables are used in every line
378 for varname, line in zip(["_ge", "_gi", "_v", "ge", "gi", "v"], lines):
379 assert line.startswith(f"{varname} = "), (
380 f'line "{line}" does not start with {varname}'
381 )
382 for variables, line in zip(
383 [
384 ["dt", "ge", "taue"],
385 ["dt", "gi", "taui"],
386 ["dt", "ge", "gi", "v", "tau"],
387 ["_ge"],
388 ["_gi"],
389 ["_v"],
390 ],
391 lines,
392 ):
393 rhs = line.split("=")[1]
394 for variable in variables:
395 assert variable in rhs, f'{variable} not in RHS: "{rhs}"'
396
397
398 @pytest.mark.codegen_independent
399 def test_illegal_calls():
400 eqs = Equations("dv/dt = -v / (10*ms) : 1")
401 clock = Clock(dt=0.1 * ms)
402 variables = {
403 "v": ArrayVariable(
404 name="name",
405 size=10,
406 owner=None,
407 device=None,
408 dtype=np.float64,
409 constant=False,
410 ),
411 "t": clock.variables["t"],
412 "dt": clock.variables["dt"],
413 }
414 with pytest.raises(TypeError):
415 StateUpdateMethod.apply_stateupdater(eqs, variables, object())
416 with pytest.raises(TypeError):
417 StateUpdateMethod.apply_stateupdater(
418 eqs, variables, group_name="my_name", method=object()
419 )
420 with pytest.raises(TypeError):
421 StateUpdateMethod.apply_stateupdater(eqs, variables, [object(), "euler"])
422 with pytest.raises(TypeError):
423 StateUpdateMethod.apply_stateupdater(
424 eqs, variables, group_name="my_name", method=[object(), "euler"]
425 )
426
427
428 def check_integration(eqs, variables, can_integrate):
429 # can_integrate maps integrators to True/False/None
430 # True/False means that the integrator should/should not integrate the equations
431 # None means that it *might* integrate the equations (only needed for the
432 # exact integration, since it can depend on the sympy version)
433 for integrator, able in can_integrate.items():
434 try:
435 integrator(eqs, variables)
436 if able is False:
437 raise AssertionError(
438 "Should not be able to integrate these "
439 f"equations (equations: '{eqs}') with "
440 f"integrator {integrator.__class__.__name__}"
441 )
442 except UnsupportedEquationsException:
443 if able is True:
444 raise AssertionError(
445 "Should be able to integrate these "
446 f"equations (equations: '{eqs}') with "
447 f"integrator {integrator.__class__.__name__}"
448 )
449
450
451 @pytest.mark.codegen_independent
452 def test_priority():
453 updater = ExplicitStateUpdater("x_new = x + dt * f(x, t)")
454 # Equations that work for the state updater
455 eqs = Equations("dv/dt = -v / (10*ms) : 1")
456 clock = Clock(dt=0.1 * ms)
457 variables = {
458 "v": ArrayVariable(
459 name="name",
460 size=10,
461 owner=None,
462 device=None,
463 dtype=np.float64,
464 constant=False,
465 ),
466 "w": ArrayVariable(
467 name="name",
468 size=10,
469 owner=None,
470 device=None,
471 dtype=np.float64,
472 constant=False,
473 ),
474 "t": clock.variables["t"],
475 "dt": clock.variables["dt"],
476 }
477 updater(eqs, variables) # should not raise an error
478
479 # External parameter in the coefficient, linear integration should work
480 param = 1
481 eqs = Equations("dv/dt = -param * v / (10*ms) : 1")
482 updater(eqs, variables) # should not raise an error
483 can_integrate = {
484 linear: True,
485 euler: True,
486 exponential_euler: True,
487 rk2: True,
488 rk4: True,
489 heun: True,
490 milstein: True,
491 }
492
493 check_integration(eqs, variables, can_integrate)
494
495 # Constant equation, should work for all except linear (see #1010)
496 param = 1
497 eqs = Equations(
498 """dv/dt = 10*Hz : 1
499 dw/dt = -v/(10*ms) : 1"""
500 )
501 updater(eqs, variables) # should not raise an error
502 can_integrate = {
503 linear: None,
504 euler: True,
505 exponential_euler: True,
506 rk2: True,
507 rk4: True,
508 heun: True,
509 milstein: True,
510 }
511
512 check_integration(eqs, variables, can_integrate)
513
514 # Equations resulting in complex linear solution for older versions of sympy
515 eqs = Equations(
516 """
517 dv/dt = (ge+gi-(v+49*mV))/(20*ms) : volt
518 dge/dt = -ge/(5*ms) : volt
519 dgi/dt = Dgi/(5*ms) : volt
520 dDgi/dt = ((-2./5) * Dgi - (1./5**2)*gi)/(10*ms) : volt
521 """
522 )
523 can_integrate = {
524 linear: None,
525 euler: True,
526 exponential_euler: True,
527 rk2: True,
528 rk4: True,
529 heun: True,
530 milstein: True,
531 }
532 check_integration(eqs, variables, can_integrate)
533
534 # Equation with additive noise
535 eqs = Equations("dv/dt = -v / (10*ms) + xi/(10*ms)**.5 : 1")
536 with pytest.raises(UnsupportedEquationsException):
537 updater(eqs, variables)
538
539 can_integrate = {
540 linear: False,
541 euler: True,
542 exponential_euler: False,
543 rk2: False,
544 rk4: False,
545 heun: True,
546 milstein: True,
547 }
548
549 check_integration(eqs, variables, can_integrate)
550
551 # Equation with multiplicative noise
552 eqs = Equations("dv/dt = -v / (10*ms) + v*xi/(10*ms)**.5 : 1")
553 with pytest.raises(UnsupportedEquationsException):
554 updater(eqs, variables)
555
556 can_integrate = {
557 linear: False,
558 euler: False,
559 exponential_euler: False,
560 rk2: False,
561 rk4: False,
562 heun: True,
563 milstein: True,
564 }
565
566 check_integration(eqs, variables, can_integrate)
567
568
569 @pytest.mark.codegen_independent
570 def test_registration():
571 """
572 Test state updater registration.
573 """
574 # Save state before tests
575 before = dict(StateUpdateMethod.stateupdaters)
576
577 lazy_updater = ExplicitStateUpdater("x_new = x")
578 StateUpdateMethod.register("lazy", lazy_updater)
579
580 # Trying to register again
581 with pytest.raises(ValueError):
582 StateUpdateMethod.register("lazy", lazy_updater)
583
584 # Trying to register something that is not a state updater
585 with pytest.raises(ValueError):
586 StateUpdateMethod.register("foo", "just a string")
587
588 # Trying to register with an invalid index
589 with pytest.raises(TypeError):
590 StateUpdateMethod.register("foo", lazy_updater, index="not an index")
591
592 # reset to state before the test
593 StateUpdateMethod.stateupdaters = before
594
595
596 @pytest.mark.codegen_independent
597 def test_determination():
598 """
599 Test the determination of suitable state updaters.
600 """
601 # To save some typing
602 apply_stateupdater = StateUpdateMethod.apply_stateupdater
603
604 eqs = Equations("dv/dt = -v / (10*ms) : 1")
605 # Just make sure that state updaters know about the two state variables
606 variables = {"v": Variable(name="v"), "w": Variable(name="w")}
607
608 # all methods should work for these equations.
609 # First, specify them explicitly (using the object)
610 for integrator in (
611 linear,
612 euler,
613 exponential_euler, # TODO: Removed "independent" here due to the issue in sympy 0.7.4
614 rk2,
615 rk4,
616 heun,
617 milstein,
618 ):
619 with catch_logs() as logs:
620 returned = apply_stateupdater(eqs, variables, method=integrator)
621 assert len(logs) == 0, (
622 f"Got {len(logs)} unexpected warnings: {str([l[2] for l in logs])}"
623 )
624
625 # Equation with multiplicative noise, only milstein and heun should work
626 eqs = Equations("dv/dt = -v / (10*ms) + v*xi*second**-.5: 1")
627 for integrator in (linear, independent, euler, exponential_euler, rk2, rk4):
628 with pytest.raises(UnsupportedEquationsException):
629 apply_stateupdater(eqs, variables, integrator)
630
631 for integrator in (heun, milstein):
632 with catch_logs() as logs:
633 returned = apply_stateupdater(eqs, variables, method=integrator)
634 assert len(logs) == 0, (
635 f"Got {len(logs)} unexpected warnings: {str([l[2] for l in logs])}"
636 )
637
638 # Arbitrary functions (converting equations into abstract code) should
639 # always work
640 my_stateupdater = lambda eqs, vars, options: "x_new = x"
641 with catch_logs() as logs:
642 returned = apply_stateupdater(eqs, variables, method=my_stateupdater)
643 # No warning here
644 assert len(logs) == 0
645
646 # Specification with names
647 eqs = Equations("dv/dt = -v / (10*ms) : 1")
648 for name, integrator in [
649 ("exact", exact),
650 ("linear", linear),
651 ("euler", euler),
652 # ('independent', independent), #TODO: Removed "independent" here due to the issue in sympy 0.7.4
653 ("exponential_euler", exponential_euler),
654 ("rk2", rk2),
655 ("rk4", rk4),
656 ("heun", heun),
657 ("milstein", milstein),
658 ]:
659 with catch_logs() as logs:
660 returned = apply_stateupdater(eqs, variables, method=name)
661 # No warning here
662 assert len(logs) == 0
663
664 # Now all except heun and milstein should refuse to work
665 eqs = Equations("dv/dt = -v / (10*ms) + v*xi*second**-.5: 1")
666 for name in [
667 "linear",
668 "exact",
669 "independent",
670 "euler",
671 "exponential_euler",
672 "rk2",
673 "rk4",
674 ]:
675 with pytest.raises(UnsupportedEquationsException):
676 apply_stateupdater(eqs, variables, method=name)
677
678 # milstein should work
679 with catch_logs() as logs:
680 apply_stateupdater(eqs, variables, method="milstein")
681 assert len(logs) == 0
682
683 # heun should work
684 with catch_logs() as logs:
685 apply_stateupdater(eqs, variables, method="heun")
686 assert len(logs) == 0
687
688 # non-existing name
689 with pytest.raises(ValueError):
690 apply_stateupdater(eqs, variables, method="does_not_exist")
691
692 # Automatic state updater choice should return linear for linear equations,
693 # euler for non-linear, non-stochastic equations and equations with
694 # additive noise, heun for equations with multiplicative noise
695 # Because it is somewhat fragile, the "independent" state updater is not
696 # included in this list
697 all_methods = ["linear", "exact", "exponential_euler", "euler", "heun", "milstein"]
698 eqs = Equations("dv/dt = -v / (10*ms) : 1")
699 with catch_logs(log_level=logging.INFO) as logs:
700 apply_stateupdater(eqs, variables, all_methods)
701 assert len(logs) == 1
702 assert ("linear" in logs[0][2]) or ("exact" in logs[0][2])
703
704 # This is conditionally linear
705 eqs = Equations(
706 """dv/dt = -(v + w**2)/ (10*ms) : 1
707 dw/dt = -w/ (10*ms) : 1"""
708 )
709 with catch_logs(log_level=logging.INFO) as logs:
710 apply_stateupdater(eqs, variables, all_methods)
711 assert len(logs) == 1
712 assert "exponential_euler" in logs[0][2]
713
714 # # Do not test for now
715 # eqs = Equations('dv/dt = sin(t) / (10*ms) : 1')
716 # assert apply_stateupdater(eqs, variables) is independent
717
718 eqs = Equations("dv/dt = -sqrt(v) / (10*ms) : 1")
719 with catch_logs(log_level=logging.INFO) as logs:
720 apply_stateupdater(eqs, variables, all_methods)
721 assert len(logs) == 1
722 assert "'euler'" in logs[0][2]
723
724 eqs = Equations("dv/dt = -v / (10*ms) + 0.1*second**-.5*xi: 1")
725 with catch_logs(log_level=logging.INFO) as logs:
726 apply_stateupdater(eqs, variables, all_methods)
727 assert len(logs) == 1
728 assert "'euler'" in logs[0][2]
729
730 eqs = Equations("dv/dt = -v / (10*ms) + v*0.1*second**-.5*xi: 1")
731 with catch_logs(log_level=logging.INFO) as logs:
732 apply_stateupdater(eqs, variables, all_methods)
733 assert len(logs) == 1
734 assert "'heun'" in logs[0][2]
735
736
737 @pytest.mark.standalone_compatible
738 def test_subexpressions_basic():
739 """
740 Make sure that the integration of a (non-stochastic) differential equation
741 does not depend on whether it's formulated using subexpressions.
742 """
743 # no subexpression
744 eqs1 = "dv/dt = (-v + sin(2*pi*100*Hz*t)) / (10*ms) : 1"
745 # same with subexpression
746 eqs2 = """dv/dt = I / (10*ms) : 1
747 I = -v + sin(2*pi*100*Hz*t): 1"""
748 method = "euler"
749 G1 = NeuronGroup(1, eqs1, method=method)
750 G1.v = 1
751 G2 = NeuronGroup(1, eqs2, method=method)
752 G2.v = 1
753 mon1 = StateMonitor(G1, "v", record=True)
754 mon2 = StateMonitor(G2, "v", record=True)
755 run(10 * ms)
756 assert_equal(mon1.v, mon2.v, f"Results for method {method} differed!")
757
758
759 def test_subexpressions():
760 """
761 Make sure that the integration of a (non-stochastic) differential equation
762 does not depend on whether it's formulated using subexpressions.
763 """
764 # no subexpression
765 eqs1 = "dv/dt = (-v + sin(2*pi*100*Hz*t)) / (10*ms) : 1"
766 # same with subexpression
767 eqs2 = """dv/dt = I / (10*ms) : 1
768 I = -v + sin(2*pi*100*Hz*t): 1"""
769
770 methods = [
771 "exponential_euler",
772 "rk2",
773 "rk4",
774 ] # euler is tested in test_subexpressions_basic
775 for method in methods:
776 G1 = NeuronGroup(1, eqs1, method=method)
777 G1.v = 1
778 G2 = NeuronGroup(1, eqs2, method=method)
779 G2.v = 1
780 mon1 = StateMonitor(G1, "v", record=True)
781 mon2 = StateMonitor(G2, "v", record=True)
782 net = Network(G1, mon1, G2, mon2)
783 net.run(10 * ms)
784 assert_equal(mon1.v, mon2.v, f"Results for method {method} differed!")
785
786
787 @pytest.mark.codegen_independent
788 def test_locally_constant_check():
789 default_dt = defaultclock.dt
790 # The linear state update can handle additive time-dependent functions
791 # (e.g. a TimedArray) but only if it can be safely assumed that the function
792 # is constant over a single time check
793 ta0 = TimedArray(np.array([1]), dt=default_dt) # ok
794 ta1 = TimedArray(np.array([1]), dt=2 * default_dt) # ok
795 ta2 = TimedArray(np.array([1]), dt=default_dt / 2) # not ok
796 ta3 = TimedArray(np.array([1]), dt=default_dt * 1.5) # not ok
797
798 for ta_func, ok in zip([ta0, ta1, ta2, ta3], [True, True, False, False]):
799 # additive
800 G = NeuronGroup(
801 1,
802 "dv/dt = -v/(10*ms) + ta(t)*Hz : 1",
803 method="exact",
804 namespace={"ta": ta_func},
805 )
806 net = Network(G)
807 if ok:
808 # This should work
809 net.run(0 * ms)
810 else:
811 # This should not
812 with catch_logs():
813 with pytest.raises(BrianObjectException) as exc:
814 net.run(0 * ms)
815 assert exc.errisinstance(UnsupportedEquationsException)
816
817 # multiplicative
818 G = NeuronGroup(
819 1, "dv/dt = -v*ta(t)/(10*ms) : 1", method="exact", namespace={"ta": ta_func}
820 )
821 net = Network(G)
822 if ok:
823 # This should work
824 net.run(0 * ms)
825 else:
826 # This should not
827 with catch_logs():
828 with pytest.raises(BrianObjectException) as exc:
829 net.run(0 * ms)
830 assert exc.errisinstance(UnsupportedEquationsException)
831
832 # If the argument is more than just "t", we cannot guarantee that it is
833 # actually locally constant
834 G = NeuronGroup(
835 1, "dv/dt = -v*ta(t/2.0)/(10*ms) : 1", method="exact", namespace={"ta": ta0}
836 )
837 net = Network(G)
838 with pytest.raises(BrianObjectException) as exc:
839 net.run(0 * ms)
840 assert exc_isinstance(exc, UnsupportedEquationsException)
841
842 # Arbitrary functions are not constant over a time step
843 G = NeuronGroup(1, "dv/dt = -v/(10*ms) + sin(2*pi*100*Hz*t)*Hz : 1", method="exact")
844 net = Network(G)
845 with pytest.raises(BrianObjectException) as exc:
846 net.run(0 * ms)
847 assert exc_isinstance(exc, UnsupportedEquationsException)
848
849 # Stateful functions aren't either
850 G = NeuronGroup(1, "dv/dt = -v/(10*ms) + rand()*Hz : 1", method="exact")
851 net = Network(G)
852 with pytest.raises(BrianObjectException) as exc:
853 net.run(0 * ms)
854 assert exc_isinstance(exc, UnsupportedEquationsException)
855
856 # Neither is "t" itself
857 G = NeuronGroup(1, "dv/dt = -v/(10*ms) + t/second**2 : 1", method="exact")
858 net = Network(G)
859 with pytest.raises(BrianObjectException) as exc:
860 net.run(0 * ms)
861 assert exc_isinstance(exc, UnsupportedEquationsException)
862
863 # But if the argument is not referring to t, all should be well
864 G = NeuronGroup(
865 1, "dv/dt = -v/(10*ms) + sin(2*pi*100*Hz*5*second)*Hz : 1", method="exact"
866 )
867 net = Network(G)
868 net.run(0 * ms)
869
870
871 def test_refractory():
872 # Compare integration with and without the addition of refractoriness --
873 # note that the cell here is not spiking, so it should never be in the
874 # refractory period and therefore the results should be exactly identical
875 # with and without (unless refractory)
876 eqs_base = "dv/dt = -v/(10*ms) : 1"
877 for method in [
878 "linear",
879 "exact",
880 "independent",
881 "euler",
882 "exponential_euler",
883 "rk2",
884 "rk4",
885 ]:
886 G_no_ref = NeuronGroup(10, eqs_base, method=method)
887 G_no_ref.v = "(i+1)/11."
888 G_ref = NeuronGroup(
889 10, f"{eqs_base}(unless refractory)", refractory=1 * ms, method=method
890 )
891 G_ref.v = "(i+1)/11."
892 net = Network(G_ref, G_no_ref)
893 net.run(10 * ms)
894 assert_allclose(
895 G_no_ref.v[:],
896 G_ref.v[:],
897 err_msg="Results with and without refractoriness differ for method %s."
898 % method,
899 )
900
901
902 def test_refractory_stochastic(fake_randn_randn_fixture):
903 eqs_base = "dv/dt = -v/(10*ms) + second**-.5*xi : 1"
904
905 for method in ["euler", "heun", "milstein"]:
906 G_no_ref = NeuronGroup(10, eqs_base, method=method)
907 G_no_ref.v = "(i+1)/11."
908 G_ref = NeuronGroup(
909 10, f"{eqs_base} (unless refractory)", refractory=1 * ms, method=method
910 )
911 G_ref.v = "(i+1)/11."
912 net = Network(G_ref, G_no_ref)
913 net.run(10 * ms)
914 assert_allclose(
915 G_no_ref.v[:],
916 G_ref.v[:],
917 err_msg="Results with and without refractoriness differ for method %s."
918 % method,
919 )
920
921
922 @pytest.mark.standalone_compatible
923 def test_check_for_invalid_values_linear_integrator():
924 # A differential equation that cannot be solved by the linear
925 # integrator should return nan values to warn the user, and not silently
926 # return incorrect values. See discussion on
927 # https://github.com/brian-team/brian2/issues/626
928 a = 0.0 / ms
929 b = 1.0 / ms
930 c = -0.5 / ms
931 d = -0.1 / ms
932 eqs = """
933 dx/dt = a * x + b * y : 1
934 dy/dt = c * x + d * y : 1
935 """
936 G = NeuronGroup(
937 1,
938 eqs,
939 threshold="x > 100",
940 reset="x = 0",
941 method="exact",
942 method_options={"simplify": False},
943 )
944 G.x = 1
945 BrianLogger._log_messages.clear() # because the log message is set to be shown only once
946 with catch_logs() as clog:
947 try:
948 run(1 * ms)
949 # this check allows for the possibility that we improve the linear
950 # integrator in the future so that it can handle this equation
951 if numpy.isnan(G.x[0]):
952 assert "invalid_values" in repr(clog)
953 else:
954 assert G.x[0] != 0
955 except BrianObjectException as exc:
956 assert isinstance(exc.__cause__, UnsupportedEquationsException)
957
958
959 if __name__ == "__main__":
960 import time
961
962 from brian2 import prefs
963
964 start = time.time()
965
966 test_determination()
967 test_explicit_stateupdater_parsing()
968 test_non_autonomous_equations()
969 test_str_repr()
970 test_multiplicative_noise()
971 test_multiple_noise_variables_basic()
972 test_multiple_noise_variables_extended()
973 test_temporary_variables()
974 test_temporary_variables2()
975 test_integrator_code()
976 test_integrator_code2()
977 test_illegal_calls()
978 test_priority()
979 test_registration()
980 test_subexpressions()
981 test_locally_constant_check()
982 test_refractory()
983 # # Need the fake random number generator from tests/conftest.py
984 # test_refractory_stochastic()
985 # test_multiple_noise_variables_deterministic_noise()
986 # test_pure_noise_deterministic()
987 test_check_for_invalid_values_linear_integrator()
988 print("Tests took", time.time() - start)