adze/adze/util.py

426 lines
14 KiB
Python
Raw Normal View History

from typing import TYPE_CHECKING
from collections.abc import Sequence
2022-08-18 23:49:48 -07:00
import numpy
from numpy.typing import NDArray
if TYPE_CHECKING:
import stl
2018-03-20 15:10:45 -07:00
2024-07-31 22:38:24 -07:00
plane_t = tuple[NDArray[numpy.floating], float | numpy.floating]
2024-07-30 23:45:47 -07:00
poly_t = dict[str, NDArray]
2018-03-28 14:58:38 -07:00
class AdzeError(Exception):
""" Custom error for Adze """
pass
2018-03-28 14:58:38 -07:00
def build_empty() -> poly_t:
2024-07-30 23:46:21 -07:00
"""
2018-03-28 14:58:38 -07:00
Build an empty Schlegel representation (containing no vertices).
2021-02-07 19:28:37 -08:00
Returns:
Empty Schelegel representation.
2024-07-30 23:46:21 -07:00
"""
2018-03-28 14:58:38 -07:00
return {
'vertices': numpy.empty((0, 3), dtype=float),
'neighbors': numpy.empty((0, 3), dtype=int),
}
2026-03-07 07:08:21 -08:00
def merge_polyhedra(polys: Sequence[poly_t]) -> poly_t:
"""
Merge multiple polyhedra into a single representation.
Args:
polys: Sequence of polyhedra to merge.
Returns:
A single polyhedron containing all input polyhedra as separate components.
"""
if not polys:
return build_empty()
valid_polys = [p for p in polys if p['vertices'].shape[0] > 0]
if not valid_polys:
return build_empty()
all_vertices = numpy.vstack([p['vertices'] for p in valid_polys])
all_neighbors = []
offset = 0
for p in valid_polys:
all_neighbors.append(p['neighbors'] + offset)
offset += p['vertices'].shape[0]
return {
'vertices': all_vertices,
'neighbors': numpy.vstack(all_neighbors),
}
2024-07-30 23:45:47 -07:00
def find_components(neighbors: NDArray[numpy.integer]) -> NDArray[numpy.integer]:
"""
2018-03-28 14:58:38 -07:00
Given an adjacency list, flood-fill to find and label connected components.
2021-02-07 19:28:37 -08:00
Args:
neighbors: NxM adjacency list. Each of the N vertices is assumed
to have the same number of neighbors, which are specified by their
indices.
Returns:
1D ndarray with N entries. Entries are integer labels denoting
2018-03-28 14:58:38 -07:00
which connected component the vertex belongs to.
2024-07-30 23:45:47 -07:00
"""
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
2024-07-31 22:38:24 -07:00
def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.intp]]:
2024-07-30 23:45:47 -07:00
"""
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.
2021-02-07 19:28:37 -08:00
Args:
neighbors: Nx3 adjacency list. Neighbors are specified by their
indices.
Returns:
List of ndarrays, each of which contains the indices in a given
2018-03-28 14:58:38 -07:00
face, starting with the lowest index in the face.
2024-07-30 23:45:47 -07:00
"""
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
2024-07-30 23:45:47 -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
2024-07-30 23:45:47 -07:00
"""
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
2024-07-31 22:38:24 -07:00
faces_arr = numpy.full((3 * num_verts, num_verts - 1), -1, dtype=int)
faces_arr[:, 0] = v_current
def add_edges(edge_id: NDArray[numpy.intp], v_nxt: NDArray[numpy.intp], kk: int) -> None:
2024-07-31 22:38:24 -07:00
faces_arr[edge_id, kk] = v_nxt
2018-03-21 12:55:29 -07:00
def cleaned_faces(remove: NDArray[numpy.int8], kk: int) -> list[NDArray[numpy.intp]]:
2018-03-21 12:55:29 -07:00
faces_set = []
2024-07-31 22:38:24 -07:00
for row in faces_arr[~remove, :kk]:
2018-03-21 12:55:29 -07:00
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
2024-07-31 22:38:24 -07:00
faces_list = [[vv] for vv in v_current]
2018-03-21 12:55:29 -07:00
def add_edges(edge_id: NDArray[numpy.intp], v_nxt: NDArray[numpy.intp], kk: int) -> None: # noqa: ARG001
for ii, vn in zip(edge_id, v_nxt, strict=True):
2024-07-31 22:38:24 -07:00
faces_list[ii].append(vn)
2018-03-21 12:55:29 -07:00
def cleaned_faces(remove: NDArray[numpy.int8], kk: int) -> list[NDArray[numpy.intp]]: # noqa: ARG001
2018-03-21 12:55:29 -07:00
faces_set = []
for ii in numpy.where(~remove)[0]:
2024-07-31 22:38:24 -07:00
faces_set.append(numpy.asarray(faces_list[ii], dtype=numpy.intp))
2018-03-21 12:55:29 -07:00
return faces_set
2024-07-30 23:46:21 -07:00
"""
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)
2024-07-30 23:46:21 -07:00
"""
kk = 1
2018-04-03 15:43:11 -07:00
mask = v_next > v_current
vv = numpy.vstack((edge_id, v_start, v_current, v_next))[:, mask]
2018-04-03 15:43:11 -07:00
remove = numpy.logical_not(mask)
2018-03-20 15:10:45 -07:00
while mask.any():
add_edges(vv[0], vv[3], kk)
2018-03-20 15:10:45 -07:00
prv_edge = (neighbors[vv[3], :] == vv[2][:, None]).argmax(axis=1)
2018-03-20 15:10:45 -07:00
nxt_edge = (prv_edge + 1) % 3
vv[2:4] = vv[3], neighbors[vv[3], nxt_edge]
2018-03-20 15:10:45 -07:00
remove_mask = vv[2] < vv[1]
remove[vv[0][remove_mask]] = True
2018-03-20 15:10:45 -07:00
mask = numpy.logical_and(vv[3] != vv[1], ~remove_mask)
vv = vv[:, mask]
kk += 1
return cleaned_faces(remove, kk)
2018-03-20 15:10:45 -07:00
def _get_map(a: NDArray, b: NDArray) -> NDArray[numpy.intp]:
2024-07-30 23:46:21 -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
2024-07-30 23:46:21 -07:00
"""
2018-03-20 15:10:45 -07:00
if a.size == 0:
2024-07-31 22:38:24 -07:00
return numpy.array((), dtype=numpy.intp)
2018-03-20 15:10:45 -07:00
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]
def _get_map_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]:
2024-07-30 23:46:21 -07:00
"""
2018-03-28 21:33:16 -07:00
Row-wise _get_map
2024-07-30 23:46:21 -07:00
"""
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) # type: ignore
b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore
2018-03-28 21:33:16 -07:00
return _get_map(a1d, b1d)
2024-07-31 22:38:24 -07:00
def _get_maps(a: NDArray, b: NDArray) -> tuple[NDArray[numpy.intp], NDArray[numpy.intp]]:
2024-07-30 23:46:21 -07:00
"""
2018-03-28 21:33:16 -07:00
Returns m, n such that a[m] == b, b[n] == a
Assumes that all elements appear exactly once in each array
2024-07-30 23:46:21 -07:00
"""
2018-03-28 21:33:16 -07:00
if a.size == 0:
2024-07-31 22:38:24 -07:00
return numpy.array((), dtype=numpy.intp), numpy.array((), dtype=numpy.intp)
2018-03-28 21:33:16 -07:00
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
2024-07-31 22:38:24 -07:00
def _get_maps_rows(a: NDArray, b: NDArray) -> tuple[NDArray[numpy.intp], NDArray[numpy.intp]]:
2024-07-30 23:46:21 -07:00
"""
2018-04-03 15:43:11 -07:00
Row-wise _get_maps
2024-07-30 23:46:21 -07:00
"""
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) # type: ignore
b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore
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: NDArray) -> NDArray[numpy.intp]:
2024-07-30 23:46:21 -07:00
"""
2018-03-28 14:58:38 -07:00
Row-wise argsort
2024-07-30 23:46:21 -07:00
"""
2018-03-20 15:10:45 -07:00
dims = a.max(0) + 1
a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore
2018-03-20 15:10:45 -07:00
return numpy.argsort(a1d)
def _searchsorted_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]:
2024-07-30 23:46:21 -07:00
"""
2018-03-28 14:58:38 -07:00
Row-wise searchsorted
2024-07-30 23:46:21 -07:00
"""
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) # type: ignore
b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore
2018-03-20 15:10:45 -07:00
return numpy.searchsorted(a1d, b1d)
2022-08-19 00:17:49 -07:00
def check_poly(poly: poly_t, check_connectivity: bool = True) -> None:
2024-07-30 23:46:21 -07:00
"""
2018-03-28 14:58:38 -07:00
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!)
2021-02-07 19:28:37 -08:00
Args:
poly: Polyhedron to check.
check_connectivity: Whether to check for 3-vertex-connectedness.
This is slow! Default `True`.
Raises:
AdzeError if the polyhedron fails a check
2024-07-30 23:46:21 -07:00
"""
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 AdzeError(f'Vertices {which_vertices} have out-of-bounds neighbors')
2018-03-20 15:10:45 -07:00
repeated_neighbors = neighbors == numpy.roll(neighbors, 1, axis=1)
if numpy.any(repeated_neighbors):
which_vertices = numpy.where(repeated_neighbors)[0]
raise AdzeError(f'Vertices {which_vertices} have duplicate neighbors')
2018-03-20 15:10:45 -07:00
vertex_uses = numpy.bincount(neighbors.ravel())
if numpy.any(vertex_uses != 3):
which_vertices = numpy.where(vertex_uses != 3)[0]
raise AdzeError(f'Vertices {which_vertices} are referenced {vertex_uses[which_vertices]} times,'
2018-03-20 15:10:45 -07:00
' 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 - {va, vb}).pop()
2018-03-20 15:10:45 -07:00
# 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 AdzeError('Vertex graph is not 3-vertex-connected')
2026-03-07 07:08:36 -08:00
def get_aabb(poly: poly_t) -> tuple[NDArray, NDArray]:
"""
Get the axis-aligned bounding box of a polyhedron.
"""
if poly['vertices'].shape[0] == 0:
return numpy.zeros(3), numpy.zeros(3)
return poly['vertices'].min(axis=0), poly['vertices'].max(axis=0)
2026-03-07 07:09:19 -08:00
def is_inside(poly: poly_t, point: NDArray, atol: float = 1e-12) -> bool:
"""
Determine if a point is inside a polyhedron using ray casting.
"""
vertices = poly['vertices']
if vertices.shape[0] == 0:
return False
# Quick AABB check
vmin, vmax = get_aabb(poly)
if numpy.any(point < vmin - atol) or numpy.any(point > vmax + atol):
return False
neighbors = poly['neighbors']
faces = find_faces(neighbors)
# Decompose into triangles
triangle_fans = []
for face in faces:
ilen = len(face) - 2
t_inds = numpy.empty((ilen, 3), dtype=int)
t_inds[:, 0] = face[0]
t_inds[:, 1] = face[1:-1]
t_inds[:, 2] = face[2:]
triangle_fans.append(vertices[t_inds])
triangles = numpy.vstack(triangle_fans) # [M x 3 x 3]
# Ray casting with a fixed random-looking ray to avoid alignment issues
ray_dir = numpy.array([0.3123, 0.7182, 0.6123])
ray_dir /= numpy.linalg.norm(ray_dir)
# Möller–Trumbore intersection algorithm
v0 = triangles[:, 0, :]
v1 = triangles[:, 1, :]
v2 = triangles[:, 2, :]
edge1 = v1 - v0
edge2 = v2 - v0
h = numpy.cross(ray_dir, edge2)
a = numpy.sum(edge1 * h, axis=1)
# Parallel ray/triangle
mask = numpy.abs(a) > 1e-15
f = 1.0 / a[mask]
s = point - v0[mask]
u = f * numpy.sum(s * h[mask], axis=1)
mask2 = numpy.logical_and(u >= -atol, u <= 1.0 + atol)
q = numpy.cross(s[mask2], edge1[mask][mask2])
v = f[mask2] * numpy.sum(ray_dir * q, axis=1)
mask3 = numpy.logical_and(v >= -atol, u[mask2] + v <= 1.0 + atol)
t = f[mask2][mask3] * numpy.sum(edge2[mask][mask2][mask3] * q[mask3], axis=1)
# Count intersections with t > 0
num_intersections = numpy.count_nonzero(t > atol)
return num_intersections % 2 == 1
def plot_brep(brep: Sequence[dict[str, NDArray]]) -> None:
"""
Plot a boundary representation
"""
from matplotlib import pyplot
from mpl_toolkits import mplot3d
meshes = brep_to_stls(brep)
figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)
scales = []
for mesh in meshes:
coll = mplot3d.art3d.Poly3DCollection(mesh.vectors)
coll.set_edgecolors('black')
axes.add_collection3d(coll)
scales.append(mesh.points.flatten())
scale = numpy.hstack(scales)
axes.auto_scale_xyz(scale, scale, scale)
pyplot.show()
def brep_to_stls(brep: Sequence[dict[str, NDArray]]) -> list['stl.mesh.Mesh']:
import stl
meshes = []
for component in brep:
tri_list = []
for face in component['faces']:
for ii in range(1, len(face) - 1):
tri_list.append([face[0], face[ii], face[ii + 1]])
triangles = numpy.asarray(tri_list, dtype=int)
mm = stl.mesh.Mesh(numpy.empty(triangles.shape[0], dtype=stl.mesh.Mesh.dtype))
for ii, ff in enumerate(triangles):
for jj in range(3):
mm.vectors[ii, jj] = component['vertices'][ff[jj], :]
# mm.save('pyr.stl')
meshes.append(mm)
return meshes