mostly comments, but broke something

This commit is contained in:
jan 2018-03-28 14:58:38 -07:00
commit 3f8b9bef06
8 changed files with 366 additions and 127 deletions

View file

@ -1,4 +1,7 @@
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

View file

@ -1,6 +1,8 @@
from typing import List, Dict
import numpy
from numpy.linalg import norm
from . import poly_t, plane_t
from .util import _get_map, find_components, find_faces
try:
@ -11,7 +13,18 @@ except NameError:
return f
def planes_from_boundary(vertices, faces):
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]
@ -26,8 +39,17 @@ def planes_from_boundary(vertices, faces):
@profile
def build_polyhedron(in_vertices, faces):
in_vertices = numpy.array(in_vertices, dtype=float)
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))
@ -36,10 +58,9 @@ def build_polyhedron(in_vertices, faces):
raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges')
if edges_per_vertex.max() == 3:
# Don't need to duplicate any vertices to make 3-connected graph
vertices = in_vertices
# Link up the vertices
'''
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
@ -61,7 +82,7 @@ def build_polyhedron(in_vertices, faces):
# 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
# 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]
@ -130,33 +151,32 @@ def build_polyhedron(in_vertices, faces):
the links to reflect their removal.
'''
# starting row for each original vertex
vstart = numpy.roll(numpy.cumsum(edges_per_vertex), 1)
vstart[0] = 0
start = numpy.roll(numpy.cumsum(edges_per_vertex), 1)
start[0] = 0
# number of input vertices (v) and duplicates (d)
num_v = in_vertices.shape[0]
num_vertices = vertices.shape[0]
num_duplicates = edges_per_vertex.sum()
# Linkage and aux array
neighbors = numpy.empty((num_duplicates, 3), dtype=int)
util = numpy.zeros(num_duplicates, 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 = vstart[face] + util[face]
v_inds = start[face] + num_filled_rows[face]
neighbors[v_inds, 1] = numpy.roll(face, -1)
neighbors[v_inds, 2] = numpy.roll(face, 1)
util[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_v):
v0 = vstart[v]
for v in range(num_vertices):
v0 = start[v]
s = slice(v0, v0 + edges_per_vertex[v])
m, n = _get_map(neighbors[s, 2], neighbors[s, 1])
neighbors[s, 0] = n + v0
@ -177,8 +197,8 @@ def build_polyhedron(in_vertices, faces):
src_mask = numpy.empty(num_duplicates, dtype=bool)
dst_mask = numpy.empty(num_duplicates, dtype=bool)
for v in range(num_v):
s = vstart[v]
for v in range(num_vertices):
s = start[v]
e = s + edges_per_vertex[v]
src_mask.fill(False)
@ -199,20 +219,20 @@ def build_polyhedron(in_vertices, faces):
'''
Remove first two duplicates of each vertex (they aren't needed)
'''
nxt, third, prv = neighbors[vstart, :].T
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[vstart] = prv # first maps to previous
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[vstart] = 0 # if we mapped from a first vertex to its previous, set to 'next'
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
# Map 'third' to where it should point to. 'dm'~'dest_map'
dm_third = dest_map[third]
dm_nxt_third = dest_map[nxt_third]
@ -223,31 +243,41 @@ def build_polyhedron(in_vertices, faces):
neighbors[dm_nxt_third, back_map[nxt_third]] = nxt_nxt # next-third's backreference points to next-next
# Mark for removal
util.fill(0)
util[vstart] = 1
util[nxt] = 1
keep_map = num_filled_rows # reuse to avoid reallocating
keep_map.fill(1)
keep_map[start] = 0
keep_map[nxt] = 0
neighbors = neighbors[util == 0]
util[util == 0] = numpy.arange(neighbors.shape[0])
neighbors[:] = util[neighbors]
neighbors = neighbors[keep_map != 0]
keep_map[keep_map != 0] = numpy.arange(neighbors.shape[0])
neighbors[:] = keep_map[neighbors]
vertices = numpy.repeat(in_vertices, edges_per_vertex - 2, axis=0)
final_vertices = numpy.repeat(vertices, edges_per_vertex - 2, axis=0)
return {'vertices': vertices, 'neighbors': neighbors}
return {'vertices': final_vertices, 'neighbors': neighbors}
@profile
def boundary_from_poly(poly):
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']
owner_components = find_components(neighbors)
owning_component = find_components(neighbors)
faces = find_faces(neighbors)
num_components = owner_components.max() + 1
num_components = owning_component.max() + 1
components = [[] for _ in range(num_components)]
for face in faces:
component_ind = owner_components[face[0]]
component_ind = owning_component[face[0]]
components[component_ind].append(face)
unique_verts, unique_vertex_map = numpy.unique(vertices, axis=0, return_inverse=True)
@ -255,7 +285,7 @@ def boundary_from_poly(poly):
boundary_map = numpy.empty(vertices.shape[0], dtype=int)
boundaries = []
for i, component in enumerate(components):
mask = owner_components == i
mask = owning_component == i
umask = unique_vertex_map[mask]
used_uverts = numpy.unique(umask)

View file

@ -1,6 +1,7 @@
from typing import Dict, Tuple
import numpy
from . import poly_t, plane_t
from .util import find_faces
try:
@ -11,56 +12,88 @@ except NameError:
return f
def number_of_moments(order):
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):
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_order):
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]
moments = numpy.zeros(number_of_moments(poly_order), dtype=float)
moments = numpy.zeros(number_of_moments(order), dtype=float)
if num_verts == 0:
return moments
'''
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 one broadcasts
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)
moments[0] = volumes.sum() / 6
if order == 0:
return moments
'''
Iteratively calculate higher-order moments, as per Koehl (2012).
'''
prevlayer, curlayer = 0, 1
S = numpy.zeros((3, poly_order + 1, poly_order + 1, 2), dtype=float)
inds = numpy.arange(poly_order + 1)
S = numpy.zeros((3, order + 1, order + 1, 2), dtype=float)
inds = numpy.arange(order + 1)
mx, my = numpy.meshgrid(inds, inds, indexing='ij')
valid = numpy.zeros((2, poly_order + 1, poly_order + 1), dtype=bool)
cropped = numpy.zeros((poly_order + 1, poly_order + 1), dtype=bool)
valid = numpy.zeros((2, order + 1, order + 1), dtype=bool)
cropped = numpy.zeros((order + 1, order + 1), dtype=bool)
for i, vecs in enumerate(triangles):
S[:, 0, 0, prevlayer] = 1
valid[prevlayer, :, :] = False
valid[prevlayer, 0, 0] = True
m = 1
for c in range(1, poly_order+1):
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()
@ -87,7 +120,7 @@ def get_moments(poly, poly_order):
m = 1
valid[prevlayer, :, :] = False
valid[prevlayer, 0, 0] = True
for c in range(1, poly_order+1):
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()

View file

@ -1,8 +1,17 @@
from typing import List
import numpy
from numpy.linalg import norm
from . import poly_t, plane_t
def build_tetrahedron(vertices: numpy.ndarray):
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((
@ -14,7 +23,14 @@ def build_tetrahedron(vertices: numpy.ndarray):
return poly
def build_box(rbounds):
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],
@ -27,14 +43,14 @@ def build_box(rbounds):
]
vertices = [
[rbounds[0, 0], rbounds[0, 1], rbounds[0, 2]],
[rbounds[1, 0], rbounds[0, 1], rbounds[0, 2]],
[rbounds[1, 0], rbounds[1, 1], rbounds[0, 2]],
[rbounds[0, 0], rbounds[1, 1], rbounds[0, 2]],
[rbounds[0, 0], rbounds[0, 1], rbounds[1, 2]],
[rbounds[1, 0], rbounds[0, 1], rbounds[1, 2]],
[rbounds[1, 0], rbounds[1, 1], rbounds[1, 2]],
[rbounds[0, 0], rbounds[1, 1], rbounds[1, 2]],
[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 {
@ -43,20 +59,33 @@ def build_box(rbounds):
}
def planes_from_box(rbounds: numpy.ndarray):
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.
'''
faces = [
(( 0, 0, 1), -rbounds[0, 2]),
(( 0, 0, -1), rbounds[1, 2]),
(( 0, 1, 0), -rbounds[0, 1]),
(( 0, -1, 0), rbounds[1, 1]),
(( 1, 0, 0), -rbounds[0, 0]),
((-1, 0, 0), rbounds[1, 0]),
(( 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):
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],
@ -73,4 +102,3 @@ def planes_from_tetrahedron(vertices: numpy.ndarray):
d = -numpy.sum(n * centers, axis=1)
return [plane for plane in zip(n, d)]

View file

@ -1,7 +1,7 @@
from typing import Dict, Tuple
import numpy
from .util import _searchsorted_rows, _argsort_rows
from . import poly_t, plane_t
from .util import _searchsorted_rows, _argsort_rows, build_empty
try:
# Check if running with line_profiler
@ -11,20 +11,37 @@ except NameError:
return f
def build_empty_poly() -> Dict:
return {
'vertices': numpy.empty((0, 3), dtype=float),
'neighbors': numpy.empty((0, 3), dtype=int),
}
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).
def clip(poly, plane):
left_poly = split(poly, plane, left_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, left_only: bool = False):
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 = poly['vertices'].shape[0]
@ -36,17 +53,19 @@ def split(poly, plane, left_only: bool = False):
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 the poly lies entirely on one side of the plane, just return it
'''
ret = None
if num_left == 0:
# if all on right or touching plane
ret = build_empty_poly(), poly
ret = build_empty(), poly
elif dists.min() >= 0:
# if all on left or touching plane
# Can't reuse 'left' because <= vs <
ret = poly, build_empty_poly()
ret = poly, build_empty()
if ret is not None:
return ret[0] if left_only else ret
return ret[0] if same_only else ret
right_inds = numpy.where(right)[0]
next_vertex = neighbors[right_inds, :].ravel()
@ -55,7 +74,9 @@ def split(poly, plane, left_only: bool = False):
far_vertex_left = left[next_vertex]
if not far_vertex_left.any():
# No edges cross, but components on either side
'''
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)
@ -64,6 +85,9 @@ def split(poly, plane, left_only: bool = False):
re = numpy.empty(0, dtype=int)
le = re.copy()
else:
'''
Some edges cross the plane
'''
right_inds3 = numpy.repeat(right_inds, 3)
pnbr_inds = numpy.arange(3 * num_right) % 3
@ -78,7 +102,9 @@ def split(poly, plane, left_only: bool = False):
num_new_vertices = r2l_edges.shape[0]
# walk counter-clockwise to next crossing edge
'''
walk to next crossing edge
'''
prev_verts = r2l_edges[:, 0]
cur_verts = r2l_edges[:, 1]
edge_walk_inds = numpy.arange(num_new_vertices)
@ -96,12 +122,13 @@ def split(poly, plane, left_only: bool = False):
next_verts = cur_links[(row, new_pn)]
# Save the current vertices as previous, and our chosen neighbors as current
# Save edges that cross back to right, and remove them from the list of verts
done = right[next_verts]
not_done = numpy.logical_not(done)
edge_walk_results[edge_walk_inds[done], 1] = cur_verts[done]
edge_walk_results[edge_walk_inds[done], 0] = next_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]
@ -144,7 +171,7 @@ def split(poly, plane, left_only: bool = False):
'neighbors': numpy.vstack((old_neighbors_left, new_neighbors_left)),
}
if left_only:
if same_only:
return left_poly
ind_map_right = numpy.zeros(num_start, dtype=int)

