0
votes

I have a large 3D grid (~800,000 pts) of evenly spaced xyz cartesian points and I want to find the volume of a sphere inside based on the number of points occupying the sphere. I'm currently using a scipy cKDTree and detecting all points within a certain radius of the origin (0,0,0) with query_ball_point to estimate a volume but this volume (grid_vol, below) is often much different (50% error or greater) than the true volume (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

in this case:

grid_vol = 78.1275
sphere_vol = 179.5944

I was wondering if there was a known module that would be good for this application of measuring a sphere from grid points

1
What do you mean by "much different"? How much? You will always lose information when going from continuous space to a voxelized space - LeoE
trying to reduce errors of 50% or greater - alchemist

1 Answers

0
votes

Hey guilian i tried your code and as far as I can tell it works just fine (some error due to approximation but not a large one

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