Skip to content

Commit 7441137

Browse files
committed
add python examples
1 parent 930ba20 commit 7441137

14 files changed

+538
-0
lines changed

python/bernoulli2D.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Mar 19 22:30:58 2018
4+
5+
@author: NICO
6+
"""
7+
8+
import numpy as np # numerical library
9+
import matplotlib.pylab as plt # plot library
10+
import matplotlib.animation as animation # animation plot
11+
12+
#%% Bernoulli2D
13+
bernoulli2D = lambda x : np.mod(2*x, 1) # bernoulli formula
14+
15+
# initial condition
16+
N = 100 # number of points
17+
x = np.linspace(0, 1, N) # x steps
18+
y = np.linspace(0, 1, N) # y steps
19+
meanx, stdx = np.mean(x), np.std(x)
20+
meany, stdy = np.mean(y), np.std(y)
21+
x, y = np.meshgrid(x, y)
22+
G = np.exp( - ( .5*(x-meanx)**2 / stdx**2 + .5*(y-meany)**2 / stdy**2 ) )
23+
24+
25+
fig = plt.figure(figsize=(8,8))
26+
time = 100 # number of iterations
27+
ims = np.empty(time - 1, dtype=np.object)
28+
ev0 = G
29+
for i in range(1, time):
30+
ev = bernoulli2D(ev0)
31+
ims[i-1] = [plt.imshow( ev, animated=True )]
32+
ev0 = ev
33+
movie = animation.ArtistAnimation(fig,
34+
ims,
35+
interval=50,
36+
blit=True,
37+
repeat_delay=100
38+
)

python/bifurcation.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Mar 19 22:30:58 2018
4+
5+
@author: NICO
6+
"""
7+
8+
import numpy as np # numerical library
9+
import matplotlib.pylab as plt # plot library
10+
11+
# logistic map
12+
logistic = lambda x, mu : 4*mu*x*(1-x)
13+
14+
# Bifurcation logistic map x_{n+1} = \mu x_n (1 - x_n)
15+
it = 100000
16+
mu = np.linspace(.5, 1, it) # coefficient values
17+
x = np.empty(it)
18+
x[0] = .5
19+
20+
for t in range(0, it-1):
21+
x[t+1] = logistic(x[t], mu[i])
22+
23+
critical_y = x[np.where(np.diff(x) > 0)[0][0]]
24+
critical_x = mu[critical_y]
25+
26+
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,8))
27+
ax.scatter(mu, x, marker=',', color='k')
28+
ax.vlines(critical_x, 0, 1, color='r', linestyle="dashed")
29+
ax.set_xlabel("$\mu$", fontsize=14)
30+
ax.set_ylabel("$x_k$", fontsize=14)
31+
ax.text(critical_y, critical_x, "$\mu = %.3f$"critical[0])
32+
ax.set_xlim(.5, 1.01)

python/bisection_root.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Mar 19 22:30:58 2018
4+
5+
@author: NICO
6+
"""
7+
8+
import numpy as np # numerical library
9+
import matplotlib.pylab as plt # plot library
10+
11+
#%% Bisection method
12+
13+
f = lambda x : x**2 - 2
14+
bisection = lambda x0, x1 : (x0, x1) if f(x0)*f(x1) < 0 else (x1, x0)
15+
16+
n = 10000
17+
toll = 1e-4
18+
x0 = 5
19+
x1 = 1
20+
x = np.linspace(start = 0, stop = 10, num = n)
21+
y = f(x)
22+
step = [x0]
23+
tst = 1
24+
while tst >= toll:
25+
c = (x0 - x1) * .5 # middle point
26+
x0, x1 = bisection(c, x0) # bisection update
27+
step.append(c) # array of steps
28+
tst = abs(step[-1] - step[-2]) # check convergence
29+
30+
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,8))
31+
ax.plot(x, y, 'b-', label="f(x)") # plot function
32+
ax.plot(step, f(np.asarray(step)), 'r--', label="bisection step") # plot steps
33+
ax.plot(step[-1], f(step[-1]), 'go') # plot root
34+
ax.set_xlabel("x", fontsize=14)
35+
ax.set_ylabel("f(x)", fontsize=14)
36+
ax.set_title("Bisection method", fontsize=14)

python/duffin_van_der_pol.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Mar 19 22:30:58 2018
4+
5+
@author: NICO
6+
"""
7+
8+
import numpy as np # numerical library
9+
import matplotlib.pylab as plt # plot library
10+
from mpl_toolkits.mplot3d import Axes3D # 3D plot
11+
12+
# Duffin-Van Der Pol oscillator
13+
dv_der_pol = lambda x, y, z, mu, f, o, dt: (dt*y, dt*(mu*1-x*x)*y - x*x*x + f*np.cos(z), z + dt*o)
14+
15+
mu = .2
16+
f = 1.
17+
omega = .94
18+
dt = 1e-3
19+
it = 10000
20+
21+
x, y, z = np.empty(it), np.empty(it), np.empty(it)
22+
x[0], y[0], z[0] = 1., 0., 1. # initial conditions
23+
time = np.arange(0, dt*it, it) # time
24+
25+
for t in range(0, it-1):
26+
x[t+1], y[t+1], z[t+1] = dv_der_pol(x[t], y[t], z[t], mu, f, o, dt)
27+
28+
fig = plt.figure(figsize=(8,8))
29+
ax = Axes3D(fig)
30+
ax.plot(x, y, np.sin(z))

