From bf057e25052744b68201e9f26777b060790fb560 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 00:46:27 -0800 Subject: [PATCH 01/35] Documentation update --- README.md | 13 ++++++------- adze/__init__.py | 30 ++++++++++++++++++++---------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index f131432..5fb61dc 100644 --- a/README.md +++ b/README.md @@ -6,28 +6,27 @@ **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 diff --git a/adze/__init__.py b/adze/__init__.py index 76b138e..b3575bd 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`. """ From ad4c0bc15770cbb5c573e3cc33a6fed7aea72dbe Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 06:49:49 -0800 Subject: [PATCH 02/35] misc cleanup and testing deps --- adze/test/utils.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/adze/test/utils.py b/adze/test/utils.py index 2192325..ad8a6b7 100644 --- a/adze/test/utils.py +++ b/adze/test/utils.py @@ -113,7 +113,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/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 From d71cb6a53594e5d40ddec2a3d3672c67df5c0a9a Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 07:07:43 -0800 Subject: [PATCH 03/35] [split] add a tolerance for splitting to avoid making tiny slivers improve numerical stability --- adze/split.py | 54 +++++++++++++++++++++++++---------------- adze/test/test_split.py | 27 +++++++++++++++++++++ 2 files changed, 60 insertions(+), 21 deletions(-) diff --git a/adze/split.py b/adze/split.py index c0c2643..3557592 100644 --- a/adze/split.py +++ b/adze/split.py @@ -5,7 +5,7 @@ from . import poly_t, plane_t from .util import build_empty, _get_map -def clip(poly: poly_t, plane: plane_t) -> poly_t: +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 +15,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 +33,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,6 +69,7 @@ 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. @@ -75,25 +78,35 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False) -> tuple[poly_ 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]) + + # 1. First, check if the polyhedron is entirely on one side (within tolerance) + # If all distances are > -atol, the whole thing is effectively on the "left" + # If all distances are < atol, the whole thing is effectively on the "right" + if (dists >= -atol).all(): + # Entirely on "left" or touching plane within tolerance + ret = poly, build_empty() + return ret[0] if same_only else ret + + if (dists <= atol).all(): + # Entirely on "right" or touching plane within tolerance + ret = build_empty(), poly + return ret[0] if same_only else ret + + # 2. If it's truly crossing, perform a binary partition for the splitting algorithm. + # We use > 0 for binary robustness of the graph surgery logic. 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 + # Note: Because of the atol checks above, we know num_left and num_right are both > 0 + # and at least one point is > atol and at least one is < -atol. right_inds = numpy.where(right)[0] next_vertex = neighbors[right_inds, :].ravel() @@ -220,4 +233,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_split.py b/adze/test/test_split.py index 5a0c64d..d295e24 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 From 0bed641d08a09ba7935dbfbb6a138308c6430a54 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 07:08:21 -0800 Subject: [PATCH 04/35] [util] add merge_polyhedra --- adze/util.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/adze/util.py b/adze/util.py index 5df0ad5..d7af74f 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. From d9a9eebe8bb7c437ac7eca9b7b3ebdc6c365f421 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 07:08:36 -0800 Subject: [PATCH 05/35] [util] add get_aabb --- adze/util.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/adze/util.py b/adze/util.py index d7af74f..247840d 100644 --- a/adze/util.py +++ b/adze/util.py @@ -310,6 +310,14 @@ 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 plot_brep(brep: Sequence[dict[str, NDArray]]) -> None: """ Plot a boundary representation From 32b2f26ad888896ac426509722a9b6d055c4a183 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 07:09:19 -0800 Subject: [PATCH 06/35] [util] add is_inside --- adze/util.py | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/adze/util.py b/adze/util.py index 247840d..c33786f 100644 --- a/adze/util.py +++ b/adze/util.py @@ -318,6 +318,71 @@ def get_aabb(poly: poly_t) -> tuple[NDArray, NDArray]: 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 4b85c059fb35fa5752d62cb97115995500d1e489 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 07:30:08 -0800 Subject: [PATCH 07/35] [planes_from_boundary] Use Newell's to improve handling of colinear vertices --- adze/boundary.py | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index 150030b..e7fbe81 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -24,16 +24,35 @@ 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) afaces = [numpy.asarray(ff) for ff in faces] planes = [] for face in afaces: face_verts = vertices[face] - n = numpy.cross(numpy.diff(face_verts, n=1, axis=0), - numpy.diff(face_verts, n=2, axis=0)) - n /= norm(n) - centroid = numpy.sum(face_verts, axis=0) / len(face) + # Newell's method for robust normal calculation + # n_x = sum (y_i - y_{i+1}) * (z_i + z_{i+1}) + # n_y = sum (z_i - z_{i+1}) * (x_i + x_{i+1}) + # n_z = sum (x_i - x_{i+1}) * (y_i + y_{i+1}) + + # Shift vertices to wrap around + v_curr = face_verts + v_next = numpy.roll(face_verts, -1, axis=0) + + # Ensure n is float64 to avoid casting issues with integer inputs + n = numpy.array([ + numpy.sum((v_curr[:, 1] - v_next[:, 1]) * (v_curr[:, 2] + v_next[:, 2])), + numpy.sum((v_curr[:, 2] - v_next[:, 2]) * (v_curr[:, 0] + v_next[:, 0])), + numpy.sum((v_curr[:, 0] - v_next[:, 0]) * (v_curr[:, 1] + v_next[:, 1])) + ], dtype=float) + + n_norm = norm(n) + if n_norm < 1e-15: + # Face is degenerate (zero area) + continue + + n /= n_norm + centroid = numpy.mean(face_verts, axis=0) d = -n @ centroid planes.append((n, d)) return planes @@ -305,4 +324,3 @@ def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: boundaries.append(boundary) return boundaries - From 981e0e5b811d55f7f1e17e66afb36848d9f94149 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 07:30:43 -0800 Subject: [PATCH 08/35] [boolean] Add boolean operations --- adze/__init__.py | 8 ++ adze/boolean.py | 166 ++++++++++++++++++++++++++++++++++++++ adze/test/test_boolean.py | 140 ++++++++++++++++++++++++++++++++ 3 files changed, 314 insertions(+) create mode 100644 adze/boolean.py create mode 100644 adze/test/test_boolean.py diff --git a/adze/__init__.py b/adze/__init__.py index b3575bd..adf6eb4 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -89,6 +89,14 @@ 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, + ) __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/test/test_boolean.py b/adze/test/test_boolean.py new file mode 100644 index 0000000..1858249 --- /dev/null +++ b/adze/test/test_boolean.py @@ -0,0 +1,140 @@ +import numpy +import adze +from adze.boolean import intersect, difference, union +from adze.shapes import build_box + +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) + + 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) + 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) + 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) + 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) + 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) + 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) + vol1 = adze.get_volume(res1) + assert numpy.isclose(vol1, 0.75) + + # Test L-shape as poly_b + res2 = intersect(b3, l_shape) + 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) + 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) + assert numpy.isclose(adze.get_volume(res2), 2.25) + +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) From 38dda21e9a8f254c94f3e01d1fa9ff028a53099a Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 07:30:58 -0800 Subject: [PATCH 09/35] [util] export is_inside --- adze/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/adze/__init__.py b/adze/__init__.py index adf6eb4..fe8a1f3 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -97,6 +97,7 @@ from .boolean import ( difference_convex as difference_convex, union_convex as union_convex, ) +from .util import is_inside as is_inside __author__ = 'Jan Petykiewicz' __version__ = '0.2' From 359ebc325ec243eb24807cc73ad638ed38088a89 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 07:52:38 -0800 Subject: [PATCH 10/35] [offset] add offsetting --- adze/__init__.py | 1 + adze/offset.py | 91 ++++++++++++++++++++++++++++++++++++++++ adze/test/test_offset.py | 46 ++++++++++++++++++++ 3 files changed, 138 insertions(+) create mode 100644 adze/offset.py create mode 100644 adze/test/test_offset.py diff --git a/adze/__init__.py b/adze/__init__.py index fe8a1f3..070145e 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -97,6 +97,7 @@ from .boolean import ( difference_convex as difference_convex, union_convex as union_convex, ) +from .offset import offset as offset from .util import is_inside as is_inside __author__ = 'Jan Petykiewicz' diff --git a/adze/offset.py b/adze/offset.py new file mode 100644 index 0000000..b7c4de2 --- /dev/null +++ b/adze/offset.py @@ -0,0 +1,91 @@ +import numpy +from . import poly_t +from .util import find_faces +from .boundary import planes_from_boundary + +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. + + Args: + poly: Input polyhedron in Schlegel representation. + delta: Offset distance. + miter_limit: Maximum allowed multiplier for displacement at sharp corners. + + Returns: + Offsetted polyhedron. + """ + 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 = [] + + 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] + face_normals.append(plane[0]) # plane[0] is unit 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]) + + # If n is INWARD normal, then to EXPAND (positive delta) we want to move + # AGAINST the normal. + # n . (V' - V) = -delta + # Let d = V' - V + # A d = -delta * [1, 1, 1]^T + + try: + # solve A d = -delta + rhs = numpy.full(3, -delta) + d = numpy.linalg.solve(A, rhs) + + # Check miter limit + d_norm = numpy.linalg.norm(d) + if abs(delta) > 1e-15 and d_norm > miter_limit * abs(delta): + # Clamp displacement + avg_n = numpy.mean(A, axis=0) + avg_n_norm = numpy.linalg.norm(avg_n) + if avg_n_norm > 1e-12: + # Move along average inward normal (negative for expansion) + new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * delta + else: + new_vertices[i] = vertices[i] + d * (miter_limit * abs(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) + if avg_n_norm > 1e-12: + new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * delta + else: + new_vertices[i] = vertices[i] + + return { + 'vertices': new_vertices, + 'neighbors': neighbors.copy() + } diff --git a/adze/test/test_offset.py b/adze/test/test_offset.py new file mode 100644 index 0000000..8a59e0a --- /dev/null +++ b/adze/test/test_offset.py @@ -0,0 +1,46 @@ +import numpy +import adze +from adze.shapes import build_box +from adze.offset import offset + +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]]) + + # Expand by 0.1 on all sides + # New cube: [-0.1, 1.1] on all axes + # New side length = 1.2 + # Expected volume = 1.2^3 = 1.728 + expanded = offset(cube, 0.1) + + vol = adze.get_volume(expanded) + assert numpy.isclose(vol, 1.728) + + # Check bounds + 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]]) + + # Shrink by 0.1 on all sides + # New cube: [0.1, 0.9] on all axes + # New side length = 0.8 + # Expected volume = 0.8^3 = 0.512 + shrunk = offset(cube, -0.1) + + vol = adze.get_volume(shrunk) + assert numpy.isclose(vol, 0.512) + + # Check bounds + 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']) From 06ab0af763c78dde3af90f7b2fbc2041bf39df00 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 07:53:02 -0800 Subject: [PATCH 11/35] Improve type hints --- adze/boundary.py | 4 ++-- adze/test/test_split.py | 4 ++-- adze/test/test_voxel.py | 2 +- adze/test/utils.py | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index e7fbe81..af46c7d 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -1,5 +1,5 @@ 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 @@ -10,7 +10,7 @@ from .util import _get_maps, find_components, find_faces, AdzeError 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- diff --git a/adze/test/test_split.py b/adze/test/test_split.py index d295e24..1253961 100644 --- a/adze/test/test_split.py +++ b/adze/test/test_split.py @@ -282,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_voxel.py b/adze/test/test_voxel.py index 51ac5d4..fa0df4d 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -53,7 +53,7 @@ def visualize_isosurface( 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 ad8a6b7..6379e09 100644 --- a/adze/test/utils.py +++ b/adze/test/utils.py @@ -1,4 +1,4 @@ -from typing import cast +from typing import cast, Sequence import random import numpy from numpy.typing import NDArray @@ -62,7 +62,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 From b755cfb2db7e787c39788a4c7d56ab01db7d820e Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 08:23:48 -0800 Subject: [PATCH 12/35] [offset] add smooth, open, close --- adze/__init__.py | 7 ++- adze/offset.py | 108 +++++++++++++++++++++++++++++++++++++++ adze/test/test_offset.py | 36 +++++++++---- adze/test/utils.py | 3 +- 4 files changed, 141 insertions(+), 13 deletions(-) diff --git a/adze/__init__.py b/adze/__init__.py index 070145e..5e4ea42 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -97,7 +97,12 @@ from .boolean import ( difference_convex as difference_convex, union_convex as union_convex, ) -from .offset import offset as offset +from .offset import ( + offset as offset, + smooth as smooth, + opening as opening, + closing as closing, + ) from .util import is_inside as is_inside __author__ = 'Jan Petykiewicz' diff --git a/adze/offset.py b/adze/offset.py index b7c4de2..aaa543b 100644 --- a/adze/offset.py +++ b/adze/offset.py @@ -8,6 +8,9 @@ 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. @@ -15,7 +18,29 @@ def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t: 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). """ + if poly['vertices'].shape[0] == 0: return poly @@ -89,3 +114,86 @@ def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t: '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/test/test_offset.py b/adze/test/test_offset.py index 8a59e0a..51618be 100644 --- a/adze/test/test_offset.py +++ b/adze/test/test_offset.py @@ -1,22 +1,17 @@ import numpy import adze from adze.shapes import build_box -from adze.offset import offset +from adze.offset import offset, smooth, closing 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]]) - # Expand by 0.1 on all sides - # New cube: [-0.1, 1.1] on all axes - # New side length = 1.2 - # Expected volume = 1.2^3 = 1.728 expanded = offset(cube, 0.1) vol = adze.get_volume(expanded) assert numpy.isclose(vol, 1.728) - # Check bounds 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]) @@ -25,16 +20,11 @@ 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]]) - # Shrink by 0.1 on all sides - # New cube: [0.1, 0.9] on all axes - # New side length = 0.8 - # Expected volume = 0.8^3 = 0.512 shrunk = offset(cube, -0.1) vol = adze.get_volume(shrunk) assert numpy.isclose(vol, 0.512) - # Check bounds 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]) @@ -44,3 +34,27 @@ def test_offset_zero() -> None: 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) diff --git a/adze/test/utils.py b/adze/test/utils.py index 6379e09..97c4ef6 100644 --- a/adze/test/utils.py +++ b/adze/test/utils.py @@ -1,4 +1,5 @@ -from typing import cast, Sequence +from typing import cast +from collections.abc import Sequence import random import numpy from numpy.typing import NDArray From f0e30f1f6c1ff3f26b41efc976fac9af9e8acfdc Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 23:53:59 -0800 Subject: [PATCH 13/35] [offset] add offset_anisotropic --- adze/__init__.py | 1 + adze/offset.py | 50 ++++++++++++++++++++++++++++++++-------- adze/test/test_offset.py | 33 +++++++++++++++++++++++++- 3 files changed, 74 insertions(+), 10 deletions(-) diff --git a/adze/__init__.py b/adze/__init__.py index 5e4ea42..c34be02 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -99,6 +99,7 @@ from .boolean import ( ) from .offset import ( offset as offset, + offset_anisotropic as offset_anisotropic, smooth as smooth, opening as opening, closing as closing, diff --git a/adze/offset.py b/adze/offset.py index aaa543b..9eed58a 100644 --- a/adze/offset.py +++ b/adze/offset.py @@ -1,8 +1,12 @@ 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. @@ -40,7 +44,21 @@ def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t: "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 @@ -54,13 +72,17 @@ def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t: # 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] - face_normals.append(plane[0]) # plane[0] is unit normal + 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) @@ -77,36 +99,46 @@ def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t: # 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 - # Let d = V' - V - # A d = -delta * [1, 1, 1]^T + # A d = -deltas + + # Max delta magnitude for miter limit check + max_delta = numpy.max(numpy.abs(deltas)) try: - # solve A d = -delta - rhs = numpy.full(3, -delta) + # solve A d = -deltas + rhs = -deltas d = numpy.linalg.solve(A, rhs) # Check miter limit d_norm = numpy.linalg.norm(d) - if abs(delta) > 1e-15 and d_norm > miter_limit * abs(delta): + 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) - new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * delta + # 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 * abs(delta) / d_norm) + 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) * delta + new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * avg_delta else: new_vertices[i] = vertices[i] diff --git a/adze/test/test_offset.py b/adze/test/test_offset.py index 51618be..1e8eed2 100644 --- a/adze/test/test_offset.py +++ b/adze/test/test_offset.py @@ -1,7 +1,7 @@ import numpy import adze from adze.shapes import build_box -from adze.offset import offset, smooth, closing +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 @@ -58,3 +58,34 @@ def test_closing_cube() -> None: # 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) From 1999b24b0cb7996132c7c22942ab55e2d79d3292 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 23:59:32 -0800 Subject: [PATCH 14/35] [tests] Check data validity and add test_difference_hole() --- adze/test/test_boolean.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/adze/test/test_boolean.py b/adze/test/test_boolean.py index 1858249..4ef625c 100644 --- a/adze/test/test_boolean.py +++ b/adze/test/test_boolean.py @@ -2,6 +2,7 @@ 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 @@ -11,6 +12,7 @@ def test_intersect_cubes() -> None: # 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) @@ -20,6 +22,7 @@ def test_intersect_no_overlap() -> None: 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 @@ -31,6 +34,7 @@ def test_difference_cubes() -> None: # 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) @@ -42,6 +46,7 @@ def test_union_cubes() -> None: # 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) @@ -51,6 +56,7 @@ def test_union_no_overlap() -> None: # 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) @@ -67,17 +73,20 @@ def test_intersect_nonconvex_lshape() -> None: # 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) @@ -89,6 +98,7 @@ def test_difference_nonconvex() -> None: # 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 @@ -99,8 +109,21 @@ def test_difference_nonconvex() -> None: 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. From 4ec8f5d41430ca01f780db030264509e1d08a0e2 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 31 Mar 2026 23:20:35 -0700 Subject: [PATCH 15/35] [voxelize] correct include_outside=True indexing --- adze/test/test_voxel.py | 13 +++++++++++++ adze/voxel.py | 7 ++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py index fa0df4d..255d4b1 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -47,6 +47,19 @@ 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], diff --git a/adze/voxel.py b/adze/voxel.py index a2e09cb..ac84d76 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -50,8 +50,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 +77,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 +97,3 @@ def voxelize( stack.append((poly_left, slices_left)) stack.append((poly_right, slices_right)) return grid - From 0dd2c459084de8b87847a1700892c5a831b444a7 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 31 Mar 2026 23:22:47 -0700 Subject: [PATCH 16/35] [rotate] fix rotation around second axis --- adze/test/test_transform.py | 31 +++++++++++++++++++++++++++++++ adze/transform.py | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 adze/test/test_transform.py diff --git a/adze/test/test_transform.py b/adze/test/test_transform.py new file mode 100644 index 0000000..834df02 --- /dev/null +++ b/adze/test/test_transform.py @@ -0,0 +1,31 @@ +import numpy +from numpy.testing import assert_allclose + +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) diff --git a/adze/transform.py b/adze/transform.py index 1c3dfdd..a8aa141 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -22,7 +22,7 @@ def rotate(poly: poly_t, theta: float, axis: int) -> poly_t: 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 + poly['vertices'][:, axis - 1] = s * v0 + c * v1 return poly From 1ff8ab1014037b7cfae4747d139455ade2349824 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 31 Mar 2026 23:23:59 -0700 Subject: [PATCH 17/35] [get_moments] fix dimension of moments of empty poly --- adze/moments.py | 2 +- adze/test/test_edge_cases.py | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 adze/test/test_edge_cases.py diff --git a/adze/moments.py b/adze/moments.py index 5ba50df..db9d6e4 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -47,7 +47,7 @@ def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]: 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/test/test_edge_cases.py b/adze/test/test_edge_cases.py new file mode 100644 index 0000000..e7654f4 --- /dev/null +++ b/adze/test/test_edge_cases.py @@ -0,0 +1,13 @@ +import numpy +import pytest +from numpy.testing import assert_allclose + +import adze + + +@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)) + From e2f6aea0a00db986dfc12c2cf18842c3355427a5 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 31 Mar 2026 23:25:53 -0700 Subject: [PATCH 18/35] [boundary_from_poly] handle empty poly correctly --- adze/boundary.py | 2 ++ adze/test/test_edge_cases.py | 3 +++ 2 files changed, 5 insertions(+) diff --git a/adze/boundary.py b/adze/boundary.py index af46c7d..a2edb7b 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -295,6 +295,8 @@ def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: """ neighbors = poly['neighbors'] vertices = poly['vertices'] + if vertices.shape[0] == 0: + return [] owning_component = find_components(neighbors) faces = find_faces(neighbors) diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py index e7654f4..619f130 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -4,6 +4,9 @@ from numpy.testing import assert_allclose import adze +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: From f4762733a6294bed79df9841c2daaa98822a8bb0 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 31 Mar 2026 23:27:17 -0700 Subject: [PATCH 19/35] [check_poly] reject malformed neighbor arrays --- adze/test/test_edge_cases.py | 20 ++++++++++++++++++++ adze/util.py | 6 +++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py index 619f130..5028036 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -3,6 +3,7 @@ import pytest from numpy.testing import assert_allclose import adze +import adze.util def test_boundary_from_empty_poly() -> None: assert adze.boundary_from_poly(adze.util.build_empty()) == [] @@ -14,3 +15,22 @@ def test_empty_poly_moments_shape(order: int) -> None: assert moments.shape == (adze.number_of_moments(order),) assert_allclose(moments, numpy.zeros_like(moments)) + + +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) diff --git a/adze/util.py b/adze/util.py index c33786f..def8541 100644 --- a/adze/util.py +++ b/adze/util.py @@ -261,6 +261,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): @@ -272,7 +276,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,' From 35bced6e553d24977a397cb9ae8f65440b9ab47f Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 31 Mar 2026 23:29:18 -0700 Subject: [PATCH 20/35] [find_faces] handle empty poly --- adze/util.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/adze/util.py b/adze/util.py index def8541..ed4b3d7 100644 --- a/adze/util.py +++ b/adze/util.py @@ -106,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 From 665e1e4161fa13bd7b03ffa74f849280dee06c8a Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 19:16:46 -0700 Subject: [PATCH 21/35] [planes_from_boundary] reject zero-area faces and incorrect dims --- adze/boundary.py | 38 +++++++++++++++--------------------- adze/test/test_edge_cases.py | 13 ++++++++++++ 2 files changed, 29 insertions(+), 22 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index a2edb7b..d4f3736 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -25,34 +25,28 @@ def planes_from_boundary( 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}') 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}') face_verts = vertices[face] - - # Newell's method for robust normal calculation - # n_x = sum (y_i - y_{i+1}) * (z_i + z_{i+1}) - # n_y = sum (z_i - z_{i+1}) * (x_i + x_{i+1}) - # n_z = sum (x_i - x_{i+1}) * (y_i + y_{i+1}) - - # Shift vertices to wrap around - v_curr = face_verts - v_next = numpy.roll(face_verts, -1, axis=0) - - # Ensure n is float64 to avoid casting issues with integer inputs - n = numpy.array([ - numpy.sum((v_curr[:, 1] - v_next[:, 1]) * (v_curr[:, 2] + v_next[:, 2])), - numpy.sum((v_curr[:, 2] - v_next[:, 2]) * (v_curr[:, 0] + v_next[:, 0])), - numpy.sum((v_curr[:, 0] - v_next[:, 0]) * (v_curr[:, 1] + v_next[:, 1])) - ], dtype=float) - + if face_verts.shape[0] < 3: + raise AdzeError('Faces must have at least three vertices') + 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 < 1e-15: - # Face is degenerate (zero area) - continue - + if n_norm <= tolerance: + raise AdzeError('Faces must have non-zero area') n /= n_norm - centroid = numpy.mean(face_verts, axis=0) + centroid = numpy.sum(face_verts, axis=0) / len(face) d = -n @ centroid planes.append((n, d)) return planes diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py index 5028036..dfc6401 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -4,6 +4,8 @@ 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()) == [] @@ -17,6 +19,17 @@ def test_empty_poly_moments_shape(order: int) -> None: +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]]) + + def test_check_poly_rejects_row_count_mismatch() -> None: poly = { 'vertices': numpy.array([ From f17667c93c976f63d3dc214d30db15e06ab31645 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 19:19:16 -0700 Subject: [PATCH 22/35] [build_polyhedron] perform more checks for polyhedron validity --- adze/boundary.py | 34 ++++++++++++++++++---- adze/test/test_edge_cases.py | 55 ++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 6 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index d4f3736..afab4b5 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -5,7 +5,7 @@ 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 planes_from_boundary( @@ -66,9 +66,28 @@ 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') @@ -102,7 +121,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. @@ -172,7 +193,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) @@ -271,7 +291,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]]: diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py index dfc6401..156d1d7 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -30,6 +30,61 @@ def test_planes_from_boundary_rejects_zero_area_face() -> None: planes_from_boundary(vertices, [[0, 1, 2]]) +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_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_check_poly_rejects_row_count_mismatch() -> None: poly = { 'vertices': numpy.array([ From 8ccdcfffd796a73d3f52dd1abcb53ab81753bc15 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 19:20:00 -0700 Subject: [PATCH 23/35] Document vertex ordering and box_corners format --- README.md | 4 ++++ adze/shapes.py | 16 ++++++++++------ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 5fb61dc..f259368 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,10 @@ 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. + To read the inline help, ```python3 import adze diff --git a/adze/shapes.py b/adze/shapes.py index 0f2ae68..387152e 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -10,7 +10,8 @@ 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. @@ -32,7 +33,8 @@ 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. @@ -48,7 +50,7 @@ def build_box(box_corners: ArrayLike) -> poly_t: [6, 3, 4], ] - box_corners = numpy.asarray(box_corners) + box_corners = numpy.asarray(box_corners, dtype=float) 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 +74,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 = numpy.asarray(box_corners, dtype=float) faces = [ (( 0, 0, 1), -box_corners[0, 2]), (( 0, 0, -1), box_corners[1, 2]), @@ -95,7 +98,8 @@ 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. From 9ef471dadc719c5c98c9957f0c851bb2aed9e0d8 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 19:20:46 -0700 Subject: [PATCH 24/35] [voxelize] Enforce 3 planes --- adze/test/test_edge_cases.py | 18 ++++++++++++++++++ adze/voxel.py | 10 +++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py index 156d1d7..5c8e0f3 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -102,3 +102,21 @@ def test_check_poly_rejects_row_count_mismatch() -> None: 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, + ) diff --git a/adze/voxel.py b/adze/voxel.py index ac84d76..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(): From f834598e0f151d3beb6325b67e33e66433b3c2f8 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 19:49:56 -0700 Subject: [PATCH 25/35] [moments] Error if order is negative or non-integer --- adze/moments.py | 16 +++ adze/test/test_edge_cases.py | 219 +++++++++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+) diff --git a/adze/moments.py b/adze/moments.py index db9d6e4..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,6 +57,7 @@ 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] diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py index 5c8e0f3..f611f65 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -18,6 +18,61 @@ def test_empty_poly_moments_shape(order: int) -> None: 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([ @@ -30,6 +85,19 @@ def test_planes_from_boundary_rejects_zero_area_face() -> None: 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], @@ -49,6 +117,33 @@ def test_build_polyhedron_rejects_unused_vertices() -> None: 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], @@ -85,6 +180,26 @@ def test_build_polyhedron_rejects_inconsistent_face_winding() -> None: 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([ @@ -120,3 +235,107 @@ def test_voxelize_requires_strictly_increasing_axes() -> None: [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], + ]) From 05f91862683ac14857ad0acd4eca2f0141be3f0a Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 19:50:56 -0700 Subject: [PATCH 26/35] [clip / _split] always return a new poly --- adze/split.py | 68 +++++++++++++++++++++++------------- adze/test/test_edge_cases.py | 6 ++++ 2 files changed, 50 insertions(+), 24 deletions(-) diff --git a/adze/split.py b/adze/split.py index 3557592..57d9ae6 100644 --- a/adze/split.py +++ b/adze/split.py @@ -1,8 +1,41 @@ 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 _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, distance def clip(poly: poly_t, plane: plane_t, atol: float = 1e-12) -> poly_t: @@ -74,6 +107,7 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float = (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] @@ -84,30 +118,20 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float = dists = plane[1] + (vertices @ plane[0]) - # 1. First, check if the polyhedron is entirely on one side (within tolerance) - # If all distances are > -atol, the whole thing is effectively on the "left" - # If all distances are < atol, the whole thing is effectively on the "right" if (dists >= -atol).all(): - # Entirely on "left" or touching plane within tolerance - ret = poly, build_empty() + ret = _copy_poly(poly), build_empty() return ret[0] if same_only else ret if (dists <= atol).all(): - # Entirely on "right" or touching plane within tolerance - ret = build_empty(), poly + ret = build_empty(), _copy_poly(poly) return ret[0] if same_only else ret - # 2. If it's truly crossing, perform a binary partition for the splitting algorithm. - # We use > 0 for binary robustness of the graph surgery logic. left = dists > 0 right = numpy.logical_not(left) num_left = numpy.count_nonzero(left) num_right = num_start - num_left - # Note: Because of the atol checks above, we know num_left and num_right are both > 0 - # and at least one point is > atol and at least one is < -atol. - right_inds = numpy.where(right)[0] next_vertex = neighbors[right_inds, :].ravel() @@ -118,8 +142,8 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float = # # 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 @@ -181,26 +205,22 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float = 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] @@ -216,8 +236,8 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float = 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] diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py index f611f65..91f6141 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -237,6 +237,7 @@ def test_voxelize_requires_strictly_increasing_axes() -> None: ) +<<<<<<< HEAD def test_clip_rejects_zero_normal_plane() -> None: poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) @@ -279,6 +280,8 @@ def test_boundary_from_poly_rejects_invalid_graph() -> None: adze.boundary_from_poly(poly) +======= +>>>>>>> 34c60fa ([clip / _split] always return a new 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]]) @@ -300,6 +303,7 @@ def test_split_noop_returns_independent_poly() -> None: assert kept_poly['vertices'] is not poly['vertices'] kept_poly['vertices'][0, 0] = 999.0 assert poly['vertices'][0, 0] == 0.0 +<<<<<<< HEAD def test_split_handles_disconnected_components_without_cut_edges() -> None: @@ -339,3 +343,5 @@ def test_tetrahedron_helpers_reject_negative_winding(tetra_fun) -> None: [1.0, 0.0, 0.0], [0.0, 0.0, 1.0], ]) +======= +>>>>>>> 34c60fa ([clip / _split] always return a new poly) From 1d2b1ca8d31424321a24a8ad4d4ca73883207522 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 19:51:34 -0700 Subject: [PATCH 27/35] [rotate / affine] check args for validity --- adze/test/test_transform.py | 39 +++++++++++++++++++++++++++++++++++++ adze/transform.py | 9 +++++++++ 2 files changed, 48 insertions(+) diff --git a/adze/test/test_transform.py b/adze/test/test_transform.py index 834df02..2b1d47a 100644 --- a/adze/test/test_transform.py +++ b/adze/test/test_transform.py @@ -1,6 +1,8 @@ import numpy +import pytest from numpy.testing import assert_allclose +import adze import adze.transform @@ -29,3 +31,40 @@ def test_rotate_z_quarter_turn() -> None: } rotated = adze.transform.rotate(poly, numpy.pi / 2, axis=2) assert_allclose(rotated['vertices'], [[0.0, 1.0, 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) diff --git a/adze/transform.py b/adze/transform.py index a8aa141..f833d9c 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -3,6 +3,7 @@ from numpy import sin, cos from numpy.typing import ArrayLike from . import poly_t +from .util import AdzeError def rotate(poly: poly_t, theta: float, axis: int) -> poly_t: @@ -18,6 +19,9 @@ 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}') + s, c = sin(theta), cos(theta) v0 = poly['vertices'][:, axis - 2].copy() v1 = poly['vertices'][:, axis - 1] @@ -72,8 +76,13 @@ def affine(poly: poly_t, xform: ArrayLike) -> poly_t: Data is altered in-place but also returned for convenience. """ 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}') + mat4x3 = xform[:, :3] mat4x1 = xform[:, 3] vh = mat4x3 @ poly['vertices'].T + mat4x1 + if numpy.any(vh[3, :] == 0): + raise AdzeError('Affine transform produced points with zero homogeneous coordinate') poly['vertices'][:] = (vh[:3, :] / vh[3, :]).T return poly From 031d93598d5c36d181a9e99bddf9ed303843a39e Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 20:53:38 -0700 Subject: [PATCH 28/35] more input validation --- adze/boundary.py | 6 +++++- adze/split.py | 2 +- adze/test/test_edge_cases.py | 6 ------ adze/transform.py | 2 ++ 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index afab4b5..7369c73 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -313,9 +313,13 @@ def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: 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)] diff --git a/adze/split.py b/adze/split.py index 57d9ae6..591eae1 100644 --- a/adze/split.py +++ b/adze/split.py @@ -35,7 +35,7 @@ def _normalize_plane(plane: plane_t) -> plane_t: 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, distance + return normal, float(distance) def clip(poly: poly_t, plane: plane_t, atol: float = 1e-12) -> poly_t: diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py index 91f6141..f611f65 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -237,7 +237,6 @@ def test_voxelize_requires_strictly_increasing_axes() -> None: ) -<<<<<<< HEAD def test_clip_rejects_zero_normal_plane() -> None: poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) @@ -280,8 +279,6 @@ def test_boundary_from_poly_rejects_invalid_graph() -> None: adze.boundary_from_poly(poly) -======= ->>>>>>> 34c60fa ([clip / _split] always return a new 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]]) @@ -303,7 +300,6 @@ def test_split_noop_returns_independent_poly() -> None: assert kept_poly['vertices'] is not poly['vertices'] kept_poly['vertices'][0, 0] = 999.0 assert poly['vertices'][0, 0] == 0.0 -<<<<<<< HEAD def test_split_handles_disconnected_components_without_cut_edges() -> None: @@ -343,5 +339,3 @@ def test_tetrahedron_helpers_reject_negative_winding(tetra_fun) -> None: [1.0, 0.0, 0.0], [0.0, 0.0, 1.0], ]) -======= ->>>>>>> 34c60fa ([clip / _split] always return a new poly) diff --git a/adze/transform.py b/adze/transform.py index f833d9c..0f72f08 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -78,6 +78,8 @@ def affine(poly: poly_t, xform: ArrayLike) -> poly_t: 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] From dd16f190048a9b509fe633d5b23f2a1c8afa857c Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 20:54:00 -0700 Subject: [PATCH 29/35] [affine] fix for >1 vertex --- adze/test/test_transform.py | 32 ++++++++++++++++++++++++++++++++ adze/transform.py | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/adze/test/test_transform.py b/adze/test/test_transform.py index 2b1d47a..633b635 100644 --- a/adze/test/test_transform.py +++ b/adze/test/test_transform.py @@ -68,3 +68,35 @@ def test_affine_rejects_zero_homogeneous_coordinate() -> None: 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]]) diff --git a/adze/transform.py b/adze/transform.py index 0f72f08..730d452 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -82,7 +82,7 @@ def affine(poly: poly_t, xform: ArrayLike) -> poly_t: raise AdzeError('Affine transform matrix must contain only finite values') mat4x3 = xform[:, :3] - mat4x1 = xform[:, 3] + mat4x1 = xform[:, 3:4] vh = mat4x3 @ poly['vertices'].T + mat4x1 if numpy.any(vh[3, :] == 0): raise AdzeError('Affine transform produced points with zero homogeneous coordinate') From 4da3376e631f3bc104fb605d19ff6a2d7f8b58d8 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 21:02:51 -0700 Subject: [PATCH 30/35] [affine] update docs --- README.md | 1 + adze/transform.py | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f259368..79bae52 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ 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 diff --git a/adze/transform.py b/adze/transform.py index 730d452..667d0da 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -65,11 +65,13 @@ def scale(poly: poly_t, factor: ArrayLike | float) -> poly_t: 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. From 4f1920c2bb3cbe72592ba5d246d480c8ce984292 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 21:26:35 -0700 Subject: [PATCH 31/35] more input validation --- adze/boundary.py | 10 ++++++++-- adze/shapes.py | 37 ++++++++++++++++++++++++++++++++---- adze/test/test_edge_cases.py | 3 +++ 3 files changed, 44 insertions(+), 6 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index 7369c73..ed9d369 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -27,14 +27,20 @@ def planes_from_boundary( 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}') - face_verts = vertices[face] - if face_verts.shape[0] < 3: + 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])), diff --git a/adze/shapes.py b/adze/shapes.py index 387152e..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: @@ -16,8 +44,9 @@ def build_tetrahedron(vertices: ArrayLike) -> poly_t: 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), @@ -39,6 +68,7 @@ def build_box(box_corners: ArrayLike) -> poly_t: Returns: Box in Schelgel representation. """ + box_corners = _normalize_box_corners(box_corners) neighbors = [ [1, 4, 3], [2, 5, 0], @@ -50,7 +80,6 @@ def build_box(box_corners: ArrayLike) -> poly_t: [6, 3, 4], ] - box_corners = numpy.asarray(box_corners, dtype=float) 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]], @@ -80,7 +109,7 @@ def planes_from_box(box_corners: ArrayLike) -> list[plane_t]: Returns: List of planes, facing inwards. """ - box_corners = numpy.asarray(box_corners, dtype=float) + box_corners = _normalize_box_corners(box_corners) faces = [ (( 0, 0, 1), -box_corners[0, 2]), (( 0, 0, -1), box_corners[1, 2]), @@ -104,7 +133,7 @@ def planes_from_tetrahedron(vertices: ArrayLike) -> list[plane_t]: 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/test/test_edge_cases.py b/adze/test/test_edge_cases.py index f611f65..44742d4 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -302,6 +302,7 @@ def test_split_noop_returns_independent_poly() -> None: assert poly['vertices'][0, 0] == 0.0 +<<<<<<< HEAD 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]]) @@ -318,6 +319,8 @@ def test_split_handles_disconnected_components_without_cut_edges() -> None: assert_allclose(adze.get_volume(split_right), 1.0) +======= +>>>>>>> 549a417 (more input validation) @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\\]'): From 2cbf4652e26d317248167ed9da91341085266f45 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 21:27:39 -0700 Subject: [PATCH 32/35] [split] fix splitting disjoint polys not touched by the splitting plane --- adze/test/test_edge_cases.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py index 44742d4..0d6d4e4 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -303,6 +303,9 @@ def test_split_noop_returns_independent_poly() -> None: <<<<<<< HEAD +<<<<<<< HEAD +======= +>>>>>>> 3c17160 ([split] fix splitting disjoint polys not touched by the splitting plane) 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]]) @@ -319,8 +322,11 @@ def test_split_handles_disconnected_components_without_cut_edges() -> None: assert_allclose(adze.get_volume(split_right), 1.0) +<<<<<<< HEAD ======= >>>>>>> 549a417 (more input validation) +======= +>>>>>>> 3c17160 ([split] fix splitting disjoint polys not touched by the splitting plane) @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\\]'): From 30b96107f44c5e4e0b1e248b893c3312d43052a1 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 22:02:52 -0700 Subject: [PATCH 33/35] [transform] improve handling of integer coordinates and general input handling --- adze/test/test_transform.py | 76 +++++++++++++++++++++++++++++++++++++ adze/transform.py | 66 ++++++++++++++++++++++++++++---- 2 files changed, 134 insertions(+), 8 deletions(-) diff --git a/adze/test/test_transform.py b/adze/test/test_transform.py index 633b635..d391db4 100644 --- a/adze/test/test_transform.py +++ b/adze/test/test_transform.py @@ -33,6 +33,18 @@ def test_rotate_z_quarter_turn() -> None: 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 = { @@ -100,3 +112,67 @@ def test_affine_translation_applies_to_multiple_vertices() -> None: 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/transform.py b/adze/transform.py index 667d0da..fd40d11 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -6,6 +6,51 @@ 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. @@ -22,11 +67,13 @@ def rotate(poly: poly_t, theta: float, axis: int) -> poly_t: 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 * v0 + c * v1 + 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 @@ -42,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 @@ -59,7 +107,8 @@ 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 @@ -77,6 +126,7 @@ def affine(poly: poly_t, xform: ArrayLike) -> poly_t: 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}') @@ -85,8 +135,8 @@ def affine(poly: poly_t, xform: ArrayLike) -> poly_t: mat4x3 = xform[:, :3] mat4x1 = xform[:, 3:4] - vh = mat4x3 @ poly['vertices'].T + mat4x1 + vh = mat4x3 @ vertices.T + mat4x1 if numpy.any(vh[3, :] == 0): raise AdzeError('Affine transform produced points with zero homogeneous coordinate') - poly['vertices'][:] = (vh[:3, :] / vh[3, :]).T + vertices[:] = (vh[:3, :] / vh[3, :]).T return poly From f650e62de5895065f143faa7533d24f2c5a33e49 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 22:11:00 -0700 Subject: [PATCH 34/35] [build_polyhedron] better validate inputs and correctly handle non-triangular faces --- adze/boundary.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index ed9d369..214aff1 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -8,6 +8,12 @@ from . import poly_t, plane_t 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: Sequence[ArrayLike] @@ -98,7 +104,7 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t: 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 # @@ -108,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. @@ -221,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 @@ -255,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] From 2c584eb87eaacbb4dc6bb1f2446a05167a6aab4a Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 1 Apr 2026 22:58:01 -0700 Subject: [PATCH 35/35] [tests] remove leftover rebase markers --- adze/test/test_edge_cases.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/adze/test/test_edge_cases.py b/adze/test/test_edge_cases.py index 0d6d4e4..f611f65 100644 --- a/adze/test/test_edge_cases.py +++ b/adze/test/test_edge_cases.py @@ -302,10 +302,6 @@ def test_split_noop_returns_independent_poly() -> None: assert poly['vertices'][0, 0] == 0.0 -<<<<<<< HEAD -<<<<<<< HEAD -======= ->>>>>>> 3c17160 ([split] fix splitting disjoint polys not touched by the splitting plane) 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]]) @@ -322,11 +318,6 @@ def test_split_handles_disconnected_components_without_cut_edges() -> None: assert_allclose(adze.get_volume(split_right), 1.0) -<<<<<<< HEAD -======= ->>>>>>> 549a417 (more input validation) -======= ->>>>>>> 3c17160 ([split] fix splitting disjoint polys not touched by the splitting plane) @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\\]'):