Reputation: 287
I'm trying to basically code multiple random walks into my python code, I've been using the brownian motion scipy page as a starting point. I know I'm basically making a mistake in the updating of each random walk array in def updateData()
.
import math
import numpy as np
import matplotlib
import matplotlib.animation as animation
import pylab as plt
from matplotlib.pylab import *
from scipy.stats import norm
from mpl_toolkits.axes_grid1 import host_subplot
def brownian(x0, n, dt, delta, out=None):
x0 = np.asarray(x0)
r = norm.rvs(size=x0.shape + (n,), scale=delta*sqrt(dt))
if out is None:
out = np.empty(r.shape)
np.cumsum(r, axis=-1, out=out)
out += np.expand_dims(x0, axis=-1)
return out
x = numpy.empty((2,N+1))
x[:, 0] = 0.0
f0 = figure()
ax01 = subplot2grid((1, 1), (0, 0))
p011, = ax01.plot([],[],'b-')
p012, = ax01.plot([],[],'g-')
arr = []
def updateData(self):
global yo
global br
for i in range(0,2):
br = brownian(x[:,0], 10, 1, 0.25, out=None)
arr.append(br)
p011.set_data(arr[0])
p012.set_data(arr[1])
return p011,p012
simulation = animation.FuncAnimation(f0, updateData,
blit=False, frames=200,
interval=20000, repeat=False)
plt.show()
If I write following loop outside updateData
:
arr = []
for i in range(0,2):
br = brownian(x[:,0], 10, 1, 0.25, out=None)
arr.append(br)
, I get the correct arrays for each random walk (arr[0]
, and arr[1]
), however I am having a lot of trouble actually getting these to work in a subplot animation.
Upvotes: 0
Views: 164
Reputation: 40697
your problem is that you keep append
'ing your new random walks to the array arr
but you always plot the same results (namely arr[0]
and arr[1]
)
if you want to plot the latest results you should use:
def updateData(frame):
for i in range(0,2):
br = brownian(x[:,0], 10, 1, 0.25, out=None)
arr.append(br)
p011.set_data(arr[-2])
p012.set_data(arr[-1])
return p011,p012
EDIT: here is the full code that seem to be doing what you want
import math
import numpy as np
import matplotlib
import matplotlib.animation as animation
import pylab as plt
from matplotlib.pylab import *
from scipy.stats import norm
from mpl_toolkits.axes_grid1 import host_subplot
from JSAnimation.IPython_display import display_animation
def brownian(x0, n, dt, delta, out=None):
x0 = np.asarray(x0)
r = norm.rvs(size=x0.shape + (n,), scale=delta*sqrt(dt))
if out is None:
out = np.empty(r.shape)
np.cumsum(r, axis=-1, out=out)
out += np.expand_dims(x0, axis=-1)
return out
N=1
x = np.empty((2,N+1))
x[:, 0] = 0.0
f0 = figure()
ax01 = subplot2grid((1, 1), (0, 0))
ax01.set_xlim(-2,2)
ax01.set_ylim(-2,2)
p011, = ax01.plot([],[],'b-')
p012, = ax01.plot([],[],'g-')
arr = []
def updateData(self):
for i in range(0,2):
br = brownian(x[:,0], 100, 1, 0.25, out=None)
arr.append(br)
p011.set_data(arr[-2])
p012.set_data(arr[-1])
return p011,p012
simulation = animation.FuncAnimation(f0, updateData, blit=False, frames=200, interval=500, repeat=False)
Upvotes: 1