在numpy中索引3d网格数据的球形子集 [英] indexing spherical subset of 3d grid data in numpy

查看:42
本文介绍了在numpy中索引3d网格数据的球形子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a 3d grid with coordinates

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 可以很大.我可以做一个简单的循环来找到我需要的东西

and I need to index points (i.e. x[i],y[j],z[k]) within some radius R of a position (x0,y0,z0). N_i can be quite large. I can do a simple loop to find what I need

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 进行这种类型的操作?

but this quite slow. Is there a more natural/ faster way to do this type of operation with 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]

你应该可以做的不是最后两行:

Instead of the last two lines you should be able to do:

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]

这篇关于在numpy中索引3d网格数据的球形子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