Debian Codegraph @

examples/coupled_oscillators.py

raw
1 """
2 Coupled oscillators, following the Kuramoto model. The current state of an oscillator
3 is given by its phase :math:`\Theta`, which follows
4
5 .. math::
6
7 \frac{d\Theta_i}{dt} = \omega_i + \frac{K}{N}\sum_j sin(\Theta_j - \Theta_i)
8
9 where :math:`\omega_i` is the intrinsic frequency of each oscillator, :math:`K` is
10 the coupling strength, and the sum is over all oscillators (all-to-all coupling).
11
12 The plots show a dot on the unit circle denoting the phase of each neuron (with the
13 color representing the initial phase at the start of the simulation). The black dot and
14 line show the average phase (dot) and the phase coherence (length of the line). The
15 simulations are run four times with different coupling strengths :math:`K`, each
16 simulation starting from the same initial phase distribution.
17
18 https://en.wikipedia.org/wiki/Kuramoto_model
19 """
20 import matplotlib.animation as animation
21
22 from brian2 import *
23 from brian2.core.functions import timestep
24
25 ### global parameters
26 N = 100
27 defaultclock.dt = 1*ms
28
29
30 ### simulation code
31 def run_sim(K, random_seed=214040893):
32 seed(random_seed)
33
34 eqs = '''
35 dTheta/dt = omega + K/N*coupling : radian
36 omega : radian/second (constant) # intrinsic frequency
37 coupling : 1
38 '''
39
40 oscillators = NeuronGroup(N, eqs, method='euler')
41 oscillators.Theta = 'rand()*2*pi' # random initial phase
42 oscillators.omega = 'clip(0.5 + randn()*0.5, 0, inf)*radian/second' # 𝒩(0.5, 0.5)
43
44 connections = Synapses(oscillators, oscillators,
45 'coupling_post = sin(Theta_pre - Theta_post) : 1 (summed)')
46 connections.connect() # all-to-all
47
48 mon = StateMonitor(oscillators, 'Theta', record=True)
49 run(10*second)
50 return mon.Theta[:]
51
52 ### Create animated plots
53 frame_delay = 40*ms
54
55 # Helper functions
56 def to_x_y(phases):
57 return np.cos(phases), np.sin(phases)
58
59 def calc_coherence_and_phase(x, y):
60 phi = np.arctan2(np.sum(y), np.sum(x))
61 r = np.sqrt(np.sum(x)**2 + np.sum(y)**2)/N
62 return r, phi
63
64 # Plot an animation with the phase of each oscillator and the average phase
65 def do_animation(fig, axes, K_values, theta_values):
66 '''
67 Makes animated subplots in the given ``axes``, where each ``theta_values`` entry
68 is the full recording of ``Theta`` from the monitor.
69 '''
70 artists = []
71 for ax, K, Theta in zip(axes, K_values, theta_values):
72 x, y = to_x_y(Theta.T[0])
73 dots = ax.scatter(x, y, c=Theta.T[0])
74 r, phi = calc_coherence_and_phase(x, y)
75 arrow = ax.arrow(0, 0, r*np.cos(phi), r*np.sin(phi), color='black')
76 mean_dot, = ax.plot(r*np.cos(phi), r*np.sin(phi), 'o', color='black')
77 if abs(K) > 0:
78 title = f"coupling strength K={K:.1f}"
79 else:
80 title = "uncoupled"
81 ax.text(-1., 1.05, title, color='gray', va='bottom')
82 ax.set_aspect('equal')
83 ax.set_axis_off()
84 ax.set(xlim=(-1.2, 1.2), ylim=(-1.2, 1.2))
85 artists.append((dots, arrow, mean_dot))
86
87
88 def update(frame_number):
89 updated_artists = []
90 for (dots, arrow, mean_dot), K, Theta in zip(artists, K_values, theta_values):
91 t = frame_delay*frame_number
92 ts = timestep(t, defaultclock.dt)
93 x, y = to_x_y(Theta.T[ts])
94 dots.set_offsets(np.vstack([x, y]).T)
95 r, phi = calc_coherence_and_phase(x, y)
96 arrow.set_data(dx=r*np.cos(phi), dy=r*np.sin(phi))
97 mean_dot.set_data(r*np.cos(phi), r*np.sin(phi))
98 updated_artists.extend([dots, arrow, mean_dot])
99 return updated_artists
100
101 ani = animation.FuncAnimation(fig, update, frames=int(magic_network.t/frame_delay),
102 interval=20, blit=True)
103
104 return ani
105
106 if __name__ == '__main__':
107 fig, axs = plt.subplots(2, 2)
108 # Manual adjustments instead of layout='tight', to avoid jumps in saved animation
109 fig.subplots_adjust(left=0.025, bottom=0.025, right=0.975, top=0.975,
110 wspace=0, hspace=0)
111 K_values = [0, 1, 2, 4]
112 theta_values = []
113 for K in K_values:
114 print(f"Running simulation for K={K:.1f}")
115 theta_values.append( run_sim(K/second))
116 ani = do_animation(fig, axs.flat, K_values, theta_values)
117
118 plt.show()