rename to adze

This commit is contained in:
jan 2018-04-19 20:15:01 -07:00
commit 31d24ed9d3
8 changed files with 114 additions and 9 deletions

64
adze/__init__.py Normal file
View file

@ -0,0 +1,64 @@
'''
adze is a library for accurate polyhedron clipping and anti-aliased voxelization.
Written with python + numpy.
Most operations are performed using an ordered adjacency-list polyhedron represenation,
capable of holding multiple unconnected possibly non-convex components.
To convert from a boundary representation, use
poly = build_polyhedron(vertex_list, face_list)
To convert back to a boundary representation, use
list_of_boundaries = boundary_from_poly(poly)
vertex_list_0 = list_of_boundaries[0]['vertices']
face_list_0 = list_of_boundaries[0]['faces']
Basic operations include
plane = (normal_vector, signed_distance_to_origin)
same_side_as_normal, other_side = split(poly, plane)
same_side_as_normal = clip(poly, plane)
volume = get_volume(poly)
volume, m_x, m_y, m_z = get_moments(poly, order=1)
Anti-aliased voxelization is done on a non-uniform rectangular grid, specified by the cell
edge coordinates:
x_planes = numpy.linspace(-5, 5, 100)
y_planes = numpy.linspace(-10, 10, 5)
z_planes = [-3, 0, 1, 2, 3]
voxel_weights = voxelize(poly, [x_planes, y_planes, z_planes], order=0)
Helper functions include
poly = build_box(box_corners)
poly = build_tetrahedron(vertices)
plane_list = planes_from_box(box_corners)
plane_list = planes_from_tetrahedron(vertices)
n = number_of_moments(order=3)
--------------------------
In the polyhedron representation returned by the build_* functions and accepted by
most other functions (split, clip, get_volume, get_moments, voxelize), the
polyhedron is stored as a 3-vertex-connected, triply-linked graph, with each vertex's
neighbors listed in counterclockwise order when viewed from outside the polyhedron. TODO
Each graph-vertex (g-vertex) is connected to exactly 3 other g-vertices; polygon-
vertices (p-vertices) are
TODO
This
representation looks like
poly = {'neighbors': ndarray[Px3, int], 'vertices': ndarray[Px3, float]}
where poly['neighbors'] contains
'''
from .util import poly_t, plane_t
from .split import split, clip
from .moments import get_volume, get_moments, number_of_moments
from .boundary import build_polyhedron, boundary_from_poly
from .shapes import build_tetrahedron, build_box, planes_from_tetrahedron, planes_from_box
from .voxel import voxelize

302
adze/boundary.py Normal file
View file