python/false_nearest_neighbours.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Mar 19 22:30:58 2018
4+
5+
@author: NICO
6+
"""
7+
8+
import numpy as np
9+
import matplotlib.pylab as plt
10+
import scipy
11+
12+
dt = .01
13+
it = 10000
14+
sigma = 16.
15+
b = 4.
16+
r = 45.92
17+
x, y, z = np.empty(shape=(it)), np.empty(shape=(it)), np.empty(shape=(it))
18+
x[0], y[0], z[0] = 10, 1, 1
19+
20+
Vx = lambda x, y, sigma : sigma*(y-x)
21+
Vy = lambda x, y, z, r : -x*z + r*x - y
22+
Vz = lambda x, y, z, b : -b*z + x*y
23+
24+
for i in range(0, it-1):
25+
x[i+1] = x[i] + dt*Vx(x[i], y[i], sigma)
26+
y[i+1] = y[i] + dt*Vy(x[i], y[i], z[i], r)
27+
z[i+1] = z[i] + dt*Vz(x[i], y[i], z[i], b)
28+
29+
# False Nearest Neighbours
30+
31+
RT = 15
32+
AT = 2
33+
sigmay = np.std(x)
34+
35+
maxEmbDim = 10
36+
delay= 1
37+
rEEM = it - (maxEmbDim*delay - delay)
38+
EEM = np.concatenate([y[delay*maxEmbDim-delay:].reshape(1, len(y[delay*maxEmbDim-delay:])),
39+
[y[delay*maxEmbDim-(i+1)*delay:-i*delay] for i in range(1, maxEmbDim)]
40+
], axis=0).T
41+
Ind1 = np.empty(maxEmbDim)
42+
Ind2 = np.empty(maxEmbDim)
43+
embedm = 0 # only for plot
44+
for k in range(1, maxEmbDim+1):
45+
D = scipy.spatial.distance.squareform(scipy.spatial.distance.pdist(EEM[:, :k], "euclidean"))
46+
np.fill_diagonal(a=D, val=np.inf)
47+
l = np.argmin(D[:rEEM - maxEmbDim - k, :], axis=1)
48+
fnn1 = np.asarray([abs(y[i + maxEmbDim + k - 1]-y[li + maxEmbDim + k - 1])/D[i, li] for i,li in enumerate(l) if D[i, li] > 0 and li + maxEmbDim + k - 1 < it])
49+
fnn2 = np.asarray([abs(y[i + maxEmbDim + k - 1]-y[li + maxEmbDim + k - 1])/sigmay for i,li in enumerate(l) if D[i, li] > 0 and li + maxEmbDim + k - 1 < it])
50+
Ind1[k-1] = len(np.where(np.asarray(fnn1) > RT)[0])
51+
Ind2[k-1] = len(np.where(np.asarray(fnn2) > AT)[0])
52+
53+
if embedm == 0: # only for plot
54+
if Ind1[k-1] / len(fnn1) < .1 and Ind2[-1] / len(fnn1) < .1 and Ind1[k-1] != 0:
55+
embedm = k
56+
#break # uncomment for true algorithm
57+
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,8))
58+
ax.plot(np.arange(0, maxEmbDim), Ind1)
59+
ax.set_xlabel('Embedding dimension', fontsize=14)
60+
ax.set_ylabel('% FNN', fontsize=14)
61+
ax.set_title('Optimal Embedding Dimension with FNN', fontsize=16)
62+
ax.plot(embedm, Ind1[embedm], 'r.')
63+
plt.text(embedm, Ind1[embedm] + 100, "EmbDim = $%d$"%(embedm))

python/grassberger_procaccia.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Mar 19 22:30:58 2018
4+
5+
@author: NICO
6+
"""
7+
8+
import numpy as np
9+
import matplotlib.pylab as plt
10+
import scipy
11+
import pandas as pd
12+
import seaborn as sns
13+
14+
dt = .01
15+
it = 10000
16+
sigma = 16.
17+
b = 4.
18+
r = 45.92
19+
x, y, z = np.empty(shape=(it)), np.empty(shape=(it)), np.empty(shape=(it))
20+
x[0], y[0], z[0] = 10, 1, 1
21+
22+
Vx = lambda x, y, sigma : sigma*(y-x)
23+
Vy = lambda x, y, z, r : -x*z + r*x - y
24+
Vz = lambda x, y, z, b : -b*z + x*y
25+
26+
for i in range(0, it-1):
27+
x[i+1] = x[i] + dt*Vx(x[i], y[i], sigma)
28+
y[i+1] = y[i] + dt*Vy(x[i], y[i], z[i], r)
29+
z[i+1] = z[i] + dt*Vz(x[i], y[i], z[i], b)
30+
31+
# Grassberger Procaccia
32+
33+
omit_pts = 3
34+
ED = scipy.spatial.distance.pdist(np.concatenate([x.reshape(len(x), 1), x.reshape(len(x),1)]), "euclidean")
35+
min_eps = ED[ED!=0].min()
36+
max_eps = 2**np.ceil(np.log(ED.max())/np.log(2))
37+
eps_vec_size = int(np.floor( (np.log(max_eps/min_eps) / np.log(2)))) + 1
38+
eps_vec = max_eps*2.**(-np.arange(0, eps_vec_size))
39+
40+
Npairs = it*(it-1)*.5
41+
C_eps = np.asarray([len(ED[(ED < eps) & (ED > 0)])/Npairs for eps in eps_vec])
42+
43+
k1 = omit_pts + 1
44+
k2 = eps_vec_size - omit_pts
45+
xp = np.log(eps_vec[np.arange(k1, k2+1)]) / np.log(2)
46+
yp = np.log(C_eps[np.arange(k1, k2+1)]) / np.log(2)
47+
48+
data = pd.DataFrame(data=[xp, yp], index=["xp", "yp"]).T
49+
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,8))
50+
plot = sns.regplot(x="xp",
51+
y="yp",
52+
data=data,
53+
ax=ax).legend()

