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