Change voxelize to use arbitrary grid

This commit is contained in:
jan 2018-03-30 16:14:03 -07:00
commit ddb4f2c473
3 changed files with 57 additions and 62 deletions

View file

@ -87,13 +87,10 @@ def split(poly, plane, same_only: bool = False):
''' '''
Some edges cross the plane Some edges cross the plane
''' '''
right_inds3 = numpy.repeat(right_inds, 3)
# remove edges which don't also touch the left half-plane # remove edges which don't also touch the left half-plane
rverts = right_inds3[far_vertex_left] which_edges_cross, rl_edge_inds = numpy.divmod(numpy.where(far_vertex_left)[0], 3)
rverts = right_inds[which_edges_cross]
lverts = next_vertex[far_vertex_left] lverts = next_vertex[far_vertex_left]
if not same_only:
pinds = (numpy.arange(3 * num_right) % 3)[far_vertex_left]
num_new_vertices = rverts.size num_new_vertices = rverts.size
@ -180,7 +177,7 @@ def split(poly, plane, same_only: bool = False):
old_neighbors_right = poly['neighbors'].copy() old_neighbors_right = poly['neighbors'].copy()
old_neighbors_right[right] = ind_map_right[old_neighbors_right[right]] old_neighbors_right[right] = ind_map_right[old_neighbors_right[right]]
old_neighbors_right[(rverts, pinds)] = num_right + numpy.arange(num_new_vertices) old_neighbors_right[(rverts, rl_edge_inds)] = num_right + numpy.arange(num_new_vertices)
old_neighbors_right = old_neighbors_right[right] old_neighbors_right = old_neighbors_right[right]
right_poly = { right_poly = {

View file

@ -1,9 +1,10 @@
from typing import Tuple from typing import Tuple, List
import numpy import numpy
from . import poly_t, plane_t from . import poly_t, plane_t
from .split import split from .split import split
from .moments import get_moments, number_of_moments from .moments import get_moments, number_of_moments
from .shapes import planes_from_box
try: try:
# Check if running with line_profiler # Check if running with line_profiler
@ -15,75 +16,74 @@ except NameError:
@profile @profile
def voxelize(poly: poly_t, def voxelize(poly: poly_t,
d: numpy.ndarray, planes: List[numpy.ndarray],
box: numpy.ndarray = None,
order: int = 0 order: int = 0
) -> numpy.ndarray: ) -> numpy.ndarray:
''' '''
Voxelize a Schelegel-representation polyhedron 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]
#TODO: COMMENT THIS FILE! grid_shape = numpy.array([e.size for e in planes], dtype=int) + 1
box = get_box(poly, d) if box is None else numpy.array(box, dtype=int)
d = numpy.array(d)
grid_shape = box[1] - box[0]
dest_grid = numpy.zeros((*grid_shape, number_of_moments(order)), dtype=float) dest_grid = numpy.zeros((*grid_shape, number_of_moments(order)), dtype=float)
if poly is None or poly['vertices'].shape[0] == 0 or (grid_shape <= 0).any(): if poly['vertices'].shape[0] == 0 or (grid_shape <= 0).any():
return dest_grid return dest_grid
# Stack-based recursive split slices = numpy.array([(0, e.size) for e in planes], dtype=int)
stack = [(poly, box)] stack = [(poly, slices)]
while stack: while stack:
c_poly, c_box = stack.pop() poly, slices = stack.pop()
# Base case 1: moments are 0 for this region # Base case 1: No vertices in this region, moments are 0
if c_poly['vertices'].shape[0] == 0: if poly['vertices'].shape[0] == 0:
continue continue
box_size = c_box[1] - c_box[0] num_planes_remaining = numpy.diff(slices, axis=1)
split_axis = box_size.argmax()
max_dist = box_size[split_axis]
# Base case 2: calculate moments for single voxel # Base case 2: calculate moments for single voxel
if max_dist == 1: if not num_planes_remaining.any():
moments = get_moments(c_poly, order) moments = get_moments(poly, order)
offset = (c_box[0] - box[0]) i, j, k = slices[:, 0] - 1
dest_grid[offset[0], offset[1], offset[2], :] += moments dest_grid[i, j, k, :] = moments
continue continue
# Recursion case: split along longest side # Recursion case: split along longest side
n = numpy.zeros(3) axis = num_planes_remaining.argmax()
n[split_axis] = -1 plane_ind = num_planes_remaining[axis] // 2 + slices[axis, 0]
plane_pos = planes[axis][plane_ind]
split_ind = c_box[0][split_axis] + max_dist // 2 plane = (numpy.roll([-1, 0, 0], axis), plane_pos)
plane = (n, d[split_axis] * split_ind) children = split(poly, plane)
children = split(c_poly, plane) slices_left = slices.copy()
slices_right = slices.copy()
slices_left[axis, 1] = plane_ind
slices_right[axis, 0] = plane_ind + 1
split_plane = c_box.copy() stack.append((children[0], slices_left ))
split_plane[:, split_axis] = split_ind stack.append((children[1], slices_right ))
stack.append((children[0], numpy.vstack((c_box[0], split_plane[1])) ))
stack.append((children[1], numpy.vstack((split_plane[0], c_box[1])) ))
return dest_grid return dest_grid
def get_box(poly: poly_t, d: numpy.ndarray) -> numpy.ndarray: def clamp_to_box(poly: poly_t,
min_box = numpy.floor(numpy.min(poly['vertices'], axis=0) / d)
max_box = numpy.ceil(numpy.max(poly['vertices'], axis=0) / d)
return numpy.array((min_box, max_box), dtype=int)
def clamp_box(poly: poly_t,
box: numpy.ndarray, box: numpy.ndarray,
clampbox: numpy.ndarray, ) -> poly_t:
d: numpy.ndarray for face in planes_from_box(box):
) -> Tuple[poly_t, numpy.ndarray]:
faces = box_faces_from_verts(clampbox)
for face in faces:
poly = clip(poly, face) poly = clip(poly, face)
box = get_box(poly, d) return poly
return poly, box

View file

@ -211,19 +211,18 @@ def test_recursive_split(num_trials: int = 10, max_depth: int = 6 ):
def test_voxelization(): def test_voxelization():
# Test r3d_voxelize() by checking that the voxelized moments # Test r3d_voxelize() by checking that the voxelized moments
# sum to those of the original input # sum to those of the original input
POLY_ORDER = 4 POLY_ORDER = 0
grid_size = 25 grid_resolution = 250
dx = numpy.ones(3) / grid_size
verts = 1.5 * (numpy.array(rand_tetrahedron_vertices()) + 1) verts = 1.5 * (numpy.array(rand_tetrahedron_vertices()) + 1)
poly = build_tetrahedron(verts) poly = build_tetrahedron(verts)
moments = get_moments(poly, POLY_ORDER) moments = get_moments(poly, POLY_ORDER)
logger.info(f'Voxelizing a tetrahedron to a grid with dx = {dx} and moments of order {POLY_ORDER}') edges = [numpy.linspace(-1, 3, grid_resolution) for _ in range(3)]
grid = voxelize(poly, dx, order=POLY_ORDER) logger.info(f'Voxelizing a tetrahedron to a grid with moments of order {POLY_ORDER}')
grid = voxelize(poly, edges, order=POLY_ORDER)
# visualize_voxels(grid) visualize_voxels(grid)
voxsum = numpy.sum(grid, axis=(0, 1, 2)) voxsum = numpy.sum(grid, axis=(0, 1, 2))
@ -323,7 +322,6 @@ def plot_brep(brep):
triangles.append([face[0], face[i], face[i+1]]) triangles.append([face[0], face[i], face[i+1]])
triangles = numpy.array(triangles, dtype=int) triangles = numpy.array(triangles, dtype=int)
m = stl.mesh.Mesh(numpy.empty(triangles.shape[0], dtype=stl.mesh.Mesh.dtype)) m = stl.mesh.Mesh(numpy.empty(triangles.shape[0], dtype=stl.mesh.Mesh.dtype))
for i, f in enumerate(triangles): for i, f in enumerate(triangles):
for j in range(3): for j in range(3):