Debian Codegraph @

brian2/input/spikegeneratorgroup.py

raw
1 """
2 Module defining `SpikeGeneratorGroup`.
3 """
4
5 import numpy as np
6
7 from brian2.core.functions import timestep
8 from brian2.core.spikesource import SpikeSource
9 from brian2.core.variables import Variables
10 from brian2.groups.group import CodeRunner, Group
11 from brian2.units.allunits import second
12 from brian2.units.fundamentalunits import Quantity, check_units
13 from brian2.utils.logger import get_logger
14
15 __all__ = ["SpikeGeneratorGroup"]
16
17
18 logger = get_logger(__name__)
19
20
21 class SpikeGeneratorGroup(Group, CodeRunner, SpikeSource):
22 """
23 SpikeGeneratorGroup(N, indices, times, dt=None, clock=None,
24 period=0*second, when='thresholds', order=0,
25 sorted=False, name='spikegeneratorgroup*',
26 codeobj_class=None)
27
28 A group emitting spikes at given times.
29
30 Parameters
31 ----------
32 N : int
33 The number of "neurons" in this group
34 indices : array of integers
35 The indices of the spiking cells
36 times : `Quantity`
37 The spike times for the cells given in ``indices``. Has to have the
38 same length as ``indices``.
39 period : `Quantity`, optional
40 If this is specified, it will repeat spikes with this period. A
41 period of 0s means not repeating spikes.
42 dt : `Quantity`, optional
43 The time step to be used for the simulation. Cannot be combined with
44 the `clock` argument.
45 clock : `Clock`, optional
46 The update clock to be used. If neither a clock, nor the `dt` argument
47 is specified, the `defaultclock` will be used.
48 when : str, optional
49 When to run within a time step, defaults to the ``'thresholds'`` slot.
50 See :ref:`scheduling` for possible values.
51 order : int, optional
52 The priority of of this group for operations occurring at the same time
53 step and in the same scheduling slot. Defaults to 0.
54 sorted : bool, optional
55 Whether the given indices and times are already sorted. Set to ``True``
56 if your events are already sorted (first by spike time, then by index),
57 this can save significant time at construction if your arrays contain
58 large numbers of spikes. Defaults to ``False``.
59
60 Notes
61 -----
62 * If `sorted` is set to ``True``, the given arrays will not be copied
63 (only affects runtime mode)..
64 """
65
66 @check_units(N=1, indices=1, times=second, period=second)
67 def __init__(
68 self,
69 N,
70 indices,
71 times,
72 dt=None,
73 clock=None,
74 period=0 * second,
75 when="thresholds",
76 order=0,
77 sorted=False,
78 name="spikegeneratorgroup*",
79 codeobj_class=None,
80 ):
81 Group.__init__(self, dt=dt, clock=clock, when=when, order=order, name=name)
82
83 # We store the indices and times also directly in the Python object,
84 # this way we can use them for checks in `before_run` even in standalone
85 # TODO: Remove this when the checks in `before_run` have been moved to the template
86 #: Array of spiking neuron indices.
87 self._neuron_index = None
88 #: Array of spiking neuron times.
89 self._spike_time = None
90 #: "Dirty flag" that will be set when spikes are changed after the
91 #: `before_run` check
92 self._spikes_changed = True
93
94 # Let other objects know that we emit spikes events
95 self.events = {"spike": None}
96
97 self.codeobj_class = codeobj_class
98
99 if N < 1 or int(N) != N:
100 raise TypeError("N has to be an integer >=1.")
101 N = int(N)
102 self.start = 0
103 self.stop = N
104
105 self.variables = Variables(self)
106 self.variables.create_clock_variables(self._clock)
107
108 indices, times = self._check_args(
109 indices, times, period, N, sorted, self._clock.dt
110 )
111
112 self.variables.add_constant("N", value=N)
113 self.variables.add_array(
114 "period",
115 dimensions=second.dim,
116 size=1,
117 constant=True,
118 read_only=True,
119 scalar=True,
120 dtype=self._clock.variables["t"].dtype,
121 )
122 self.variables.add_arange("i", N)
123 self.variables.add_dynamic_array(
124 "spike_number",
125 values=np.arange(len(indices)),
126 size=len(indices),
127 dtype=np.int32,
128 read_only=True,
129 constant=True,
130 index="spike_number",
131 unique=True,
132 )
133 self.variables.add_dynamic_array(
134 "neuron_index",
135 values=indices,
136 size=len(indices),
137 dtype=np.int32,
138 index="spike_number",
139 read_only=True,
140 constant=True,
141 )
142 self.variables.add_dynamic_array(
143 "spike_time",
144 values=times,
145 size=len(times),
146 dimensions=second.dim,
147 index="spike_number",
148 read_only=True,
149 constant=True,
150 dtype=self._clock.variables["t"].dtype,
151 )
152 self.variables.add_dynamic_array(
153 "_timebins",
154 size=len(times),
155 index="spike_number",
156 read_only=True,
157 constant=True,
158 dtype=np.int32,
159 )
160 self.variables.add_array(
161 "_period_bins",
162 size=1,
163 constant=True,
164 read_only=True,
165 scalar=True,
166 dtype=np.int32,
167 )
168 self.variables.add_array("_spikespace", size=N + 1, dtype=np.int32)
169 self.variables.add_array(
170 "_lastindex", size=1, values=0, dtype=np.int32, read_only=True, scalar=True
171 )
172
173 #: Remember the dt we used the last time when we checked the spike bins
174 #: to not repeat the work for multiple runs with the same dt
175 self._previous_dt = None
176
177 CodeRunner.__init__(
178 self,
179 self,
180 code="",
181 template="spikegenerator",
182 clock=self._clock,
183 when=when,
184 order=order,
185 name=None,
186 )
187
188 # Activate name attribute access
189 self._enable_group_attributes()
190
191 self.variables["period"].set_value(period)
192
193 def _full_state(self):
194 state = super()._full_state()
195 # Store the internal information we use to decide whether to rebuild
196 # the time bins
197 state["_previous_dt"] = self._previous_dt
198 state["_spikes_changed"] = self._spikes_changed
199 return state
200
201 def _restore_from_full_state(self, state):
202 state = state.copy() # copy to avoid errors for multiple restores
203 self._previous_dt = state.pop("_previous_dt")
204 self._spikes_changed = state.pop("_spikes_changed")
205 super()._restore_from_full_state(state)
206
207 def before_run(self, run_namespace):
208 # Do some checks on the period vs. dt
209 dt = self.dt_[:] # make a copy
210 period = self.period_
211 if period < np.inf and period != 0:
212 if period < dt:
213 raise ValueError(
214 f"The period of '{self.name}' is {self.period[:]!s}, "
215 f"which is smaller than its dt of {dt * second!s}."
216 )
217
218 if self._spikes_changed:
219 current_t = self.variables["t"].get_value().item()
220 timesteps = timestep(self._spike_time, dt)
221 current_step = timestep(current_t, dt)
222 in_the_past = np.nonzero(timesteps < current_step)[0]
223 if len(in_the_past):
224 logger.warn(
225 "The SpikeGeneratorGroup contains spike times "
226 "earlier than the start time of the current run "
227 f"(t = {current_t * second!s}), these spikes will be "
228 "ignored.",
229 name_suffix="ignored_spikes",
230 )
231 self.variables["_lastindex"].set_value(in_the_past[-1] + 1)
232 else:
233 self.variables["_lastindex"].set_value(0)
234
235 # Check that we don't have more than one spike per neuron in a time bin
236 if self._previous_dt is None or dt != self._previous_dt or self._spikes_changed:
237 # We shift all the spikes by a tiny amount to make sure that spikes
238 # at exact multiples of dt do not end up in the previous time bin
239 # This shift has to be quite significant relative to machine
240 # epsilon, we use 1e-3 of the dt here
241 shift = 1e-3 * dt
242 timebins = np.asarray(
243 np.asarray(self._spike_time + shift) / dt, dtype=np.int32
244 )
245 # time is already in sorted order, so it's enough to check if the condition
246 # that timebins[i]==timebins[i+1] and self._neuron_index[i]==self._neuron_index[i+1]
247 # is ever both true
248 if (
249 np.logical_and(np.diff(timebins) == 0, np.diff(self._neuron_index) == 0)
250 ).any():
251 raise ValueError(
252 f"Using a dt of {self.dt!s}, some neurons of "
253 f"SpikeGeneratorGroup '{self.name}' spike more than "
254 "once during a time step."
255 )
256 self.variables["_timebins"].set_value(timebins)
257 period_bins = np.round(period / dt)
258 max_int = np.iinfo(np.int32).max
259 if period_bins > max_int:
260 logger.warn(
261 f"Periods longer than {max_int} timesteps "
262 f"(={max_int * dt * second!s}) are not "
263 "supported, the period will therefore be "
264 "considered infinite. Set the period to 0*second "
265 "to avoid this "
266 "warning.",
267 "spikegenerator_long_period",
268 )
269 period = period_bins = 0
270 if np.abs(period_bins * dt - period) > period * np.finfo(dt.dtype).eps:
271 raise NotImplementedError(
272 f"The period of '{self.name}' is "
273 f"{self.period[:]!s}, which is "
274 "not an integer multiple of its dt "
275 f"of {dt * second!s}."
276 )
277
278 self.variables["_period_bins"].set_value(period_bins)
279
280 self._previous_dt = dt
281 self._spikes_changed = False
282
283 super().before_run(run_namespace=run_namespace)
284
285 @check_units(indices=1, times=second, period=second)
286 def set_spikes(self, indices, times, period=0 * second, sorted=False):
287 """
288 set_spikes(indices, times, period=0*second, sorted=False)
289
290 Change the spikes that this group will generate.
291
292 This can be used to set the input for a second run of a model based on
293 the output of a first run (if the input for the second run is already
294 known before the first run, then all the information should simply be
295 included in the initial `SpikeGeneratorGroup` initializer call,
296 instead).
297
298 Parameters
299 ----------
300 indices : array of integers
301 The indices of the spiking cells
302 times : `Quantity`
303 The spike times for the cells given in ``indices``. Has to have the
304 same length as ``indices``.
305 period : `Quantity`, optional
306 If this is specified, it will repeat spikes with this period. A
307 period of 0s means not repeating spikes.
308 sorted : bool, optional
309 Whether the given indices and times are already sorted. Set to
310 ``True`` if your events are already sorted (first by spike time,
311 then by index), this can save significant time at construction if
312 your arrays contain large numbers of spikes. Defaults to ``False``.
313 """
314
315 indices, times = self._check_args(
316 indices, times, period, self.N, sorted, self.dt
317 )
318
319 self.variables["period"].set_value(period)
320 self.variables["neuron_index"].resize(len(indices))
321 self.variables["spike_time"].resize(len(indices))
322 self.variables["spike_number"].resize(len(indices))
323 self.variables["spike_number"].set_value(np.arange(len(indices)))
324 self.variables["_timebins"].resize(len(indices))
325 self.variables["neuron_index"].set_value(indices)
326 self.variables["spike_time"].set_value(times)
327 # _lastindex and _timebins will be set as part of before_run
328
329 def _check_args(self, indices, times, period, N, sorted, dt):
330 times = Quantity(times)
331 if len(indices) != len(times):
332 raise ValueError(
333 "Length of the indices and times array must "
334 f"match, but {len(indices)} != {len(times)}"
335 )
336 if period < 0 * second:
337 raise ValueError("The period cannot be negative.")
338 elif len(times) and period != 0 * second:
339 period_bins = np.round(period / dt)
340 # Note: we have to use the timestep function here, to use the same
341 # binning as in the actual simulation
342 max_bin = timestep(np.max(times), dt)
343 if max_bin >= period_bins:
344 raise ValueError(
345 "The period has to be greater than the maximum of the spike times"
346 )
347 if len(times) and np.min(times) < 0 * second:
348 raise ValueError("Spike times cannot be negative")
349 if len(indices) and (np.min(indices) < 0 or np.max(indices) >= N):
350 raise ValueError(f"Indices have to lie in the interval [0, {int(N)}[")
351
352 times = np.asarray(times)
353 indices = np.asarray(indices)
354 if not sorted:
355 # sort times and indices first by time, then by indices
356 sort_indices = np.lexsort((indices, times))
357 indices = indices[sort_indices]
358 times = times[sort_indices]
359
360 # We store the indices and times also directly in the Python object,
361 # this way we can use them for checks in `before_run` even in standalone
362 # TODO: Remove this when the checks in `before_run` have been moved to the template
363 self._neuron_index = indices
364 self._spike_time = times
365 self._spikes_changed = True
366
367 return indices, times
368
369 @property
370 def spikes(self):
371 """
372 The spikes returned by the most recent thresholding operation.
373 """
374 # Note that we have to directly access the ArrayVariable object here
375 # instead of using the Group mechanism by accessing self._spikespace
376 # Using the latter would cut _spikespace to the length of the group
377 spikespace = self.variables["_spikespace"].get_value()
378 return spikespace[: spikespace[-1]]
379
380 def __repr__(self):
381 cls = self.__class__.__name__
382 size = self.variables["neuron_index"].size
383 return (
384 f"{cls}({self.N}, indices=<length {size} array>, times=<length"
385 f" {size} array>)"
386 )