@ -0,0 +1,302 @@
from typing import List, Dict
import numpy
from numpy.linalg import norm
from . import poly_t, plane_t
from .util import _get_maps, find_components, find_faces
try:
# Check if running with line_profiler
profile
except NameError:
def profile(f):
return f
def planes_from_boundary(vertices: numpy.ndarray,
faces: List[numpy.ndarray]
) -> List[plane_t]:
'''
Generate a list of planes (normal, signed distance) from the faces of a boundary-
representation polyhedron.
:param vertices: Nx3 ndarray specifying the polyhedron's vertex positions.
:param faces: List of 1d ndarrays. Each ndarray is a list of vertex indices,
specifying a face.
:return: List of planes, represented by (normal vector, signed distance to origin) tuples.
'''
planes = []
for face in faces:
face_verts = vertices[face]
n = numpy.cross(numpy.diff(face_verts, n=1, axis=0),
numpy.diff(face_verts, n=2, axis=0))
n /= norm(n)
centroid = numpy.sum(face_verts, axis=0) / len(face)
d = -n @ centroid
planes.append(n, d)
return planes
@profile
def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t:
'''
Generate a 3-verted-connected Schlegel diagram corresponding to the
provided boundary-representation polyhedron.
:param vertices: Nx3 ndarray specifying the polyhedron's vertex positions.
:param faces: List of 1d ndarrays. Each ndarray is a list of vertex indices,
specifying a face.
:return: Schelgel-representation polyhedron
'''
vertices = numpy.array(vertices, dtype=float)
faces = [numpy.array(face, dtype=int) for face in faces]
edges_per_vertex = numpy.bincount(numpy.hstack(faces))
if edges_per_vertex.min() < 3:
raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges')
if edges_per_vertex.max() == 3:
'''
In this case, we don't need to duplicate any vertices to make a 3-vertex-connected graph
'''
neighbors = numpy.empty_like(vertices, dtype=int).fill(vertices.size)
for face in faces:
# Check if each vertex in this face is already linked to its next or previous face-neighbor
prev_vert = numpy.roll(face, 1)
next_vert = numpy.roll(face, -1)
neighbor_rows = neighbors[face, :]
has_prev = (neighbor_rows == prev_vert).any(axis=1)
has_next = (neighbor_rows == next_vert).any(axis=1)
# Each vertex touches 3 faces; each vertex triplet (neighbor_row) is a triangle on a face.
# Thus, we will never encounter a situation in which prv == nxt.
# If the vertex hasn't been linked to anything yet, set its first two
# polyhedron-neighbors to its face-neighbors
empty = numpy.logical_not(numpy.logical_or(has_prev, has_next))
neighbors[face[empty], 0] = next_vert[empty]
neighbors[face[empty], 1] = prev_vert[empty]
# If the vertex has already been linked to something (by a different face),
# fill in the third neighbor
# Note that this causes excess writes; it might improve performace to check
# if the third neighbor is already filled (maybe? TODO)
neighbors[face[has_prev], 2] = next_vert[has_prev]
neighbors[face[has_next], 2] = prev_vert[has_next]
return {'vertices': vertices, 'neighbors': neighbors}
'''
Some vertices link more than three edges.
We only allow three edges per vertex in the graph, so we need to make
degenerate copies of those vertices.
For convenience, duplicate each vertex as many times as it has edges.
This creates 2 'excess' duplicates of each vertex (e.g. a vertex with
3 edges will turn into 3 vertices, even though it was fine as-is).
Link the "duplicate" vertices together, as follows:
- Each set of duplicates becomes a doubly-linked ring.
- Each duplicate has an additional, "third" pointer, pointing to one
of the duplicates created for a _different_ original vertex (i.e., this
pointer and its counterpart both correspond to the edge which caused
these two duplicates to be created).
We perform this linkage by creating a list of 3 entries per duplicate, aiming
to eventually fill each row with the indices
[next_row, third_row, prev_row]
corresponding to the linked duplicates.
We begin by filling columns (1, 2) with the (next, prev) _original_ vertex indices
for each face. The subset of the list corresponding to a single original vertex
thus looks like
[???, f0_next, f0_prev] <-- (i.e., the angle fromed by the three points
[???, f3_next, f3_prev] [..., prev, me, next, ...], where 'me' is the
[???, f7_next, f7_prev] (original) vertex index corresponding to this row
... and prev, next are original vertex indices as listed
in face 0's vertex list)
and so on, with a row and f# for each face the original vertex participates in.
The full list is just
[ rows for
original vertex 0
...
rows for
original vertex 1
...
etc
]
(note that each original vertex takes as many rows as it has edges)
Next, note that the newly filled columns will hold the same sets of numbers, just permuted.
Each row specifies two edges (an angle), and each edge is shared by two faces, and appears
once as a "previous" pointer and once as a "next" pointer.
So, we can set column 0 to the (new) index of the row whose f_prev matches our row's f_next.
In other words, pick column 0 to ensure dn[i, 1] == dn[dn[i, 0], 2]. Our columns become
[next_row, f#_next, f#_prev]
Then, replace f#_prev with a back-pointer based on next_row,
[next_row, f#_next, prev_row]
which completes our doubly-linked duplicate vertex rings.
To complete the linkage, we need to link to 'third_row'. We can do this by,
For each set of rows (corresponding to an original vertex V0),
- searching the sets of rows Vi corresponding to the listed f#_next values
for rows whose f#_next == V0
- doubly linking each row (i) in V0 with its 'found' row in Vi
Finally, we can remove the first two ('excess') duplicate vertices in each ring, and update
the links to reflect their removal.
'''
# starting row for each original vertex
start = numpy.roll(numpy.cumsum(edges_per_vertex), 1)
start[0] = 0
# number of input vertices (v) and duplicates (d)
num_vertices = vertices.shape[0]
num_duplicates = edges_per_vertex.sum()
neighbors = numpy.empty((num_duplicates, 3), dtype=int)
'''
Fill columns (1, 2) with original vertex inds (f#_next, f#_prev)
'''
num_filled_rows = numpy.zeros(num_duplicates, dtype=int)
for face in faces:
# assume a face can't use the same vertex twice
v_inds = start[face] + num_filled_rows[face]
neighbors[v_inds, 1] = numpy.roll(face, -1)
neighbors[v_inds, 2] = numpy.roll(face, 1)
num_filled_rows[face] += 1
'''
Fill columns (0, 2) with new vertex inds (next_row, prev_row)
to complete doubly-linked rings
'''
for v in range(num_vertices):
v0 = start[v]
s = slice(v0, v0 + edges_per_vertex[v])
m, n = _get_maps(neighbors[s, 2], neighbors[s, 1])
neighbors[s, 0] = n + v0
neighbors[s, 2] = m + v0
'''
for each pair of original vertices,
find subvertices whose f#_next pointers point to each other's original vertices,
and link them using column 1 (i.e. set their third_row pointers to each other)
'''
# Mapping from row to original vertex index
v0s = numpy.repeat(numpy.arange(len(edges_per_vertex)), edges_per_vertex)
# Copy column 1 to save target info
target_vert = neighbors[:, 1].copy()
# Preallocate mask arrays
src_mask = numpy.empty(num_duplicates, dtype=bool)
dst_mask = numpy.empty(num_duplicates, dtype=bool)
for v in range(num_vertices):
s = start[v]
e = s + edges_per_vertex[v]
src_mask.fill(False)
src_mask[e:] = target_vert[e:] == v # find rows which reference us
src_vert = v0s[src_mask] # figure out their original vertex numbers
if src_vert.size == 0:
continue
dst_mask.fill(False)
dst_mask[s:e] = target_vert[s:e] > v # mask out any references to verts >= current
dst_vert = target_vert[dst_mask]
ma, mb = _get_maps(dst_vert, src_vert)
neighbors[dst_mask, 1] = numpy.where(src_mask)[0][mb]
neighbors[src_mask, 1] = numpy.where(dst_mask)[0][ma]
'''
Remove first two duplicates of each vertex (they aren't needed)
'''
nxt, third, prv = neighbors[start, :].T
nxt_nxt, nxt_third, _nxt_prv = neighbors[nxt, :].T
# Which vertex to link to
dest_map = numpy.arange(num_duplicates, dtype=int) # default maps to itself
dest_map[start] = prv # first maps to previous
dest_map[nxt] = nxt_nxt # second maps to next
# Which backreference to modify
back_map = numpy.full_like(dest_map, 1) # default is 'third'
back_map[start] = 0 # if we mapped from a first vertex to its previous, set to 'next'
back_map[nxt] = 2 # if we mapped from a second vertex to its next, set to 'previous'
# Map 'third' to where it should point to. 'dm'~'dest_map'
dm_third = dest_map[third]
dm_nxt_third = dest_map[nxt_third]
neighbors[prv, 0] = dm_third # previous's next reference points to third
neighbors[nxt_nxt, 2] = dm_nxt_third # next-next's previous reference points to next-third
neighbors[dm_third, back_map[third]] = prv # third's backreference points to previous
neighbors[dm_nxt_third, back_map[nxt_third]] = nxt_nxt # next-third's backreference points to next-next
# Mark for removal
keep_map = num_filled_rows # reuse to avoid reallocating
keep_map.fill(1)
keep_map[start] = 0
keep_map[nxt] = 0
neighbors = neighbors[keep_map != 0]
keep_map[keep_map != 0] = numpy.arange(neighbors.shape[0])
neighbors[:] = keep_map[neighbors]
final_vertices = numpy.repeat(vertices, edges_per_vertex - 2, axis=0)
return {'vertices': final_vertices, 'neighbors': neighbors}
@profile
def boundary_from_poly(poly: poly_t) -> Dict:
'''
Generate a boundary represeentation corresponding to the provided
3-vertex-connected Schlegel diagram.
:param poly: Polyhedron to convert, in Schlegel representation.
:return: Dict containing 'vertices' (Nx3 ndarray of vertex locations)
and 'faces' (list of ndarrays specifying the indices of vertices
used for constructing each face).
'''
neighbors = poly['neighbors']
vertices = poly['vertices']
owning_component = find_components(neighbors)
faces = find_faces(neighbors)
num_components = owning_component.max() + 1
components = [[] for _ in range(num_components)]
for face in faces:
component_ind = owning_component[face[0]]
components[component_ind].append(face)
unique_verts, unique_vertex_map = numpy.unique(vertices, axis=0, return_inverse=True)
umap = numpy.empty(unique_verts.shape[0], dtype=int)
boundary_map = numpy.empty(vertices.shape[0], dtype=int)
boundaries = []
for i, component in enumerate(components):
mask = owning_component == i
umask = unique_vertex_map[mask]
used_uverts = numpy.unique(umask)
umap[used_uverts] = numpy.arange(used_uverts.size) # map to account for deletion of unique verts not used in this component
boundary_map[mask] = umap[umask] # map from non-unique verts in face to unique, in-use verts
boundary = {
'vertices': unique_verts[used_uverts],
'faces': [boundary_map[face] for face in component],
}
boundaries.append(boundary)
return boundaries

