adze/chop/voxel.py
2018-04-03 15:46:52 -07:00

81 lines
2.9 KiB
Python

from typing import Tuple, List
import numpy
from . import poly_t, plane_t
from .split import split
from .moments import get_moments, number_of_moments
from .shapes import planes_from_box
try:
# Check if running with line_profiler
profile
except NameError:
def profile(f):
return f
@profile
def voxelize(poly: poly_t,
planes: List[numpy.ndarray],
order: int = 0
) -> numpy.ndarray:
'''
Voxelize a Schelegel-representation polyhedron on an arbitrary rectangular grid.
The grid is specified by supplying 3 sets of axis-aligned planes, in the form
[[x0, x1, x2, ..., xX], [y0, y1, y2, ..., yY], [z0, z1, ..., zZ]]
The output array has size [X+1, Y+1, Z+1, N], where N is the number of moments
corresponding to the requested order. The outer borders of the output correspond
to portions of the polyhedron that protruded outside the bounds of the provided grid.
:param poly: Polyhedron to voxelize.
:param planes: List of coordinate lists, specifying the axis-aligned planes
which form the voxel grid:
[[x0, x1, ..., xX], [y0, y1, ..., yY], [z0, z1, ..., zZ]]
:param order: Polynomial order of moments to calculate. Default 0.
:return: (X + 1) x (Y + 1) x (Z + 1) x N array, where the outer borders of the
first three dimensions correspond to portions of the polyhedron that protruded
outside the outermost planes, and N is number_of_moments(order).
'''
planes = [numpy.array(p) for p in planes]
grid_shape = numpy.array([e.size for e in planes], dtype=int) + 1
dest_grid = numpy.zeros((*grid_shape, number_of_moments(order)), dtype=float)
if poly['vertices'].shape[0] == 0 or (grid_shape <= 0).any():
return dest_grid
slices = numpy.array([(0, e.size) for e in planes], dtype=int)
stack = [(poly, slices)]
while stack:
poly, slices = stack.pop()
# Base case 1: No vertices in this region, moments are 0
if poly['vertices'].shape[0] == 0:
continue
num_planes_remaining = numpy.diff(slices, axis=1)
# Base case 2: calculate moments for single voxel
if not num_planes_remaining.any():
moments = get_moments(poly, order)
i, j, k = slices[:, 0] - 1
dest_grid[i, j, k, :] = moments
continue
# Recursion case: split along longest side
axis = num_planes_remaining.argmax()
plane_ind = num_planes_remaining[axis] // 2 + slices[axis, 0]
plane_pos = planes[axis][plane_ind]
plane = (numpy.roll([-1, 0, 0], axis), plane_pos)
poly_left, poly_right = split(poly, plane)
slices_left = slices.copy()
slices_right = slices.copy()
slices_left[axis, 1] = plane_ind
slices_right[axis, 0] = plane_ind + 1
stack.append((poly_left, slices_left))
stack.append((poly_right, slices_right))
return dest_grid