0
Hello, I am working with the following code, in which I simulate a walk Random and compare with a diffusion equation:
In short: I am simulating M Random Walkers that move in a single dimension, between -100 and +100 (-L and +L), and then plot a histogram of the "concentration" in each position after a certain number of time intervals, in addition to plotting the same concentration as predicted by the diffusion equation.
# Comparing random walks and diffusion in 1d
import numpy as np
import pylab as py
import matplotlib.pyplot as plt
M = 100000 # Nr of walkers
L = 100 # Lattice size
# Each time step, move walkers and propagate diffusion solution
p = 0.1 # Prob for motion
pinv = 1.0-p
nsteps = 2001 # Nr of time steps
# Initializing walkers
x = np.zeros(M) # Initial posicion of walkers
edges = np.array(range(-L,L+1))-0.5
xc = 0.5*(edges[:-1]+edges[1:])
# Initializing concentrations
c = np.zeros((2*L+1,2))
i0 = 0
i1 = 1
c[L] = M # c[L] corresponds to x = 0
cx = range(-L,L+1)
D = p
#%%
py.ion()
noutput = 100
for it in range(nsteps):
# First update positions of all walkers
for iw in range(M):
rnd = py.rand(1)
dx = -1*(rnd<p)+1*(rnd>pinv)
x[iw] = x[iw] + dx
# Perform explicit step for diffusion equation
for ix in range(1,len(c)-1):
# Use i0 and generate i1
c[ix,i1] = c[ix,i0] + D*(c[ix-1,i0]-2*c[ix,i0]+c[ix+1,i0])
# Flip i0 and i1
ii = i1
i1 = i0
i0 = ii
# Plot both concentrations
if (np.mod(it,noutput)==0):
Nx,e = py.histogram(x,edges)
plt.clf()
plt.plot(cx,c[:,0],'r',label='Difusão')
plt.plot(xc,Nx,'b',label='Random Walk')
plt.title('Tempo={}'.format(it))
plt.legend()
plt.xlabel('Distância percorrida')
plt.ylabel('Concentração')
plt.savefig('tempo_{}.png'.format(it),dpi=300)
plt.pause(0.001)
Now, I’m trying to create an animation that shows the trajectory of these Walkers along that range [-100,+100]. Obviously I won’t do with 100,000 Walkers like on the histogram, but anything between 10 and 100 would be good enough. But I still haven’t found a way to create this animation, I’ve tried a lot of matplotlib.Animation thing and it didn’t work.