128
adze/moments.py Normal file
View file

@ -0,0 +1,128 @@
from typing import Dict, Tuple
import numpy
from . import poly_t, plane_t
from .util import find_faces
try:
# Check if running with line_profiler
profile
except NameError:
def profile(f):
return f
def number_of_moments(order: int) -> int:
'''
Returns the number of moments with a given order or below.
:param order: Maximum polynomial order for the moments.
:return: Number of moments with that order or fewer.
'''
return ((order + 1) * (order + 2) * (order + 3)) // 6
def get_volume(poly: poly_t) -> float:
'''
Calculates the volume of a polyhedron (0th moment).
:param poly: Polyhedron to evaluate, in Schlegel representation.
:return: Volume of the polyhedron.
'''
return get_moments(poly, 0)[0]
@profile
def get_moments(poly: poly_t, order: int) -> numpy.ndarray:
'''
Calculates the moments of a polyhedron, up to the specified polynomial order.
:param poly: Polyhedron to evaluate, in Schlegel representation.
:param order: Maximum polynomial order for moments.
:return: Moments, increasing polynomial order:
[1, x, y, z, xx, xy, xz, yy, yz, zz, xxx, xxy, xxz, ...]
'''
vertices = poly['vertices']
neighbors = poly['neighbors']
num_verts = vertices.shape[0]
if num_verts == 0:
return numpy.array([0], dtype=float)
'''
Decompose polyhedron into triangle fans
'''
faces = find_faces(neighbors)
triangle_fans = []
max_face_len = max(len(face) for face in faces)
triangle_inds = numpy.empty((max_face_len - 2, 3), dtype=int)
for face in faces:
# Build a triangle fan from each face
ilen = len(face) - 2
triangle_inds[:ilen, 0] = face[0] # this assignment is a broadcast
triangle_inds[:ilen, 1] = face[1:-1]
triangle_inds[:ilen, 2] = face[2:]
triverts = vertices[triangle_inds[:ilen]]
triangle_fans.append(triverts)
'''
Calculate the 0th-order moment
'''
triangles = numpy.vstack(triangle_fans)
volumes = -numpy.linalg.det(triangles)
moment0 = numpy.array([volumes.sum() / 6])
if order == 0:
return moment0
'''
Iteratively calculate higher-order moments, as per Koehl (2012).
'''
prevlayer, curlayer = 0, 1
inds = numpy.arange(order + 1)
mx, my = numpy.meshgrid(inds, inds, indexing='ij')
valid = numpy.zeros((2, order + 1, order + 1), dtype=bool)
cropped = numpy.zeros((order + 1, order + 1), dtype=bool)
Q = numpy.zeros((len(triangles), 3, order + 1, order + 1, 2), dtype=float)
Q[:, :, 0, 0, prevlayer] = 1
S = numpy.zeros((order + 1, order + 1, 2), dtype=float)
S[0, 0, prevlayer] = 1
valid[prevlayer, :, :] = False
valid[prevlayer, 0, 0] = True
moment_list = [moment0]
for c in range(1, order + 1):
valid[curlayer] = c >= mx + my
num_valid = (c + 1) * (c + 2) // 2 # always an int, see number_of_moments()
Q_prev = Q[:, :, valid[prevlayer], prevlayer]
Q[:, :, 0, :, curlayer] = 0
S_prev = S[valid[prevlayer], prevlayer]
S[0, :, curlayer] = 0
cropped.fill(0)
cropped[1:, :] = valid[curlayer, 1:, :]
Q[:, :, cropped, curlayer] = triangles[:, :, 0:1] * Q_prev
S[cropped, curlayer] = S_prev
cropped = numpy.moveaxis(cropped, 0, 1)
Q[:, :, cropped, curlayer] += triangles[:, :, 1:2] * Q_prev
S[cropped, curlayer] += S_prev
Q[:, :, valid[prevlayer], curlayer] += triangles[:, :, 2:3] * Q_prev
S[valid[prevlayer], curlayer] += S_prev
# Actually only need to cumsum S[:, valid[prevlayer], curlayer], but it's faster
# when done in-place for the whole array
numpy.cumsum(Q, axis=1, out=Q)
numer = (volumes[:, None] * Q[:, 2, valid[curlayer], curlayer]).sum(axis=0)
denom = S[valid[curlayer], curlayer] * (c + 1) * (c + 2) * (c + 3)
moment_list.append( (numer / denom).ravel())
prevlayer, curlayer = curlayer, prevlayer
return numpy.hstack(moment_list)

