-
Notifications
You must be signed in to change notification settings - Fork 1
/
stability.py
355 lines (284 loc) · 9.91 KB
/
stability.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
"""
Analytically investigate stability of oscillator system.
Convert images to gif: convert -delay 100 -loop 0 *.png animation.gif
"""
import itertools
import numpy as np
from scipy.integrate import odeint
from sympy import Symbol, symbols, sin, Matrix, N, re
from sympy.utilities.lambdify import lambdify
from sympy.solvers.solvers import nsolve
import seaborn as sns
import matplotlib.pylab as plt
import matplotlib.lines as mlines
from tqdm import tqdm
from reconstruction import find_tpi_crossings
class StabilityInvestigator(object):
"""
Investigate stability of provided system configuration
"""
def __init__(self, func):
"""
Initialize system.
Arguments
func
Definition of ODE
"""
self.func = func
self.max_val = 2 * np.pi
def _get_ode_values(self, resolution):
"""
Compute ODE at mesh of given resolution.
Arguments
resolution
Resolution of plot
"""
x_dom = np.linspace(0, self.max_val, resolution)
y_dom = np.linspace(0, self.max_val, resolution)
x_mesh, y_mesh = np.meshgrid(x_dom, y_dom)
ode_x, ode_y = self.func((x_mesh, y_mesh))
return x_mesh, y_mesh, ode_x, ode_y
def _plot_vector_field(self, resolution):
"""
Plot vector field.
Arguments
resolution
Resolution of plot
"""
x_mesh, y_mesh, ode_x, ode_y = self._get_ode_values(resolution)
# scale vector field
hyp = np.hypot(ode_x, ode_y)
hyp[hyp==0] = 1.
ode_x /= hyp
ode_y /= hyp
plt.quiver(
x_mesh, y_mesh,
ode_x, ode_y,
pivot='mid', color='lightgray')
def _plot_nullclines(self, resolution):
"""
Plot nullclines.
Arguments
resolution
Resolution of plot
"""
x_mesh, y_mesh, ode_x, ode_y = self._get_ode_values(resolution)
plt.contour(
x_mesh, y_mesh, ode_x,
levels=[0], linewidths=2, colors='black')
plt.contour(
x_mesh, y_mesh, ode_y,
levels=[0], linewidths=2, colors='black',
linestyles='dashed')
lblx = mlines.Line2D(
[], [],
color='black',
marker='', markersize=15,
label=r'$\dot\varphi_0=0$')
lbly = mlines.Line2D(
[], [],
color='black', linestyle='dashed',
marker='', markersize=15,
label=r'$\dot\varphi_1=0$')
plt.legend(handles=[lblx, lbly], loc='best')
def _plot_trajectories(self, initial_conds):
"""
Plot trajectories.
Arguments
initial_conds
List of initial conditions for trajectories
"""
def fix_wrapping(series):
idx = find_tpi_crossings(series)
series[idx] = None
return series
ts = np.linspace(0, 10, 500)
lbl = r'$\varphi_i$ ODE trajectory'
for init in initial_conds:
sol = odeint(self.func, init, ts)
phi_0, phi_1 = sol.T % self.max_val
# fix wrapping
phi_0 = fix_wrapping(phi_0)
phi_1 = fix_wrapping(phi_1)
plt.plot(phi_0, phi_1, linewidth=3, label=lbl)
lbl = None
def phase_space(self, resolution=200, initial_conds=[], fname_app=None):
"""
Plot phase space of system.
Arguments
resolution
Resolution of plot
initial_conds
List of initial conditions for trajectories
"""
fig = plt.figure()
self._plot_vector_field(resolution/10)
self._plot_nullclines(resolution)
self._plot_trajectories(initial_conds)
plt.xlabel(r'$\varphi_0$')
plt.ylabel(r'$\varphi_1$')
plt.title(
'Phase plane{}'.format(
'' if fname_app is None else ' ({})'.format(fname_app)))
plt.savefig(
'images/phase_space{}.pdf'.format(
'' if fname_app is None else '_{:04}'.format(fname_app)))
plt.close()
class Functions(object):
def __init__(self, N):
self.N = N
self.O = Symbol('Ω', real=True)
self.o = Symbol('ω', real=True)
self.As = []
for i in range(self.N):
self.As.append([])
for j in range(self.N):
sym = Symbol('A{}{}'.format(i,j), real=True)
self.As[-1].append(sym)
self.As = tuple(tuple(x) for x in self.As)
self.Bs = symbols('B0:{}'.format(self.N), real=True)
self.phis = symbols('ϕ0:{}'.format(self.N), real=True)
def _gen_system(self):
syst = []
for i in range(self.N):
eq = self.O - self.o - \
sum([self.As[i][j] * sin(self.phis[i] - self.phis[j])
for j in range(self.N) if i != j]) - \
self.Bs[i] * sin(self.phis[i])
yield eq
def get_equations(self, substitutions):
# scale up if necessary
val = substitutions[self.As]
if np.isscalar(val):
substitutions[self.As] = val * np.ones((self.N,self.N))
else:
assert np.asarray(val).shape == (self.N, self.N), 'Invalid dimension of A: {}'.format(np.asarray(val).shape)
val = substitutions[self.Bs]
if np.isscalar(val):
substitutions[self.Bs] = val * np.ones(self.N)
else:
assert np.asarray(val).shape == (self.N,), 'Invalid dimension of B: {}'.format(np.asarray(val).shape)
# apply substitutions (in an ugly way)
eqs = []
for eq in self._gen_system():
for sym, val in substitutions.items():
if isinstance(sym, tuple):
for ss, vv in zip(sym, val):
if isinstance(ss, tuple):
for s, v in zip(ss, vv):
eq = eq.subs(s, v)
else:
eq = eq.subs(ss, vv)
else:
eq = eq.subs(sym, val)
eqs.append(eq)
return eqs
def get_roots(self, eqs, steps=2):
fix = lambda r: (r+2*np.pi) if r < 0 else r
domain = np.linspace(0, np.pi, steps)
space = np.meshgrid(*([domain]*self.N))
points = np.vstack(map(np.ravel, space)).T
roots = []
for init in points:
try:
res = nsolve(eqs, self.phis, init.tolist(), verify=False)
root = [round(fix(r), 5) for r in res]
if root not in roots:
roots.append(root)
except:# ZeroDivisonError:
pass
return roots
def get_jacobian(self, eqs, at=None):
jac = Matrix(eqs).jacobian(Matrix(self.phis))
if not at is None:
assert len(self.phis) == len(at)
for p, v in zip(self.phis, at):
jac = jac.subs(p, v)
return jac
def get_ode(self, eqs):
eqs = [lambdify(self.phis, e, 'numpy') for e in eqs]
def func(state, t=0):
return [e(*state) for e in eqs]
return func
def get_roots_plus(self, eqs):
roots = self.get_roots(eqs)
data = []
for root in roots:
jac = self.get_jacobian(eqs, at=root)
eigvals = Functions.get_eigenvalues(jac)
data.append((root, [re(e) for e in eigvals]))
return data
@staticmethod
def get_eigenvalues(jac):
# expect only eigenvalues of multiplicity one
assert set(jac.eigenvals().values()) == set([1]), jac.eigenvals()
return sorted([N(k) for k in jac.eigenvals().keys()])
@staticmethod
def get_stable_root(rp_data):
return [(root, eigvals) for root, eigvals in rp_data
if all([re(e) < 0 for e in eigvals])]
@staticmethod
def main(dim=2, reps=100):
def gen(o=5, B=2):
data = [[] for _ in range(dim)]
for O in tqdm(np.linspace(0, 20, reps)):
f = Functions(dim)
eqs = f.get_equations({
f.O: O, f.o: o,
f.Bs: B,
f.As: 1})
ode = f.get_ode(eqs)
roots_p = f.get_roots_plus(eqs)
stab = Functions.get_stable_root(roots_p)
if len(stab) > 0:
for i, ev in enumerate(stab[0][1]):
data[i].append((O, ev))
return data
# compute data
data = {
r'$\omega=5, B=2$': gen(o=5, B=2),
#r'$\omega=5, B=5$': gen(o=5, B=5),
#r'$\omega=15, B=2$': gen(o=15, B=2),
r'$\omega=15, B=5$': gen(o=15, B=5)
}
# plot result
plt.figure()
used_lbls = set()
colors = itertools.cycle(['blue', 'green', 'red', 'violet'])
for lbl, dat in data.items():
col = next(colors)
markers = itertools.cycle(['o', '*', 'D'])
for e_list in dat:
plt.plot(
*zip(*e_list),
marker=next(markers), linestyle='None', markersize=5,
color=col,
label=lbl if not lbl in used_lbls else None)
used_lbls.add(lbl)
plt.xlabel(r'$\Omega$')
plt.ylabel(r'$\lambda_i$')
plt.legend(loc='best')
plt.savefig('images/stability_overview.pdf')
def generate_ode(OMEGA=4, omega=3, A=1, B=2):
"""
Generate ODE system
"""
f = Functions(2)
eqs = f.get_equations({
f.O: OMEGA,
f.o: omega,
f.As: A,
f.Bs: B
})
return f.get_ode(eqs)
def main():
"""
Main interface
"""
func = generate_ode()
stabi = StabilityInvestigator(func)
stabi.phase_space()
# initial_conds=[[2,1], [2,4], [4,1]])
if __name__ == '__main__':
#main()
Functions.main()