Debian Codegraph @

docs_sphinx/user/recording.rst

raw
1 Recording during a simulation
2 =============================
3 .. sidebar:: For Brian 1 users
4
5 See the document :doc:`../introduction/brian1_to_2/monitors` for details how
6 to convert Brian 1 code.
7
8 .. contents::
9 :local:
10 :depth: 1
11
12 Recording variables during a simulation is done with "monitor" objects.
13 Specifically, spikes are recorded with `SpikeMonitor`, the time evolution of
14 variables with `StateMonitor` and the firing rate of a population of neurons
15 with `PopulationRateMonitor`.
16
17 Recording spikes
18 ----------------
19
20 To record spikes from a group ``G`` simply create a `SpikeMonitor` via
21 ``SpikeMonitor(G)``. After the simulation, you can access the attributes
22 ``i``, ``t``, ``num_spikes`` and ``count`` of the monitor.
23 The ``i`` and ``t``
24 attributes give the array of neuron indices and times of the spikes. For
25 example, if ``M.i==[0, 2, 1]`` and ``M.t==[1*ms, 2*ms, 3*ms]`` it means that
26 neuron 0 fired a spike at 1 ms, neuron 2 fired a spike at 2 ms, and neuron 1
27 fired a spike at 3 ms. Alternatively, you can also call the
28 `~brian2.monitors.spikemonitor.SpikeMonitor.spike_trains` method to get a
29 dictionary mapping neuron indices to arrays of spike times, i.e. in the above
30 example, ``spike_trains = M.spike_trains(); spike_trains[1]`` would return
31 ``array([ 3.]) * msecond``. The ``num_spikes`` attribute gives the total number
32 of spikes recorded, and ``count`` is an array of the length of the recorded
33 group giving the total number of spikes recorded from each neuron.
34
35 Example::
36
37 G = NeuronGroup(N, model='...')
38 M = SpikeMonitor(G)
39 run(runtime)
40 plot(M.t/ms, M.i, '.')
41
42 If you are only interested in summary statistics but not the individual spikes,
43 you can set the ``record`` argument to ``False``. You will then not have access
44 to ``i`` and ``t`` but you can still get the ``count`` and the total number of
45 spikes (``num_spikes``).
46
47 To get a matrix of spike rates in time bins for each neuron you can use a monitor's
48 `~.EventMonitor.binned_rate` method. To get smoothed rates use
49 `~.RateMonitor.smooth_rate`
50
51 .. _recording_variables_spike_time:
52
53 Recording variables at spike time
54 ---------------------------------
55
56 By default, a `SpikeMonitor` only records the time of the spike and the index
57 of the neuron that spiked. Sometimes it can be useful to addtionaly record
58 other variables, e.g. the membrane potential for models where the threshold is
59 not at a fixed value. This can be done by providing an extra ``variables``
60 argument, the recorded variable can then be accessed as an attribute of the
61 `SpikeMonitor`, e.g.::
62
63 G = NeuronGroup(10, 'v : 1', threshold='rand()<100*Hz*dt')
64 G.run_regularly('v = rand()')
65 M = SpikeMonitor(G, variables=['v'])
66 run(100*ms)
67 plot(M.t/ms, M.v, '.')
68
69 To conveniently access the values of a recorded variable for
70 a single neuron, the `SpikeMonitor.values` method can be used that returns a
71 dictionary with the values for each neuron.::
72
73 G = NeuronGroup(N, '''dv/dt = (1-v)/(10*ms) : 1
74 v_th : 1''',
75 threshold='v > v_th',
76 # randomly change the threshold after a spike:
77 reset='''v=0
78 v_th = clip(v_th + rand()*0.2 - 0.1, 0.1, 0.9)''')
79 G.v_th = 0.5
80 spike_mon = SpikeMonitor(G, variables='v')
81 run(1*second)
82 v_values = spike_mon.values('v')
83 print('Threshold crossing values for neuron 0: {}'.format(v_values[0]))
84 hist(spike_mon.v, np.arange(0, 1, .1))
85 show()
86
87 .. note:: Spikes are not the only events that can trigger recordings, see
88 :doc:`../advanced/custom_events`.
89
90 .. _recording_variables_continuously:
91
92 Recording variables continuously
93 --------------------------------
94
95 To record how a variable evolves over time, use a `StateMonitor`, e.g.
96 to record the variable ``v`` at every time step and plot it for
97 neuron 0::
98
99 G = NeuronGroup(...)
100 M = StateMonitor(G, 'v', record=True)
101 run(...)
102 plot(M.t/ms, M.v[0]/mV)
103
104 In general,
105 you specify the group, variables and indices you want to record from. You
106 specify the variables with a string or list of strings, and the indices
107 either as an array of indices or ``True`` to record all indices (but beware
108 because this may take a lot of memory).
109
110 After the simulation, you can access these variables as attributes of the
111 monitor. They are 2D arrays with shape ``(num_indices, num_times)``. The
112 special attribute ``t`` is an array of length ``num_times`` with the
113 corresponding times at which the values were recorded.
114
115 Note that you can also use `StateMonitor` to record from `Synapses` where
116 the indices are the synapse indices rather than neuron indices.
117
118 In this example, we record two variables v and u, and record from indices 0,
119 10 and 100. Afterwards, we plot the recorded values of v and u from neuron 0::
120
121 G = NeuronGroup(...)
122 M = StateMonitor(G, ('v', 'u'), record=[0, 10, 100])
123 run(...)
124 plot(M.t/ms, M.v[0]/mV, label='v')
125 plot(M.t/ms, M.u[0]/mV, label='u')
126
127 There are two subtly different ways to get the values for specific neurons: you
128 can either index the 2D array stored in the attribute with the variable name
129 (as in the example above) or you can index the monitor itself. The former will
130 use an index relative to the recorded neurons (e.g. `M.v[1]` will return the
131 values for the second *recorded* neuron which is the neuron with the index 10
132 whereas `M.v[10]` would raise an error because only three neurons have been
133 recorded), whereas the latter will use an absolute index corresponding to the
134 recorded group (e.g. `M[1].v` will raise an error because the neuron with the
135 index 1 has not been recorded and `M[10].v` will return the values for the
136 neuron with the index 10). If all neurons have been recorded (e.g. with
137 ``record=True``) then both forms give the same result.
138
139 Note that for plotting all recorded values at once, you have to transpose the
140 variable values::
141
142 plot(M.t/ms, M.v.T/mV)
143
144 .. note::
145 In contrast to Brian 1, the values are recorded at the
146 beginning of a time step and not at the end (you can set the ``when`` argument
147 when creating a `StateMonitor`, details about scheduling can be
148 found here: :ref:`scheduling`).
149
150 Recording variables at pre-defined times
151 ----------------------------------------
152 A `StateMonitor` can also be used to record variable values at arbitrary times, by
153 making it run on an `~brian2.core.clocks.EventClock` instead of with the usual regular clock::
154
155 M = StateMonitor(G, 'v', record=True, clock=EventClock(times=[1, 10, 100]*ms))
156
157 The recorded values can be accessed in the same way as for a monitor running on a
158 regular clock.
159
160 Recording population rates
161 --------------------------
162
163 To record the time-varying firing rate of a population of neurons use
164 `PopulationRateMonitor`. After the simulation the monitor will have two
165 attributes ``t`` and ``rate``, the latter giving the firing rate at each
166 time step corresponding to the time in ``t``. For example::
167
168 G = NeuronGroup(...)
169 M = PopulationRateMonitor(G)
170 run(...)
171 plot(M.t/ms, M.rate/Hz)
172
173 To get a smoother version of the rate, use the monitor's
174 `~.RateMonitor.smooth_rate` method. To get rates in non-overlapping bins use
175 `~.PopulationRateMonitor.binned_rate`.
176
177 .. admonition:: The following topics are not essential for beginners.
178
179 |
180
181 Getting all data
182 ----------------
183
184 Note that all monitors are implement as "groups", so you can get all the stored
185 values in a monitor with the `~.VariableOwner.get_states` method, which can be useful to
186 dump all recorded data to disk, for example::
187
188 import pickle
189 group = NeuronGroup(...)
190 state_mon = StateMonitor(group, 'v', record=...)
191 run(...)
192 data = state_mon.get_states(['t', 'v'])
193 with open('state_mon.pickle', 'w') as f:
194 pickle.dump(data, f)
195
196
197 Recording values for a subset of the run
198 ----------------------------------------
199
200 Monitors can be created and deleted between runs, e.g. to ignore the first second
201 of your simulation in your recordings you can do::
202
203 # Set up network without monitor
204 run(1*second)
205 state_mon = StateMonitor(....)
206 run(...) # Continue run and record with the StateMonitor
207
208 Alternatively, you can set the monitor's `~.BrianObject.active` attribute as
209 explained in the :ref:`scheduling` section.
210
211 Freeing up memory in long recordings
212 ------------------------------------
213
214 Creating and deleting monitors can also be useful to free memory during a
215 long recording. The following will do a simulation run, dump the monitor
216 data to disk, delete the monitor and finally continue the run with a new
217 monitor::
218
219 import pickle
220 # Set up network
221 state_mon = StateMonitor(...)
222 run(...) # a long run
223 data = state_mon.get_states(...)
224 with open('first_part.data', 'w') as f:
225 pickle.dump(data, f)
226 del state_mon
227 del data
228 state_mon = StateMonitor(...)
229 run(...) # another long run
230
231 Note that this technique cannot be applied in :ref:`standalone mode <cpp_standalone>`.
232
233 Recording random subsets of neurons
234 -----------------------------------
235
236 In large networks, you might only be interested in the activity of a
237 random subset of neurons. While you can specify a ``record`` argument
238 for a `StateMonitor` that allows you to select a subset of neurons, this
239 is not possible for `SpikeMonitor`/`EventMonitor` and `PopulationRateMonitor`.
240 However, Brian allows you to record with these monitors from a subset of neurons
241 by using a :ref:`subgroup <subgroups>`::
242
243 group = NeuronGroup(1000, ...)
244 spike_mon = SpikeMonitor(group[:100]) # only record first 100 neurons
245
246 It might seem like a restriction that such a subgroup has to be contiguous, but
247 the order of neurons in a group does not have any meaning as such; in a randomly
248 ordered group of neurons, any contiguous group of neurons can be considered a
249 random subset. If some aspects of your model *do* depend on the position of the
250 neuron in a group (e.g. a ring model, where neurons are connected based on their
251 distance in the ring, or a model where initial values or parameters span a
252 range of values in a regular fashion), then this requires an extra step: instead
253 of using the order of neurons in the group directly, or depending on the neuron
254 index ``i``, create a new, shuffled, index variable as part of the model
255 definition and then depend on this index instead::
256
257 group = NeuronGroup(10000, '''....
258 index : integer (constant)''')
259 indices = group.i[:]
260 np.random.shuffle(indices)
261 group.index = indices
262 # Then use 'index' in string expressions or use it as an index array
263 # for initial values/parameters defined as numpy arrays
264
265 If this solution is not feasible for some reason, there is another approach that
266 works for a `SpikeMonitor`/`EventMonitor`. You can add an additional flag to
267 each neuron, stating whether it should be recorded or not. Then, you define a
268 new :doc:`custom event </advanced/custom_events>` that is identical to the event you are
269 interested in, but additionally requires the flag to be set. E.g. to only record
270 the spikes of neurons with the ``to_record`` attribute set::
271
272 group = NeuronGroup(..., '''...
273 to_record : boolean (constant)''',
274 threshold='...', reset='...',
275 events={'recorded_spike': '... and to_record'})
276 group.to_record = ...
277 mon_events = EventMonitor(group, 'recorded_spike')
278
279 Note that this solution will evaluate the threshold condition for each neuron
280 twice, and is therefore slightly less efficient. There's one additional caveat:
281 you'll have to manually include ``and not_refractory`` in your ``events``
282 definition if your neuron uses refractoriness. This is done automatically
283 for the ``threshold`` condition, but not for any user-defined events.
284
285 Recording population averages
286 -----------------------------
287
288 Continuous recordings from large groups over long simulation times can
289 fill up the working memory quickly: recording a single variable from
290 1000 neurons for 100 seconds at the default time resolution results in
291 an array of about 8 Gigabytes. While this issue can be ameliorated using the
292 above approaches, the downstream data analysis is often based on
293 population averages. These can be recorded efficiently using a dummy
294 group and the `Synapses` class' :ref:`summed variable syntax
295 <summed_variables>`::
296
297 group = NeuronGroup(..., 'dv/dt = ... : volt', ...)
298
299 # Dummy group to store the average membrane potential at every time step
300 vm_container = NeuronGroup(1, 'average_vm : volt')
301
302 # Synapses averaging the membrane potential of all neurons in group
303 vm_averager = Synapses(group, vm_container, 'average_vm_post = v_pre/N_pre : volt (summed)')
304 vm_averager.connect()
305
306 # Monitor recording the average membrane potential
307 vm_monitor = StateMonitor(vm_container, 'average_vm', record=True)