计算二维随机游走在Python的均方位移 [英] Computing the mean square displacement of a 2d random walk in Python

查看:2333
本文介绍了计算二维随机游走在Python的均方位移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模拟的二维随机游走,用方向0℃; θ< 2π和T = 1000步。我已经有一个code这模拟的是单走,重复它的12倍,并节省每碰到顺序命名的文本文件:

I'm simulating a 2-dimensional random walk, with direction 0 < θ < 2π and T=1000 steps. I already have a code which simulates a single walk, repeats it 12 times, and saves each run into sequentially named text files:

a=np.zeros((1000,2), dtype=np.float)
print a                                   # Prints array with zeros as entries

# Single random walk
def randwalk(x,y):              # Defines the randwalk function
    theta=2*math.pi*rd.rand() 
    x+=math.cos(theta);
    y+=math.sin(theta);
    return (x,y)                # Function returns new (x,y) coordinates

x, y = 0., 0.                   # Starting point is the origin
for i in range(1000):           # Walk contains 1000 steps
    x, y = randwalk(x,y)
    a[i,:] = x, y               # Replaces entries of a with (x,y) coordinates

# Repeating random walk 12 times
fn_base = "random_walk_%i.txt"      # Saves each run to sequentially named .txt
for j in range(12):
    rd.seed()                       # Uses different random seed for every run
    x, y = 0., 0.
    for i in range(1000):
        x, y = randwalk(x,y)
        a[i,:] = x, y
    fn = fn_base % j                # Allocates fn to the numbered file
    np.savetxt(fn, a)               # Saves run data to appropriate text file

现在我想对所有12个阶层来计算均方位移。要做到这一点,我最初的想法是从每一个文本文件中的数据导入回到一个numpy的数组,例如:

Now I want to calculate the mean square displacement over all 12 walks. To do this, my initial thought was to import the data from each text file back into a numpy array, eg:

infile="random_walk_0.txt"
rw0dat=np.genfromtxt(infile)
print rw0dat

和然后以某种方式操纵阵列发现的均方位移。

And then somehow manipulate the arrays to find the mean square displacement.

有没有更有效的方法去与我有什么发现的MSD?

Is there a more efficient way to go about finding the MSD with what I have?

推荐答案

下面是一个快速snipet计算均方位移(MSD)。
其中,路径是由在时间上等距隔开的点,因为它似乎是这种情况
您randwalk。您可以只需将在12散步的循环,计算它为每个[我,:]

Here is a quick snipet to compute the mean square displacement (MSD). Where path is made of points equally spaced in time, as it seems to be the case for your randwalk. You can just place in the 12-walk for loop and compute it for each a[i,:]

#input path =[ [x1,y1], ... ,[xn,yn] ].

def compute_MSD(path):
   totalsize=len(path)
   msd=[]
   for i in range(totalsize-1):
       j=i+1
       msd.append(np.sum((path[0:-j]-path[j::])**2)/float(totalsize-j))

   msd=np.array(msd)
   return msd

这篇关于计算二维随机游走在Python的均方位移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