105
adze/shapes.py Normal file
View file

@ -0,0 +1,105 @@
from typing import List
import numpy
from numpy.linalg import norm
from . import poly_t, plane_t
def build_tetrahedron(vertices: numpy.ndarray) -> poly_t:
'''
Build a Schelegel-representation tetrahedron.
:param vertices: 4x3 array, representing the vertex coordinates.
:return: Tetrahedron in Schelgel representation.
'''
poly = {
'vertices': numpy.array(vertices, dtype=float),
'neighbors': numpy.array((
(1, 3, 2),
(2, 3, 0),
(0, 3, 1),
(1, 2, 0)), dtype=int),
}
return poly
def build_box(box_corners: numpy.ndarray) -> poly_t:
'''
Build a Schelegel-representation box.
:param box_corners: 2x3 array, representing the vertex coordinates of
two diagonally-opposite corners of the box.
:return: Box in Schelgel representation.
'''
neighbors = [
[1, 4, 3],
[2, 5, 0],
[3, 6, 1],
[0, 7, 2],
[7, 0, 5],
[4, 1, 6],
[5, 2, 7],
[6, 3, 4],
]
vertices = [
[box_corners[0, 0], box_corners[0, 1], box_corners[0, 2]],
[box_corners[1, 0], box_corners[0, 1], box_corners[0, 2]],
[box_corners[1, 0], box_corners[1, 1], box_corners[0, 2]],
[box_corners[0, 0], box_corners[1, 1], box_corners[0, 2]],
[box_corners[0, 0], box_corners[0, 1], box_corners[1, 2]],
[box_corners[1, 0], box_corners[0, 1], box_corners[1, 2]],
[box_corners[1, 0], box_corners[1, 1], box_corners[1, 2]],
[box_corners[0, 0], box_corners[1, 1], box_corners[1, 2]],
]
return {
'neighbors': numpy.array(neighbors, dtype=int),
'vertices': numpy.array(vertices, dtype=float),
}
def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]:
'''
Construct a list of planes corresponding to the faces of a box.
:param box_corners: 2x3 array, representing the vertex coordinates of
two diagonally-opposite corners of the box.
:return: List of planes, facing inwards.
'''
box_corners = numpy.array(box_corners)
faces = [
(( 0, 0, 1), -box_corners[0, 2]),
(( 0, 0, -1), box_corners[1, 2]),
(( 0, 1, 0), -box_corners[0, 1]),
(( 0, -1, 0), box_corners[1, 1]),
(( 1, 0, 0), -box_corners[0, 0]),
((-1, 0, 0), box_corners[1, 0]),
]
return [(numpy.array(n), d) for n, d in faces]
def planes_from_tetrahedron(vertices: numpy.ndarray) -> List[plane_t]:
'''
Construct a list of planes corresponding to the faces of a tetrahedron.
:param vertices: 4x3 array, representing the vertex coordinates.
:return: List of planes, facing inwards.
'''
verts = numpy.array(vertices, dtype=float)
vset_inds = numpy.array((
[3, 1, 2, 1],
[2, 0, 3, 2],
[1, 3, 0, 3],
[0, 2, 1, 0]))
vertsets = numpy.moveaxis(numpy.dstack(verts[v] for v in vset_inds), 2, 0)
ab = vertsets[:, 0, :] - vertsets[:, 1, :]
cd = vertsets[:, 2, :] - vertsets[:, 3, :]
n = numpy.cross(ab, cd)
n /= norm(n, axis=1)[:, None]
centers = numpy.sum(vertsets[:, :3, :], axis=1) / 3
d = -numpy.sum(n * centers, axis=1)
return [plane for plane in zip(n, d)]

