Debian Codegraph @

brian2/tests/test_neurongroup.py

raw
1 import uuid
2
3 import numpy as np
4 import pytest
5 import sympy
6 from numpy.testing import assert_equal
7
8 from brian2.core.base import BrianObjectException
9 from brian2.core.clocks import defaultclock
10 from brian2.core.magic import run
11 from brian2.core.network import Network
12 from brian2.core.preferences import prefs
13 from brian2.core.variables import linked_var
14 from brian2.devices.device import device, get_device, seed
15 from brian2.equations.equations import Equations
16 from brian2.groups.group import get_dtype
17 from brian2.groups.neurongroup import NeuronGroup
18 from brian2.monitors.statemonitor import StateMonitor
19 from brian2.synapses.synapses import Synapses
20 from brian2.tests.utils import assert_allclose, exc_isinstance
21 from brian2.units.allunits import second, volt
22 from brian2.units.fundamentalunits import (
23 DIMENSIONLESS,
24 DimensionMismatchError,
25 have_same_dimensions,
26 )
27 from brian2.units.stdunits import Hz, ms, mV
28 from brian2.units.unitsafefunctions import linspace
29 from brian2.utils.logger import catch_logs
30
31
32 @pytest.mark.codegen_independent
33 def test_creation():
34 """
35 A basic test that creating a NeuronGroup works.
36 """
37 G = NeuronGroup(42, model="dv/dt = -v/(10*ms) : 1", reset="v=0", threshold="v>1")
38 assert len(G) == 42
39
40 # Test some error conditions
41 # --------------------------
42
43 # Model equations as first argument (no number of neurons)
44 with pytest.raises(TypeError):
45 NeuronGroup("dv/dt = 5*Hz : 1", 1)
46
47 # Not a number as first argument
48 with pytest.raises(TypeError):
49 NeuronGroup(object(), "dv/dt = 5*Hz : 1")
50
51 # Illegal number
52 with pytest.raises(ValueError):
53 NeuronGroup(0, "dv/dt = 5*Hz : 1")
54
55 # neither string nor Equations object as model description
56 with pytest.raises(TypeError):
57 NeuronGroup(1, object())
58
59
60 @pytest.mark.codegen_independent
61 def test_integer_variables_and_mod():
62 """
63 Test that integer operations and variable definitions work.
64 """
65 n = 10
66 eqs = """
67 dv/dt = (a+b+j+k)/second : 1
68 j = i%n : integer
69 k = i//n : integer
70 a = v%(i+1) : 1
71 b = v%(2*v) : 1
72 """
73 G = NeuronGroup(100, eqs)
74 G.v = np.random.rand(len(G))
75 run(1 * ms)
76 assert_equal(G.j[:], G.i[:] % n)
77 assert_equal(G.k[:], G.i[:] // n)
78 assert_equal(G.a[:], G.v[:] % (G.i[:] + 1))
79
80
81 @pytest.mark.codegen_independent
82 def test_variables():
83 """
84 Test the correct creation of the variables dictionary.
85 """
86 G = NeuronGroup(1, "dv/dt = -v/(10*ms) : 1")
87 assert all((x in G.variables) for x in ["v", "t", "dt", "t_in_timesteps"])
88 assert "not_refractory" not in G.variables and "lastspike" not in G.variables
89
90 G = NeuronGroup(1, "dv/dt = -v/tau + xi*tau**-0.5: 1")
91 assert "tau" not in G.variables and "xi" in G.variables
92
93 # NeuronGroup with refractoriness
94 G = NeuronGroup(1, "dv/dt = -v/(10*ms) : 1", refractory=5 * ms)
95 assert "not_refractory" in G.variables and "lastspike" in G.variables
96
97
98 @pytest.mark.codegen_independent
99 def test_variableview_calculations():
100 # Check that you can directly calculate with "variable views"
101 G = NeuronGroup(
102 10,
103 """
104 x : 1
105 y : volt
106 idx : integer
107 """,
108 )
109 G.x = np.arange(10)
110 G.y = np.arange(10)[::-1] * mV
111 G.idx = np.arange(10, dtype=int)
112 assert_allclose(G.x * G.y, np.arange(10) * np.arange(10)[::-1] * mV)
113 assert_allclose(-G.x, -np.arange(10))
114 assert_allclose(-G.y, -np.arange(10)[::-1] * mV)
115
116 assert_allclose(3 * G.x, 3 * np.arange(10))
117 assert_allclose(3 * G.y, 3 * np.arange(10)[::-1] * mV)
118 assert_allclose(G.x * 3, 3 * np.arange(10))
119 assert_allclose(G.y * 3, 3 * np.arange(10)[::-1] * mV)
120 assert_allclose(G.x / 2.0, np.arange(10) / 2.0)
121 assert_allclose(G.y / 2, np.arange(10)[::-1] * mV / 2)
122 assert_equal(G.idx % 2, np.arange(10, dtype=int) % 2)
123 assert_allclose(G.x + 2, 2 + np.arange(10))
124 assert_allclose(G.y + 2 * mV, 2 * mV + np.arange(10)[::-1] * mV)
125 assert_allclose(2 + G.x, 2 + np.arange(10))
126 assert_allclose(2 * mV + G.y, 2 * mV + np.arange(10)[::-1] * mV)
127 assert_allclose(G.x - 2, np.arange(10) - 2)
128 assert_allclose(G.y - 2 * mV, np.arange(10)[::-1] * mV - 2 * mV)
129 assert_allclose(2 - G.x, 2 - np.arange(10))
130 assert_allclose(2 * mV - G.y, 2 * mV - np.arange(10)[::-1] * mV)
131 assert_allclose(G.x**2, np.arange(10) ** 2)
132 assert_allclose(G.y**2, (np.arange(10)[::-1] * mV) ** 2)
133 assert_allclose(2**G.x, 2 ** np.arange(10))
134
135 # incorrect units
136 with pytest.raises(DimensionMismatchError):
137 G.x + G.y
138 with pytest.raises(DimensionMismatchError):
139 G.x[:] + G.y
140 with pytest.raises(DimensionMismatchError):
141 G.x + G.y[:]
142 with pytest.raises(DimensionMismatchError):
143 G.x + 3 * mV
144 with pytest.raises(DimensionMismatchError):
145 3 * mV + G.x
146 with pytest.raises(DimensionMismatchError):
147 G.y + 3
148 with pytest.raises(DimensionMismatchError):
149 3 + G.y
150 with pytest.raises(TypeError):
151 2**G.y # raising to a power with units
152
153
154 @pytest.mark.standalone_compatible
155 def test_variableview_properties():
156 G = NeuronGroup(
157 10,
158 """
159 x : 1
160 y : volt
161 idx : integer
162 """,
163 )
164 # The below properties should not require access to the values
165 G.x = "rand()"
166 G.y = "rand()*mV"
167 G.idx = "int(rand()*10)"
168
169 assert have_same_dimensions(G.x.unit, DIMENSIONLESS)
170 assert have_same_dimensions(G.y.unit, volt)
171 assert have_same_dimensions(G.idx.unit, DIMENSIONLESS)
172
173 assert G.x.shape == G.y.shape == G.idx.shape == (10,)
174 assert G.x.ndim == G.y.ndim == G.idx.ndim == 1
175 assert G.x.dtype == G.y.dtype == prefs.core.default_float_dtype
176 assert G.idx.dtype == np.int32
177
178
179 @pytest.mark.codegen_independent
180 def test_variableview_inplace_calculations():
181 # Check that you can directly do in-place calculation with "variable views"
182 G = NeuronGroup(
183 10,
184 """
185 x : 1
186 y : volt
187 """,
188 )
189 x_vals = np.arange(10)
190 y_vals = np.arange(10)[::-1] * mV
191 G.x[:] = x_vals
192 G.y[:] = y_vals
193
194 # Addition
195 G.x += 1
196 G.y += 1 * mV
197 assert_allclose(G.x[:], x_vals + 1)
198 assert_allclose(G.y[:], y_vals + 1 * mV)
199 G.y_ += float(1 * mV)
200 assert_allclose(G.y[:], y_vals + 2 * mV)
201 with pytest.raises(DimensionMismatchError):
202 G.x += 1 * mV
203 with pytest.raises(DimensionMismatchError):
204 G.y += 1
205 with pytest.raises(DimensionMismatchError):
206 G.y += 1 * ms
207 G.x[:] = x_vals
208 G.y[:] = y_vals
209
210 # Subtraction
211 G.x -= 1
212 G.y -= 1 * mV
213 assert_allclose(G.x[:], x_vals - 1)
214 assert_allclose(G.y[:], y_vals - 1 * mV)
215 G.y_ -= float(1 * mV)
216 assert_allclose(G.y[:], y_vals - 2 * mV)
217 with pytest.raises(DimensionMismatchError):
218 G.x -= 1 * mV
219 with pytest.raises(DimensionMismatchError):
220 G.y -= 1
221 with pytest.raises(DimensionMismatchError):
222 G.y -= 1 * ms
223 G.x[:] = x_vals
224 G.y[:] = y_vals
225
226 # Multiplication
227 G.x *= 2
228 G.y *= 2
229 assert_allclose(G.x[:], x_vals * 2)
230 assert_allclose(G.y[:], y_vals * 2)
231 with pytest.raises(DimensionMismatchError):
232 G.x *= 2 * mV
233 with pytest.raises(DimensionMismatchError):
234 G.y *= 1 * mV
235 G.x[:] = x_vals
236 G.y[:] = y_vals
237
238 # Division
239 G.x /= 2
240 G.y /= 2
241 assert_allclose(G.x[:], x_vals / 2)
242 assert_allclose(G.y[:], y_vals / 2)
243 with pytest.raises(DimensionMismatchError):
244 G.x /= 2 * mV
245 with pytest.raises(DimensionMismatchError):
246 G.y /= 1 * mV
247 G.x[:] = x_vals
248 G.y[:] = y_vals
249
250 # Floor division
251 G.x //= 2
252 # This is very sensitive to rounding issues, so increase the value a bit
253 G.y += 0.01 * mV
254 G.y //= 0.001
255 assert_allclose(G.x[:], x_vals // 2)
256 assert_allclose(G.y[:], y_vals // 0.001)
257 with pytest.raises(DimensionMismatchError):
258 G.x //= 2 * mV
259 with pytest.raises(DimensionMismatchError):
260 G.y //= 1 * mV
261 G.x[:] = x_vals
262 G.y[:] = y_vals
263
264 # Modulo
265 G.x %= 2
266 G.y %= 3.3 * mV
267 assert_allclose(G.x[:], x_vals % 2)
268 assert_allclose(G.y[:], y_vals % (3.3 * mV))
269 with pytest.raises(DimensionMismatchError):
270 G.y %= 2
271 with pytest.raises(DimensionMismatchError):
272 G.y %= 2 * ms
273 G.x[:] = x_vals
274 G.y[:] = y_vals
275
276 # Power
277 G.x **= 2
278 assert_allclose(G.x[:], x_vals**2)
279 with pytest.raises(DimensionMismatchError):
280 G.y **= 2
281
282
283 @pytest.mark.standalone_compatible
284 def test_stochastic_variable():
285 """
286 Test that a NeuronGroup with a stochastic variable can be simulated. Only
287 makes sure no error occurs.
288 """
289 tau = 10 * ms
290 G = NeuronGroup(1, "dv/dt = -v/tau + xi*tau**-0.5: 1")
291 run(defaultclock.dt)
292
293
294 @pytest.mark.standalone_compatible
295 def test_stochastic_variable_multiplicative():
296 """
297 Test that a NeuronGroup with multiplicative noise can be simulated. Only
298 makes sure no error occurs.
299 """
300 mu = 0.5 / second # drift
301 sigma = 0.1 / second # diffusion
302 G = NeuronGroup(
303 1, "dX/dt = (mu - 0.5*second*sigma**2)*X + X*sigma*xi*second**.5: 1"
304 )
305 run(defaultclock.dt)
306
307
308 def test_scalar_variable():
309 """
310 Test the correct handling of scalar variables
311 """
312 tau = 10 * ms
313 G = NeuronGroup(
314 10,
315 """
316 E_L : volt (shared)
317 s2 : 1 (shared)
318 dv/dt = (E_L - v) / tau : volt
319 """,
320 )
321 # Setting should work in these ways
322 G.E_L = -70 * mV
323 assert_allclose(G.E_L[:], -70 * mV)
324 G.E_L[:] = -60 * mV
325 assert_allclose(G.E_L[:], -60 * mV)
326 G.E_L = "E_L + s2*mV - 10*mV"
327 assert_allclose(G.E_L[:], -70 * mV)
328 G.E_L[:] = "-75*mV"
329 assert_allclose(G.E_L[:], -75 * mV)
330 net = Network(G)
331 net.run(defaultclock.dt)
332
333
334 @pytest.mark.standalone_compatible
335 def test_referred_scalar_variable():
336 """
337 Test the correct handling of referred scalar variables in subexpressions
338 """
339 G = NeuronGroup(
340 10,
341 """
342 out = sin(2*pi*t*freq) + x: 1
343 x : 1
344 freq : Hz (shared)
345 """,
346 )
347 G.freq = 1 * Hz
348 G.x = np.arange(10)
349 G2 = NeuronGroup(10, "")
350 G2.variables.add_reference("out", G)
351 run(0.25 * second)
352 assert_allclose(G2.out[:], np.arange(10) + 1)
353
354
355 @pytest.mark.standalone_compatible
356 def test_linked_variable_correct():
357 """
358 Test correct uses of linked variables.
359 """
360 tau = 10 * ms
361 G1 = NeuronGroup(10, "dv/dt = -v / tau : volt")
362 G1.v = linspace(0 * mV, 20 * mV, 10)
363 G2 = NeuronGroup(10, "v : volt (linked)")
364 G2.v = linked_var(G1.v)
365 mon1 = StateMonitor(G1, "v", record=True)
366 mon2 = StateMonitor(G2, "v", record=True)
367 run(10 * ms)
368 assert_allclose(mon1.v[:, :], mon2.v[:, :])
369 # Make sure that printing the variable values works
370 assert len(str(G2.v)) > 0
371 assert len(repr(G2.v)) > 0
372 assert len(str(G2.v[:])) > 0
373 assert len(repr(G2.v[:])) > 0
374
375
376 @pytest.mark.codegen_independent
377 def test_linked_variable_incorrect():
378 """
379 Test incorrect uses of linked variables.
380 """
381 G1 = NeuronGroup(
382 10,
383 """
384 x : volt
385 y : 1
386 """,
387 )
388 G2 = NeuronGroup(20, """x: volt""")
389 G3 = NeuronGroup(
390 10,
391 """
392 l : volt (linked)
393 not_linked : volt
394 """,
395 )
396
397 # incorrect unit
398 with pytest.raises(DimensionMismatchError):
399 setattr(G3, "l", linked_var(G1.y))
400 # incorrect group size
401 with pytest.raises(ValueError):
402 setattr(G3, "l", linked_var(G2.x))
403 # incorrect use of linked_var
404 with pytest.raises(ValueError):
405 setattr(G3, "l", linked_var(G1.x, "x"))
406 with pytest.raises(ValueError):
407 setattr(G3, "l", linked_var(G1))
408 # Not a linked variable
409 with pytest.raises(TypeError):
410 setattr(G3, "not_linked", linked_var(G1.x))
411
412
413 @pytest.mark.standalone_compatible
414 def test_linked_variable_scalar():
415 """
416 Test linked variable from a size 1 group.
417 """
418 G1 = NeuronGroup(1, "dx/dt = -x / (10*ms) : 1")
419 G2 = NeuronGroup(
420 10,
421 """
422 dy/dt = (-y + x) / (20*ms) : 1
423 x : 1 (linked)
424 """,
425 )
426 G1.x = 1
427 G2.y = np.linspace(0, 1, 10)
428 G2.x = linked_var(G1.x)
429 mon = StateMonitor(G2, "y", record=True)
430 # We don't test anything for now, except that it runs without raising an
431 # error
432 run(defaultclock.dt)
433 # Make sure that printing the variable values works
434 assert len(str(G2.x)) > 0
435 assert len(repr(G2.x)) > 0
436 assert len(str(G2.x[:])) > 0
437 assert len(repr(G2.x[:])) > 0
438 assert np.isscalar(G2.x[:])
439 # Check that subgroups work correctly (see github issue #916)
440 sg1 = G2[:5]
441 sg2 = G2[5:]
442 assert sg1.x == G2.x
443 assert sg2.x == G2.x
444
445
446 @pytest.mark.codegen_independent
447 def test_linked_variable_indexed():
448 """
449 Test linking a variable with an index specified as an array
450 """
451 G = NeuronGroup(
452 10,
453 """
454 x : 1
455 y : 1 (linked)
456 """,
457 )
458
459 G.x = np.arange(10) * 0.1
460 G.y = linked_var(G.x, index=np.arange(10)[::-1])
461 # G.y should refer to an inverted version of G.x
462 assert_allclose(G.y[:], np.arange(10)[::-1] * 0.1)
463
464
465 @pytest.mark.codegen_independent
466 def test_linked_variable_index_variable():
467 """
468 Test linking a variable with an index specified as an array
469 """
470 G = NeuronGroup(
471 10,
472 """
473 x : 1
474 index_var : integer
475 not_an_index_var : 1
476 y : 1 (linked)
477 """,
478 )
479
480 G.x = np.arange(10) * 0.1
481 with pytest.raises(TypeError):
482 G.y = linked_var(G.x, index="not_an_index_var")
483 G.y = linked_var(G.x, index="index_var")
484 G.index_var = np.arange(10)[::-1]
485 # G.y should refer to an inverted version of G.x
486 assert_allclose(G.y[:], np.arange(10)[::-1] * 0.1)
487
488
489 @pytest.mark.codegen_independent
490 def test_linked_variable_repeat():
491 """
492 Test a "repeat"-like connection between two groups of different size
493 """
494 G1 = NeuronGroup(5, "w : 1")
495 G2 = NeuronGroup(10, "v : 1 (linked)")
496 G2.v = linked_var(G1.w, index=np.arange(5).repeat(2))
497 G1.w = np.arange(5) * 0.1
498 assert_allclose(G2.v[:], np.arange(5).repeat(2) * 0.1)
499
500
501 @pytest.mark.codegen_independent
502 def test_linked_double_linked1():
503 """
504 Linked to a linked variable, without indices
505 """
506 G1 = NeuronGroup(10, "x : 1")
507 G2 = NeuronGroup(10, "y : 1 (linked)")
508 G2.y = linked_var(G1.x)
509 G3 = NeuronGroup(10, "z: 1 (linked)")
510 G3.z = linked_var(G2.y)
511
512 G1.x = np.arange(10)
513 assert_allclose(G3.z[:], np.arange(10))
514
515
516 @pytest.mark.codegen_independent
517 def test_linked_double_linked2():
518 """
519 Linked to a linked variable, first without indices, second with indices
520 """
521
522 G1 = NeuronGroup(5, "x : 1")
523 G2 = NeuronGroup(5, "y : 1 (linked)")
524 G2.y = linked_var(G1.x)
525 G3 = NeuronGroup(10, "z: 1 (linked)")
526 G3.z = linked_var(G2.y, index=np.arange(5).repeat(2))
527
528 G1.x = np.arange(5) * 0.1
529 assert_allclose(G3.z[:], np.arange(5).repeat(2) * 0.1)
530
531
532 @pytest.mark.codegen_independent
533 def test_linked_double_linked3():
534 """
535 Linked to a linked variable, first with indices, second without indices
536 """
537 G1 = NeuronGroup(5, "x : 1")
538 G2 = NeuronGroup(10, "y : 1 (linked)")
539 G2.y = linked_var(G1.x, index=np.arange(5).repeat(2))
540 G3 = NeuronGroup(10, "z: 1 (linked)")
541 G3.z = linked_var(G2.y)
542
543 G1.x = np.arange(5) * 0.1
544 assert_allclose(G3.z[:], np.arange(5).repeat(2) * 0.1)
545
546
547 @pytest.mark.codegen_independent
548 def test_linked_double_linked4():
549 """
550 Linked to a linked variable, both use indices
551 """
552 G1 = NeuronGroup(5, "x : 1")
553 G2 = NeuronGroup(10, "y : 1 (linked)")
554 G2.y = linked_var(G1.x, index=np.arange(5).repeat(2))
555 G3 = NeuronGroup(10, "z: 1 (linked)")
556 G3.z = linked_var(G2.y, index=np.arange(10)[::-1])
557
558 G1.x = np.arange(5) * 0.1
559 assert_allclose(G3.z[:], np.arange(5).repeat(2)[::-1] * 0.1)
560
561
562 @pytest.mark.codegen_independent
563 def test_linked_triple_linked():
564 """
565 Link to a linked variable that links to a linked variable, all use indices
566 """
567 G1 = NeuronGroup(2, "a : 1")
568
569 G2 = NeuronGroup(4, "b : 1 (linked)")
570 G2.b = linked_var(G1.a, index=np.arange(2).repeat(2))
571
572 G3 = NeuronGroup(4, "c: 1 (linked)")
573 G3.c = linked_var(G2.b, index=np.arange(4)[::-1])
574
575 G4 = NeuronGroup(8, "d: 1 (linked)")
576 G4.d = linked_var(G3.c, index=np.arange(4).repeat(2))
577
578 G1.a = np.arange(2) * 0.1
579 assert_allclose(G4.d[:], np.arange(2).repeat(2)[::-1].repeat(2) * 0.1)
580
581
582 @pytest.mark.codegen_independent
583 def test_linked_subgroup():
584 """
585 Test linking a variable from a subgroup
586 """
587 G1 = NeuronGroup(10, "x : 1")
588 G1.x = np.arange(10) * 0.1
589 G2 = G1[3:8]
590 G3 = NeuronGroup(5, "y:1 (linked)")
591 G3.y = linked_var(G2.x)
592
593 assert_allclose(G3.y[:], (np.arange(5) + 3) * 0.1)
594
595
596 @pytest.mark.codegen_independent
597 def test_linked_subgroup2():
598 """
599 Test linking a variable from a subgroup with indexing
600 """
601 G1 = NeuronGroup(10, "x : 1")
602 G1.x = np.arange(10) * 0.1
603 G2 = G1[3:8]
604 G3 = NeuronGroup(10, "y:1 (linked)")
605 G3.y = linked_var(G2.x, index=np.arange(5).repeat(2))
606
607 assert_allclose(G3.y[:], (np.arange(5) + 3).repeat(2) * 0.1)
608
609
610 @pytest.mark.standalone_compatible
611 def test_linked_subexpression():
612 """
613 Test a subexpression referring to a linked variable.
614 """
615 G = NeuronGroup(2, "dv/dt = 100*Hz : 1", threshold="v>1", reset="v=0")
616 G.v = [0, 0.5]
617 G2 = NeuronGroup(
618 10,
619 """
620 I = clip(x, 0, inf) : 1
621 x : 1 (linked)
622 """,
623 )
624
625 G2.x = linked_var(G.v, index=np.array([0, 1]).repeat(5))
626 mon = StateMonitor(G2, "I", record=True)
627 run(5 * ms)
628
629 # Due to the linking, the first 5 and the second 5 recorded I vectors should
630 # be identical
631 assert all(all(mon[i].I == mon[0].I) for i in range(5))
632 assert all(all(mon[i + 5].I == mon[5].I) for i in range(5))
633
634
635 @pytest.mark.standalone_compatible
636 def test_linked_subexpression_2():
637 """
638 Test a linked variable referring to a subexpression without indices
639 """
640 G = NeuronGroup(
641 2,
642 """
643 dv/dt = 100*Hz : 1
644 I = clip(v, 0, inf) : 1
645 """,
646 threshold="v>1",
647 reset="v=0",
648 )
649 G.v = [0, 0.5]
650 G2 = NeuronGroup(2, """I_l : 1 (linked) """)
651
652 G2.I_l = linked_var(G.I)
653 mon1 = StateMonitor(G, "I", record=True)
654 mon = StateMonitor(G2, "I_l", record=True)
655 run(5 * ms)
656
657 assert all(mon[0].I_l == mon1[0].I)
658 assert all(mon[1].I_l == mon1[1].I)
659
660
661 @pytest.mark.standalone_compatible
662 def test_linked_subexpression_3():
663 """
664 Test a linked variable referring to a subexpression with indices
665 """
666 G = NeuronGroup(
667 2,
668 """
669 dv/dt = 100*Hz : 1
670 I = clip(v, 0, inf) : 1
671 """,
672 threshold="v>1",
673 reset="v=0",
674 )
675 G.v = [0, 0.5]
676 G2 = NeuronGroup(10, """I_l : 1 (linked) """)
677
678 G2.I_l = linked_var(G.I, index=np.array([0, 1]).repeat(5))
679 mon1 = StateMonitor(G, "I", record=True)
680 mon = StateMonitor(G2, "I_l", record=True)
681 run(5 * ms)
682
683 # Due to the linking, the first 5 and the second 5 recorded I vectors should
684 # refer to the
685 assert all(all(mon[i].I_l == mon1[0].I) for i in range(5))
686 assert all(all(mon[i + 5].I_l == mon1[1].I) for i in range(5))
687
688
689 def test_linked_subexpression_synapse():
690 """
691 Test a complicated setup (not unlikely when using brian hears)
692 """
693 G = NeuronGroup(2, "dv/dt = 100*Hz : 1", threshold="v>1", reset="v=0")
694 G.v = [0, 0.5]
695 G2 = NeuronGroup(
696 10,
697 """
698 I = clip(x, 0, inf) : 1
699 x : 1 (linked)
700 """,
701 )
702
703 # This will not be able to include references to `I` as `I_pre` etc., since
704 # the indirect indexing would have to change depending on the synapses
705 G2.x = linked_var(G.v, index=np.array([0, 1]).repeat(5))
706 S = Synapses(G2, G2, "")
707 S.connect("i==j")
708 assert "I" not in S.variables
709 assert "I_pre" not in S.variables
710 assert "I_post" not in S.variables
711 assert "x" not in S.variables
712 assert "x_pre" not in S.variables
713 assert "x_post" not in S.variables
714
715
716 @pytest.mark.codegen_independent
717 def test_linked_variable_indexed_incorrect():
718 """
719 Test errors when providing incorrect index arrays
720 """
721 G = NeuronGroup(
722 10,
723 """
724 x : 1
725 y : 1 (linked)
726 """,
727 )
728
729 G.x = np.arange(10) * 0.1
730 with pytest.raises(TypeError):
731 setattr(G, "y", linked_var(G.x, index=np.arange(10) * 1.0))
732 with pytest.raises(TypeError):
733 setattr(G, "y", linked_var(G.x, index=np.arange(10).reshape(5, 2)))
734 with pytest.raises(TypeError):
735 setattr(G, "y", linked_var(G.x, index=np.arange(5)))
736 with pytest.raises(ValueError):
737 setattr(G, "y", linked_var(G.x, index=np.arange(10) - 1))
738 with pytest.raises(ValueError):
739 setattr(G, "y", linked_var(G.x, index=np.arange(10) + 1))
740
741
742 @pytest.mark.codegen_independent
743 def test_linked_synapses():
744 """
745 Test linking to a synaptic variable (should raise an error).
746 """
747 G = NeuronGroup(10, "")
748 S = Synapses(G, G, "w:1")
749 S.connect()
750 G2 = NeuronGroup(100, "x : 1 (linked)")
751 with pytest.raises(NotImplementedError):
752 setattr(G2, "x", linked_var(S, "w"))
753
754
755 @pytest.mark.standalone_compatible
756 def test_linked_var_in_reset():
757 G1 = NeuronGroup(3, "x:1")
758 G2 = NeuronGroup(
759 3,
760 """
761 x_linked : 1 (linked)
762 y:1
763 """,
764 threshold="y>1",
765 reset="y=0; x_linked += 1",
766 )
767 G2.x_linked = linked_var(G1, "x")
768 G2.y = [0, 1.1, 0]
769 # In this context, x_linked should not be considered as a scalar variable
770 # and therefore the reset statement should be allowed
771 run(3 * defaultclock.dt)
772 assert_allclose(G1.x[:], [0, 1, 0])
773
774
775 @pytest.mark.standalone_compatible
776 def test_linked_var_in_reset_size_1():
777 G1 = NeuronGroup(1, "x:1")
778 G2 = NeuronGroup(
779 1,
780 """
781 x_linked : 1 (linked)
782 y:1
783 """,
784 threshold="y>1",
785 reset="y=0; x_linked += 1",
786 )
787 G2.x_linked = linked_var(G1, "x")
788 G2.y = 1.1
789 # In this context, x_linked should not be considered as a scalar variable
790 # and therefore the reset statement should be allowed
791 run(3 * defaultclock.dt)
792 assert_allclose(G1.x[:], 1)
793
794
795 @pytest.mark.codegen_independent
796 def test_linked_var_in_reset_incorrect():
797 # Raise an error if a scalar variable (linked variable from a group of size
798 # 1 is set in a reset statement of a group with size > 1)
799 G1 = NeuronGroup(1, "x:1")
800 G2 = NeuronGroup(
801 2,
802 """
803 x_linked : 1 (linked)
804 y:1
805 """,
806 threshold="y>1",
807 reset="y=0; x_linked += 1",
808 )
809 G2.x_linked = linked_var(G1, "x")
810 G2.y = 1.1
811 net = Network(G1, G2)
812 # It is not well-defined what x_linked +=1 means in this context
813 # (as for any other shared variable)
814 with pytest.raises(BrianObjectException) as exc:
815 net.run(0 * ms)
816 assert exc_isinstance(exc, SyntaxError)
817
818
819 @pytest.mark.codegen_independent
820 def test_incomplete_namespace():
821 """
822 Test that the namespace does not have to be complete at creation time.
823 """
824 # This uses tau which is not defined yet (explicit namespace)
825 G = NeuronGroup(1, "dv/dt = -v/tau : 1", namespace={})
826 G.namespace["tau"] = 10 * ms
827 net = Network(G)
828 net.run(0 * ms)
829
830 # This uses tau which is not defined yet (implicit namespace)
831 G = NeuronGroup(1, "dv/dt = -v/tau : 1")
832 tau = 10 * ms
833 net = Network(G)
834 net.run(0 * ms)
835
836
837 @pytest.mark.codegen_independent
838 def test_namespace_errors():
839 # model equations use unknown identifier
840 G = NeuronGroup(1, "dv/dt = -v/tau : 1")
841 net = Network(G)
842 with pytest.raises(BrianObjectException) as exc:
843 net.run(1 * ms)
844 assert exc_isinstance(exc, KeyError)
845
846 # reset uses unknown identifier
847 G = NeuronGroup(1, "dv/dt = -v/tau : 1", threshold="False", reset="v = v_r")
848 net = Network(G)
849 with pytest.raises(BrianObjectException) as exc:
850 net.run(1 * ms)
851 assert exc_isinstance(exc, KeyError)
852
853 # threshold uses unknown identifier
854 G = NeuronGroup(1, "dv/dt = -v/tau : 1", threshold="v > v_th")
855 net = Network(G)
856 with pytest.raises(BrianObjectException) as exc:
857 net.run(1 * ms)
858 assert exc_isinstance(exc, KeyError)
859
860
861 @pytest.mark.codegen_independent
862 def test_namespace_warnings():
863 G1 = NeuronGroup(
864 1,
865 """
866 x : 1
867 y : 1
868 """,
869 # unique names to get warnings every time:
870 name=f"neurongroup_{str(uuid.uuid4()).replace('-', '_')}",
871 )
872 # conflicting variable in namespace
873 y = 5
874 with catch_logs() as l:
875 G1.x = "y"
876 assert len(l) == 1, f"got {str(l)} as warnings"
877 assert l[0][1].endswith(".resolution_conflict")
878
879 del y
880
881 # conflicting variables with special meaning
882 i = 5
883 N = 3
884 with catch_logs() as l:
885 G1.x = "i // N"
886 assert len(l) == 2, f"got {str(l)} as warnings"
887 assert l[0][1].endswith(".resolution_conflict")
888 assert l[1][1].endswith(".resolution_conflict")
889
890 del i
891 del N
892 # conflicting variables in equations
893 y = 5 * Hz
894 G2 = NeuronGroup(
895 1,
896 """
897 y : Hz
898 dx/dt = y : 1
899 """,
900 # unique names to get warnings every time:
901 name=f"neurongroup_{str(uuid.uuid4()).replace('-', '_')}",
902 )
903
904 net = Network(G2)
905 with catch_logs() as l:
906 net.run(0 * ms)
907 assert len(l) == 1, f"got {str(l)} as warnings"
908 assert l[0][1].endswith(".resolution_conflict")
909 del y
910
911 i = 5
912 # i is referring to the neuron number:
913 G3 = NeuronGroup(
914 1,
915 "dx/dt = i*Hz : 1",
916 # unique names to get warnings every time:
917 name=f"neurongroup_{str(uuid.uuid4()).replace('-', '_')}",
918 )
919 net = Network(G3)
920 with catch_logs() as l:
921 net.run(0 * ms)
922 assert len(l) == 1, f"got {str(l)} as warnings"
923 assert l[0][1].endswith(".resolution_conflict")
924 del i
925
926 # Variables that are used internally but not in equations should not raise
927 # a warning
928 N = 3
929 i = 5
930 dt = 1 * ms
931 G4 = NeuronGroup(
932 1,
933 "dx/dt = x/(10*ms) : 1",
934 # unique names to get warnings every time:
935 name=f"neurongroup_{str(uuid.uuid4()).replace('-', '_')}",
936 )
937 net = Network(G4)
938 with catch_logs() as l:
939 net.run(0 * ms)
940 assert len(l) == 0, f"got {str(l)} as warnings"
941
942
943 @pytest.mark.standalone_compatible
944 def test_threshold_reset():
945 """
946 Test that threshold and reset work in the expected way.
947 """
948 # Membrane potential does not change by itself
949 G1 = NeuronGroup(3, "dv/dt = 0 / second : 1", threshold="v > 1", reset="v=0.5")
950 G1.v = np.array([0, 1, 2])
951 run(defaultclock.dt)
952 assert_allclose(G1.v[:], np.array([0, 1, 0.5]))
953
954 with catch_logs() as logs:
955 G2 = NeuronGroup(1, "v : 1", threshold="True")
956 assert len(logs) == 1
957 assert logs[0][0] == "WARNING" and logs[0][1].endswith("only_threshold")
958
959 with catch_logs() as logs:
960 G3 = NeuronGroup(1, "v : 1", threshold="True", reset="")
961 assert len(logs) == 0
962
963 with catch_logs() as logs:
964 G4 = NeuronGroup(1, "v : 1", threshold="True", refractory=1 * ms)
965 assert len(logs) == 0
966
967
968 @pytest.mark.codegen_independent
969 def test_unit_errors_threshold_reset():
970 """
971 Test that unit errors in thresholds and resets are detected.
972 """
973 # Unit error in threshold
974 group = NeuronGroup(1, "dv/dt = -v/(10*ms) : 1", threshold="v > -20*mV")
975 with pytest.raises(BrianObjectException) as exc:
976 Network(group).run(0 * ms)
977 assert exc_isinstance(exc, DimensionMismatchError)
978
979 # Unit error in reset
980 group = NeuronGroup(
981 1, "dv/dt = -v/(10*ms) : 1", threshold="True", reset="v = -65*mV"
982 )
983 with pytest.raises(BrianObjectException) as exc:
984 Network(group).run(0 * ms)
985 assert exc_isinstance(exc, DimensionMismatchError)
986
987 # More complicated unit reset with an intermediate variable
988 # This should pass
989 group = NeuronGroup(
990 1,
991 "dv/dt = -v/(10*ms) : 1",
992 threshold="False",
993 reset="""temp_var = -65
994 v = temp_var""",
995 )
996 run(0 * ms)
997 # throw in an empty line (should still pass)
998 group = NeuronGroup(
999 1,
1000 "dv/dt = -v/(10*ms) : 1",
1001 threshold="False",
1002 reset="""temp_var = -65
1003
1004 v = temp_var""",
1005 )
1006 run(0 * ms)
1007 # This should fail
1008 group = NeuronGroup(
1009 1,
1010 "dv/dt = -v/(10*ms) : 1",
1011 threshold="False",
1012 reset="""temp_var = -65*mV
1013 v = temp_var""",
1014 )
1015 with pytest.raises(BrianObjectException) as exc:
1016 Network(group).run(0 * ms)
1017 assert exc_isinstance(exc, DimensionMismatchError)
1018
1019 # Resets with an in-place modification
1020 # This should work
1021 group = NeuronGroup(
1022 1, "dv/dt = -v/(10*ms) : 1", threshold="False", reset="""v /= 2"""
1023 )
1024 run(0 * ms)
1025
1026 # This should fail
1027 group = NeuronGroup(
1028 1, "dv/dt = -v/(10*ms) : 1", threshold="False", reset="""v -= 60*mV"""
1029 )
1030 with pytest.raises(BrianObjectException) as ecx:
1031 Network(group).run(0 * ms)
1032 assert exc_isinstance(exc, DimensionMismatchError)
1033
1034
1035 @pytest.mark.codegen_independent
1036 def test_syntax_errors():
1037 """
1038 Test that syntax errors are already caught at initialization time.
1039 For equations this is already tested in test_equations
1040 """
1041
1042 # We do not specify the exact type of exception here: Python throws a
1043 # SyntaxError while C++ results in a ValueError
1044 # Syntax error in threshold
1045 group = NeuronGroup(1, "dv/dt = 5*Hz : 1", threshold=">1")
1046 with pytest.raises(Exception):
1047 Network(group).run(0 * ms)
1048
1049 # Syntax error in reset
1050 group = NeuronGroup(1, "dv/dt = 5*Hz : 1", threshold="True", reset="0")
1051 with pytest.raises(Exception):
1052 Network(group).run(0 * ms)
1053
1054
1055 @pytest.mark.codegen_independent
1056 def test_custom_events():
1057 G = NeuronGroup(
1058 2,
1059 """
1060 event_time1 : second
1061 event_time2 : second
1062 """,
1063 events={
1064 "event1": "t>=i*ms and t<i*ms+dt",
1065 "event2": "t>=(i+1)*ms and t<(i+1)*ms+dt",
1066 },
1067 )
1068 G.run_on_event("event1", "event_time1 = t")
1069 G.run_on_event("event2", "event_time2 = t")
1070 net = Network(G)
1071 net.run(2.1 * ms)
1072 assert_allclose(G.event_time1[:], [0, 1] * ms)
1073 assert_allclose(G.event_time2[:], [1, 2] * ms)
1074
1075
1076 def test_custom_events_schedule():
1077 # In the same time step: event2 will be checked and its code executed
1078 # before event1 is checked and its code executed
1079 G = NeuronGroup(
1080 2,
1081 """
1082 x : 1
1083 event_time : second
1084 """,
1085 events={"event1": "x>0", "event2": "t>=(i+1)*ms and t<(i+1)*ms+dt"},
1086 )
1087 G.set_event_schedule("event1", when="after_resets")
1088 G.run_on_event("event2", "x = 1", when="resets")
1089 G.run_on_event(
1090 "event1",
1091 """
1092 event_time = t
1093 x = 0
1094 """,
1095 when="after_resets",
1096 order=1,
1097 )
1098 net = Network(G)
1099 net.run(2.1 * ms)
1100 assert_allclose(G.event_time[:], [1, 2] * ms)
1101
1102
1103 @pytest.mark.codegen_independent
1104 def test_incorrect_custom_event_definition():
1105 # Incorrect event name
1106 with pytest.raises(TypeError):
1107 NeuronGroup(1, "", events={"1event": "True"})
1108 # duplicate definition of 'spike' event
1109 with pytest.raises(ValueError):
1110 NeuronGroup(1, "", threshold="True", events={"spike": "False"})
1111 # not a threshold
1112 G = NeuronGroup(1, "", events={"my_event": 10 * mV})
1113 with pytest.raises(BrianObjectException) as exc:
1114 Network(G).run(0 * ms)
1115 assert exc_isinstance(exc, TypeError)
1116 # schedule for a non-existing event
1117 G = NeuronGroup(1, "", threshold="False", events={"my_event": "True"})
1118 with pytest.raises(ValueError):
1119 G.set_event_schedule("another_event")
1120 # code for a non-existing event
1121 with pytest.raises(ValueError):
1122 G.run_on_event("another_event", "")
1123
1124
1125 def test_state_variables():
1126 """
1127 Test the setting and accessing of state variables.
1128 """
1129 G = NeuronGroup(10, "v : volt")
1130
1131 # The variable N should be always present
1132 assert G.N == 10
1133 # But it should be read-only
1134 with pytest.raises(TypeError):
1135 G.__setattr__("N", 20)
1136 with pytest.raises(TypeError):
1137 G.__setattr__("N_", 20)
1138
1139 G.v = -70 * mV
1140 with pytest.raises(DimensionMismatchError):
1141 G.__setattr__("v", -70)
1142 G.v_ = float(-70 * mV)
1143 assert_allclose(G.v[:], -70 * mV)
1144 G.v = -70 * mV + np.arange(10) * mV
1145 assert_allclose(G.v[:], -70 * mV + np.arange(10) * mV)
1146 G.v = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] * volt
1147 assert_allclose(G.v[:], np.arange(10) * volt)
1148 # incorrect size
1149 with pytest.raises(ValueError):
1150 G.__setattr__("v", [0, 1] * volt)
1151 with pytest.raises(ValueError):
1152 G.__setattr__("v", np.arange(11) * volt)
1153
1154 G.v = -70 * mV
1155 # Numpy methods should be able to deal with state variables
1156 assert_allclose(np.mean(G.v), -70 * mV)
1157 assert_allclose(np.mean(G.v[:]), -70 * mV)
1158
1159 # You should also be able to set variables with a string
1160 G.v = "-70*mV + i*mV"
1161 assert_allclose(G.v[0], -70 * mV)
1162 assert_allclose(G.v[9], -61 * mV)
1163 assert_allclose(G.v[:], -70 * mV + np.arange(10) * mV)
1164
1165 # And it should raise an unit error if the units are incorrect
1166 with pytest.raises(DimensionMismatchError):
1167 G.__setattr__("v", "70 + i")
1168 with pytest.raises(DimensionMismatchError):
1169 G.__setattr__("v", "70 + i*mV")
1170
1171 # Calculating with state variables should work too
1172 # With units
1173 assert_allclose(G.v - G.v, 0 * mV)
1174 assert_allclose(G.v - G.v[:], 0 * mV)
1175 assert_allclose(G.v[:] - G.v, 0 * mV)
1176 assert_allclose(G.v + 70 * mV, G.v[:] + 70 * mV)
1177 assert_allclose(70 * mV + G.v, G.v[:] + 70 * mV)
1178 assert_allclose(G.v + G.v, 2 * G.v)
1179 assert_allclose(G.v / 2.0, 0.5 * G.v)
1180 assert_allclose(1.0 / G.v, 1.0 / G.v[:])
1181 assert_allclose((-G.v)[:], -G.v[:])
1182 assert_allclose((+G.v)[:], G.v[:])
1183 # Without units
1184 assert_allclose(G.v_ - G.v_, 0)
1185 assert_allclose(G.v_ - G.v_[:], 0)
1186 assert_allclose(G.v_[:] - G.v_, 0)
1187 assert_allclose(G.v_ + float(70 * mV), G.v_[:] + float(70 * mV))
1188 assert_allclose(float(70 * mV) + G.v_, G.v_[:] + float(70 * mV))
1189 assert_allclose(G.v_ + G.v_, 2 * G.v_)
1190 assert_allclose(G.v_ / 2.0, 0.5 * G.v_)
1191 assert_allclose(1.0 / G.v_, 1.0 / G.v_[:])
1192 assert_allclose((-G.v)[:], -G.v[:])
1193 assert_allclose((+G.v)[:], G.v[:])
1194
1195 # And in-place modification should work as well
1196 G.v += 10 * mV
1197 G.v -= 10 * mV
1198 G.v *= 2
1199 G.v /= 2.0
1200
1201 # with unit checking
1202 with pytest.raises(DimensionMismatchError):
1203 G.v.__iadd__(3 * second)
1204 with pytest.raises(DimensionMismatchError):
1205 G.v.__iadd__(3)
1206 with pytest.raises(DimensionMismatchError):
1207 G.v.__imul__(3 * second)
1208
1209 # in-place modification with strings should not work
1210 with pytest.raises(TypeError):
1211 G.v.__iadd__("string")
1212 with pytest.raises(TypeError):
1213 G.v.__imul__("string")
1214 with pytest.raises(TypeError):
1215 G.v.__idiv__("string")
1216 with pytest.raises(TypeError):
1217 G.v.__isub__("string")
1218
1219
1220 @pytest.mark.codegen_independent
1221 def test_state_variable_access():
1222 G = NeuronGroup(10, "v:volt")
1223 G.v = np.arange(10) * volt
1224
1225 assert_allclose(np.asarray(G.v[:]), np.arange(10))
1226 assert have_same_dimensions(G.v[:], volt)
1227 assert_allclose(np.asarray(G.v[:]), G.v_[:])
1228 # Accessing single elements, slices and arrays
1229 assert G.v[5] == 5 * volt
1230 assert G.v_[5] == 5
1231 assert_allclose(G.v[:5], np.arange(5) * volt)
1232 assert_allclose(G.v_[:5], np.arange(5))
1233 assert_allclose(G.v[[0, 5]], [0, 5] * volt)
1234 assert_allclose(G.v_[[0, 5]], np.array([0, 5]))
1235
1236 # Illegal indexing
1237 with pytest.raises(IndexError):
1238 G.v[0, 0]
1239 with pytest.raises(IndexError):
1240 G.v_[0, 0]
1241 with pytest.raises(TypeError):
1242 G.v[object()]
1243 with pytest.raises(TypeError):
1244 G.v_[object()]
1245
1246 # A string representation should not raise any error
1247 assert len(str(G.v))
1248 assert len(repr(G.v))
1249 assert len(str(G.v_))
1250 assert len(repr(G.v_))
1251
1252
1253 def test_state_variable_access_strings():
1254 G = NeuronGroup(
1255 10,
1256 """
1257 v : volt
1258 dv_ref/dt = -v_ref/(10*ms) : 1 (unless refractory)
1259 """,
1260 threshold="v_ref>1",
1261 reset="v_ref=1",
1262 refractory=1 * ms,
1263 )
1264 G.v = np.arange(10) * volt
1265 # Indexing with strings
1266 assert G.v["i==2"] == G.v[2]
1267 assert G.v_["i==2"] == G.v_[2]
1268 assert_allclose(G.v["v >= 3*volt"], G.v[3:])
1269 assert_allclose(G.v_["v >= 3*volt"], G.v_[3:])
1270 # Should also check for units
1271 with pytest.raises(DimensionMismatchError):
1272 G.v["v >= 3"]
1273 with pytest.raises(DimensionMismatchError):
1274 G.v["v >= 3*second"]
1275
1276
1277 @pytest.mark.standalone_compatible
1278 def test_state_variable_set_strings():
1279 # Instead of overwriting the same variable over and over, we have one
1280 # variable for each assignment so that we can test everything in the end
1281 # for standalone.
1282 G = NeuronGroup(
1283 10,
1284 """
1285 v1 : volt
1286 v2 : volt
1287 v3 : volt
1288 v4 : volt
1289 v5 : volt
1290 v6 : volt
1291 v7 : volt
1292 v7b : volt
1293 v7c : volt
1294 v8 : volt
1295 v9 : volt
1296 v9b : volt
1297 v9c : volt
1298 v10 : volt
1299 v11 : volt
1300 dv_ref/dt = -v_ref/(10*ms) : 1 (unless refractory)
1301 """,
1302 threshold="v_ref>1",
1303 reset="v_ref=1",
1304 refractory=1 * ms,
1305 )
1306 # Setting with strings
1307 # --------------------
1308 # String value referring to i
1309 G.v1 = "2*i*volt"
1310 # String value referring to i
1311 G.v1[:5] = "3*i*volt"
1312
1313 # Conditional write variable
1314 G.v_ref = "2*i"
1315
1316 G.v2 = np.arange(10) * volt
1317 # String value referring to a state variable
1318 G.v2 = "2*v2"
1319 G.v2[:5] = "2*v2"
1320
1321 G.v3 = np.arange(10) * volt
1322 # String value referring to state variables, i, and an external variable
1323 ext = 5 * volt
1324 G.v3 = "v3 + ext + (N + i)*volt"
1325
1326 G.v4 = np.arange(10) * volt
1327 G.v4[:5] = "v4 + ext + (N + i)*volt"
1328
1329 G.v5 = "v5 + randn()*volt" # only check that it doesn't raise an error
1330 G.v5[:5] = "v5 + randn()*volt" # only check that it doesn't raise an error
1331
1332 G.v6 = np.arange(10) * volt
1333 # String index using a random number
1334 G.v6["rand() <= 1"] = 0 * mV
1335
1336 G.v7 = np.arange(10) * volt
1337 # String index referring to i and setting to a scalar value
1338 G.v7["i>=5"] = 0 * mV
1339
1340 G.v7b = np.arange(10) * volt
1341 # String index referring to i and setting to a scalar value (no effect)
1342 G.v7b["i>=10"] = 0 * mV
1343
1344 G.v7c = np.arange(10) * volt
1345 # String index referring to i and setting to a scalar value (no effect)
1346 G.v7c["False"] = 0 * mV
1347
1348 G.v8[:5] = np.arange(5) * volt
1349 # String index referring to a state variable
1350 G.v8["v8<3*volt"] = 0 * mV
1351 # String index referring to state variables, i, and an external variable
1352 ext = 2 * volt
1353 G.v8["v8>=ext and i==(N-6)"] = 0 * mV
1354
1355 G.v9 = np.arange(10) * volt
1356 # Strings for both condition and values
1357 G.v9["i>=5"] = "v9*2"
1358 G.v9["v9<5*volt"] = "3*i*volt"
1359
1360 G.v9b = np.arange(10) * volt
1361 # Strings for both condition and values (no effect)
1362 G.v9b["i<0"] = "v9 + 100*volt"
1363
1364 G.v9c = np.arange(10) * volt
1365 # Strings for both condition and values (no effect)
1366 G.v9c["False"] = "v9 + 100*volt"
1367
1368 G.v10 = np.arange(10) * volt
1369 G.v10["i<=5"] = "(100 + rand())*volt"
1370
1371 # string assignment to scalars
1372 G.v11[0] = "1*volt"
1373 G.v11[1] = "(1 + i)*volt"
1374 G.v11[2] = "v11 + 3*volt"
1375 G.v11[3] = "inf*volt"
1376 G.v11[4] = "rand()*volt"
1377 run(0 * ms)
1378 assert_allclose(G.v1[:], [0, 3, 6, 9, 12, 10, 12, 14, 16, 18] * volt)
1379 assert_allclose(G.v_ref[:], 2 * np.arange(10))
1380 assert_allclose(G.v2[:], [0, 4, 8, 12, 16, 10, 12, 14, 16, 18] * volt)
1381 assert_allclose(G.v3[:], 2 * np.arange(10) * volt + 15 * volt)
1382 assert_allclose(G.v4[:], [15, 17, 19, 21, 23, 5, 6, 7, 8, 9] * volt)
1383 assert_allclose(G.v6[:], np.zeros(10) * volt)
1384 assert_allclose(G.v7[:], [0, 1, 2, 3, 4, 0, 0, 0, 0, 0] * volt)
1385 assert_allclose(G.v7b[:], np.arange(10) * volt)
1386 assert_allclose(G.v7c[:], np.arange(10) * volt)
1387 assert_allclose(G.v8[:], [0, 0, 0, 3, 0, 0, 0, 0, 0, 0] * volt)
1388 assert_allclose(G.v9[:], [0, 3, 6, 9, 12, 10, 12, 14, 16, 18] * volt)
1389 assert_allclose(G.v9b[:], np.arange(10) * volt)
1390 assert_allclose(G.v9c[:], np.arange(10) * volt)
1391 assert_allclose(G.v10[6:], np.arange(4) * volt + 6 * volt) # unchanged
1392 assert all(G.v10[:6] >= 100 * volt)
1393 assert all(G.v10[:6] <= 101 * volt)
1394 assert np.var(G.v10_[:6]) > 0
1395 assert_allclose(G.v11[:3], [1, 2, 3] * volt)
1396 assert np.isinf(G.v11_[3])
1397
1398
1399 @pytest.mark.codegen_independent
1400 def test_unknown_state_variables():
1401 # Test how setting attribute names that do not correspond to a state
1402 # variable are handled
1403 G = NeuronGroup(10, "v : 1")
1404 with pytest.raises(AttributeError):
1405 setattr(G, "unknown", 42)
1406
1407 # Creating a new private attribute should be fine
1408 G._unknown = 42
1409 assert G._unknown == 42
1410
1411 # Explicitly create the attribute
1412 G.add_attribute("unknown")
1413 G.unknown = 42
1414 assert G.unknown == 42
1415
1416
1417 @pytest.mark.codegen_independent
1418 def test_subexpression():
1419 G = NeuronGroup(
1420 10,
1421 """
1422 dv/dt = freq : 1
1423 freq : Hz
1424 array : 1
1425 expr = 2*freq + array*Hz : Hz""",
1426 )
1427 G.freq = "10*i*Hz"
1428 G.array = 5
1429 assert_allclose(G.expr[:], 2 * 10 * np.arange(10) * Hz + 5 * Hz)
1430
1431
1432 @pytest.mark.codegen_independent
1433 def test_subexpression_with_constant():
1434 g = 2
1435 G = NeuronGroup(
1436 1,
1437 """
1438 x : 1
1439 I = x*g : 1
1440 """,
1441 )
1442 G.x = 1
1443 assert_allclose(G.I[:], np.array([2]))
1444 # Subexpressions that refer to external variables are tricky, see github
1445 # issue #313 for details
1446
1447 # Comparisons
1448 assert G.I == 2
1449 assert G.I >= 1
1450 assert G.I > 1
1451 assert G.I < 3
1452 assert G.I <= 3
1453 assert G.I != 3
1454
1455 # arithmetic operations
1456 assert G.I + 1 == 3
1457 assert 1 + G.I == 3
1458 assert G.I * 1 == 2
1459 assert 1 * G.I == 2
1460 assert G.I - 1 == 1
1461 assert 3 - G.I == 1
1462 assert G.I / 1 == 2
1463 assert G.I // 1 == 2.0
1464 assert 1.0 / G.I == 0.5
1465 assert 1 // G.I == 0
1466 assert +G.I == 2
1467 assert -G.I == -2
1468
1469 # other operations
1470 assert len(G.I) == 1
1471
1472 # These will not work
1473 with pytest.raises(KeyError):
1474 np.array(G.I)
1475 with pytest.raises(KeyError):
1476 np.mean(G.I)
1477 # But these should
1478 assert_allclose(np.array(G.I[:]), G.I[:])
1479 assert np.mean(G.I[:]) == 2
1480
1481 # This will work but display a text, advising to use G.I[:] instead of
1482 # G.I
1483 assert len(str(G.I))
1484 assert len(repr(G.I))
1485
1486
1487 @pytest.mark.codegen_independent
1488 def test_scalar_parameter_access():
1489 G = NeuronGroup(
1490 10,
1491 """
1492 dv/dt = freq : 1
1493 freq : Hz (shared)
1494 number : 1 (shared)
1495 array : 1
1496 """,
1497 )
1498
1499 # Try setting a scalar variable
1500 G.freq = 100 * Hz
1501 assert_allclose(G.freq[:], 100 * Hz)
1502 G.freq[:] = 200 * Hz
1503 assert_allclose(G.freq[:], 200 * Hz)
1504 G.freq = "freq - 50*Hz + number*Hz"
1505 assert_allclose(G.freq[:], 150 * Hz)
1506 G.freq[:] = "50*Hz"
1507 assert_allclose(G.freq[:], 50 * Hz)
1508
1509 # Check the second method of accessing that works
1510 assert_allclose(np.asanyarray(G.freq), 50 * Hz)
1511
1512 # Check error messages
1513 with pytest.raises(IndexError):
1514 G.freq[0]
1515 with pytest.raises(IndexError):
1516 G.freq[1]
1517 with pytest.raises(IndexError):
1518 G.freq[0:1]
1519 with pytest.raises(IndexError):
1520 G.freq["i>5"]
1521
1522 with pytest.raises(ValueError):
1523 G.freq.set_item(slice(None), [0, 1] * Hz)
1524 with pytest.raises(IndexError):
1525 G.freq.set_item(0, 100 * Hz)
1526 with pytest.raises(IndexError):
1527 G.freq.set_item(1, 100 * Hz)
1528 with pytest.raises(IndexError):
1529 G.freq.set_item("i>5", 100 * Hz)
1530
1531
1532 @pytest.mark.codegen_independent
1533 def test_scalar_subexpression():
1534 G = NeuronGroup(
1535 10,
1536 """
1537 dv/dt = freq : 1
1538 freq : Hz (shared)
1539 number : 1 (shared)
1540 array : 1
1541 sub = freq + number*Hz : Hz (shared)
1542 """,
1543 )
1544 G.freq = 100 * Hz
1545 G.number = 50
1546 assert G.sub[:] == 150 * Hz
1547
1548 with pytest.raises(SyntaxError):
1549 NeuronGroup(
1550 10,
1551 """
1552 dv/dt = freq : 1
1553 freq : Hz (shared)
1554 array : 1
1555 sub = freq + array*Hz : Hz (shared)
1556 """,
1557 )
1558
1559 # A scalar subexpresion cannot refer to implicitly vectorized functions
1560 group = NeuronGroup(
1561 10,
1562 """x : 1
1563 sub = rand() : 1 (shared)""",
1564 )
1565 group.run_regularly("x = sub")
1566 net = Network(group)
1567 with pytest.raises(BrianObjectException) as exc:
1568 net.run(0 * ms)
1569 assert exc_isinstance(exc, SyntaxError)
1570
1571
1572 @pytest.mark.standalone_compatible
1573 def test_sim_with_scalar_variable():
1574 G = NeuronGroup(
1575 10,
1576 """
1577 tau : second (shared)
1578 dv/dt = -v/tau : 1
1579 """,
1580 method="exact",
1581 )
1582 G.tau = 10 * ms
1583 G.v = "1.0*i/N"
1584 run(1 * ms)
1585 assert_allclose(G.v[:], np.exp(-0.1) * np.linspace(0, 1, 10, endpoint=False))
1586
1587
1588 @pytest.mark.standalone_compatible
1589 def test_sim_with_scalar_subexpression():
1590 G = NeuronGroup(
1591 10,
1592 """
1593 tau = 10*ms : second (shared)
1594 dv/dt = -v/tau : 1
1595 """,
1596 method="exact",
1597 )
1598 G.v = "1.0*i/N"
1599 run(1 * ms)
1600 assert_allclose(G.v[:], np.exp(-0.1) * np.linspace(0, 1, 10, endpoint=False))
1601
1602
1603 @pytest.mark.standalone_compatible
1604 def test_constant_variable_subexpression():
1605 G = NeuronGroup(
1606 10,
1607 """
1608 dv1/dt = -v1**2 / (10*ms) : 1
1609 dv2/dt = -v_const**2 / (10*ms) : 1
1610 dv3/dt = -v_var**2 / (10*ms) : 1
1611 dv4/dt = -v_noflag**2 / (10*ms) : 1
1612 v_const = v2 : 1 (constant over dt)
1613 v_var = v3 : 1
1614 v_noflag = v4 : 1
1615 """,
1616 method="rk2",
1617 )
1618 G.v1 = "1.0*i/N"
1619 G.v2 = "1.0*i/N"
1620 G.v3 = "1.0*i/N"
1621 G.v4 = "1.0*i/N"
1622
1623 run(10 * ms)
1624 # "variable over dt" subexpressions are directly inserted into the equation
1625 assert_allclose(G.v3[:], G.v1[:])
1626 assert_allclose(G.v4[:], G.v1[:])
1627 # "constant over dt" subexpressions will keep a fixed value over the time
1628 # step and therefore give a slightly different result for multi-step
1629 # methods
1630 assert np.sum((G.v2 - G.v1) ** 2) > 1e-10
1631
1632
1633 @pytest.mark.codegen_independent
1634 def test_constant_subexpression_order():
1635 G = NeuronGroup(
1636 10,
1637 """
1638 dv/dt = -v / (10*ms) : 1
1639 s1 = v : 1 (constant over dt)
1640 s2 = 2*s3 : 1 (constant over dt)
1641 s3 = 1 + s1 : 1 (constant over dt)
1642 """,
1643 )
1644 run(0 * ms)
1645 code_lines = G.subexpression_updater.abstract_code.split("\n")
1646 assert code_lines[0].startswith("s1")
1647 assert code_lines[1].startswith("s3")
1648 assert code_lines[2].startswith("s2")
1649
1650
1651 @pytest.mark.codegen_independent
1652 def test_subexpression_checks():
1653 group = NeuronGroup(
1654 1,
1655 """
1656 dv/dt = -v / (10*ms) : volt
1657 y = rand() : 1 (constant over dt)
1658 z = 17*v**2 : volt**2
1659 """,
1660 )
1661 # This should all be fine
1662 net = Network(group)
1663 net.run(0 * ms)
1664
1665 # The following should raise an error
1666 group = NeuronGroup(
1667 1,
1668 """
1669 dv/dt = -v / (10*ms) : volt
1670 y = rand() : 1
1671 z = 17*v**2 : volt**2
1672 """,
1673 )
1674 net = Network(group)
1675 with pytest.raises(BrianObjectException) as exc:
1676 net.run(0 * ms)
1677 assert exc_isinstance(exc, SyntaxError)
1678
1679
1680 @pytest.mark.codegen_independent
1681 def test_repr():
1682 G = NeuronGroup(
1683 10,
1684 """
1685 dv/dt = -(v + Inp) / tau : volt
1686 Inp = sin(2*pi*freq*t) : volt
1687 freq : Hz
1688 """,
1689 )
1690
1691 # Test that string/LaTeX representations do not raise errors
1692 for func in [str, repr, sympy.latex]:
1693 assert len(func(G))
1694 assert "textbackslash" not in func(G) # for LaTeX, see #1296
1695 assert len(func(G.equations))
1696 assert "textbackslash" not in func(G.equations)
1697 for eq in G.equations.values():
1698 assert len(func(eq))
1699
1700
1701 @pytest.mark.codegen_independent
1702 def test_ipython_html():
1703 G = NeuronGroup(
1704 10,
1705 """
1706 dv/dt = -(v + Inp) / tau : volt
1707 Inp = sin(2*pi*freq*t) : volt
1708 freq : Hz
1709 """,
1710 )
1711
1712 # Test that HTML representation in IPython does not raise errors
1713 assert len(G._repr_html_())
1714
1715
1716 @pytest.mark.codegen_independent
1717 def test_indices():
1718 G = NeuronGroup(10, "v : 1")
1719 G.v = "i"
1720 ext_var = 5
1721 assert_allclose(G.indices[:], G.i[:])
1722 assert_allclose(G.indices[5:], G.indices["i >= 5"])
1723 assert_allclose(G.indices[5:], G.indices["i >= ext_var"])
1724 assert_allclose(G.indices["v >= 5"], np.nonzero(G.v >= 5)[0])
1725
1726 # We should not accept "None" as an index, because in numpy this stands for
1727 # "new axis". In fact, x[0, None] is used in matplotlib to check whether
1728 # something behaves as a numpy array -- if NeuronGroup accepts None as an
1729 # index, then synaptic variables will allow indexing in such a way. This
1730 # makes plotting in matplotlib 1.5.1 fail with a non-obivous error
1731 # See https://groups.google.com/d/msg/briansupport/yRA4PHKAvN8/cClOEUlOAQAJ
1732 with pytest.raises(TypeError):
1733 G.indices.__getitem__(None)
1734
1735
1736 @pytest.mark.codegen_independent
1737 def test_get_dtype():
1738 """
1739 Check the utility function get_dtype
1740 """
1741 eqs = Equations(
1742 """
1743 dv/dt = -v / (10*ms) : volt
1744 x : 1
1745 b : boolean
1746 n : integer
1747 """
1748 )
1749
1750 # Test standard dtypes
1751 assert get_dtype(eqs["v"]) == prefs["core.default_float_dtype"]
1752 assert get_dtype(eqs["x"]) == prefs["core.default_float_dtype"]
1753 assert get_dtype(eqs["n"]) == prefs["core.default_integer_dtype"]
1754 assert get_dtype(eqs["b"]) == bool
1755
1756 # Test a changed default (float) dtype
1757 assert get_dtype(eqs["v"], np.float32) == np.float32, get_dtype(
1758 eqs["v"], np.float32
1759 )
1760 assert get_dtype(eqs["x"], np.float32) == np.float32
1761 # integer and boolean variables should be unaffected
1762 assert get_dtype(eqs["n"]) == prefs["core.default_integer_dtype"]
1763 assert get_dtype(eqs["b"]) == bool
1764
1765 # Explicitly provide a dtype for some variables
1766 dtypes = {"v": np.float32, "x": np.float64, "n": np.int64}
1767 for varname in dtypes:
1768 assert get_dtype(eqs[varname], dtypes) == dtypes[varname]
1769
1770 # Not setting some dtypes should use the standard dtypes
1771 dtypes = {"n": np.int64}
1772 assert get_dtype(eqs["n"], dtypes) == np.int64
1773 assert get_dtype(eqs["v"], dtypes) == prefs["core.default_float_dtype"]
1774
1775 # Test that incorrect types raise an error
1776 # incorrect general dtype
1777 with pytest.raises(TypeError):
1778 get_dtype(eqs["v"], np.int32)
1779 # incorrect specific types
1780 with pytest.raises(TypeError):
1781 get_dtype(eqs["v"], {"v": np.int32})
1782 with pytest.raises(TypeError):
1783 get_dtype(eqs["n"], {"n": np.float32})
1784 with pytest.raises(TypeError):
1785 get_dtype(eqs["b"], {"b": np.int32})
1786
1787
1788 def test_aliasing_in_statements():
1789 """
1790 Test an issue around variables aliasing other variables (#259)
1791 """
1792 if prefs.codegen.target != "numpy":
1793 pytest.skip("numpy-only test")
1794
1795 runner_code = """x_1 = x_0
1796 x_0 = -1"""
1797 g = NeuronGroup(
1798 1,
1799 model="""
1800 x_0 : 1
1801 x_1 : 1
1802 """,
1803 )
1804 g.run_regularly(runner_code)
1805 net = Network(g)
1806 net.run(defaultclock.dt)
1807 assert_allclose(g.x_0_[:], np.array([-1]))
1808 assert_allclose(g.x_1_[:], np.array([0]))
1809
1810
1811 @pytest.mark.codegen_independent
1812 def test_get_states():
1813 G = NeuronGroup(
1814 10,
1815 """
1816 v : volt
1817 x : 1
1818 subexpr = x + v/volt : 1
1819 subexpr2 = x*volt + v : volt
1820 """,
1821 )
1822 G.v = "i*volt"
1823 G.x = "10*i"
1824 states_units = G.get_states(["v", "x", "subexpr", "subexpr2"], units=True)
1825 states = G.get_states(["v", "x", "subexpr", "subexpr2"], units=False)
1826
1827 assert len(states_units) == len(states) == 4
1828 assert_allclose(states_units["v"], np.arange(10) * volt)
1829 assert_allclose(states_units["x"], 10 * np.arange(10))
1830 assert_allclose(states_units["subexpr"], 11 * np.arange(10))
1831 assert_allclose(states_units["subexpr2"], 11 * np.arange(10) * volt)
1832 assert_allclose(states["v"], np.arange(10))
1833 assert_allclose(states["x"], 10 * np.arange(10))
1834 assert_allclose(states["subexpr"], 11 * np.arange(10))
1835 assert_allclose(states["subexpr2"], 11 * np.arange(10))
1836
1837 all_states = G.get_states(units=True)
1838 assert set(all_states.keys()) == {"v", "x", "N", "t", "dt", "i", "t_in_timesteps"}
1839 all_states = G.get_states(units=True, subexpressions=True)
1840 assert set(all_states.keys()) == {
1841 "v",
1842 "x",
1843 "N",
1844 "t",
1845 "dt",
1846 "i",
1847 "t_in_timesteps",
1848 "subexpr",
1849 "subexpr2",
1850 }
1851
1852
1853 @pytest.mark.codegen_independent
1854 def test_set_states():
1855 G = NeuronGroup(
1856 10,
1857 """
1858 v : volt
1859 x : 1
1860 subexpr = x + v/volt : 1
1861 subexpr2 = x*volt + v : volt
1862 """,
1863 )
1864 G.v = "i*volt"
1865 G.x = "10*i"
1866 with pytest.raises(ValueError):
1867 G.set_states({"v": np.arange(2, 11) * volt}, units=True)
1868 # we test if function prevents from setting read_only variables
1869 with pytest.raises(TypeError):
1870 G.set_states({"N": 1})
1871 with pytest.raises(DimensionMismatchError):
1872 G.set_states({"x": np.arange(2, 12) * volt}, units=True)
1873 with pytest.raises(DimensionMismatchError):
1874 G.set_states({"v": np.arange(2, 12)}, units=True)
1875 G.set_states({"v": np.arange(2, 12)}, units=False)
1876 assert_allclose(G.v, np.arange(2, 12) * volt)
1877 G.set_states({"v": np.arange(2, 12) * volt}, units=True)
1878 assert_allclose(G.v, np.arange(2, 12) * volt)
1879 G.set_states({"x": np.arange(2, 12)}, units=False)
1880 assert_allclose(G.x, np.arange(2, 12))
1881 G.set_states({"x": np.arange(2, 12)}, units=True)
1882 assert_allclose(G.x, np.arange(2, 12))
1883
1884
1885 @pytest.mark.codegen_independent
1886 def test_get_states_pandas():
1887 try:
1888 import pandas as pd
1889 except ImportError:
1890 pytest.skip("Cannot test export to Pandas data frame, Pandas is not installed.")
1891 G = NeuronGroup(
1892 10,
1893 """
1894 v : volt
1895 x : 1
1896 subexpr = x + v/volt : 1
1897 subexpr2 = x*volt + v : volt
1898 """,
1899 )
1900 G.v = "i*volt"
1901 G.x = "10*i"
1902 with pytest.raises(NotImplementedError):
1903 G.get_states(["v", "x", "subexpr", "subexpr2"], units=True, format="pandas")
1904 states = G.get_states(
1905 ["v", "x", "subexpr", "subexpr2"], units=False, format="pandas"
1906 )
1907 assert_allclose(states["v"].values, np.arange(10))
1908 assert_allclose(states["x"].values, 10 * np.arange(10))
1909 assert_allclose(states["subexpr"].values, 11 * np.arange(10))
1910 assert_allclose(states["subexpr2"].values, 11 * np.arange(10))
1911
1912 all_states = G.get_states(units=False, format="pandas")
1913 assert set(all_states.columns) == {"v", "x", "N", "t", "dt", "i", "t_in_timesteps"}
1914 all_states = G.get_states(units=False, subexpressions=True, format="pandas")
1915 assert set(all_states.columns) == {
1916 "v",
1917 "x",
1918 "N",
1919 "t",
1920 "dt",
1921 "i",
1922 "t_in_timesteps",
1923 "subexpr",
1924 "subexpr2",
1925 }
1926
1927
1928 @pytest.mark.codegen_independent
1929 def test_set_states_pandas():
1930 try:
1931 import pandas as pd
1932 except ImportError:
1933 pytest.skip("Cannot test export to Pandas data frame, Pandas is not installed.")
1934 G = NeuronGroup(
1935 10,
1936 """
1937 v : volt
1938 x : 1
1939 subexpr = x + v/volt : 1
1940 subexpr2 = x*volt + v : volt
1941 """,
1942 )
1943 G.v = "i*volt"
1944 G.x = "10*i"
1945 df = pd.DataFrame(np.arange(2, 11), columns=["v"])
1946 with pytest.raises(NotImplementedError):
1947 G.set_states(df, units=True, format="pandas")
1948 with pytest.raises(ValueError):
1949 G.set_states(df, units=False, format="pandas")
1950 # we test if function prevents from setting read_only variables
1951 df = pd.DataFrame(np.array([1]), columns=["N"])
1952 with pytest.raises(TypeError):
1953 G.set_states(df, units=False, format="pandas")
1954 df = pd.DataFrame(np.vstack((np.arange(2, 12), np.arange(2, 12))).T)
1955 df.columns = ["v", "x"]
1956 G.set_states(df, units=False, format="pandas")
1957 assert_allclose(G.v, np.arange(2, 12) * volt)
1958 assert_allclose(G.x, np.arange(2, 12))
1959
1960
1961 def test_random_vector_values():
1962 # Make sure that the new "loop-invariant optimisation" does not pull out
1963 # the random number generation and therefore makes all neurons receiving
1964 # the same values
1965 tau = 10 * ms
1966 G = NeuronGroup(100, "dv/dt = -v / tau + xi*tau**-0.5: 1")
1967 G.v[:] = "rand()"
1968 assert np.var(G.v[:]) > 0
1969 G.v[:] = 0
1970 net = Network(G)
1971 net.run(defaultclock.dt)
1972 assert np.var(G.v[:]) > 0
1973
1974
1975 @pytest.mark.standalone_compatible
1976 def test_random_values_random_seed():
1977 G = NeuronGroup(
1978 100,
1979 """
1980 v1 : 1
1981 v2 : 1
1982 """,
1983 )
1984 seed()
1985 G.v1 = "rand() + randn()"
1986 seed()
1987 G.v2 = "rand() + randn()"
1988 run(0 * ms) # for standalone
1989 assert np.var(G.v1[:]) > 0
1990 assert np.var(G.v2[:]) > 0
1991 assert np.var(G.v1[:] - G.v2[:]) > 0
1992
1993
1994 @pytest.mark.standalone_compatible
1995 def test_random_values_fixed_seed():
1996 G = NeuronGroup(
1997 100,
1998 """
1999 v1 : 1
2000 v2 : 1
2001 """,
2002 )
2003 seed(12345678)
2004 G.v1 = "rand() + randn()"
2005 seed(12345678)
2006 G.v2 = "rand() + randn()"
2007 run(0 * ms) # for standalone
2008 assert np.var(G.v1[:]) > 0
2009 assert np.var(G.v2[:]) > 0
2010 assert_allclose(G.v1[:], G.v2[:])
2011
2012
2013 _random_values = {
2014 ("RuntimeDevice", "numpy", None): (
2015 [0.1636023, 0.76229608, 0.74945305, 0.82121212, 0.82669968],
2016 [-0.7758696, 0.13295831, 0.87360834, -1.21879122, 0.62980314],
2017 ),
2018 ("RuntimeDevice", "cython", None): (
2019 [0.1636023, 0.76229608, 0.74945305, 0.82121212, 0.82669968],
2020 # Cython uses a buffer for the random values that it gets from numpy, the
2021 # values for the second call are therefore different
2022 [-0.24349748, 1.1164414, -1.97421849, 1.58092889, -0.06444478],
2023 ),
2024 ("CPPStandaloneDevice", None, 1): (
2025 [0.1636023, 0.76229608, 0.74945305, 0.82121212, 0.82669968],
2026 [-0.7758696, 0.13295831, 0.87360834, -1.21879122, 0.62980314],
2027 ),
2028 ("CPPStandaloneDevice", None, 4): (
2029 [0.1636023, 0.76229608, 0.27318909, 0.44124824, 0.69454226],
2030 [0.36643979, -1.53883951, 0.07274151, 1.34278769, 0.63249739],
2031 ),
2032 }
2033
2034
2035 def _config_tuple():
2036 config = [
2037 get_device().__class__.__name__,
2038 prefs.codegen.target,
2039 prefs.devices.cpp_standalone.openmp_threads,
2040 ]
2041 if config[0] == "RuntimeDevice":
2042 config[2] = None
2043 else:
2044 config[1] = None
2045 return tuple(config)
2046
2047
2048 @pytest.mark.standalone_compatible
2049 def test_random_values_fixed_seed_numbers():
2050 # Verify a subset of random numbers, to make sure these numbers stay the same across updates
2051 G = NeuronGroup(
2052 100,
2053 """
2054 v1 : 1
2055 v2 : 1
2056 """,
2057 )
2058 seed(9876)
2059 G.v1 = "rand()"
2060 G.v2 = "randn()"
2061 run(0 * ms) # for standalone
2062 expected_values = _random_values.get(_config_tuple(), None)
2063 if expected_values is None:
2064 pytest.skip(
2065 f"Random values not known for this configuration (config_tuple: {_config_tuple()})"
2066 )
2067 assert_allclose(G.v1[::20], expected_values[0])
2068 assert_allclose(G.v2[::20], expected_values[1])
2069
2070
2071 @pytest.mark.standalone_compatible
2072 @pytest.mark.multiple_runs
2073 def test_random_values_fixed_and_random():
2074 G = NeuronGroup(10, "dv/dt = -v/(10*ms) + 0.1*xi/sqrt(ms) : 1", method="euler")
2075 mon = StateMonitor(G, "v", record=True)
2076
2077 # first run
2078 seed(13579)
2079 G.v = "rand()"
2080 seed()
2081 run(2 * defaultclock.dt)
2082
2083 # second run
2084 seed(13579)
2085 G.v = "rand()"
2086 seed()
2087 run(2 * defaultclock.dt)
2088
2089 device.build(direct_call=False, **device.build_options)
2090
2091 first_run_values = np.array(mon.v[:, [0, 1]])
2092 second_run_values = np.array(mon.v[:, [2, 3]])
2093
2094 # First time step should be identical (same seed)
2095 assert all(abs(first_run_values[:, 0] - second_run_values[:, 0]) < 0.0001)
2096 # Increase in second time step should be different (random seed)
2097 assert all(
2098 abs(
2099 (first_run_values[:, 1] - first_run_values[:, 0])
2100 - (second_run_values[:, 1] - second_run_values[:, 0])
2101 )
2102 > 1e-6
2103 )
2104
2105
2106 @pytest.mark.codegen_independent
2107 def test_no_code():
2108 # Make sure that we are not unncessarily creating code objects for a state
2109 # updater that has nothing to do
2110 group_1 = NeuronGroup(10, "v: 1", threshold="False")
2111 # The refractory argument will automatically add a statement for each time
2112 # step, so we'll need a state updater here
2113 group_2 = NeuronGroup(10, "v: 1", threshold="False", refractory=2 * ms)
2114 run(0 * ms)
2115 assert len(group_1.state_updater.code_objects) == 0
2116 assert group_1.state_updater.codeobj is None
2117 assert len(group_2.state_updater.code_objects) == 1
2118 assert group_2.state_updater.codeobj is not None
2119
2120
2121 @pytest.mark.standalone_compatible
2122 def test_run_regularly_scheduling():
2123 G = NeuronGroup(
2124 1,
2125 """
2126 v1 : 1
2127 v2 : 1
2128 v3 : 1
2129 """,
2130 )
2131 G.run_regularly("v1 += 1")
2132 G.run_regularly("v2 = v1", when="end")
2133 G.run_regularly("v3 = v1", when="before_start")
2134 run(2 * defaultclock.dt)
2135 assert_allclose(G.v1[:], 2)
2136 assert_allclose(G.v2[:], 2)
2137 assert_allclose(G.v3[:], 1)
2138
2139
2140 @pytest.mark.standalone_compatible
2141 def test_run_regularly_scheduling_2():
2142 # This form is relevant for Brian2GeNN, where we are not allowed to change
2143 # the "when" attribute, but can change the order.
2144 G = NeuronGroup(
2145 1,
2146 """
2147 v1 : 1
2148 v2 : 1
2149 v3 : 1
2150 """,
2151 )
2152 # The order should be:
2153 # 0: 'v3 = v1'
2154 # 1: monitor 1 (v1)
2155 # 2: v1 += 1
2156 # 3: monitor 2 (v1)
2157 # 4: monitor 3 (v2)
2158 # 5: v2 = v1
2159 # 6: monitor 4 (v2)
2160 mon_1 = StateMonitor(G, "v1", record=0, order=1)
2161 mon_2 = StateMonitor(G, "v1", record=0, order=3)
2162 mon_3 = StateMonitor(G, "v2", record=0, order=4)
2163 mon_4 = StateMonitor(G, "v2", record=0, order=6)
2164 G.run_regularly("v3 = v1", order=0)
2165 G.run_regularly("v1 += 1", order=2)
2166 G.run_regularly("v2 = v1", order=5)
2167
2168 run(2 * defaultclock.dt)
2169 assert_allclose(G.v1[:], 2)
2170 assert_allclose(G.v2[:], 2)
2171 assert_allclose(G.v3[:], 1)
2172 assert_allclose(mon_1.v1[0], [0, 1])
2173 assert_allclose(mon_2.v1[0], [1, 2])
2174 assert_allclose(mon_3.v2[0], [0, 1])
2175 assert_allclose(mon_4.v2[0], [1, 2])
2176
2177
2178 @pytest.mark.standalone_compatible
2179 def test_run_regularly_dt():
2180 G = NeuronGroup(1, "v : 1")
2181 G.run_regularly("v += 1", dt=2 * defaultclock.dt)
2182 M = StateMonitor(G, "v", record=0, when="end")
2183 run(10 * defaultclock.dt)
2184 assert_allclose(G.v[:], 5)
2185 assert_allclose(np.diff(M.v[0]), np.tile([0, 1], 5)[:-1])
2186
2187
2188 @pytest.mark.standalone_compatible
2189 def test_run_at():
2190 G = NeuronGroup(1, "v : 1")
2191 G.run_at("v += 1", times=[0, 1, 3] * defaultclock.dt)
2192 M = StateMonitor(G, "v", record=0, when="end")
2193 run(4 * defaultclock.dt)
2194 assert_allclose(G.v[:], 3)
2195 assert_allclose(M.v[0], [1, 2, 2, 3])
2196
2197
2198 @pytest.mark.standalone_compatible
2199 def test_run_regularly_shared():
2200 # Check that shared variables are handled correctly in run_regularly
2201 # operations. See brian-team/brian2genn#113
2202 model = Equations(
2203 """
2204 individual_var: 1
2205 shared_var: 1 (shared)
2206 individual_var_i: integer
2207 shared_var_i: integer (shared)
2208 individual_var_b: boolean
2209 shared_var_b: boolean (shared)
2210 """
2211 )
2212 G = NeuronGroup(10, model)
2213 G.run_regularly(
2214 """
2215 shared_var = 1.0
2216 shared_var_i = 2
2217 shared_var_b = True
2218 individual_var = 1.0
2219 individual_var_i = 2
2220 individual_var_b = True
2221 """,
2222 dt=defaultclock.dt,
2223 )
2224 run(defaultclock.dt)
2225 assert_equal(G.shared_var[:], 1.0)
2226 assert_equal(G.individual_var[:], np.ones(10))
2227 assert_equal(G.shared_var_i[:], 2)
2228 assert_equal(G.individual_var_i[:], 2 * np.ones(10, dtype=int))
2229 assert_equal(G.shared_var_b[:], True)
2230 assert_equal(G.individual_var_b[:], np.ones(10, dtype=bool))
2231
2232
2233 @pytest.mark.standalone_compatible
2234 def test_semantics_floor_division():
2235 # See github issues #815, #661, and #1495
2236 G = NeuronGroup(
2237 300,
2238 """
2239 a : integer
2240 b : integer
2241 x : 1
2242 y : 1
2243 fvalue : 1
2244 ivalue : integer
2245 """,
2246 dtype={"a": np.int32, "b": np.int64, "x": float, "y": float},
2247 )
2248 int_values = np.arange(-150, 150)
2249 float_values = np.linspace(-100, 100, 300, dtype=np.float64)
2250 G.ivalue = int_values
2251 G.fvalue = float_values
2252 with catch_logs() as l:
2253 G.run_regularly(
2254 """
2255 a = ivalue//98
2256 b = ivalue//98
2257 x = fvalue//98
2258 y = fvalue//98
2259 """
2260 )
2261 run(defaultclock.dt)
2262 assert len(l) == 0
2263 assert_equal(G.a[:], int_values // 98)
2264 assert_equal(G.b[:], int_values // 98)
2265 assert_allclose(G.x[:], float_values // 98)
2266 assert_allclose(G.y[:], float_values // 98)
2267
2268
2269 @pytest.mark.standalone_compatible
2270 def test_semantics_floating_point_division():
2271 # See github issues #815 and #661
2272 G = NeuronGroup(
2273 11,
2274 """
2275 x1 : 1
2276 x2 : 1
2277 y1 : 1
2278 y2 : 1
2279 fvalue : 1
2280 ivalue : integer
2281 """,
2282 dtype={"a": np.int32, "b": np.int64, "x": float, "y": float},
2283 )
2284 int_values = np.arange(-5, 6)
2285 float_values = np.arange(-5.0, 6.0, dtype=np.float64)
2286 G.ivalue = int_values
2287 G.fvalue = float_values
2288 with catch_logs() as l:
2289 G.run_regularly(
2290 """
2291 x1 = ivalue/3
2292 x2 = fvalue/3
2293 y1 = ivalue/3
2294 y2 = fvalue/3
2295 """
2296 )
2297 run(defaultclock.dt)
2298
2299 assert_allclose(G.x1[:], int_values / 3)
2300 assert_allclose(G.y1[:], int_values / 3)
2301 assert_allclose(G.x2[:], float_values / 3)
2302 assert_allclose(G.y2[:], float_values / 3)
2303
2304
2305 @pytest.mark.standalone_compatible
2306 def test_semantics_mod():
2307 # See github issues #815 and #661
2308 G = NeuronGroup(
2309 300,
2310 """
2311 a : integer
2312 b : integer
2313 x : 1
2314 y : 1
2315 fvalue : 1
2316 ivalue : integer
2317 """,
2318 dtype={"a": np.int32, "b": np.int64, "x": float, "y": float},
2319 )
2320 int_values = np.arange(-150, 150)
2321 float_values = np.linspace(-100, 100, 300, dtype=np.float64)
2322 G.ivalue = int_values
2323 G.fvalue = float_values
2324 with catch_logs() as l:
2325 G.run_regularly(
2326 """
2327 a = ivalue % 98
2328 b = ivalue % 98
2329 x = fvalue % 98
2330 y = fvalue % 98
2331 """
2332 )
2333 run(defaultclock.dt)
2334 assert len(l) == 0
2335 assert_equal(G.a[:], int_values % 98)
2336 assert_equal(G.b[:], int_values % 98)
2337 assert_allclose(G.x[:], float_values % 98)
2338 assert_allclose(G.y[:], float_values % 98)
2339
2340
2341 if __name__ == "__main__":
2342 test_set_states()
2343 test_creation()
2344 test_integer_variables_and_mod()
2345 test_variables()
2346 test_variableview_calculations()
2347 test_scalar_variable()
2348 test_referred_scalar_variable()
2349 test_linked_variable_correct()
2350 test_linked_variable_incorrect()
2351 test_linked_variable_scalar()
2352 test_linked_variable_indexed()
2353 test_linked_variable_repeat()
2354 test_linked_double_linked1()
2355 test_linked_double_linked2()
2356 test_linked_double_linked3()
2357 test_linked_double_linked4()
2358 test_linked_triple_linked()
2359 test_linked_subgroup()
2360 test_linked_subgroup2()
2361 test_linked_subexpression()
2362 test_linked_subexpression_2()
2363 test_linked_subexpression_3()
2364 test_linked_subexpression_synapse()
2365 test_linked_variable_indexed_incorrect()
2366 test_linked_synapses()
2367 test_linked_var_in_reset()
2368 test_linked_var_in_reset_size_1()
2369 test_linked_var_in_reset_incorrect()
2370 test_stochastic_variable()
2371 test_stochastic_variable_multiplicative()
2372 test_threshold_reset()
2373 test_unit_errors_threshold_reset()
2374 test_custom_events()
2375 test_custom_events_schedule()
2376 test_incorrect_custom_event_definition()
2377 test_incomplete_namespace()
2378 test_namespace_errors()
2379 test_namespace_warnings()
2380 test_syntax_errors()
2381 test_state_variables()
2382 test_state_variable_access()
2383 test_state_variable_access_strings()
2384 test_state_variable_set_strings()
2385 test_unknown_state_variables()
2386 test_subexpression()
2387 test_subexpression_with_constant()
2388 test_scalar_parameter_access()
2389 test_scalar_subexpression()
2390 test_sim_with_scalar_variable()
2391 test_sim_with_scalar_subexpression()
2392 test_constant_variable_subexpression()
2393 test_constant_subexpression_order()
2394 test_subexpression_checks()
2395 test_indices()
2396 test_repr()
2397 test_ipython_html()
2398 test_get_dtype()
2399 if prefs.codegen.target == "numpy":
2400 test_aliasing_in_statements()
2401 test_get_states()
2402 test_set_states()
2403 test_get_states_pandas()
2404 test_set_states_pandas()
2405 test_random_vector_values()
2406 test_random_values_random_seed()
2407 test_random_values_fixed_seed()
2408 test_random_values_fixed_seed_numbers()
2409 test_random_values_fixed_and_random()
2410 test_no_code()
2411 test_run_regularly_scheduling()
2412 test_run_regularly_scheduling_2()
2413 test_run_regularly_dt()
2414 test_semantics_floor_division()
2415 test_semantics_floating_point_division()
2416 test_semantics_mod()