adze/chop/util.py

272 lines
8.5 KiB
Python
Raw Normal View History

2018-03-28 14:58:38 -07:00
from typing import Dict, Tuple, List
2018-03-20 15:10:45 -07:00
import numpy
try:
2018-03-28 10:54:15 -07:00
# Check if running with line_profiler
2018-03-20 15:10:45 -07:00
profile
except NameError:
def profile(f):
return f
2018-03-28 14:58:38 -07:00
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),
}
2018-03-20 15:10:45 -07:00
@profile
2018-03-28 14:58:38 -07:00
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.
'''
2018-03-20 15:10:45 -07:00
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
2018-03-28 14:58:38 -07:00
def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]:
'''
2018-03-28 14:58:38 -07:00
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.
'''
2018-03-20 15:10:45 -07:00
num_verts = neighbors.shape[0]
edge_id = numpy.arange(3 * num_verts)
2018-03-28 14:58:38 -07:00
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]
2018-03-20 15:10:45 -07:00
2018-03-28 14:58:38 -07:00
'''
Choose a method for storing the face info based on expected
runtime vs unnecessary memory allocation
'''
2018-03-21 12:55:29 -07:00
if num_verts < 1000:
2018-03-21 14:41:08 -07:00
# ~3n^2 in memory, but much faster in cases where n isn't prohibitively large
2018-03-21 12:55:29 -07:00
faces = numpy.full((3*num_verts, num_verts-1), -1, dtype=int)
2018-03-28 14:58:38 -07:00
faces[:, 0] = v_current
2018-03-28 14:58:38 -07:00
def add_edges(edge_id, v_nxt, k):
faces[edge_id, k] = v_nxt
2018-03-21 12:55:29 -07:00
2018-03-21 14:41:08 -07:00
def cleaned_faces(remove, k):
2018-03-21 12:55:29 -07:00
faces_set = []
for row in faces[~remove, :k]:
faces_set.append(row[row >= 0])
return faces_set
else:
2018-03-28 14:58:38 -07:00
# Alternative approach, less memory-intensive but slower
faces = [[v] for v in v_current]
2018-03-21 12:55:29 -07:00
2018-03-28 14:58:38 -07:00
def add_edges(edge_id, v_nxt, _k):
for i, vn in zip(edge_id, v_nxt):
2018-03-21 12:55:29 -07:00
faces[i].append(vn)
2018-03-21 14:41:08 -07:00
def cleaned_faces(remove, _k):
2018-03-21 12:55:29 -07:00
faces_set = []
for i in numpy.where(~remove)[0]:
faces_set.append(faces[i])
return faces_set
2018-03-28 14:58:38 -07:00
'''
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
2018-04-03 15:43:11 -07:00
mask = v_next > v_current
v = numpy.vstack((edge_id, v_start, v_current, v_next))[:, mask]
remove = numpy.logical_not(mask)
2018-03-20 15:10:45 -07:00
while mask.any():
2018-03-21 14:41:08 -07:00
add_edges(v[0], v[3], k)
2018-03-20 15:10:45 -07:00
2018-03-21 14:41:08 -07:00
prv_edge = (neighbors[v[3], :] == v[2][:, None]).argmax(axis=1)
2018-03-20 15:10:45 -07:00
nxt_edge = (prv_edge + 1) % 3
2018-03-21 14:41:08 -07:00
v[2:4] = v[3], neighbors[v[3], nxt_edge]
2018-03-20 15:10:45 -07:00
2018-03-21 14:41:08 -07:00
remove_mask = v[2] < v[1]
remove[v[0][remove_mask]] = True
2018-03-20 15:10:45 -07:00
2018-03-21 14:41:08 -07:00
mask = numpy.logical_and(v[3] != v[1], ~remove_mask)
v = v[:, mask]
k += 1
2018-03-21 14:41:08 -07:00
return cleaned_faces(remove, k)
2018-03-20 15:10:45 -07:00
2018-03-28 21:33:16 -07:00
@profile
2018-03-20 15:10:45 -07:00
def _get_map(a, b):
2018-03-28 14:58:38 -07:00
'''
2018-03-28 21:33:16 -07:00
Returns m such that a[m] == b
2018-03-28 14:58:38 -07:00
Assumes that all elements appear exactly once in each array
'''
2018-03-20 15:10:45 -07:00
if a.size == 0:
return numpy.array(()), numpy.array(())
sa = a.argsort()
sb = b.argsort()
2018-03-28 21:33:16 -07:00
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):
'''
2018-04-03 15:43:11 -07:00
Row-wise _get_maps
2018-03-28 21:33:16 -07:00
'''
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)
2018-04-03 15:43:11 -07:00
return _get_maps(a1d, b1d)
2018-03-20 15:10:45 -07:00
def _argsort_rows(a):
2018-03-28 14:58:38 -07:00
'''
Row-wise argsort
'''
2018-03-20 15:10:45 -07:00
dims = a.max(0) + 1
a1d = numpy.ravel_multi_index(a.T, dims)
return numpy.argsort(a1d)
def _searchsorted_rows(a, b):
2018-03-28 14:58:38 -07:00
'''
Row-wise searchsorted
'''
2018-03-20 15:10:45 -07:00
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)
2018-03-28 14:58:38 -07:00
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
'''
2018-03-20 15:10:45 -07:00
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')