194
adze/split.py Normal file
View file

@ -0,0 +1,194 @@
import numpy
from . import poly_t, plane_t
from .util import build_empty, _get_map
try:
# Check if running with line_profiler
profile
except NameError:
def profile(f):
return f
def clip(poly: poly_t, plane: plane_t) -> poly_t:
'''
Clip a polyhedron with a plane, keeping only the part which is on
the same side as the plane's normal vector.
This function is equivalent to calling split(poly, plane, same_only=True).
:param poly: Polyhedron to clip, in chiral Schlegel representation.
:param plane: Plane to clip against.
:return: Clipped polyhedron.
'''
left_poly = split(poly, plane, same_only=True)
return left_poly
@profile
def split(poly, plane, same_only: bool = False):
'''
Clip a polyhedron with a plane.
If same_only is False (default), returns the tuple (same_side_poly, other_side_poly),
where same_side_poly is on the same side as the plane's normal vector. Otherwise,
returns only same_side_poly (somewhat faster).
:param poly: Polyhedron to clip, in chiral Schlegel representation.
:param plane: Plane to clip against.
:param same_only: If True, only returns the clipped poly from the same side as the
plane's normal vector. Default False.
:return: (same_side_poly, other_side_poly) if same_only is False (default), otherwise
only returns same_side_poly.
'''
vertices = poly['vertices']
neighbors = poly['neighbors']
num_start = neighbors.shape[0]
dists = plane[1] + (vertices @ plane[0])
left = dists > 0
right = numpy.logical_not(left)
num_left = numpy.count_nonzero(left)
num_right = num_start - num_left
'''
if the poly lies entirely on one side of the plane, just return it
'''
if num_left == 0:
# if all on right or touching plane
ret = build_empty(), poly
return ret[0] if same_only else ret
elif dists.min() >= 0:
# if all on left or touching plane
# Can't reuse 'left' because <= vs <
ret = poly, build_empty()
return ret[0] if same_only else ret
right_inds = numpy.where(right)[0]
next_vertex = neighbors[right_inds, :].ravel()
# remove edges which connect two same-side vertices
far_vertex_left = left[next_vertex]
if not far_vertex_left.any():
'''
No edges cross the plane, but components exist on either side
'''
r2l_edges = numpy.empty((0, 3), dtype=int)
target_edge_inds = numpy.empty((0, 1), dtype=int)
new_vertices = numpy.empty((0, 3), dtype=float)
src_pns = target_edge_inds.copy()
num_new_vertices = 0
rverts = numpy.empty(0, dtype=int)
lverts = rverts.copy()
else:
'''
Some edges cross the plane
'''
# remove edges which don't also touch the left half-plane
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]
num_new_vertices = rverts.size
'''
figure out new vertex positions
'''
d_right = dists[rverts][:, None]
d_left = dists[lverts][:, None]
new_vertices = (d_right * vertices[lverts] - d_left * vertices[rverts]) / (d_right - d_left)
'''
walk to next crossing edge
'''
prev_verts = rverts
cur_verts = lverts
edge_walk_inds = numpy.arange(num_new_vertices)
edge_walk_results = numpy.empty((2, num_new_vertices), dtype=int)
src_pns = None
while cur_verts.size > 0:
# Get the list of our current neighbors, find which one points to the
# vertex we came from, and choose the next (ccw) one
cur_links = neighbors[cur_verts]
row, src_pn = numpy.where(cur_links == prev_verts[:, None])
new_pn = (src_pn + 1) % 3
if src_pns is None:
src_pns = src_pn
next_verts = cur_links[(row, new_pn)]
# Save edges that cross back to right, and remove them from the list of verts
done = right[next_verts]
edge_walk_results[:, edge_walk_inds[done]] = (next_verts[done], cur_verts[done])
# Save the current vertices as previous, and our chosen neighbors as current
not_done = numpy.logical_not(done)
prev_verts = cur_verts[not_done]
cur_verts = next_verts[not_done]
edge_walk_inds = edge_walk_inds[not_done]
# now edge_walk_results is list of [[target clipped adjacent vertex, target connected vertex], ...]
# figure out the index of each target edge using row-wise _get_map
dims = [num_start, num_start]
a1d = numpy.ravel_multi_index((rverts, lverts), dims)
b1d = numpy.ravel_multi_index(edge_walk_results, dims)
target_edge_inds = _get_map(a1d, b1d)
'''
map from old vertex ind to new
'''
ind_map_left = numpy.zeros(num_start, dtype=int)
# current side vertices get new (equal or lower) indices from delete operation, remain in same order
ind_map_left[left] = numpy.arange(num_left)
# Hops across the boundary depend on (origin, destination) pair since that determines final vertex
# use argsort to generate link from target edge to current edge
target_order = numpy.argsort(target_edge_inds)
new_neighbors_left = numpy.column_stack((
ind_map_left[lverts], # update left vertices based on new indexing
target_order + num_left, # new vertex indices are same as edge indices + offset
target_edge_inds + num_left))
old_vertices_left = vertices[left]
old_neighbors_left = neighbors.copy()
old_neighbors_left[left] = ind_map_left[old_neighbors_left[left]] # map vertices on left side, wrongly mapping any right-side vertices to 0
old_neighbors_left[(lverts, src_pns)] = num_left + numpy.arange(num_new_vertices)
old_neighbors_left = old_neighbors_left[left]
left_poly = {
'vertices': numpy.vstack((old_vertices_left, new_vertices)),
'neighbors': numpy.vstack((old_neighbors_left, new_neighbors_left)),
}
if same_only:
return left_poly
ind_map_right = numpy.zeros(num_start, dtype=int)
ind_map_right[right] = numpy.arange(num_right)
new_neighbors_right = numpy.column_stack((
ind_map_right[rverts], # update right vertices based on new indexing
target_edge_inds + num_right, # new vertex indices are same as edge indices + offset
target_order + num_right))
old_vertices_right = vertices[right]
old_neighbors_right = neighbors.copy()
old_neighbors_right[right] = ind_map_right[old_neighbors_right[right]]
old_neighbors_right[(rverts, rl_edge_inds)] = num_right + numpy.arange(num_new_vertices)
old_neighbors_right = old_neighbors_right[right]
right_poly = {
'vertices': numpy.vstack((old_vertices_right, new_vertices)),
'neighbors': numpy.vstack((old_neighbors_right, new_neighbors_right)),
}
return left_poly, right_poly

