python - 在 numpy 中索引 3d 网格数据的球形子集

标签 python numpy 3d grid subset

我有一个带坐标的 3d 网格

x = linspace(0, Lx, Nx)
y = linspace(0, Ly, Ny)
z = linspace(0, Lz, Nz)

我需要在位置 (x0,y0,z0) 的某个半径 R 内索引点(即 x[i],y[j],z[k])。 N_i 可以很大。我可以做一个简单的循环来找到我需要的东西

points=[]
i0,j0,k0 = floor( (x0,y0,z0)/grid_spacing )
Nr = (i0,j0,k0)/grid_spacing + 2
for i in range(i0-Nr, i0+Nr):
    for j in range(j0-Nr, j0+Nr):
        for k in range(k0-Nr, k0+Nr):
            if norm(array([i,j,k])*grid_spacing - (x0,y0,k0)) < cutoff:
                points.append((i,j,k))

但这很慢。有没有更自然/更快速的方法来使用 numpy 进行此类操作?

最佳答案

这个怎么样:

import scipy.spatial as sp
x = np.linspace(0, Lx, Nx)
y = np.linspace(0, Ly, Ny)
z = np.linspace(0, Lz, Nz)

#Manipulate x,y,z here to obtain the dimensions you are looking for

center=np.array([x0,y0,z0])

#First mask the obvious points- may actually slow down your calculation depending.
x=x[abs(x-x0)<cutoff]
y=y[abs(y-y0)<cutoff]
z=z[abs(z-z0)<cutoff]


#Generate grid of points
X,Y,Z=np.meshgrid(x,y,z)
data=np.vstack((X.ravel(),Y.ravel(),Z.ravel())).T

distance=sp.distance.cdist(data,center.reshape(1,-1)).ravel()
points_in_sphere=data[distance<cutoff]

除了最后两行你应该能够做到:

tree=sp.cKDTree(data)
mask=tree.query_ball_point(center,cutoff)
points_in_sphere=data[mask]

如果你不想调用空间:

distance=np.power(np.sum(np.power(data-center,2),axis=1),.5)
points_in_sphere=data[distance<cutoff]

关于python - 在 numpy 中索引 3d 网格数据的球形子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17663393/

相关文章:

python - 如果至少有一个值在 python 中匹配,则联合列表

python - 如何使用 Python 对大文件进行排序?

python - 大型稀疏线性系统求解,重新排序和预处理器会变得更糟吗?

c++ - Blas 看起来很慢

javascript - Three.js 光线转换不适用于移动物体

python - 无法将 TensorFlow Keras LSTM 模型保存为 SavedModel 格式

python - numpy 的就地操作(例如 `+=` )如何工作?

algorithm - 是否有生成 3d 云的算法?

安卓3D动画

python - “conda install”命令中c标志的作用是什么