Debian Codegraph @

brian2/tests/test_spikegenerator.py

raw
1 """
2 Tests for `SpikeGeneratorGroup`
3 """
4
5 import os
6 import tempfile
7
8 import pytest
9 from numpy.testing import assert_array_equal, assert_equal
10
11 from brian2 import *
12 from brian2.core.network import schedule_propagation_offset
13 from brian2.devices.device import reinit_and_delete
14 from brian2.tests.utils import assert_allclose, exc_isinstance
15 from brian2.utils.logger import catch_logs
16
17
18 @pytest.mark.standalone_compatible
19 def test_spikegenerator_connected():
20 """
21 Test that `SpikeGeneratorGroup` connects properly.
22 """
23 G = NeuronGroup(10, "v:1")
24 mon = StateMonitor(G, "v", record=True, when="end")
25 indices = np.array([3, 2, 1, 1, 4, 5])
26 times = np.array([6, 5, 4, 3, 3, 1]) * ms
27 SG = SpikeGeneratorGroup(10, indices, times)
28 S = Synapses(SG, G, on_pre="v+=1")
29 S.connect(j="i")
30 run(7 * ms)
31 # The following neurons should not receive any spikes
32 for idx in [0, 6, 7, 8, 9]:
33 assert all(mon[idx].v == 0)
34 offset = schedule_propagation_offset()
35 # The following neurons should receive a single spike
36 for idx, time in zip([2, 3, 4, 5], [5, 6, 3, 1] * ms):
37 assert all(mon[idx].v[mon.t < time + offset] == 0)
38 assert all(mon[idx].v[mon.t >= time + offset] == 1)
39 # This neuron receives two spikes
40 assert all(mon[1].v[mon.t < 3 * ms + offset] == 0)
41 assert all(mon[1].v[(mon.t >= 3 * ms + offset) & (mon.t < 4 * ms + offset)] == 1)
42 assert all(mon[1].v[(mon.t >= 4 * ms + offset)] == 2)
43
44
45 @pytest.mark.standalone_compatible
46 def test_spikegenerator_basic():
47 """
48 Basic test for `SpikeGeneratorGroup`.
49 """
50 indices = np.array([3, 2, 1, 1, 2, 3, 3, 2, 1])
51 times = np.array([1, 4, 4, 3, 2, 4, 2, 3, 2]) * ms
52 SG = SpikeGeneratorGroup(5, indices, times)
53 s_mon = SpikeMonitor(SG)
54 run(5 * ms)
55 _compare_spikes(5, indices, times, s_mon)
56
57
58 @pytest.mark.standalone_compatible
59 def test_spikegenerator_basic_sorted():
60 """
61 Basic test for `SpikeGeneratorGroup` with already sorted spike events.
62 """
63 indices = np.array([3, 1, 2, 3, 1, 2, 1, 2, 3])
64 times = np.array([1, 2, 2, 2, 3, 3, 4, 4, 4]) * ms
65 SG = SpikeGeneratorGroup(5, indices, times)
66 s_mon = SpikeMonitor(SG)
67 run(5 * ms)
68 _compare_spikes(5, indices, times, s_mon)
69
70
71 @pytest.mark.standalone_compatible
72 def test_spikegenerator_basic_sorted_with_sorted():
73 """
74 Basic test for `SpikeGeneratorGroup` with already sorted spike events.
75 """
76 indices = np.array([3, 1, 2, 3, 1, 2, 1, 2, 3])
77 times = np.array([1, 2, 2, 2, 3, 3, 4, 4, 4]) * ms
78 SG = SpikeGeneratorGroup(5, indices, times, sorted=True)
79 s_mon = SpikeMonitor(SG)
80 run(5 * ms)
81 _compare_spikes(5, indices, times, s_mon)
82
83
84 @pytest.mark.standalone_compatible
85 def test_spikegenerator_period():
86 """
87 Basic test for `SpikeGeneratorGroup`.
88 """
89 indices = np.array([3, 2, 1, 1, 2, 3, 3, 2, 1])
90 times = np.array([1, 4, 4, 3, 2, 4, 2, 3, 2]) * ms
91 SG = SpikeGeneratorGroup(5, indices, times, period=5 * ms)
92
93 s_mon = SpikeMonitor(SG)
94 run(10 * ms)
95 for idx in range(5):
96 generator_spikes = sorted(
97 [(idx, time) for time in times[indices == idx]]
98 + [(idx, time + 5 * ms) for time in times[indices == idx]]
99 )
100 recorded_spikes = sorted([(idx, time) for time in s_mon.t[s_mon.i == idx]])
101 assert_allclose(generator_spikes, recorded_spikes)
102
103
104 @pytest.mark.codegen_independent
105 def test_spikegenerator_extreme_period():
106 """
107 Basic test for `SpikeGeneratorGroup`.
108 """
109 indices = np.array([0, 1, 2])
110 times = np.array([0, 1, 2]) * ms
111 SG = SpikeGeneratorGroup(5, indices, times, period=1e6 * second)
112 s_mon = SpikeMonitor(SG)
113 with catch_logs() as l:
114 run(10 * ms)
115
116 assert_equal(s_mon.i, np.array([0, 1, 2]))
117 assert_allclose(s_mon.t, [0, 1, 2] * ms)
118 assert len(l) == 1 and l[0][1].endswith("spikegenerator_long_period")
119
120
121 @pytest.mark.standalone_compatible
122 def test_spikegenerator_period_rounding():
123 # See discussion in PR #1042
124 # The last spike will be considered to be in the time step *after* 1s, due
125 # to the way our rounding works. Although probably not what the user
126 # expects, this should therefore raise an error. In previous versions of
127 # Brian, this did not raise any error but silently discarded the spike.
128 with pytest.raises(ValueError):
129 SpikeGeneratorGroup(
130 1, [0, 0, 0], [0 * ms, 0.9 * ms, 0.99999 * ms], period=1 * ms, dt=0.1 * ms
131 )
132 # This should also raise a ValueError, since the last two spikes fall into
133 # the same bin
134 s = SpikeGeneratorGroup(
135 1, [0, 0, 0], [0 * ms, 0.9 * ms, 0.96 * ms], period=1 * ms, dt=0.1 * ms
136 )
137 net = Network(s)
138 with pytest.raises(BrianObjectException) as exc:
139 net.run(0 * ms)
140 assert exc_isinstance(exc, ValueError)
141
142
143 def test_spikegenerator_period_repeat():
144 """
145 Basic test for `SpikeGeneratorGroup`.
146 """
147 indices = np.zeros(10)
148 times = arange(0, 1, 0.1) * ms
149
150 rec = np.rec.fromarrays([times, indices], names=["t", "i"])
151 rec.sort()
152 sorted_times = np.ascontiguousarray(rec.t) * 1000
153 sorted_indices = np.ascontiguousarray(rec.i)
154 SG = SpikeGeneratorGroup(1, indices, times, period=1 * ms)
155 s_mon = SpikeMonitor(SG)
156 net = Network(SG, s_mon)
157 rate = PopulationRateMonitor(SG)
158 for idx in range(5):
159 net.run(1 * ms)
160 assert (idx + 1) * len(SG.spike_time) == s_mon.num_spikes
161
162
163 def _compare_spikes(
164 N, indices, times, recorded, start_time=0 * ms, end_time=1e100 * second
165 ):
166 for idx in range(N):
167 generator_spikes = sorted([(idx, time) for time in times[indices == idx]])
168 recorded_spikes = sorted(
169 [
170 (idx, time)
171 for time in recorded.t[recorded.i == idx]
172 if time >= start_time and time < end_time
173 ]
174 )
175 assert_allclose(generator_spikes, recorded_spikes)
176
177
178 @pytest.mark.standalone_compatible
179 @pytest.mark.multiple_runs
180 def test_spikegenerator_change_spikes():
181 indices1 = np.array([3, 2, 1, 1, 2, 3, 3, 2, 1])
182 times1 = np.array([1, 4, 4, 3, 2, 4, 2, 3, 2]) * ms
183 SG = SpikeGeneratorGroup(5, indices1, times1)
184 s_mon = SpikeMonitor(SG)
185 net = Network(SG, s_mon)
186 net.run(5 * ms)
187
188 indices2 = np.array([3, 2, 1, 1, 2, 3, 3, 2, 1, 3, 3, 3, 1, 2])
189 times2 = (
190 np.array([1, 4, 4, 3, 2, 4, 2, 3, 2, 4.5, 4.7, 4.8, 4.5, 4.7]) * ms + 5 * ms
191 )
192
193 SG.set_spikes(indices2, times2)
194 net.run(5 * ms)
195
196 indices3 = np.array([4, 1, 0])
197 times3 = np.array([1, 3, 4]) * ms + 10 * ms
198
199 SG.set_spikes(indices3, times3)
200 net.run(5 * ms)
201 device.build(direct_call=False, **device.build_options)
202 _compare_spikes(5, indices1, times1, s_mon, 0 * ms, 5 * ms)
203 _compare_spikes(5, indices2, times2, s_mon, 5 * ms, 10 * ms)
204 _compare_spikes(5, indices3, times3, s_mon, 10 * ms)
205
206
207 @pytest.mark.standalone_compatible
208 @pytest.mark.multiple_runs
209 def test_spikegenerator_change_period():
210 """
211 Basic test for `SpikeGeneratorGroup`.
212 """
213 indices1 = np.array([3, 2, 1, 1, 2, 3, 3, 2, 1])
214 times1 = np.array([1, 4, 4, 3, 2, 4, 2, 3, 2]) * ms
215 SG = SpikeGeneratorGroup(5, indices1, times1, period=5 * ms)
216 s_mon = SpikeMonitor(SG)
217 net = Network(SG, s_mon)
218 net.run(10 * ms)
219
220 indices2 = np.array([3, 2, 1, 1, 2, 3, 3, 2, 1, 3, 3, 3, 1, 2])
221 times2 = (
222 np.array([1, 4, 4, 3, 2, 4, 2, 3, 2, 4.5, 4.7, 4.8, 4.5, 4.7]) * ms + 10 * ms
223 )
224
225 SG.set_spikes(indices2, times2)
226 net.run(10 * ms) # period should no longer be in effect
227 device.build(direct_call=False, **device.build_options)
228
229 _compare_spikes(
230 5,
231 np.hstack([indices1, indices1]),
232 np.hstack([times1, times1 + 5 * ms]),
233 s_mon,
234 0 * ms,
235 10 * ms,
236 )
237 _compare_spikes(5, indices2, times2, s_mon, 10 * ms)
238
239
240 @pytest.mark.codegen_independent
241 def test_spikegenerator_incorrect_values():
242 with pytest.raises(TypeError):
243 SpikeGeneratorGroup(0, [], [] * second)
244 # Floating point value for N
245 with pytest.raises(TypeError):
246 SpikeGeneratorGroup(1.5, [], [] * second)
247 # Negative index
248 with pytest.raises(ValueError):
249 SpikeGeneratorGroup(5, [0, 3, -1], [0, 1, 2] * ms)
250 # Too high index
251 with pytest.raises(ValueError):
252 SpikeGeneratorGroup(5, [0, 5, 1], [0, 1, 2] * ms)
253 # Negative time
254 with pytest.raises(ValueError):
255 SpikeGeneratorGroup(5, [0, 1, 2], [0, -1, 2] * ms)
256
257
258 @pytest.mark.codegen_independent
259 def test_spikegenerator_incorrect_period():
260 """
261 Test that you cannot provide incorrect period arguments or combine
262 inconsistent period and dt arguments.
263 """
264 # Period is negative
265 with pytest.raises(ValueError):
266 SpikeGeneratorGroup(1, [], [] * second, period=-1 * ms)
267
268 # Period is smaller than the highest spike time
269 with pytest.raises(ValueError):
270 SpikeGeneratorGroup(1, [0], [2] * ms, period=1 * ms)
271 # Period is not an integer multiple of dt
272 SG = SpikeGeneratorGroup(1, [], [] * second, period=1.25 * ms, dt=0.1 * ms)
273 net = Network(SG)
274 with pytest.raises(BrianObjectException) as exc:
275 net.run(0 * ms)
276 assert exc_isinstance(exc, NotImplementedError)
277
278 SG = SpikeGeneratorGroup(1, [], [] * second, period=0.101 * ms, dt=0.1 * ms)
279 net = Network(SG)
280 with pytest.raises(BrianObjectException) as exc:
281 net.run(0 * ms)
282 assert exc_isinstance(exc, NotImplementedError)
283
284 SG = SpikeGeneratorGroup(1, [], [] * second, period=3.333 * ms, dt=0.1 * ms)
285 net = Network(SG)
286 with pytest.raises(BrianObjectException) as exc:
287 net.run(0 * ms)
288 assert exc_isinstance(exc, NotImplementedError)
289
290 # This should not raise an error (see #1041)
291 SG = SpikeGeneratorGroup(1, [], [] * ms, period=150 * ms, dt=0.1 * ms)
292 net = Network(SG)
293 net.run(0 * ms)
294
295 # Period is smaller than dt
296 SG = SpikeGeneratorGroup(1, [], [] * second, period=1 * ms, dt=2 * ms)
297 net = Network(SG)
298 with pytest.raises(BrianObjectException) as exc:
299 net.run(0 * ms)
300 assert exc_isinstance(exc, ValueError)
301
302
303 def test_spikegenerator_rounding():
304 # all spikes should fall into the first time bin
305 indices = np.arange(100)
306 times = np.linspace(0, 0.1, 100, endpoint=False) * ms
307 SG = SpikeGeneratorGroup(100, indices, times, dt=0.1 * ms)
308 mon = SpikeMonitor(SG)
309 net = Network(SG, mon)
310 net.run(0.1 * ms)
311 assert_equal(mon.count, np.ones(100))
312
313 # all spikes should fall in separate bins
314 dt = 0.1 * ms
315 indices = np.zeros(10000)
316 times = np.arange(10000) * dt
317 SG = SpikeGeneratorGroup(1, indices, times, dt=dt)
318 target = NeuronGroup(
319 1, "count : 1", threshold="True", reset="count=0"
320 ) # set count to zero at every time step
321 syn = Synapses(SG, target, on_pre="count+=1")
322 syn.connect()
323 mon = StateMonitor(target, "count", record=0, when="end")
324 net = Network(SG, target, syn, mon)
325 # change the schedule so that resets are processed before synapses
326 net.schedule = ["start", "groups", "thresholds", "resets", "synapses", "end"]
327 net.run(10000 * dt)
328 assert_equal(mon[0].count, np.ones(10000))
329
330
331 @pytest.mark.standalone_compatible
332 @pytest.mark.long
333 def test_spikegenerator_rounding_long():
334 # all spikes should fall in separate bins
335 dt = 0.1 * ms
336 N = 1000000
337 indices = np.zeros(N)
338 times = np.arange(N) * dt
339 SG = SpikeGeneratorGroup(1, indices, times, dt=dt)
340 target = NeuronGroup(1, "count : 1")
341 syn = Synapses(SG, target, on_pre="count+=1")
342 syn.connect()
343 spikes = SpikeMonitor(SG)
344 mon = StateMonitor(target, "count", record=0, when="end")
345 run(N * dt, report="text")
346 assert spikes.count[0] == N, f"expected {int(N)} spikes, got {int(spikes.count[0])}"
347 assert all(np.diff(mon[0].count[:]) == 1)
348
349
350 @pytest.mark.standalone_compatible
351 @pytest.mark.long
352 def test_spikegenerator_rounding_period():
353 # all spikes should fall in separate bins
354 dt = 0.1 * ms
355 N = 100
356 repeats = 10000
357 indices = np.zeros(N)
358 times = np.arange(N) * dt
359 SG = SpikeGeneratorGroup(1, indices, times, dt=dt, period=N * dt)
360 target = NeuronGroup(1, "count : 1")
361 syn = Synapses(SG, target, on_pre="count+=1")
362 syn.connect()
363 spikes = SpikeMonitor(SG)
364 mon = StateMonitor(target, "count", record=0, when="end")
365 run(N * repeats * dt, report="text")
366 # print np.int_(np.round(spikes.t/dt))
367 assert_equal(spikes.count[0], N * repeats)
368 assert all(np.diff(mon[0].count[:]) == 1)
369
370
371 @pytest.mark.codegen_independent
372 def test_spikegenerator_multiple_spikes_per_bin():
373 # Multiple spikes per bin are of course fine if they don't belong to the
374 # same neuron
375 SG = SpikeGeneratorGroup(2, [0, 1], [0, 0.05] * ms, dt=0.1 * ms)
376 net = Network(SG)
377 net.run(0 * ms)
378
379 # This should raise an error
380 SG = SpikeGeneratorGroup(2, [0, 0], [0, 0.05] * ms, dt=0.1 * ms)
381 net = Network(SG)
382 with pytest.raises(BrianObjectException) as exc:
383 net.run(0 * ms)
384 print(exc.value.__cause__)
385 assert exc_isinstance(exc, ValueError)
386
387 # More complicated scenario where dt changes between runs
388 defaultclock.dt = 0.1 * ms
389 SG = SpikeGeneratorGroup(2, [0, 0], [0.05, 0.15] * ms)
390 net = Network(SG)
391 net.run(0 * ms) # all is fine
392 defaultclock.dt = 0.2 * ms # Now the two spikes fall into the same bin
393 with pytest.raises(BrianObjectException) as exc:
394 net.run(0 * ms)
395 assert exc_isinstance(exc, ValueError)
396
397
398 @pytest.mark.standalone_compatible
399 @pytest.mark.multiple_runs
400 def test_spikegenerator_multiple_runs():
401 indices = np.zeros(5)
402 times = np.arange(5) * ms
403 spike_gen = SpikeGeneratorGroup(1, indices, times) # all good
404 spike_mon = SpikeMonitor(spike_gen)
405 run(5 * ms)
406 # Setting the same spike times again should not do anything, since they are
407 # before the start of the current simulation
408 spike_gen.set_spikes(indices, times)
409 # however, a warning should be raised
410 with catch_logs() as l:
411 run(5 * ms)
412 device.build(direct_call=False, **device.build_options)
413 assert len(l) == 1 and l[0][1].endswith("ignored_spikes")
414 assert spike_mon.num_spikes == 5
415
416
417 def test_spikegenerator_restore():
418 # Check whether SpikeGeneratorGroup works with store/restore
419 # See github issue #1084
420 gen = SpikeGeneratorGroup(1, [0, 0, 0], [0, 1, 2] * ms)
421 mon = SpikeMonitor(gen)
422 store()
423 run(3 * ms)
424 assert_array_equal(mon.i, [0, 0, 0])
425 assert_allclose(mon.t, [0, 1, 2] * ms)
426 restore()
427 run(3 * ms)
428 assert_array_equal(mon.i, [0, 0, 0])
429 assert_allclose(mon.t, [0, 1, 2] * ms)
430
431
432 if __name__ == "__main__":
433 import time
434
435 start = time.time()
436
437 test_spikegenerator_connected()
438 test_spikegenerator_basic()
439 test_spikegenerator_basic_sorted()
440 test_spikegenerator_basic_sorted_with_sorted()
441 test_spikegenerator_period()
442 test_spikegenerator_period_rounding()
443 test_spikegenerator_extreme_period()
444 test_spikegenerator_period_repeat()
445 test_spikegenerator_change_spikes()
446 test_spikegenerator_change_period()
447 test_spikegenerator_incorrect_values()
448 test_spikegenerator_incorrect_period()
449 test_spikegenerator_rounding()
450 test_spikegenerator_rounding_long()
451 test_spikegenerator_rounding_period()
452 test_spikegenerator_multiple_spikes_per_bin()
453 test_spikegenerator_multiple_runs()
454 test_spikegenerator_restore()
455 print("Tests took", time.time() - start)