View file

@ -1,31 +1,65 @@
import numpy
from numpy import sin, cos
from . import poly_t, plane_t
def rotate(poly, theta: float, axis: int):
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].copy()
poly['vertices'][:, axis - 2] = c * v0 - s * v1
poly['vertices'][:, axis - 1] = s * v1 + c * v0
return poly
def translate(poly, shift):
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, factor):
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 shear(poly, factor: float, axb: int, axs: int):
poly['vertices'][:, axb] += factor * poly['vertices'][:, axs]
def affine(poly: poly_t, xform: numpy.ndarray) -> poly_t:
'''
Perform arbitrary affine trasnformation on the polyhedron.
def affine(poly, mat):
mat4x3 = mat[:, :3]
mat4x1 = mat[:, 3]
: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, :]
poly['vertices'][:] = (vh[:3, :] / vh[3, :]).T
return poly

View file

@ -1,3 +1,4 @@
from typing import Dict, Tuple, List
import numpy
try:
@ -8,8 +9,33 @@ except NameError:
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):
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)
@ -28,27 +54,39 @@ def find_components(neighbors):
@profile
def find_faces(neighbors: numpy.ndarray):
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)
nxt_edge = numpy.arange(num_verts * 3) % 3
vstart = edge_id // 3
vcur = vstart.copy()
vnext = neighbors[vcur, nxt_edge]
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]
mask = vstart # dummy for loop init, could use numpy.array([True]) instead
mask = v_start # dummy for loop init, could use numpy.array([True]) instead
remove = numpy.zeros_like(edge_id, dtype=bool)
'''
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] = vcur
faces[:, 0] = v_current
def add_edges(edge_id, vnext, k):
faces[edge_id, k] = vnext
def add_edges(edge_id, v_nxt, k):
faces[edge_id, k] = v_nxt
def cleaned_faces(remove, k):
faces_set = []
@ -56,11 +94,11 @@ def find_faces(neighbors: numpy.ndarray):
faces_set.append(row[row >= 0])
return faces_set
else:
# Alternative approach, less memory-intensive buy slower
faces = [[v] for v in vcur]
# Alternative approach, less memory-intensive but slower
faces = [[v] for v in v_current]
def add_edges(edge_id, vnext, _k):
for i, vn in zip(edge_id, vnext):
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):
@ -69,8 +107,17 @@ def find_faces(neighbors: numpy.ndarray):
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
v = numpy.vstack((edge_id, vstart, vcur, vnext))
#init_mask = v_next > v_current
#v = numpy.vstack((edge_id, v_start, v_current, v_next))[:, init_mask]
v = numpy.vstack((edge_id, v_start, v_current, v_next))
while mask.any():
add_edges(v[0], v[3], k)
@ -89,8 +136,10 @@ def find_faces(neighbors: numpy.ndarray):
def _get_map(a, b):
# Assume all elements appear exactly once in each array
# Returns m, n such that a[m] == b, b[n] == a
'''
Returns m, n such that a[m] == b, b[n] == a
Assumes that all elements appear exactly once in each array
'''
assert(a.size == b.size)
if a.size == 0:
return numpy.array(()), numpy.array(())
@ -104,12 +153,18 @@ def _get_map(a, b):
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 _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)
@ -117,13 +172,28 @@ def _get_map_rows(a, b):
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, check_connectivity=True) -> bool:
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]
@ -174,4 +244,3 @@ def check_poly(poly, check_connectivity=True) -> bool:
# 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')
return True

