use*_*528 5 python 3d grid numpy subset
我有一个带坐标的三维网格
x = linspace(0, Lx, Nx)
y = linspace(0, Ly, Ny)
z = linspace(0, Lz, Nz)
Run Code Online (Sandbox Code Playgroud)
我需要在一个位置(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))
Run Code Online (Sandbox Code Playgroud)
但这很慢.是否有一种更自然/更快捷的方式来进行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]
Run Code Online (Sandbox Code Playgroud)
您应该能够执行以下操作,而不是最后两行:
tree=sp.cKDTree(data)
mask=tree.query_ball_point(center,cutoff)
points_in_sphere=data[mask]
Run Code Online (Sandbox Code Playgroud)
如果你不想调用空间:
distance=np.power(np.sum(np.power(data-center,2),axis=1),.5)
points_in_sphere=data[distance<cutoff]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1251 次 |
| 最近记录: |