65
adze/transform.py Normal file
View file

@ -0,0 +1,65 @@
import numpy
from numpy import sin, cos
from . import poly_t, plane_t
def rotate(poly: poly_t, theta: float, axis: int) -> poly_t:
'''
Rotate the polyhedron around an axis.
:param poly: Polyhedron to rotate. Changed in-place.
:param theta: Angle to rotate by (radians).
:param axis: Axis to rotate around (0-2).
:return: Rotated polyhedron.
Data is altered in-place but also returned for convenience.
'''
s, c = sin(theta), cos(theta)
v0 = poly['vertices'][:, axis - 2].copy()
v1 = poly['vertices'][:, axis - 1]
poly['vertices'][:, axis - 2] = c * v0 - s * v1
poly['vertices'][:, axis - 1] = s * v1 + c * v0
return poly
def translate(poly: poly_t, shift: numpy.ndarray) -> poly_t:
'''
Translate the polyhedron by a vector.
:param poly: Polyhedron to translate. Changed in-place.
:param shift: Vector to translate by.
:return: Translated polyhedron.
Data is altered in-place but also returned for convenience.
'''
poly['vertices'] += shift
return poly
def scale(poly: poly_t, factor: numpy.ndarray or float) -> poly_t:
'''
Scale the polyhedron.
Can scale by a single value, or scale each axis individually
:param poly: Polyhedron to scale. Changed in-place.
:param factor: Scalar or vector to scale by.
:return: Scaled polyhedron.
Data is altered in-place but also returned for convenience.
'''
poly['vertices'] *= factor
return poly
def affine(poly: poly_t, xform: numpy.ndarray) -> poly_t:
'''
Perform arbitrary affine trasnformation on the polyhedron.
:param poly: Polyhedron to transform. Changed in-place.
:param xform: 4x4 affine transformation matrix.
:return: Transformed polyhedron.
Data is altered in-place but also returned for convenience.
'''
mat4x3 = xform[:, :3]
mat4x1 = xform[:, 3]
vh = mat4x3 @ poly['vertices'].T + mat4x1
poly['vertices'][:] = (vh[:3, :] / vh[3, :]).T
return poly

