【发布时间】:2016-01-04 10:49:40
【问题描述】:
这是对社区的一次呼吁,看看是否有人有提高此 MSD 计算实施速度的想法。它主要基于这篇博文中的实现:http://damcb.com/mean-square-disp.html
目前,对于 5000 个点的 2D 轨迹,当前实现大约需要 9 秒。如果你需要计算很多轨迹,这真的太多了......
我没有尝试并行化它(使用multiprocess 或joblib),但我觉得创建新进程对于这种算法来说太繁重了。
代码如下:
import os
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Parameters
N = 5000
max_time = 100
dt = max_time / N
# Generate 2D brownian motion
t = np.linspace(0, max_time, N)
xy = np.cumsum(np.random.choice([-1, 0, 1], size=(N, 2)), axis=0)
traj = pd.DataFrame({'t': t, 'x': xy[:,0], 'y': xy[:,1]})
print(traj.head())
# Draw motion
ax = traj.plot(x='x', y='y', alpha=0.6, legend=False)
# Set limits
ax.set_xlim(traj['x'].min(), traj['x'].max())
ax.set_ylim(traj['y'].min(), traj['y'].max())
然后输出:
t x y
0 0.000000 -1 -1
1 0.020004 -1 0
2 0.040008 -1 -1
3 0.060012 -2 -2
4 0.080016 -2 -2
def compute_msd(trajectory, t_step, coords=['x', 'y']):
tau = trajectory['t'].copy()
shifts = np.floor(tau / t_step).astype(np.int)
msds = np.zeros(shifts.size)
msds_std = np.zeros(shifts.size)
for i, shift in enumerate(shifts):
diffs = trajectory[coords] - trajectory[coords].shift(-shift)
sqdist = np.square(diffs).sum(axis=1)
msds[i] = sqdist.mean()
msds_std[i] = sqdist.std()
msds = pd.DataFrame({'msds': msds, 'tau': tau, 'msds_std': msds_std})
return msds
# Compute MSD
msd = compute_msd(traj, t_step=dt, coords=['x', 'y'])
print(msd.head())
# Plot MSD
ax = msd.plot(x="tau", y="msds", logx=True, logy=True, legend=False)
ax.fill_between(msd['tau'], msd['msds'] - msd['msds_std'], msd['msds'] + msd['msds_std'], alpha=0.2)
然后输出:
msds msds_std tau
0 0.000000 0.000000 0.000000
1 1.316463 0.668169 0.020004
2 2.607243 2.078604 0.040008
3 3.891935 3.368651 0.060012
4 5.200761 4.685497 0.080016
还有一些分析:
%timeit msd = compute_msd(traj, t_step=dt, coords=['x', 'y'])
给这个:
1 loops, best of 3: 8.53 s per loop
有什么想法吗?
【问题讨论】:
-
因为你已经有了工作代码,这可能是 codereview 的一个很好的候选者。
-
哦,我不知道 codereview。版主可以确认一下,我会将其移至 codereview 吗?
-
我是 Code Review 的版主,我已将此问题标记为迁移到 Code Review。我们所能做的就是等着看 Stack Overflow 版主是否同意这一点。
-
我得到一个 NA 并且
compute_msd第二行中的floor函数在尝试转换为int时抛出异常。 (numpy 1.9.2、Py2.7.10、OSX)还有其他人吗? -
在 Ubuntu 上使用 numpy 1.9.3、pandas 0.16.2 和 python 3.4 对我有用...
标签: python-3.x numpy pandas physics