Simple 1D random walk animation in Python
Date: 2017-05-01This is a demo I created as part of teaching Physics 105 (Scientific Computation) at the University of Arizona in the Spring of 2017.
"""
A 1D randomwalk program - A. Pyarelal
Usage:
python 1d_randomwalk.py -h : Display help and options
python 1d_randomwalk.py --animate : Run animation and make histogram
python 1d_randomwalk.py : Make histogram without animation
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import argparse
import time
from tqdm import tqdm
# Set the number of walkers and number of steps
= 5
nwalkers = 200
nsteps
"""
The subplots function in the pyplot module returns a figure and a set of axes.
Both the figure and the axes are 'objects' - that is, they are data structures
that have functions associated with them. We will return to this when we
encounter object-oriented programming.
"""
= plt.subplots()
fig, axes
# Set the x and y limits of the plot
-20,20)
axes.set_ylim(0,nsteps)
axes.set_xlim(
"""
The line below is an instance of a 'list comprehension', which is a nice
feature in Python. axes.plot(0,0) creates a Line2D object (a collection of
points joined by a line) with a single point, (0,0). The [0] returns the Line2D
object for us to use. Thus, the variable lines below is a list of Line2D objects.
"""
= [axes.plot(0,0)[0] for i in range(nwalkers)]
lines
def update_lines(step_number):
""" For each Line2D object in lines, add an (x,y) coordinate."""
for line in lines:
# append the new x-coordinate (always 1 for the 1D random walk)
line.set_xdata(np.append(line.get_xdata(),[step_number]))= line.get_ydata()[-1] # Get the last y-coordinate
y
if np.random.rand() < 0.5: # Get a random number and test it
# line.get_ydata()[-1] +=1
+1]))
line.set_ydata(np.append(line.get_ydata(),[yelse:
# line.get_ydata()[-1] -=1
-1]))
line.set_ydata(np.append(line.get_ydata(),[y
# Using the argparse module to handle command line options
# Create an instance of the ArgumentParser class
= argparse.ArgumentParser()
parser
# Add an argument called 'animation'
"--animate", help = "Show the 1D randomwalk animation",
parser.add_argument(= "store_true")
action
# Call the parse_args() method and store the arguments as an object called args
= parser.parse_args()
args
def show_animation():
""" Function to perform the animation """
= animation.FuncAnimation(fig, update_lines, nsteps,
ani =1,repeat = False)
interval
plt.show()
def show_histogram():
""" Function to show the histogram """
= plt.figure()
histogram_figure = [line.get_ydata()[-1] for line in lines]
final_y_coordinates
plt.hist(final_y_coordinates)
plt.show()
if __name__ == '__main__':
if args.animate:
= animation.FuncAnimation(fig, update_lines, nsteps,
ani =1,repeat = False)
interval'1D_randomwalk.mp4', writer='ffmpeg', dpi = 150, fps = 2)
ani.save(else:
for i in range(nsteps): update_lines(i)
You can check out an animation of the random walk below: