Debian Codegraph @

brian2/tests/test_cpp_standalone.py

raw
1 import os
2 import platform
3 import tempfile
4
5 import pytest
6 from numpy.testing import assert_allclose, assert_equal
7
8 from brian2 import *
9 from brian2.devices import device_module
10 from brian2.devices.device import reinit_and_delete, reset_device, set_device
11 from brian2.tests.utils import assert_allclose
12 from brian2.utils.logger import catch_logs
13
14
15 @pytest.mark.cpp_standalone
16 @pytest.mark.standalone_only
17 def test_cpp_standalone():
18 set_device("cpp_standalone", build_on_run=False)
19 ##### Define the model
20 tau = 1 * ms
21 eqs = """
22 dV/dt = (-40*mV-V)/tau : volt (unless refractory)
23 """
24 threshold = "V>-50*mV"
25 reset = "V=-60*mV"
26 refractory = 5 * ms
27 N = 1000
28
29 G = NeuronGroup(
30 N, eqs, reset=reset, threshold=threshold, refractory=refractory, name="gp"
31 )
32 G.V = "-i*mV"
33 M = SpikeMonitor(G)
34 S = Synapses(G, G, "w : volt", on_pre="V += w")
35 S.connect("abs(i-j)<5 and i!=j")
36 S.w = 0.5 * mV
37 S.delay = "0*ms"
38
39 net = Network(G, M, S)
40 net.run(100 * ms)
41 device.build(directory=None, with_output=False)
42 # we do an approximate equality here because depending on minor details of how it was compiled, the results
43 # may be slightly different (if -ffast-math is on)
44 assert len(M.i) >= 17000 and len(M.i) <= 18000
45 assert len(M.t) == len(M.i)
46 assert M.t[0] == 0.0
47 reset_device()
48
49
50 @pytest.mark.cpp_standalone
51 @pytest.mark.standalone_only
52 def test_multiple_connects():
53 set_device("cpp_standalone", build_on_run=False)
54 G = NeuronGroup(10, "v:1")
55 S = Synapses(G, G, "w:1")
56 S.connect(i=[0], j=[0])
57 S.connect(i=[1], j=[1])
58 run(0 * ms)
59 device.build(directory=None, with_output=False)
60 assert len(S) == 2 and len(S.w[:]) == 2
61 reset_device()
62
63
64 @pytest.mark.cpp_standalone
65 @pytest.mark.standalone_only
66 def test_device_cache_synapses():
67 # Check that we can ask for known synaptic information at runtime
68 set_device("cpp_standalone", build_on_run=False)
69 G = NeuronGroup(10, "v:1")
70 S = Synapses(G, G, "w:1")
71 S.connect(i=[0], j=[0])
72 assert len(S) == 1
73 assert_equal(S.i[:], [0])
74 assert_equal(S.j[:], [0])
75
76 S.connect(i=[1], j=[1])
77 assert len(S) == 2
78 assert_equal(S.i[:], [0, 1])
79 assert_equal(S.j[:], [0, 1])
80
81 S.connect(p=0.1) # We can't know anything about synapses anymore
82
83 with pytest.raises(NotImplementedError):
84 len(S)
85
86 with pytest.raises(NotImplementedError):
87 S.i[:]
88
89 with pytest.raises(NotImplementedError):
90 S.j[:]
91
92 S.connect(i=[1], j=[1])
93 # Synapses are still "unknown" due to the previous p=0.1 call
94 with pytest.raises(NotImplementedError):
95 len(S)
96
97 with pytest.raises(NotImplementedError):
98 S.i[:]
99
100 with pytest.raises(NotImplementedError):
101 S.j[:]
102
103
104 @pytest.mark.cpp_standalone
105 @pytest.mark.standalone_only
106 def test_storing_loading():
107 set_device("cpp_standalone", build_on_run=False)
108 G = NeuronGroup(
109 10,
110 """
111 v : volt
112 x : 1
113 n : integer
114 b : boolean
115 """,
116 )
117 v = np.arange(10) * volt
118 x = np.arange(10, 20)
119 n = np.arange(20, 30)
120 b = np.array([True, False]).repeat(5)
121 G.v = v
122 G.x = x
123 G.n = n
124 G.b = b
125 S = Synapses(
126 G,
127 G,
128 """
129 v_syn : volt
130 x_syn : 1
131 n_syn : integer
132 b_syn : boolean
133 """,
134 )
135 S.connect(j="i")
136 S.v_syn = v
137 S.x_syn = x
138 S.n_syn = n
139 S.b_syn = b
140 run(0 * ms)
141 device.build(directory=None, with_output=False)
142 assert_allclose(G.v[:], v)
143 assert_allclose(S.v_syn[:], v)
144 assert_allclose(G.x[:], x)
145 assert_allclose(S.x_syn[:], x)
146 assert_allclose(G.n[:], n)
147 assert_allclose(S.n_syn[:], n)
148 assert_allclose(G.b[:], b)
149 assert_allclose(S.b_syn[:], b)
150 reset_device()
151
152
153 @pytest.mark.cpp_standalone
154 @pytest.mark.standalone_only
155 @pytest.mark.openmp
156 def test_openmp_consistency():
157 previous_device = get_device()
158 n_cells = 100
159 n_recorded = 10
160 taum = 20 * ms
161 taus = 5 * ms
162 Vt = -50 * mV
163 Vr = -60 * mV
164 El = -49 * mV
165 fac = 60 * 0.27 / 10
166 gmax = 20 * fac
167 dApre = 0.01
168 taupre = 20 * ms
169 taupost = taupre
170 dApost = -dApre * taupre / taupost * 1.05
171 dApost *= 0.1 * gmax
172 dApre *= 0.1 * gmax
173
174 eqs = Equations(
175 """
176 dv/dt = (g-(v-El))/taum : volt
177 dg/dt = -g/taus : volt
178 """
179 )
180 numpy.random.seed(42)
181 connectivity = numpy.random.randn(n_cells, n_cells)
182 sources = numpy.random.randint(0, n_cells - 1, 10 * n_cells)
183 # Only use one spike per time step (to rule out that a single source neuron
184 # has more than one spike in a time step)
185 times = (
186 numpy.random.choice(numpy.arange(10 * n_cells), 10 * n_cells, replace=False)
187 * ms
188 )
189 v_init = Vr + numpy.random.rand(n_cells) * (Vt - Vr)
190
191 results = {}
192
193 for n_threads, devicename in [
194 (0, "runtime"),
195 (0, "cpp_standalone"),
196 (1, "cpp_standalone"),
197 (2, "cpp_standalone"),
198 (3, "cpp_standalone"),
199 (4, "cpp_standalone"),
200 ]:
201 set_device(devicename, build_on_run=False, with_output=False)
202 # clear all instances
203 Synapses.__instances__().clear()
204 if devicename == "cpp_standalone":
205 reinit_and_delete()
206 prefs.devices.cpp_standalone.openmp_threads = n_threads
207 P = NeuronGroup(
208 n_cells, model=eqs, threshold="v>Vt", reset="v=Vr", refractory=5 * ms
209 )
210 Q = SpikeGeneratorGroup(n_cells, sources, times)
211 P.v = v_init.copy() # Use copy to avoid reference issues
212 P.g = 0 * mV
213 S = Synapses(
214 P,
215 P,
216 model="""
217 dApre/dt=-Apre/taupre : 1 (event-driven)
218 dApost/dt=-Apost/taupost : 1 (event-driven)
219 w : 1
220 """,
221 pre="""
222 g += w*mV
223 Apre += dApre
224 w = w + Apost
225 """,
226 post="""
227 Apost += dApost
228 w = w + Apre
229 """,
230 )
231 S.connect()
232
233 S.w = fac * connectivity.flatten()
234
235 T = Synapses(Q, P, model="w : 1", on_pre="g += w*mV")
236 T.connect(j="i")
237 T.w = 10 * fac
238
239 spike_mon = SpikeMonitor(P)
240 rate_mon = PopulationRateMonitor(P)
241 state_mon = StateMonitor(S, "w", record=np.arange(n_recorded), dt=0.1 * second)
242 v_mon = StateMonitor(P, "v", record=np.arange(n_recorded))
243
244 run(0.2 * second, report="text")
245
246 if devicename == "cpp_standalone":
247 device.build(directory=None, with_output=False)
248
249 results[n_threads, devicename] = {}
250 results[n_threads, devicename]["w"] = state_mon.w.copy()
251 results[n_threads, devicename]["v"] = v_mon.v.copy()
252 results[n_threads, devicename]["s"] = spike_mon.num_spikes
253 results[n_threads, devicename]["r"] = rate_mon.rate[:].copy()
254
255 # Now run the assertions
256 for key1, key2 in [
257 ((0, "runtime"), (0, "cpp_standalone")),
258 ((1, "cpp_standalone"), (0, "cpp_standalone")),
259 ((2, "cpp_standalone"), (0, "cpp_standalone")),
260 ((3, "cpp_standalone"), (0, "cpp_standalone")),
261 ((4, "cpp_standalone"), (0, "cpp_standalone")),
262 ]:
263 assert_allclose(results[key1]["w"], results[key2]["w"])
264 assert_allclose(results[key1]["v"], results[key2]["v"])
265 assert_allclose(results[key1]["r"], results[key2]["r"])
266 assert_allclose(results[key1]["s"], results[key2]["s"])
267 reset_device(previous_device)
268
269
270 @pytest.mark.cpp_standalone
271 @pytest.mark.standalone_only
272 def test_duplicate_names_across_nets():
273 set_device("cpp_standalone", build_on_run=False)
274 # In standalone mode, names have to be globally unique, not just unique
275 # per network
276 obj1 = BrianObject(name="name1")
277 obj2 = BrianObject(name="name2")
278 obj3 = BrianObject(name="name3")
279 obj4 = BrianObject(name="name1")
280 net1 = Network(obj1, obj2)
281 net2 = Network(obj3, obj4)
282 net1.run(0 * ms)
283 net2.run(0 * ms)
284 with pytest.raises(ValueError):
285 device.build()
286
287 reset_device()
288
289
290 @pytest.mark.cpp_standalone
291 @pytest.mark.standalone_only
292 @pytest.mark.openmp
293 def test_openmp_scalar_writes():
294 # Test that writing to a scalar variable only is done once in an OpenMP
295 # setting (see github issue #551)
296 set_device("cpp_standalone", build_on_run=False)
297 prefs.devices.cpp_standalone.openmp_threads = 4
298 G = NeuronGroup(10, "s : 1 (shared)")
299 G.run_regularly("s += 1")
300 run(defaultclock.dt)
301 device.build(directory=None, with_output=False)
302 assert_equal(G.s[:], 1.0)
303
304 reset_device()
305
306
307 @pytest.mark.cpp_standalone
308 @pytest.mark.standalone_only
309 def test_time_after_run():
310 set_device("cpp_standalone", build_on_run=False)
311 # Check that the clock and network time after a run is correct, even if we
312 # have not actually run the code yet (via build)
313 G = NeuronGroup(10, "dv/dt = -v/(10*ms) : 1")
314 net = Network(G)
315 assert_allclose(defaultclock.dt, 0.1 * ms)
316 assert_allclose(defaultclock.t, 0.0 * ms)
317 assert_allclose(G.t, 0.0 * ms)
318 assert_allclose(net.t, 0.0 * ms)
319 net.run(10 * ms)
320 assert_allclose(defaultclock.t, 10.0 * ms)
321 assert_allclose(G.t, 10.0 * ms)
322 assert_allclose(net.t, 10.0 * ms)
323 net.run(10 * ms)
324 assert_allclose(defaultclock.t, 20.0 * ms)
325 assert_allclose(G.t, 20.0 * ms)
326 assert_allclose(net.t, 20.0 * ms)
327 device.build(directory=None, with_output=False)
328 # Everything should of course still be accessible
329 assert_allclose(defaultclock.t, 20.0 * ms)
330 assert_allclose(G.t, 20.0 * ms)
331 assert_allclose(net.t, 20.0 * ms)
332
333 reset_device()
334
335
336 @pytest.mark.cpp_standalone
337 @pytest.mark.standalone_only
338 def test_array_cache():
339 # Check that variables are only accessible from Python when they should be
340 set_device("cpp_standalone", build_on_run=False)
341 G = NeuronGroup(
342 10,
343 """
344 dv/dt = -v / (10*ms) : 1
345 w : 1
346 x : 1
347 y : 1
348 z : 1 (shared)
349 """,
350 threshold="v>1",
351 )
352 S = Synapses(G, G, "weight: 1", on_pre="w += weight")
353 S.connect(p=0.2)
354 S.weight = 7
355 # All neurongroup values should be known
356 assert_allclose(G.v, 0)
357 assert_allclose(G.w, 0)
358 assert_allclose(G.x, 0)
359 assert_allclose(G.y, 0)
360 assert_allclose(G.z, 0)
361 assert_allclose(G.i, np.arange(10))
362
363 # But the synaptic variable is not -- we don't know the number of synapses
364 with pytest.raises(NotImplementedError):
365 S.weight[:]
366
367 # Setting variables with explicit values should not change anything
368 G.v = np.arange(10) + 1
369 G.w = 2
370 G.y = 5
371 G.z = 7
372 assert_allclose(G.v, np.arange(10) + 1)
373 assert_allclose(G.w, 2)
374 assert_allclose(G.y, 5)
375 assert_allclose(G.z, 7)
376
377 # But setting with code should invalidate them
378 G.x = "i*2"
379 with pytest.raises(NotImplementedError):
380 G.x[:]
381
382 # Make sure that the array cache does not allow to use incorrectly sized
383 # values to pass
384 with pytest.raises(ValueError):
385 G.w = [0, 2]
386 with pytest.raises(ValueError):
387 G.w.__setitem__(slice(0, 4), [0, 2])
388
389 run(10 * ms)
390 # v is now no longer known without running the network
391 with pytest.raises(NotImplementedError):
392 G.v[:]
393 # Neither is w, it is updated in the synapse
394 with pytest.raises(NotImplementedError):
395 G.w[:]
396 # However, no code touches y or z
397 assert_allclose(G.y, 5)
398 assert_allclose(G.z, 7)
399 # i is read-only anyway
400 assert_allclose(G.i, np.arange(10))
401
402 # After actually running the network, everything should be accessible
403 device.build(directory=None, with_output=False)
404 assert all(G.v > 0)
405 assert all(G.w > 0)
406 assert_allclose(G.x, np.arange(10) * 2)
407 assert_allclose(G.y, 5)
408 assert_allclose(G.z, 7)
409 assert_allclose(G.i, np.arange(10))
410 assert_allclose(S.weight, 7)
411
412
413 @pytest.mark.cpp_standalone
414 @pytest.mark.standalone_only
415 def test_run_with_debug():
416 # We just want to make sure that it works for now (i.e. not fails with a
417 # compilation or runtime error), capturing the output is actually
418 # a bit involved to get right.
419 set_device("cpp_standalone", build_on_run=True, debug=True, directory=None)
420 group = NeuronGroup(1, "v: 1", threshold="False")
421 syn = Synapses(group, group, on_pre="v += 1")
422 syn.connect()
423 mon = SpikeMonitor(group)
424 run(defaultclock.dt)
425
426
427 @pytest.mark.cpp_standalone
428 @pytest.mark.standalone_only
429 def test_run_with_clean():
430 # We just want to make sure that it works for now (there was a bug on Windows where
431 # using clean=True deleted sourcefiles.txt)
432 set_device(
433 "cpp_standalone", build_on_run=True, debug=True, clean=True, directory=None
434 )
435 group = NeuronGroup(1, "v: 1", threshold="False")
436 syn = Synapses(group, group, on_pre="v += 1")
437 syn.connect()
438 mon = SpikeMonitor(group)
439 run(defaultclock.dt)
440
441
442 @pytest.mark.cpp_standalone
443 @pytest.mark.standalone_only
444 def test_run_with_synapses_and_profile():
445 set_device("cpp_standalone", build_on_run=True, directory=None)
446 group = NeuronGroup(1, "v: 1", threshold="False", reset="")
447 syn = Synapses(group, group, on_pre="v += 1")
448 syn.connect()
449 mon = SpikeMonitor(group)
450 run(defaultclock.dt, profile=True)
451
452
453 @pytest.mark.cpp_standalone
454 @pytest.mark.standalone_only
455 def test_changing_profile_arg():
456 set_device("cpp_standalone", build_on_run=False)
457 G = NeuronGroup(10000, "v : 1")
458 op1 = G.run_regularly("v = exp(-v)", name="op1")
459 op2 = G.run_regularly("v = exp(-v)", name="op2")
460 op3 = G.run_regularly("v = exp(-v)", name="op3")
461 op4 = G.run_regularly("v = exp(-v)", name="op4")
462 # Op 1 is active only during the first profiled run
463 # Op 2 is active during both profiled runs
464 # Op 3 is active only during the second profiled run
465 # Op 4 is never active (only during the unprofiled run)
466 op1.active = True
467 op2.active = True
468 op3.active = False
469 op4.active = False
470 run(1000 * defaultclock.dt, profile=True)
471 op1.active = True
472 op2.active = True
473 op3.active = True
474 op4.active = True
475 run(1000 * defaultclock.dt, profile=False)
476 op1.active = False
477 op2.active = True
478 op3.active = True
479 op4.active = False
480 run(1000 * defaultclock.dt, profile=True)
481 device.build(directory=None, with_output=False)
482 profiling_dict = dict(magic_network.profiling_info)
483 # Note that for now, C++ standalone creates a new CodeObject for every run,
484 # which is most of the time unnecessary (this is partly due to the way we
485 # handle constants: they are included as literals in the code but they can
486 # change between runs). Therefore, the profiling info is potentially
487 # difficult to interpret
488 assert len(profiling_dict) == 4 # 2 during first run, 2 during last run
489 # The two code objects that were executed during the first run
490 assert (
491 "op1_codeobject" in profiling_dict
492 and profiling_dict["op1_codeobject"] > 0 * second
493 )
494 assert (
495 "op2_codeobject" in profiling_dict
496 and profiling_dict["op2_codeobject"] > 0 * second
497 )
498 # Four code objects were executed during the second run, but no profiling
499 # information was saved
500 for name in [
501 "op1_codeobject_1",
502 "op2_codeobject_1",
503 "op3_codeobject",
504 "op4_codeobject",
505 ]:
506 assert name not in profiling_dict
507 # Two code objects were exectued during the third run
508 assert (
509 "op2_codeobject_2" in profiling_dict
510 and profiling_dict["op2_codeobject_2"] > 0 * second
511 )
512 assert (
513 "op3_codeobject_1" in profiling_dict
514 and profiling_dict["op3_codeobject_1"] > 0 * second
515 )
516
517
518 @pytest.mark.cpp_standalone
519 @pytest.mark.standalone_only
520 def test_profile_via_set_device_arg():
521 set_device("cpp_standalone", build_on_run=False, profile=True)
522 G = NeuronGroup(10000, "v : 1")
523 op1 = G.run_regularly("v = exp(-v)", name="op1")
524 op2 = G.run_regularly("v = exp(-v)", name="op2")
525 op3 = G.run_regularly("v = exp(-v)", name="op3")
526 op4 = G.run_regularly("v = exp(-v)", name="op4")
527 # Op 1 is active only during the first profiled run
528 # Op 2 is active during both profiled runs
529 # Op 3 is active only during the second profiled run
530 # Op 4 is never active (only during the unprofiled run)
531 op1.active = True
532 op2.active = True
533 op3.active = False
534 op4.active = False
535 run(1000 * defaultclock.dt) # Should use profile=True via set_device
536 op1.active = True
537 op2.active = True
538 op3.active = True
539 op4.active = True
540 run(1000 * defaultclock.dt, profile=False)
541 op1.active = False
542 op2.active = True
543 op3.active = True
544 op4.active = False
545 run(1000 * defaultclock.dt, profile=True)
546 device.build(directory=None, with_output=False)
547 profiling_dict = dict(magic_network.profiling_info)
548 # Note that for now, C++ standalone creates a new CodeObject for every run,
549 # which is most of the time unnecessary (this is partly due to the way we
550 # handle constants: they are included as literals in the code but they can
551 # change between runs). Therefore, the profiling info is potentially
552 # difficult to interpret
553 assert len(profiling_dict) == 4 # 2 during first run, 2 during last run
554 # The two code objects that were executed during the first run
555 assert (
556 "op1_codeobject" in profiling_dict
557 and profiling_dict["op1_codeobject"] > 0 * second
558 )
559 assert (
560 "op2_codeobject" in profiling_dict
561 and profiling_dict["op2_codeobject"] > 0 * second
562 )
563 # Four code objects were executed during the second run, but no profiling
564 # information was saved
565 for name in [
566 "op1_codeobject_1",
567 "op2_codeobject_1",
568 "op3_codeobject",
569 "op4_codeobject",
570 ]:
571 assert name not in profiling_dict
572 # Two code objects were exectued during the third run
573 assert (
574 "op2_codeobject_2" in profiling_dict
575 and profiling_dict["op2_codeobject_2"] > 0 * second
576 )
577 assert (
578 "op3_codeobject_1" in profiling_dict
579 and profiling_dict["op3_codeobject_1"] > 0 * second
580 )
581
582
583 @pytest.mark.cpp_standalone
584 @pytest.mark.standalone_only
585 def test_delete_code_data():
586 set_device("cpp_standalone", build_on_run=False)
587 group = NeuronGroup(10, "dv/dt = -v / (10*ms) : volt", method="exact")
588 group.v = np.arange(10) * mV # uses the static array mechanism
589 run(defaultclock.dt)
590 # Overwrite the initial values via run_args mechanims
591 device.build(run_args={group.v: np.arange(10)[::-1] * mV}, directory=None)
592 results_dir = os.path.join(device.project_dir, "results")
593 assert os.path.exists(results_dir) and os.path.isdir(results_dir)
594 # There should be 3 files for the clock, 2 for the neurongroup (index + v),
595 # as well as the default "last_run_info.txt" and "random_generator_state" files
596 assert len(os.listdir(results_dir)) == 7
597 device.delete(data=True, run_args=False, code=False, directory=False)
598 assert os.path.exists(results_dir) and os.path.isdir(results_dir)
599 assert len(os.listdir(results_dir)) == 0
600 static_arrays_before = len(
601 os.listdir(os.path.join(device.project_dir, "static_arrays"))
602 )
603 assert static_arrays_before > 0
604 assert len(os.listdir(os.path.join(device.project_dir, "code_objects"))) > 0
605 device.delete(data=False, code=True, run_args=False, directory=False)
606 assert (
607 0
608 < len(os.listdir(os.path.join(device.project_dir, "static_arrays")))
609 < static_arrays_before
610 )
611 assert len(os.listdir(os.path.join(device.project_dir, "code_objects"))) == 0
612 device.delete(data=False, code=False, run_args=True, directory=False)
613 len(os.listdir(os.path.join(device.project_dir, "static_arrays"))) == 0
614
615
616 @pytest.mark.cpp_standalone
617 @pytest.mark.standalone_only
618 def test_delete_directory():
619 set_device("cpp_standalone", build_on_run=True, directory=None)
620 group = NeuronGroup(10, "dv/dt = -v / (10*ms) : volt", method="exact")
621 group.v = np.arange(10) * mV # uses the static array mechanism
622 run(defaultclock.dt)
623 # Add a new file
624 dummy_file = os.path.join(device.project_dir, "results", "dummy.txt")
625 open(dummy_file, "w").flush()
626 assert os.path.isfile(dummy_file)
627 with catch_logs() as logs:
628 device.delete(directory=True)
629 assert (
630 len(
631 [
632 l
633 for l in logs
634 if l[1] == "brian2.devices.cpp_standalone.device.delete_skips_directory"
635 ]
636 )
637 == 1
638 )
639 assert os.path.isfile(dummy_file)
640 with catch_logs() as logs:
641 device.delete(directory=True, force=True)
642 assert (
643 len(
644 [
645 l
646 for l in logs
647 if l[1] == "brian2.devices.cpp_standalone.device.delete_skips_directory"
648 ]
649 )
650 == 0
651 )
652 # everything should be deleted
653 assert not os.path.exists(device.project_dir)
654
655
656 @pytest.mark.cpp_standalone
657 @pytest.mark.standalone_only
658 def test_multiple_standalone_runs():
659 # see github issue #1189
660 set_device("cpp_standalone", directory=None)
661
662 network = Network()
663 Pe = NeuronGroup(1, "v : 1", threshold="False")
664 C_ee = Synapses(Pe, Pe, on_pre="v += 1")
665 C_ee.connect()
666 network.add(Pe, C_ee)
667 network.run(defaultclock.dt)
668
669 device.reinit()
670 device.activate(directory=None)
671
672 network2 = Network()
673 Pe = NeuronGroup(1, "v : 1", threshold="False")
674 C_ee = Synapses(Pe, Pe, on_pre="v += 1")
675 C_ee.connect()
676 network2.add(Pe, C_ee)
677 network2.run(defaultclock.dt)
678
679
680 @pytest.mark.cpp_standalone
681 @pytest.mark.standalone_only
682 def test_continued_standalone_runs():
683 # see github issue #1237
684 set_device("cpp_standalone", build_on_run=False)
685
686 source = SpikeGeneratorGroup(1, [0], [0] * ms)
687 target = NeuronGroup(1, "v : 1")
688 C_ee = Synapses(source, target, on_pre="v += 1", delay=2 * ms)
689 C_ee.connect()
690 run(1 * ms)
691 # Spike has not been delivered yet
692 run(2 * ms)
693
694 device.build(directory=None)
695 assert target.v[0] == 1 # Make sure the spike got delivered
696
697
698 @pytest.mark.cpp_standalone
699 @pytest.mark.standalone_only
700 def test_constant_replacement():
701 # see github issue #1276
702 set_device("cpp_standalone")
703 x = 42
704 G = NeuronGroup(1, "y : 1")
705 G.y = "x"
706 run(0 * ms)
707 assert G.y[0] == 42.0
708
709
710 @pytest.mark.cpp_standalone
711 @pytest.mark.standalone_only
712 def test_change_parameter_without_recompile():
713 prefs.core.default_float_dtype = np.float32
714 set_device("cpp_standalone", directory=None, with_output=True, debug=True)
715 on_off = TimedArray([True, False, True], dt=defaultclock.dt, name="on_off")
716 stim = TimedArray(
717 np.arange(30).reshape(3, 10) * nA, dt=defaultclock.dt, name="stim"
718 )
719 G = NeuronGroup(
720 10,
721 """
722 x : 1 (constant)
723 v : volt (constant)
724 n : integer (constant)
725 b : boolean (constant)
726 s = int(on_off(t))*stim(t, i) : amp
727 """,
728 name="neurons",
729 )
730 G.x = np.arange(10)
731 G.n = np.arange(10)
732 G.b = np.arange(10) % 2 == 0
733 G.v = np.arange(10) * volt
734 mon = StateMonitor(G, "s", record=True)
735 run(3 * defaultclock.dt)
736 assert array_equal(G.x, np.arange(10))
737 assert array_equal(G.n, np.arange(10))
738 assert array_equal(G.b, np.arange(10) % 2 == 0)
739 assert array_equal(G.v, np.arange(10) * volt)
740 assert_allclose(
741 mon.s.T / nA,
742 np.array(
743 [
744 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
745 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # on_off(t) == False
746 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
747 ]
748 ),
749 )
750
751 device.run(
752 run_args=[
753 "neurons.x=5",
754 "neurons.v=3",
755 "neurons.n=17",
756 "neurons.b=True",
757 "on_off.values=True",
758 ]
759 )
760 assert array_equal(G.x, np.ones(10) * 5)
761 assert array_equal(G.n, np.ones(10) * 17)
762 assert array_equal(G.b, np.ones(10, dtype=bool))
763 assert array_equal(G.v, np.ones(10) * 3 * volt)
764 assert_allclose(
765 mon.s.T / nA,
766 np.array(
767 [
768 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
769 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
770 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
771 ]
772 ),
773 )
774 ar = np.arange(10) * 2.0
775 ar.astype(G.x.dtype).tofile(os.path.join(device.project_dir, "init_values_x1.dat"))
776 ar.astype(G.n.dtype).tofile(os.path.join(device.project_dir, "init_values_n1.dat"))
777 (np.arange(10) % 2 != 0).tofile(
778 os.path.join(device.project_dir, "init_values_b1.dat")
779 )
780 ar.astype(G.v.dtype).tofile(os.path.join(device.project_dir, "init_values_v1.dat"))
781 ar2 = 2 * np.arange(30).reshape(3, 10) * nA
782 ar2.astype(stim.values.dtype).tofile(
783 os.path.join(device.project_dir, "init_stim_values.dat")
784 )
785 device.run(
786 run_args=[
787 "neurons.v=init_values_v1.dat",
788 "neurons.x=init_values_x1.dat",
789 "neurons.b=init_values_b1.dat",
790 "neurons.n=init_values_n1.dat",
791 "stim.values=init_stim_values.dat",
792 ]
793 )
794 assert array_equal(G.x, ar)
795 assert array_equal(G.n, ar)
796 assert array_equal(G.b, np.arange(10) % 2 != 0)
797 assert array_equal(G.v, ar * volt)
798 assert_allclose(
799 mon.s.T / nA,
800 np.array(
801 [
802 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
803 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # on_off(t) == False
804 [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
805 ]
806 ),
807 )
808 reset_device()
809
810
811 @pytest.mark.cpp_standalone
812 @pytest.mark.standalone_only
813 def test_change_parameter_without_recompile_errors():
814 set_device("cpp_standalone", directory=None, with_output=False)
815 G = NeuronGroup(10, "v:volt", name="neurons")
816 G.v = np.arange(10) * volt
817
818 run(0 * ms)
819
820 with pytest.raises(DimensionMismatchError):
821 device.run(run_args={G.v: 5})
822 with pytest.raises(DimensionMismatchError):
823 device.run(run_args={G.v: 5 * siemens})
824 with pytest.raises(TypeError):
825 device.run(run_args={G.v: np.arange(9) * volt})
826
827 reset_device()
828
829
830 @pytest.mark.cpp_standalone
831 @pytest.mark.standalone_only
832 def test_change_parameter_without_recompile_dict_syntax():
833 set_device("cpp_standalone", directory=None, with_output=False)
834 on_off = TimedArray([True, False, True], dt=defaultclock.dt, name="on_off")
835 stim = TimedArray(
836 np.arange(30).reshape(3, 10) * nA, dt=defaultclock.dt, name="stim"
837 )
838 G = NeuronGroup(
839 10,
840 """
841 x : 1 (constant)
842 n : integer (constant)
843 b : boolean (constant)
844 v : volt (constant)
845 s = int(on_off(t))*stim(t, i) : amp
846 """,
847 name="neurons",
848 )
849 G.x = np.arange(10)
850 G.n = np.arange(10)
851 G.b = np.arange(10) % 2 == 0
852 G.v = np.arange(10) * volt
853 mon = StateMonitor(G, "s", record=True)
854 run(3 * defaultclock.dt)
855 assert array_equal(G.x, np.arange(10))
856 assert array_equal(G.n, np.arange(10))
857 assert array_equal(G.b, np.arange(10) % 2 == 0)
858 assert array_equal(G.v, np.arange(10) * volt)
859 assert_allclose(
860 mon.s.T / nA,
861 np.array(
862 [
863 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
864 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # on_off(t) == False
865 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
866 ]
867 ),
868 )
869 device.run(run_args={G.x: 5, G.v: 3 * volt, G.n: 17, G.b: True, on_off: True})
870 assert array_equal(G.x, np.ones(10) * 5)
871 assert array_equal(G.n, np.ones(10) * 17)
872 assert array_equal(G.b, np.ones(10, dtype=bool))
873 assert array_equal(G.v, np.ones(10) * 3 * volt)
874 assert_allclose(
875 mon.s.T / nA,
876 np.array(
877 [
878 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
879 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
880 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
881 ]
882 ),
883 )
884 ar = np.arange(10) * 2.0
885 ar2 = 2 * np.arange(30).reshape(3, 10) * nA
886 device.run(
887 run_args={
888 G.x: ar,
889 G.v: ar * volt,
890 G.n: ar,
891 G.b: np.arange(10) % 2 != 0,
892 stim: ar2,
893 }
894 )
895 assert array_equal(G.x, ar)
896 assert array_equal(G.n, ar)
897 assert array_equal(G.b, np.arange(10) % 2 != 0)
898 assert array_equal(G.v, ar * volt)
899 assert_allclose(
900 mon.s.T / nA,
901 np.array(
902 [
903 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
904 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # on_off(t) == False
905 [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
906 ]
907 ),
908 )
909 reset_device()
910
911
912 @pytest.mark.cpp_standalone
913 @pytest.mark.standalone_only
914 def test_change_synapse_parameter_without_recompile_dict_syntax():
915 set_device("cpp_standalone", directory=None, with_output=False)
916 G = NeuronGroup(10, "", name="neurons")
917 S = Synapses(G, G, "w:1", name="Synapses")
918 S.connect(j="i")
919 S.w = np.arange(10)
920 run(0 * ms)
921 assert array_equal(S.w, np.arange(10))
922
923 device.run(run_args={S.w: 17})
924 assert array_equal(S.w, np.ones(10) * 17)
925
926 ar = np.arange(10) * 2.0
927 device.run(run_args={S.w: ar})
928 assert array_equal(S.w, ar)
929
930 reset_device()
931
932
933 @pytest.mark.cpp_standalone
934 @pytest.mark.standalone_only
935 def test_change_parameter_without_recompile_dependencies():
936 set_device("cpp_standalone", directory=None, with_output=False)
937 G = NeuronGroup(
938 10,
939 """
940 v:volt
941 w:1
942 """,
943 name="neurons",
944 )
945 G.v = np.arange(10) * volt
946 device.apply_run_args()
947 G.w = "v/volt*2"
948
949 run(0 * ms)
950 assert array_equal(G.v, np.arange(10))
951 assert array_equal(G.w, np.arange(10) * 2)
952
953 device.run(run_args=["neurons.v=5"])
954 assert array_equal(G.v, np.ones(10) * 5 * volt)
955 assert array_equal(G.w, np.ones(10) * 5 * 2)
956
957 ar = np.arange(10) * 2.0
958 ar.astype(G.v.dtype).tofile(os.path.join(device.project_dir, "init_values_v2.dat"))
959 device.run(run_args=["neurons.v=init_values_v2.dat"])
960 assert array_equal(G.v, ar * volt)
961 assert array_equal(G.w, ar * 2)
962
963 reset_device()
964
965
966 class RunSim:
967 def __init__(self):
968 self.device = get_device()
969 self.G = NeuronGroup(
970 10,
971 """
972 v:volt
973 w:1
974 x:1
975 """,
976 name="neurons",
977 )
978 run(0 * ms)
979
980 def run_sim(self, idx):
981 # Ugly hack needed for windows
982 device_module.active_device = self.device
983 device.run(
984 results_directory=f"results_{idx}",
985 run_args={
986 self.G.v: idx * volt,
987 self.G.w: np.arange(10), # Same values for all processes
988 self.G.x: np.arange(10) * idx, # Different values
989 },
990 )
991 return self.G.v[:], self.G.w[:], self.G.x[:]
992
993
994 @pytest.mark.cpp_standalone
995 @pytest.mark.standalone_only
996 @pytest.mark.skipif(
997 platform.system() == "Darwin" and platform.processor() == "arm",
998 reason="multiprocessing hangs on macOS with Apple Silicon",
999 )
1000 def test_change_parameters_multiprocessing():
1001 set_device("cpp_standalone", directory=None)
1002 sim = RunSim()
1003
1004 import multiprocessing
1005
1006 p = multiprocessing.Pool()
1007 try:
1008 results = p.map(sim.run_sim, range(5))
1009 finally:
1010 p.close()
1011 p.join()
1012
1013 for idx, result in zip(range(5), results):
1014 v, w, x = result
1015 assert array_equal(v, np.ones(10) * idx * volt)
1016 assert array_equal(w, np.arange(10))
1017 assert array_equal(x, np.arange(10) * idx)
1018
1019
1020 @pytest.mark.cpp_standalone
1021 @pytest.mark.standalone_only
1022 def test_header_file_inclusion():
1023 set_device("cpp_standalone", directory=None, debug=True)
1024 with tempfile.TemporaryDirectory() as tmpdir:
1025 with open(os.path.join(tmpdir, "foo.h"), "w") as f:
1026 f.write(
1027 """
1028 namespace brian_test_namespace {
1029 extern double test_variable;
1030 }
1031 """
1032 )
1033 with open(os.path.join(tmpdir, "foo.cpp"), "w") as f:
1034 f.write(
1035 """
1036 namespace brian_test_namespace {
1037 double test_variable = 42;
1038 }
1039 """
1040 )
1041
1042 @implementation(
1043 "cpp",
1044 """
1045 double brian_function(int index) {
1046 using namespace brian_test_namespace;
1047 return test_variable * index;
1048 }
1049 """,
1050 headers=['"foo.h"'],
1051 sources=[os.path.join(tmpdir, "foo.cpp")],
1052 include_dirs=[tmpdir],
1053 )
1054 @check_units(index=1, result=1)
1055 def brian_function(index):
1056 raise NotImplementedError()
1057
1058 # Use the function in a somewhat convoluted way that exposes errors in the
1059 # code generation process
1060 G = PoissonGroup(5, rates="brian_function(i)*Hz")
1061 S = Synapses(G, G, "rate_copy : Hz")
1062 S.connect(j="i")
1063 S.run_regularly("rate_copy = rates_pre")
1064 run(defaultclock.dt)
1065 assert_allclose(S.rate_copy[:], np.arange(len(G)) * 42 * Hz)
1066
1067
1068 @pytest.mark.cpp_standalone
1069 @pytest.mark.standalone_only
1070 def test_negative_duration_in_standalone_device():
1071 set_device("cpp_standalone")
1072 G = NeuronGroup(1, "v:1")
1073 with pytest.raises(ValueError):
1074 run(-1 * second)
1075
1076
1077 if __name__ == "__main__":
1078 for t in [
1079 test_cpp_standalone,
1080 test_multiple_connects,
1081 test_storing_loading,
1082 test_openmp_consistency,
1083 test_duplicate_names_across_nets,
1084 test_openmp_scalar_writes,
1085 test_time_after_run,
1086 test_array_cache,
1087 test_run_with_debug,
1088 test_changing_profile_arg,
1089 test_profile_via_set_device_arg,
1090 test_delete_code_data,
1091 test_delete_directory,
1092 test_multiple_standalone_runs,
1093 test_change_parameter_without_recompile,
1094 test_change_parameter_without_recompile_errors,
1095 test_change_parameter_without_recompile_dict_syntax,
1096 test_change_parameter_without_recompile_dependencies,
1097 test_change_synapse_parameter_without_recompile_dict_syntax,
1098 test_change_parameters_multiprocessing,
1099 test_header_file_inclusion,
1100 ]:
1101 t()
1102 reinit_and_delete()