Debian Codegraph @

docs_sphinx/user/running.rst

raw
1 Running a simulation
2 ====================
3 .. sidebar:: For Brian 1 users
4
5 See the document :doc:`../introduction/brian1_to_2/networks_and_clocks` for
6 details how to convert Brian 1 code.
7
8 .. contents::
9 :local:
10 :depth: 1
11
12
13 To run a simulation, one either constructs a new `Network` object and calls its
14 `Network.run` method, or uses the "magic" system and a plain `run` call,
15 collecting all the objects in the current namespace.
16
17 Note that Brian has several different ways of running the actual computations,
18 and choosing the right one can make orders of magnitude of difference in
19 terms of simplicity and efficiency. See :doc:`computation` for more details.
20
21 .. _networks:
22
23 Networks
24 --------
25 In most straightforward simulations, you do not have to explicitly create a
26 `Network` object but instead can simply call `run` to run a simulation. This is
27 what is called the "magic" system, because Brian figures out automatically what
28 you want to do.
29
30 When calling `run`, Brian runs the `collect` function to gather all the objects
31 in the current context. It will include all the objects that are "visible", i.e.
32 that you could refer to with an explicit name::
33
34 G = NeuronGroup(10, 'dv/dt = -v / (10*ms) : 1',
35 threshold='v > 1', reset='v = 0')
36 S = Synapses(G, G, model='w:1', on_pre='v+=w')
37 S.connect('i!=j')
38 S.w = 'rand()'
39 mon = SpikeMonitor(G)
40
41 run(10*ms) # will include G, S, mon
42
43 Note that it will not automatically include objects that are "hidden" in
44 containers, e.g. if you store several monitors in a list. Use an explicit
45 `Network` object in this case. It might be convenient to use the `collect`
46 function when creating the `Network` object in that case::
47
48 G = NeuronGroup(10, 'dv/dt = -v / (10*ms) : 1',
49 threshold='v > 1', reset='v = 0')
50 S = Synapses(G, G, model='w:1', on_pre='v+=w')
51 S.connect('i!=j')
52 S.w = 'rand()'
53 monitors = [SpikeMonitor(G), StateMonitor(G, 'v', record=True)]
54
55 # a simple run would not include the monitors
56 net = Network(collect()) # automatically include G and S
57 net.add(monitors) # manually add the monitors
58
59 net.run(10*ms)
60
61 .. _time_steps:
62
63 Setting the simulation time step
64 --------------------------------
65
66 To set the simulation time step for every simulated object, set the ``dt`` attribute of the `defaultclock` which is used
67 by all objects that do not explicitly specify a ``clock`` or ``dt`` value during construction::
68
69 defaultclock.dt = 0.05*ms
70
71 If some objects should use a different clock (e.g. to record values with a `StateMonitor` not at every time step in a
72 long running simulation), you can provide a ``dt`` argument to the respective object::
73
74 s_mon = StateMonitor(group, 'v', record=True, dt=1*ms)
75
76 To sum up:
77
78 * Set ``defaultclock.dt`` to the time step that should be used by most (or all) of your objects.
79 * Set ``dt`` explicitly when creating objects that should use a different time step.
80
81 Behind the scenes, a new `Clock` object will be created for each object that defines its own ``dt`` value.
82
83 .. _progress_reporting:
84
85 Progress reporting
86 ------------------
87 Especially for long simulations it is useful to get some feedback about the
88 progress of the simulation. Brian offers a few built-in options and an
89 extensible system to report the progress of the simulation. In the `Network.run`
90 or `run` call, two arguments determine the output: ``report`` and
91 ``report_period``. When ``report`` is set to ``'text'`` or ``'stdout'``, the
92 progress will be printed to the standard output, when it is set to ``'stderr'``,
93 it will be printed to "standard error". There will be output at the start and
94 the end of the run, and during the run in ``report_period`` intervals. It is
95 also possible to do :ref:`custom progress reporting <custom_progress_reporting>`.
96
97 .. _continue_repeat:
98
99 Continuing/repeating simulations
100 --------------------------------
101
102 To store the current state of the simulation, call
103 `store` (use the `Network.store` method for a `Network`). You
104 can store more than one snapshot of a system by providing a name for the
105 snapshot; if `store` is called without a specified name,
106 ``'default'`` is used as the name. To restore the state, use
107 `restore`.
108
109 The following simple example shows how this system can be used to run several
110 trials of an experiment::
111
112 # set up the network
113 G = NeuronGroup(...)
114 ...
115 spike_monitor = SpikeMonitor(G)
116
117 # Snapshot the state
118 store()
119
120 # Run the trials
121 spike_counts = []
122 for trial in range(3):
123 restore() # Restore the initial state
124 run(...)
125 # store the results
126 spike_counts.append(spike_monitor.count)
127
128 The following schematic shows how multiple snapshots can be used to run a
129 network with a separate "train" and "test" phase. After training, the test is
130 run several times based on the trained network. The whole process of training
131 and testing is repeated several times as well::
132
133 # set up the network
134 G = NeuronGroup(..., '''...
135 test_input : amp
136 ...''')
137 S = Synapses(..., '''...
138 plastic : boolean (shared)
139 ...''')
140 G.v = ...
141 S.connect(...)
142 S.w = ...
143
144 # First snapshot at t=0
145 store('initialized')
146
147 # Run 3 complete trials
148 for trial in range(3):
149 # Simulate training phase
150 restore('initialized')
151 S.plastic = True
152 run(...)
153
154 # Snapshot after learning
155 store('after_learning')
156
157 # Run 5 tests after the training
158 for test_number in range(5):
159 restore('after_learning')
160 S.plastic = False # switch plasticity off
161 G.test_input = test_inputs[test_number]
162 # monitor the activity now
163 spike_mon = SpikeMonitor(G)
164 run(...)
165 # Do something with the result
166 # ...
167
168 .. admonition:: The following topics are not essential for beginners.
169
170 |
171
172 Multiple magic runs
173 -------------------
174
175 When you use more than a single `run` statement, the magic system tries to
176 detect which of the following two situations applies:
177
178 1. You want to continue a previous simulation
179 2. You want to start a new simulation
180
181 For this, it uses the following heuristic: if a simulation consists only of
182 objects that have not been run, it will start a new simulation starting at
183 time 0 (corresponding to the creation of a new `Network` object). If a
184 simulation only consists of objects that have been simulated in the previous
185 `run` call, it will continue that simulation at the previous time.
186
187 If neither of these two situations apply, i.e., the network consists of a mix
188 of previously run objects and new objects, an error will be raised. If this is
189 not a mistake but intended (e.g. when a new input source and synapses should be
190 added to a network at a later stage), use an explicit `Network` object.
191
192 In these checks, "non-invalidating" objects (i.e. objects that have
193 `BrianObject.invalidates_magic_network` set to ``False``) are ignored, e.g.
194 creating new monitors is always possible.
195
196 Note that if you do not want to run an object for the complete duration of your
197 simulation, you can create the object in the beginning of your simulation
198 and then set its `~.BrianObject.active` attribute. For details, see the
199 :ref:`Scheduling <Scheduling>` section below.
200
201 Changing the simulation time step
202 ---------------------------------
203 You can change the simulation time step after objects have been created or even after a simulation has been run::
204
205 defaultclock.dt = 0.1*ms
206 # Set the network
207 # ...
208 run(initial_time)
209 defaultclock.dt = 0.01*ms
210 run(full_time - initial_time)
211
212 To change the time step between runs for objects that do not use the `defaultclock`, you cannot directly change their
213 ``dt`` attribute (which is read-only) but instead you have to change the ``dt`` of the ``clock`` attribute. If you want
214 to change the ``dt`` value of several objects at the same time (but not for all of them, i.e. when you cannot use
215 ``defaultclock.dt``) then you might consider creating a `Clock` object explicitly and then passing this clock to each
216 object with the ``clock`` keyword argument (instead of ``dt``). This way, you can later change the ``dt`` for several
217 objects at once by assigning a new value to `Clock.dt`.
218
219 Note that a change of ``dt`` has to be compatible with the internal representation of
220 clocks as an integer value (the number of elapsed time steps). For example, you
221 can simulate an object for 100ms with a time step of 0.1ms (i.e. for 1000 steps)
222 and then switch to a ``dt`` of 0.5ms, the time will then be internally
223 represented as 200 steps. You cannot, however, switch to a dt of 0.3ms, because
224 100ms are not an integer multiple of 0.3ms.
225
226 .. _profiling:
227
228 Profiling
229 ---------
230
231 To get an idea which parts of a simulation take the most time, Brian offers a
232 basic profiling mechanism. If a simulation is run with the ``profile=True``
233 keyword argument, it will collect information about the total simulation time
234 for each `CodeObject`. This information can then be retrieved from
235 `Network.profiling_info`, which contains a list of ``(name, time)`` tuples. For
236 convenience, a string summary can be obtained by calling `profiling_summary` (which
237 will automatically refer to the current :ref:`"magic" network <networks>`). The
238 following example shows profiling output after running the CUBA example (where
239 the neuronal state updates take up the most time)::
240
241 >>> from brian2 import profiling_summary
242 >>> profiling_summary(show=5) # show the 5 objects that took the longest # doctest: +SKIP
243 Profiling summary
244 =================
245 neurongroup_stateupdater 5.54 s 61.32 %
246 synapses_pre 1.39 s 15.39 %
247 synapses_1_pre 1.03 s 11.37 %
248 spikemonitor 0.59 s 6.55 %
249 neurongroup_thresholder 0.33 s 3.66 %
250
251 If you use an explicit `~.Network` object, you need to pass it to ``profiling_summary``::
252
253 >>> net = Network(...) # doctest: +SKIP
254 >>> profiling_summary(net, ...) # doctest: +SKIP
255
256 .. _scheduling:
257
258 Scheduling
259 ----------
260
261 Every simulated object in Brian has three attributes that can be specified at
262 object creation time: ``dt``, ``when``, and ``order``. The time step of the
263 simulation is determined by ``dt``, if it is specified, or otherwise by
264 ``defaultclock.dt``. Changing this will therefore change the ``dt`` of
265 all objects that don't specify one. Alternatively, a ``clock`` object
266 can be specified directly, this can be useful if a clock should be shared
267 between several objects -- under most circumstances, however, a user should not
268 have to deal with the creation of `Clock` objects and just define ``dt``.
269
270 During a single time step, objects are updated in an order according first
271 to their ``when``
272 argument's position in the schedule. This schedule is determined by
273 `Network.schedule` which is a list of strings, determining "execution slots" and
274 their order. It defaults to: ``['start', 'groups', 'thresholds', 'synapses',
275 'resets', 'end']``. In addition to the names provided in the schedule, names
276 such as ``before_thresholds`` or ``after_synapses`` can be used that are
277 understood as slots in the respective positions. The default
278 for the ``when`` attribute is a sensible value for most objects (resets will
279 happen in the ``reset`` slot, etc.) but sometimes it make sense to change it,
280 e.g. if one would like a `StateMonitor`, which by default records in the
281 ``start`` slot, to record the membrane potential before a reset is applied
282 (otherwise no threshold crossings will be observed in the membrane potential
283 traces).
284
285 Finally, if during a time step two objects fall in the same execution
286 slot, they will be updated in ascending order according to their
287 ``order`` attribute, an integer number defaulting to 0. If two objects have
288 the same ``when`` and ``order`` attribute then they will be updated in an
289 arbitrary but reproducible order (based on the lexicographical order of their
290 names).
291
292 Note that objects that don't do any computation by themselves but only
293 act as a container for other objects (e.g. a `NeuronGroup` which contains a
294 `StateUpdater`, a `Resetter` and a `Thresholder`), don't have any value for
295 ``when``, but pass on the given values for ``dt`` and ``order`` to their
296 containing objects.
297
298 If you want your simulation object to run only for a particular time
299 period of the whole simulation, you can use the `~.BrianObject.active`
300 attribute. For example, this can be useful when you want a monitor to be
301 active only for some time out of a long simulation::
302
303 # Set up the network
304 # ...
305 monitor = SpikeMonitor(...)
306 monitor.active = False
307 run(long_time*seconds) # not recording
308 monitor.active = True
309 run(required_time*seconds) # recording
310
311 To see how the objects in a network are scheduled, you can use the
312 `scheduling_summary` function::
313
314 >>> group = NeuronGroup(10, 'dv/dt = -v/(10*ms) : 1', threshold='v > 1',
315 ... reset='v = 0')
316 >>> mon = StateMonitor(group, 'v', record=True, dt=1*ms)
317 >>> scheduling_summary() # doctest: +SKIP
318 object | part of | Clock dt | when | order | active
319 ----------------------------------------+-----------------------------+------------------------+------------+-------+-------
320 statemonitor (StateMonitor) | statemonitor (StateMonitor) | 1. ms (every 10 steps) | start | 0 | yes
321 neurongroup_stateupdater (StateUpdater) | neurongroup (NeuronGroup) | 100. us (every step) | groups | 0 | yes
322 neurongroup_thresholder (Thresholder) | neurongroup (NeuronGroup) | 100. us (every step) | thresholds | 0 | yes
323 neurongroup_resetter (Resetter) | neurongroup (NeuronGroup) | 100. us (every step) | resets | 0 | yes
324
325
326 As you can see in the output above, the `StateMonitor` will only record the
327 membrane potential every 10 time steps, but when it does, it will do it at the
328 start of the time step, before the numerical integration, the thresholding, and
329 the reset operation takes place.
330
331 Every new `Network` starts a simulation at time 0; `Network.t` is a read-only
332 attribute, to go back to a previous moment in time (e.g. to do another trial
333 of a simulation with a new noise instantiation) use the mechanism described
334 below.
335
336 Store/restore
337 -------------
338
339 Note that `Network.run`, `Network.store` and `Network.restore` (or `run`,
340 `store`, `restore`) are the only way of affecting the time of the clocks. In
341 contrast to Brian1, it is no longer necessary (nor possible) to directly set
342 the time of the clocks or call a ``reinit`` function.
343
344 The state of a network can also be stored on disk with the optional ``filename``
345 argument of `Network.store`/`store`. This way, you can run the initial part of
346 a simulation once, store it to disk, and then continue from this state later.
347 Note that the `store`/`restore` mechanism does not re-create the network as
348 such, you still need to construct all the `NeuronGroup`, `Synapses`,
349 `StateMonitor`, ... objects, restoring will only restore all the state variable
350 values (membrane potential, conductances, synaptic connections/weights/delays,
351 ...). This restoration does however restore the internal state of the objects
352 as well, e.g. spikes that have not been delivered yet because of synaptic
353 delays will be delivered correctly.