计算二维随机游走在Python的均方位移(Computing the mean square dis

2019-10-21 04:23发布

我模拟二维随机游走,与方向0 <θ<2π和T = 1000步。 我已经有这模拟的是单走,重复它的12倍,并节省了每次运行到顺序命名文本文件的代码:

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的阵列,例如:

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

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

有没有一种更有效的方式去与我有什么发现的MSD?

Answer 1:

这里是一个快速snipet计算均方位移(MSD)。 当路径是由点的时间等距,因为它似乎是你的randwalk的情况。 你只需将在12散步循环,计算它的每个A [1 ,:]

#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


Answer 2:

首先,你实际上并不需要存储整个1000步走,只是最终位置。

此外,没有任何理由将它们存储出去TEXTFILES并加载它们回来了,你可以用它们在内存中,只是把它们在阵列的列表,或在1个以上尺寸的数组。 即使你需要将它们写出来,你可以做到这一点,以及 到位的保持,而不是最终值。 (另外,如果你没有实际使用numpy性能或建立二维数组简单,你可能要考虑反复构建它,例如,使用csv模块,而是一个人的更多的是主观判断的。)

无论如何,鉴于你12个的最终位置,你只是计算每一个的距离(0, 0)则方,通过12(或者,由于明显的方式来计算从距离和他们,和鸿沟(0, 0)是刚添加的平方xy位置,然后平方根的结果,只是跳过在端部的平方根和正方形)。

但是如果你给每个整个步行存储到某种原因一个文件,然后你在加载他们回来后, walk[-1]给你的最终位置为2倍的值的一维数组。 所以,你可以阅读这些12点最终位置为12X2阵列和矢量化均方距离,或者只是蓄积在列表和做手工。

虽然我们是在它的rd.seed()是没有必要的; 一个PRNG的整点是,你继续得到不同的数字,除非你明确的种子重置为初始值赘述。

这里是下降的两个额外的复杂性,直接做的一切的例子:

destinations = np.zeros((12, 2), dtype=np.float)
for j in range(12):
    x, y = 0., 0.
    for i in range(1000):
        x, y = randwalk(x, y)
    destinations[j] = x, y

square_distances = destinations[:,0] ** 2 + destinations[:,1] ** 2
mean_square_distance = np.mean(square_distances)


文章来源: Computing the mean square displacement of a 2d random walk in Python