Debian Codegraph @

docs_sphinx/user/models.rst

raw
1 Models and neuron groups
2 ========================
3 .. sidebar:: For Brian 1 users
4
5 See the document :doc:`../introduction/brian1_to_2/neurongroup` for details how
6 to convert Brian 1 code.
7
8 .. contents::
9 :local:
10 :depth: 1
11
12 Model equations
13 ---------------
14
15 The core of every simulation is a `NeuronGroup`, a group of neurons that share
16 the same equations defining their properties. The minimum `NeuronGroup`
17 specification contains the number of neurons and the model description in the
18 form of equations::
19
20 G = NeuronGroup(10, 'dv/dt = -v/(10*ms) : volt')
21
22 This defines a group of 10 leaky integrators. The model description can be
23 directly given as a (possibly multi-line) string as above, or as an
24 `Equations` object. For more details on the form of equations, see
25 :doc:`equations`. Brian needs the model to be given in the form of differential
26 equations, but you might see the integrated form of synapses in some textbooks
27 and papers. See :doc:`converting_from_integrated_form` for details on how
28 to convert between these representations.
29
30 Note that model descriptions can make reference to physical
31 units, but also to scalar variables declared outside of the model description
32 itself::
33
34 tau = 10*ms
35 G = NeuronGroup(10, 'dv/dt = -v/tau : volt')
36
37 If a variable should be taken as a *parameter* of the neurons, i.e. if it
38 should be possible to vary its value across neurons, it has to be declared
39 as part of the model description::
40
41 G = NeuronGroup(10, '''dv/dt = -v/tau : volt
42 tau : second''')
43
44 To make complex model descriptions more readable, named subexpressions can
45 be used::
46
47 G = NeuronGroup(10, '''dv/dt = I_leak / Cm : volt
48 I_leak = g_L*(E_L - v) : amp''')
49
50 For a list of some standard model equations, see
51 :doc:`../introduction/brian1_to_2/neurongroup`.
52
53 Noise
54 -----
55
56 In addition to ordinary differential equations, Brian allows you to
57 introduce random noise by specifying a
58 `stochastic differential equation <https://en.wikipedia.org/wiki/Stochastic_differential_equation>`__.
59 Brian uses the physicists' notation used in the
60 `Langevin equation <https://en.wikipedia.org/wiki/Langevin_equation>`__,
61 representing the "noise" as a term :math:`\xi(t)`, rather than the
62 mathematicians' stochastic differential :math:`\mathrm{d}W_t`. The
63 following is an example of the
64 `Ornstein-Uhlenbeck process <http://www.scholarpedia.org/article/Stochastic_dynamical_systems#Ornstein-Uhlenbeck_process>`__
65 that is often used to model a leaky integrate-and-fire neuron with
66 a stochastic current::
67
68 G = NeuronGroup(10, 'dv/dt = -v/tau + sigma*sqrt(2/tau)*xi : volt')
69
70 You can start by thinking of ``xi`` as just a Gaussian random variable
71 with mean 0 and standard deviation 1. However, it scales in an
72 unusual way with time and this gives it units of ``1/sqrt(second)``.
73 You don't necessarily need to understand why this is, but it is
74 possible to get a reasonably simple intuition for it by thinking
75 about numerical integration: :ref:`see below <time_scaling_of_noise>`.
76
77 .. note::
78 If you want to use noise in more than one equation of a
79 `NeuronGroup` or `Synapses`, you will have to use suffixed names (see
80 :ref:`equation_strings` for details).
81
82 Threshold and reset
83 -------------------
84 To emit spikes, neurons need a *threshold*. Threshold and reset are given
85 as strings in the `NeuronGroup` constructor::
86
87 tau = 10*ms
88 G = NeuronGroup(10, 'dv/dt = -v/tau : volt', threshold='v > -50*mV',
89 reset='v = -70*mV')
90
91 Whenever the threshold condition is fulfilled, the reset statements will be
92 executed. Again, both threshold and reset can refer to physical units,
93 external variables and parameters, in the same way as model descriptions::
94
95 v_r = -70*mV # reset potential
96 G = NeuronGroup(10, '''dv/dt = -v/tau : volt
97 v_th : volt # neuron-specific threshold''',
98 threshold='v > v_th', reset='v = v_r')
99
100 You can also create non-spike events. See :doc:`/advanced/custom_events`
101 for more details.
102
103 Refractoriness
104 --------------
105 To make a neuron non-excitable for a certain time period after a spike, the
106 refractory keyword can be used::
107
108 G = NeuronGroup(10, 'dv/dt = -v/tau : volt', threshold='v > -50*mV',
109 reset='v = -70*mV', refractory=5*ms)
110
111 This will not allow any threshold crossing for a neuron for 5ms after a spike.
112 The refractory keyword allows for more flexible refractoriness specifications,
113 see :doc:`refractoriness` for details.
114
115 .. _state_variables:
116
117 State variables
118 ---------------
119 Differential equations and parameters in model descriptions are stored as
120 *state variables* of the `NeuronGroup`. In addition to these variables, Brian
121 also defines two variables automatically:
122
123 ``i``
124 The index of a neuron.
125
126 ``N``
127 The total number of neurons.
128
129 All state variables can be accessed and set as an
130 attribute of the group. To get the values without physical units (e.g. for
131 analysing data with external tools), use an underscore after the name:
132
133 .. doctest::
134
135 >>> G = NeuronGroup(10, '''dv/dt = -v/tau : volt
136 ... tau : second''', name='neurons')
137 >>> G.v = -70*mV
138 >>> G.v
139 <neurons.v: array([-70., -70., -70., -70., -70., -70., -70., -70., -70., -70.]) * mvolt>
140 >>> G.v_ # values without units
141 <neurons.v_: array([-0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.07])>
142
143 The value of state variables can also be set using string expressions that can
144 refer to units and external variables, other state variables or mathematical
145 functions:
146
147 .. doctest::
148
149 >>> G.tau = '5*ms + (1.0*i/N)*5*ms'
150 >>> G.tau
151 <neurons.tau: array([ 5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5]) * msecond>
152
153 You can also set the value only if a condition holds, for example:
154
155 .. doctest::
156
157 >>> G.v['tau>7.25*ms'] = -60*mV
158 >>> G.v
159 <neurons.v: array([-70., -70., -70., -70., -70., -60., -60., -60., -60., -60.]) * mvolt>
160
161 .. _subgroups:
162
163 Subgroups
164 ---------
165 It is often useful to refer to a subset of neurons, this can be achieved using
166 Python's slicing syntax::
167
168 G = NeuronGroup(10, '''dv/dt = -v/tau : volt
169 tau : second''',
170 threshold='v > -50*mV',
171 reset='v = -70*mV')
172 # Create subgroups
173 G1 = G[:5]
174 G2 = G[5:]
175
176 # This will set the values in the main group, subgroups are just "views"
177 G1.tau = 10*ms
178 G2.tau = 20*ms
179
180 Here ``G1`` refers to the first 5 neurons in G, and ``G2`` to the second 5
181 neurons. In general ``G[i:j]`` refers to the neurons with indices from ``i``
182 to ``j-1``, as in general in Python.
183
184 For convenience, you can also use a single index, i.e. ``G[i]`` is equivalent
185 to ``G[i:i+1]``. In some situations, it can be easier to provide a list of
186 indices instead of a slice, Brian therefore also allows for this syntax. Note
187 that this is restricted to cases that are strictly equivalent with slicing
188 syntax, e.g. you can write ``G[[3, 4, 5]]`` instead of ``G[3:6]``, but you
189 *cannot* write ``G[[3, 5, 7]]`` or ``G[[5, 4, 3]]``.
190
191 Subgroups can be used in most places where regular groups are used, e.g. their
192 state variables or spiking activity can be recorded using monitors, they can be
193 connected via `Synapses`, etc. In such situations, indices (e.g. the indices of
194 the neurons to record from in a `StateMonitor`) are relative to the subgroup,
195 not to the main group
196
197 .. admonition:: The following topics are not essential for beginners.
198
199 |
200
201 .. _shared_variables:
202
203 Shared variables
204 ----------------
205
206 Sometimes it can also be useful to introduce shared variables or subexpressions,
207 i.e. variables that have a common value for all neurons. In contrast to
208 external variables (such as ``Cm`` above), such variables can change during a
209 run, e.g. by using :meth:`~brian2.groups.group.Group.run_regularly`. This can be
210 for example used for an external stimulus that changes in the course of a run:
211
212 .. doctest::
213
214 >>> G = NeuronGroup(10, '''shared_input : volt (shared)
215 ... dv/dt = (-v + shared_input)/tau : volt
216 ... tau : second''', name='neurons')
217
218 Note that there are several restrictions around the use of shared variables:
219 they cannot be written to in contexts where statements apply only to a subset
220 of neurons (e.g. reset statements, see below). If a code block mixes statements
221 writing to shared and vector variables, then the shared statements have to
222 come first.
223
224 By default, subexpressions are re-evaluated whenever they are used, i.e. using
225 a subexpression is completely equivalent to substituting it. Sometimes it is
226 useful to instead only evaluate a subexpression once and then use this value
227 for the rest of the time step. This can be achieved by using the
228 ``(constant over dt)`` flag. This flag is mandatory for subexpressions that
229 refer to stateful functions like ``rand()`` which notably allows them to be
230 recorded with a `StateMonitor` -- otherwise the monitor would record a different
231 instance of the random number than the one that was used in the equations.
232
233 For shared variables, setting by string expressions can only refer to shared values:
234
235 .. doctest::
236
237 >>> G.shared_input = '(4.0/N)*mV'
238 >>> G.shared_input
239 <neurons.shared_input: 0.4 * mvolt>
240
241 .. _storing_state_variables:
242
243 Storing state variables
244 -----------------------
245
246 Sometimes it can be convenient to access multiple state variables at once, e.g.
247 to set initial values from a dictionary of values or to store all the values of
248 a group on disk. This can be done with the
249 :meth:`~brian2.groups.group.VariableOwner.get_states` and
250 :meth:`~brian2.groups.group.VariableOwner.set_states` methods:
251
252 .. doctest::
253
254 >>> group = NeuronGroup(5, '''dv/dt = -v/tau : 1
255 ... tau : second''', name='neurons')
256 >>> initial_values = {'v': [0, 1, 2, 3, 4],
257 ... 'tau': [10, 20, 10, 20, 10]*ms}
258 >>> group.set_states(initial_values)
259 >>> group.v[:]
260 array([ 0., 1., 2., 3., 4.])
261 >>> group.tau[:]
262 array([ 10., 20., 10., 20., 10.]) * msecond
263 >>> states = group.get_states()
264 >>> states['v']
265 array([ 0., 1., 2., 3., 4.])
266
267 The data (without physical units) can also be exported/imported to/from
268 `Pandas <http://pandas.pydata.org/>`_ data frames (needs an installation of ``pandas``)::
269
270 >>> df = group.get_states(units=False, format='pandas') # doctest: +SKIP
271 >>> df # doctest: +SKIP
272 N dt i t tau v
273 0 5 0.0001 0 0.0 0.01 0.0
274 1 5 0.0001 1 0.0 0.02 1.0
275 2 5 0.0001 2 0.0 0.01 2.0
276 3 5 0.0001 3 0.0 0.02 3.0
277 4 5 0.0001 4 0.0 0.01 4.0
278 >>> df['tau'] # doctest: +SKIP
279 0 0.01
280 1 0.02
281 2 0.01
282 3 0.02
283 4 0.01
284 Name: tau, dtype: float64
285 >>> df['tau'] *= 2 # doctest: +SKIP
286 >>> group.set_states(df[['tau']], units=False, format='pandas') # doctest: +SKIP
287 >>> group.tau # doctest: +SKIP
288 <neurons.tau: array([ 20., 40., 20., 40., 20.]) * msecond>
289
290
291 .. _linked_variables:
292
293 Linked variables
294 ----------------
295
296 A `NeuronGroup`, `Synapses`, or `SpatialNeuron` can define parameters that are
297 not stored in this group, but are instead a reference to a variable in another group.
298 For this, a group defines a parameter as ``linked`` and then uses `linked_var` to
299 specify the linking. This can for example be useful to model shared noise
300 between cells::
301
302 inp = NeuronGroup(1, 'dnoise/dt = -noise/tau + tau**-0.5*xi : 1')
303
304 neurons = NeuronGroup(100, '''noise : 1 (linked)
305 dv/dt = (-v + noise_strength*noise)/tau : volt''')
306 neurons.noise = linked_var(inp, 'noise')
307
308 If the two groups have the same size, the linking will be done in a 1-to-1
309 fashion. If the source group has the size one (as in the above example) or if
310 the source parameter is a shared variable, then the linking will be done as
311 1-to-all. In all other cases, you have to specify the indices to use for the
312 linking explicitly::
313
314 # two inputs with different phases
315 inp = NeuronGroup(2, '''phase : 1
316 dx/dt = 1*mV/ms*sin(2*pi*100*Hz*t-phase) : volt''')
317 inp.phase = [0, pi/2]
318
319 neurons = NeuronGroup(100, '''inp : volt (linked)
320 dv/dt = (-v + inp) / tau : volt''')
321 # Half of the cells get the first input, other half gets the second
322 neurons.inp = linked_var(inp, 'x', index=np.repeat([0, 1], 50))
323
324 Note that this linking does not work for `Synapses`, since the number of synapses
325 is not known in advance. However, all groups supported linking with an index variable.
326 The above example could also be written as::
327
328 # two inputs with different phases
329 inp = NeuronGroup(2, '''phase : 1
330 dx/dt = 1*mV/ms*sin(2*pi*100*Hz*t-phase) : volt''')
331 inp.phase = [0, pi/2]
332
333 neurons = NeuronGroup(100, '''inp : volt (linked)
334 index_var : integer (constant)
335 dv/dt = (-v + inp) / tau : volt''')
336 # Half of the cells get the first input, other half gets the second
337 neurons.inp = linked_var(inp, 'x', index='index_var')
338 neurons.index_var = np.repeat([0, 1], 50)
339
340 .. _time_scaling_of_noise:
341
342 Time scaling of noise
343 ---------------------
344
345 Suppose we just
346 had the differential equation
347
348 :math:`dx/dt=\xi`
349
350 To solve this
351 numerically, we could compute
352
353 :math:`x(t+\mathrm{d}t)=x(t)+\xi_1`
354
355 where :math:`\xi_1` is a normally distributed random number
356 with mean 0 and standard deviation 1.
357 However, what happens if we change the time step? Suppose we used
358 a value of :math:`\mathrm{d}t/2` instead of :math:`\mathrm{d}t`.
359 Now, we compute
360
361 :math:`x(t+\mathrm{d}t)=x(t+\mathrm{d}t/2)+\xi_1=x(t)+\xi_2+\xi_1`
362
363 The mean value of :math:`x(t+\mathrm{d}t)` is 0 in both cases,
364 but the standard deviations are different. The first method
365 :math:`x(t+\mathrm{d}t)=x(t)+\xi_1` gives :math:`x(t+\mathrm{d}t)`
366 a standard deviation of 1, whereas the second method
367 :math:`x(t+\mathrm{d}t)=x(t+\mathrm{d}/2)+\xi_1=x(t)+\xi_2+\xi_1`
368 gives :math:`x(t)` a variance of 1+1=2 and therefore a
369 standard deviation of :math:`\sqrt{2}`.
370
371 In order to solve this
372 problem, we use the rule
373 :math:`x(t+\mathrm{d}t)=x(t)+\sqrt{\mathrm{d}t}\xi_1`, which makes
374 the mean and standard deviation of the value at time :math:`t`
375 independent of :math:`\mathrm{d}t`.
376 For this to make sense dimensionally, :math:`\xi` must have
377 units of ``1/sqrt(second)``.
378
379 For further details, refer to a textbook on stochastic
380 differential equations.