python/harmonic.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Mar 19 22:30:58 2018
4+
5+
@author: NICO
6+
"""
7+
8+
import numpy as np # numerical library
9+
import matplotlib.pylab as plt # plot library
10+
11+
# Harmonic oscillator
12+
Vx = lambda q, p : p
13+
Vy = lambda q, p : -q
14+
15+
# Integrators
16+
euler = lambda q, p, dt, k : ( q + dt*Vx(q, p), q + dt*k*Vy(q, p) )
17+
simplettic = lambda q, p, dt, k : ( q + dt+Vx(q, p + dt*k*Vy(q, p)), p + dt*k*Vy(q, p))
18+
19+
20+
k = .5
21+
it = 1000
22+
dt = .1
23+
q_eu, p_eu = np.empty(it), np.empty(it)
24+
q_eu[0], p_eu[0] = .5, 0 # initial conditions
25+
q_si, p_si = np.empty(it), np.empty(it)
26+
q_si[0], p_si[0] = .5, 0 # initial conditions
27+
28+
for t in range(0, it-1):
29+
q_eu[t+1], p_eu[t+1] = euler(q_eu[t], p_eu[t], dt, k)
30+
q_si[t+1], p_si[t+1] = rk2(q_si[t], p_si[t], dt, k)
31+
32+
time = np.arange(0, it*dt, dt)
33+
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(8,8))
34+
ax1.plot(time, q_eu, 'b-', label="q euler")
35+
ax1.plot(time, p_eu, 'r-', label="p euler")
36+
ax2.plot(q_eu, p_eu, 'b-', label="phase space")
37+
38+
ax3.plot(time, q_si, 'b-', label="q simplettic")
39+
ax3.plot(time, p_si, 'r-', label="p simplettic")
40+
ax4.plot(q_si, p_si, 'b-', label="phase space")

python/integration.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Mar 19 22:30:58 2018
4+
5+
@author: NICO
6+
"""
7+
8+
import numpy as np # numerical library
9+
10+
#%% Integration
11+
12+
f = lambda x : np.sin(x)
13+
rettangoli = lambda dx, N : sum( [dx * f(i * dx) for i in range(N)] )
14+
trapezi = lambda dx, N : sum( [dx * (f(i*dx) + f((i+1)*dx)) *.5 for i in range(N)] )
15+
simpson = lambda dx, N : sum( [dx/6*(f(i*dx) + 4*f((i*dx + (i+1)*dx)*.5) + f((i+1)*dx)) for i in range(N)] )
16+
17+
truth = 1. - np.cos(1.) # sin primitive in [0, 1]
18+
dx = 1.
19+
for n in range(1, 100):
20+
N = n*n
21+
print( N, abs(rettangoli(dx / N, N) - truth), abs(trapezi(dx / N, N) - truth), abs(simpson(dx / N, N) - truth) )
22+

