indexing spherical subset of 3d grid data in numpy(在numpy中索引3d网格数据的球形子集)
本文介绍了在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网格数据的球形子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在numpy中索引3d网格数据的球形子集


基础教程推荐
猜你喜欢
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01