272
adze/util.py Normal file
View file

@ -0,0 +1,272 @@
from typing import Dict, Tuple, List
import numpy
try:
# Check if running with line_profiler
profile
except NameError:
def profile(f):
return f
plane_t = Tuple[numpy.ndarray, float]
poly_t = Dict[str, numpy.ndarray]
def build_empty() -> poly_t:
'''
Build an empty Schlegel representation (containing no vertices).
:return: Empty Schelegel representation.
'''
return {
'vertices': numpy.empty((0, 3), dtype=float),
'neighbors': numpy.empty((0, 3), dtype=int),
}
@profile
def find_components(neighbors: numpy.ndarray) -> numpy.ndarray:
'''
Given an adjacency list, flood-fill to find and label connected components.
:param neighbors: NxM adjacency list. Each of the N vertices is assumed
to have the same number of neighbors, which are specified by their
indices.
:return: 1D ndarray with N entries. Entries are integer labels denoting
which connected component the vertex belongs to.
'''
num_vertices = neighbors.shape[0]
current_component = 1
component = numpy.zeros(num_vertices, dtype=int)
for v_start in range(num_vertices):
if component[v_start] != 0:
continue
verts = numpy.array([v_start], dtype=int)
while verts.size > 0:
component[verts] = current_component
next_verts = numpy.unique(neighbors[verts])
verts = next_verts[component[next_verts] == 0]
current_component += 1
return component - 1
@profile
def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]:
'''
Traverse the Schlegel diagram to find chordless cycles
(i.e., faces of the polyhedron). Assumes 3-vertex-connected
graph with exactly 3 neighbors per vertex. Neighbors are ordered
counter-clockwise.
:param neighbors: Nx3 adjacency list. Neighbors are specified by their
indices.
:return: List of ndarrays, each of which contains the indices in a given
face, starting with the lowest index in the face.
'''
num_verts = neighbors.shape[0]
edge_id = numpy.arange(3 * num_verts)
v_start, nxt_edge = numpy.divmod(edge_id, 3) # arange % 3 is faster than tile
v_current = v_start.copy()
v_next = neighbors[v_current, nxt_edge]
'''
Choose a method for storing the face info based on expected
runtime vs unnecessary memory allocation
'''
if num_verts < 1000:
# ~3n^2 in memory, but much faster in cases where n isn't prohibitively large
faces = numpy.full((3*num_verts, num_verts-1), -1, dtype=int)
faces[:, 0] = v_current
def add_edges(edge_id, v_nxt, k):
faces[edge_id, k] = v_nxt
def cleaned_faces(remove, k):
faces_set = []
for row in faces[~remove, :k]:
faces_set.append(row[row >= 0])
return faces_set
else:
# Alternative approach, less memory-intensive but slower
faces = [[v] for v in v_current]
def add_edges(edge_id, v_nxt, _k):
for i, vn in zip(edge_id, v_nxt):
faces[i].append(vn)
def cleaned_faces(remove, _k):
faces_set = []
for i in numpy.where(~remove)[0]:
faces_set.append(faces[i])
return faces_set
'''
Starting at all vertices, take a step along all edges.
If the vertex index decreases, stop traversal and mark the path for removal.
Otherwise, continue stepping along the _next_ edge each time, until
a) the vertex index decreases (stop and mark for removal)
b) we reach the original vertex (stop, done with this path)
'''
k = 1
mask = v_next > v_current
v = numpy.vstack((edge_id, v_start, v_current, v_next))[:, mask]
remove = numpy.logical_not(mask)
while mask.any():
add_edges(v[0], v[3], k)
prv_edge = (neighbors[v[3], :] == v[2][:, None]).argmax(axis=1)
nxt_edge = (prv_edge + 1) % 3
v[2:4] = v[3], neighbors[v[3], nxt_edge]
remove_mask = v[2] < v[1]
remove[v[0][remove_mask]] = True
mask = numpy.logical_and(v[3] != v[1], ~remove_mask)
v = v[:, mask]
k += 1
return cleaned_faces(remove, k)
@profile
def _get_map(a, b):
'''
Returns m such that a[m] == b
Assumes that all elements appear exactly once in each array
'''
if a.size == 0:
return numpy.array(()), numpy.array(())
sa = a.argsort()
sb = b.argsort()
r = numpy.empty_like(sa)
r[sb] = numpy.arange(sa.size)
return sa[r]
@profile
def _get_map_rows(a, b):
'''
Row-wise _get_map
'''
dims = numpy.maximum(a.max(0), b.max(0)) + 1
a1d = numpy.ravel_multi_index(a.T, dims)
b1d = numpy.ravel_multi_index(b.T, dims)
return _get_map(a1d, b1d)
@profile
def _get_maps(a, b):
'''
Returns m, n such that a[m] == b, b[n] == a
Assumes that all elements appear exactly once in each array
'''
if a.size == 0:
return numpy.array(()), numpy.array(())
sa = a.argsort()
sb = b.argsort()
r = numpy.empty_like(sa)
r[sb] = numpy.arange(sa.size)
m = sa[r]
r[sa] = numpy.arange(sa.size)
n = sb[r]
return m, n
@profile
def _get_maps_rows(a, b):
'''
Row-wise _get_maps
'''
dims = numpy.maximum(a.max(0), b.max(0)) + 1
a1d = numpy.ravel_multi_index(a.T, dims)
b1d = numpy.ravel_multi_index(b.T, dims)
return _get_maps(a1d, b1d)
def _argsort_rows(a):
'''
Row-wise argsort
'''
dims = a.max(0) + 1
a1d = numpy.ravel_multi_index(a.T, dims)
return numpy.argsort(a1d)
def _searchsorted_rows(a, b):
'''
Row-wise searchsorted
'''
dims = numpy.maximum(a.max(0), b.max(0)) + 1
a1d = numpy.ravel_multi_index(a.T, dims)
b1d = numpy.ravel_multi_index(b.T, dims)
return numpy.searchsorted(a1d, b1d)
def check_poly(poly: poly_t, check_connectivity: bool = True):
'''
Verify that the polyhedron
- has no out-of-bounds neighbors
- has no duplicate neighbors
- has exactly 3 edges per vertex
- is 3-vertex-connected (if check_connectivity is True; slow!)
:param poly: Polyhedron to check.
:param check_connectivity: Whether to check for 3-vertex-connectedness.
This is slow! Default True.
:raises: Exception if the polyhedron fails a check
'''
neighbors = poly['neighbors']
vertices = poly['vertices']
num_vertices = vertices.shape[0]
out_of_bounds = numpy.logical_or(neighbors >= vertices.shape[0], neighbors < 0)
if numpy.any(out_of_bounds):
which_vertices = numpy.where(out_of_bounds)[0]
raise Exception(f'Vertices {which_vertices} have out-of-bounds neighbors')
repeated_neighbors = neighbors == numpy.roll(neighbors, 1, axis=1)
if numpy.any(repeated_neighbors):
which_vertices = numpy.where(repeated_neighbors)[0]
raise Exception(f'Vertices {which_vertices} have duplicate neighbors')
vertex_uses = numpy.bincount(neighbors.ravel())
if numpy.any(vertex_uses != 3):
which_vertices = numpy.where(vertex_uses != 3)[0]
raise Exception(f'Vertices {which_vertices} are referenced {vertex_uses[which_vertices]} times,'
' should be exactly 3')
# check for 3-vertex-connectedness (~n^3 because need bfs for each removed vertex pair)
if check_connectivity:
components = find_components(neighbors)
vert_ids = numpy.arange(num_vertices, dtype=int)
visited = numpy.empty(num_vertices, dtype=bool)
for part_id in numpy.unique(components):
part_mask = components == part_id
part_verts = vert_ids[part_mask]
vcs = set(part_verts[:3])
for ia in range(part_verts.size):
va = part_verts[ia]
for vb in part_verts[ia + 1:]:
# pick vc != {va, vb}
vc = (vcs - set((va, vb))).pop()
# flood-fill from vc without passing through va, vb
visited.fill(False)
visited[[va, vb]] = True
nums = numpy.array([vc], dtype=int)
while nums.size > 0:
visited[nums] = True
new_nums = numpy.unique(neighbors[nums])
nums = new_nums[~visited[new_nums]]
# Make sure we touched all vertices in the component
if not visited[components == part_id].all():
raise Exception('Vertex graph is not 3-vertex-connected')

