Debian Codegraph @

brian2/monitors/spikemonitor.py

raw
1 """
2 Module defining `EventMonitor` and `SpikeMonitor`.
3 """
4
5 import numpy as np
6
7 from brian2.core.functions import timestep
8 from brian2.core.names import Nameable
9 from brian2.core.spikesource import SpikeSource
10 from brian2.core.variables import Variables
11 from brian2.groups.group import CodeRunner
12 from brian2.monitors.ratemonitor import RateMonitor
13 from brian2.units.allunits import hertz, second
14 from brian2.units.fundamentalunits import Quantity, check_units
15
16 __all__ = ["EventMonitor", "SpikeMonitor"]
17
18
19 class EventMonitor(RateMonitor):
20 """
21 Record events from a `NeuronGroup` or another event source.
22
23 The recorded events can be accessed in various ways:
24 the attributes `~EventMonitor.i` and `~EventMonitor.t` store all the indices
25 and event times, respectively. Alternatively, you can get a dictionary
26 mapping neuron indices to event trains, by calling the `event_trains`
27 method.
28
29 Parameters
30 ----------
31 source : `NeuronGroup`, `SpikeSource`
32 The source of events to record.
33 event : str
34 The name of the event to record
35 variables : str or sequence of str, optional
36 Which variables to record at the time of the event (in addition to the
37 index of the neuron). Can be the name of a variable or a list of names.
38 record : bool, optional
39 Whether or not to record each event in `i` and `t` (the `count` will
40 always be recorded). Defaults to ``True``.
41 when : str, optional
42 When to record the events, by default records events in the same slot
43 where the event is emitted. See :ref:`scheduling` for possible values.
44 order : int, optional
45 The priority of of this group for operations occurring at the same time
46 step and in the same scheduling slot. Defaults to the order where the
47 event is emitted + 1, i.e. it will be recorded directly afterwards.
48 name : str, optional
49 A unique name for the object, otherwise will use
50 ``source.name+'_eventmonitor_0'``, etc.
51 codeobj_class : class, optional
52 The `CodeObject` class to run code with.
53
54 See Also
55 --------
56 SpikeMonitor
57 """
58
59 invalidates_magic_network = False
60 add_to_magic_network = True
61
62 def __init__(
63 self,
64 source,
65 event,
66 variables=None,
67 record=True,
68 when=None,
69 order=None,
70 name="eventmonitor*",
71 codeobj_class=None,
72 ):
73 if not isinstance(source, SpikeSource):
74 raise TypeError(
75 f"{self.__class__.__name__} can only monitor groups "
76 "producing spikes (such as NeuronGroup), but the given "
77 f"argument is of type {type(source)}."
78 )
79 #: The source we are recording from
80 self.source = source
81 #: Whether to record times and indices of events
82 self.record = record
83 #: The array of event counts (length = size of target group)
84 self.count = None
85 del self.count # this is handled by the Variable mechanism
86
87 if event not in source.events:
88 if event == "spike":
89 threshold_text = " Did you forget to set a 'threshold'?"
90 else:
91 threshold_text = ""
92 raise ValueError(
93 f"Recorded group '{source.name}' does not define an event "
94 f"'{event}'.{threshold_text}"
95 )
96 if when is None:
97 if order is not None:
98 raise ValueError("Cannot specify order if when is not specified.")
99 # TODO: Would be nicer if there was a common way of accessing the
100 # relevant object for NeuronGroup and SpikeGeneratorGroup
101 if hasattr(source, "thresholder"):
102 parent_obj = source.thresholder[event]
103 else:
104 parent_obj = source
105 when = parent_obj.when
106 order = parent_obj.order + 1
107 elif order is None:
108 order = 0
109
110 #: The event that we are listening to
111 self.event = event
112
113 if variables is None:
114 variables = {}
115 elif isinstance(variables, str):
116 variables = {variables}
117
118 #: The additional variables that will be recorded
119 self.record_variables = set(variables)
120
121 for variable in variables:
122 if variable not in source.variables:
123 raise ValueError(
124 f"'{variable}' is not a variable of the recorded group"
125 )
126
127 if self.record:
128 self.record_variables |= {"i", "t"}
129
130 # Some dummy code so that code generation takes care of the indexing
131 # and subexpressions
132 code = [f"_to_record_{v} = _source_{v}" for v in sorted(self.record_variables)]
133 code = "\n".join(code)
134
135 self.codeobj_class = codeobj_class
136
137 # Since this now works for general events not only spikes, we have to
138 # pass the information about which variable to use to the template,
139 # it can not longer simply refer to "_spikespace"
140 eventspace_name = f"_{event}space"
141
142 # Handle subgroups correctly
143 start = getattr(source, "start", 0)
144 stop = getattr(source, "stop", len(source))
145 source_N = getattr(source, "_source_N", len(source))
146
147 Nameable.__init__(self, name=name)
148
149 self.variables = Variables(self)
150 self.variables.add_reference(eventspace_name, source)
151
152 for variable in self.record_variables:
153 source_var = source.variables[variable]
154 self.variables.add_reference(f"_source_{variable}", source, variable)
155 self.variables.add_auxiliary_variable(
156 f"_to_record_{variable}",
157 dimensions=source_var.dim,
158 dtype=source_var.dtype,
159 )
160 self.variables.add_dynamic_array(
161 variable,
162 size=0,
163 dimensions=source_var.dim,
164 dtype=source_var.dtype,
165 read_only=True,
166 )
167 self.variables.add_arange("_source_idx", size=len(source))
168 self.variables.add_array(
169 "count",
170 size=len(source),
171 dtype=np.int32,
172 read_only=True,
173 index="_source_idx",
174 )
175 self.variables.add_constant("_source_start", start)
176 self.variables.add_constant("_source_stop", stop)
177 self.variables.add_constant("_source_N", source_N)
178 self.variables.add_array(
179 "N", size=1, dtype=np.int32, read_only=True, scalar=True
180 )
181
182 record_variables = {
183 varname: self.variables[varname] for varname in self.record_variables
184 }
185 template_kwds = {
186 "eventspace_variable": source.variables[eventspace_name],
187 "record_variables": record_variables,
188 "record": self.record,
189 }
190 needed_variables = {eventspace_name} | self.record_variables
191 CodeRunner.__init__(
192 self,
193 group=self,
194 code=code,
195 template="spikemonitor",
196 name=None, # The name has already been initialized
197 clock=source.clock,
198 when=when,
199 order=order,
200 needed_variables=needed_variables,
201 template_kwds=template_kwds,
202 )
203
204 self.variables.create_clock_variables(self._clock, prefix="_clock_")
205 self.add_dependency(source)
206 self.written_readonly_vars = {
207 self.variables[varname] for varname in self.record_variables
208 }
209 self._enable_group_attributes()
210
211 def resize(self, new_size):
212 # Note that this does not set N, this has to be done in the template
213 # since we use a restricted pointer to access it (which promises that
214 # we only change the value through this pointer)
215 for variable in self.record_variables:
216 self.variables[variable].resize(new_size)
217
218 def reinit(self):
219 """
220 Clears all recorded spikes
221 """
222 raise NotImplementedError()
223
224 @property
225 def it(self):
226 """
227 Returns the pair (`i`, `t`).
228 """
229 if not self.record:
230 raise AttributeError(
231 "Indices and times have not been recorded."
232 "Set the record argument to True to record "
233 "them."
234 )
235 return self.i, self.t
236
237 @property
238 def it_(self):
239 """
240 Returns the pair (`i`, `t_`).
241 """
242 if not self.record:
243 raise AttributeError(
244 "Indices and times have not been recorded."
245 "Set the record argument to True to record "
246 "them."
247 )
248
249 return self.i, self.t_
250
251 def _values_dict(self, first_pos, sort_indices, used_indices, var):
252 sorted_values = self.state(var, use_units=False)[sort_indices]
253 dim = self.variables[var].dim
254 event_values = {}
255 current_pos = 0 # position in the all_indices array
256 for idx in range(len(self.source)):
257 if current_pos < len(used_indices) and used_indices[current_pos] == idx:
258 if current_pos < len(used_indices) - 1:
259 event_values[idx] = Quantity(
260 sorted_values[
261 first_pos[current_pos] : first_pos[current_pos + 1]
262 ],
263 dim=dim,
264 )
265 else:
266 event_values[idx] = Quantity(
267 sorted_values[first_pos[current_pos] :], dim=dim
268 )
269 current_pos += 1
270 else:
271 event_values[idx] = Quantity([], dim=dim)
272 return event_values
273
274 def values(self, var):
275 """
276 Return a dictionary mapping neuron indices to arrays of variable values
277 at the time of the events (sorted by time).
278
279 Parameters
280 ----------
281 var : str
282 The name of the variable.
283
284 Returns
285 -------
286 values : dict
287 Dictionary mapping each neuron index to an array of variable
288 values at the time of the events
289
290 Examples
291 --------
292 >>> from brian2 import *
293 >>> G = NeuronGroup(2, '''counter1 : integer
294 ... counter2 : integer
295 ... max_value : integer''',
296 ... threshold='counter1 >= max_value',
297 ... reset='counter1 = 0')
298 >>> G.run_regularly('counter1 += 1; counter2 += 1') # doctest: +ELLIPSIS
299 CodeRunner(...)
300 >>> G.max_value = [50, 100]
301 >>> mon = EventMonitor(G, event='spike', variables='counter2')
302 >>> run(10*ms)
303 >>> counter2_values = mon.values('counter2')
304 >>> print(counter2_values[0])
305 [ 50 100]
306 >>> print(counter2_values[1])
307 [100]
308 """
309 if not self.record:
310 raise AttributeError(
311 "Indices and times have not been recorded."
312 "Set the record argument to True to record "
313 "them."
314 )
315 indices = self.i[:]
316 # We have to make sure that the sort is stable, otherwise our spike
317 # times do not necessarily remain sorted.
318 sort_indices = np.argsort(indices, kind="mergesort")
319 used_indices, first_pos = np.unique(self.i[:][sort_indices], return_index=True)
320 return self._values_dict(first_pos, sort_indices, used_indices, var)
321
322 def all_values(self):
323 """
324 Return a dictionary mapping recorded variable names (including ``t``)
325 to a dictionary mapping neuron indices to arrays of variable values at
326 the time of the events (sorted by time). This is equivalent to (but more
327 efficient than) calling `values` for each variable and storing the
328 result in a dictionary.
329
330 Returns
331 -------
332 all_values : dict
333 Dictionary mapping variable names to dictionaries which themselves
334 are mapping neuron indicies to arrays of variable values at the
335 time of the events.
336
337 Examples
338 --------
339 >>> from brian2 import *
340 >>> G = NeuronGroup(2, '''counter1 : integer
341 ... counter2 : integer
342 ... max_value : integer''',
343 ... threshold='counter1 >= max_value',
344 ... reset='counter1 = 0')
345 >>> G.run_regularly('counter1 += 1; counter2 += 1') # doctest: +ELLIPSIS
346 CodeRunner(...)
347 >>> G.max_value = [50, 100]
348 >>> mon = EventMonitor(G, event='spike', variables='counter2')
349 >>> run(10*ms)
350 >>> all_values = mon.all_values()
351 >>> print(all_values['counter2'][0])
352 [ 50 100]
353 >>> print(all_values['t'][1])
354 [ 9.9] ms
355 """
356 if not self.record:
357 raise AttributeError(
358 "Indices and times have not been recorded."
359 "Set the record argument to True to record "
360 "them."
361 )
362 indices = self.i[:]
363 sort_indices = np.argsort(indices, kind="mergesort")
364 used_indices, first_pos = np.unique(self.i[:][sort_indices], return_index=True)
365 all_values_dict = {}
366 for varname in self.record_variables - {"i"}:
367 all_values_dict[varname] = self._values_dict(
368 first_pos, sort_indices, used_indices, varname
369 )
370 return all_values_dict
371
372 def event_trains(self):
373 """
374 Return a dictionary mapping neuron indices to arrays of event times.
375 Equivalent to calling ``values('t')``.
376
377 Returns
378 -------
379 event_trains : dict
380 Dictionary that stores an array with the event times for each
381 neuron index.
382
383 See Also
384 --------
385 SpikeMonitor.spike_trains
386 """
387 return self.values("t")
388
389 @check_units(bin_size=second)
390 def binned_rate(self, bin_size):
391 """
392 Return the event rates binned with the given bin size.
393
394 Parameters
395 ----------
396 bin_size : `Quantity`
397 The size of the bins in seconds. Should be a multiple of dt.
398
399 Returns
400 -------
401 bins : `Quantity`
402 The start time of the bins.
403 binned_values : `Quantity`
404 The binned rates as a 2D array (neurons × bins) in Hz.
405
406 Notes
407 -----
408 The returned bin times represent the **start** of each bin interval, not the center.
409 This is consistent with how Brian2 records spike times and other temporal data.
410 For example, a spike recorded at time `t` occurred during the interval `[t, t+dt)`.
411
412 For plotting purposes, especially with larger bin sizes, you may want to use bin
413 centers instead of bin starts for a more intuitive visualization. You can easily
414 calculate the bin centers by adding half the bin size::
415
416 >> bins, rates = monitor.binned_rate(10*ms)
417 >> bin_centers = bins + 10*ms / 2
418 >> plt.plot(bin_centers, rates)
419
420 This adjustment is particularly helpful when the bins are large relative to the
421 time scale of interest, as it better represents where the rate measurement applies
422 within each time window.
423 """
424 if (bin_size / self.clock.dt) % 1 > 1e-6:
425 raise ValueError("bin_size has to be a multiple of dt.")
426
427 # Get the total duration and number of bins
428 bin_timesteps = timestep(bin_size, self.clock.dt)
429 num_bins = int(self.clock.timestep // bin_timesteps)
430 bin_starts_timesteps = (np.arange(num_bins)) * bin_timesteps
431 bins = bin_starts_timesteps * self.clock.dt
432
433 num_neurons = len(self.source)
434
435 # Now we initialize the binned values array (neurons × bins)
436 binned_values = np.zeros((num_neurons, num_bins))
437 if self.record and len(self.t) > 0:
438 # Get the event times and indices
439 event_times = self.t[:]
440
441 event_timesteps = np.asarray(timestep(event_times, self.clock.dt))
442 bin_indices = event_timesteps // bin_timesteps
443
444 np.add.at(binned_values, (self.i[:], bin_indices), 1)
445
446 # Convert counts to rates (Hz)
447 binned_values = binned_values / float(bin_size)
448 return bins, Quantity(binned_values, dim=hertz.dim)
449
450 @property
451 def num_events(self):
452 """
453 Returns the total number of recorded events.
454 """
455 return self.N[:]
456
457 def __repr__(self):
458 classname = self.__class__.__name__
459 return f"<{classname}, recording event '{self.event}' from '{self.group.name}'>"
460
461 def after_run(self):
462 super().after_run()
463 # In Cython runtime mode, we directly update the underlying dynamic array,
464 # so the size attribute of the Variable does not get updated automatically
465 for var in self.record_variables:
466 try:
467 self.variables[var].size = len(self.variables[var].get_value())
468 except NotImplementedError:
469 pass # Does not apply to standalone mode
470
471
472 class SpikeMonitor(EventMonitor):
473 """
474 Record spikes from a `NeuronGroup` or other spike source.
475
476 The recorded spikes can be accessed in various ways (see Examples below):
477 the attributes `~SpikeMonitor.i` and `~SpikeMonitor.t` store all the indices
478 and spike times, respectively. Alternatively, you can get a dictionary
479 mapping neuron indices to spike trains, by calling the `spike_trains`
480 method. If you record additional variables with the ``variables`` argument,
481 these variables can be accessed by their name (see Examples).
482
483 Parameters
484 ----------
485 source : (`NeuronGroup`, `SpikeSource`)
486 The source of spikes to record.
487 variables : str or sequence of str, optional
488 Which variables to record at the time of the spike (in addition to the
489 index of the neuron). Can be the name of a variable or a list of names.
490 record : bool, optional
491 Whether or not to record each spike in `i` and `t` (the `count` will
492 always be recorded). Defaults to ``True``.
493 when : str, optional
494 When to record the events, by default records events in the same slot
495 where the event is emitted. See :ref:`scheduling` for possible values.
496 order : int, optional
497 The priority of of this group for operations occurring at the same time
498 step and in the same scheduling slot. Defaults to the order where the
499 event is emitted + 1, i.e. it will be recorded directly afterwards.
500 name : str, optional
501 A unique name for the object, otherwise will use
502 ``source.name+'_spikemonitor_0'``, etc.
503 codeobj_class : class, optional
504 The `CodeObject` class to run code with.
505
506 Examples
507 --------
508 >>> from brian2 import *
509 >>> spikes = SpikeGeneratorGroup(3, [0, 1, 2], [0, 1, 2]*ms)
510 >>> spike_mon = SpikeMonitor(spikes)
511 >>> net = Network(spikes, spike_mon)
512 >>> net.run(3*ms)
513 >>> print(spike_mon.i[:])
514 [0 1 2]
515 >>> print(spike_mon.t[:])
516 [ 0. 1. 2.] ms
517 >>> print(spike_mon.t_[:])
518 [ 0. 0.001 0.002]
519 >>> from brian2 import *
520 >>> G = NeuronGroup(2, '''counter1 : integer
521 ... counter2 : integer
522 ... max_value : integer''',
523 ... threshold='counter1 >= max_value',
524 ... reset='counter1 = 0')
525 >>> G.run_regularly('counter1 += 1; counter2 += 1') # doctest: +ELLIPSIS
526 CodeRunner(...)
527 >>> G.max_value = [50, 100]
528 >>> mon = SpikeMonitor(G, variables='counter2')
529 >>> net = Network(G, mon)
530 >>> net.run(10*ms)
531 >>> print(mon.i[:])
532 [0 0 1]
533 >>> print(mon.counter2[:])
534 [ 50 100 100]
535 """
536
537 def __init__(
538 self,
539 source,
540 variables=None,
541 record=True,
542 when=None,
543 order=None,
544 name="spikemonitor*",
545 codeobj_class=None,
546 ):
547 #: The array of spike counts (length = size of target group)
548 self.count = None
549 del self.count # this is handled by the Variable mechanism
550 super().__init__(
551 source,
552 event="spike",
553 variables=variables,
554 record=record,
555 when=when,
556 order=order,
557 name=name,
558 codeobj_class=codeobj_class,
559 )
560
561 @property
562 def num_spikes(self):
563 """
564 Returns the total number of recorded spikes.
565 """
566 return self.num_events
567
568 # We "re-implement" the following functions only to get more specific
569 # doc strings (and to make sure that the methods are included in the
570 # reference documentation for SpikeMonitor).
571
572 def spike_trains(self):
573 """
574 Return a dictionary mapping neuron indices to arrays of spike times.
575
576 Returns
577 -------
578 spike_trains : dict
579 Dictionary that stores an array with the spike times for each
580 neuron index.
581
582 Examples
583 --------
584 >>> from brian2 import *
585 >>> spikes = SpikeGeneratorGroup(3, [0, 1, 2], [0, 1, 2]*ms)
586 >>> spike_mon = SpikeMonitor(spikes)
587 >>> run(3*ms)
588 >>> spike_trains = spike_mon.spike_trains()
589 >>> spike_trains[1]
590 array([ 1.]) * msecond
591 """
592 return self.event_trains()
593
594 def values(self, var):
595 """
596 Return a dictionary mapping neuron indices to arrays of variable values
597 at the time of the spikes (sorted by time).
598
599 Parameters
600 ----------
601 var : str
602 The name of the variable.
603
604 Returns
605 -------
606 values : dict
607 Dictionary mapping each neuron index to an array of variable
608 values at the time of the spikes.
609
610 Examples
611 --------
612 >>> from brian2 import *
613 >>> G = NeuronGroup(2, '''counter1 : integer
614 ... counter2 : integer
615 ... max_value : integer''',
616 ... threshold='counter1 >= max_value',
617 ... reset='counter1 = 0')
618 >>> G.run_regularly('counter1 += 1; counter2 += 1') # doctest: +ELLIPSIS
619 CodeRunner(...)
620 >>> G.max_value = [50, 100]
621 >>> mon = SpikeMonitor(G, variables='counter2')
622 >>> run(10*ms)
623 >>> counter2_values = mon.values('counter2')
624 >>> print(counter2_values[0])
625 [ 50 100]
626 >>> print(counter2_values[1])
627 [100]
628 """
629 return super().values(var)
630
631 def all_values(self):
632 """
633 Return a dictionary mapping recorded variable names (including ``t``)
634 to a dictionary mapping neuron indices to arrays of variable values at
635 the time of the spikes (sorted by time). This is equivalent to (but more
636 efficient than) calling `values` for each variable and storing the
637 result in a dictionary.
638
639 Returns
640 -------
641 all_values : dict
642 Dictionary mapping variable names to dictionaries which themselves
643 are mapping neuron indicies to arrays of variable values at the
644 time of the spikes.
645
646 Examples
647 --------
648 >>> from brian2 import *
649 >>> G = NeuronGroup(2, '''counter1 : integer
650 ... counter2 : integer
651 ... max_value : integer''',
652 ... threshold='counter1 >= max_value',
653 ... reset='counter1 = 0')
654 >>> G.run_regularly('counter1 += 1; counter2 += 1') # doctest: +ELLIPSIS
655 CodeRunner(...)
656 >>> G.max_value = [50, 100]
657 >>> mon = SpikeMonitor(G, variables='counter2')
658 >>> run(10*ms)
659 >>> all_values = mon.all_values()
660 >>> print(all_values['counter2'][0])
661 [ 50 100]
662 >>> print(all_values['t'][1])
663 [ 9.9] ms
664 """
665 return super().all_values()
666
667 def __repr__(self):
668 classname = self.__class__.__name__
669 return f"<{classname}, recording from '{self.group.name}'>"