给定XYZ网格点,计算内部球体的体积

时间:2020-01-21 00:15:17

标签: python numpy scipy

我有一个均匀分布的xyz笛卡尔点的大型3D网格(〜800,000 pts),我想根据占据球体的点数来查找球体内部的体积。我目前正在使用scipy cKDTree并使用query_ball_point检测原点(0,0,0)的一定半径内的所有点以估计体积,但此体积(grid_vol,下方)通常相差很大(误差为50%或更大) ),而不是真实的体积(sphere_vol)。

import numpy as np
from scipy import spatial
import math
#constants
xl = -3.15
xr =  1.75
yl = -2.0
yr =  2.0
zl = -1.15
zr = 3.9
spacing = 0.05
R = 3.5
cube = spacing ** 3  
#Create grid
x=np.arange(xl,xr,spacing)
y=np.arange(yl,yr,spacing)
z=np.arange(zl,zr,spacing)
x2,y2,z2=np.meshgrid(x,y,z,indexing='ij')
all_grid=np.array([x2.flatten(),y2.flatten(),z2.flatten()]).T
cube = spacing ** 3                  
point_tree = spatial.cKDTree(all_grid)                  # allgrid = evenly spaced rectangular grid
n_voxel = len(point_tree.query_ball_point((0,0,0), R))   # number of points in grid occupying sphere of radius R
grid_vol = n_voxel * cube                               # volume based on grid points
sphere_vol = 4 / 3 * math.pi * R ** 3                # vol of sphere w/ radius R to compare

在这种情况下:

grid_vol = 78.1275
sphere_vol = 179.5944

我想知道是否有一个已知的模块对这种从网格点测量球体的应用会很好

1 个答案:

答案 0 :(得分:0)

您好guilian我尝试了您的代码,据我所知它可以正常工作(由于近似而有些错误,但不是很大

import numpy as np
from scipy import spatial
#define constants
l=-1
r=1
spacing=0.05
R=0.5
cube = spacing ** 3  
#Create grid
x=np.arange(l,r,spacing)
y=np.arange(l,r,spacing)
z=np.arange(l,r,spacing)
x2,y2,z2=np.meshgrid(x,y,z,indexing='ij')
all_grid=np.array([x2.flatten(),y2.flatten(),z2.flatten()]).T
# your code            
point_tree = spatial.cKDTree(all_grid)
n_voxel = len(point_tree.query_ball_point((0,0,0), R))   # number of points in grid occupying sphere of radius R
grid_vol = n_voxel * cube                               # volume based on grid points
sphere_volume = 4 / 3 * np.pi * R ** 3
print(grid_vol) # 0.5185000000000001
print(sphere_volume) # 0.5235987755982988
相关问题