diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index c28ab72..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -include README.md -include LICENSE.md diff --git a/README.md b/README.md index 0e60000..79bae52 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# adze +# adze **adze** is a Python package for accurate polyhedron clipping and anti-aliased voxelization. @@ -6,18 +6,18 @@ **Homepage:** https://mpxd.net/code/jan/adze **Capabilities:** - - Clipping or splitting arbitrary polyhedra - - by a plane or a collection of planes (i.e. a convex polyhedron) - - Voxelizing arbitrary polyhedra - - + - Clipping or splitting arbitrary polyhedra by a plane or a collection of planes (i.e. a convex polyhedron). + - Accurate anti-aliased voxelization of arbitrary polyhedra on non-uniform rectangular grids. + - Calculation of polynomial moments (volume, centroid, inertia, etc.) for clipped polyhedra. ## Installation **Dependencies:** -* python 3.5 or newer +* python 3.11 or newer * numpy - +* pytest (optional, testing) +* pytest-benchmark (optional, benchmarking) Install with pip from PyPi (preferred): ```bash @@ -26,30 +26,20 @@ pip install adze Install directly from git repository: ```bash -pip install git+https://mpxd.net/code/jan/adze.git@release +uv pip install git+https://mpxd.net/code/jan/adze.git ``` ## Documentation Most functions and classes are documented inline. +Geometry helper input contracts: +- `build_tetrahedron()` and `planes_from_tetrahedron()` expect tetrahedron vertices in the helper's documented positive winding. +- `build_box()` and `planes_from_box()` expect `box_corners[0]` to be the per-axis minimum and `box_corners[1]` the per-axis maximum. +- `adze.transform.affine()` accepts a general 4x4 homogeneous transform and applies the perspective divide using the fourth row, so projective transforms are supported. + To read the inline help, ```python3 import adze help(adze) help(adze.split) ``` - - -## Examples - -TODO -Read an OASIS file and write it back out: -```python3 - import fatamorgana - - with open('test.oas', 'rb') as f: - layout = fatamorgana.OasisLayout.read(f) - - with open('test_write.oas', 'wb') as f: - layout.write(f) -``` diff --git a/adze/LICENSE.md b/adze/LICENSE.md new file mode 120000 index 0000000..7eabdb1 --- /dev/null +++ b/adze/LICENSE.md @@ -0,0 +1 @@ +../LICENSE.md \ No newline at end of file diff --git a/adze/README.md b/adze/README.md new file mode 120000 index 0000000..32d46ee --- /dev/null +++ b/adze/README.md @@ -0,0 +1 @@ +../README.md \ No newline at end of file diff --git a/adze/__init__.py b/adze/__init__.py index e45d3d7..c34be02 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -1,4 +1,4 @@ -''' +""" adze is a library for accurate polyhedron clipping and anti-aliased voxelization. Written with python + numpy. @@ -38,27 +38,73 @@ Helper functions include -------------------------- -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 +### Internal Representation: The Schlegel Diagram +adze represents 3D shapes (polyhedra) using a specialized graph called a Schlegel +diagram. This format is designed for high-performance geometric calculations. - TODO - This - representation looks like - poly = {'neighbors': ndarray[Px3, int], 'vertices': ndarray[Px3, float]} - where poly['neighbors'] contains +#### Key Features: +- **Exactly Three Neighbors:** Every vertex in the graph is connected to exactly + three other vertices. This "3-regular" property makes algorithms for clipping and + splitting shapes much simpler and more robust. +- **Ordered Adjacency:** For each vertex, the three neighbors are listed in + counter-clockwise order when viewed from outside the shape. This order defines + the "orientation" of the shape's surfaces. +- **Handling Complex Corners:** In real-world shapes, a corner (vertex) might have + more than three edges meeting (e.g., the tip of a pyramid). adze handles this by + creating multiple "copy" vertices at the same physical location, each handling + part of the original corner's connectivity. -''' +#### Data Structure: +Shapes are stored as a dictionary containing two NumPy arrays: +- `poly['vertices']`: An `[N x 3]` array of float coordinates (X, Y, Z). +- `poly['neighbors']`: An `[N x 3]` array of integer indices. + `poly['neighbors'][i, :]` contains the indices of the 3 vertices connected to vertex `i`. -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 +from .util import ( + poly_t as poly_t, + plane_t as plane_t, + AdzeError as AdzeError, + ) +from .split import ( + split as split, + clip as clip, + ) +from .moments import ( + get_volume as get_volume, + get_moments as get_moments, + number_of_moments as number_of_moments, + ) +from .boundary import ( + build_polyhedron as build_polyhedron, + boundary_from_poly as boundary_from_poly, + ) +from .shapes import ( + build_tetrahedron as build_tetrahedron, + build_box as build_box, + planes_from_tetrahedron as planes_from_tetrahedron, + planes_from_box as planes_from_box, + ) +from .voxel import voxelize as voxelize +from .boolean import ( + intersect as intersect, + difference as difference, + union as union, + intersect_convex as intersect_convex, + difference_convex as difference_convex, + union_convex as union_convex, + ) +from .offset import ( + offset as offset, + offset_anisotropic as offset_anisotropic, + smooth as smooth, + opening as opening, + closing as closing, + ) +from .util import is_inside as is_inside + +__author__ = 'Jan Petykiewicz' +__version__ = '0.2' diff --git a/adze/boolean.py b/adze/boolean.py new file mode 100644 index 0000000..340d668 --- /dev/null +++ b/adze/boolean.py @@ -0,0 +1,166 @@ +import numpy +from . import poly_t, plane_t +from .split import clip, split +from .boundary import planes_from_boundary, boundary_from_poly +from .util import merge_polyhedra, build_empty, is_inside, get_aabb + +def intersect_convex(poly_a: poly_t, poly_b: poly_t, atol: float = 1e-12) -> poly_t: + """ + Intersect two polyhedra, assuming poly_b is convex. + """ + breps = boundary_from_poly(poly_b) + + result = poly_a + for brep in breps: + planes = planes_from_boundary(brep['vertices'], brep['faces']) + for plane in planes: + result = clip(result, plane, atol=atol) + if result['vertices'].shape[0] == 0: + return result + + return result + +def difference_convex(poly_a: poly_t, poly_b: poly_t, atol: float = 1e-12) -> poly_t: + """ + Subtract poly_b from poly_a, assuming poly_b is convex. + """ + breps = boundary_from_poly(poly_b) + + components_to_process = [poly_a] + outside_parts = [] + + for brep in breps: + planes = planes_from_boundary(brep['vertices'], brep['faces']) + for plane in planes: + next_to_process = [] + for comp in components_to_process: + in_part, out_part = split(comp, plane, atol=atol) + if out_part['vertices'].shape[0] > 0: + outside_parts.append(out_part) + if in_part['vertices'].shape[0] > 0: + next_to_process.append(in_part) + components_to_process = next_to_process + if not components_to_process: + break + + return merge_polyhedra(outside_parts) + +def union_convex(poly_a: poly_t, poly_b: poly_t, atol: float = 1e-12) -> poly_t: + """ + Union of two polyhedra, assuming poly_b is convex. + """ + a_minus_b = difference_convex(poly_a, poly_b, atol=atol) + return merge_polyhedra([a_minus_b, poly_b]) + +def fragment_poly(poly: poly_t, planes: list[plane_t], atol: float = 1e-12) -> list[poly_t]: + """ + Fragment a polyhedron by splitting it with a list of planes. + """ + fragments = [poly] + for plane in planes: + new_fragments = [] + for frag in fragments: + p_in, p_out = split(frag, plane, atol=atol) + if p_in['vertices'].shape[0] > 0: + new_fragments.append(p_in) + if p_out['vertices'].shape[0] > 0: + new_fragments.append(p_out) + fragments = new_fragments + if not fragments: + break + return fragments + +def _get_poly_planes(poly: poly_t) -> list[plane_t]: + """ Helper to get unique planes from a polyhedron. """ + breps = boundary_from_poly(poly) + all_planes = [] + for brep in breps: + all_planes.extend(planes_from_boundary(brep['vertices'], brep['faces'])) + return all_planes + +def _is_poly_convex(poly: poly_t, atol: float = 1e-12) -> bool: + """ + Check if a polyhedron is convex. + A polyhedron is convex if all vertices are 'inside' every face plane. + """ + planes = _get_poly_planes(poly) + vertices = poly['vertices'] + for n, d in planes: + dists = d + (vertices @ n) + if numpy.any(dists < -atol): + return False + return True + +def intersect(poly_a: poly_t, poly_b: poly_t, atol: float = 1e-12, assume_convex: bool = False) -> poly_t: + """ + General intersection of two polyhedra. + """ + if poly_a['vertices'].shape[0] == 0 or poly_b['vertices'].shape[0] == 0: + return build_empty() + + # Bounding box optimization + amin, amax = get_aabb(poly_a) + bmin, bmax = get_aabb(poly_b) + if numpy.any(amin > bmax + atol) or numpy.any(bmin > amax + atol): + return build_empty() + + if assume_convex or _is_poly_convex(poly_b, atol=atol): + return intersect_convex(poly_a, poly_b, atol=atol) + + # General non-convex algorithm: fragment A by planes of B, keep parts inside B. + planes_b = _get_poly_planes(poly_b) + frags_a = fragment_poly(poly_a, planes_b, atol=atol) + + kept_a = [] + for frag in frags_a: + point = numpy.mean(frag['vertices'], axis=0) + if is_inside(poly_b, point, atol=atol): + kept_a.append(frag) + + return merge_polyhedra(kept_a) + +def difference(poly_a: poly_t, poly_b: poly_t, atol: float = 1e-12, assume_convex: bool = False) -> poly_t: + """ + General difference: poly_a - poly_b + """ + if poly_a['vertices'].shape[0] == 0: + return build_empty() + if poly_b['vertices'].shape[0] == 0: + return poly_a + + # Bounding box optimization + amin, amax = get_aabb(poly_a) + bmin, bmax = get_aabb(poly_b) + if numpy.any(amin > bmax + atol) or numpy.any(bmin > amax + atol): + return poly_a + + if assume_convex or _is_poly_convex(poly_b, atol=atol): + return difference_convex(poly_a, poly_b, atol=atol) + + # General non-convex algorithm: fragment A by planes of B, keep parts outside B. + planes_b = _get_poly_planes(poly_b) + frags_a = fragment_poly(poly_a, planes_b, atol=atol) + + kept_a = [] + for frag in frags_a: + point = numpy.mean(frag['vertices'], axis=0) + if not is_inside(poly_b, point, atol=atol): + kept_a.append(frag) + + return merge_polyhedra(kept_a) + +def union(poly_a: poly_t, poly_b: poly_t, atol: float = 1e-12, assume_convex: bool = False) -> poly_t: + """ + General union: poly_a + poly_b + """ + if poly_a['vertices'].shape[0] == 0: + return poly_b + if poly_b['vertices'].shape[0] == 0: + return poly_a + + if assume_convex or _is_poly_convex(poly_b, atol=atol): + return union_convex(poly_a, poly_b, atol=atol) + + # A union B = (A - B) + B + a_minus_b = difference(poly_a, poly_b, atol=atol) + return merge_polyhedra([a_minus_b, poly_b]) diff --git a/adze/boundary.py b/adze/boundary.py index e9e283f..214aff1 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -1,77 +1,124 @@ -from typing import List, Dict +from typing import Any +from collections.abc import Iterable, Sequence import numpy from numpy.linalg import norm +from numpy.typing import ArrayLike, NDArray 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 +from .util import _get_maps, find_components, find_faces, check_poly, AdzeError -def planes_from_boundary(vertices: numpy.ndarray, - faces: List[numpy.ndarray] - ) -> List[plane_t]: - ''' +def _get_maps_checked(a: NDArray[numpy.integer], b: NDArray[numpy.integer]) -> tuple[NDArray[numpy.intp], NDArray[numpy.intp]]: + if a.size != b.size or not numpy.array_equal(numpy.sort(a), numpy.sort(b)): + raise AdzeError('Faces do not describe a valid closed polyhedron boundary') + return _get_maps(a, b) + + +def planes_from_boundary( + vertices: ArrayLike, + faces: Sequence[ArrayLike] + ) -> 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] + Args: + vertices: Nx3 ndarray specifying the polyhedron's vertex positions. + faces: List of 1d ndarrays. Each ndarray is a list of vertex indices, + specifying a face. - n = numpy.cross(numpy.diff(face_verts, n=1, axis=0), - numpy.diff(face_verts, n=2, axis=0)) - n /= norm(n) + Returns: + List of planes, represented by (normal vector, signed distance to origin) tuples. + """ + vertices = numpy.asarray(vertices, dtype=float) + if vertices.ndim != 2 or vertices.shape[1] != 3: + raise AdzeError(f'Vertices must have shape (N, 3). Got {vertices.shape}') + num_vertices = vertices.shape[0] + afaces = [numpy.asarray(ff) for ff in faces] + planes = [] + for face in afaces: + if face.ndim != 1: + raise AdzeError(f'Faces must be 1-dimensional. Got face with shape {face.shape}') + if face.size < 3: + raise AdzeError('Faces must have at least three vertices') + if numpy.unique(face).size != face.size: + raise AdzeError('Faces may not repeat a vertex index') + if numpy.any(face < 0) or numpy.any(face >= num_vertices): + raise AdzeError('Faces reference vertices outside the provided vertex list') + + face_verts = vertices[face] + rolled_verts = numpy.roll(face_verts, -1, axis=0) + n = numpy.array(( + numpy.sum((face_verts[:, 1] - rolled_verts[:, 1]) * (face_verts[:, 2] + rolled_verts[:, 2])), + numpy.sum((face_verts[:, 2] - rolled_verts[:, 2]) * (face_verts[:, 0] + rolled_verts[:, 0])), + numpy.sum((face_verts[:, 0] - rolled_verts[:, 0]) * (face_verts[:, 1] + rolled_verts[:, 1])), + ), dtype=float) + tolerance = numpy.finfo(float).eps * 64 * max(1.0, float(numpy.abs(face_verts).max())) ** 2 + n_norm = norm(n) + if n_norm <= tolerance: + raise AdzeError('Faces must have non-zero area') + n /= n_norm centroid = numpy.sum(face_verts, axis=0) / len(face) d = -n @ centroid - planes.append(n, d) + 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. +def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t: + """ + Generate a 3-verted-connected Schlegel diagram representation + 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 - ''' + Args: + vertices: Nx3 ndarray specifying the polyhedron's vertex positions. + faces: List of 1d ndarrays. Each ndarray is a list of vertex indices, + specifying a face. + + Returns: + Schelgel-representation polyhedron + """ vertices = numpy.array(vertices, dtype=float) - faces = [numpy.array(face, dtype=int) for face in faces] + if vertices.ndim != 2 or vertices.shape[1] != 3: + raise AdzeError(f'Vertices must have shape (N, 3). Got {vertices.shape}') - edges_per_vertex = numpy.bincount(numpy.hstack(faces)) + afaces = [numpy.array(face, dtype=int) for face in faces] + if not afaces: + raise AdzeError('Need at least one face') + + num_vertices = vertices.shape[0] + for face in afaces: + if face.ndim != 1: + raise AdzeError(f'Faces must be 1-dimensional. Got face with shape {face.shape}') + if face.size < 3: + raise AdzeError('Faces must have at least three vertices') + if numpy.unique(face).size != face.size: + raise AdzeError('Faces may not repeat a vertex index') + if numpy.any(face < 0) or numpy.any(face >= num_vertices): + raise AdzeError('Faces reference vertices outside the provided vertex list') + + edges_per_vertex = numpy.bincount(numpy.hstack(afaces), minlength=num_vertices) + unused_vertices = numpy.where(edges_per_vertex == 0)[0] + if unused_vertices.size: + raise AdzeError(f'Vertices {unused_vertices} are unused by any face') if edges_per_vertex.min() < 3: - raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges') + raise AdzeError(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: + if edges_per_vertex.max() == 3 and all(face.size == 3 for face in afaces): + # + # In this case, we don't need to duplicate any vertices to make a 3-vertex-connected graph + # + neighbors = numpy.full_like(vertices, vertices.size, dtype=int) + for face in afaces: # 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) + has_prev = (neighbor_rows == prev_vert[:, None]).any(axis=1) + has_next = (neighbor_rows == next_vert[:, None]).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. + # Thus, we will never encounter a situation in which prev == next. # If the vertex hasn't been linked to anything yet, set its first two # polyhedron-neighbors to its face-neighbors @@ -86,9 +133,11 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: neighbors[face[has_prev], 2] = next_vert[has_prev] neighbors[face[has_next], 2] = prev_vert[has_next] - return {'vertices': vertices, 'neighbors': neighbors} + poly = {'vertices': vertices, 'neighbors': neighbors} + check_poly(poly, check_connectivity=False) + return poly - ''' + """ 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. @@ -149,44 +198,44 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: 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) - ''' + # + # 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: + for face in afaces: # 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 - ''' + # + # 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]) + m, n = _get_maps_checked(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) - ''' + # + # 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) @@ -198,27 +247,27 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: dst_mask = numpy.empty(num_duplicates, dtype=bool) for v in range(num_vertices): - s = start[v] - e = s + edges_per_vertex[v] + ss = start[v] + ee = ss + edges_per_vertex[v] src_mask.fill(False) - src_mask[e:] = target_vert[e:] == v # find rows which reference us + src_mask[ee:] = target_vert[ee:] == 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_mask[ss:ee] = target_vert[ss:ee] > v # mask out any references to verts >= current dst_vert = target_vert[dst_mask] - ma, mb = _get_maps(dst_vert, src_vert) + ma, mb = _get_maps_checked(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 @@ -254,28 +303,38 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: final_vertices = numpy.repeat(vertices, edges_per_vertex - 2, axis=0) - return {'vertices': final_vertices, 'neighbors': neighbors} + poly = {'vertices': final_vertices, 'neighbors': neighbors} + check_poly(poly, check_connectivity=False) + return poly -@profile -def boundary_from_poly(poly: poly_t) -> Dict: - ''' +def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: + """ 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) + Args: + poly: Polyhedron to convert, in Schlegel representation. + + Returns: + 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'] + if vertices.shape[0] == 0: + return [] + check_poly(poly, check_connectivity=False) owning_component = find_components(neighbors) - faces = find_faces(neighbors) + try: + faces = find_faces(neighbors) + except (IndexError, ValueError) as exc: + raise AdzeError('Polyhedron has invalid neighbor ordering and cannot be converted to a boundary representation') from exc num_components = owning_component.max() + 1 - components = [[] for _ in range(num_components)] + components: list[list[NDArray[numpy.integer]]] = [[] for _ in range(num_components)] for face in faces: component_ind = owning_component[face[0]] components[component_ind].append(face) @@ -299,4 +358,3 @@ def boundary_from_poly(poly: poly_t) -> Dict: boundaries.append(boundary) return boundaries - diff --git a/adze/moments.py b/adze/moments.py index 794e465..78822de 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -1,57 +1,73 @@ -from typing import Dict, Tuple -import numpy +from operator import index -from . import poly_t, plane_t +import numpy +from numpy.typing import NDArray + +from . import poly_t +from .util import AdzeError from .util import find_faces -try: - # Check if running with line_profiler - profile -except NameError: - def profile(f): - return f + +def _normalize_order(order: int) -> int: + try: + normalized = index(order) + except TypeError as exc: + raise AdzeError('Moment order must be an integer') from exc + + if normalized < 0: + raise AdzeError(f'Moment order must be non-negative. Got {normalized}') + return normalized 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. - ''' + Args: + order: Maximum polynomial order for the moments. + + Returns: + Number of moments with that order or fewer. + """ + order = _normalize_order(order) 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. - ''' + Args: + poly: Polyhedron to evaluate, in Schlegel representation. + + Returns: + Volume of the polyhedron. + """ return get_moments(poly, 0)[0] -@profile -def get_moments(poly: poly_t, order: int) -> numpy.ndarray: - ''' +def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]: + """ 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: + Args: + poly: Polyhedron to evaluate, in Schlegel representation. + order: Maximum polynomial order for moments. + + Returns: Moments, increasing polynomial order: [1, x, y, z, xx, xy, xz, yy, yz, zz, xxx, xxy, xxz, ...] - ''' + """ + order = _normalize_order(order) vertices = poly['vertices'] neighbors = poly['neighbors'] num_verts = vertices.shape[0] if num_verts == 0: - return numpy.array([0], dtype=float) + return numpy.zeros(number_of_moments(order), dtype=float) - ''' - Decompose polyhedron into triangle fans - ''' + # + # Decompose polyhedron into triangle fans + # faces = find_faces(neighbors) triangle_fans = [] @@ -67,9 +83,9 @@ def get_moments(poly: poly_t, order: int) -> numpy.ndarray: triverts = vertices[triangle_inds[:ilen]] triangle_fans.append(triverts) - ''' - Calculate the 0th-order moment - ''' + # + # Calculate the 0th-order moment + # triangles = numpy.vstack(triangle_fans) volumes = -numpy.linalg.det(triangles) moment0 = numpy.array([volumes.sum() / 6]) @@ -77,9 +93,9 @@ def get_moments(poly: poly_t, order: int) -> numpy.ndarray: if order == 0: return moment0 - ''' - Iteratively calculate higher-order moments, as per Koehl (2012). - ''' + # + # 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') @@ -95,7 +111,7 @@ def get_moments(poly: poly_t, order: int) -> numpy.ndarray: 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() + # num_valid = (c + 1) * (c + 2) // 2 # always an int, see number_of_moments() Q_prev = Q[:, :, valid[prevlayer], prevlayer] Q[:, :, 0, :, curlayer] = 0 diff --git a/adze/offset.py b/adze/offset.py new file mode 100644 index 0000000..9eed58a --- /dev/null +++ b/adze/offset.py @@ -0,0 +1,231 @@ +import numpy +from numpy.typing import NDArray +from collections.abc import Callable +from . import poly_t +from .util import find_faces +from .boundary import planes_from_boundary + +RateFunction = Callable[[NDArray[numpy.floating]], float] + +def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t: + """ + Offset a polyhedron by a distance delta. + Positive delta expands the shape, negative delta shrinks (etches) it. + + This implementation uses a "mitered" offset, shifting the planes of the + polyhedron and recalculating vertex positions. + + Args: + poly: Input polyhedron in Schlegel representation. + delta: Offset distance. + miter_limit: Maximum allowed multiplier for displacement at sharp corners. + + Returns: + Offsetted polyhedron. + + Note: + - **Topology Preservation:** This operation preserves the graph topology. + It will not automatically merge components that collide or remove + holes that close up. + - **Self-Intersection:** Large offsets (especially inward) can cause + faces to pass through each other, creating "inside-out" geometry + with negative volume. + - **Cleanup Recommendation:** For robust results in simulators, it is + recommended to use boolean operations to "clean" the result: + - **Shrinking:** Use `intersect(original, result)` to ensure the result + remains strictly within the original bounds and to remove inverted geometry. + - **Expansion:** Use `union(original, result)` to ensure no "gaps" are created + between the original and expanded shape due to numerical drift, and + `intersect(boundary, result)` to keep the shape within a global domain. + - **Smoothing and Gap-Filling:** + - **Smoothing:** High-curvature areas can be smoothed by moving vertices + toward the average of their three neighbors. + - **Gap-Filling:** Small gaps or numerical "noise" can be filled using a + "Closing" operation: an expansion followed by a shrinking of the same + magnitude (or vice versa for small protrusions). + """ + def constant_rate(_n: NDArray) -> float: + return delta + return offset_anisotropic(poly, constant_rate, miter_limit) + + +def offset_anisotropic(poly: poly_t, rate_func: RateFunction, miter_limit: float = 10.0) -> poly_t: + """ + Offset a polyhedron with a direction-dependent rate. + + Args: + poly: Input polyhedron. + rate_func: Function taking a unit normal (inward facing) and returning + the scalar offset for that face. Positive values expand against the normal. + miter_limit: Maximum allowed multiplier for displacement. + """ + if poly['vertices'].shape[0] == 0: + return poly + + vertices = poly['vertices'] + neighbors = poly['neighbors'] + num_verts = vertices.shape[0] + + # 1. Find all faces and their unit normals + faces = find_faces(neighbors) + + # Map vertex to which faces it belongs to + vertex_to_faces: list[list[int]] = [[] for _ in range(num_verts)] + face_normals = [] + face_deltas = [] + + for face_idx, face in enumerate(faces): + # planes_from_boundary handles robust normal calculation via Newell's method. + # Note: adze convention for boundary representation usually has + # INWARD facing normals for clipping. + plane = planes_from_boundary(vertices, [face])[0] + normal = plane[0] + face_normals.append(normal) + face_deltas.append(rate_func(normal)) + + for v_idx in face: + vertex_to_faces[v_idx].append(face_idx) + + # 2. For each vertex, solve the 3x3 system + new_vertices = numpy.zeros_like(vertices) + + for i in range(num_verts): + f_indices = vertex_to_faces[i] + if len(f_indices) != 3: + # Fallback if topology is non-manifold + new_vertices[i] = vertices[i] + continue + + # Normal matrix A + A = numpy.array([face_normals[fi] for fi in f_indices]) + + # Target deltas for the 3 faces + deltas = numpy.array([face_deltas[fi] for fi in f_indices]) + + # If n is INWARD normal, then to EXPAND (positive delta) we want to move + # AGAINST the normal. + # n . (V' - V) = -delta + # A d = -deltas + + # Max delta magnitude for miter limit check + max_delta = numpy.max(numpy.abs(deltas)) + + try: + # solve A d = -deltas + rhs = -deltas + d = numpy.linalg.solve(A, rhs) + + # Check miter limit + d_norm = numpy.linalg.norm(d) + if max_delta > 1e-15 and d_norm > miter_limit * max_delta: + # Clamp displacement + avg_n = numpy.mean(A, axis=0) + avg_n_norm = numpy.linalg.norm(avg_n) + # Fallback direction is average normal + # Fallback magnitude is limited + if avg_n_norm > 1e-12: + # Move along average inward normal (negative for expansion) + # Use the average requested delta + avg_delta = numpy.mean(deltas) + new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * avg_delta + else: + new_vertices[i] = vertices[i] + d * (miter_limit * max_delta / d_norm) + else: + new_vertices[i] = vertices[i] + d + except numpy.linalg.LinAlgError: + # Singular matrix + avg_n = numpy.mean(A, axis=0) + avg_n_norm = numpy.linalg.norm(avg_n) + avg_delta = numpy.mean(deltas) + if avg_n_norm > 1e-12: + new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * avg_delta + else: + new_vertices[i] = vertices[i] + + return { + 'vertices': new_vertices, + 'neighbors': neighbors.copy() + } + +def smooth(poly: poly_t, factor: float = 0.5) -> poly_t: + """ + Perform Laplacian smoothing on the polyhedron vertices. + Each vertex is moved toward the average position of its three neighbors. + + Args: + poly: Input polyhedron. + factor: Smoothing factor (0.0 to 1.0). 0.0 is no change, 1.0 is full move. + + Returns: + Smoothed polyhedron. + """ + if poly['vertices'].shape[0] == 0: + return poly + + vertices = poly['vertices'] + neighbors = poly['neighbors'] + + # Average of 3 neighbors + neighbor_verts = vertices[neighbors] # [N x 3 x 3] + avg_neighbor_pos = numpy.mean(neighbor_verts, axis=1) # [N x 3] + + new_vertices = vertices + factor * (avg_neighbor_pos - vertices) + + return { + 'vertices': new_vertices, + 'neighbors': neighbors.copy() + } + +def closing(poly: poly_t, delta: float, cleanup: bool = True) -> poly_t: + """ + Perform a morphological 'Closing' operation: Expansion followed by Shrinking. + Useful for filling small gaps or cracks. + + Args: + poly: Input polyhedron. + delta: magnitude of offset (must be positive). + cleanup: Whether to perform boolean cleanup after expansion. + """ + if delta <= 0: + return poly + + # 1. Expand + expanded = offset(poly, delta) + if cleanup: + from .boolean import union + expanded = union(poly, expanded) + + # 2. Shrink + result = offset(expanded, -delta) + if cleanup: + from .boolean import intersect + result = intersect(expanded, result) + + return result + +def opening(poly: poly_t, delta: float, cleanup: bool = True) -> poly_t: + """ + Perform a morphological 'Opening' operation: Shrinking followed by Expansion. + Useful for removing small protrusions or 'noise'. + + Args: + poly: Input polyhedron. + delta: magnitude of offset (must be positive). + cleanup: Whether to perform boolean cleanup after shrinking. + """ + if delta <= 0: + return poly + + # 1. Shrink + shrunk = offset(poly, -delta) + if cleanup: + from .boolean import intersect + shrunk = intersect(poly, shrunk) + + # 2. Expand + result = offset(shrunk, delta) + if cleanup: + from .boolean import union + result = union(shrunk, result) + + return result diff --git a/adze/shapes.py b/adze/shapes.py index 3b7817c..2e81c49 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -1,19 +1,52 @@ -from typing import List import numpy from numpy.linalg import norm +from numpy.typing import ArrayLike from . import poly_t, plane_t +from .util import AdzeError -def build_tetrahedron(vertices: numpy.ndarray) -> poly_t: - ''' +def _normalize_tetrahedron_vertices(vertices: ArrayLike) -> numpy.ndarray: + verts = numpy.asarray(vertices, dtype=float) + if verts.shape != (4, 3): + raise AdzeError(f'Tetrahedron vertices must have shape (4, 3). Got {verts.shape}') + if not numpy.isfinite(verts).all(): + raise AdzeError('Tetrahedron vertices must contain only finite values') + + signed_six_volume = -numpy.linalg.det(verts[:3] - verts[3]) + tolerance = numpy.finfo(float).eps * 64 * max(1.0, float(numpy.abs(verts).max())) ** 3 + if abs(signed_six_volume) <= tolerance: + raise AdzeError('Tetrahedron vertices must span a non-zero volume') + if signed_six_volume < 0: + raise AdzeError("Tetrahedron vertices must use the helper's positive winding") + return verts + + +def _normalize_box_corners(box_corners: ArrayLike) -> numpy.ndarray: + corners = numpy.asarray(box_corners, dtype=float) + if corners.shape != (2, 3): + raise AdzeError(f'Box corners must have shape (2, 3). Got {corners.shape}') + if not numpy.isfinite(corners).all(): + raise AdzeError('Box corners must contain only finite values') + if numpy.any(corners[0] >= corners[1]): + raise AdzeError('Box corners must satisfy box_corners[0] < box_corners[1] on every axis') + return corners + + +def build_tetrahedron(vertices: ArrayLike) -> poly_t: + """ Build a Schelegel-representation tetrahedron. - :param vertices: 4x3 array, representing the vertex coordinates. - :return: Tetrahedron in Schelgel representation. - ''' + Args: + vertices: 4x3 array, representing the vertex coordinates. Vertices must + be ordered with the positive winding expected by this helper. + + Returns: + Tetrahedron in Schelgel representation. + """ + vertices = _normalize_tetrahedron_vertices(vertices) poly = { - 'vertices': numpy.array(vertices, dtype=float), + 'vertices': vertices, 'neighbors': numpy.array(( (1, 3, 2), (2, 3, 0), @@ -23,14 +56,19 @@ def build_tetrahedron(vertices: numpy.ndarray) -> poly_t: return poly -def build_box(box_corners: numpy.ndarray) -> poly_t: - ''' +def build_box(box_corners: ArrayLike) -> 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. - ''' + Args: + box_corners: 2x3 array, representing the vertex coordinates of + two diagonally-opposite corners of the box. `box_corners[0]` must be + the per-axis minimum corner and `box_corners[1]` the per-axis maximum. + + Returns: + Box in Schelgel representation. + """ + box_corners = _normalize_box_corners(box_corners) neighbors = [ [1, 4, 3], [2, 5, 0], @@ -59,15 +97,19 @@ def build_box(box_corners: numpy.ndarray) -> poly_t: } -def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]: - ''' +def planes_from_box(box_corners: ArrayLike) -> 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) + Args: + box_corners: 2x3 array, representing the vertex coordinates of + two diagonally-opposite corners of the box. `box_corners[0]` must be + the per-axis minimum corner and `box_corners[1]` the per-axis maximum. + + Returns: + List of planes, facing inwards. + """ + box_corners = _normalize_box_corners(box_corners) faces = [ (( 0, 0, 1), -box_corners[0, 2]), (( 0, 0, -1), box_corners[1, 2]), @@ -80,20 +122,24 @@ def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]: return [(numpy.array(n), d) for n, d in faces] -def planes_from_tetrahedron(vertices: numpy.ndarray) -> List[plane_t]: - ''' +def planes_from_tetrahedron(vertices: ArrayLike) -> 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) + Args: + vertices: 4x3 array, representing the vertex coordinates. Vertices must + be ordered with the positive winding expected by this helper. + + Returns: + List of planes, facing inwards. + """ + verts = _normalize_tetrahedron_vertices(vertices) 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) + vertsets = numpy.moveaxis(numpy.dstack([verts[v] for v in vset_inds]), 2, 0) ab = vertsets[:, 0, :] - vertsets[:, 1, :] cd = vertsets[:, 2, :] - vertsets[:, 3, :] @@ -102,4 +148,4 @@ def planes_from_tetrahedron(vertices: numpy.ndarray) -> List[plane_t]: centers = numpy.sum(vertsets[:, :3, :], axis=1) / 3 d = -numpy.sum(n * centers, axis=1) - return [plane for plane in zip(n, d)] + return list(zip(n, d, strict=True)) diff --git a/adze/split.py b/adze/split.py index 71715a9..591eae1 100644 --- a/adze/split.py +++ b/adze/split.py @@ -1,71 +1,137 @@ +from typing import overload, Literal +import math 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 +from .util import build_empty, _get_map, AdzeError -def clip(poly: poly_t, plane: plane_t) -> poly_t: - ''' +def _copy_poly(poly: poly_t) -> poly_t: + return { + 'vertices': poly['vertices'].copy(), + 'neighbors': poly['neighbors'].copy(), + } + + +def _normalize_plane(plane: plane_t) -> plane_t: + normal = plane[0] + if not isinstance(normal, numpy.ndarray) or normal.shape != (3,): + normal = numpy.asarray(normal, dtype=float) + if normal.shape != (3,): + raise AdzeError(f'Plane normal must have shape (3,). Got {normal.shape}') + + nx = float(normal[0]) + ny = float(normal[1]) + nz = float(normal[2]) + if not (math.isfinite(nx) and math.isfinite(ny) and math.isfinite(nz)): + raise AdzeError('Plane normal must contain only finite values') + if nx == 0.0 and ny == 0.0 and nz == 0.0: + raise AdzeError('Plane normal must be non-zero') + + try: + distance = float(plane[1]) + except (TypeError, ValueError) as exc: + distance_shape = numpy.asarray(plane[1]).shape + raise AdzeError(f'Plane distance must be a scalar. Got {distance_shape}') from exc + if not math.isfinite(distance): + raise AdzeError('Plane distance must be finite') + return normal, float(distance) + + +def clip(poly: poly_t, plane: plane_t, atol: float = 1e-12) -> 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). + 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) + Args: + poly: Polyhedron to clip, in chiral Schlegel representation. + plane: Plane to clip against. + atol: Absolute tolerance for "on-plane" checks. Default 1e-12. + + Returns: + Clipped polyhedron. + """ + left_poly = _split(poly, plane, same_only=True, atol=atol) return left_poly -@profile -def split(poly, plane, same_only: bool = False): - ''' +def split(poly: poly_t, plane: plane_t, atol: float = 1e-12) -> tuple[poly_t, poly_t]: + """ + Clip a polyhedron with a plane, keeping both parts. + + This function is equivalent to calling _split(poly, plane, same_only=False). + + Args: + poly: Polyhedron to clip, in chiral Schlegel representation. + plane: Plane to clip against. + atol: Absolute tolerance for "on-plane" checks. Default 1e-12. + Returns: + same_side_poly, other_side_poly + The first polyhedron is on from the same side as the plane's normal vector. + """ + return _split(poly, plane, same_only=False, atol=atol) + + +@overload +def _split(poly: poly_t, plane: plane_t, same_only: Literal[True], atol: float = 1e-12) -> poly_t: + ... + + +@overload +def _split(poly: poly_t, plane: plane_t, same_only: Literal[False], atol: float = 1e-12) -> tuple[poly_t, poly_t]: + ... + + +@overload +def _split(poly: poly_t, plane: plane_t, same_only: bool, atol: float = 1e-12) -> tuple[poly_t, poly_t] | poly_t: + ... + + +def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float = 1e-12) -> tuple[poly_t, poly_t] | poly_t: + """ 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. - ''' + Args: + poly: Polyhedron to clip, in chiral Schlegel representation. + plane: Plane to clip against. + same_only: If True, only returns the clipped poly from the same side as the + plane's normal vector. Default False. + atol: Absolute tolerance for "on-plane" checks. Default 1e-12. + Returns: + (same_side_poly, other_side_poly) if same_only is False (default), otherwise + only returns same_side_poly. + """ + plane = _normalize_plane(plane) vertices = poly['vertices'] neighbors = poly['neighbors'] num_start = neighbors.shape[0] + if num_start == 0: + ret = build_empty(), build_empty() + return ret[0] if same_only else ret + dists = plane[1] + (vertices @ plane[0]) + + if (dists >= -atol).all(): + ret = _copy_poly(poly), build_empty() + return ret[0] if same_only else ret + + if (dists <= atol).all(): + ret = build_empty(), _copy_poly(poly) + return ret[0] if same_only else ret + 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() @@ -73,20 +139,20 @@ def split(poly, plane, same_only: bool = False): 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) + # + # No edges cross the plane, but components exist on either side + # + rl_edge_inds = numpy.empty(0, dtype=int) + target_edge_inds = numpy.empty(0, 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 - ''' + # + # 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] @@ -94,16 +160,16 @@ def split(poly, plane, same_only: bool = False): num_new_vertices = rverts.size - ''' - figure out new vertex positions - ''' + # + # 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 - ''' + # + # walk to next crossing edge + # prev_verts = rverts cur_verts = lverts edge_walk_inds = numpy.arange(num_new_vertices) @@ -136,29 +202,25 @@ def split(poly, plane, same_only: bool = False): # 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) + b1d = numpy.ravel_multi_index(tuple(edge_walk_results), dims) target_edge_inds = _get_map(a1d, b1d) - - ''' - map from old vertex ind to new - ''' + # + # 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 + ind_map_left[lverts], + target_order + num_left, 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[left] = ind_map_left[old_neighbors_left[left]] old_neighbors_left[(lverts, src_pns)] = num_left + numpy.arange(num_new_vertices) old_neighbors_left = old_neighbors_left[left] @@ -174,8 +236,8 @@ def split(poly, plane, same_only: bool = False): 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 + ind_map_right[rverts], + target_edge_inds + num_right, target_order + num_right)) old_vertices_right = vertices[right] @@ -191,4 +253,3 @@ def split(poly, plane, same_only: bool = False): } return left_poly, right_poly - diff --git a/adze/test/__init__.py b/adze/test/__init__.py new file mode 100644 index 0000000..e02b636 --- /dev/null +++ b/adze/test/__init__.py @@ -0,0 +1,3 @@ +""" +Tests (run with `python3 -m pytest -rxPXs | tee results.txt`) +""" diff --git a/adze/test/conftest.py b/adze/test/conftest.py new file mode 100644 index 0000000..c1bf7c0 --- /dev/null +++ b/adze/test/conftest.py @@ -0,0 +1,10 @@ +from typing import Any +import pytest + + +FixtureRequest = Any + + +@pytest.fixture(scope='module', params=[0, 1, 2]) +def poly_order(request: FixtureRequest) -> int: + return request.param diff --git a/adze/test/test_benchmarks.py b/adze/test/test_benchmarks.py new file mode 100644 index 0000000..56aaa7c --- /dev/null +++ b/adze/test/test_benchmarks.py @@ -0,0 +1,56 @@ +""" +Benchmarking, run with `python3 -m adze.test.benchmark` + +TODO: Consider using pytest-benchmark? +""" +from collections.abc import Callable +import logging + +import numpy +from numpy.typing import NDArray + +import adze +import adze.util + +from .utils import build_rand_tetrahedron, rand_tetrahedron_vertices + + +logger = logging.getLogger(__name__) + + +def test_split(benchmark: Callable) -> None: + poly = build_rand_tetrahedron() + faceset = adze.planes_from_tetrahedron(rand_tetrahedron_vertices()) + benchmark(adze.clip, poly, faceset[0]) + + +def test_split_bulk_1000(benchmark: Callable) -> None: + NUM_TRIALS = 1000 + polys_bulk = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)] + faceset = adze.planes_from_tetrahedron(rand_tetrahedron_vertices()) + bulk = { + 'vertices': numpy.vstack([p['vertices'] for p in polys_bulk]), + 'neighbors': numpy.vstack([p['neighbors'] for p in polys_bulk]) + numpy.arange(NUM_TRIALS).repeat(4)[:, None] * 4, + } + benchmark(adze.clip, bulk, faceset[0]) + + + +def get_intersection_moments(poly: adze.poly_t, faces: NDArray[numpy.intp], poly_order: int) -> NDArray[numpy.float64]: + # Clip the first tetrahedron using the faces of the second + for face in faces: + poly = adze.clip(poly, face) + + # find the moments (up to quadratic order) of the clipped poly + om = adze.get_moments(poly, poly_order) + return om + + +def test_intersection(benchmark: Callable, poly_order: int = 0) -> None: + """ + Benchmark intersection between pairs of tetrahedra + """ + poly = build_rand_tetrahedron() + faces = adze.planes_from_tetrahedron(rand_tetrahedron_vertices()) + benchmark(get_intersection_moments, poly, faces, poly_order) + diff --git a/adze/test/test_boolean.py b/adze/test/test_boolean.py new file mode 100644 index 0000000..4ef625c --- /dev/null +++ b/adze/test/test_boolean.py @@ -0,0 +1,163 @@ +import numpy +import adze +from adze.boolean import intersect, difference, union +from adze.shapes import build_box +from adze.util import check_poly + +def test_intersect_cubes() -> None: + # Cube 1: (0,0,0) to (2,2,2), volume = 8 + poly_a = build_box([[0, 0, 0], [2, 2, 2]]) + # Cube 2: (1,1,1) to (3,3,3), volume = 8 + poly_b = build_box([[1, 1, 1], [3, 3, 3]]) + + # Overlap is from (1,1,1) to (2,2,2), volume = 1 + result = intersect(poly_a, poly_b) + check_poly(result) + + volume = adze.get_volume(result) + assert numpy.isclose(volume, 1.0) + +def test_intersect_no_overlap() -> None: + poly_a = build_box([[0, 0, 0], [1, 1, 1]]) + poly_b = build_box([[2, 2, 2], [3, 3, 3]]) + + result = intersect(poly_a, poly_b) + check_poly(result) + assert result['vertices'].shape[0] == 0 + assert adze.get_volume(result) == 0.0 + +def test_difference_cubes() -> None: + # Cube 1: (0,0,0) to (2,2,2), volume = 8 + poly_a = build_box([[0, 0, 0], [2, 2, 2]]) + # Cube 2: (1,1,1) to (3,3,3), volume = 8 + poly_b = build_box([[1, 1, 1], [3, 3, 3]]) + + # A - B should be 8 - 1 = 7 + result = difference(poly_a, poly_b) + check_poly(result) + volume = adze.get_volume(result) + assert numpy.isclose(volume, 7.0) + +def test_union_cubes() -> None: + # Cube 1: (0,0,0) to (2,2,2), volume = 8 + poly_a = build_box([[0, 0, 0], [2, 2, 2]]) + # Cube 2: (1,1,1) to (3,3,3), volume = 8 + poly_b = build_box([[1, 1, 1], [3, 3, 3]]) + + # A + B should be 8 + 8 - 1 = 15 + result = union(poly_a, poly_b) + check_poly(result) + volume = adze.get_volume(result) + assert numpy.isclose(volume, 15.0) + +def test_union_no_overlap() -> None: + poly_a = build_box([[0, 0, 0], [1, 1, 1]]) + poly_b = build_box([[2, 2, 2], [3, 3, 3]]) + + # A + B should be 1 + 1 = 2 + result = union(poly_a, poly_b) + check_poly(result) + volume = adze.get_volume(result) + assert numpy.isclose(volume, 2.0) + +def test_intersect_nonconvex_lshape() -> None: + """ + Test intersection with a non-convex L-shaped object. + The L-shape is formed by two boxes: + B1: [0,2]x[0,1]x[0,1] + B2: [0,1]x[0,2]x[0,1] + Total volume = 2 + 2 - 1 (overlap [0,1]x[0,1]x[0,1]) = 3 + """ + b1 = build_box([[0, 0, 0], [2, 1, 1]]) + b2 = build_box([[0, 0, 0], [1, 2, 1]]) + + # union(b1, b2) will produce a non-convex polyhedron + l_shape = union(b1, b2) + check_poly(l_shape) + assert numpy.isclose(adze.get_volume(l_shape), 3.0) + + b3 = build_box([[0.5, 0.5, 0], [1.5, 1.5, 1]]) + + # Test L-shape as poly_a + res1 = intersect(l_shape, b3) + check_poly(res1) + vol1 = adze.get_volume(res1) + assert numpy.isclose(vol1, 0.75) + + # Test L-shape as poly_b + res2 = intersect(b3, l_shape) + check_poly(res2) + vol2 = adze.get_volume(res2) + assert numpy.isclose(vol2, 0.75) + +def test_difference_nonconvex() -> None: + # B1: [0,2]x[0,1]x[0,1], vol=2 + b1 = build_box([[0, 0, 0], [2, 1, 1]]) + # B2: [0,1]x[0,2]x[0,1], vol=2 + b2 = build_box([[0, 0, 0], [1, 2, 1]]) + + # B1 - B2 = [1, 2] x [0, 1] x [0, 1] -> vol=1 + res = difference(b1, b2) + check_poly(res) + assert numpy.isclose(adze.get_volume(res), 1.0) + + # L-shape - B3 + # L-shape: B1 + B2 + # B3: [0.5, 1.5] x [0.5, 1.5] x [0, 1] + # L-shape \cap B3 = 0.75 + # L-shape - B3 = 3 - 0.75 = 2.25 + l_shape = union(b1, b2) + b3 = build_box([[0.5, 0.5, 0], [1.5, 1.5, 1]]) + res2 = difference(l_shape, b3) + check_poly(res2) + assert numpy.isclose(adze.get_volume(res2), 2.25) + +def test_difference_hole() -> None: + """ + Test subtracting a small box strictly inside a larger box (Hole Drilling). + """ + outer = build_box([[0, 0, 0], [3, 3, 3]]) # Vol 27 + inner = build_box([[1, 1, 1], [2, 2, 2]]) # Vol 1 + + diff = difference(outer, inner) + check_poly(diff) + + assert numpy.isclose(adze.get_volume(diff), 26.0) + +def test_robust_normals() -> None: + """ + Test that planes_from_boundary handles collinear vertices. + """ + # A flat square face with collinear points at the start + # [0,0,0], [1,0,0], [2,0,0] are collinear. + vertices = numpy.array([ + [0, 0, 0], + [1, 0, 0], + [2, 0, 0], + [2, 2, 0], + [0, 2, 0], + # Add a top point to make it a pyramid (non-degenerate 3D shape) + [1, 1, 1] + ]) + # Pyramid faces + faces = [ + [0, 1, 2, 3, 4], # Base (with collinear points) + [0, 5, 1], + [1, 5, 2], + [2, 5, 3], + [3, 5, 4], + [4, 5, 0] + ] + + # This should now succeed and produce correct planes + planes = adze.boundary.planes_from_boundary(vertices, faces) + + # Check the base plane (first face) + # The normal should be [0, 0, -1] (facing inward for a CCW base viewed from below?) + # Let's check orientation. vertices 0,1,2,3,4 are CCW if viewed from +Z. + # Newell's method for CCW [0,0,0] -> [1,0,0] -> [2,0,0] -> [2,2,0] -> [0,2,0] + # produces [0, 0, Area*2]. So normal [0, 0, 1]. + + base_plane = planes[0] + assert numpy.allclose(base_plane[0], [0, 0, 1]) + assert numpy.isclose(base_plane[1], 0.0) diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py new file mode 100644 index 0000000..f611f65 --- /dev/null +++ b/adze/test/test_edge_cases.py @@ -0,0 +1,341 @@ +import numpy +import pytest +from numpy.testing import assert_allclose + +import adze +import adze.util +from adze.boundary import planes_from_boundary + + +def test_boundary_from_empty_poly() -> None: + assert adze.boundary_from_poly(adze.util.build_empty()) == [] + + +@pytest.mark.parametrize('order', [0, 1, 2, 3]) +def test_empty_poly_moments_shape(order: int) -> None: + moments = adze.get_moments(adze.util.build_empty(), order) + assert moments.shape == (adze.number_of_moments(order),) + assert_allclose(moments, numpy.zeros_like(moments)) + + +@pytest.mark.parametrize('order', [-3, -2, -1]) +def test_negative_moment_order_rejected(order: int) -> None: + poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) + edges = [numpy.array([0.0, 1.0]) for _ in range(3)] + + with pytest.raises(adze.AdzeError, match='Moment order must be non-negative'): + adze.number_of_moments(order) + with pytest.raises(adze.AdzeError, match='Moment order must be non-negative'): + adze.get_moments(poly, order) + with pytest.raises(adze.AdzeError, match='Moment order must be non-negative'): + adze.voxelize(poly, edges, order=order) + + +def test_planes_from_boundary_tetrahedron() -> None: + vertices = numpy.array([ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + ]) + faces = [ + [0, 1, 2], + [0, 3, 1], + [0, 2, 3], + [1, 3, 2], + ] + + planes = planes_from_boundary(vertices, faces) + assert len(planes) == 4 + for normal, distance in planes: + assert normal.shape == (3,) + assert numpy.isscalar(distance) + assert_allclose(numpy.linalg.norm(normal), 1.0) + + +def test_planes_from_boundary_nontriangular_face() -> None: + vertices = numpy.array([ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [1.0, 1.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + ]) + faces = [ + [0, 3, 2, 1], + [0, 1, 4], + [1, 2, 4], + [2, 3, 4], + [3, 0, 4], + ] + + normal, distance = planes_from_boundary(vertices, faces)[0] + assert_allclose(normal, [0.0, 0.0, -1.0]) + assert_allclose(distance, 0.0) + + +def test_planes_from_boundary_rejects_zero_area_face() -> None: + vertices = numpy.array([ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [2.0, 0.0, 0.0], + ]) + + with pytest.raises(adze.AdzeError, match='non-zero area'): + planes_from_boundary(vertices, [[0, 1, 2]]) + + +@pytest.mark.parametrize('face', [[-1, 1, 2], [0, 1, 5]]) +def test_planes_from_boundary_rejects_invalid_face_index(face: list[int]) -> None: + vertices = numpy.array([ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + ]) + + with pytest.raises(adze.AdzeError, match='outside the provided vertex list'): + planes_from_boundary(vertices, [face]) + + +def test_build_polyhedron_rejects_unused_vertices() -> None: + vertices = numpy.array([ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + [9.0, 9.0, 9.0], + ]) + faces = [ + [0, 1, 2], + [0, 3, 1], + [0, 2, 3], + [1, 3, 2], + ] + + with pytest.raises(adze.AdzeError, match='unused by any face'): + adze.build_polyhedron(vertices, faces) + + +def test_build_polyhedron_accepts_box_with_quadrilateral_faces() -> None: + vertices = numpy.array([ + [0.0, 0.0, 0.0], + [0.0, 0.0, 1.0], + [0.0, 1.0, 0.0], + [0.0, 1.0, 1.0], + [1.0, 0.0, 0.0], + [1.0, 0.0, 1.0], + [1.0, 1.0, 0.0], + [1.0, 1.0, 1.0], + ]) + faces = [ + [0, 4, 6, 2], + [0, 1, 5, 4], + [0, 2, 3, 1], + [4, 5, 7, 6], + [6, 7, 3, 2], + [1, 3, 7, 5], + ] + + poly = adze.build_polyhedron(vertices, faces) + + adze.util.check_poly(poly) + assert_allclose(adze.get_volume(poly), 1.0) + assert len(adze.boundary_from_poly(poly)) == 1 + + +def test_build_polyhedron_rejects_invalid_face_index() -> None: + vertices = numpy.array([ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + ]) + faces = [ + [0, 1, 2], + [0, 3, 1], + [0, 2, 3], + [1, 3, 5], + ] + + with pytest.raises(adze.AdzeError, match='outside the provided vertex list'): + adze.build_polyhedron(vertices, faces) + + +def test_build_polyhedron_rejects_inconsistent_face_winding() -> None: + vertices = numpy.array([ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + ]) + faces = [ + [0, 1, 2], + [0, 1, 3], + [0, 3, 2], + [1, 2, 3], + ] + + with pytest.raises(adze.AdzeError, match='duplicate neighbors'): + adze.build_polyhedron(vertices, faces) + + +def test_build_polyhedron_rejects_invalid_high_degree_boundary() -> None: + vertices = numpy.array([ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [1.0, 1.0, 0.0], + [0.5, 0.5, 1.0], + ]) + faces = [ + [0, 1, 2, 3], + [0, 1, 4], + [1, 3, 4], + [3, 2, 4], + [2, 0, 4], + ] + + with pytest.raises(adze.AdzeError, match='valid closed polyhedron boundary'): + adze.build_polyhedron(vertices, faces) + + +def test_check_poly_rejects_row_count_mismatch() -> None: + poly = { + 'vertices': numpy.array([ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [9.0, 9.0, 9.0], + ]), + 'neighbors': numpy.array([ + [1, 2, 0], + [2, 0, 1], + [0, 1, 2], + ], dtype=int), + } + + with pytest.raises(adze.AdzeError, match='Neighbors must have shape'): + adze.util.check_poly(poly, check_connectivity=False) + + +def test_voxelize_requires_three_axes() -> None: + poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) + + with pytest.raises(adze.AdzeError, match='exactly three plane axes'): + adze.voxelize(poly, [numpy.array([0.0, 1.0]), numpy.array([0.0, 1.0])], order=0) + + +def test_voxelize_requires_strictly_increasing_axes() -> None: + poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) + + with pytest.raises(adze.AdzeError, match='strictly increasing'): + adze.voxelize( + poly, + [numpy.array([1.0, 0.0]), numpy.array([0.0, 1.0]), numpy.array([0.0, 1.0])], + order=0, + ) + + +def test_clip_rejects_zero_normal_plane() -> None: + poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) + + with pytest.raises(adze.AdzeError, match='Plane normal must be non-zero'): + adze.clip(poly, (numpy.array([0.0, 0.0, 0.0]), 0.0)) + + +@pytest.mark.parametrize('normal', [numpy.array([1.0, 0.0]), numpy.array([1.0, 0.0, 0.0, 0.0])]) +def test_split_rejects_wrong_plane_normal_shape(normal: numpy.ndarray) -> None: + poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) + + with pytest.raises(adze.AdzeError, match='Plane normal must have shape'): + adze.split(poly, (normal, 0.0)) + + +def test_split_rejects_non_scalar_plane_distance() -> None: + poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) + + with pytest.raises(adze.AdzeError, match='Plane distance must be a scalar'): + adze.split(poly, (numpy.array([1.0, 0.0, 0.0]), numpy.array([0.0, 1.0]))) + + +def test_boundary_from_poly_rejects_invalid_graph() -> None: + poly = { + 'vertices': numpy.array([ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + ]), + 'neighbors': numpy.array([ + [1, 2, 3], + [2, 3, 0], + [3, 0, 1], + [0, 1, 2], + ], dtype=int), + } + + with pytest.raises(adze.AdzeError, match='invalid neighbor ordering'): + adze.boundary_from_poly(poly) + + +def test_clip_noop_returns_independent_poly() -> None: + poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) + + clipped = adze.clip(poly, (numpy.array([1.0, 0.0, 0.0]), 0.0)) + + assert clipped is not poly + assert clipped['vertices'] is not poly['vertices'] + clipped['vertices'][0, 0] = 999.0 + assert poly['vertices'][0, 0] == 0.0 + + +def test_split_noop_returns_independent_poly() -> None: + poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) + + empty_poly, kept_poly = adze.split(poly, (numpy.array([1.0, 0.0, 0.0]), -2.0)) + + assert empty_poly['vertices'].shape == (0, 3) + assert kept_poly is not poly + assert kept_poly['vertices'] is not poly['vertices'] + kept_poly['vertices'][0, 0] = 999.0 + assert poly['vertices'][0, 0] == 0.0 + + +def test_split_handles_disconnected_components_without_cut_edges() -> None: + poly_left = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) + poly_right = adze.build_box([[3.0, 0.0, 0.0], [4.0, 1.0, 1.0]]) + poly = { + 'vertices': numpy.vstack((poly_left['vertices'], poly_right['vertices'])), + 'neighbors': numpy.vstack((poly_left['neighbors'], poly_right['neighbors'] + poly_left['vertices'].shape[0])), + } + + split_left, split_right = adze.split(poly, (numpy.array([1.0, 0.0, 0.0]), -2.0)) + + adze.util.check_poly(split_left) + adze.util.check_poly(split_right) + assert_allclose(adze.get_volume(split_left), 1.0) + assert_allclose(adze.get_volume(split_right), 1.0) + + +@pytest.mark.parametrize('box_fun', [adze.build_box, adze.planes_from_box]) +def test_box_helpers_reject_inverted_corners(box_fun) -> None: + with pytest.raises(adze.AdzeError, match='box_corners\\[0\\] < box_corners\\[1\\]'): + box_fun([[1.0, 1.0, 1.0], [0.0, 0.0, 0.0]]) + + +@pytest.mark.parametrize('tetra_fun', [adze.build_tetrahedron, adze.planes_from_tetrahedron]) +def test_tetrahedron_helpers_reject_wrong_shape(tetra_fun) -> None: + with pytest.raises(adze.AdzeError, match='shape \\(4, 3\\)'): + tetra_fun([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) + + +@pytest.mark.parametrize('tetra_fun', [adze.build_tetrahedron, adze.planes_from_tetrahedron]) +def test_tetrahedron_helpers_reject_negative_winding(tetra_fun) -> None: + with pytest.raises(adze.AdzeError, match='positive winding'): + tetra_fun([ + [0.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 0.0, 1.0], + ]) diff --git a/adze/test/test_offset.py b/adze/test/test_offset.py new file mode 100644 index 0000000..1e8eed2 --- /dev/null +++ b/adze/test/test_offset.py @@ -0,0 +1,91 @@ +import numpy +import adze +from adze.shapes import build_box +from adze.offset import offset, smooth, closing, offset_anisotropic + +def test_offset_cube_expand() -> None: + # Unit cube: [0,1]x[0,1]x[0,1], vol=1 + cube = build_box([[0, 0, 0], [1, 1, 1]]) + + expanded = offset(cube, 0.1) + + vol = adze.get_volume(expanded) + assert numpy.isclose(vol, 1.728) + + vmin, vmax = adze.util.get_aabb(expanded) + assert numpy.allclose(vmin, [-0.1, -0.1, -0.1]) + assert numpy.allclose(vmax, [1.1, 1.1, 1.1]) + +def test_offset_cube_shrink() -> None: + # Unit cube: [0,1]x[0,1]x[0,1], vol=1 + cube = build_box([[0, 0, 0], [1, 1, 1]]) + + shrunk = offset(cube, -0.1) + + vol = adze.get_volume(shrunk) + assert numpy.isclose(vol, 0.512) + + vmin, vmax = adze.util.get_aabb(shrunk) + assert numpy.allclose(vmin, [0.1, 0.1, 0.1]) + assert numpy.allclose(vmax, [0.9, 0.9, 0.9]) + +def test_offset_zero() -> None: + cube = build_box([[0, 0, 0], [1, 1, 1]]) + same = offset(cube, 0.0) + assert numpy.isclose(adze.get_volume(same), 1.0) + assert numpy.allclose(cube['vertices'], same['vertices']) + +def test_smooth_cube() -> None: + # Smoothing a cube should move vertices toward the center + cube = build_box([[0, 0, 0], [1, 1, 1]]) + # Centroid is [0.5, 0.5, 0.5] + + smoothed = smooth(cube, factor=0.1) + + # Check that volume decreased (cube is rounding in) + assert adze.get_volume(smoothed) < adze.get_volume(cube) + + # Check one vertex: [0,0,0] + # Neighbors of [0,0,0] are [1,0,0], [0,1,0], [0,0,1] (for a unit box) + # Average of neighbors = [1/3, 1/3, 1/3] + # New V = [0,0,0] + 0.1 * ([1/3, 1/3, 1/3] - [0,0,0]) = [1/30, 1/30, 1/30] + assert numpy.allclose(smoothed['vertices'][0], [1/30, 1/30, 1/30]) + +def test_closing_cube() -> None: + # Closing a cube shouldn't change it much if delta is small and cube is simple + cube = build_box([[0, 0, 0], [1, 1, 1]]) + closed = closing(cube, 0.1, cleanup=True) + + # For a perfect cube, offset(0.1) then offset(-0.1) should return to original + assert numpy.isclose(adze.get_volume(closed), 1.0, atol=1e-7) + +def test_anisotropic_etch() -> None: + # Unit cube [0,1]^3 + cube = build_box([[0, 0, 0], [1, 1, 1]]) + + # Define an etch rate function: + # Fast vertical etch (-0.2), slow horizontal etch (-0.05) + # Note: Normals are inward facing for adze clipping convention? + # Wait, planes_from_box in shapes.py returns normals like (0,0,1) for z=0 face. + # Let's verify normal direction with a quick check if needed, but standard logic: + # offset uses inward normals. A negative return value from rate_func shrinks. + + def vertical_etch_rate(normal: numpy.ndarray) -> float: + # Check if normal is primarily vertical (z-axis) + if abs(normal[2]) > 0.9: + return -0.2 + return -0.05 + + etched = offset_anisotropic(cube, vertical_etch_rate) + + # Expected bounds: + # Z: [0,1] -> [0.2, 0.8] (shrunk by 0.2 on both top and bottom) -> height 0.6 + # X, Y: [0,1] -> [0.05, 0.95] (shrunk by 0.05 on sides) -> width 0.9 + + vmin, vmax = adze.util.get_aabb(etched) + + assert numpy.allclose(vmin, [0.05, 0.05, 0.2]) + assert numpy.allclose(vmax, [0.95, 0.95, 0.8]) + + # Volume = 0.9 * 0.9 * 0.6 = 0.486 + assert numpy.isclose(adze.get_volume(etched), 0.486) diff --git a/adze/test/test_split.py b/adze/test/test_split.py new file mode 100644 index 0000000..1253961 --- /dev/null +++ b/adze/test/test_split.py @@ -0,0 +1,300 @@ +from collections.abc import Callable +import warnings +import logging + +import pytest + +import numpy +from numpy.typing import NDArray +from numpy import floating +from numpy.linalg import norm +from numpy.testing import assert_allclose + +import adze +import adze.util + +from .utils import TOL_FAIL, TOL_WARN, PRNG, MIN_VOLUME, flip_plane, tetrahedron_volume +from .utils import build_rand_tetrahedron, gen_plane_through_centroid, plane_generators, gen_torus_brep + + +logger = logging.getLogger(__name__) + + +def test_manual_tetrahedron(poly_order: int) -> None: + tet = adze.build_tetrahedron([ + [0,0,0], + [2,0,0], + [0,2,0], + [0,0,2]]) + + volume = tetrahedron_volume(tet['vertices']) + logger.debug(f'Splitting manual tetrahedron {tet}') + logger.debug(f'volume {volume}') + + plane = numpy.array((-1, 0, 0)), 1 + p_left, p_right = adze.split(tet, plane) + + logger.debug(f'left {p_left}') + logger.debug(f'right {p_right}') + + adze.util.check_poly(tet) + adze.util.check_poly(p_left) + adze.util.check_poly(p_right) + + m0 = adze.get_moments(tet, 0) + ml = adze.get_moments(p_left, 0) + mr = adze.get_moments(p_right, 0) + + logger.debug(f'0th moments: tot {m0[0]}, left {ml[0]}, right {mr[0]}') + assert m0 == pytest.approx(volume, abs=TOL_FAIL) + check_split_moments(tet, p_left, p_right, poly_order) + + +def test_manual_pyramid(poly_order: int) -> None: + vertices = numpy.array([ + [0, 0, 1], + [1, 1, 0], + [1, -1, 0], + [-1, -1, 0], + [-1, 1, 0], + ]) + faces = [ + [0, 1, 2], + [0, 2, 3], + [0, 3, 4], + [0, 4, 1], + [4, 3, 2, 1], + ] + + # initialize a general polyhedron + poly = adze.build_polyhedron(vertices, faces) # type: ignore # (mypy error?) + adze.util.check_poly(poly) + + brep = adze.boundary_from_poly(poly) + logger.info(f'Round-trip converted pyramid: {brep}') + #adze.util.plot_brep(brep) + + stack_split(poly, poly_order) + + +def test_tetrahedrons_through_centroid(poly_order: int) -> None: + """ + Splits some tetrahedrons through their centroids and + checks if each two resulting volumes sum to the original + """ + + # Generate random tetrahedrons and clip planes + ntets = 100 + polys = [build_rand_tetrahedron() for _ in range(ntets)] + plane = gen_plane_through_centroid(polys[ntets//7]) + + # split them all with the same plane + poly12 = [adze.split(p, plane) for p in polys] + poly1, poly2 = zip(*poly12, strict=True) + + for orig, p1, p2 in zip(polys, poly1, poly2, strict=True): + adze.util.check_poly(orig) + adze.util.check_poly(p1) + adze.util.check_poly(p2) + check_split_moments(orig, p1, p2, poly_order) + + +def test_manual_nonconvex(poly_order: int, n_zigs: int = 3, z_offset: float = 0.1) -> None: + """ + Splits a non-convex polyhedron and checks if the resulting + volumes add up to the original + """ + # manually create a non-convex polyhedron + num_verts = 4 * n_zigs + vertices = numpy.empty((num_verts, 3), dtype=float) + neighbors = numpy.empty((num_verts, 3), dtype=int) + + for v in range(n_zigs): + m = n_zigs - v - 1 + v0 = numpy.array([v, v % 2 + z_offset, 0]) + v1 = numpy.array([m, m % 2, 0]) + vertices[v + 0 * n_zigs] = v0 + vertices[v + 1 * n_zigs] = v1 + vertices[v + 2 * n_zigs] = v0 + (0, 0, 1) + vertices[v + 3 * n_zigs] = v1 + (0, 0, 1) + + nz2 = 2 * n_zigs + for v in range(nz2): + neighbors[v] = ((v + 1) % nz2, + (v - 1) % nz2, + v + nz2) + neighbors[v + nz2] = neighbors[v][[1, 0, 2]] + (nz2, nz2, -nz2) + poly = { + 'vertices': vertices, + 'neighbors': neighbors, + } + + logger.debug("Checking poly...") + adze.util.check_poly(poly) + logger.debug("poly is valid.") + + # + # Perform splits along three axes + # + def split_and_check(poly: adze.poly_t, plane: adze.plane_t, poly_order: int = 0) -> None: + poly_l = adze.clip(poly, plane) + poly_r = adze.clip(poly, flip_plane(plane)) + check_split_moments(poly, poly_l, poly_r, poly_order) + + # split along the x-axis (two single connected components) + split_and_check(poly, (numpy.array((1, 0, 0)), -0.5 * (n_zigs - 1)), poly_order) + + # split along the z-axis (two single connected components) + split_and_check(poly, (numpy.array((0, 0, 1)), -0.5), poly_order) + + # split along the y-axis (multiple connected components) + split_and_check(poly, (numpy.array((0, 1, 0)), -0.5 * (1.0 + z_offset)), poly_order) + + +def test_clip_with_atol() -> None: + """ + Verify that atol correctly handles vertices very close to the plane. + """ + # Unit tetrahedron + tet = adze.build_tetrahedron([ + [0, 0, 0], + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + # Plane x = 0 (keeping x > 0) + plane = (numpy.array([1, 0, 0]), 0) + + # Move one vertex slightly to x = -1e-13 + tet['vertices'][0, 0] = -1e-13 + + # Without atol (default 1e-12), it should still keep the whole thing + # because -1e-13 > -1e-12. + clipped = adze.clip(tet, plane, atol=1e-12) + assert_allclose(adze.get_volume(tet), adze.get_volume(clipped)) + + # With a very small atol, it might clip it + clipped_small = adze.clip(tet, plane, atol=1e-15) + assert adze.get_volume(clipped_small) < adze.get_volume(tet) + + +def test_torus(poly_order: int) -> None: + """ + Recursively split a torus with random degenerate cut planes until the pieces + are smaller than `MIN_VOLUME`, then check that the moments add up properly. + + This checks `build_polyhedron()` with for >3 edges per vertex and non-convex + geometry. + """ + vertices, faces = gen_torus_brep(n_theta=20, n_phi=20, r0=1.0, r1=0.1) + + # Shift center away from the origin, to avoid 0-valued moments + vertices += (0.5, 0.7, 0.9) + + opoly = adze.build_polyhedron(vertices, faces) +# adze.util.check_poly(opoly) + + brep = adze.boundary_from_poly(opoly) + logger.debug(f'Round-trip converted torus: {brep}') + #adze.util.plot_brep(brep) + + stack_split(opoly, poly_order) + + +def test_recursive(poly_order: int, num_trials: int = 10, max_depth: int = 6) -> None: + """ + Starting with a tetrahedron, recusively split until the pieces + are smaller than `MIN_VOLUME` or have been split more than `max_depth` times, + then check that the moments add up as expected. + """ + logger.info(f'Recursively splitting {num_trials} tetrahedra, maximum depth {max_depth}:') + logger.info(' - Through centroid') + for _ in range(num_trials): + stack_split(build_rand_tetrahedron(), poly_order, plane_fun=gen_plane_through_centroid, max_depth=max_depth) + + logger.info(' - Through degenerate plane') + for _ in range(num_trials): + stack_split(build_rand_tetrahedron(), poly_order, max_depth=max_depth) + + logger.info(' - Through perturbed plane') + for t in range(num_trials): + perturb = 10 ** -(1 + t % 16) + stack_split(build_rand_tetrahedron(), poly_order, perturb=perturb, max_depth=max_depth) + + +def check_split_moments( + original_poly: adze.poly_t, + left_poly: adze.poly_t, + right_poly: adze.poly_t, + poly_order: int = 0, + ) -> tuple[NDArray[floating], NDArray[floating], NDArray[floating]]: + m0, ml, mr = (adze.get_moments(x, poly_order) for x in (original_poly, left_poly, right_poly)) + logger.debug(f'Check: original {m0[0]} parts {(ml[0], mr[0])} sum {ml[0] + mr[0]}') + + # Make sure each part is smaller than the whole + if not ml[0] < m0[0] * (1.0 + TOL_WARN): + warnings.warn('ml[0] < m0[0]', stacklevel=1) + assert(ml[0] < m0[0] * (1.0 + TOL_FAIL)) + if not mr[0] < m0[0] * (1.0 + TOL_WARN): + warnings.warn('mr[0] < m0[0]', stacklevel=1) + assert(mr[0] < m0[0] * (1.0 + TOL_FAIL)) + + # make sure the sum of moments equals the original + mtot = ml + mr + assert_allclose(m0, mtot, atol=TOL_FAIL) +# if not numpy.all(diff < TOL_FAIL): +# logger.error(f'diff failed: {diff} \n original {m0} \n left {ml} \n right {mr}') +# assert(False) + if not numpy.allclose(m0, mtot, atol=TOL_WARN): + warnings.warn('Moments outside tolerance', stacklevel=1) + + return m0, ml, mr + + +def stack_split( + poly: adze.poly_t, + poly_order: int, + plane_fun: Callable | None = None, + perturb: float = 0, + max_depth: int = 10, + ) -> None: + stack = [(poly, 0)] + + i = 0 + while stack: + i += 1 + poly, depth = stack.pop() + + # pick a plane + if plane_fun is None: + pfun_used = PRNG.choice(plane_generators) # type: ignore + plane = pfun_used(poly) + while norm(plane[0]) == 0: + pfun_used = PRNG.choice(plane_generators) # type: ignore + plane = pfun_used(poly) + plane = list(plane) + logger.debug(f'used {pfun_used}') + else: + plane = list(plane_fun(poly)) + + # perturb the plane + plane[0] *= 1 + perturb * (PRNG.rand() - 0.5) + plane[1] *= 1 + perturb * (PRNG.rand() - 0.5) + + # split the poly + poly_l = adze.clip(poly, tuple(plane)) + poly_r = adze.clip(poly, flip_plane(tuple(plane))) + m0, ml, mr = check_split_moments(poly, poly_l, poly_r, poly_order) + + logger.debug(f'nstack = {len(stack)}, depth = {depth}, ' + f'opoly = {m0[0]:.10e}, p1 = {ml[0]:.10e}, p2 = {mr[0]:.10e}, ' + f'err = {abs(1.0 - m0[0]/(ml[0] + mr[0])):.10e}') + + # add the children to the stack if they are big enough + if depth < max_depth: + if ml[0] > MIN_VOLUME: + stack.append((poly_l, depth + 1)) + if mr[0] > MIN_VOLUME: + stack.append((poly_r, depth + 1)) + if i % 300 == 0: + logger.info(f'Stack split iter {i} length {len(stack)} depth {depth}') diff --git a/adze/test/test_transform.py b/adze/test/test_transform.py new file mode 100644 index 0000000..d391db4 --- /dev/null +++ b/adze/test/test_transform.py @@ -0,0 +1,178 @@ +import numpy +import pytest +from numpy.testing import assert_allclose + +import adze +import adze.transform + + +def test_rotate_x_quarter_turn() -> None: + poly = { + 'vertices': numpy.array([[0.0, 1.0, 0.0]]), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + rotated = adze.transform.rotate(poly, numpy.pi / 2, axis=0) + assert_allclose(rotated['vertices'], [[0.0, 0.0, 1.0]], atol=1e-12) + + +def test_rotate_y_quarter_turn() -> None: + poly = { + 'vertices': numpy.array([[0.0, 0.0, 1.0]]), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + rotated = adze.transform.rotate(poly, numpy.pi / 2, axis=1) + assert_allclose(rotated['vertices'], [[1.0, 0.0, 0.0]], atol=1e-12) + + +def test_rotate_z_quarter_turn() -> None: + poly = { + 'vertices': numpy.array([[1.0, 0.0, 0.0]]), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + rotated = adze.transform.rotate(poly, numpy.pi / 2, axis=2) + assert_allclose(rotated['vertices'], [[0.0, 1.0, 0.0]], atol=1e-12) + + +def test_rotate_promotes_integer_vertices_to_float() -> None: + poly = { + 'vertices': numpy.array([[1, 0, 0]], dtype=int), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + + rotated = adze.transform.rotate(poly, numpy.pi / 4, axis=2) + + assert numpy.issubdtype(rotated['vertices'].dtype, numpy.floating) + assert_allclose(rotated['vertices'], [[numpy.sqrt(0.5), numpy.sqrt(0.5), 0.0]], atol=1e-12) + + +@pytest.mark.parametrize('axis', [-1, 3, 4]) +def test_rotate_rejects_invalid_axis(axis: int) -> None: + poly = { + 'vertices': numpy.array([[1.0, 2.0, 3.0]]), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + + with pytest.raises(adze.AdzeError, match='Axis must be 0, 1, or 2'): + adze.transform.rotate(poly, numpy.pi / 2, axis=axis) + + +def test_affine_requires_4x4_matrix() -> None: + poly = { + 'vertices': numpy.array([[1.0, 2.0, 3.0]]), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + + with pytest.raises(adze.AdzeError, match='shape \\(4, 4\\)'): + adze.transform.affine(poly, numpy.eye(3)) + + +def test_affine_rejects_zero_homogeneous_coordinate() -> None: + poly = { + 'vertices': numpy.array([[1.0, 2.0, 3.0]]), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + xform = numpy.array([ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 0.0], + ]) + + with pytest.raises(adze.AdzeError, match='zero homogeneous coordinate'): + adze.transform.affine(poly, xform) + + +def test_affine_identity_preserves_multiple_vertices() -> None: + poly = { + 'vertices': numpy.array([ + [1.0, 0.0, 0.0], + [2.0, 1.0, 0.0], + ]), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + + transformed = adze.transform.affine(poly, numpy.eye(4)) + assert_allclose(transformed['vertices'], [[1.0, 0.0, 0.0], [2.0, 1.0, 0.0]]) + + +def test_affine_translation_applies_to_multiple_vertices() -> None: + poly = { + 'vertices': numpy.array([ + [1.0, 0.0, 0.0], + [2.0, 1.0, 0.0], + ]), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + xform = numpy.array([ + [1.0, 0.0, 0.0, 1.0], + [0.0, 1.0, 0.0, 2.0], + [0.0, 0.0, 1.0, 3.0], + [0.0, 0.0, 0.0, 1.0], + ]) + + transformed = adze.transform.affine(poly, xform) + assert_allclose(transformed['vertices'], [[2.0, 2.0, 3.0], [3.0, 3.0, 3.0]]) + + +def test_affine_promotes_integer_vertices_to_float() -> None: + poly = { + 'vertices': numpy.array([[1, 1, 1]], dtype=int), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + xform = numpy.array([ + [1.0, 0.0, 0.0, 0.5], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ]) + + transformed = adze.transform.affine(poly, xform) + + assert numpy.issubdtype(transformed['vertices'].dtype, numpy.floating) + assert_allclose(transformed['vertices'], [[1.5, 1.0, 1.0]]) + + +def test_translate_promotes_integer_vertices_to_float() -> None: + poly = { + 'vertices': numpy.array([[1, 0, 0]], dtype=int), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + + transformed = adze.transform.translate(poly, [0.5, 1.0, 0.0]) + + assert numpy.issubdtype(transformed['vertices'].dtype, numpy.floating) + assert_allclose(transformed['vertices'], [[1.5, 1.0, 0.0]]) + + +def test_scale_promotes_integer_vertices_to_float() -> None: + poly = { + 'vertices': numpy.array([[1, 1, 1]], dtype=int), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + + transformed = adze.transform.scale(poly, 0.5) + + assert numpy.issubdtype(transformed['vertices'].dtype, numpy.floating) + assert_allclose(transformed['vertices'], [[0.5, 0.5, 0.5]]) + + +@pytest.mark.parametrize('shift', [[1.0, 2.0], [1.0, 2.0, 3.0, 4.0]]) +def test_translate_rejects_invalid_shift_shape(shift: list[float]) -> None: + poly = { + 'vertices': numpy.array([[1.0, 0.0, 0.0]]), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + + with pytest.raises(adze.AdzeError, match='Shift must have shape'): + adze.transform.translate(poly, shift) + + +@pytest.mark.parametrize('factor', [[1.0, 2.0], [1.0, 2.0, 3.0, 4.0]]) +def test_scale_rejects_invalid_factor_shape(factor: list[float]) -> None: + poly = { + 'vertices': numpy.array([[1.0, 0.0, 0.0]]), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + + with pytest.raises(adze.AdzeError, match='Scale factor must be a scalar or have shape'): + adze.transform.scale(poly, factor) diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py new file mode 100644 index 0000000..255d4b1 --- /dev/null +++ b/adze/test/test_voxel.py @@ -0,0 +1,115 @@ +from typing import TYPE_CHECKING +import logging +import warnings +from time import perf_counter + +import numpy +from numpy.typing import NDArray +from numpy.testing import assert_allclose + +import adze +import adze.util + +from .utils import TOL_FAIL, TOL_WARN, rand_tetrahedron_vertices +#from .utils import PRNG, MIN_VOLUME, flip_plane, tetrahedron_volume +#from .utils import build_rand_tetrahedron, gen_plane_through_centroid, plane_generators, gen_torus_brep + +if TYPE_CHECKING: + import matplotlib + + +logger = logging.getLogger(__name__) + + +def test_voxelization(poly_order: int, grid_resolution: int | None = None) -> None: + """ + Test that the voxelized moments sum to those of the original input + """ + if grid_resolution is None: + grid_resolution = 250 if poly_order == 0 else 50 + + verts = 1.5 * (numpy.array(rand_tetrahedron_vertices()) + 1) + poly = adze.build_tetrahedron(verts) + moments = adze.get_moments(poly, poly_order) + + edges = [numpy.linspace(-1, 3, grid_resolution) for _ in range(3)] + logger.info(f'Voxelizing a tetrahedron to a grid with moments of order {poly_order}') + t0 = perf_counter() + grid = adze.voxelize(poly, edges, order=poly_order) + logger.info(f'voxel time: {perf_counter() - t0}') + + #visualize_isosurface(grid[:, :, :, 0], edges) + + voxsum = numpy.sum(grid, axis=(0, 1, 2)) + + assert_allclose(moments, voxsum, atol=TOL_FAIL) + if not numpy.allclose(moments, voxsum, atol=TOL_WARN): + warnings.warn('Moments failed tolerance in voxels', stacklevel=1) + + +def test_voxelization_include_outside_keeps_axis_assignment() -> None: + poly = adze.build_box([[-1, 0, 0], [2, 1, 1]]) + edges = [numpy.array([0.0, 1.0]) for _ in range(3)] + + grid = adze.voxelize(poly, edges, include_outside=True, order=0) + voxels = grid[..., 0] + + assert voxels.shape == (3, 3, 3) + assert_allclose(voxels.sum(axis=(1, 2)), [1.0, 1.0, 1.0]) + assert_allclose(voxels.sum(axis=(0, 2)), [0.0, 3.0, 0.0]) + assert_allclose(voxels.sum(axis=(0, 1)), [0.0, 3.0, 0.0]) + + +def visualize_isosurface( + grid: NDArray[numpy.float64], + edges: NDArray[numpy.int64], + level: float | None = None, + show_edges: bool = True, + finalize: bool = True, + ) -> tuple['matplotlib.figure.Figure', 'matplotlib.axes.Axes']: + """ + Draw an isosurface plot of the device. + + Args: + level: Value at which to find isosurface. Default (None) uses mean value in grid. + show_edges: Whether to draw triangle edges. Default True + finalize: Whether to call pyplot.show() after constructing the plot. Default True + """ + from matplotlib import pyplot + import skimage.measure + # Claims to be unused, but needed for subplot(projection='3d') + from mpl_toolkits.mplot3d import Axes3D + del Axes3D # imported for side-effects only + + if level is None: + level = grid.mean() + + # Find isosurface with marching cubes + verts, faces, _normals, _values = skimage.measure.marching_cubes(grid, level) + + xs, ys, zs = (edges[aa][verts[:, aa].astype(int)] for aa in range(3)) + + # Draw the plot + fig = pyplot.figure() + ax = fig.add_subplot(111, projection='3d') + if show_edges: + ax.plot_trisurf(xs, ys, faces, zs) + else: + ax.plot_trisurf(xs, ys, faces, zs, edgecolor='none') + + # Add a fake plot of a cube to force the axes to be equal lengths + max_range = numpy.array([xs.max() - xs.min(), + ys.max() - ys.min(), + zs.max() - zs.min()], dtype=float).max() + mg = numpy.mgrid[-1:2:2, -1:2:2, -1:2:2] + xbs = 0.5 * max_range * mg[0].flatten() + 0.5 * (xs.max() + xs.min()) + ybs = 0.5 * max_range * mg[1].flatten() + 0.5 * (ys.max() + ys.min()) + zbs = 0.5 * max_range * mg[2].flatten() + 0.5 * (zs.max() + zs.min()) + # Comment or uncomment following both lines to test the fake bounding box: + for xb, yb, zb in zip(xbs, ybs, zbs, strict=True): + ax.plot([xb], [yb], [zb], 'w') + + if finalize: + pyplot.show() + + return fig, ax diff --git a/adze/test/utils.py b/adze/test/utils.py new file mode 100644 index 0000000..97c4ef6 --- /dev/null +++ b/adze/test/utils.py @@ -0,0 +1,208 @@ +from typing import cast +from collections.abc import Sequence +import random +import numpy +from numpy.typing import NDArray +from numpy import pi, cos, sin, floating +from numpy.linalg import norm + +import adze + + +PRNG = numpy.random.RandomState(12345) +PRNG_PYRANDOM = random.Random(12345) + + +# numerical tolerances for pass/warn/fail tests +TOL_WARN = 1e-8 +TOL_FAIL = 1e-4 + +# minimum volume allowed for test polyhedra +MIN_VOLUME = 1e-8 + +# order of polynomial integration for all tests +POLY_ORDER = 0 + + +def gen_torus_brep( + n_theta: int = 20, + n_phi: int = 20, + r0: float = 1.0, + r1: float = 0.1, + ) -> tuple[NDArray[numpy.float64], NDArray[numpy.intp]]: + """ + Generate a boundary representation for an elliptical torus + """ + # Generate vertices + theta, phi = numpy.meshgrid( + numpy.linspace(0, 2*pi, n_theta, endpoint=False), + numpy.linspace(0, 2*pi, n_phi, endpoint=False), + ) + theta = theta.ravel(order='F') + phi = phi.ravel(order='F') + + vertices = numpy.column_stack(( + (r0 + r1 * cos(theta)) * cos(phi), + (r0 + r1 * cos(theta)) * sin(phi), + r1 * sin(theta), + )) + + # Generate faces + i, j = numpy.meshgrid(numpy.arange(n_phi), numpy.arange(n_theta), indexing='ij') + + a = i * n_theta + j + b = ((i + 1) % n_phi) * n_theta + c = (j + 1) % n_theta + + aa = numpy.hstack((a, a)).ravel() + bb = numpy.hstack((b + j, b + c)).ravel() + cc = numpy.hstack((b + c, c + i * n_theta)).ravel() + + faces = numpy.column_stack((aa, bb, cc)) + + return vertices, faces + + +def tetrahedron_volume(vertices: NDArray | Sequence[NDArray]) -> float: + ad, bd, cd = vertices[0:3] - vertices[3] + return -ad @ numpy.cross(bd, cd) / 6 + + +def flip_plane(plane: adze.plane_t) -> adze.plane_t: + return (-plane[0], -plane[1]) + + +def rand_tetrahedron_vertices(min_volume: float = MIN_VOLUME) -> NDArray[numpy.float64]: + # generates a random tetrahedron with vertices on the unit sphere, + # guaranteeing a volume of at least min_volume + volume = 0.0 + while volume < min_volume: + verts = [rand_unit_vector() for _ in range(4)] + volume = tetrahedron_volume(verts) + if volume < 0: + verts[2], verts[3] = verts[3], verts[2] + volume = -volume + return numpy.asarray(verts) + + +def build_rand_tetrahedron(min_volume: float = MIN_VOLUME) -> adze.poly_t: + return adze.build_tetrahedron(rand_tetrahedron_vertices(min_volume=min_volume)) + + +def rand_unit_vector() -> NDArray[numpy.float64]: + # generates a random, isotropically distributed unit vector + s: numpy.floating | float = 0.0 + while s == 0.0: + v = PRNG.randn(3) + s = norm(v) + return v / s + + +def get_centroid(poly: adze.poly_t) -> NDArray[numpy.floating]: + """ + Average the vertices to get the centroid + """ + centroid = numpy.sum(poly['vertices'], axis=0) / poly['vertices'].shape[0] + return centroid + + +def gen_plane_through_centroid( + poly: adze.poly_t, + ) -> adze.plane_t: + """ + Generate a randomly-oriented plane passing through the polyhedron's centroid + """ + centroid = get_centroid(poly) + n = rand_unit_vector() + d = cast('numpy.floating', -n @ centroid) + return n, d + + +def gen_plane_from_face( + poly: adze.poly_t, + ) -> adze.plane_t: + """ + Generate a plane coplanar with one of the polyhedron's faces + """ + # make a plane coplanar with a face of the poly + v0 = PRNG.randint(poly['vertices'].shape[0]) + v1, v2 = PRNG_PYRANDOM.sample(list(poly['neighbors'][v0]), 2) + points = (poly['vertices'][vi] for vi in (v0, v1, v2)) + return gen_plane_through_points(*points) + + +def gen_plane_through_centroid_and_edge( + poly: adze.poly_t, + ) -> adze.plane_t: + """ + Generate a plane through an edge of the polyhedron and the polyhedron's centroid + """ + v0 = PRNG.randint(poly['vertices'].shape[0]) + v1 = PRNG.choice(poly['neighbors'][v0]) + p0 = poly['vertices'][v0] + p1 = poly['vertices'][v1] + centroid = get_centroid(poly) + return gen_plane_through_points(p0, p1, centroid) + + +def gen_plane_through_edge( + poly: adze.poly_t, + ) -> adze.plane_t: + """ + Generate a plane through an edge of the polyhedron, but otherwise randomly oriented + """ + v0 = PRNG.randint(poly['vertices'].shape[0]) + v1 = PRNG.choice(poly['neighbors'][v0]) + p0 = poly['vertices'][v0] + p1 = poly['vertices'][v1] + return gen_plane_through_points(p0, p1, rand_unit_vector()) + + +def gen_plane_through_centroid_and_vertex( + poly: adze.poly_t, + ) -> adze.plane_t: + """ + Generate a plane through a vertex and the centroid, but otherwise randomly oriented + """ + vertices = poly['vertices'] + p0 = vertices[PRNG.choice(vertices.shape[0])] + centroid = get_centroid(poly) + return gen_plane_through_points(p0, centroid, rand_unit_vector()) + + +def gen_plane_through_vertex( + poly: adze.poly_t, + ) -> adze.plane_t: + """ + Generate a plane passing through a vertex, but otherwise randomly oriented + """ + vertices = poly['vertices'] + p0 = vertices[PRNG.choice(vertices.shape[0])] + n = rand_unit_vector() + d = -n @ p0 + return n, d + + +def gen_plane_through_points( + p0: NDArray[floating], + p1: NDArray[floating], + p2: NDArray[floating], + ) -> adze.plane_t: + """ + Generate a plane passing through three given points + """ + n = numpy.cross(p1 - p0, p2 - p0) + n /= norm(n) + 1e-40 + d = -n @ p0 + return n, d + + +plane_generators = [ + gen_plane_through_centroid, + gen_plane_from_face, + gen_plane_through_centroid_and_edge, + gen_plane_through_edge, + gen_plane_through_centroid_and_vertex, + gen_plane_through_vertex, + ] + diff --git a/adze/test_results.txt b/adze/test_results.txt new file mode 100644 index 0000000..e89dde7 --- /dev/null +++ b/adze/test_results.txt @@ -0,0 +1,129 @@ +============================= test session starts ============================== +platform linux -- Python 3.8.2, pytest-4.6.9, py-1.8.1, pluggy-0.13.0 +rootdir: /d/home/jan/projects/adze +collected 6 items + +test/test_split.py FFFFFF [100%] + +=================================== FAILURES =================================== +__________________________ test_manual_tetrahedron[0] __________________________ + +poly_order = 0 + + def test_manual_tetrahedron(poly_order): +> tet = build_tetrahedron([ + [0,0,0], + [2,0,0], + [0,2,0], + [0,0,2]]) +E NameError: name 'build_tetrahedron' is not defined + +test/test_split.py:20: NameError +____________________ test_tetrahedrons_through_centroid[0] _____________________ + +poly_order = 0 + + def test_tetrahedrons_through_centroid(poly_order): + """ + Splits some tetrahedrons through their centroids and + checks if the two resulting volumes sum up to the original + """ + + # Generate random tetrahedrons and clip planes + ntets = 100 +> polys = [build_rand_tetrahedron() for _ in range(ntets)] + +test/test_split.py:57: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +test/test_split.py:57: in + polys = [build_rand_tetrahedron() for _ in range(ntets)] +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +min_volume = 1e-08 + + def build_rand_tetrahedron(min_volume: float = MIN_VOL): +> return build_tetrahedron(rand_tetrahedron_vertices()) +E NameError: name 'build_tetrahedron' is not defined + +test/utils.py:42: NameError +__________________________ test_manual_tetrahedron[1] __________________________ + +poly_order = 1 + + def test_manual_tetrahedron(poly_order): +> tet = build_tetrahedron([ + [0,0,0], + [2,0,0], + [0,2,0], + [0,0,2]]) +E NameError: name 'build_tetrahedron' is not defined + +test/test_split.py:20: NameError +____________________ test_tetrahedrons_through_centroid[1] _____________________ + +poly_order = 1 + + def test_tetrahedrons_through_centroid(poly_order): + """ + Splits some tetrahedrons through their centroids and + checks if the two resulting volumes sum up to the original + """ + + # Generate random tetrahedrons and clip planes + ntets = 100 +> polys = [build_rand_tetrahedron() for _ in range(ntets)] + +test/test_split.py:57: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +test/test_split.py:57: in + polys = [build_rand_tetrahedron() for _ in range(ntets)] +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +min_volume = 1e-08 + + def build_rand_tetrahedron(min_volume: float = MIN_VOL): +> return build_tetrahedron(rand_tetrahedron_vertices()) +E NameError: name 'build_tetrahedron' is not defined + +test/utils.py:42: NameError +__________________________ test_manual_tetrahedron[2] __________________________ + +poly_order = 2 + + def test_manual_tetrahedron(poly_order): +> tet = build_tetrahedron([ + [0,0,0], + [2,0,0], + [0,2,0], + [0,0,2]]) +E NameError: name 'build_tetrahedron' is not defined + +test/test_split.py:20: NameError +____________________ test_tetrahedrons_through_centroid[2] _____________________ + +poly_order = 2 + + def test_tetrahedrons_through_centroid(poly_order): + """ + Splits some tetrahedrons through their centroids and + checks if the two resulting volumes sum up to the original + """ + + # Generate random tetrahedrons and clip planes + ntets = 100 +> polys = [build_rand_tetrahedron() for _ in range(ntets)] + +test/test_split.py:57: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +test/test_split.py:57: in + polys = [build_rand_tetrahedron() for _ in range(ntets)] +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +min_volume = 1e-08 + + def build_rand_tetrahedron(min_volume: float = MIN_VOL): +> return build_tetrahedron(rand_tetrahedron_vertices()) +E NameError: name 'build_tetrahedron' is not defined + +test/utils.py:42: NameError +=========================== 6 failed in 2.42 seconds =========================== diff --git a/adze/transform.py b/adze/transform.py index 8c77c71..fd40d11 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -1,65 +1,142 @@ import numpy from numpy import sin, cos +from numpy.typing import ArrayLike -from . import poly_t, plane_t +from . import poly_t +from .util import AdzeError + + +def _normalize_vertices(poly: poly_t) -> numpy.ndarray: + vertices = numpy.asarray(poly['vertices']) + if vertices.ndim != 2 or vertices.shape[1] != 3: + raise AdzeError(f"Vertices must have shape (N, 3). Got {vertices.shape}") + if not numpy.isfinite(vertices).all(): + raise AdzeError('Vertices must contain only finite values') + if not numpy.issubdtype(vertices.dtype, numpy.floating): + vertices = vertices.astype(float) + poly['vertices'] = vertices + return vertices + + +def _normalize_theta(theta: float) -> float: + try: + angle = float(theta) + except (TypeError, ValueError) as exc: + raise AdzeError('Rotation angle must be a scalar') from exc + if not numpy.isfinite(angle): + raise AdzeError('Rotation angle must be finite') + return angle + + +def _normalize_vector(value: ArrayLike, name: str) -> numpy.ndarray: + vector = numpy.asarray(value, dtype=float) + if vector.shape != (3,): + raise AdzeError(f'{name} must have shape (3,). Got {vector.shape}') + if not numpy.isfinite(vector).all(): + raise AdzeError(f'{name} must contain only finite values') + return vector + + +def _normalize_scale_factor(factor: ArrayLike | float) -> float | numpy.ndarray: + afactor = numpy.asarray(factor, dtype=float) + if afactor.shape == (): + scalar = float(afactor) + if not numpy.isfinite(scalar): + raise AdzeError('Scale factor must be finite') + return scalar + if afactor.shape != (3,): + raise AdzeError(f'Scale factor must be a scalar or have shape (3,). Got {afactor.shape}') + if not numpy.isfinite(afactor).all(): + raise AdzeError('Scale factor must contain only finite values') + return afactor 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. + Args: + poly: Polyhedron to rotate. Changed in-place. + theta: Angle to rotate by (radians). + axis: Axis to rotate around (0-2). + + Returns: + Rotated polyhedron. Data is altered in-place but also returned for convenience. - ''' + """ + if axis not in (0, 1, 2): + raise AdzeError(f'Axis must be 0, 1, or 2. Got {axis}') + + vertices = _normalize_vertices(poly) + theta = _normalize_theta(theta) 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 + v0 = vertices[:, axis - 2].copy() + v1 = vertices[:, axis - 1] + vertices[:, axis - 2] = c * v0 - s * v1 + vertices[:, axis - 1] = s * v0 + c * v1 return poly -def translate(poly: poly_t, shift: numpy.ndarray) -> poly_t: - ''' +def translate(poly: poly_t, shift: ArrayLike) -> 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. + Args: + poly: Polyhedron to translate. Changed in-place. + shift: Vector to translate by. + + Returns: + Translated polyhedron. Data is altered in-place but also returned for convenience. - ''' - poly['vertices'] += shift + """ + vertices = _normalize_vertices(poly) + vertices += _normalize_vector(shift, 'Shift') return poly -def scale(poly: poly_t, factor: numpy.ndarray or float) -> poly_t: - ''' +def scale(poly: poly_t, factor: ArrayLike | 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. + Args: + poly: Polyhedron to scale. Changed in-place. + factor: Scalar or vector to scale by. + + Returns: + Scaled polyhedron. Data is altered in-place but also returned for convenience. - ''' - poly['vertices'] *= factor + """ + vertices = _normalize_vertices(poly) + vertices *= _normalize_scale_factor(factor) return poly -def affine(poly: poly_t, xform: numpy.ndarray) -> poly_t: - ''' - Perform arbitrary affine trasnformation on the polyhedron. +def affine(poly: poly_t, xform: ArrayLike) -> poly_t: + """ + Perform an arbitrary homogeneous 4x4 transformation on the polyhedron. - :param poly: Polyhedron to transform. Changed in-place. - :param xform: 4x4 affine transformation matrix. - :return: Transformed polyhedron. + Args: + poly: Polyhedron to transform. Changed in-place. + xform: 4x4 homogeneous transformation matrix. The transformed homogeneous + coordinates are divided by the fourth row, so projective transforms are + supported in addition to affine ones. + + Returns: + Transformed polyhedron. Data is altered in-place but also returned for convenience. - ''' + """ + vertices = _normalize_vertices(poly) + xform = numpy.array(xform, copy=False) + if xform.shape != (4, 4): + raise AdzeError(f'Affine transform matrix must have shape (4, 4). Got {xform.shape}') + if not numpy.isfinite(xform).all(): + raise AdzeError('Affine transform matrix must contain only finite values') + mat4x3 = xform[:, :3] - mat4x1 = xform[:, 3] - vh = mat4x3 @ poly['vertices'].T + mat4x1 - poly['vertices'][:] = (vh[:3, :] / vh[3, :]).T + mat4x1 = xform[:, 3:4] + vh = mat4x3 @ vertices.T + mat4x1 + if numpy.any(vh[3, :] == 0): + raise AdzeError('Affine transform produced points with zero homogeneous coordinate') + vertices[:] = (vh[:3, :] / vh[3, :]).T return poly diff --git a/adze/util.py b/adze/util.py index c7c14b7..ed4b3d7 100644 --- a/adze/util.py +++ b/adze/util.py @@ -1,41 +1,78 @@ -from typing import Dict, Tuple, List +from typing import TYPE_CHECKING +from collections.abc import Sequence import numpy +from numpy.typing import NDArray -try: - # Check if running with line_profiler - profile -except NameError: - def profile(f): - return f +if TYPE_CHECKING: + import stl -plane_t = Tuple[numpy.ndarray, float] -poly_t = Dict[str, numpy.ndarray] +plane_t = tuple[NDArray[numpy.floating], float | numpy.floating] +poly_t = dict[str, NDArray] + + +class AdzeError(Exception): + """ Custom error for Adze """ + pass def build_empty() -> poly_t: - ''' + """ Build an empty Schlegel representation (containing no vertices). - :return: Empty Schelegel representation. - ''' + Returns: + 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: - ''' +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), + } + + +def find_components(neighbors: NDArray[numpy.integer]) -> NDArray[numpy.integer]: + """ 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 + 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 which connected component the vertex belongs to. - ''' + """ num_vertices = neighbors.shape[0] current_component = 1 component = numpy.zeros(num_vertices, dtype=int) @@ -53,94 +90,97 @@ def find_components(neighbors: numpy.ndarray) -> numpy.ndarray: return component - 1 -@profile -def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]: - ''' +def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.intp]]: + """ 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 + Args: + neighbors: Nx3 adjacency list. Neighbors are specified by their + indices. + + Returns: + 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] + if num_verts == 0: + return [] 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 + faces_arr = numpy.full((3 * num_verts, num_verts - 1), -1, dtype=int) + faces_arr[:, 0] = v_current - def add_edges(edge_id, v_nxt, k): - faces[edge_id, k] = v_nxt + def add_edges(edge_id: NDArray[numpy.intp], v_nxt: NDArray[numpy.intp], kk: int) -> None: + faces_arr[edge_id, kk] = v_nxt - def cleaned_faces(remove, k): + def cleaned_faces(remove: NDArray[numpy.int8], kk: int) -> list[NDArray[numpy.intp]]: faces_set = [] - for row in faces[~remove, :k]: + for row in faces_arr[~remove, :kk]: faces_set.append(row[row >= 0]) return faces_set else: # Alternative approach, less memory-intensive but slower - faces = [[v] for v in v_current] + faces_list = [[vv] for vv 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 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): + faces_list[ii].append(vn) - def cleaned_faces(remove, _k): + def cleaned_faces(remove: NDArray[numpy.int8], kk: int) -> list[NDArray[numpy.intp]]: # noqa: ARG001 faces_set = [] - for i in numpy.where(~remove)[0]: - faces_set.append(faces[i]) + for ii in numpy.where(~remove)[0]: + faces_set.append(numpy.asarray(faces_list[ii], dtype=numpy.intp)) 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 + """ + kk = 1 mask = v_next > v_current - v = numpy.vstack((edge_id, v_start, v_current, v_next))[:, mask] + vv = 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) + add_edges(vv[0], vv[3], kk) - prv_edge = (neighbors[v[3], :] == v[2][:, None]).argmax(axis=1) + prv_edge = (neighbors[vv[3], :] == vv[2][:, None]).argmax(axis=1) nxt_edge = (prv_edge + 1) % 3 - v[2:4] = v[3], neighbors[v[3], nxt_edge] + vv[2:4] = vv[3], neighbors[vv[3], nxt_edge] - remove_mask = v[2] < v[1] - remove[v[0][remove_mask]] = True + remove_mask = vv[2] < vv[1] + remove[vv[0][remove_mask]] = True - mask = numpy.logical_and(v[3] != v[1], ~remove_mask) - v = v[:, mask] - k += 1 + mask = numpy.logical_and(vv[3] != vv[1], ~remove_mask) + vv = vv[:, mask] + kk += 1 - return cleaned_faces(remove, k) + return cleaned_faces(remove, kk) -@profile -def _get_map(a, b): - ''' +def _get_map(a: NDArray, b: NDArray) -> NDArray[numpy.intp]: + """ 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(()) + return numpy.array((), dtype=numpy.intp) sa = a.argsort() sb = b.argsort() r = numpy.empty_like(sa) @@ -148,25 +188,23 @@ def _get_map(a, b): return sa[r] -@profile -def _get_map_rows(a, b): - ''' +def _get_map_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]: + """ 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) + a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore + b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore return _get_map(a1d, b1d) -@profile -def _get_maps(a, b): - ''' +def _get_maps(a: NDArray, b: NDArray) -> tuple[NDArray[numpy.intp], NDArray[numpy.intp]]: + """ 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(()) + return numpy.array((), dtype=numpy.intp), numpy.array((), dtype=numpy.intp) sa = a.argsort() sb = b.argsort() r = numpy.empty_like(sa) @@ -177,67 +215,73 @@ def _get_maps(a, b): return m, n -@profile -def _get_maps_rows(a, b): - ''' +def _get_maps_rows(a: NDArray, b: NDArray) -> tuple[NDArray[numpy.intp], NDArray[numpy.intp]]: + """ 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) + a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore + b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore return _get_maps(a1d, b1d) -def _argsort_rows(a): - ''' +def _argsort_rows(a: NDArray) -> NDArray[numpy.intp]: + """ Row-wise argsort - ''' + """ dims = a.max(0) + 1 - a1d = numpy.ravel_multi_index(a.T, dims) + a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore return numpy.argsort(a1d) -def _searchsorted_rows(a, b): - ''' +def _searchsorted_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]: + """ 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) + a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore + b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore return numpy.searchsorted(a1d, b1d) -def check_poly(poly: poly_t, check_connectivity: bool = True): - ''' +def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: + """ 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 - ''' + 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 + """ neighbors = poly['neighbors'] vertices = poly['vertices'] num_vertices = vertices.shape[0] + if vertices.ndim != 2 or vertices.shape[1] != 3: + raise AdzeError(f'Vertices must have shape (N, 3). Got {vertices.shape}') + if neighbors.shape != (num_vertices, 3): + raise AdzeError(f'Neighbors must have shape ({num_vertices}, 3). Got {neighbors.shape}') 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') + raise AdzeError(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') + raise AdzeError(f'Vertices {which_vertices} have duplicate neighbors') - vertex_uses = numpy.bincount(neighbors.ravel()) + vertex_uses = numpy.bincount(neighbors.ravel(), minlength=num_vertices) 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,' + raise AdzeError(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) @@ -255,7 +299,7 @@ def check_poly(poly: poly_t, check_connectivity: bool = True): va = part_verts[ia] for vb in part_verts[ia + 1:]: # pick vc != {va, vb} - vc = (vcs - set((va, vb))).pop() + vc = (vcs - {va, vb}).pop() # flood-fill from vc without passing through va, vb visited.fill(False) @@ -269,4 +313,120 @@ def check_poly(poly: poly_t, check_connectivity: bool = True): # 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') + raise AdzeError('Vertex graph is not 3-vertex-connected') + + +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) + + +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 diff --git a/adze/voxel.py b/adze/voxel.py index 79f91a0..11d81ca 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -1,62 +1,69 @@ -from typing import Tuple, List +from collections.abc import Sequence import numpy +from numpy.typing import ArrayLike, NDArray -from . import poly_t, plane_t +from . import poly_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 +from .util import AdzeError -@profile -def voxelize(poly: poly_t, - planes: List[numpy.ndarray], - include_outside: bool = False, - order: int = 0, - ) -> numpy.ndarray: - ''' +def voxelize( + poly: poly_t, + planes: Sequence[ArrayLike], + include_outside: bool = False, + order: int = 0, + ) -> NDArray[numpy.float64]: + """ 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]] + `[[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 + `[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 + 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] + Args: + poly: Polyhedron to voxelize. + planes: List of coordinate lists, specifying the axis-aligned planes + which form the voxel grid: + `[[x0, x1, ..., xX], [y0, y1, ..., yY], [z0, z1, ..., zZ]]` + include_outside: Whether to include cells corresponding to portions of the + polyhedron that fall outside of the grid. Default `False`. + order: Polynomial order of moments to calculate. Default `0`. - num_planes = numpy.array([e.size for e in planes], dtype=int) + Returns: + (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)`. + """ + if len(planes) != 3: + raise AdzeError(f'Need exactly three plane axes. Got {len(planes)}') + + aplanes = [numpy.asarray(p, dtype=float) for p in planes] + for axis, axis_planes in enumerate(aplanes): + if axis_planes.ndim != 1: + raise AdzeError(f'Plane axis {axis} must be 1-dimensional. Got {axis_planes.shape}') + if numpy.any(numpy.diff(axis_planes) <= 0): + raise AdzeError(f'Plane axis {axis} must be strictly increasing') + + num_planes = numpy.array([e.size for e in aplanes], dtype=int) if (num_planes < 2).any(): - # TODO raw exception - raise Exception(f'Need at least two planes per dimension. Got {num_planes} planes.') + raise AdzeError(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_offset = 0 + else: grid_shape = num_planes - 1 - for face in planes_from_box([[p[0] for p in planes], - [p[-1] for p in planes]]): + grid_offset = -1 + for face in planes_from_box([[p[0] for p in aplanes], + [p[-1] for p in aplanes]]): poly = clip(poly, face) grid = numpy.zeros((*grid_shape, number_of_moments(order)), dtype=float) @@ -64,7 +71,7 @@ def voxelize(poly: poly_t, if poly['vertices'].shape[0] == 0: return grid - slices = numpy.array([(0, e.size) for e in planes], dtype=int) + slices = numpy.array([(0, e.size) for e in aplanes], dtype=int) stack = [(poly, slices)] while stack: poly, slices = stack.pop() @@ -78,14 +85,14 @@ def voxelize(poly: poly_t, # 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 + i, j, k = slices[:, 0] + grid_offset 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_ind = (num_planes_remaining[axis] // 2 + slices[axis, 0])[0] + plane_pos = aplanes[axis][plane_ind] plane = (numpy.roll([-1, 0, 0], axis), plane_pos) poly_left, poly_right = split(poly, plane) @@ -98,4 +105,3 @@ def voxelize(poly: poly_t, stack.append((poly_left, slices_left)) stack.append((poly_right, slices_right)) return grid - diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..6c95a0f --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,91 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "adze" +description = "Polyhedron clipping and antialiased voxelization" +readme = "README.md" +license = { file = "LICENSE.md" } +authors = [ + { name="Jan Petykiewicz", email="jan@mpxd.net" }, + ] +homepage = "https://mpxd.net/code/jan/adze" +repository = "https://mpxd.net/code/jan/adze" +keywords = [ + "geometry", + "geometric", + "polyhedron", + "voxel", + "voxelize", + "clip", + "clipping", + "split", + "moment", + "schlegel", + "3D", + "boolean", + ] +classifiers = [ + "Programming Language :: Python :: 3", + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: GNU Affero General Public License v3", + "Operating System :: OS Independent", + "Topic :: Multimedia :: Graphics", + "Topic :: Scientific/Engineering", + ] +requires-python = ">=3.11" +dynamic = ["version"] +dependencies = [ + "numpy>=1.26", + ] + +[tool.hatch.version] +path = "adze/__init__.py" + +[project.optional-dependencies] +stl = ["stl"] +test = ["pytest", "pytest-benchmark"] + +[tool.ruff] +exclude = [ + ".git", + "dist", + ] +line-length = 145 +indent-width = 4 +lint.dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" +lint.select = [ + "NPY", "E", "F", "W", "B", "ANN", "UP", "SLOT", "SIM", "LOG", + "C4", "ISC", "PIE", "PT", "RET", "TCH", "PTH", "INT", + "ARG", "PL", "R", "TRY", + "G010", "G101", "G201", "G202", + "Q002", "Q003", "Q004", + ] +lint.ignore = [ + #"ANN001", # No annotation + "ANN002", # *args + "ANN003", # **kwargs + "ANN401", # Any + "SIM108", # single-line if / else assignment + "RET504", # x=y+z; return x + "PIE790", # unnecessary pass + "ISC003", # non-implicit string concatenation + "C408", # dict(x=y) instead of {'x': y} + "PLR09", # Too many xxx + "PLR2004", # magic number + "PLC0414", # import x as x + "TRY003", # Long exception message + ] + + +[[tool.mypy.overrides]] +module = [ + "matplotlib", + "mpl_toolkits", + "mpl_toolkits.mplot3d", + "stl", + ] +ignore_missing_imports = true diff --git a/setup.py b/setup.py deleted file mode 100644 index b2c6582..0000000 --- a/setup.py +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env python3 - -from setuptools import setup, find_packages - -setup(name='adze', - version='0.1', - description='Polyhedron clipping and antialiased voxelization', - author='Jan Petykiewicz', - author_email='anewusername@gmail.com', - url='https://mpxd.net/code/jan/adze', - keywords=[ - 'geometry', - 'geometric', - 'polyhedron', - 'voxel', - 'voxelize', - 'clip', - 'clipping', - 'split', - 'moment', - 'schlegel', - '3D', - 'boolean', - ], - classifiers=[ - 'Programming Language :: Python', - 'Programming Language :: Python :: 3', - 'Development Status :: 4 - Beta', - 'Environment :: Other Environment', - 'Intended Audience :: Developers', - 'Intended Audience :: Science/Research', - 'License :: OSI Approved', - 'License :: OSI Approved :: GNU Affero General Public License v3', - 'Operating System :: OS Independent', - 'Topic :: Multimedia :: Graphics', - 'Topic :: Scientific/Engineering', - 'Topic :: Scientific/Engineering :: Mathematics', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - packages=find_packages(), - install_requires=[ - 'typing', - 'numpy', - ], - extras_require={ - }, - ) - diff --git a/tpy_r3d.py b/tpy_r3d.py deleted file mode 100644 index 988eb18..0000000 --- a/tpy_r3d.py +++ /dev/null @@ -1,558 +0,0 @@ -import warnings -from time import perf_counter -import random -import logging - -import numpy -from numpy import sin, cos, pi -from numpy.linalg import norm - -from adze import (number_of_moments, get_moments, split, clip, build_tetrahedron, - build_box, planes_from_tetrahedron, build_polyhedron, boundary_from_poly, - voxelize) -from adze.util import check_poly - -try: - # Check if running with line_profiler - profile -except NameError: - def profile(f): - return f - - -logger = logging.getLogger(__name__) - - -# numerical tolerances for pass/warn/fail tests -TOL_WARN = 1e-8 -TOL_FAIL = 1e-4 - -# minimum volume allowed for test polyhedra -MIN_VOL = 1e-8 - -# order of polynomial integration for all tests -POLY_ORDER = 0 - - -def test_split_tet_manual(): - tet = build_tetrahedron([ - [0,0,0], - [2,0,0], - [0,2,0], - [0,0,2]]) - - volume = tetrahedron_volume(tet['vertices']) - logger.debug(f'Splitting manual tetrahedron {tet}') - logger.debug(f'volume {volume}') - - plane = numpy.array((-1, 0, 0)), 1 - p_left, p_right = split(tet, plane) - - logger.debug(f'left {p_left}') - logger.debug(f'right {p_right}') - - check_poly(tet) - check_poly(p_left) - check_poly(p_right) - - m0 = get_moments(tet, 0) - ml = get_moments(p_left, 0) - mr = get_moments(p_right, 0) - - logger.debug(f'0th moments: tot {m0}, left {ml}, right {mr}') - assert(abs(m0 - volume) < TOL_FAIL) - check_split_moments(tet, p_left, p_right, POLY_ORDER) - - -def test_split_tets_thru_centroid(): - # a very basic sanity check. Splits a tet through its centroid - # and checks to see whether the two resulting volumes add up to equal the original - - # generate a random tet and clip plane - ntets = 1 - polys = [build_rand_tetrahedron() for _ in range(ntets)] - plane = plane_centroid(polys[ntets//7]) - - # split them all with the same plane - poly12 = [split(p, plane) for p in polys] - poly1, poly2 = zip(*poly12) - - for orig, p1, p2 in zip(polys, poly1, poly2): - check_poly(orig) - check_poly(p1) - check_poly(p2) - check_split_moments(orig, p1, p2, POLY_ORDER) - - -def time_split(): - NUM_TRIALS = 10_000 - logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') - polys = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)] - facesets = [planes_from_tetrahedron(rand_tetrahedron_vertices()) for _ in range(NUM_TRIALS)] - t0 = perf_counter() - for t in range(NUM_TRIALS): - # clip the first tet against the faces of the second - for face in facesets[t]: - polys[t] = clip(polys[t], face) - if (t+1) % (NUM_TRIALS // 10) == 0: - t_each = (perf_counter() - t0) / (t + 1) - logger.info(f'time per split for {t+1} splits: {t_each}') - logger.info(f'done timing, time per split: {(perf_counter() - t0) / NUM_TRIALS}') - - polys_bulk = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)] - bulk = { - 'vertices': numpy.vstack(p['vertices'] for p in polys_bulk), - 'neighbors': numpy.vstack(p['neighbors'] for p in polys_bulk) + numpy.arange(NUM_TRIALS).repeat(4)[:, None] * 4, - } - t1 = perf_counter() - poly = clip(bulk, facesets[0][0]) - logger.info(f'bulked split time per tet: {(perf_counter() - t1) / NUM_TRIALS}') - - -@profile -def test_tet_tet_timing(): - # Intersects pairs of tetrahedra, for timing purposes only. - - # for timing only, no assertions - NUM_TRIALS = 1000 - t0 = perf_counter() - logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') - for t in range(NUM_TRIALS): - # generate the first random tet - poly = build_rand_tetrahedron() - - # generate the second random tet - faces = planes_from_tetrahedron(rand_tetrahedron_vertices()) - - # clip the first tet against the faces of the second - for face in faces: - poly = clip(poly, face) - - # find the moments (up to quadratic order) of the clipped poly - _om = get_moments(poly, POLY_ORDER) - - if (t+1) % 10000 == 0: - t_each = (perf_counter() - t0) / (t + 1) - logger.info(f'time per split+get_moments for {t+1} iterations: {t_each}') - logger.info(f'done timing, time per split+get_moments: {(perf_counter() - t0) / NUM_TRIALS}') - - -def test_split_nonconvex(): - # a very basic sanity check. Splits a nonconvex poly (a zig-zag prism of sorts) - # and checks to see whether the two resulting volumes add up to equal the original - NZIGS = 3 - ZOFF = 0.1 - - # explicitly create the nonconvex poly - num_verts = 4 * NZIGS - vertices = numpy.empty((num_verts, 3), dtype=float) - neighbors = numpy.empty((num_verts, 3), dtype=int) - - for v in range(NZIGS): - m = NZIGS - v - 1 - v0 = numpy.array([v, v % 2 + ZOFF, 0]) - v1 = numpy.array([m, m % 2, 0]) - vertices[v + 0 * NZIGS] = v0 - vertices[v + 1 * NZIGS] = v1 - vertices[v + 2 * NZIGS] = v0 + (0, 0, 1) - vertices[v + 3 * NZIGS] = v1 + (0, 0, 1) - - nz2 = 2 * NZIGS - for v in range(nz2): - neighbors[v] = ((v + 1) % nz2, - (v - 1) % nz2, - v + nz2) - neighbors[v + nz2] = neighbors[v][[1, 0, 2]] + (nz2, nz2, -nz2) - poly = { - 'vertices': vertices, - 'neighbors': neighbors, - } - - logger.debug("Checking poly...") - check_poly(poly) - logger.debug("poly is valid.") - - def split_and_check(poly, plane, poly_order=0): - poly_l = clip(poly, plane) - poly_r = clip(poly, flip_plane(plane)) - check_split_moments(poly, poly_l, poly_r) - - # split along the x-axis (two single connected components this direction) - split_and_check(poly, [numpy.array((1, 0, 0)), -0.5 * (NZIGS - 1)], POLY_ORDER) - - # split along the z-axis (two single connected components this direction) - split_and_check(poly, [numpy.array((0, 0, 1)), -0.5], POLY_ORDER) - - # split along the y-axis (multiple connected components this direction) - split_and_check(poly, [numpy.array((0, 1, 0)), -0.5 * (1.0 + ZOFF)], POLY_ORDER) - - -def test_recursive_split(num_trials: int = 10, max_depth: int = 6 ): - ''' - Starting with a tetrahedron, recusively split until the pieces - are smaller than MIN_VOL or have been split more than max_depth times - ''' - logger.info(f'Recursively splitting {num_trials} tetrahedra, maximum depth {max_depth}:') - logger.info(f' - Through centroid') - for _ in range(num_trials): - stack_split(build_rand_tetrahedron(), plane_fun=plane_centroid, max_depth=max_depth) - - logger.info(f' - Through degenerate plane') - for _ in range(num_trials): - stack_split(build_rand_tetrahedron(), max_depth=max_depth) - - logger.info(f' - Through perturbed plane') - for t in range(num_trials): - perturb = 10 ** -(1 + t % 16) - stack_split(build_rand_tetrahedron(), perturb=perturb, max_depth=max_depth) - - -@profile -def test_voxelization(): - # Test r3d_voxelize() by checking that the voxelized moments - # sum to those of the original input - POLY_ORDER = 0 - grid_resolution = 250 - - verts = 1.5 * (numpy.array(rand_tetrahedron_vertices()) + 1) - poly = build_tetrahedron(verts) - moments = get_moments(poly, POLY_ORDER) - - edges = [numpy.linspace(-1, 3, grid_resolution) for _ in range(3)] - logger.info(f'Voxelizing a tetrahedron to a grid with moments of order {POLY_ORDER}') - t0 = perf_counter() - grid = voxelize(poly, edges, order=POLY_ORDER) - print(f'voxel time: {perf_counter() - t0}') - - #visualize_voxels(grid) - - voxsum = numpy.sum(grid, axis=(0, 1, 2)) - - assert(numpy.all(numpy.abs(moments - voxsum) < TOL_FAIL)) - if not numpy.all(numpy.abs(moments - voxsum) < TOL_WARN): - warnings.warn('Moments failed tolerance in voxels') - - -def visualize_voxels(grid): - import gridlock - g = gridlock.Grid([numpy.arange(n+1) for n in grid.shape], shifts=[[0, 0, 0]]) - g.grids[0][:] = grid[:, :, :, 0] - g.visualize_isosurface() - - -@profile -def stack_split(poly, plane_fun=None, perturb=0, max_depth=10): - stack = [(poly, 0)] - - i = 0 - while stack: - i += 1 - poly, depth = stack.pop() - - # pick a plane - if plane_fun is None: - pfun_used = random.choice(plane_gen) - plane = pfun_used(poly) - while norm(plane[0]) == 0: - pfun_used = random.choice(plane_gen) - plane = pfun_used(poly) - plane = list(plane) - logger.debug(f'used {pfun_used}') - else: - plane = list(plane_fun(poly)) - - # perturb the plane - plane[0] *= 1 + perturb * (numpy.random.rand() - 0.5) - plane[1] *= 1 + perturb * (numpy.random.rand() - 0.5) - - # split the poly - poly_l = clip(poly, plane) - poly_r = clip(poly, flip_plane(plane)) - m0, ml, mr = check_split_moments(poly, poly_l, poly_r, POLY_ORDER) - - logger.debug(f'nstack = {len(stack)}, depth = {depth}, ' - f'opoly = {m0[0]:.10e}, p1 = {ml[0]:.10e}, p2 = {mr[0]:.10e}, ' - f'err = {abs(1.0 - m0[0]/(ml[0] + mr[0])):.10e}') - - # add the children to the stack if they are big enough - if depth < max_depth: - if ml[0] > MIN_VOL: - stack.append((poly_l, depth + 1)) - if mr[0] > MIN_VOL: - stack.append((poly_r, depth + 1)) - if i % 300 == 0: - logger.info(f'Stack split iter {i} length {len(stack)} depth {depth}') - - -@profile -def test_poly_pyramid(): - vertices = numpy.array([ - [0, 0, 1], - [1, 1, 0], - [1, -1, 0], - [-1, -1, 0], - [-1, 1, 0], - ]) - faces = [ - [0, 1, 2], - [0, 2, 3], - [0, 3, 4], - [0, 4, 1], - [4, 3, 2, 1], - ] - - # initialize a general polyhedron - poly = build_polyhedron(vertices, faces) - check_poly(poly) - stack_split(poly) - - brep = boundary_from_poly(poly) - logger.info(f'Round-trip converted pyramid: {brep}') - #plot_brep(brep) - - -def plot_brep(brep): - import stl - from matplotlib import pyplot - from mpl_toolkits import mplot3d - - meshes = [] - for component in brep: - triangles = [] - for face in component['faces']: - for i in range(1, len(face) - 1): - triangles.append([face[0], face[i], face[i+1]]) - triangles = numpy.array(triangles, dtype=int) - - m = stl.mesh.Mesh(numpy.empty(triangles.shape[0], dtype=stl.mesh.Mesh.dtype)) - for i, f in enumerate(triangles): - for j in range(3): - m.vectors[i, j] = component['vertices'][f[j], :] - -# m.save('pyr.stl') - meshes.append(m) - - figure = pyplot.figure() - axes = mplot3d.Axes3D(figure) - scales = [] - for mesh in meshes: - coll = mplot3d.art3d.Poly3DCollection(m.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() - - -@profile -def test_torus_load_and_chop(): - # Recursively splits a polyhedron (starting from a torus) with a cut plane - # that is always degenerate with the poly in some way, - # checking to see that the resulting volumes add up properly. - # This checks non-convex geometry, and also build_polyhedron() when more than - # three edges per vertex are needed. - - n_th = 20 - n_phi = 20 - r_maj = 1.0 - r_min = 0.1 - - # make vertices - th, phi = numpy.meshgrid( - numpy.linspace(0, 2*pi, n_th, endpoint=False), - numpy.linspace(0, 2*pi, n_phi, endpoint=False), - ) - th, phi = th.ravel(order='F'), phi.ravel(order='F') - - vertices = numpy.column_stack(( - (r_maj + r_min * cos(th)) * cos(phi), - (r_maj + r_min * cos(th)) * sin(phi), - r_min * sin(th), - )) - - # shift away from the origin so that none of the moments are identically zero - vertices += (0.5, 0.7, 0.9) - - # make faces - i, j = numpy.meshgrid(numpy.arange(n_phi), numpy.arange(n_th), indexing='ij') - - a = i * n_th + j - b = ((i + 1) % n_phi) * n_th - c = (j + 1) % n_th - - aa = numpy.hstack((a, a)).ravel() - bb = numpy.hstack((b + j, b + c)).ravel() - cc = numpy.hstack((b + c, c + i * n_th)).ravel() - - faces = numpy.column_stack((aa, bb, cc)) - - - # initialize a general polyhedron - opoly = build_polyhedron(vertices, faces) -# check_poly(opoly) - stack_split(opoly) - - brep = boundary_from_poly(opoly) - logger.debug(f'Round-trip converted torus: {brep}') - #plot_brep(brep) - - -def tetrahedron_volume(vertices): - ad, bd, cd = vertices[0:3] - vertices[3] - return -ad @ numpy.cross(bd, cd) / 6 - - -def flip_plane(plane): - return (-plane[0], -plane[1]) - - -def check_split_moments(original_poly, left_poly, right_poly, poly_order=0): - m0, ml, mr = (get_moments(x, poly_order) for x in (original_poly, left_poly, right_poly)) - logger.debug(f'Check: original {m0[0]} parts {(ml[0], mr[0])} sum {ml[0] + mr[0]}') - - # Make sure each part is smaller than the whole - if not ml[0] < m0[0] * (1.0 + TOL_WARN): - warnings.warn('ml[0] < m0[0]') - assert(ml[0] < m0[0] * (1.0 + TOL_FAIL)) - if not mr[0] < m0[0] * (1.0 + TOL_WARN): - warnings.warn('mr[0] < m0[0]') - assert(mr[0] < m0[0] * (1.0 + TOL_FAIL)) - - # make sure the sum of moments equals the original - diff = numpy.abs(m0 - (ml + mr)) - if not numpy.all(diff < TOL_FAIL): - logger.error(f'diff failed: {diff} \n original {m0} \n left {ml} \n right {mr}') - assert(False) - if not numpy.all(diff < TOL_WARN): - warnings.warn('Moments outside tolerance') - - return m0, ml, mr - - -def plane_centroid(poly): - # make a randomly-oriented plane passing through the centroid - centroid = get_centroid(poly) - n = rand_unit_vector() - d = -n @ centroid - return n, d - - -def plane_face(poly): - # make a plane coplanar with a face of the poly - v0 = numpy.random.randint(poly['vertices'].shape[0]) - v1, v2 = random.sample(list(poly['neighbors'][v0]), 2) - points = (poly['vertices'][vi] for vi in (v0, v1, v2)) - return plane_points(*points) - - -def plane_centroid_edge(poly): - # make a plane coplanar with an edge and the centroid of the poly - v0 = numpy.random.randint(poly['vertices'].shape[0]) - v1 = random.choice(poly['neighbors'][v0]) - p0 = poly['vertices'][v0] - p1 = poly['vertices'][v1] - centroid = get_centroid(poly) - return plane_points(p0, p1, centroid) - - -def plane_edge(poly): - # make a plane coplanar with an edge, but otherwise randomly oriented - v0 = numpy.random.randint(poly['vertices'].shape[0]) - v1 = random.choice(poly['neighbors'][v0]) - p0 = poly['vertices'][v0] - p1 = poly['vertices'][v1] - return plane_points(p0, p1, rand_unit_vector()) - - -def plane_centroid_vertex(poly): - # make a plane coplanar with a vertex and the centroid, but otherwise randomly oriented - p0 = random.choice(poly['vertices']) - centroid = get_centroid(poly) - return plane_points(p0, centroid, rand_unit_vector()) - - -def plane_vertex(poly): - # make a plane coplanar with a vertex, but otherwise randomly oriented - p0 = random.choice(poly['vertices']) - n = rand_unit_vector() - d = -n @ p0 - return n, d - - -def plane_points(p0, p1, p2): - # generate a plane passing through the three points given - n = numpy.cross(p1 - p0, p2 - p0) - n /= norm(n) + 1e-40 - d = -n @ p0 - return n, d - - -def rand_unit_vector(): - # generates a random, isotropically distributed unit vector - s = 0 - while s == 0: - v = numpy.random.randn(3) - s = norm(v) - return v / s - - -def rand_tetrahedron_vertices(min_volume: float = MIN_VOL): - # generates a random tetrahedron with vertices on the unit sphere, - # guaranteeing a volume of at least min_volume - volume = 0 - while volume < min_volume: - verts = [rand_unit_vector() for _ in range(4)] - volume = tetrahedron_volume(verts) - if volume < 0: - verts[2], verts[3] = verts[3], verts[2] - volume = -volume - return verts - - -def build_rand_tetrahedron(min_volume: float = MIN_VOL): - return build_tetrahedron(rand_tetrahedron_vertices()) - - -def get_centroid(poly): - # get the centroid by averaging vertices - centroid = numpy.sum(poly['vertices'], axis=0) / poly['vertices'].shape[0] - return centroid - - -plane_gen = [plane_centroid, plane_face, - plane_centroid_edge, plane_edge, - plane_centroid_vertex, plane_vertex] - - -if __name__ == '__main__': - logging.basicConfig(level=logging.INFO) - - logger.info('poly_pyramid') - test_poly_pyramid() - - logger.info('load_chop_torus') - test_torus_load_and_chop() - - logger.info('test_split_tet_manual') - test_split_tet_manual() - - logger.info('test_split_tets_thru_centroid') - test_split_tets_thru_centroid() - - logger.info('test_split_nonconvex') - test_split_nonconvex() - - logger.info('split_recursive') - test_recursive_split() - - logger.info('voxelization') -# test_voxelization() - - logger.info('test_tet_tet_timing') - test_tet_tet_timing() - - logger.info('time_split') - time_split() - - logger.info('success')