优化Python距离计算,同时考虑周期性边界条件

时间:2012-06-19 20:27:13

标签: python optimization list-comprehension

我编写了一个Python脚本来计算3D空间中两点之间的距离,同时考虑周期性边界条件。问题是我需要对很多很多点进行计算,计算速度很慢。这是我的功能。

def PBCdist(coord1,coord2,UC):
    dx = coord1[0] - coord2[0]
    if (abs(dx) > UC[0]*0.5):
       dx = UC[0] - dx
    dy = coord1[1] - coord2[1]
    if (abs(dy) > UC[1]*0.5):
       dy = UC[1] - dy
    dz = coord1[2] - coord2[2]
    if (abs(dz) > UC[2]*0.5):
       dz = UC[2] - dz
    dist = np.sqrt(dx**2 + dy**2 + dz**2)
    return dist

然后我将该函数调用为

for i, coord2 in enumerate(coordlist):
  if (PBCdist(coord1,coord2,UC) < radius):
      do something with i

最近我读到我可以通过使用列表理解来大大提高性能。以下适用于非PBC案件,但不适用于PBC案件

coord_indices = [i for i, y in enumerate([np.sqrt(np.sum((coord2-coord1)**2)) for coord2 in coordlist]) if y < radius]
for i in coord_indices:
   do something

是否有某种方法可以为PBC案例做相同的事情?有没有更好的选择?

4 个答案:

答案 0 :(得分:12)

您应该以一种可以将循环矢量化为5711点的方式编写distance()函数。以下实现接受一个点数组作为x0x1参数:

def distance(x0, x1, dimensions):
    delta = numpy.abs(x0 - x1)
    delta = numpy.where(delta > 0.5 * dimensions, delta - dimensions, delta)
    return numpy.sqrt((delta ** 2).sum(axis=-1))

示例:

>>> dimensions = numpy.array([3.0, 4.0, 5.0])
>>> points = numpy.array([[2.7, 1.5, 4.3], [1.2, 0.3, 4.2]])
>>> distance(points, [1.5, 2.0, 2.5], dimensions)
array([ 2.22036033,  2.42280829])

结果是作为第二个参数传递给distance()的点与points中每个点之间的距离数组。

答案 1 :(得分:4)

import numpy as np

bounds = np.array([10, 10, 10])
a = np.array([[0, 3, 9], [1, 1, 1]])
b = np.array([[2, 9, 1], [5, 6, 7]])

min_dists = np.min(np.dstack(((a - b) % bounds, (b - a) % bounds)), axis = 2)
dists = np.sqrt(np.sum(min_dists ** 2, axis = 1))

此处ab是您要计算的矢量列表,而bounds之间的距离是空间的边界(所以这里所有三个维度都从0到10,然后换行)。它会计算a[0]b[0]a[1]b[1]之间的距离,依此类推。

我确信numpy专家可以做得更好,但这可能会比你正在做的快一个数量级,因为大部分工作现在用C语言完成。

答案 2 :(得分:0)

看看Ian Ozsvalds high performance python tutorial。它包含了很多关于你可以去哪里的建议。

,包括:

  • 矢量
  • 用Cython
  • pypy
  • numexpr
  • pycuda
  • multiprocesing
  • parallel python

答案 3 :(得分:0)

我发现meshgrid对于产生距离非常有用。例如:

import numpy as np
row_diff, col_diff = np.meshgrid(range(7), range(8))
radius_squared = (row_diff - x_coord)**2 + (col_diff - y_coord)**2

我现在有一个数组(radius_squared),其中每个条目都指定距离数组位置[x_coord, y_coord]的距离的平方。

要使阵列圆化,我可以执行以下操作:

row_diff, col_diff = np.meshgrid(range(7), range(8))
row_diff = np.abs(row_diff - x_coord)
row_circ_idx = np.where(row_diff > row_diff.shape[1] / 2)
row_diff[row_circ_idx] = (row_diff[row_circ_idx] - 
                         2 * (row_circ_idx + x_coord) + 
                         row_diff.shape[1])
row_diff = np.abs(row_diff)
col_diff = np.abs(col_diff - y_coord)
col_circ_idx = np.where(col_diff > col_diff.shape[0] / 2)
col_diff[row_circ_idx] = (row_diff[col_circ_idx] - 
                         2 * (col_circ_idx + y_coord) + 
                         col_diff.shape[0])
col_diff = np.abs(row_diff)
circular_radius_squared = (row_diff - x_coord)**2 + (col_diff - y_coord)**2

我现在所有的数组距离都用矢量数学进行了圆形化。