View file

@ -1,5 +1,7 @@
from typing import Tuple
import numpy
from . import poly_t, plane_t
from .split import split
from .moments import get_moments, number_of_moments
@ -12,12 +14,21 @@ except NameError:
@profile
def voxelize(poly, d, box=None, poly_order=0):
def voxelize(poly: poly_t,
d: numpy.ndarray,
box: numpy.ndarray = None,
order: int = 0
) -> numpy.ndarray:
'''
Voxelize a Schelegel-representation polyhedron
'''
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(poly_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():
return dest_grid
@ -37,7 +48,7 @@ def voxelize(poly, d, box=None, poly_order=0):
# Base case 2: calculate moments for single voxel
if max_dist == 1:
moments = get_moments(c_poly, poly_order)
moments = get_moments(c_poly, order)
offset = (c_box[0] - box[0])
dest_grid[offset[0], offset[1], offset[2], :] += moments
continue
@ -59,13 +70,17 @@ def voxelize(poly, d, box=None, poly_order=0):
return dest_grid
def get_box(poly, d):
def get_box(poly: poly_t, d: numpy.ndarray) -> numpy.ndarray:
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, box, clampbox, d):
def clamp_box(poly: poly_t,
box: numpy.ndarray,
clampbox: numpy.ndarray,
d: numpy.ndarray
) -> Tuple[poly_t, numpy.ndarray]:
faces = box_faces_from_verts(clampbox)
for face in faces:
poly = clip(poly, face)