Simulate Random Walks With Python | Towards Data Science

What is a random walk?
Simply put, a random walk is the process of taking successive steps in a “randomized” fashion w.r.t. the current state. Additional conditions can be then applied to this base description to create a random walk for your specific use case. Brownian motion of particles, stock ticker movement, living cell movement in a substrate are just some of the better known random walks seen in real world.
Here, we simulate a simplified random walk in 1-D, 2-D and 3-D starting at origin and a discrete step size chosen from [-1, 0, 1] with equal probability. Starting points are denoted by + and stop points are denoted by o.
For different applications, these conditions change as needed e.g. the walk starts at a chosen stock price, an initial cell position detected using microscopy etc and step choices are usually probabilistic and depend on additional information from past data, projection assumptions, hypothesis being tested etc.
Setup your Jupyter notebook :
%pylab inlinefrom itertools import cyclefrom mpl_toolkits.mplot3d import Axes3Dcolors = cycle(‘bgrcmykbgrcmykbgrcmykbgrcmyk’)
Random walk in 1-D :
We start at origin ( y=0 ) and choose a step to move for each successive step with equal probability. Starting point is shown in red and end point is shown in black. A cumulative sum is plotted in the plot below which shows path followed by a body in 1D over 10k steps.
# Define parameters for the walkdims = 1step_n = 10000step_set = [-1, 0, 1]origin = np.zeros((1,dims))# Simulate steps in 1Dstep_shape = (step_n,dims)steps = np.random.choice(a=step_set, size=step_shape)path = np.concatenate([origin, steps]).cumsum(0)start = path[:1]stop = path[-1:]# Plot the pathfig = plt.figure(figsize=(8,4),dpi=200)ax = fig.add_subplot(111)ax.scatter(np.arange(step_n+1), path, c=’blue’,alpha=0.25,s=0.05);ax.plot(path,c=’blue’,alpha=0.5,lw=0.5,ls=’ — ‘,);ax.plot(0, start, c=’red’, marker=’+’)ax.plot(step_n, stop, c=’black’, marker=’o’)plt.title(‘1D Random Walk’)plt.tight_layout(pad=0)plt.savefig(‘plots/random_walk_1d.png’,dpi=250);
Random walk in 2-D :
We start at origin (x=0,y=0) and take random steps in each direction giving us 9 possible directions for movement at each step (∆x, ∆y ) ⋲ {-1, 0, 1} :
(-1,-1), (-1,0), (-1,1),(0,-1), (0,0), (0,1),(1,-1), (1,0), (1,1)
A simulation over 10k steps gives us the following path. A particle moving on the surface of a fluid exhibits 2D random walk and shows a trajectory like below.
# Define parameters for the walkdims = 2step_n = 10000step_set = [-1, 0, 1]origin = np.zeros((1,dims))# Simulate steps in 2Dstep_shape = (step_n,dims)steps = np.random.choice(a=step_set, size=step_shape)path = np.concatenate([origin, steps]).cumsum(0)start = path[:1]stop = path[-1:]# Plot the pathfig = plt.figure(figsize=(8,8),dpi=200)ax = fig.add_subplot(111)ax.scatter(path[:,0], path[:,1],c=’blue’,alpha=0.25,s=0.05);ax.plot(path[:,0], path[:,1],c=’blue’,alpha=0.5,lw=0.25,ls=’ — ‘);ax.plot(start[:,0], start[:,1],c=’red’, marker=’+’)ax.plot(stop[:,0], stop[:,1],c=’black’, marker=’o’)plt.title(‘2D Random Walk’)plt.tight_layout(pad=0)plt.savefig(‘plots/random_walk_2d.png’,dpi=250);
Simulate k Random Walks in 2D :
Random Walk in 3-D :
A body moving in a volume is an example of random walk in 3D space. We start at origin (x=0,y=0,z=0) and take steps in arandom fashion chosen from a set of 27 directions (∆x, ∆y, ∆z)⋲ {-1, 0, 1} :
# Define parameters for the walkdims = 3step_n = 1000step_set = [-1, 0, 1]origin = np.zeros((1,dims))# Simulate steps in 3Dstep_shape = (step_n,dims)steps = np.random.choice(a=step_set, size=step_shape)path = np.concatenate([origin, steps]).cumsum(0)start = path[:1]stop = path[-1:]# Plot the pathfig = plt.figure(figsize=(10,10),dpi=200)ax = fig.add_subplot(111, projection=’3d’)ax.grid(False)ax.xaxis.pane.fill = ax.yaxis.pane.fill = ax.zaxis.pane.fill = Falseax.set_xlabel(‘X’)ax.set_ylabel(‘Y’)ax.set_zlabel(‘Z’)ax.scatter3D(path[:,0], path[:,1], path[:,2],              c=’blue’, alpha=0.25,s=1)ax.plot3D(path[:,0], path[:,1], path[:,2],           c=’blue’, alpha=0.5, lw=0.5)ax.plot3D(start[:,0], start[:,1], start[:,2],           c=’red’, marker=’+’)ax.plot3D(stop[:,0], stop[:,1], stop[:,2],           c=’black’, marker=’o’)plt.title(‘3D Random Walk’)plt.savefig(‘plots/random_walk_3d.png’,dpi=250);
Simulate k Random Walks in 3D :
Now we simulate multiple random walks in 3D. Each random walk represents motion of a point source starting out at the same time with starting point set at points chosen from (x, y, z) ⋲ [-10, 10].
A few cells/particles moving without any sustained directional force would show a trajectory like this. An interesting aspect of 3 dimensional random walk is that even though the starting points are close together, as time progresses, the objects spread out.
# Define parameters for the walkdims = 3n_runs = 10step_n = 1000step_set = [-1, 0 ,1]runs = np.arange(n_runs)step_shape = (step_n,dims)# Plotfig = plt.figure(figsize=(10,10),dpi=250)ax = fig.add_subplot(111, projection=’3d’)ax.grid(False)ax.xaxis.pane.fill = ax.yaxis.pane.fill = ax.zaxis.pane.fill = Falseax.set_xlabel(‘X’)ax.set_ylabel(‘Y’)ax.set_zlabel(‘Z’) for i, col in zip(runs, colors):    # Simulate steps in 3D    origin = np.random.randint(low=-10,high=10,size=(1,dims))    steps = np.random.choice(a=step_set, size=step_shape)    path = np.concatenate([origin, steps]).cumsum(0)    start = path[:1]    stop = path[-1:]    # Plot the path    ax.scatter3D(path[:,0], path[:,1], path[:,2],                 c=col,alpha=0.15,s=1);    ax.plot3D(path[:,0], path[:,1], path[:,2],               c=col, alpha=0.25,lw=0.25)    ax.plot3D(start[:,0], start[:,1], start[:,2],              c=col, marker=’+’)    ax.plot3D(stop[:,0], stop[:,1], stop[:,2],              c=col, marker=’o’);plt.title(‘3D Random Walk - Multiple runs’)plt.savefig(‘plots/random_walk_3d_multiple_runs.png’,dpi=250);
In this post, we discussed how to simulate a barebones random walk in 1D, 2D and 3D. There are different measures that we can use to do a descriptive analysis (distance, displacement, speed, velocity, angle distribution, indicator counts, confinement ratios etc) for random walks exhibited by a population. We can also simulate and discuss directed/biased random walks where the direction of next step depends on current position either due to some form of existing gradient or a directional force.