DynamicalSystemsWithApplicationsUsingPython 2ed Lynch PDF
DynamicalSystemsWithApplicationsUsingPython 2ed Lynch PDF
DynamicalSystemsWithApplicationsUsingPython 2ed Lynch PDF
@author: sladmin
"""
def fmu(mu, x):
return mu * x * (1 - x)
In [2]: fmu(3,0.2)
Out[2]: 0.4800000000000001
In [4]: F2K()
In [5]: # Define a function to list the first n terms of the Fibonacci sequence.
# Save file as fibonacci.py.
# Run the Module (or type F5).
def fibonacci(n):
a, b = 0, 1
print(a), print(b), print(a + b)
for i in range(n - 3):
a, b = b, a + b
print(a + b)
In [6]: fibonacci(10)
0
1
1
2
3
5
8
13
21
34
In [8]: sumN(100)
a = 12348
b = 14238
while b != 0:
d = a % b
a = b
b = d
def grade(score):
if score >= 70:
letter = 'A'
elif score >= 60:
letter = 'B'
elif score >= 50:
letter = 'C'
elif score >= 40:
letter = 'D'
else:
letter = 'F'
return letter
In [11]: grade(75)
Out[11]: 'A'
num_guesses = 0
name = input('Hi! What is your name? ')
number = random.randint(1, 20) # A random integer between 1 and 20.
print('Welcome, {}! I am thinking of an integer between 1 and 20.'.format(name)
)
if guess == number:
print('Well done {}! You guessed my number in {} guesses!'.format(name, num
_guesses))
else:
print('Sorry, you lose! The number I was thinking of was {}'.format(number)
)
speed(0)
if level > 0:
fd(length) # Forward.
rt(30) # Right turn 30 degrees.
FractalTreeColor(length*0.7, level-1)
lt(90) # Left turn 90 degrees.
FractalTreeColor(length*0.5, level-1)
rt(60) # Right turn 60 degrees.
penup()
bk(length) # Backward.
pendown()
In [14]: FractalTreeColor(200,10)
In [16]: KochSquare(200,4)
for i in range(3):
Sierpinski(length/2, level-1)
fd(length)
lt(120) # Left turn 120 degrees.
end_fill()
In [18]: Sierpinski(200,5)
In [19]: # Program 01a: A program that solves a simple Ordinary Differential Equation (O
DE).
# See Example 10.
Eq(x(t), C1*exp(-t) + 1)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('Voltage-time plot')
plt.grid(True)
plt.savefig("Voltage-Time Plot.png")
plt.show()
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
plt.figure(1)
plt.subplot(211) #subplot(num rows,num cols,fig num)
plt.plot(t1,f(t1),'bo',t2,f(t2),'k',label='damping')
plt.xlabel('time (s)')
plt.ylabel('amplitude (m)')
plt.title('Damped pendulum')
legend = plt.legend(loc='upper center',shadow=True)
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2),'g--',linewidth=4)
plt.xlabel('time (s)')
plt.ylabel('amplitude (m)')
plt.title('Undamped pendulum')
plt.subplots_adjust(hspace=0.8)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
alpha=0.7
phi_ext=2*np.pi*0.5
def flux_qubit_potential(phi_m,phi_p):
return 2+alpha-2*np.cos(phi_p)*np.cos(phi_m)-alpha*np.cos(phi_ext-2*phi_p)
phi_m=np.linspace(0,2*np.pi,100)
phi_p=np.linspace(0,2*np.pi,100)
X,Y=np.meshgrid(phi_p,phi_m)
Z=flux_qubit_potential(X,Y).T
fig=plt.figure(figsize=(8,6))
ax=fig.add_subplot(1,1,1,projection='3d')
p=ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)
ax.plot_surface(X,Y,Z,rstride=4,cstride=4,alpha=0.25)
cset=ax.contour(X,Y,Z,zdir='z',offset=-np.pi,cmap=plt.cm.coolwarm)
cset=ax.contour(X,Y,Z,zdir='x',offset=-np.pi,cmap=plt.cm.coolwarm)
cset=ax.contour(X,Y,Z,zdir='y',offset=3*np.pi,cmap=plt.cm.coolwarm)
ax.set_xlim3d(-np.pi, 2*np.pi);
ax.set_ylim3d(0, 3*np.pi);
ax.set_zlim3d(-np.pi, 2*np.pi);
ax.set_xlabel('$\phi_p$',fontsize=15)
ax.set_ylabel('$\phi_m$',fontsize=15)
ax.set_zlabel('Potential',fontsize=15)
plt.tick_params(labelsize=15)
ax.set_title("Surface and contour plots",fontsize=15)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig=plt.figure(figsize=(8,6))
ax=fig.add_subplot(1,1,1,projection='3d')
t = np.linspace(-10,10,1000)
x = np.sin(t)
y = np.cos(t)
z = t
ax.plot(x, y, z)
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("3D Parametric Curve")
plt.show()
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
ax = plt.axes(xlim=(0, 2),ylim=(-2, 2))
line, = ax.plot([],[],lw=2)
plt.xlabel('time')
plt.ylabel('sin($\omega$t)')
def init():
line.set_data([],[])
return line,
# Note: blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init, \
frames=100, interval=200, blit=False)
2 4 6
t 3⋅t t ⎛ 8⎞
x(t) = 1 - ── + ──── - ── + O⎝t ⎠
2 8 16
⎛ 4 2 ⎞ ⎛ 3 2 ⎞
⎜t t ⎟ ⎜ t t ⎟ ⎛ 6⎞
x(t) = C₂⋅⎜── + ── + 1⎟ + C₁⋅t⋅⎜- ── + ── + 1⎟ + O⎝t ⎠
⎝24 2 ⎠ ⎝ 12 6 ⎠
X0 = [1, 0]
t = np.linspace(0, 10, 1000)
x = sol[:, 0]
y = sol[:, 1]
fig, ax = plt.subplots()
ax.plot(t,x,label='Numerical')
ax.plot(t, 1 + t**2/2 + t**4/24,'r-', label='Truncated series')
plt.xlabel("t",fontsize=15)
plt.ylabel("x",fontsize=15)
plt.tick_params(labelsize=15)
plt.xlim(0,4)
plt.ylim(0,4)
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
plt.figure(1)
plt.xlabel('Time')
plt.ylabel('Concentrations')
plt.title('Chemical Kinetics')
plt.plot(t, x, label='|A|')
plt.plot(t, y, label='|B|')
plt.plot(t, z, label='|C|')
legend = plt.legend(loc='right center')
plt.show()
In [36]: # Program 03b: Nonlinear system, phase portrait with vector plot.
# See Figure 3.12.
In [37]: # Program 03c: Finding critical points. Check by plotting the curves of interse
ction.
# See Example 9.
import sympy as sm
x, y = sm.symbols('x, y')
P = x*(1 - x/2 - y)
Q = y*(x - 1 - y/2)
In [38]: # Program 04a: Holling-Tanner model. See Figures 4.5 and 4.6.
# Time series and phase portrait for a predator-prey system.
# An isolated periodic solution (limit cycle).
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
X, infodict = integrate.odeint(Holling_Tanner,Sys0,t,full_output=True)
x,y = X.T
fig = plt.figure(figsize=(15,5))
fig.subplots_adjust(wspace = 0.5, hspace = 0.3)
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)
ax1.plot(t,x, 'r-',label='prey')
ax1.plot(t,y, 'b-',label='predator')
ax1.set_title("Time Series")
ax1.set_xlabel("time")
ax1.grid()
ax1.legend(loc='best')
ax2.plot(x, y, color="blue")
ax2.set_xlabel("x")
ax2.set_ylabel("y")
ax2.set_title("Phase portrait")
ax2.grid()
plt.show()
eps=0.3
x0 = 2
t = np.linspace(0, 10, 1000)
plt.plot(t,x,label='x(t)')
plt.plot(t,2*np.exp(-t),label='O(1)')
plt.plot(t,2*np.exp(-t)+4*eps*(np.exp(-t)-np.exp(-2*t)),label='O($\epsilon $)')
plt.plot(t,2*np.exp(-t)+4*eps*(np.exp(-t)-np.exp(-2*t))+ \
eps**2*8*(np.exp(-t)-2*np.exp(-2*t)+np.exp(-3*t)),label='O($\epsilon^2
$)')
plt.xlabel('t', fontsize=15)
plt.ylabel('x', fontsize=15)
plt.tick_params(labelsize=15)
plt.xlim(0, 8)
plt.ylim(0, 2.1)
plt.legend()
plt.show()
In [42]: # Program 05c: Error between xN and x0. See Figure 5.9.
# Error between one term solution and numerical solution.
def dx_dt(x,t):
return [x[1], 0.01*x[0]**3 - x[0]]
x0=[1,0]
ts=np.linspace(0,100,2000)
xs=odeint(dx_dt,x0,ts)
xN=xs[:,0]
xpert0=np.cos(ts)
plt.plot(ts,xN-xpert0)
plt.xlabel('t')
plt.ylabel('$x_N-x_0$')
plt.show()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.arange(-10.0, 10.0, 0.1)
y = np.arange(-4.0, 4.0, 0.1)
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
ax.plot_surface(X, Y, Z)
ax.set_xlabel(r'$\theta$',fontsize=12)
ax.set_ylabel(r'$\phi$',fontsize=12)
ax.set_zlabel(r'$H(\theta,\phi)$',fontsize=12)
plt.tick_params(labelsize=12)
ax.view_init(30, -70)
plt.show()
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
def init():
line.set_data([],[])
return line,
bifurcation=animation.FuncAnimation(fig,animate,init_func=init,
frames=np.linspace(mu_min,mu_max,1000),interval=10,blit=False)
plt.xlabel("x",fontsize=15)
plt.ylabel("y",fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
fig=plt.figure()
myimages=[]
my_anim = animation.ArtistAnimation(fig,myimages,interval=100,blit=False,repeat
_delay=100)
plt.show()
In [ ]: # Program 07c: Animation of a Saddle Node on an Invariant Circle (SNIC) bifurca
tion.
# See Figure 7.12.
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
from scipy.integrate import odeint
fig=plt.figure()
myimages=[]
def SNIC(x, t):
return [x[0]*(1-x[0]**2-x[1]**2)-x[1]*(1+mu+x[0]),
x[1]*(1-x[0]**2-x[1]**2)+x[0]*(1+mu+x[0])]
my_anim = animation.ArtistAnimation(fig,myimages,interval=100,blit=False,repeat
_delay=100)
plt.show()
In [46]: # Program 08a: The Rossler chaotic attractor. See Fig. 8.10(a).
# In this case, iteration is used to solve the ODEs.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def Rossler(x,y,z,a=0.2,b=0.2,c=6.3):
x_dot = - y - z
y_dot = x + a*y
z_dot = b + x*z - c*z
return x_dot, y_dot, z_dot
dt = 0.01
stepCnt = 50000
xs=np.empty((stepCnt+1,))
ys=np.empty((stepCnt+1,))
zs=np.empty((stepCnt+1,))
# Iterate.
for i in range(stepCnt):
x_dot,y_dot,z_dot = Rossler(xs[i],ys[i],zs[i])
xs[i+1]=xs[i] + (x_dot*dt)
ys[i+1]=ys[i] + (y_dot*dt)
zs[i+1] =zs[i] + (z_dot*dt)
fig=plt.figure()
ax=Axes3D(fig)
plt.show()
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
ax.plot(x, y, z,'b-',lw=0.5)
ax.set_xlabel("x", fontsize=15)
ax.set_ylabel("y", fontsize=15)
ax.set_zlabel("z", fontsize=15)
plt.tick_params(labelsize=15)
ax.set_title("Lorenz Attractor", fontsize=15)
plt.show()
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def B_ZReaction(X,t,q,f,eps,delta):
x, y, z = X
dx = (q*y - x*y + x*(1 - x))/eps
dy = ( - q*y - x*y + f*z)/delta
dz = x - z
return dx, dy, dz
t = np.linspace(0, tmax, n)
f = odeint(B_ZReaction, (x0, y0, z0), t, args=((q,f,eps,delta)))
x, y, z = f.T
ax1.plot(t, x, 'b-')
ax2.plot(t, y, 'r-')
ax3.plot(t, z, 'm-')
plt.show()
mo=-1/7;m1=2/7;Tmax=100;
def Chua(x, t):
return [a*(x[1]-(m1*x[0]+(mo-m1)/2*(np.abs(x[0]+1)-np.abs(x[0]-1)))),x[0]-x
[1]+x[2],-15*x[1]]
my_anim=animation.ArtistAnimation(fig,myimages,interval=500,\
blit=False,repeat_delay=500)
plt.show()
# Phase portrait.
t=np.linspace(0,16*np.pi,10000)
xs=odeint(dx_dt,[1,0],t)
plt.plot(xs[:,0],xs[:,1], "r-")
plt.xlabel("x",fontsize=15)
plt.ylabel("y",fontsize=15)
plt.tick_params(labelsize=15)
plt.xlim(xmin,xmax)
plt.ylim(ymin,ymax);
plt.show()
r_ 0 = 1.0
r_ 1 = 0.13730247618333363
r_ 2 = 0.0737116398245952
r_ 3 = 0.050378946444256625
r_ 4 = 0.03826617811397822
r_ 5 = 0.03084905202922912
r_ 6 = 0.02584041437408372
r_ 7 = 0.022231002965186188
r_ 8 = 0.019506343238878496
import numpy as np
from scipy.integrate import odeint
from sympy import sqrt
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
t = np.linspace(0, tmax, n)
f = odeint(Hamiltonian4D, (0.5, 1.5, 0.5, 0), t)
p1, p2, q1, q2 = f.T
fig=plt.figure()
ax = Axes3D(fig)
In [51]: # Program 09c: Phase portrait and Poincare section of a nonautonomous ODE.
# See Figure 9.11(b): The Duffing equation.
# Phase portrait.
t=np.linspace(0,500,10000)
xs=odeint(dx_dt,[1,0],t)
plt.plot(xs[:,0],xs[:,1], "r-",lw=0.5)
plt.xlabel("x",fontsize=15)
plt.ylabel("y",fontsize=15)
plt.tick_params(labelsize=15)
plt.xlim(xmin,xmax)
plt.ylim(ymin,ymax);
plt.show()
fig, ax = plt.subplots(figsize=(6,6))
t=np.linspace(0,4000*(2*np.pi)/omega,16000000)
xs=odeint(dx_dt,[1,0],t)
for i in range(4000):
x.extend([xs[4000*i,0]])
y.extend([xs[4000*i,1]])
ax.scatter(x,y, color='blue',s=0.1)
plt.xlabel("x",fontsize=15)
plt.ylabel("y",fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
k = 0.3
omega = 1.25
alpha = 1
beta = -1
rs_up = []
rs_down = []
rs_up = np.array(rs_up)
rs_down = np.array(rs_down)
fig, ax = plt.subplots()
xtick_labels = np.linspace(0, interval, 5)
ax.set_xticks([x / interval * num_steps for x in xtick_labels])
ax.set_xticklabels(['{:.1f}'.format(xtick) for xtick in xtick_labels])
{V40: -a2**2/2 + b3/4, V31: -a2*b2/4 - 5*a3/8, V22: 0, V13: a2*b2/4 - 3*a3/8, V
04: 0, eta4: a2*b2/4 - 3*a3/8}
{V50: -2*a2**2*b2/3 + b4/5, V41: 2*a2**3 - a4, V32: 0, V23: 8*a2**3/3 + 2*a2*b3
/3 - 4*a4/3, V14: 0, V05: 16*a2**3/15 + 4*a2*b3/15 - 8*a4/15}
{V60: 14*a2**4/9 - 2*a2**2*b2**2/9 + a2**2*b3/18 - 10*a2*a4/9 + b5/6, V51: 8*a2
**3*b2/3 + 5*a2*b2*b3/24 - a2*b4/8 - 5*a4*b2/12 - 11*a5/16, V42: a2*(4*a2**3 +
a2*b3 - 2*a4)/6, V33: 16*a2**3*b2/9 - a2*b2*b3/9 + a2*b4/3 + 2*a4*b2/9 - 5*a5/6
, V24: a2*(-4*a2**3 - a2*b3 + 2*a4)/6, V15: -5*a2*b2*b3/24 + a2*b4/8 + 5*a4*b2/
12 - 5*a5/16, V06: a2*(-4*a2**3 - a2*b3 + 2*a4)/36, eta6: -5*a2*b2*b3/24 + a2*b
4/8 + 5*a4*b2/12 - 5*a5/16}
G=groebner([-a1,2*a2*b2-3*a3,5*b2*(2*a4-b3*a2),\
-5*b2*(92*b2**2*a4-99*b3**2*a2+1520*a2**2*a4-760*a2**3*b3-46*b2**2*b3*a2+198*b3
*a4),\
-b2*(14546*b2**4*a4+105639*a2**3*b3**2+96664*a2**3*b2**2*b3-193328*a2**2*b2**2*
a4-\
891034*a2**4*a4+445517*a2**5*b3+211632*a2*a4**2-317094*a2**2*b3*a4-44190*b2**2*
b3*a4+\
22095*b2**2*b3**2*a2-7273*b2**4*b3*a2+5319*b3**3*a2-10638*b3**2*a4)],order='lex
')
print(G)
GroebnerBasis([a1, 2*a2*b2 - 3*a3, 3*a3*b3 - 4*a4*b2], a1, a2, a3, a4, b2, b3,
domain='ZZ', order='lex')
In [ ]: # Program 10f: First homoclinic limit cycle bifurcation animation. See Figure 1
0.2.
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
from scipy.integrate import odeint
fig=plt.figure()
plt.axis([-1.5, 1.5, -1.5, 1.5])
myimages=[]
my_anim = animation.ArtistAnimation(fig,myimages,interval=100,blit=False,repeat
_delay=100)
plt.show()
In [ ]: # Program 10g: Second homoclinic limit cycle bifurcation. See Figure 10.3.
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
from scipy.integrate import odeint
fig=plt.figure()
plt.axis([-2, 0.5, -1, 1])
myimages=[]
my_anim = animation.ArtistAnimation(fig,myimages,interval=100,blit=False,repeat
_delay=100)
plt.show()
fig=plt.figure();xmin=-1.5;xmax=1.5;ymin=-5;ymax=5;
ax=plt.axes(xlim=(xmin,xmax),ylim=(ymin,ymax))
myimages=[]
my_anim = animation.ArtistAnimation(fig,myimages,interval=100,\
blit=False,repeat_delay=100)
plt.show()
def phi(i,t):
if i==0:
return 1 # Initial history x(t)=1 on [-1,0].
else:
return phi(i-1,i-1)-integrate(phi(i-1,xi-1),(xi,i-1,t))
x=[]
tmax=10;
for j in range(tmax+1):
p=phi(j,t)
x.append(p)
print('x(t)=',x)
x(t)= [1, -t + 1, t**2/2 - 2*t + 3/2, -t**3/6 + 3*t**2/2 - 4*t + 17/6, t**4/24
- 2*t**3/3 + 15*t**2/4 - 17*t/2 + 149/24, -t**5/120 + 5*t**4/24 - 2*t**3 + 109*
t**2/12 - 115*t/6 + 1769/120, t**6/720 - t**5/20 + 35*t**4/48 - 197*t**3/36 + 1
061*t**2/48 - 1085*t/24 + 26239/720, -t**7/5040 + 7*t**6/720 - t**5/5 + 107*t**
4/48 - 521*t**3/36 + 13081*t**2/240 - 13201*t/120 + 463609/5040, t**8/40320 - t
**7/630 + 7*t**6/160 - 487*t**5/720 + 3685*t**4/576 - 27227*t**3/720 + 39227*t*
*2/288 - 39371*t/144 + 3157891/13440, -t**9/362880 + t**8/4480 - t**7/126 + 701
*t**6/4320 - 1511*t**5/720 + 51193*t**4/2880 - 212753*t**3/2160 + 1156699*t**2/
3360 - 1158379*t/1680 + 43896157/72576, t**10/3628800 - t**9/36288 + 11*t**8/89
60 - 323*t**7/10080 + 1873*t**6/3456 - 89269*t**5/14400 + 279533*t**4/5760 - 77
61511*t**3/30240 + 23602499*t**2/26880 - 23615939*t/13440 + 5681592251/3628800]
import numpy as np
import matplotlib.pyplot as plt
plt.xlabel("t",fontsize=25)
plt.ylabel("x(t)",fontsize=25)
plt.tick_params(labelsize=25)
plt.show()
import pylab as pl
from pydelay import dde23
# set the history of to the constant function 0.5 (using a python lambda functi
on)
histfunc = {
'x': lambda t: 0.5
}
dde.hist_from_funcs(histfunc, 51)
pl.plot(x1, x2)
pl.xlabel('$x(t)$')
pl.ylabel('$x(t - 15)$')
pl.show()
tfinal = 10000
tau = 1000
params = {
'a' : 4.0,
'p' : 1.0,
'T' : 200.0,
'K' : 0.1,
'tau': tau,
'nu' : 10**-5,
'n0' : 10.0
}
dde.run()
t = dde.sol['t']
E = dde.sol['E']
n = dde.sol['n']
pl.xlabel('$t$')
pl.ylabel('$|E|$')
pl.xlim((0.95*tfinal, tfinal))
pl.ylim((0,3))
pl.show()
x_n= 10000*1.03**n
x(5)=£ 11592.74
X(50)= [[15696.]
[ 4604.]
[ 2249.]]
Eigenvalues= [ 1.02304502 -0.85068938 -0.17235564]
Eigenvectors= [[ 0.95064458 -0.92555739 0.18403341]
[ 0.27876913 0.32640259 -0.32032617]
[ 0.1362448 -0.19184593 0.9292593 ]]
In [64]: # Program 13d: The Leslie matrix population plot. See Example 4.
# Plot the population distribution for 0<t<50 years.
# In this case, one age class is one year.
import numpy as np
import numpy.linalg as LA
import matplotlib.pyplot as plt
t_span = 51
L=np.array([[0,3,1],[0.3,0,0],[0,0.5,0]])
X=[0]*t_span;X1=[0]*t_span;X2=[0]*t_span;X3=[0]*t_span;
X[0]=np.array([[1000],[2000],[3000]])
for i in range(t_span):
X[i] =np.array(np.dot(LA.matrix_power(L,i),X[0])).tolist()
X1[i] = X[i][0]
X2[i] = X[i][1]
X3[i] = X[i][2]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(X1,color='r',label='Age Class 1')
ax.plot(X2,color='b',label='Age Class 2')
ax.plot(X3,color='k',label='Age Class 3')
plt.xlabel("Age classes",fontsize=15)
plt.ylabel("Populations",fontsize=15)
plt.tick_params(labelsize=15)
legend = plt.legend(loc='upper center',shadow=True)
plt.show()
plt.show()
1/5
2/5
4/5
2/5
4/5
2/5
4/5
2/5
4/5
if __name__ == "__main__":
ys = []
rs = np.linspace(0, 4, 2000)
#rs = np.linspace(3.5, 4, 2000) # For Figure 14.16.
for r in rs:
x = 0.1
for i in range(500):
x = f(x, r)
for i in range(50):
x = f(x, r)
ys.append([r, x])
ys = np.array(ys)
plt.plot(ys[:,0],ys[:,1],'r.',markersize=0.05)
plt.xlabel("$\mu$",fontsize=15)
plt.ylabel("x",fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
Numpoints=16000;
result = []
lambdas = []
maps = []
xmin = 3
xmax = 4
mult=(xmax-xmin)*Numpoints
for r in muvalues:
x = 0.1
result = []
for t in range(100):
x = r * x * (1 - x)
result.append(np.log(abs(r - 2*r*x)))
lambdas.append(np.mean(result))
# Ignore first 100 iterates.
for t in range(20):
x = r * x * (1 - x)
maps.append(x)
fig = plt.figure(figsize=(8,6))
ax1 = fig.add_subplot(1,1,1)
/anaconda3/lib/python3.7/site-packages/matplotlib/cbook/__init__.py:424: Matplo
tlibDeprecationWarning:
Passing one of 'on', 'true', 'off', 'false' as a boolean is deprecated; use an
actual boolean (True/False) instead.
warn_deprecated("2.2", "Passing one of 'on', 'true', 'off', 'false' as a "
def Henon(X):
x, y = X
xn = 1 - a*x*x + y
yn = b*x
return xn,yn
X,Y=[],[]
for i in range(Num_iterations):
xn,yn=Henon(X0)
X, Y = X + [xn], Y + [yn]
X0=[xn,yn]
fig, ax = plt.subplots(figsize=(6,6))
ax.scatter(X,Y,color='blue',s=0.1)
plt.xlabel("x",fontsize=15)
plt.ylabel("y",fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
import numpy as np
a=1.2;b=0.4;x=0;y=0;
vec1=[1,0];vec2=[0,1];
for i in range(490):
xn = 1 - a*x*x + y
yn = b*x
x=xn;y=yn;
J=np.array([[-2*a*x, 1],[b, 0]])
vec1=J.dot(vec1)
vec2=J.dot(vec2)
dotprod1=np.dot(vec1,vec1)
dotprod2=np.dot(vec1,vec2)
vec2=vec2-np.multiply((dotprod2/dotprod1),vec1)
lengthv1=np.sqrt(dotprod1)
area=np.multiply(vec1[0],vec2[1])-np.multiply(vec1[1],vec2[0])
h1=np.log(lengthv1)/i
h2=np.log(area)/i-h1
print('h_1=',h1)
print('h_2=',h2)
h_1= 0.3391568093091681
h_2= -1.2565387259040743
/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:20: RuntimeWarning
: divide by zero encountered in double_scalars
/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:21: RuntimeWarning
: invalid value encountered in log
import numpy as np
import matplotlib.pyplot as plt
plt.show()
# Parameters
a =0;b=1.1; # To plot J(a,b).
k=15
Num_iterations=2**k
def Julia(X):
x, y = X
x1=x;y1=y;
u = sqrt((x1-a)**2+(y1-b)**2)/2
v=(x-a)/2
u1=sqrt(u+v)
v1=sqrt(u-v)
xn=u1;yn=v1;
if y1<b:
yn=-yn
if random.random() < 0.5:
xn=-u1
yn=-yn
return xn, yn
x1=(re(0.5+sqrt(0.25-(a+b*I)))).expand(complex=True)
y1=(im(0.5+sqrt(0.25-(a+b*I)))).expand(complex=True)
isunstable=2*abs(x1+y1*I)
print(isunstable)
X0 = [x1, y1]
X, Y = [], []
for i in range(Num_iterations):
xn, yn = Julia(X0)
X, Y = X + [xn], Y + [yn]
X0 = [xn, yn]
fig, ax = plt.subplots(figsize=(6,6))
ax.scatter(X, Y, color='blue', s=0.15)
ax.axis('off')
plt.show()
2.97195366175600
fig, ax = plt.subplots(figsize=(6,6))
ax.axis('off')
ax.imshow(Julia, interpolation='nearest', cmap=cm.hot)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
xmin=-2.5;xmax=1;ymin=-1.5;ymax=1.5;
xrange=xmax-xmin;yrange=ymax-ymin;
for i in range(Max_it):
z = z**2 + c
Div_test = z*np.conj(z) > 2**2
Div_num = Div_test & (Div_iter==Max_it)
Div_iter[Div_num] = i
z[Div_test] = 2
/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:29: DeprecationWar
ning: object of type <class 'float'> cannot be safely interpreted as an integer
.
/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:32: DeprecationWar
ning: object of type <class 'float'> cannot be safely interpreted as an integer
.
for re in range(scale):
zx=re*(xmax-xmin)/(scale-1)+xmin
for im in range(scale):
zy=im*(ymax-ymin)/(scale-1)+ymin
z=complex(zx, zy)
for i in range(niters):
try:
z -= (z**3-1)/(3*z**2)
except ZeroDivisionError:
# Divide by zero exception.
continue
if(abs(z**3-1) < epsilon):
break
# Shade colors.
color_shade = int((niters-i)*255.0/niters)
# RGB roots.
err = [ abs(z-root) for root in roots ]
distances = zip(err, range(len(colors)))
# Select color.
color = [i*color_shade for i in colors[min(distances)[1]]]
img.putpixel((re, im), tuple(color))
img.save('Newton_Fractal.png','PNG')
img.show()
import numpy as np
import matplotlib.pyplot as plt
A, B = 2.2, 0.15
x, y = np.mgrid[0:4:100j, -4:4:100j]
z1 = A + B*x*np.cos(x**2 + y**2) - B*y*np.sin(x**2 + y**2) - x
z2 = B*x*np.sin(x**2 + y**2) + B*y*np.cos(x**2 + y**2) - y
fig, ax = plt.subplots()
plt.contour(x, y, z1, levels=[0])
plt.contour(x, y, z2, levels=[0], colors='r')
ax.set_xlabel('x(t)', fontsize=15)
ax.set_ylabel('y(t)', fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
# Parameters
A, B = 10, 0.15
def ikeda(X):
x, y = X
xn = A + B*x*np.cos(x**2 + y**2) - B*y*np.sin(x**2 + y**2)
yn = B*x*np.sin(x**2 + y**2) + B*y*np.cos(x**2 + y**2)
return (xn, yn)
X0 = [A, 0]
X, Y = [], []
for i in range(10000):
xn, yn = ikeda(X0)
X, Y = X + [xn], Y + [yn]
X0 = [xn, yn]
fig, ax = plt.subplots(figsize=(6,6))
ax.scatter(X, Y, color='blue', s=0.1)
plt.xlabel('$Re(E_n)$', fontsize=15)
plt.ylabel('$Im(E_n)$', fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
# Parameters
C = 0.345913
kappa = 0.0225
Pmax = 120
phi = np.pi
half_N = 4999
N = 2*half_N + 1
N1 = 1 + half_N
esqr_up, esqr_down = [], []
E1 = E2 = 0
ns_up = np.arange(half_N)
ns_down = np.arange(N1, N)
esqr_up = np.array(esqr_up)
esqr_down=np.array(esqr_down)
fig, ax = plt.subplots()
xtick_labels = np.linspace(0, Pmax, 6)
ax.set_xticks([x / Pmax * N1 for x in xtick_labels])
ax.set_xticklabels(['{:.1f}'.format(xtick) for xtick in xtick_labels])
import numpy as np
import matplotlib.pyplot as plt
from math import floor
k=6
n_lines = 4**k
h = 3**(-k);
x = [0]*(n_lines+1)
y = [0]*(n_lines+1)
x[0], y[0] = 0, 0
segment=[0] * n_lines;
plt.axis('equal')
plt.plot(x,y)
plt.show()
iterates = 50000
x, y = [0]*iterates, [0]*iterates
x[0], y[0] = random(), random()
# The transformation T
f1 = lambda x, y: (0.0, 0.2*y)
f2 = lambda x, y: (0.85*x + 0.05*y, -0.04*x + 0.85*y + 1.6)
f3 = lambda x, y: (0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6)
f4 = lambda x, y: (-0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44)
fs = [f1, f2, f3, f4]
num_points = 60000
x, y = 0, 0
for i in range(num_points):
# Choose a random transformation
f = np.random.choice(fs, p=[0.01, 0.85, 0.07, 0.07])
x, y = f(x,y)
# Map (x,y) to pixel coordinates
# Center the image
cx, cy = int(width / 2 + x * width / 10), int(y * height / 10)
fern[cy, cx] = 1
fig, ax=plt.subplots(figsize=(6,6))
plt.imshow(fern[::-1,:], cmap=cm.Greens)
ax.axis('off')
plt.show()
In [81]: # Program 17d: Plot tau curve, D_q curve and f(alpha) curve.
# See Figure 17.16: Multifractal spectra.
import numpy as np
import matplotlib.pyplot as plt
import scipy.misc
plt.subplots_adjust(hspace=1)
plt.figure(1)
plt.subplot(3, 1, 1)
plt.plot(x, y)
plt.xlabel('$q$', fontsize=15)
plt.ylabel(r'$\tau(q)$', fontsize=15)
plt.tick_params(labelsize=15)
plt.subplot(3, 1, 3)
plt.plot(x, f)
plt.xlabel(r'$\alpha$', fontsize=15)
plt.ylabel(r'$f(\alpha)$', fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from skimage import exposure, io, img_as_uint
/anaconda3/lib/python3.7/site-packages/skimage/util/dtype.py:141: UserWarning:
Possible precision loss when converting from float64 to uint16
.format(dtypeobj_in, dtypeobj_out))
face = misc.face()
fig1 = plt.figure()
plt.imshow(face)
width, height, _ = face.shape
fig2 = plt.figure()
plt.imshow(white_pixels, cmap='gray')
print('There are {:,} white pixels'.format(int(np.sum(white_pixels))))
plt.show()
microbes_img = io.imread('Microbes.png')
fig1 = plt.figure()
plt.imshow(microbes_img,cmap='gray', interpolation='nearest')
width, height, _ = microbes_img.shape
binary = np.zeros((width, height))
fig2 = plt.figure()
plt.imshow(binary,cmap='gray')
print('There are {:,} white pixels'.format(int(np.sum(binary))))
blobs = np.where(binary>0.5, 1, 0)
labels, no_objects = ndimage.label(blobs)
props = regionprops(blobs)
print('There are {:,} clusters of cells:'.format(no_objects))
fig3 = plt.figure()
edges=feature.canny(binary,sigma=2,low_threshold=0.5)
plt.imshow(edges,cmap=plt.cm.gray)
fig4 = plt.figure()
labeled_areas = np.bincount(labels.ravel())[1:]
print(labeled_areas)
plt.hist(labeled_areas,bins=no_objects)
plt.xlabel('Area',fontsize=15)
plt.ylabel('Number of clusters',fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft
fig2 = plt.figure()
yf = fft(y)
xf = np.linspace(0, 1/(2*T), Ns//2)
plt.plot(xf, 2/Ns * np.abs(yf[0:Ns//2]))
plt.xlabel('Frequency (Hz)', fontsize=15)
plt.ylabel('$|Y(f)|$', fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
# Parameters
a, b = 1, 0.3 # To get Figures 18.6(e) and (f)
n = 50000
def map_2d(X):
x, y = X
xn = 1 - a*y**2 + b*x
yn = x
return (xn, yn)
X0 = [(1 - b) / 2, (1 - b) / 2]
X, Y = [], []
for i in range(n):
xn, yn = map_2d(X0)
X, Y = X + [xn], Y + [yn]
X0 = [xn, yn]
fig2 = plt.figure()
f = np.linspace(-1, 1, n)
power = np.abs(fft(X)**2)
power = np.log(power)
plt.plot(f, power)
plt.xlim(0, 1)
plt.xlabel('Frequency (Hz)', fontsize=15)
plt.ylabel('log(Power)', fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
import numpy as np
import skimage.io as io
import pylab
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
lena = rgb2gray(io.imread('lena.jpg'))
fig1 = plt.figure()
plt.imshow(lena, cmap='gray')
fig2 = plt.figure()
# Take the 2-dimensional DFT and centre the frequencies
ftimage = np.fft.fft2(lena)
ftimage = np.fft.fftshift(ftimage)
ftimage = np.abs(ftimage)
fftimage = np.log(ftimage)
fftimage = rgb2gray(fftimage)
pylab.imshow(fftimage, cmap='gray')
plt.show()
lena = rgb2gray(io.imread('lena.jpg'))
edge_roberts = roberts(lena)
edge_sobel = sobel(lena)
ax[0].imshow(edge_roberts, cmap=plt.cm.gray)
ax[0].set_title('Roberts Edge Detection')
ax[1].imshow(edge_sobel, cmap=plt.cm.gray)
ax[1].set_title('Sobel Edge Detection')
for a in ax:
a.axis('off')
plt.tight_layout()
plt.show()
# Parameters
mu = 4
k = 0.217
num_iterations = 60
xs, x = [], [0.6]
ns = np.arange(0, num_iterations, 2)
nsc = np.arange(num_iterations, 2*num_iterations, 2)
for n in ns:
x1 = mu*x[n] * (1 - x[n])
x.append(x1)
xs.append([n, x1])
x2 = mu*x1 * (1 - x1)
x.append(x2)
xs.append([n+1, x2])
for n in nsc:
x1 = k*mu*x[n] * (1 - x[n])
x.append(x1)
xs.append([n, x1])
x2 = mu*x1 * (1 - x1)
x.append(x2)
xs.append([n+1, x2])
xs = np.array(xs)
ns = np.arange(num_iterations)
nsc = np.arange(num_iterations, 2*num_iterations)
for n in ns:
xn = a + b*y - x**2
yn = x
x, y = xn, yn
r = np.sqrt(x**2 + y**2)
rs.append([n, r])
for n in nsc:
xn = -k1 * (x - xstar) - k2 * (y - ystar) + a + b*y - x**2
yn = x
x, y = xn, yn
r = np.sqrt(x**2 + y**2)
rs.append([n, r])
rs = np.array(rs)
fig, ax = plt.subplots(figsize=(6,6))
plt.plot(rs[:, 0], rs[:, 1])
plt.plot(rs[:, 0], rs[:, 1], 'ro')
plt.xlabel('n', fontsize=15)
plt.ylabel(r'$r_n^2$', fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
1.376306895063647 0.41076041951050035
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# Constants
sigma = 16
b = 4
r = 45.92
tmax = 100
plt.figure(1)
plt.plot(x3, y3)
plt.xlabel(r'$x_3$', fontsize=15)
plt.ylabel(r'$y_3$', fontsize=15)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# Constants
mu = 5.7
sigma = 16
b = 4
r = 45.92
g = 8 # When g=4, there is no synchronization.
tmax = 100
def rossler_lorenz_odes(X,t):
x1, x2, x3, y1, y2, y3, z1, z2, z3 = X
dx1 = -(x2 + x3)
dx2 = x1 + 0.2*x2
dx3 = 0.2 + x3 * (x1 - mu)
dy1 = sigma * (y2 - y1) - g * (y1 - x1)
dy2 = -y1 * y3 + r*y1 - y2
dy3 = y1 * y2 - b*y3
dz1 = sigma * (z2 - z1) - g * (z1 - x1)
dz2 = -z1*z3 + r*z1 - z2
dz3 = z1*z2 - b*z3
return (dx1, dx2, dx3, dy1, dy2, dy3, dz1, dz2, dz3)
plt.figure(1)
# Delete first 500 iterates.
plt.plot(y2[500:len(y2)], z2[500:len(z2)])
plt.xlabel(r'$y_2$', fontsize=15)
plt.ylabel(r'$z_2$', fontsize=15)
plt.show()
data = np.loadtxt('housing.txt')
rows, columns = data.shape
columns = 4 # Using 4 columns from data in this case
xmean = X.mean(axis=0)
xstd = X.std(axis=0)
ones = np.array([np.ones(rows)])
X = (X - xmean * ones.T) / (xstd * ones.T)
X = np.c_[np.ones(rows), X]
w = 0.1 * np.random.random(columns)
y1 = np.tanh(X.dot(w))
e1 = t - y1
mse = np.var(e1)
for m in range(num_epochs):
for n in range(rows):
yk = np.tanh(X[n, :].dot(w))
err = yk - t[n]
g = X[n, :].T * ((1 - yk**2) * err)
w = w - eta*g
k += 1
ws1.append([k, np.array(w[0]).tolist()])
ws2.append([k, np.array(w[1]).tolist()])
ws3.append([k, np.array(w[2]).tolist()])
ws4.append([k, np.array(w[3]).tolist()])
ws1 = np.array(ws1)
ws2 = np.array(ws2)
ws3 = np.array(ws3)
ws4 = np.array(ws4)
L = [0, 1, 2, 3, 4]
n = random.sample(L, len(L))
if xtest == x1:
print('Net has converged to X1')
elif xtest == x2:
print('Net has converged to X2')
elif xtest == x3:
print('Net has converged to X3')
else:
print('Iterate again: May have converged to spurious state')
# Parameters
b1, b2, w11, w21, w12, a = -2, 3, -20, -6, 6, 1
num_iterations = 10000
def neuromodule(X):
x,y=X
xn=b1+w11/(1+np.exp(-a*x))+w12/(1+np.exp(-a*y))
yn=b2+w21/(1+np.exp(-a*x))
return xn,yn
X0 = [0, 2]
X, Y = [], []
for i in range(num_iterations):
xn, yn = neuromodule(X0)
X, Y = X + [xn], Y + [yn]
X0 = [xn, yn]
# Parameters
b2, w11, w21, w12, a = 3, 7, 5, -4, 1
start, max = -5, 10
half_N = 1999
N = 2 * half_N + 1
N1 = 1 + half_N
xs_up, xs_down = [], []
x, y = -10, -3
ns_up = np.arange(half_N)
ns_down = np.arange(N1, N)
# Ramp b1 up
for n in ns_up:
b1 = start + n*max / half_N
x = b1 + w11 / (1 + np.exp(-a*x)) + w12 / (1 + np.exp(-a*y))
y = b2+w21 / (1 + np.exp(-a*x))
xn = x
xs_up.append([n, xn])
xs_up = np.array(xs_up)
# Ramp b1 down
for n in ns_down:
b1 = start + 2*max - n*max / half_N
x = b1 + w11 / (1 + np.exp(-a*x)) + w12 / (1 + np.exp(-a*y))
y = b2 + w21 / (1 + np.exp(-a*x))
xn = x
xs_down.append([N-n, xn])
xs_down = np.array(xs_down)
fig, ax = plt.subplots()
xtick_labels = np.linspace(start, max, 7)
ax.set_xticks([(-start + x) / max * N1 for x in xtick_labels])
ax.set_xticklabels(['{:.1f}'.format(xtick) for xtick in xtick_labels])
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# Constants
C_m = 1.0 # uF/cm^2
g_Na = 120.0 # mS/cm^2
g_K = 36.0
g_L = 0.3
V_Na = 50.0 # mV
V_K = -77.0
V_L = -54.402
# Input current
def Input_current(t): return 10 * (t > 100) - 10 * (t > 200) + 25 * (t > 300)
plt.subplots_adjust(hspace = 1)
plt.figure(1)
plt.subplot(5, 1, 1)
plt.title('Hodgkin-Huxley Neuron')
plt.plot(t, V, 'b')
plt.ylabel('V (mV)')
plt.subplot(5, 1, 2)
plt.plot(t m 'k')
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# Input current.
def Input_1(t):
return 1*(t>500)-1*(t>1000)+1*(t>1500)
def Input_2(t):
return 1*(t>1000)
# Constants
theta=0.1;gamma=0.1;epsilon=0.1;
Tmax=2000;
m=-100;c=60;
def FN_ODEs(X,t):
u1,v1,u2,v2,u3,v3,u4,v4=X
du1 = -u1*(u1-theta)*(u1-1)-v1+Input_1(t)
dv1 = epsilon*(u1-gamma*v1)
du2 = -u2*(u2-theta)*(u2-1)-v2+Input_2(t)
dv2 = epsilon*(u2-gamma*v2)
du3 = -u3*(u3-theta)*(u3-1)-v3+0.8/(1+np.exp(m*v1+c))+ \
0.8/(1+np.exp(m*v2+c))-1.5/(1+np.exp(m*v4+c))
dv3 = epsilon*(u3-gamma*v3)
du4 = -u4*(u4-theta)*(u4-1)-v4+0.45/(1+np.exp(m*v1+c))+ \
0.45/(1+np.exp(m*v2+c))
dv4 = epsilon*(u4-gamma*v4)
return du1,dv1,du2,dv2,du3,dv3,du4,dv4
X = odeint(FN_ODEs,[0.01,0.01,0.01,0.01,0,0,0,0],t,rtol=1e-6)
u1 = X[:,0];v1 = X[:,1];u2 = X[:,2];v2 = X[:,3]
u3 = X[:,4];v3 = X[:,5];u4 = X[:,6];v4 = X[:,7]
plt.subplots_adjust(hspace = 1)
plt.figure(1)
plt.subplot(4,1,1)
plt.title('Fitzhugh-Nagumo Half-Adder')
plt.plot(t, u1, 'b')
plt.ylim(-1, 1.5)
plt.ylabel('I$_1$')
plt.subplot(4,1,2)
plt.plot(t, u2, 'b')
plt.ylim(-1, 1.5)
plt.ylabel('I$_2$')
plt.subplot(4,1,3)
plt.plot(t, u3, 'g')
plt.ylim(0, 1)
plt.ylim(-1, 1.5)
plt.ylabel('O$_1$')
plt.subplot(4,1,4)
plt.plot(t, u4, 'g')
plt.ylim(-1, 1.5)
plt.ylabel('O$_2$')
fig = plt.figure()
bj = 1.2
tmax = 100
kappa = 1.4
plt.xlabel(r'$\sin(\phi)$', fontsize=15)
plt.ylabel(r'$\Omega$', fontsize=15)
plt.tick_params(labelsize=15)
plt.show()
fig = plt.figure()
myimages = []
bj = 1.2
tmax = 100
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# Constants
eta, L, Roff, Ron, p, T, w0 = 1.0, 1.0, 70.0, 1.0, 10.0, 20.0, 0.5