I'd like to calculate the mean square displacement at all times of a 1d trajectory. I'm a novice programmer, so I've attempted it from a simulated random walk.
import numpy as np
import matplotlib.pyplot as plt
# generate random walk
path = np.zeros(60)
position = 0
for i in range(1, path.size):
move = np.random.randint(0, 2)
if move == 0: position += -1
else: position += 1
path[i] = position
# returns a vector of MSDs from a given path
def calcMSD(data):
msd = np.zeros(data.size - 1)
for i in range(1, data.size):
squareddisplacements = (data[i:] - data[:data.size - i])**2
msd[i - 1] = squareddisplacements.mean()
return msd
msd = calcMSD(path)
plt.plot(msd)
plt.show()
Have I implemented this correctly? Any and all advice is appreciated, thanks.
Mean Squared Displacement
Definition of mean squared displacement
To make sure we are agreeing on the definition, the mean squared displacement (MSD) is the mean of the squared distance from origin of a collection of particles (in our case, walkers) at a specific step.
Since we are in 1D, the distance is simply the absolute position : distance at time t = | path[t] |
To get the MSD at step t, we must take all the squared positions at step t, then take the mean of the resulting array.
That means :
MSD at step t == (path[:, t]**2).mean()
(the element-wise squaring makes it useless to take the absolute values)path[:, t]
means here : the positions of each walker at step t.Generating paths
We must edit your code a bit to have several independant paths.
As a sidenote, you could also use random.choice to randomly pick -1 or 1 directly, like so:
From now, path is a 2D array : a row per walker path.
Getting MSD at each step
To get all the MSD at every steps, we vary t from 1 to the number of steps.
You can do it inside a list comprehension in Python (and getting rid of your
calcMSD
function):Result
Your function was not adapted to plot several walkers.
The proposed solution will give you something like this :
What you want
I hope I understood what you truly wanted. I don't know how it's called but it can also be calculated in a list comprehension. Considering the path for a single walker :
We go from start to start + step to get the difference between two positions that are
step
steps apart. We reproduce this operation, starting from 0 to the end of the list. Then we square the obtained list and take the mean.We do that for all step size : 1 to the whole length.
Result :