python/logistic_map.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Mar 19 22:30:58 2018
4+
5+
@author: NICO
6+
"""
7+
8+
import numpy as np # numerical library
9+
import matplotlib.pylab as plt # plot library
10+
from scipy.integrate import odeint # python integrator
11+
12+
# Logistic map
13+
logistic = lambda x, t, mu : mu * (np.mod(x, 1) - np.mod(x**2, 1)) # logistic formula
14+
15+
it = 60
16+
dt = .1
17+
x0 = np.mod(.1, 1)
18+
mu = 1.3
19+
t = np.arange(0, dt*it, dt)
20+
x = np.empty(shape=(it))
21+
x[0] = x0
22+
23+
for i in range(0, it-1):
24+
x[i+1] = np.mod( np.mod(x[i], 1) + dt*logistic(x[i], t[i], mu) , 1)
25+
26+
xt = odeint(logistic, x0, t, args=(mu, ))
27+
28+
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,8))
29+
ax.scatter(t, x, marker='o', facecolors="none", edgecolor='k', s=20, label="euler")
30+
ax.plot(t, xt, 'r-', lw=2, alpha=.5, label="scipy")
31+
ax.set_ylim(0, 1)
32+
ax.legend(loc='best', fontsize=14)

python/lorentz_attractor.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Mar 19 22:30:58 2018
4+
5+
@author: NICO
6+
"""
7+
8+
import numpy as np # numerical library
9+
import matplotlib.pylab as plt # plot library
10+
from mpl_toolkits.mplot3d import Axes3D # 3D plot
11+
12+
# Lorentz attractor
13+
14+
dt = .01
15+
it = 10000
16+
sigma = 16.
17+
b = 4.
18+
r = 45.92
19+
x, y, z = np.empty(shape=(it)), np.empty(shape=(it)), np.empty(shape=(it))
20+
x[0], y[0], z[0] = 10, 1, 1 # initial conditions
21+
22+
# lorentz formula
23+
Vx = lambda x, y, sigma : sigma*(y-x)
24+
Vy = lambda x, y, z, r : -x*z + r*x - y
25+
Vz = lambda x, y, z, b : -b*z + x*y
26+
27+
# euler integration
28+
for i in range(0, it-1):
29+
x[i+1] = x[i] + dt*Vx(x[i], y[i], sigma)
30+
y[i+1] = y[i] + dt*Vy(x[i], y[i], z[i], r)
31+
z[i+1] = z[i] + dt*Vz(x[i], y[i], z[i], b)
32+
33+
fig = plt.figure(figsize=(8,8))
34+
ax = Axes3D(fig)
35+
ax.plot(x, y, z)

0 commit comments

Comments
 (0)