Debian Codegraph @

examples/frompapers/Maass_Natschlaeger_Markram_2002.py

raw
1 #!/usr/bin/env python3
2 """
3 Fig. 2 from:
4
5 Real-Time Computing Without Stable States: A New
6 Framework for Neural Computation Based on Perturbations
7
8 Neural Computation 14, 2531–2560 (2002)
9
10 by Maass W., Natschläger T. and Markram H.
11
12 Sebastian Schmitt, 2022
13 """
14 from collections import defaultdict
15 import multiprocessing
16
17 import numpy as np
18 import matplotlib.pyplot as plt
19
20 from brian2 import (
21 NeuronGroup,
22 Synapses,
23 SpikeGeneratorGroup,
24 SpikeMonitor,
25 Network,
26 prefs,
27 )
28 from brian2 import ms, mV, Mohm, nA, second, Hz
29 from brian2 import defaultclock, prefs
30
31 N_NEURONS = 135
32 V_THRESH = 15 * mV
33 V_RESET = 13.5 * mV
34
35 STIMULUS_POISSON_RATE = 20 * Hz
36 TARGET_DISTANCES = [0.4, 0.2, 0.1]
37 N_PAIRS = 200
38
39 DT = 0.1 * ms
40 DURATION = 500 * ms
41 TS = np.arange(0, DURATION / ms, DT / ms)
42
43
44 def exponential_convolution(t, spikes, tau):
45 """Convolute spikes with exponential kernel
46 t -- numpy array of times to evaluate the convolution
47 spikes -- iterable of spike times
48 tau -- exponential decay constant
49 """
50 if len(spikes):
51 return sum([np.exp(-((t - st) / tau)) * (t >= st) for st in spikes])
52 else:
53 return np.zeros(len(TS))
54
55
56 def gaussian_convolution(t, spikes, tau):
57 """Convolute spikes with Gaussian kernel
58 t -- numpy array of times to evaluate the convolution
59 spikes -- iterable of spike times
60 tau -- exponential decay constant
61 """
62 if len(spikes):
63 return sum([np.exp(-(((t - st) / tau) ** 2)) for st in spikes])
64 else:
65 return np.zeros(len(TS))
66
67
68 def euclidian_distance(liquid_states_u, liquid_states_v):
69 """Euclidian distance between liquid states
70 liquid_states_u -- liquid states
71 liquid_states_v -- other liquid states
72
73 To match the numbers in the paper, the square root is omitted
74 """
75
76 return np.mean((liquid_states_u - liquid_states_v) ** 2, axis=0)
77
78
79 def distance(conv_a, conv_b, dt):
80 """Difference of convolutions in the L2-norm
81 conv_a -- convolutions
82 conv_b -- other convolutions
83 dt -- time step
84
85 To match the numbers in the paper, the square root is omitted
86 """
87
88 return sum((conv_a - conv_b) ** 2) * dt
89
90
91 def generate_poisson(duration, rate):
92 """Generate Poisson spike train
93 duration -- duration of spike train
94 rate -- rate of spike train
95
96 Return only spike trains that do not have multiple spikes per time bin
97 """
98 while True:
99 N = np.random.poisson(rate * duration)
100 spikes = np.random.uniform(0, duration, N)
101
102 spikes_orig = np.sort(spikes)
103 shift = 1e-3 * (DT / ms)
104 timebins = ((spikes_orig + shift) / (DT / ms)).astype(np.int32)
105
106 if not any(np.diff(timebins) == 0):
107 return spikes_orig
108
109
110 def collect_stimulus_pairs():
111 """Collect pairs of input stimuli close in target distance"""
112 DELTA_DISTANCE = 0.01
113 collected_pairs = defaultdict(list)
114
115 while True:
116
117 spikes_u = generate_poisson(DURATION / ms, STIMULUS_POISSON_RATE / Hz / 1e3)
118 spikes_v = generate_poisson(DURATION / ms, STIMULUS_POISSON_RATE / Hz / 1e3)
119
120 conv_u = gaussian_convolution(TS, spikes_u, tau=5)
121 conv_v = gaussian_convolution(TS, spikes_v, tau=5)
122
123 normed_distance = distance(conv_u, conv_v, DT / ms) / (DURATION / ms)
124
125 for target_distance in TARGET_DISTANCES:
126 if (
127 abs(normed_distance - target_distance) < DELTA_DISTANCE
128 and len(collected_pairs[target_distance]) < N_PAIRS
129 ):
130 collected_pairs[target_distance].append((spikes_u, spikes_v))
131
132 # stop if we have enough pairs collected
133 if len(collected_pairs) == len(TARGET_DISTANCES) and all(
134 np.array(list(map(len, collected_pairs.values()))) == N_PAIRS
135 ):
136 break
137
138 return collected_pairs
139
140
141 def get_neurons():
142 neurons = NeuronGroup(
143 N_NEURONS,
144 """
145 tau_mem : second (shared, constant)
146 tau_refrac : second (constant)
147 v_reset : volt (shared, constant)
148 v_thresh : volt (shared, constant)
149 I_b : ampere (shared, constant)
150 tau_stimulus : second (constant)
151 I_syn_ee_synapses : ampere
152 I_syn_ei_synapses : ampere
153 I_syn_ie_synapses : ampere
154 I_syn_ii_synapses : ampere
155 dI_stimulus/dt = -I_stimulus/tau_stimulus : ampere
156 R_in : ohm
157 dv/dt = -v/tau_mem + (I_syn_ee_synapses +
158 I_syn_ei_synapses +
159 I_syn_ie_synapses +
160 I_syn_ii_synapses)*R_in/tau_mem
161 + I_b*R_in/tau_mem
162 + I_stimulus*R_in/tau_mem: volt (unless refractory)
163 x_pos : 1 (constant)
164 y_pos : 1 (constant)
165 z_pos : 1 (constant)
166 """,
167 threshold="v>v_thresh",
168 reset="v=v_reset",
169 refractory="tau_refrac",
170 method="exact",
171 name="neurons",
172 )
173
174 neurons.tau_mem = 30 * ms
175 neurons.v_thresh = V_THRESH
176 neurons.v_reset = V_RESET
177
178 neurons.I_b = 13.5 * nA
179
180 neurons.v[:] = (
181 np.random.uniform(V_RESET / mV, V_THRESH / mV, size=len(neurons)) * mV
182 )
183
184 neurons.R_in = 1 * Mohm
185
186 # to randomly assign excitatory and inhibitory neurons later
187 indices = np.arange(len(neurons))
188 np.random.shuffle(indices)
189
190 # a column of 15x3x3 neurons
191 neurons.x_pos = indices % 3
192 neurons.y_pos = (indices // 3) % 3
193 neurons.z_pos = indices // 9
194
195 return neurons
196
197
198 def get_synapses(name, source, target, C, l, tau_I, A, U, D, F, delay):
199 synapses_eqs = """
200 A : ampere (constant)
201 U : 1 (constant)
202 tau_I : second (shared, constant)
203 D : second (constant)
204 dx/dt = z/D : 1 (clock-driven) # recovered
205 dy/dt = -y/tau_I : 1 (clock-driven) # active
206 z = 1 - x - y : 1 # inactive
207 I_syn_{}_post = A*y : ampere (summed)
208 """.format(name)
209
210 if F:
211 synapses_eqs += """
212 du/dt = -u/F : 1 (clock-driven)
213 F : second (constant)
214 """
215
216 synapses_action = """
217 u += U*(1-u)
218 y += u*x # important: update y first
219 x += -u*x
220 """
221 else:
222 synapses_action = """
223 y += U*x # important: update y first
224 x += -U*x
225 """
226
227 synapses = Synapses(
228 source,
229 target,
230 model=synapses_eqs,
231 on_pre=synapses_action,
232 method="exact",
233 name=name,
234 delay=delay,
235 )
236
237 synapses.connect(
238 p=f"{C} * exp(-((x_pos_pre-x_pos_post)**2 + (y_pos_pre-y_pos_post)**2 + (z_pos_pre-z_pos_post)**2)/{l}**2)"
239 )
240
241 N_syn = len(synapses)
242
243 synapses.tau_I = tau_I
244
245 synapses.A[:] = np.sign(A / nA) * np.random.gamma(1, abs(A / nA), size=N_syn) * nA
246
247 synapses.U[:] = np.random.normal(U, 0.5 * U, size=N_syn)
248 # paper samples from uniform, we take the mean
249 synapses.U[:][synapses.U < 0] = U
250
251 synapses.D[:] = np.random.normal(D / ms, 0.5 * D / ms, size=N_syn) * ms
252 # paper samples from uniform, we take the mean
253 synapses.D[:][synapses.D / ms <= 0] = D
254
255 # start fully recovered
256 synapses.x = 1
257
258 if F:
259 synapses.F[:] = np.random.normal(F / ms, 0.5 * F / ms, size=N_syn) * ms
260 # paper samples from uniform, we take the mean
261 synapses.F[:][synapses.F / ms <= 0] = F
262
263 return synapses
264
265
266 def sim(net, spike_times):
267 """Run network with given stimulus
268
269 Redraws initial membrane voltages
270
271 net -- the network to simulate
272 spike_times -- the stimulus to inject
273 """
274 net.restore()
275
276 net["neurons"].v = (
277 np.random.uniform(V_RESET / mV, V_THRESH / mV, size=len(neurons)) * mV
278 )
279 net["stimulus"].set_spikes([0] * len(spike_times), spike_times * ms)
280
281 net.run(DURATION)
282
283 spikes = list(net["spike_monitor_exc"].spike_trains().values()) + list(
284 net["spike_monitor_inh"].spike_trains().values()
285 )
286
287 liquid_states = np.array(
288 [exponential_convolution(TS, st / ms, tau=30) for st in spikes]
289 )
290
291 return liquid_states
292
293 if __name__ == '__main__':
294 neurons = get_neurons()
295
296 N_exc = int(0.8 * len(neurons))
297
298 exc_neurons = neurons[:N_exc]
299 exc_neurons.tau_refrac = 3 * ms
300 exc_neurons.tau_stimulus = 3 * ms
301
302 inh_neurons = neurons[N_exc:]
303 inh_neurons.tau_refrac = 2 * ms
304 inh_neurons.tau_stimulus = 6 * ms
305
306 l_lambda = 2
307
308 ee_synapses = get_synapses(
309 "ee_synapses",
310 exc_neurons,
311 exc_neurons,
312 C=0.3,
313 l=l_lambda,
314 tau_I=3 * ms,
315 A=30 * nA,
316 U=0.5,
317 D=1.1 * second,
318 F=0.05 * second,
319 delay=1.5 * ms,
320 )
321 ei_synapses = get_synapses(
322 "ei_synapses",
323 exc_neurons,
324 inh_neurons,
325 C=0.2,
326 l=l_lambda,
327 tau_I=3 * ms,
328 A=60 * nA,
329 U=0.05,
330 D=0.125 * second,
331 F=1.2 * second,
332 delay=0.8 * ms,
333 )
334 ie_synapses = get_synapses(
335 "ie_synapses",
336 inh_neurons,
337 exc_neurons,
338 C=0.4,
339 l=l_lambda,
340 tau_I=6 * ms,
341 A=-19 * nA,
342 U=0.25,
343 D=0.7 * second,
344 F=0.02 * second,
345 delay=0.8 * ms,
346 )
347 ii_synapses = get_synapses(
348 "ii_synapses",
349 inh_neurons,
350 inh_neurons,
351 C=0.1,
352 l=l_lambda,
353 tau_I=6 * ms,
354 A=-19 * nA,
355 U=0.32,
356 D=0.144 * second,
357 F=0.06 * second,
358 delay=0.8 * ms,
359 )
360
361 # place holder for stimulus
362 stimulus = SpikeGeneratorGroup(1, [], [] * ms, name="stimulus")
363
364 spike_monitor_stimulus = SpikeMonitor(stimulus)
365
366 static_synapses_exc = Synapses(
367 stimulus,
368 exc_neurons,
369 "A : ampere (shared, constant)",
370 on_pre="I_stimulus += A"
371 )
372 static_synapses_exc.connect(p=1)
373 static_synapses_exc.A = 18 * nA
374
375 static_synapses_inh = Synapses(
376 stimulus,
377 inh_neurons,
378 "A : ampere (shared, constant)",
379 on_pre="I_stimulus += A"
380 )
381 static_synapses_inh.connect(p=1)
382 static_synapses_inh.A = 9 * nA
383
384 spike_monitor_exc = SpikeMonitor(exc_neurons, name="spike_monitor_exc")
385 spike_monitor_inh = SpikeMonitor(inh_neurons, name="spike_monitor_inh")
386
387 defaultclock.dt = DT
388
389 net = Network(
390 [
391 neurons,
392 ee_synapses,
393 ei_synapses,
394 ie_synapses,
395 ii_synapses,
396 static_synapses_exc,
397 static_synapses_inh,
398 stimulus,
399 spike_monitor_exc,
400 spike_monitor_inh,
401 ]
402 )
403 net.store()
404
405 collected_pairs = collect_stimulus_pairs()
406
407 # add only jittered pairs
408 collected_pairs[0] = [
409 [generate_poisson(DURATION / ms, STIMULUS_POISSON_RATE / Hz / 1e3)] * 2
410 for _ in range(N_PAIRS)
411 ]
412
413 def map_sim(spike_times):
414 """Wrapper to sim for multiprocessing
415 """
416 return sim(net, spike_times)
417
418 result = defaultdict(list)
419 # loop over all distances and Poisson stimulus pairs
420 for d, pairs in collected_pairs.items():
421
422 with multiprocessing.Pool() as p:
423 states_u = p.map(map_sim, [p[0] for p in pairs])
424 states_v = p.map(map_sim, [p[1] for p in pairs])
425
426 for liquid_states_u, liquid_states_v in zip(states_u, states_v):
427 ed = euclidian_distance(liquid_states_u, liquid_states_v)
428 result[d].append(ed)
429 # plot
430 fig, ax = plt.subplots(figsize=(5, 5))
431
432 linestyles = ["dashed", (0, (8, 6, 1, 6)), (0, (5, 10)), "solid"]
433
434 for d, ls in zip(TARGET_DISTANCES + [0], linestyles):
435
436 eds = result[d]
437 eds = np.array(eds)
438
439 ax.plot(
440 TS / 1000, np.mean(eds, axis=0), label=f"d(u,v)={d}", linestyle=ls, color="k"
441 )
442
443 ax.set_xlabel("time [sec]")
444 ax.set_ylabel("state distance")
445
446 ax.set_xlim(0, 0.5)
447 ax.set_ylim(0, 2.5)
448
449 ax.legend(loc="upper center", fontsize="x-large", frameon=False)
450
451 plt.show()