I use TrackMate in order to get the trajectories of particles, then it generates a csv file that contains positions in X, in Y and the corresponding times for each particle. I tried calculating MSD using different approaches but the result seems odd to me every time. It should have a brownian motion so my results are not consistent. I expect to have an increasing curve overtime and that is not the case.
Here is the function I try to use:
def Mean3(filename, ax=None):
# Step 1: Read CSV file
df = pd.read_csv(filename, low_memory=False)
# Step 2: Drop useless lines and columns
df = df.drop(labels="LABEL", axis=1)
df = df.drop(index=range(3), axis=0)
df = df.astype(float) #By default, str is the type
# Step 3: Sort data
df = df.sort_values(by=['TRACK_ID', 'POSITION_T'])
# Step 4: Calculate the differences of position by time
df['DX'] = df.groupby('TRACK_ID')['POSITION_X'].diff()
df['DY'] = df.groupby('TRACK_ID')['POSITION_Y'].diff()
# Step 5: Calculate MSD for each particle
df['MSD'] = df['DX'] ** 2 + df['DY'] ** 2
# Step 6: Calculate MSD mean for each time using all trajectories
msd_mean = df.groupby('POSITION_T')['MSD'].mean()
msd_mean_all = df.groupby('POSITION_T')['MSD'].mean()
# Step 7: Check if the curve is increasing according to brownian motion
if not np.all(np.diff(msd_mean.values) >= 0):
print('La courbe MSD n\'est pas croissante conformément à un mouvement brownien !')
# Step 8: Plot MSD global
plt.plot(msd_mean_all.index, msd_mean_all.values, label="All trajectories")
# Step 9: Calculate MSD for each trajectory
msd_mean_traj = df.groupby(['TRACK_ID', 'POSITION_T'])['MSD'].mean().reset_index()
# Step 10: Plot MSD for each trajectory
for traj_id in msd_mean_traj['TRACK_ID'].unique():
traj_data = msd_mean_traj[msd_mean_traj['TRACK_ID'] == traj_id]
plt.plot(traj_data['POSITION_T'], traj_data['MSD'])
plt.xlabel('Time T')
plt.ylabel('Mean Square Displacement (MSD)')
plt.legend()
plt.show()