In [26]:
# Question 2: Changing "sinwave.py" so that it plots a moving, pulsating blob
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
fig = plt.figure()
ax = plt.axes(xlim=(-2, 12), ylim=(0, 1))  ### changed this line
line, = ax.plot([], [], lw=2)
def init():  # Initialize with a blank plot
line.set_data([], [])
return line,
def animate(i):  # Plot a moving sine wave
x = np.linspace(-2, 12, 1000)           ### changed these lines
x0 = 5*(1 + np.sin(0.01*i))             ###
x1 = 0.05*i                             ###
y = np.exp(-(x-x0)**2/(1.5+np.cos(x1))) ###
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=1000, interval=20, blit=False)
# Changed the number of frames from 200 to 1000 for a longer animation
# On my Mac, I had to set blit=False. On the Managed Desktops you can set blit=True.
plt.show()

In [27]:
# Question 3: Animating the predator-prey system
from scipy.integrate import odeint

f, g, h = 8/3, 3/50, 3/20
# predator-prey equations
def dX_dt(X, t):
x, y = X
dxdt = x*(1-g*x) - x*y/(1+h*x)
dydt = -f*y + x*y/(1+h*x)
return [dxdt, dydt]

def random_ic():  # generate initial condition
return (5/2*(0.5+np.random.rand(2)))

npts = 500; tmax = 100.0
ts = np.linspace(0.0, tmax, npts)
nlines = 20
linedata = []
for ic in [random_ic() for i in range(nlines)]:
linedata.append( odeint(dX_dt, ic, ts) )

fig = plt.figure()
ax = plt.axes(xlim=(0,12), ylim=(0, 4))
line, = ax.plot([], [], 'ro')
npts = len(linedata[0][:,0])
def init():
line.set_data([],[])
return line,
def animate(i):
line.set_data([l[i,0] for l in linedata], [l[i,1] for l in linedata])
return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=npts, interval=50, blit=False)
plt.show()

In [25]:
# Question 4: Building up the set of points in the complex plane which map onto
# 0 under the iterative map  z -> z - f(z)/f'(z),  with f(z) = z^3 - 1.

# First, generate the data.
n = 9;
l = [np.zeros(1)]
for k in range(n):
myroots = np.zeros(3**(k+1),dtype=np.complex)
for j in range(len(l[k])):
w = l[k][j]
t0 = np.roots([2, -3*w, 0, 1])
myroots[3*j:3*(j+1)] = t0
l.append(myroots)

def topoints(l, k):
arr = np.array([item for sublist in l[:k] for item in sublist])
return (arr.real, arr.imag)

# For a static plot, uncomment these lines
#pts = topoints(l,n)
#plt.plot(pts[0], pts[1], 'r.')
#plt.xlim([-5,5]); plt.ylim([-5,5])
#plt.show()

# Next, create the animation.
fig = plt.figure()
ax = plt.axes(xlim=(-5, 5), ylim=(-5, 5))
line, = ax.plot([], [], 'b.', lw=0.2)
def init():  # Initialize with just one point
line.set_data([0], [0])
return line,
def animate(i):
x, y = topoints(l, i)
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=n, interval=1000, blit=False)
# I set the time between frames to 1 second (1000 milliseconds)
plt.show()

In [ ]: