diff --git a/README.md b/README.md index f131432..79bae52 100644 --- a/README.md +++ b/README.md @@ -6,33 +6,37 @@ **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.6 or newer +* python 3.11 or newer * numpy * pytest (optional, testing) * pytest-benchmark (optional, benchmarking) Install with pip from PyPi (preferred): ```bash -pip3 install adze +pip install adze ``` Install directly from git repository: ```bash -pip3 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 diff --git a/adze/__init__.py b/adze/__init__.py index 76b138e..c34be02 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -38,18 +38,28 @@ 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`. """ @@ -79,6 +89,22 @@ from .shapes import ( 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 150030b..214aff1 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -1,16 +1,22 @@ from typing import Any -from collections.abc import Iterable +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, AdzeError +from .util import _get_maps, find_components, find_faces, check_poly, AdzeError + + +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: list[ArrayLike] + faces: Sequence[ArrayLike] ) -> list[plane_t]: """ Generate a list of planes (normal, signed distance) from the faces of a boundary- @@ -24,15 +30,34 @@ def planes_from_boundary( Returns: List of planes, represented by (normal vector, signed distance to origin) tuples. """ - vertices = numpy.asarray(vertices) + 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: - face_verts = vertices[face] + 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') - n = numpy.cross(numpy.diff(face_verts, n=1, axis=0), - numpy.diff(face_verts, n=2, axis=0)) - n /= norm(n) + 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)) @@ -53,14 +78,33 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t: Schelgel-representation polyhedron """ vertices = numpy.array(vertices, dtype=float) - afaces = [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(afaces)) + 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 AdzeError(f'Vertex {edges_per_vertex.argmin()} has < 3 edges') - if edges_per_vertex.max() == 3: + 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 # @@ -70,8 +114,8 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t: 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 prev == next. @@ -89,7 +133,9 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> 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. @@ -159,7 +205,6 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t: 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) @@ -182,7 +227,7 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t: 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 @@ -216,7 +261,7 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t: 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] @@ -258,7 +303,9 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> 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 def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: @@ -276,9 +323,15 @@ def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: """ 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: list[list[NDArray[numpy.integer]]] = [[] for _ in range(num_components)] @@ -305,4 +358,3 @@ def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: boundaries.append(boundary) return boundaries - diff --git a/adze/moments.py b/adze/moments.py index 5ba50df..78822de 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -1,10 +1,24 @@ +from operator import index + import numpy from numpy.typing import NDArray from . import poly_t +from .util import AdzeError from .util import find_faces +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. @@ -15,6 +29,7 @@ def number_of_moments(order: int) -> int: Returns: Number of moments with that order or fewer. """ + order = _normalize_order(order) return ((order + 1) * (order + 2) * (order + 3)) // 6 @@ -42,12 +57,13 @@ def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]: 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 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 0f2ae68..2e81c49 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -3,6 +3,34 @@ from numpy.linalg import norm from numpy.typing import ArrayLike from . import poly_t, plane_t +from .util import AdzeError + + +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: @@ -10,13 +38,15 @@ def build_tetrahedron(vertices: ArrayLike) -> poly_t: Build a Schelegel-representation tetrahedron. Args: - vertices: 4x3 array, representing the vertex coordinates. + 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), @@ -32,11 +62,13 @@ def build_box(box_corners: ArrayLike) -> poly_t: Args: box_corners: 2x3 array, representing the vertex coordinates of - two diagonally-opposite corners of the box. + 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], @@ -48,7 +80,6 @@ def build_box(box_corners: ArrayLike) -> poly_t: [6, 3, 4], ] - box_corners = numpy.asarray(box_corners) vertices = [ [box_corners[0, 0], box_corners[0, 1], box_corners[0, 2]], [box_corners[1, 0], box_corners[0, 1], box_corners[0, 2]], @@ -72,12 +103,13 @@ def planes_from_box(box_corners: ArrayLike) -> list[plane_t]: Args: box_corners: 2x3 array, representing the vertex coordinates of - two diagonally-opposite corners of the box. + 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 = numpy.asarray(box_corners) + box_corners = _normalize_box_corners(box_corners) faces = [ (( 0, 0, 1), -box_corners[0, 2]), (( 0, 0, -1), box_corners[1, 2]), @@ -95,12 +127,13 @@ def planes_from_tetrahedron(vertices: ArrayLike) -> list[plane_t]: Construct a list of planes corresponding to the faces of a tetrahedron. Args: - vertices: 4x3 array, representing the vertex coordinates. + 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 = numpy.asarray(vertices, dtype=float) + verts = _normalize_tetrahedron_vertices(vertices) vset_inds = numpy.array(( [3, 1, 2, 1], [2, 0, 3, 2], diff --git a/adze/split.py b/adze/split.py index c0c2643..591eae1 100644 --- a/adze/split.py +++ b/adze/split.py @@ -1,11 +1,44 @@ from typing import overload, Literal +import math import numpy from . import poly_t, plane_t -from .util import build_empty, _get_map +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. @@ -15,15 +48,16 @@ def clip(poly: poly_t, plane: plane_t) -> poly_t: 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) + left_poly = _split(poly, plane, same_only=True, atol=atol) return left_poly -def split(poly: poly_t, plane: plane_t) -> tuple[poly_t, poly_t]: +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. @@ -32,29 +66,30 @@ def split(poly: poly_t, plane: plane_t) -> tuple[poly_t, poly_t]: 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) + return _split(poly, plane, same_only=False, atol=atol) @overload -def _split(poly: poly_t, plane: plane_t, same_only: Literal[True]) -> poly_t: +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]) -> tuple[poly_t, poly_t]: +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) -> tuple[poly_t, poly_t] | poly_t: +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) -> 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. @@ -67,34 +102,36 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False) -> tuple[poly_ 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 - if 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() @@ -105,8 +142,8 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False) -> tuple[poly_ # # 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) + 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 @@ -168,26 +205,22 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False) -> tuple[poly_ b1d = numpy.ravel_multi_index(tuple(edge_walk_results), dims) target_edge_inds = _get_map(a1d, b1d) - # # map from old vertex ind to new # ind_map_left = numpy.zeros(num_start, dtype=int) - # current side vertices get new (equal or lower) indices from delete operation, remain in same order ind_map_left[left] = numpy.arange(num_left) - # Hops across the boundary depend on (origin, destination) pair since that determines final vertex - # use argsort to generate link from target edge to current edge target_order = numpy.argsort(target_edge_inds) new_neighbors_left = numpy.column_stack(( - ind_map_left[lverts], # update left vertices based on new indexing - target_order + num_left, # new vertex indices are same as edge indices + offset + 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] @@ -203,8 +236,8 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False) -> tuple[poly_ 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] @@ -220,4 +253,3 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False) -> tuple[poly_ } return left_poly, right_poly - 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 index 5a0c64d..1253961 100644 --- a/adze/test/test_split.py +++ b/adze/test/test_split.py @@ -151,6 +151,33 @@ def test_manual_nonconvex(poly_order: int, n_zigs: int = 3, z_offset: float = 0. 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 @@ -255,8 +282,8 @@ def stack_split( plane[1] *= 1 + perturb * (PRNG.rand() - 0.5) # split the poly - poly_l = adze.clip(poly, plane) - poly_r = adze.clip(poly, flip_plane(plane)) + 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}, ' 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 index 51ac5d4..255d4b1 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -47,13 +47,26 @@ def test_voxelization(poly_order: int, grid_resolution: int | None = None) -> No 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', 'matplotlib.Axes']: + ) -> tuple['matplotlib.figure.Figure', 'matplotlib.axes.Axes']: """ Draw an isosurface plot of the device. diff --git a/adze/test/utils.py b/adze/test/utils.py index 2192325..97c4ef6 100644 --- a/adze/test/utils.py +++ b/adze/test/utils.py @@ -1,4 +1,5 @@ from typing import cast +from collections.abc import Sequence import random import numpy from numpy.typing import NDArray @@ -62,7 +63,7 @@ def gen_torus_brep( return vertices, faces -def tetrahedron_volume(vertices: NDArray[numpy.floating] | list[NDArray[numpy.floating]]) -> float: +def tetrahedron_volume(vertices: NDArray | Sequence[NDArray]) -> float: ad, bd, cd = vertices[0:3] - vertices[3] return -ad @ numpy.cross(bd, cd) / 6 @@ -113,7 +114,7 @@ def gen_plane_through_centroid( """ centroid = get_centroid(poly) n = rand_unit_vector() - d = cast(numpy.floating, -n @ centroid) + d = cast('numpy.floating', -n @ centroid) return n, d diff --git a/adze/transform.py b/adze/transform.py index 1c3dfdd..fd40d11 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -3,6 +3,52 @@ from numpy import sin, cos from numpy.typing import ArrayLike 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: @@ -18,11 +64,16 @@ def rotate(poly: poly_t, theta: float, axis: int) -> poly_t: 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 @@ -38,7 +89,8 @@ def translate(poly: poly_t, shift: ArrayLike) -> poly_t: 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 @@ -55,25 +107,36 @@ def scale(poly: poly_t, factor: ArrayLike | float) -> poly_t: 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: ArrayLike) -> poly_t: """ - Perform arbitrary affine trasnformation on the polyhedron. + Perform an arbitrary homogeneous 4x4 transformation on the polyhedron. Args: poly: Polyhedron to transform. Changed in-place. - xform: 4x4 affine transformation matrix. + 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 5df0ad5..ed4b3d7 100644 --- a/adze/util.py +++ b/adze/util.py @@ -29,6 +29,37 @@ def build_empty() -> poly_t: } +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. @@ -75,6 +106,8 @@ def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.intp]]: 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 @@ -230,6 +263,10 @@ def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: 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): @@ -241,7 +278,7 @@ def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: which_vertices = numpy.where(repeated_neighbors)[0] 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 AdzeError(f'Vertices {which_vertices} are referenced {vertex_uses[which_vertices]} times,' @@ -279,6 +316,79 @@ def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: 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 diff --git a/adze/voxel.py b/adze/voxel.py index a2e09cb..11d81ca 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -42,7 +42,15 @@ def voxelize( correspond to portions of the polyhedron that protruded outside the outermost planes. N is `number_of_moments(order)`. """ - aplanes = [numpy.asarray(p) for p in planes] + 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(): @@ -50,8 +58,10 @@ def voxelize( if include_outside: grid_shape = num_planes + 1 - if not include_outside: + grid_offset = 0 + else: grid_shape = num_planes - 1 + 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) @@ -75,7 +85,7 @@ def voxelize( # 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 @@ -95,4 +105,3 @@ def voxelize( stack.append((poly_left, slices_left)) stack.append((poly_right, slices_right)) return grid - diff --git a/pyproject.toml b/pyproject.toml index 5e5a093..6c95a0f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,6 +47,7 @@ path = "adze/__init__.py" [project.optional-dependencies] stl = ["stl"] +test = ["pytest", "pytest-benchmark"] [tool.ruff] exclude = [ @@ -68,7 +69,6 @@ lint.ignore = [ "ANN002", # *args "ANN003", # **kwargs "ANN401", # Any - "ANN101", # self: Self "SIM108", # single-line if / else assignment "RET504", # x=y+z; return x "PIE790", # unnecessary pass