101
adze/voxel.py Normal file
View file

@ -0,0 +1,101 @@
from typing import Tuple, List
import numpy
from . import poly_t, plane_t
from .split import split, clip
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],
include_outside: bool = False,
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] (include_outside False) or
[X+1, Y+1, Z+1, N] (include_outside True), where N is the number of moments
corresponding to the requested order. If include_outside is true, the outer borders
of the first three dimensions of the output correspond to portions of the polyhedron
that protruded outside 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 include_outside: Whether to include cells corresponding to portions of the
polyhedron that fall outside of the grid. Default False.
:param order: Polynomial order of moments to calculate. Default 0.
:return: (X - 1) x (Y - 1) x (Z - 1) x N (include_outside False) or
(X + 1) x (Y + 1) x (Z + 1) x N (include_outside True) ndarray.
If include_outside is true, the outer borders of the first three dimensions
correspond to portions of the polyhedron that protruded outside the outermost
planes. N is number_of_moments(order).
'''
planes = [numpy.array(p) for p in planes]
num_planes = numpy.array([e.size for e in planes], dtype=int)
if (num_planes < 2).any():
# TODO raw exception
raise Exception(f'Need at least two planes per dimension. Got {num_planes} planes.')
if include_outside:
grid_shape = num_planes + 1
if not include_outside:
grid_shape = num_planes - 1
for face in planes_from_box([[p[0] for p in planes],
[p[-1] for p in planes]]):
poly = clip(poly, face)
grid = numpy.zeros((*grid_shape, number_of_moments(order)), dtype=float)
if poly['vertices'].shape[0] == 0:
return 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
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
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 grid