Debian Codegraph @

examples/frompapers/Spreizer_et_al_2019/Spreizer_et_al_2019.py

raw
1 #!/usr/bin/env python
2 # coding: utf-8
3
4 """
5 Reproduction of Fig. 2 (b and c) of Spreizer et al. 2019 in Brian:
6
7 Spreizer S, Aertsen A, Kumar A. From space to time: Spatial inhomogeneities lead to the emergence of spatiotemporal sequences in spiking neuronal networks. PLOS Computational Biology. 2019;15(10):e1007432. doi:10.1371/journal.pcbi.1007432
8
9 - Requires the ``noise`` package for setting up the Perlin landscape with freshly generated noise. Otherwise,
10 the landscapes for different network sizes (scaled down by a factor of 1 to 5) can be
11 loaded from the provided files.
12
13 This code was written by Arash Golmohammadi, 2022. Modified plotting code by Marcel Stimberg, 2023.
14 """
15 import os
16 import numpy as np
17 import brian2 as b2
18 from brian2.units import ms, pA, mV
19
20 import matplotlib.pyplot as plt
21 from matplotlib import animation
22
23 b2.seed(8)
24
25
26 def round_to_even(gs, scaler):
27 """
28 rounds the network size to an even number.
29 """
30 rounded = round(gs / scaler)
31 if rounded % 2:
32 rounded += 1
33 return int(rounded)
34
35
36 # ---------------- CONFIGURATIONS ---------------- #
37
38 # NETWORK TOPOLOGY
39 SCALE_DOWN = 5 # For faster computation I recommend running with SCALE_DOWN 2 or 3
40 GRID_SIZE = round_to_even(100, SCALE_DOWN)
41 NCONN = round_to_even(1000, SCALE_DOWN**2)
42
43 # CELL CONFIGS
44 THR, REF, RESET = -55 * mV, 2 * ms, -70 * mV
45
46 # PROFILE
47 THETA, KAPPA, GAP = 3 / SCALE_DOWN, 4, 3
48
49 # ANISOTROPY
50 R, SCALE = 1.0, 4 # perlin noise
51 PHI_H = np.pi / 6 # homog. angle
52
53 # WARMUP
54 DUR_WU, STD_WU = 500 * ms, 500 * pA
55
56 # BACKGROUND
57 MU, SIGMA = 700 * pA, 100 * pA
58
59
60 EQ_NRN = """
61 dv/dt = (E-v)/tau_m + (noise + I_syn)/C : volt (unless refractory)
62 I_syn : amp
63 noise = mu + sigma*sqrt(noise_dt)*xi_pop: amp
64
65 mu : amp (shared)
66 sigma : amp (shared)
67 noise_dt = 1*ms : second (shared)
68 C = 250*pF : farad (shared)
69 tau_m = 10*ms : second (shared)
70 E = -70*mV : volt (shared)
71 """
72
73 EQ_SYN = f"""
74 dg/dt = (-g+h) / tau_s : 1 (clock-driven)
75 dh/dt = -h / tau_s : 1 (clock-driven)
76 I_syn_post = J*g : amp (summed)
77 J = -{SCALE_DOWN}*10*pA : amp (shared)
78 tau_s = 5*ms : second (shared)
79 """
80
81 ON_PRE = "h += exp(1)" # to match NEST's normalization
82
83
84 # ---------------- UTILITIES ---------------- #
85 def coord2idx(coords, pop):
86 """Converts array of coordinates to indices."""
87 coords = np.asarray(coords).reshape(-1, 2)
88 idxs = coords[:, 1] * GRID_SIZE + coords[:, 0]
89 return idxs
90
91
92 def idx2coord(idxs, pop):
93 """Converts array of indices to coordinates"""
94 idxs = np.asarray(idxs)
95 y, x = np.divmod(idxs, GRID_SIZE)
96 coords = np.array([x, y]).T
97 return coords
98
99
100 def make_periodic(x, y, grid_size=GRID_SIZE):
101 x = x % GRID_SIZE
102 y = y % GRID_SIZE
103 return x, y
104
105
106 # ---------------- LANDSCAPE GENERATION ---------------- #
107 def landscape(anisotropy="perlin"):
108 """Generates an angular bias for each neuron in the
109 network such that no angle is more likely than the
110 other. Yet, nearby bias angles may be correleted.
111
112 Note that this is a flattened array."""
113
114 if anisotropy == "perlin": # requires noise package
115 if os.path.exists(f"perlin{SCALE_DOWN}.npy"):
116 print("Loading perlin noise from file...")
117 phis = np.load(f"perlin{SCALE_DOWN}.npy")
118 else:
119 print("Generating perlin noise...")
120 from noise import pnoise2 as perlin
121
122 x = y = np.linspace(0, SCALE, GRID_SIZE)
123 phis = [[perlin(i, j, repeatx=SCALE, repeaty=SCALE) for j in y] for i in x]
124 phis = np.concatenate(phis)
125 phis = balance_landscape(phis)
126 phis -= phis.min()
127 phis *= 2 * np.pi / phis.max()
128 elif anisotropy == "homog":
129 phis = np.ones(GRID_SIZE**2) * PHI_H
130 else: # both random and symmetric have the same landscape
131 phis = np.random.uniform(0, 2 * np.pi, size=GRID_SIZE**2)
132
133 return phis
134
135
136 def balance_landscape(array):
137 """Equalizes the histogram."""
138
139 sorted_idx = np.argsort(array)
140 gs = int(np.sqrt(len(array)))
141 max_val = gs * 2
142 idx = int(len(array) // max_val)
143 for i, val in enumerate(range(max_val)):
144 array[sorted_idx[i * idx : (i + 1) * idx]] = val
145
146 return (array - gs) / gs
147
148 # ---------------- NETWORK SETUP ---------------- #
149 def setup_net(phis):
150 I = b2.NeuronGroup(
151 N=GRID_SIZE**2,
152 name="I",
153 model=EQ_NRN,
154 refractory=5 * ms,
155 threshold=f"v>{THR / mV}*mV",
156 reset=f"v={RESET / mV}*mV",
157 method="euler",
158 )
159 I.mu = MU
160 I.sigma = SIGMA
161
162 syn_II = b2.Synapses(
163 I, I, model=EQ_SYN, on_pre=ON_PRE, method="exact", name="syn_II"
164 )
165
166 for s_idx in range(len(I)):
167 rel_coords = draw_post(s_idx, phis[s_idx])
168 s_coord = idx2coord(s_idx, I) # check shape
169 x, y = (rel_coords + s_coord).T
170 x, y = make_periodic(x, y)
171 t_coords = np.array([x, y]).T.astype(int)
172 t_idxs = coord2idx(t_coords, I)
173
174 syn_II.connect(i=s_idx, j=t_idxs)
175
176 return I, syn_II
177
178
179 def draw_post(idx, phi):
180 alpha = np.random.uniform(-np.pi, np.pi, NCONN)
181 radius = np.concatenate(
182 [
183 -np.random.gamma(shape=KAPPA, scale=THETA, size=int(NCONN // 2)),
184 +np.random.gamma(shape=KAPPA, scale=THETA, size=NCONN - int(NCONN // 2)),
185 ]
186 )
187
188 radius[radius < 0] -= GAP
189 radius[radius >= 0] += GAP
190
191 x, y = radius * np.cos(alpha), radius * np.sin(alpha)
192 x += R * np.cos(phi)
193 y += R * np.sin(phi)
194
195 eps = 1e-3
196 self_link = x**2 + y**2 < eps**2
197 x = x[~self_link]
198 y = y[~self_link]
199
200 coords = np.array([x, y]).T
201 return np.round(coords).astype(int)
202
203
204 def warmup(net):
205 net["I"].mu = 0 * pA
206 net["I"].sigma = STD_WU
207
208 net.run(DUR_WU / 2)
209 net["I"].mu = MU
210 net["I"].sigma = SIGMA
211 net.run(DUR_WU / 2)
212
213
214 def simulate(phis, dur=3000 * ms):
215 b2.start_scope()
216 I, syn_II = setup_net(phis)
217 mon = b2.SpikeMonitor(I, record=True)
218
219 net = b2.Network()
220 net.add(I)
221 net.add(syn_II)
222 net.add(mon)
223
224 warmup(net)
225 net.run(dur)
226
227 return net, mon
228
229 # ---------------- VISUALIZATION ---------------- #
230 def plot_firing_rate_disto(idxs, ts, ax, name):
231 """plots distribution of firing rates over the simulation"""
232
233 T = np.max(ts) - np.min(ts)
234 _, rates = np.unique(idxs, return_counts=True)
235 rates = rates * 1.0 / T
236 ax.hist(
237 rates,
238 bins=25,
239 density=True,
240 label=name,
241 histtype="step",
242 orientation="horizontal",
243 lw=2,
244 )
245 ax.set(
246 ylabel="Firing rate [Hz]",
247 xlabel="Probability density",
248 xscale="log",
249 ylim=(0, 64),
250 )
251
252 def plot_in_deg(in_deg, ax, ax_hist, name):
253 """plots distribution as well as the heat map of in-degree from each neuron."""
254 # field map & distribution of in-degrees
255 m = ax.pcolormesh(in_deg, shading="flat", vmin=0.5 * NCONN, vmax=1.5 * NCONN)
256 ax_hist.hist(
257 in_deg.flatten(),
258 bins=50,
259 density=True,
260 label=name,
261 histtype="step",
262 orientation="horizontal",
263 lw=2,
264 )
265
266 ax_hist.set(ylabel="In-degree", ylim=(0.5 * NCONN, 1.5 * NCONN))
267
268 ax.set(
269 aspect="equal",
270 xticks=[],
271 yticks=[],
272 title=name,
273 )
274 ax_hist.locator_params(axis="x", nbins=3)
275 return m
276
277 def animator(fig, all_imgs, all_vals):
278 """used for making an activity animation"""
279 n_frames = len(all_vals[0][0]) # total number of frames
280
281 def animate(frame_id):
282 for img, vals in zip(all_imgs, all_vals):
283 img.set_array(vals[frame_id])
284 return all_imgs
285
286 # Call the animator.
287 anim = animation.FuncAnimation(
288 fig, animate, frames=n_frames, interval=50, blit=True
289 )
290
291 return anim
292
293 def plot_animations(all_idxs, all_ts, duration, fig, axs, cax, ss_dur=25):
294 """Plots neuronal activity as an animation"""
295
296 ts_bins = np.arange(0, duration / ms + 1, ss_dur) * ms
297
298 field_vals, field_imgs = [], []
299 for idxs, ts, ax in zip(all_idxs, all_ts, axs.flat):
300 h = np.histogram2d(ts, idxs, bins=[ts_bins, range(GRID_SIZE**2 + 1)])[0]
301 field_val = h.reshape(-1, GRID_SIZE, GRID_SIZE) / (float(ss_dur * ms))
302 field_img = ax.imshow(field_val[0], vmin=0, vmax=64, origin="lower")
303 field_imgs.append(field_img)
304 field_vals.append(field_val)
305 ax.set(xticks=[], yticks=[])
306
307 plt.colorbar(field_img, cax=cax)
308
309 anim = animator(fig, field_imgs, field_vals)
310 return anim
311
312
313 # ---------------- MAIN ---------------- #
314 fig, axs = plt.subplots(
315 2,
316 6,
317 figsize=(15, 6),
318 layout="constrained",
319 gridspec_kw={"width_ratios": [1, 1, 1, 1, 0.1, 1]},
320 )
321 all_idxs, all_ts = [], []
322
323 for idx, lscp in enumerate(["symmetric", "random", "perlin", "homog"]):
324 print(f"Simulating {lscp} landscape.")
325
326 phis = landscape(lscp)
327 net, mon = simulate(phis)
328
329 ## Static plots
330 # In-degrees
331 syn = net["syn_II"]
332 in_deg = syn.N_incoming_post.reshape((GRID_SIZE, GRID_SIZE))
333
334 m = plot_in_deg(in_deg, axs[0, idx], axs[0, 5], lscp)
335
336 # Firing rates
337 idxs, ts = mon.it
338 all_idxs.append(idxs)
339 all_ts.append(ts)
340 plot_firing_rate_disto(idxs, ts, axs[1, 5], lscp)
341
342 # Add colorbar and legend for in-degree plots
343 plt.colorbar(m, cax=axs[0, 4])
344 axs[0, -1].legend()
345
346 # Plot animations
347 duration = net.t
348 anim = plot_animations(all_idxs, all_ts, duration, fig, axs[1, :4], axs[1, 4], ss_dur=25)
349
350 plt.show()