gpt4 book ai didi

python - 在考虑周期性边界条件的同时优化 Python 距离计算

转载 作者:太空狗 更新时间:2023-10-29 18:23:31 28 4
gpt4 key购买 nike

我编写了一个 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 案例,是否有某种方法可以做同样的事情?有没有更好的替代方案?

最佳答案

您应该以一种可以对 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 中的每个点之间的距离数组。

关于python - 在考虑周期性边界条件的同时优化 Python 距离计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11108869/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com