Debian Codegraph @

brian2/tests/test_monitor.py

raw
1 import logging
2 import uuid
3
4 import pytest
5 from numpy.testing import assert_array_equal
6
7 from brian2 import *
8 from brian2.devices.cpp_standalone.device import CPPStandaloneDevice
9 from brian2.tests.utils import assert_allclose
10 from brian2.utils.logger import catch_logs
11
12
13 @pytest.mark.standalone_compatible
14 def test_spike_monitor():
15 G_without_threshold = NeuronGroup(5, "x : 1")
16 G = NeuronGroup(
17 3,
18 """
19 dv/dt = rate : 1
20 rate: Hz
21 """,
22 threshold="v>1",
23 reset="v=0",
24 )
25 # We don't use 100 and 1000Hz, because then the membrane potential would
26 # be exactly at 1 after 10 resp. 100 timesteps. Due to floating point
27 # issues this will not be exact,
28 G.rate = [101, 0, 1001] * Hz
29
30 mon = SpikeMonitor(G)
31
32 with pytest.raises(ValueError):
33 SpikeMonitor(G, order=1) # need to specify 'when' as well
34 with pytest.raises(ValueError) as ex:
35 SpikeMonitor(G_without_threshold)
36 assert "threshold" in str(ex)
37
38 # Creating a SpikeMonitor for a Synapses object should not work
39 S = Synapses(G, G, on_pre="v += 0")
40 S.connect()
41 with pytest.raises(TypeError):
42 SpikeMonitor(S)
43
44 run(10 * ms)
45
46 spike_trains = mon.spike_trains()
47
48 assert_allclose(mon.t[mon.i == 0], [9.9] * ms)
49 assert len(mon.t[mon.i == 1]) == 0
50 assert_allclose(mon.t[mon.i == 2], np.arange(10) * ms + 0.9 * ms)
51 assert_allclose(mon.t_[mon.i == 0], np.array([9.9 * float(ms)]))
52 assert len(mon.t_[mon.i == 1]) == 0
53 assert_allclose(mon.t_[mon.i == 2], (np.arange(10) + 0.9) * float(ms))
54 assert_allclose(spike_trains[0], [9.9] * ms)
55 assert len(spike_trains[1]) == 0
56 assert_allclose(spike_trains[2], np.arange(10) * ms + 0.9 * ms)
57 assert_array_equal(mon.count, np.array([1, 0, 10]))
58
59 i, t = mon.it
60 i_, t_ = mon.it_
61 assert_array_equal(i, mon.i)
62 assert_array_equal(i, i_)
63 assert_array_equal(t, mon.t)
64 assert_array_equal(t_, mon.t_)
65
66 with pytest.raises(KeyError):
67 spike_trains[3]
68 with pytest.raises(KeyError):
69 spike_trains[-1]
70 with pytest.raises(KeyError):
71 spike_trains["string"]
72
73 # Check that indexing into the VariableView works (this fails if we do not
74 # update the N variable correctly)
75 assert_allclose(mon.t[:5], [0.9, 1.9, 2.9, 3.9, 4.9] * ms)
76
77
78 def test_spike_monitor_indexing():
79 generator = SpikeGeneratorGroup(3, [0, 0, 0, 1], [0, 1, 2, 1] * ms)
80 mon = SpikeMonitor(generator)
81 run(3 * ms)
82
83 assert_array_equal(mon.t["i == 1"], [1] * ms)
84 assert_array_equal(mon.t[mon.i == 1], [1] * ms)
85 assert_array_equal(mon.i[mon.t > 1.5 * ms], [0] * ms)
86 assert_array_equal(mon.i["t > 1.5 * ms"], [0] * ms)
87
88
89 @pytest.mark.standalone_compatible
90 def test_spike_monitor_variables():
91 G = NeuronGroup(
92 3,
93 """
94 dv/dt = rate : 1
95 rate : Hz
96 prev_spikes : integer
97 """,
98 threshold="v>1",
99 reset="v=0; prev_spikes += 1",
100 )
101 # We don't use 100 and 1000Hz, because then the membrane potential would
102 # be exactly at 1 after 10 resp. 100 timesteps. Due to floating point
103 # issues this will not be exact,
104 G.rate = [101, 0, 1001] * Hz
105 mon1 = SpikeMonitor(G, variables="prev_spikes")
106 mon2 = SpikeMonitor(G, variables="prev_spikes", when="after_resets")
107 run(10 * ms)
108 all_values = mon1.all_values()
109 prev_spikes_values = mon1.values("prev_spikes")
110 assert_array_equal(mon1.prev_spikes[mon1.i == 0], [0])
111 assert_array_equal(prev_spikes_values[0], [0])
112 assert_array_equal(all_values["prev_spikes"][0], [0])
113 assert_array_equal(mon1.prev_spikes[mon1.i == 1], [])
114 assert_array_equal(prev_spikes_values[1], [])
115 assert_array_equal(all_values["prev_spikes"][1], [])
116 assert_array_equal(mon1.prev_spikes[mon1.i == 2], np.arange(10))
117 assert_array_equal(prev_spikes_values[2], np.arange(10))
118 assert_array_equal(all_values["prev_spikes"][2], np.arange(10))
119 assert_array_equal(mon2.prev_spikes[mon2.i == 0], [1])
120 assert_array_equal(mon2.prev_spikes[mon2.i == 1], [])
121 assert_array_equal(mon2.prev_spikes[mon2.i == 2], np.arange(10) + 1)
122
123
124 @pytest.mark.standalone_compatible
125 def test_spike_monitor_get_states():
126 G = NeuronGroup(
127 3,
128 """dv/dt = rate : 1
129 rate : Hz
130 prev_spikes : integer""",
131 threshold="v>1",
132 reset="v=0; prev_spikes += 1",
133 )
134 # We don't use 100 and 1000Hz, because then the membrane potential would
135 # be exactly at 1 after 10 resp. 100 timesteps. Due to floating point
136 # issues this will not be exact,
137 G.rate = [101, 0, 1001] * Hz
138 mon1 = SpikeMonitor(G, variables="prev_spikes")
139 run(10 * ms)
140 all_states = mon1.get_states()
141 assert set(all_states.keys()) == {"count", "i", "t", "prev_spikes", "N"}
142 assert_array_equal(all_states["count"], mon1.count[:])
143 assert_array_equal(all_states["i"], mon1.i[:])
144 assert_array_equal(all_states["t"], mon1.t[:])
145 assert_array_equal(all_states["prev_spikes"], mon1.prev_spikes[:])
146 assert_array_equal(all_states["N"], mon1.N)
147
148
149 @pytest.mark.standalone_compatible
150 def test_spike_monitor_subgroups():
151 G = NeuronGroup(6, """do_spike : boolean""", threshold="do_spike")
152 G.do_spike = [True, False, False, False, True, True]
153 spikes_all = SpikeMonitor(G)
154 spikes_1 = SpikeMonitor(G[:2])
155 spikes_2 = SpikeMonitor(G[2:4])
156 spikes_3 = SpikeMonitor(G[4:])
157 run(defaultclock.dt)
158 assert spikes_all.i.shape == (3,)
159 assert_allclose(spikes_all.i, [0, 4, 5])
160 assert_allclose(spikes_all.t, [0, 0, 0] * ms)
161 assert_allclose(spikes_1.i, [0])
162 assert_allclose(spikes_1.t, [0] * ms)
163 assert len(spikes_2.i) == 0
164 assert len(spikes_2.t) == 0
165 assert_allclose(spikes_3.i, [0, 1]) # recorded spike indices are relative
166 assert_allclose(spikes_3.t, [0, 0] * ms)
167
168
169 def test_spike_monitor_bug_824():
170 # See github issue #824
171 if prefs.codegen.target != "numpy":
172 pytest.skip("numpy-only test")
173
174 G = NeuronGroup(6, """do_spike : boolean""", threshold="do_spike")
175 G.do_spike = [True, False, False, True, False, False]
176 spikes_1 = SpikeMonitor(G[:3])
177 spikes_2 = SpikeMonitor(G[3:])
178 run(4 * defaultclock.dt)
179 assert_array_equal(spikes_1.count, [4, 0, 0])
180 assert_array_equal(spikes_2.count, [4, 0, 0])
181
182
183 @pytest.mark.standalone_compatible
184 def test_event_monitor():
185 G = NeuronGroup(
186 3,
187 """
188 dv/dt = rate : 1
189 rate: Hz
190 """,
191 events={"my_event": "v>1"},
192 )
193 G.run_on_event("my_event", "v=0")
194 # We don't use 100 and 1000Hz, because then the membrane potential would
195 # be exactly at 1 after 10 resp. 100 timesteps. Due to floating point
196 # issues this will not be exact,
197 G.rate = [101, 0, 1001] * Hz
198
199 mon = EventMonitor(G, "my_event")
200 net = Network(G, mon)
201 net.run(10 * ms)
202
203 event_trains = mon.event_trains()
204
205 assert_allclose(mon.t[mon.i == 0], [9.9] * ms)
206 assert len(mon.t[mon.i == 1]) == 0
207 assert_allclose(mon.t[mon.i == 2], np.arange(10) * ms + 0.9 * ms)
208 assert_allclose(mon.t_[mon.i == 0], np.array([9.9 * float(ms)]))
209 assert len(mon.t_[mon.i == 1]) == 0
210 assert_allclose(mon.t_[mon.i == 2], (np.arange(10) + 0.9) * float(ms))
211 assert_allclose(event_trains[0], [9.9] * ms)
212 assert len(event_trains[1]) == 0
213 assert_allclose(event_trains[2], np.arange(10) * ms + 0.9 * ms)
214 assert_array_equal(mon.count, np.array([1, 0, 10]))
215
216 i, t = mon.it
217 i_, t_ = mon.it_
218 assert_array_equal(i, mon.i)
219 assert_array_equal(i, i_)
220 assert_array_equal(t, mon.t)
221 assert_array_equal(t_, mon.t_)
222
223 with pytest.raises(KeyError):
224 event_trains[3]
225 with pytest.raises(KeyError):
226 event_trains[-1]
227 with pytest.raises(KeyError):
228 event_trains["string"]
229
230
231 @pytest.mark.standalone_compatible
232 def test_event_monitor_no_record():
233 # Check that you can switch off recording spike times/indices
234 G = NeuronGroup(
235 3,
236 """
237 dv/dt = rate : 1
238 rate: Hz
239 """,
240 events={"my_event": "v>1"},
241 threshold="v>1",
242 reset="v=0",
243 )
244 # We don't use 100 and 1000Hz, because then the membrane potential would
245 # be exactly at 1 after 10 resp. 100 timesteps. Due to floating point
246 # issues this will not be exact,
247 G.rate = [101, 0, 1001] * Hz
248
249 event_mon = EventMonitor(G, "my_event", record=False)
250 event_mon2 = EventMonitor(G, "my_event", variables="rate", record=False)
251 spike_mon = SpikeMonitor(G, record=False)
252 spike_mon2 = SpikeMonitor(G, variables="rate", record=False)
253 net = Network(G, event_mon, event_mon2, spike_mon, spike_mon2)
254 net.run(10 * ms)
255
256 # i and t should not be there
257 assert "i" not in event_mon.variables
258 assert "t" not in event_mon.variables
259 assert "i" not in spike_mon.variables
260 assert "t" not in spike_mon.variables
261
262 assert_array_equal(event_mon.count, np.array([1, 0, 10]))
263 assert_array_equal(spike_mon.count, np.array([1, 0, 10]))
264 assert spike_mon.num_spikes == sum(spike_mon.count)
265 assert event_mon.num_events == sum(event_mon.count)
266
267 # Other variables should still have been recorded
268 assert len(spike_mon2.rate) == spike_mon.num_spikes
269 assert len(event_mon2.rate) == event_mon.num_events
270
271
272 @pytest.mark.standalone_compatible
273 def test_spike_trains():
274 # An arbitrary combination of indices that has been shown to sort in an
275 # unstable way with quicksort and therefore lead to out-of-order values
276 # in the dictionary returned by spike_trains() of several neurons (see #725)
277 generator = SpikeGeneratorGroup(
278 10,
279 [6, 1, 2, 4, 6, 9, 1, 4, 7, 8, 0, 6, 3, 6, 4, 8, 9, 2, 5, 3],
280 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] * ms,
281 dt=1 * ms,
282 )
283 monitor = SpikeMonitor(generator)
284 run(19.1 * ms)
285 trains = monitor.spike_trains()
286 for idx, spike_times in trains.items():
287 assert all(np.diff(spike_times) > 0 * ms), (
288 f"Spike times for neuron {int(idx)} are not sorted"
289 )
290
291
292 def test_synapses_state_monitor():
293 G = NeuronGroup(2, "")
294 S = Synapses(G, G, "w: siemens")
295 S.connect(True)
296 S.w = "j*nS"
297
298 # record from a Synapses object (all synapses connecting to neuron 1)
299 synapse_mon = StateMonitor(S, "w", record=S[:, 1])
300 synapse_mon2 = StateMonitor(S, "w", record=S["j==1"])
301
302 net = Network(G, S, synapse_mon, synapse_mon2)
303 net.run(10 * ms)
304 # Synaptic variables
305 assert_allclose(synapse_mon[S[0, 1]].w, 1 * nS)
306 assert_allclose(synapse_mon.w[1], 1 * nS)
307 assert_allclose(synapse_mon2[S[0, 1]].w, 1 * nS)
308 assert_allclose(synapse_mon2[S["i==0 and j==1"]].w, 1 * nS)
309 assert_allclose(synapse_mon2.w[1], 1 * nS)
310
311
312 @pytest.mark.standalone_compatible
313 def test_state_monitor():
314 # Unique name to get the warning even for repeated runs of the test
315 unique_name = f"neurongroup_{str(uuid.uuid4()).replace('-', '_')}"
316 # Check that all kinds of variables can be recorded
317 G = NeuronGroup(
318 2,
319 """
320 dv/dt = -v / (10*ms) : 1
321 f = clip(v, 0.1, 0.9) : 1
322 rate: Hz
323 """,
324 threshold="v>1",
325 reset="v=0",
326 refractory=2 * ms,
327 name=unique_name,
328 )
329 G.rate = [100, 1000] * Hz
330 G.v = 1
331
332 S = Synapses(G, G, "w: siemens")
333 S.connect(True)
334 S.w = "j*nS"
335
336 # A bit peculiar, but in principle one should be allowed to record
337 # nothing except for the time
338 nothing_mon = StateMonitor(G, [], record=True)
339 no_record = StateMonitor(G, "v", record=False)
340
341 # Use a single StateMonitor
342 v_mon = StateMonitor(G, "v", record=True)
343 v_mon1 = StateMonitor(G, "v", record=[1])
344
345 # Use a StateMonitor for specified variables
346 multi_mon = StateMonitor(G, ["v", "f", "rate"], record=True)
347 multi_mon1 = StateMonitor(G, ["v", "f", "rate"], record=[1])
348
349 # Use a StateMonitor recording everything
350 all_mon = StateMonitor(G, True, record=True)
351
352 # Record synapses with explicit indices (the only way allowed in standalone)
353 synapse_mon = StateMonitor(S, "w", record=np.arange(len(G) ** 2))
354
355 run(10 * ms)
356
357 # Check time recordings
358 assert_array_equal(nothing_mon.t, v_mon.t)
359 assert_array_equal(nothing_mon.t_, np.asarray(nothing_mon.t))
360 assert_array_equal(nothing_mon.t_, v_mon.t_)
361 assert_allclose(nothing_mon.t, np.arange(len(nothing_mon.t)) * defaultclock.dt)
362 assert_array_equal(no_record.t, v_mon.t)
363
364 # Check v recording
365 assert_allclose(v_mon.v.T, np.exp(np.tile(-v_mon.t, (2, 1)).T / (10 * ms)))
366 assert_allclose(v_mon.v_.T, np.exp(np.tile(-v_mon.t_, (2, 1)).T / float(10 * ms)))
367 assert_array_equal(v_mon.v, multi_mon.v)
368 assert_array_equal(v_mon.v_, multi_mon.v_)
369 assert_array_equal(v_mon.v, all_mon.v)
370 assert_array_equal(v_mon.v[1:2], v_mon1.v)
371 assert_array_equal(multi_mon.v[1:2], multi_mon1.v)
372 assert len(no_record.v) == 0
373
374 # Other variables
375 assert_array_equal(
376 multi_mon.rate_.T, np.tile(np.atleast_2d(G.rate_), (multi_mon.rate.shape[1], 1))
377 )
378 assert_array_equal(multi_mon.rate[1:2], multi_mon1.rate)
379 assert_allclose(np.clip(multi_mon.v, 0.1, 0.9), multi_mon.f)
380 assert_allclose(np.clip(multi_mon1.v, 0.1, 0.9), multi_mon1.f)
381
382 assert all(all_mon[0].not_refractory[:] == True), (
383 "not_refractory should be True, but got(not_refractory, v):%s "
384 % str((all_mon.not_refractory, all_mon.v))
385 )
386
387 # Synapses
388 assert_allclose(
389 synapse_mon.w[:], np.tile(S.j[:] * nS, (synapse_mon.w[:].shape[1], 1)).T
390 )
391
392
393 @pytest.mark.standalone_compatible
394 def test_state_monitor_event_clock():
395 # Test recording at certain time points
396 G = NeuronGroup(10, "dv/dt = -v / (10*ms) : 1")
397 G.v = "rand()"
398 mon_continuous = StateMonitor(G, "v", record=True, dt=1 * ms)
399 mon_events = StateMonitor(
400 G, "v", record=True, clock=EventClock(times=np.arange(10) * ms)
401 )
402 run(10 * ms)
403 assert len(mon_continuous) == len(mon_events)
404 assert_allclose(mon_continuous.t[:], mon_events.t[:])
405 assert_allclose(mon_continuous.v[:], mon_events.v[:])
406
407
408 @pytest.mark.standalone_compatible
409 @pytest.mark.multiple_runs
410 def test_state_monitor_record_single_timestep():
411 G = NeuronGroup(1, "dv/dt = -v/(5*ms) : 1")
412 G.v = 1
413 mon = StateMonitor(G, "v", record=True)
414 # Recording before a run should not work
415 with pytest.raises(TypeError):
416 mon.record_single_timestep()
417 run(0.5 * ms)
418 mon.record_single_timestep()
419 device.build(direct_call=False, **device.build_options)
420 assert mon.t[0] == 0 * ms
421 assert mon[0].v[0] == 1
422 assert_allclose(mon.t[-1], 0.5 * ms)
423 assert len(mon.t) == 6
424 assert mon[0].v[-1] == G.v
425
426
427 @pytest.mark.standalone_compatible
428 def test_state_monitor_bigger_dt():
429 # Check that it is possible to record with a slower clock, i.e. bigger dt
430 G = NeuronGroup(1, "dv/dt = -v/(5*ms) : 1", method="exact")
431 G.v = 1
432 mon = StateMonitor(G, "v", record=True)
433 slow_mon = StateMonitor(G, "v", record=True, dt=defaultclock.dt * 5)
434 run(defaultclock.dt * 11)
435 assert len(mon.t) == len(mon.v[0]) == 11
436 assert len(slow_mon.t) == len(slow_mon.v[0]) == 3
437 for timepoint in [0, 5, 10]:
438 assert mon.t[timepoint] == slow_mon.t[timepoint // 5]
439 assert mon.v[0, timepoint] == slow_mon.v[0, timepoint // 5]
440
441
442 @pytest.mark.standalone_compatible
443 def test_state_monitor_indexing():
444 # Check indexing semantics
445 G = NeuronGroup(10, "v:volt")
446 G.v = np.arange(10) * volt
447 mon = StateMonitor(G, "v", record=[5, 6, 7])
448
449 run(2 * defaultclock.dt)
450
451 assert_array_equal(mon.v, np.array([[5, 5], [6, 6], [7, 7]]) * volt)
452 assert_array_equal(mon.v_, np.array([[5, 5], [6, 6], [7, 7]]))
453 assert_array_equal(mon[5].v, mon.v[0])
454 assert_array_equal(mon[7].v, mon.v[2])
455 assert_array_equal(mon[[5, 7]].v, mon.v[[0, 2]])
456 assert_array_equal(mon[np.array([5, 7])].v, mon.v[[0, 2]])
457
458 assert_allclose(mon.t[1:], Quantity([defaultclock.dt]))
459
460 with pytest.raises(IndexError):
461 mon[8]
462 with pytest.raises(TypeError):
463 mon["string"]
464 with pytest.raises(TypeError):
465 mon[5.0]
466 with pytest.raises(TypeError):
467 mon[[5.0, 6.0]]
468
469
470 @pytest.mark.standalone_compatible
471 def test_state_monitor_get_states():
472 G = NeuronGroup(
473 2,
474 """
475 dv/dt = -v / (10*ms) : 1
476 f = clip(v, 0.1, 0.9) : 1
477 rate: Hz
478 """,
479 threshold="v>1",
480 reset="v=0",
481 refractory=2 * ms,
482 )
483 G.rate = [100, 1000] * Hz
484 G.v = 1
485 mon = StateMonitor(G, ["v", "f", "rate"], record=True)
486 run(10 * defaultclock.dt)
487 all_states = mon.get_states()
488 assert set(all_states.keys()) == {"v", "f", "rate", "t", "N"}
489 assert_array_equal(all_states["v"].T, mon.v[:])
490 assert_array_equal(all_states["f"].T, mon.f[:])
491 assert_array_equal(all_states["rate"].T, mon.rate[:])
492 assert_array_equal(all_states["t"], mon.t[:])
493 assert_array_equal(all_states["N"], mon.N)
494
495
496 @pytest.mark.standalone_compatible
497 def test_state_monitor_resize():
498 # Test for issue #518 (cython did not resize the Variable object)
499 G = NeuronGroup(2, "v : 1")
500 mon = StateMonitor(G, "v", record=True)
501 defaultclock.dt = 0.1 * ms
502 run(1 * ms)
503 # On standalone, the size information of the variables is only updated
504 # after the variable has been accessed, so we can not only check the size
505 # information of the variables object
506 assert len(mon.t) == 10
507 assert mon.v.shape == (2, 10)
508 assert mon.variables["t"].size == 10
509 # Note that the internally stored variable has the transposed shape of the
510 # variable that is visible to the user
511 assert mon.variables["v"].size == (10, 2)
512
513
514 @pytest.mark.standalone_compatible
515 def test_state_monitor_synapses():
516 # Check that recording from synapses works correctly
517 G = NeuronGroup(5, "v : 1", threshold="False", reset="v = 0")
518 S1 = Synapses(G, G, "w : 1", on_pre="v_post += w")
519 S1.run_regularly("w += 1")
520 S1.connect(i=[0, 1], j=[2, 3])
521 S1.w = "i"
522 # We can check the record argument even in standalone mode, since we created
523 # the synapses with an array of indices of known length
524 with catch_logs() as l:
525 S1_mon = StateMonitor(S1, "w", record=[0, 1])
526 assert len(l) == 0
527
528 with pytest.raises(IndexError):
529 StateMonitor(S1, "w", record=[0, 2])
530
531 S2 = Synapses(G, G, "w : 1", on_pre="v_post += w")
532 S2.run_regularly("w += 1")
533 S2.connect("i==j") # Not yet executed for standalone mode
534 S2.w = "i"
535 with catch_logs() as l:
536 S2_mon = StateMonitor(S2, "w", record=[0, 4])
537
538 if isinstance(get_device(), CPPStandaloneDevice):
539 assert len(l) == 1
540 assert l[0][0] == "WARNING"
541 assert l[0][1].endswith(".cannot_check_statemonitor_indices")
542 else:
543 assert len(l) == 0
544 run(2 * defaultclock.dt)
545 assert_array_equal(S1_mon.w[:], [[0, 1], [1, 2]])
546 assert_array_equal(S2_mon.w[:], [[0, 1], [4, 5]])
547
548
549 @pytest.mark.codegen_independent
550 def test_statemonitor_namespace():
551 # Make sure that StateMonitor is correctly inheriting its source's namespace
552 G = NeuronGroup(2, "x = i + y : integer", namespace={"y": 3})
553 mon = StateMonitor(G, "x", record=True)
554 run(defaultclock.dt, namespace={})
555 assert_array_equal(mon.x, [[3], [4]])
556
557
558 @pytest.mark.standalone_compatible
559 def test_rate_monitor_1():
560 G = NeuronGroup(5, "v : 1", threshold="v>1") # no reset
561 G.v = 1.1 # All neurons spike every time step
562 rate_mon = PopulationRateMonitor(G)
563 run(10 * defaultclock.dt)
564
565 assert_allclose(rate_mon.t, np.arange(10) * defaultclock.dt)
566 assert_allclose(rate_mon.t_, np.arange(10) * defaultclock.dt_)
567 assert_allclose(rate_mon.t, np.arange(10) * defaultclock.dt)
568 assert_allclose(rate_mon.rate, np.ones(10) / defaultclock.dt)
569 assert_allclose(rate_mon.rate_, np.asarray(np.ones(10) / defaultclock.dt_))
570 # Check that indexing into the VariableView works (this fails if we do not
571 # update the N variable correctly)
572 assert_allclose(rate_mon.t[:5], np.arange(5) * defaultclock.dt)
573
574
575 @pytest.mark.standalone_compatible
576 def test_rate_monitor_2():
577 G = NeuronGroup(10, "v : 1", threshold="v>1") # no reset
578 G.v["i<5"] = 1.1 # Half of the neurons fire every time step
579 rate_mon = PopulationRateMonitor(G)
580 net = Network(G, rate_mon)
581 net.run(10 * defaultclock.dt)
582 assert_allclose(rate_mon.rate, 0.5 * np.ones(10) / defaultclock.dt)
583 assert_allclose(rate_mon.rate_, 0.5 * np.asarray(np.ones(10) / defaultclock.dt_))
584
585
586 @pytest.mark.codegen_independent
587 def test_rate_monitor_smoothed_rate():
588 # Test the filter response by having a single spiking neuron
589 G = SpikeGeneratorGroup(1, [0], [1] * ms)
590 r_mon = PopulationRateMonitor(G)
591 run(3 * ms)
592 index = int(np.round(1 * ms / defaultclock.dt))
593 except_index = np.array([idx for idx in range(len(r_mon.rate)) if idx != index])
594 assert_array_equal(r_mon.rate[except_index], 0 * Hz)
595 assert_allclose(r_mon.rate[index], 1 / defaultclock.dt)
596 ### Flat window
597 # Using a flat window of size = dt should not change anything
598 assert_allclose(r_mon.rate, r_mon.smooth_rate(window="flat", width=defaultclock.dt))
599 smoothed = r_mon.smooth_rate(window="flat", width=5 * defaultclock.dt)
600 assert_array_equal(smoothed[: index - 2], 0 * Hz)
601 assert_array_equal(smoothed[index + 3 :], 0 * Hz)
602 assert_allclose(smoothed[index - 2 : index + 3], 0.2 / defaultclock.dt)
603 with catch_logs(log_level=logging.INFO):
604 smoothed2 = r_mon.smooth_rate(window="flat", width=5.4 * defaultclock.dt)
605
606 # The window size should round up to 7.
607 # So, the spike at 'index' should be spread over 7 bins.
608 # The center is at 'index', with 3 bins on each side.
609 assert_array_equal(smoothed2[: index - 3], 0 * Hz)
610 assert_array_equal(smoothed2[index + 4 :], 0 * Hz)
611
612 # The value should be 1/dt spread over 7 bins.
613 expected_value = (1 / defaultclock.dt) / 7.0
614 assert_allclose(smoothed2[index - 3 : index + 4], expected_value)
615
616 ### Gaussian window
617 width = 5 * defaultclock.dt
618 smoothed = r_mon.smooth_rate(window="gaussian", width=width)
619 # 0 outside of window
620 assert_array_equal(smoothed[: index - 10], 0 * Hz)
621 assert_array_equal(smoothed[index + 11 :], 0 * Hz)
622 # Gaussian around the spike
623 gaussian = np.exp(
624 -((r_mon.t[index - 10 : index + 11] - 1 * ms) ** 2) / (2 * width**2)
625 )
626 gaussian /= sum(gaussian)
627 assert_allclose(smoothed[index - 10 : index + 11], 1 / defaultclock.dt * gaussian)
628
629 ### Arbitrary window
630 window = np.ones(5)
631 smoothed_flat = r_mon.smooth_rate(window="flat", width=5 * defaultclock.dt)
632 smoothed_custom = r_mon.smooth_rate(window=window)
633 assert_allclose(smoothed_flat, smoothed_custom)
634
635
636 @pytest.mark.codegen_independent
637 def test_rate_monitor_smoothed_rate_incorrect():
638 # Test the filter response by having a single spiking neuron
639 G = SpikeGeneratorGroup(1, [0], [1] * ms)
640 r_mon = PopulationRateMonitor(G)
641 run(2 * ms)
642
643 with pytest.raises(TypeError):
644 r_mon.smooth_rate(window="flat") # no width
645 with pytest.raises(TypeError):
646 r_mon.smooth_rate(window=np.ones(5), width=1 * ms)
647 with pytest.raises(NotImplementedError):
648 r_mon.smooth_rate(window="unknown", width=1 * ms)
649 with pytest.raises(TypeError):
650 r_mon.smooth_rate(window=object())
651 with pytest.raises(TypeError):
652 r_mon.smooth_rate(window=np.ones(5, 2))
653 with pytest.raises(TypeError):
654 r_mon.smooth_rate(window=np.ones(4)) # even number
655
656
657 @pytest.mark.standalone_compatible
658 def test_rate_monitor_get_states():
659 G = NeuronGroup(5, "v : 1", threshold="v>1") # no reset
660 G.v = 1.1 # All neurons spike every time step
661 rate_mon = PopulationRateMonitor(G)
662 run(10 * defaultclock.dt)
663 all_states = rate_mon.get_states()
664 assert set(all_states.keys()) == {"rate", "t", "N"}
665 assert_array_equal(all_states["rate"], rate_mon.rate[:])
666 assert_array_equal(all_states["t"], rate_mon.t[:])
667 assert_array_equal(all_states["N"], rate_mon.N)
668
669
670 @pytest.mark.standalone_compatible
671 def test_rate_monitor_subgroups():
672 old_dt = defaultclock.dt
673 defaultclock.dt = 0.01 * ms
674 G = NeuronGroup(
675 4,
676 """
677 dv/dt = rate : 1
678 rate : Hz
679 """,
680 threshold="v>0.999",
681 reset="v=0",
682 )
683 G.rate = [100, 200, 400, 800] * Hz
684 rate_all = PopulationRateMonitor(G)
685 rate_1 = PopulationRateMonitor(G[:2])
686 rate_2 = PopulationRateMonitor(G[2:])
687 run(1 * second)
688 assert_allclose(mean(G.rate_[:]), mean(rate_all.rate_[:]))
689 assert_allclose(mean(G.rate_[:2]), mean(rate_1.rate_[:]))
690 assert_allclose(mean(G.rate_[2:]), mean(rate_2.rate_[:]))
691
692 defaultclock.dt = old_dt
693
694
695 @pytest.mark.standalone_compatible
696 def test_rate_monitor_subgroups_2():
697 G = NeuronGroup(6, """do_spike : boolean""", threshold="do_spike")
698 G.do_spike = [True, False, False, False, True, True]
699 rate_all = PopulationRateMonitor(G)
700 rate_1 = PopulationRateMonitor(G[:2])
701 rate_2 = PopulationRateMonitor(G[2:4])
702 rate_3 = PopulationRateMonitor(G[4:])
703 run(2 * defaultclock.dt)
704 assert_allclose(rate_all.rate, 0.5 / defaultclock.dt)
705 assert_allclose(rate_1.rate, 0.5 / defaultclock.dt)
706 assert_allclose(rate_2.rate, 0 * Hz)
707 assert_allclose(rate_3.rate, 1 / defaultclock.dt)
708
709
710 # ====== Tests to test the added rate monitoring functionality in monitors =====
711
712
713 @pytest.mark.codegen_independent
714 def test_population_rate_monitor_binning():
715 """Test binning functionality for PopulationRateMonitor."""
716 # Create a group with deterministic regular spiking
717 # 10 neurons, each spiking every 10ms, but staggered by 1ms
718 N = 10
719 spike_times = []
720 spike_indices = []
721
722 # Generate regular spike pattern: neuron i spikes at i*1ms, (i+10)*1ms, (i+20)*1ms, etc.
723 for neuron_idx in range(N):
724 for spike_time in range(
725 neuron_idx, 100, 10
726 ): # Every 10ms, offset by neuron_idx
727 spike_indices.append(neuron_idx)
728 spike_times.append(spike_time)
729
730 spike_indices = np.array(spike_indices)
731 spike_times = np.array(spike_times) * ms
732
733 G = SpikeGeneratorGroup(N, spike_indices, spike_times)
734 mon = PopulationRateMonitor(G)
735 run(100 * ms)
736
737 # Test 1: bin_size = 10ms
738 # Each 10ms bin should have exactly 10 spikes (one per neuron)
739 # Rate = 10 spikes / 10 neurons / 0.01s = 100 Hz
740 bins, binned_rates = mon.binned_rate(10 * ms)
741 expected_bins = np.arange(10) * 10 * ms # Starts at 0, 10, 20, ..., 90 ms
742 assert_allclose(bins, expected_bins)
743 assert len(binned_rates) == 10
744 # Each bin has 10 spikes over 10 neurons over 10ms = 100 Hz average
745 expected_rate = 10 / (10 * 0.01) * Hz # 10 spikes / (10 neurons * 0.01s)
746 assert_allclose(binned_rates, expected_rate, rtol=1e-6)
747
748 # Test 2: bin_size = 20ms
749 # Each 20ms bin should have exactly 20 spikes
750 bins, binned_rates = mon.binned_rate(20 * ms)
751 expected_bins = np.arange(5) * 20 * ms # Starts at 0, 20, 40, 60, 80 ms
752 assert_allclose(bins, expected_bins)
753 assert len(binned_rates) == 5
754 expected_rate = 20 / (10 * 0.02) * Hz # 20 spikes / (10 neurons * 0.02s)
755 assert_allclose(binned_rates, expected_rate, rtol=1e-6)
756
757 # Test 3: bin_size = 1ms
758 # Each 1ms bin has 1 spike from one neuron
759 # Bins starts at 0, 1, 2, 3, ..., 99 ms
760 bins, binned_rates = mon.binned_rate(1 * ms)
761 expected_bins = np.arange(100) * 1 * ms
762 assert_allclose(bins, expected_bins)
763 assert len(binned_rates) == 100
764 # Average rate should be 100 Hz (10 neurons × 10 spikes each / 100ms)
765 assert_allclose(np.mean(binned_rates), 100 * Hz, rtol=0.01)
766
767 # Test 4: bin_size = dt (should return original data)
768 dt = defaultclock.dt
769 bins, binned_rates = mon.binned_rate(dt)
770 assert_allclose(bins, mon.t[:])
771 assert_allclose(binned_rates, mon.rate[:])
772
773 # Test 5: bin_size must be multiple of dt
774 with pytest.raises(ValueError):
775 mon.binned_rate(1.5 * dt)
776
777
778 @pytest.mark.codegen_independent
779 def test_population_rate_monitor_binning_incomplete_bins():
780 """Test that incomplete bins at the end are handled correctly."""
781 # Create spikes such that the last bin is incomplete
782 N = 5
783 spike_indices = [0, 1, 2, 3, 4] * 7 # 35 spikes total
784 spike_times = list(range(35)) # At 0ms, 1ms, 2ms, ..., 34ms
785
786 G = SpikeGeneratorGroup(N, spike_indices, spike_times * ms)
787 mon = PopulationRateMonitor(G)
788 run(35 * ms)
789
790 # With bin_size = 10ms, we should have 3 complete bins (0-10, 10-20, 20-30)
791 # The last 5ms (30-35) should be excluded
792 bins, binned_rates = mon.binned_rate(10 * ms)
793
794 assert len(bins) == 3
795 assert len(binned_rates) == 3
796 expected_bins = [0, 10, 20] * ms
797 assert_allclose(bins, expected_bins)
798
799 # Each bin has 10 spikes / 5 neurons / 0.01s = 200 Hz
800 expected_rate = 10 / (5 * 0.01) * Hz
801 assert_allclose(binned_rates, expected_rate, rtol=1e-6)
802
803
804 @pytest.mark.codegen_independent
805 def test_population_rate_monitor_binning_midrun():
806 """Test binning when monitor is added mid-simulation."""
807 N = 5
808 spike_indices = [0, 1, 2, 3, 4] * 10 # 50 spikes
809 spike_times = list(range(50)) # At 0-49ms
810
811 G = SpikeGeneratorGroup(N, spike_indices, spike_times * ms)
812
813 # Run first 20ms without monitor
814 run(20 * ms)
815
816 # Add monitor and run another 30ms
817 mon = PopulationRateMonitor(G)
818 run(30 * ms)
819
820 # Monitor only recorded from 20-50ms (30ms total)
821 # With bin_size = 10ms, should have 3 bins
822 bins, binned_rates = mon.binned_rate(10 * ms)
823
824 assert len(bins) == 3
825 # Bins should start at 20, 30, 40 ms (where recording began)
826 expected_bins = [20, 30, 40] * ms
827 assert_allclose(bins, expected_bins)
828
829 # Each bin still has 10 spikes / 5 neurons / 0.01s = 200 Hz
830 expected_rate = 10 / (5 * 0.01) * Hz
831 assert_allclose(binned_rates, expected_rate, rtol=1e-6)
832
833
834 @pytest.mark.codegen_independent
835 def test_spike_monitor_binning():
836 """Test binning functionality for SpikeMonitor."""
837 # Create neurons with known spike times
838 indices = [0, 0, 1, 1, 2]
839 times = [10, 30, 20, 40, 50] * ms
840
841 G = SpikeGeneratorGroup(3, indices, times)
842 mon = SpikeMonitor(G)
843
844 run(100 * ms)
845
846 # Test binning with 20ms bins
847 bins, binned_rates = mon.binned_rate(20 * ms)
848
849 # Expected: 5 bins of 20ms each
850 assert len(bins) == 5
851 assert bins[0] == 0 * ms # First bin start
852
853 # Check spike counts/rates for each neuron
854 # Bins: [0-20ms), [20-40ms), [40-60ms), [60-80ms), [80-100ms) with starts at 0, 20, 40, 60, 80
855 # Neuron 0: spikes at 10ms (bin 0: [0-20ms)) and 30ms (bin 1: [20-40ms))
856 assert binned_rates[0, 0] == 50 * Hz # 1 spike / 20ms
857 assert binned_rates[0, 1] == 50 * Hz
858 assert np.sum(binned_rates[0, 2:]) == 0
859
860 # Neuron 1: spikes at 20ms (bin 1) and 40ms (bin 2)
861 assert binned_rates[1, 1] == 50 * Hz
862 assert binned_rates[1, 2] == 50 * Hz
863
864 # Neuron 2: spike at 50ms (bin 2)
865 assert binned_rates[2, 2] == 50 * Hz
866 assert np.sum(binned_rates[2, [0, 1, 3, 4]]) == 0
867
868
869 @pytest.mark.codegen_independent
870 def test_smooth_rates_spike_monitor():
871 """Test smoothing functionality for SpikeMonitor."""
872 # Create a neuron with a burst of spikes
873 times = np.arange(40, 61) * ms # Burst from 40-60ms
874 indices = np.zeros(21, dtype=int)
875
876 G = SpikeGeneratorGroup(10, indices, times)
877 mon = SpikeMonitor(G)
878
879 run(100 * ms)
880
881 # Test Gaussian smoothing
882 width = 5 * ms
883 smoothed = mon.smooth_rate(window="gaussian", width=width)
884
885 # Should be smooth and peak around the burst
886 assert smoothed.ndim == 2 # (neurons, time)
887 assert smoothed.shape[0] == 10 # ten neuron
888
889 # Peak should be around 50ms (middle of burst)
890 peak_time = np.argmax(smoothed[0]) * defaultclock.dt
891 assert 45 * ms < peak_time < 55 * ms
892
893 # Test flat window smoothing
894 smoothed_flat = mon.smooth_rate(window="flat", width=10 * ms)
895 assert smoothed_flat.shape == smoothed.shape
896
897 # Test custom window
898 custom_window = np.array([0.25, 0.5, 0.25])
899 smoothed_custom = mon.smooth_rate(window=custom_window)
900 assert smoothed_custom.shape == smoothed.shape
901
902
903 @pytest.mark.codegen_independent
904 def test_smooth_rates_population_monitor():
905 """Test that smooth_rates works correctly for PopulationRateMonitor."""
906 N = 100
907
908 rate_val = 50 * Hz
909 G = NeuronGroup(N, "rate : Hz", threshold="rand() < rate*dt")
910 G.rate = rate_val
911 mon = PopulationRateMonitor(G)
912 run(200 * ms)
913
914 # Test different smoothing windows
915 smoothed_gauss = mon.smooth_rate("gaussian", width=10 * ms)
916 smoothed_flat = mon.smooth_rate("flat", width=10 * ms)
917
918 # Smoothed rates should have same length as original
919 assert len(smoothed_gauss) == len(mon.rate)
920 assert len(smoothed_flat) == len(mon.rate)
921
922 # Smoothed version should have less variance
923 assert np.var(smoothed_gauss) < np.var(mon.rate)
924 assert np.var(smoothed_flat) < np.var(mon.rate)
925
926
927 @pytest.mark.codegen_independent
928 def test_subgroup_spike_monitor():
929 """Test that binning works correctly with subgroups."""
930 N = 10
931 G = NeuronGroup(N, "v:1", threshold="i<5 and rand()<0.1")
932
933 # Monitor only neurons 2-7
934 subgroup = G[2:8]
935 mon = SpikeMonitor(subgroup)
936
937 run(100 * ms)
938
939 _, rates = mon.binned_rate(10 * ms)
940
941 # Should have 6 neurons (indices 2-7)
942 assert rates.shape[0] == 6
943
944 # Only neurons 0,1,2 of subgroup (i.e., 2,3,4 of full group) can spike
945 if mon.num_spikes > 0:
946 assert np.all(mon.i[:] < 5) # In original indices
947 # In binned output, only first 3 rows can be non-zero
948 assert np.sum(rates[3:, :]) == 0
949
950
951 @pytest.mark.codegen_independent
952 def test_rate_monitor_errors():
953 """Test error conditions."""
954 G = NeuronGroup(
955 10, "v : 1", threshold="v > 1000"
956 ) # Very high threshold , as we don;t need actual spikes
957 mon = SpikeMonitor(G)
958
959 run(10 * ms)
960
961 # Test that width is required for predefined windows
962 with pytest.raises(TypeError):
963 mon.smooth_rate("gaussian")
964
965 # Test that width cannot be specified for custom windows
966 with pytest.raises(TypeError):
967 mon.smooth_rate(np.array([1, 2, 1]), width=5 * ms)
968
969 # Test unknown window type
970 with pytest.raises(NotImplementedError):
971 mon.smooth_rate("unknown", width=5 * ms)
972
973 # Test that custom window must be 1D
974 with pytest.raises(TypeError):
975 mon.smooth_rate(np.array([[1, 2], [3, 4]]))
976
977 # Test that custom window must have odd length
978 with pytest.raises(TypeError):
979 mon.smooth_rate(np.array([1, 2, 3, 4]))
980
981
982 @pytest.mark.codegen_independent
983 def test_monitor_str_repr():
984 # Basic test that string representations are not empty
985 G = NeuronGroup(2, "dv/dt = -v/(10*ms) : 1", threshold="v>1", reset="v=0")
986 spike_mon = SpikeMonitor(G)
987 state_mon = StateMonitor(G, "v", record=True)
988 rate_mon = PopulationRateMonitor(G)
989 for obj in [spike_mon, state_mon, rate_mon]:
990 assert len(str(obj))
991 assert len(repr(obj))
992
993
994 if __name__ == "__main__":
995 from _pytest.outcomes import Skipped
996
997 test_spike_monitor()
998 test_spike_monitor_indexing()
999 test_spike_monitor_get_states()
1000 test_spike_monitor_subgroups()
1001 try:
1002 test_spike_monitor_bug_824()
1003 except Skipped:
1004 pass
1005 test_spike_monitor_variables()
1006 test_event_monitor()
1007 test_event_monitor_no_record()
1008 test_spike_trains()
1009 test_synapses_state_monitor()
1010 test_state_monitor()
1011 test_state_monitor_record_single_timestep()
1012 test_state_monitor_get_states()
1013 test_state_monitor_indexing()
1014 test_state_monitor_resize()
1015 test_rate_monitor_1()
1016 test_rate_monitor_2()
1017 test_rate_monitor_smoothed_rate()
1018 test_rate_monitor_smoothed_rate_incorrect()
1019 test_rate_monitor_get_states()
1020 test_rate_monitor_subgroups()
1021 test_rate_monitor_subgroups_2()
1022 test_monitor_str_repr()
1023 # Rate monitor tests
1024 test_population_rate_monitor_binning()
1025 test_spike_monitor_binning()
1026 test_smooth_rates_spike_monitor()
1027 test_smooth_rates_population_monitor()
1028 test_subgroup_spike_monitor()
1029 test_rate_monitor_errors()