Compare commits

..
28 changed files with 1046 additions and 2982 deletions

2
MANIFEST.in Normal file
View file

@ -0,0 +1,2 @@
include README.md
include LICENSE.md

View file

@ -6,18 +6,18 @@
**Homepage:** https://mpxd.net/code/jan/adze
**Capabilities:**
- Clipping or splitting arbitrary polyhedra by a plane or a collection of planes (i.e. a convex polyhedron).
- Accurate anti-aliased voxelization of arbitrary polyhedra on non-uniform rectangular grids.
- Calculation of polynomial moments (volume, centroid, inertia, etc.) for clipped polyhedra.
- Clipping or splitting arbitrary polyhedra
- by a plane or a collection of planes (i.e. a convex polyhedron)
- Voxelizing arbitrary polyhedra
-
## Installation
**Dependencies:**
* python 3.11 or newer
* python 3.5 or newer
* numpy
* pytest (optional, testing)
* pytest-benchmark (optional, benchmarking)
Install with pip from PyPi (preferred):
```bash
@ -26,20 +26,30 @@ pip install adze
Install directly from git repository:
```bash
uv pip install git+https://mpxd.net/code/jan/adze.git
pip install git+https://mpxd.net/code/jan/adze.git@release
```
## Documentation
Most functions and classes are documented inline.
Geometry helper input contracts:
- `build_tetrahedron()` and `planes_from_tetrahedron()` expect tetrahedron vertices in the helper's documented positive winding.
- `build_box()` and `planes_from_box()` expect `box_corners[0]` to be the per-axis minimum and `box_corners[1]` the per-axis maximum.
- `adze.transform.affine()` accepts a general 4x4 homogeneous transform and applies the perspective divide using the fourth row, so projective transforms are supported.
To read the inline help,
```python3
import adze
help(adze)
help(adze.split)
```
## Examples
TODO
Read an OASIS file and write it back out:
```python3
import fatamorgana
with open('test.oas', 'rb') as f:
layout = fatamorgana.OasisLayout.read(f)
with open('test_write.oas', 'wb') as f:
layout.write(f)
```

View file

@ -1 +0,0 @@
../LICENSE.md

View file

@ -1 +0,0 @@
../README.md

View file

@ -1,4 +1,4 @@
"""
'''
adze is a library for accurate polyhedron clipping and anti-aliased voxelization.
Written with python + numpy.
@ -38,73 +38,27 @@ Helper functions include
--------------------------
### Internal Representation: The Schlegel Diagram
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
adze represents 3D shapes (polyhedra) using a specialized graph called a Schlegel
diagram. This format is designed for high-performance geometric calculations.
#### 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.
TODO
This
representation looks like
poly = {'neighbors': ndarray[Px3, int], 'vertices': ndarray[Px3, float]}
where poly['neighbors'] contains
#### Data Structure:
Shapes are stored as a dictionary containing two NumPy arrays:
- `poly['vertices']`: An `[N x 3]` array of float coordinates (X, Y, Z).
- `poly['neighbors']`: An `[N x 3]` array of integer indices.
`poly['neighbors'][i, :]` contains the indices of the 3 vertices connected to vertex `i`.
'''
"""
from .util import poly_t, plane_t
from .util import (
poly_t as poly_t,
plane_t as plane_t,
AdzeError as AdzeError,
)
from .split import split, clip
from .moments import get_volume, get_moments, number_of_moments
from .boundary import build_polyhedron, boundary_from_poly
from .shapes import build_tetrahedron, build_box, planes_from_tetrahedron, planes_from_box
from .voxel import voxelize
from .split import (
split as split,
clip as clip,
)
from .moments import (
get_volume as get_volume,
get_moments as get_moments,
number_of_moments as number_of_moments,
)
from .boundary import (
build_polyhedron as build_polyhedron,
boundary_from_poly as boundary_from_poly,
)
from .shapes import (
build_tetrahedron as build_tetrahedron,
build_box as build_box,
planes_from_tetrahedron as planes_from_tetrahedron,
planes_from_box as planes_from_box,
)
from .voxel import voxelize as voxelize
from .boolean import (
intersect as intersect,
difference as difference,
union as union,
intersect_convex as intersect_convex,
difference_convex as difference_convex,
union_convex as union_convex,
)
from .offset import (
offset as offset,
offset_anisotropic as offset_anisotropic,
smooth as smooth,
opening as opening,
closing as closing,
)
from .util import is_inside as is_inside
__author__ = 'Jan Petykiewicz'
__version__ = '0.2'

View file

@ -1,166 +0,0 @@
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])

View file

@ -1,124 +1,77 @@
from typing import Any
from collections.abc import Iterable, Sequence
from typing import List, Dict
import numpy
from numpy.linalg import norm
from numpy.typing import ArrayLike, NDArray
from . import poly_t, plane_t
from .util import _get_maps, find_components, find_faces, check_poly, AdzeError
from .util import _get_maps, find_components, find_faces
try:
# Check if running with line_profiler
profile
except NameError:
def profile(f):
return f
def _get_maps_checked(a: NDArray[numpy.integer], b: NDArray[numpy.integer]) -> tuple[NDArray[numpy.intp], NDArray[numpy.intp]]:
if a.size != b.size or not numpy.array_equal(numpy.sort(a), numpy.sort(b)):
raise AdzeError('Faces do not describe a valid closed polyhedron boundary')
return _get_maps(a, b)
def planes_from_boundary(
vertices: ArrayLike,
faces: Sequence[ArrayLike]
) -> list[plane_t]:
"""
def planes_from_boundary(vertices: numpy.ndarray,
faces: List[numpy.ndarray]
) -> List[plane_t]:
'''
Generate a list of planes (normal, signed distance) from the faces of a boundary-
representation polyhedron.
Args:
vertices: Nx3 ndarray specifying the polyhedron's vertex positions.
faces: List of 1d ndarrays. Each ndarray is a list of vertex indices,
:param vertices: Nx3 ndarray specifying the polyhedron's vertex positions.
:param faces: List of 1d ndarrays. Each ndarray is a list of vertex indices,
specifying a face.
Returns:
List of planes, represented by (normal vector, signed distance to origin) tuples.
"""
vertices = numpy.asarray(vertices, dtype=float)
if vertices.ndim != 2 or vertices.shape[1] != 3:
raise AdzeError(f'Vertices must have shape (N, 3). Got {vertices.shape}')
num_vertices = vertices.shape[0]
afaces = [numpy.asarray(ff) for ff in faces]
:return: List of planes, represented by (normal vector, signed distance to origin) tuples.
'''
planes = []
for face in afaces:
if face.ndim != 1:
raise AdzeError(f'Faces must be 1-dimensional. Got face with shape {face.shape}')
if face.size < 3:
raise AdzeError('Faces must have at least three vertices')
if numpy.unique(face).size != face.size:
raise AdzeError('Faces may not repeat a vertex index')
if numpy.any(face < 0) or numpy.any(face >= num_vertices):
raise AdzeError('Faces reference vertices outside the provided vertex list')
for face in faces:
face_verts = vertices[face]
rolled_verts = numpy.roll(face_verts, -1, axis=0)
n = numpy.array((
numpy.sum((face_verts[:, 1] - rolled_verts[:, 1]) * (face_verts[:, 2] + rolled_verts[:, 2])),
numpy.sum((face_verts[:, 2] - rolled_verts[:, 2]) * (face_verts[:, 0] + rolled_verts[:, 0])),
numpy.sum((face_verts[:, 0] - rolled_verts[:, 0]) * (face_verts[:, 1] + rolled_verts[:, 1])),
), dtype=float)
tolerance = numpy.finfo(float).eps * 64 * max(1.0, float(numpy.abs(face_verts).max())) ** 2
n_norm = norm(n)
if n_norm <= tolerance:
raise AdzeError('Faces must have non-zero area')
n /= n_norm
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)
d = -n @ centroid
planes.append((n, d))
planes.append(n, d)
return planes
def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t:
"""
Generate a 3-verted-connected Schlegel diagram representation
corresponding to the provided boundary-representation polyhedron.
@profile
def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t:
'''
Generate a 3-verted-connected Schlegel diagram corresponding to the
provided boundary-representation polyhedron.
Args:
vertices: Nx3 ndarray specifying the polyhedron's vertex positions.
faces: List of 1d ndarrays. Each ndarray is a list of vertex indices,
:param vertices: Nx3 ndarray specifying the polyhedron's vertex positions.
:param faces: List of 1d ndarrays. Each ndarray is a list of vertex indices,
specifying a face.
Returns:
Schelgel-representation polyhedron
"""
:return: Schelgel-representation polyhedron
'''
vertices = numpy.array(vertices, dtype=float)
if vertices.ndim != 2 or vertices.shape[1] != 3:
raise AdzeError(f'Vertices must have shape (N, 3). Got {vertices.shape}')
faces = [numpy.array(face, dtype=int) for face in faces]
afaces = [numpy.array(face, dtype=int) for face in faces]
if not afaces:
raise AdzeError('Need at least one face')
num_vertices = vertices.shape[0]
for face in afaces:
if face.ndim != 1:
raise AdzeError(f'Faces must be 1-dimensional. Got face with shape {face.shape}')
if face.size < 3:
raise AdzeError('Faces must have at least three vertices')
if numpy.unique(face).size != face.size:
raise AdzeError('Faces may not repeat a vertex index')
if numpy.any(face < 0) or numpy.any(face >= num_vertices):
raise AdzeError('Faces reference vertices outside the provided vertex list')
edges_per_vertex = numpy.bincount(numpy.hstack(afaces), minlength=num_vertices)
unused_vertices = numpy.where(edges_per_vertex == 0)[0]
if unused_vertices.size:
raise AdzeError(f'Vertices {unused_vertices} are unused by any face')
edges_per_vertex = numpy.bincount(numpy.hstack(faces))
if edges_per_vertex.min() < 3:
raise AdzeError(f'Vertex {edges_per_vertex.argmin()} has < 3 edges')
raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges')
if edges_per_vertex.max() == 3 and all(face.size == 3 for face in afaces):
#
# In this case, we don't need to duplicate any vertices to make a 3-vertex-connected graph
#
neighbors = numpy.full_like(vertices, vertices.size, dtype=int)
for face in afaces:
if edges_per_vertex.max() == 3:
'''
In this case, we don't need to duplicate any vertices to make a 3-vertex-connected graph
'''
neighbors = numpy.empty_like(vertices, dtype=int).fill(vertices.size)
for face in faces:
# Check if each vertex in this face is already linked to its next or previous face-neighbor
prev_vert = numpy.roll(face, 1)
next_vert = numpy.roll(face, -1)
neighbor_rows = neighbors[face, :]
has_prev = (neighbor_rows == prev_vert[:, None]).any(axis=1)
has_next = (neighbor_rows == next_vert[:, None]).any(axis=1)
has_prev = (neighbor_rows == prev_vert).any(axis=1)
has_next = (neighbor_rows == next_vert).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.
# Thus, we will never encounter a situation in which prv == nxt.
# If the vertex hasn't been linked to anything yet, set its first two
# polyhedron-neighbors to its face-neighbors
@ -133,11 +86,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]
poly = {'vertices': vertices, 'neighbors': neighbors}
check_poly(poly, check_connectivity=False)
return poly
return {'vertices': vertices, 'neighbors': neighbors}
"""
'''
Some vertices link more than three edges.
We only allow three edges per vertex in the graph, so we need to make
degenerate copies of those vertices.
@ -198,44 +149,44 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t:
Finally, we can remove the first two ('excess') duplicate vertices in each ring, and update
the links to reflect their removal.
"""
'''
# starting row for each original vertex
start = numpy.roll(numpy.cumsum(edges_per_vertex), 1)
start[0] = 0
# number of input vertices (v) and duplicates (d)
num_vertices = vertices.shape[0]
num_duplicates = edges_per_vertex.sum()
neighbors = numpy.empty((num_duplicates, 3), dtype=int)
#
# Fill columns (1, 2) with original vertex inds (f#_next, f#_prev)
#
'''
Fill columns (1, 2) with original vertex inds (f#_next, f#_prev)
'''
num_filled_rows = numpy.zeros(num_duplicates, dtype=int)
for face in afaces:
for face in faces:
# assume a face can't use the same vertex twice
v_inds = start[face] + num_filled_rows[face]
neighbors[v_inds, 1] = numpy.roll(face, -1)
neighbors[v_inds, 2] = numpy.roll(face, 1)
num_filled_rows[face] += 1
#
# Fill columns (0, 2) with new vertex inds (next_row, prev_row)
# to complete doubly-linked rings
#
'''
Fill columns (0, 2) with new vertex inds (next_row, prev_row)
to complete doubly-linked rings
'''
for v in range(num_vertices):
v0 = start[v]
s = slice(v0, v0 + edges_per_vertex[v])
m, n = _get_maps_checked(neighbors[s, 2], neighbors[s, 1])
m, n = _get_maps(neighbors[s, 2], neighbors[s, 1])
neighbors[s, 0] = n + v0
neighbors[s, 2] = m + v0
#
# for each pair of original vertices,
# find subvertices whose f#_next pointers point to each other's original vertices,
# and link them using column 1 (i.e. set their third_row pointers to each other)
#
'''
for each pair of original vertices,
find subvertices whose f#_next pointers point to each other's original vertices,
and link them using column 1 (i.e. set their third_row pointers to each other)
'''
# Mapping from row to original vertex index
v0s = numpy.repeat(numpy.arange(len(edges_per_vertex)), edges_per_vertex)
@ -247,27 +198,27 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t:
dst_mask = numpy.empty(num_duplicates, dtype=bool)
for v in range(num_vertices):
ss = start[v]
ee = ss + edges_per_vertex[v]
s = start[v]
e = s + edges_per_vertex[v]
src_mask.fill(False)
src_mask[ee:] = target_vert[ee:] == v # find rows which reference us
src_mask[e:] = target_vert[e:] == v # find rows which reference us
src_vert = v0s[src_mask] # figure out their original vertex numbers
if src_vert.size == 0:
continue
dst_mask.fill(False)
dst_mask[ss:ee] = target_vert[ss:ee] > v # mask out any references to verts >= current
dst_mask[s:e] = target_vert[s:e] > v # mask out any references to verts >= current
dst_vert = target_vert[dst_mask]
ma, mb = _get_maps_checked(dst_vert, src_vert)
ma, mb = _get_maps(dst_vert, src_vert)
neighbors[dst_mask, 1] = numpy.where(src_mask)[0][mb]
neighbors[src_mask, 1] = numpy.where(dst_mask)[0][ma]
"""
'''
Remove first two duplicates of each vertex (they aren't needed)
"""
'''
nxt, third, prv = neighbors[start, :].T
nxt_nxt, nxt_third, _nxt_prv = neighbors[nxt, :].T
@ -303,38 +254,28 @@ def build_polyhedron(vertices: ArrayLike, faces: Iterable[ArrayLike]) -> poly_t:
final_vertices = numpy.repeat(vertices, edges_per_vertex - 2, axis=0)
poly = {'vertices': final_vertices, 'neighbors': neighbors}
check_poly(poly, check_connectivity=False)
return poly
return {'vertices': final_vertices, 'neighbors': neighbors}
def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]:
"""
@profile
def boundary_from_poly(poly: poly_t) -> Dict:
'''
Generate a boundary represeentation corresponding to the provided
3-vertex-connected Schlegel diagram.
Args:
poly: Polyhedron to convert, in Schlegel representation.
Returns:
Dict containing 'vertices' (Nx3 ndarray of vertex locations)
:param poly: Polyhedron to convert, in Schlegel representation.
:return: Dict containing 'vertices' (Nx3 ndarray of vertex locations)
and 'faces' (list of ndarrays specifying the indices of vertices
used for constructing each face).
"""
'''
neighbors = poly['neighbors']
vertices = poly['vertices']
if vertices.shape[0] == 0:
return []
check_poly(poly, check_connectivity=False)
owning_component = find_components(neighbors)
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)]
components = [[] for _ in range(num_components)]
for face in faces:
component_ind = owning_component[face[0]]
components[component_ind].append(face)
@ -358,3 +299,4 @@ def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]:
boundaries.append(boundary)
return boundaries

View file

@ -1,73 +1,57 @@
from operator import index
from typing import Dict, Tuple
import numpy
from numpy.typing import NDArray
from . import poly_t
from .util import AdzeError
from . import poly_t, plane_t
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
# Check if running with line_profiler
profile
except NameError:
def profile(f):
return f
def number_of_moments(order: int) -> int:
"""
'''
Returns the number of moments with a given order or below.
Args:
order: Maximum polynomial order for the moments.
Returns:
Number of moments with that order or fewer.
"""
order = _normalize_order(order)
:param order: Maximum polynomial order for the moments.
:return: Number of moments with that order or fewer.
'''
return ((order + 1) * (order + 2) * (order + 3)) // 6
def get_volume(poly: poly_t) -> float:
"""
'''
Calculates the volume of a polyhedron (0th moment).
Args:
poly: Polyhedron to evaluate, in Schlegel representation.
Returns:
Volume of the polyhedron.
"""
:param poly: Polyhedron to evaluate, in Schlegel representation.
:return: Volume of the polyhedron.
'''
return get_moments(poly, 0)[0]
def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]:
"""
@profile
def get_moments(poly: poly_t, order: int) -> numpy.ndarray:
'''
Calculates the moments of a polyhedron, up to the specified polynomial order.
Args:
poly: Polyhedron to evaluate, in Schlegel representation.
order: Maximum polynomial order for moments.
Returns: Moments, increasing polynomial order:
:param poly: Polyhedron to evaluate, in Schlegel representation.
:param order: Maximum polynomial order for moments.
:return: Moments, increasing polynomial order:
[1, x, y, z, xx, xy, xz, yy, yz, zz, xxx, xxy, xxz, ...]
"""
order = _normalize_order(order)
'''
vertices = poly['vertices']
neighbors = poly['neighbors']
num_verts = vertices.shape[0]
if num_verts == 0:
return numpy.zeros(number_of_moments(order), dtype=float)
return numpy.array([0], dtype=float)
#
# Decompose polyhedron into triangle fans
#
'''
Decompose polyhedron into triangle fans
'''
faces = find_faces(neighbors)
triangle_fans = []
@ -83,9 +67,9 @@ def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]:
triverts = vertices[triangle_inds[:ilen]]
triangle_fans.append(triverts)
#
# Calculate the 0th-order moment
#
'''
Calculate the 0th-order moment
'''
triangles = numpy.vstack(triangle_fans)
volumes = -numpy.linalg.det(triangles)
moment0 = numpy.array([volumes.sum() / 6])
@ -93,9 +77,9 @@ def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]:
if order == 0:
return moment0
#
# Iteratively calculate higher-order moments, as per Koehl (2012).
#
'''
Iteratively calculate higher-order moments, as per Koehl (2012).
'''
prevlayer, curlayer = 0, 1
inds = numpy.arange(order + 1)
mx, my = numpy.meshgrid(inds, inds, indexing='ij')
@ -111,7 +95,7 @@ def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]:
moment_list = [moment0]
for c in range(1, order + 1):
valid[curlayer] = c >= mx + my
# num_valid = (c + 1) * (c + 2) // 2 # always an int, see number_of_moments()
num_valid = (c + 1) * (c + 2) // 2 # always an int, see number_of_moments()
Q_prev = Q[:, :, valid[prevlayer], prevlayer]
Q[:, :, 0, :, curlayer] = 0

View file

@ -1,231 +0,0 @@
import numpy
from numpy.typing import NDArray
from collections.abc import Callable
from . import poly_t
from .util import find_faces
from .boundary import planes_from_boundary
RateFunction = Callable[[NDArray[numpy.floating]], float]
def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t:
"""
Offset a polyhedron by a distance delta.
Positive delta expands the shape, negative delta shrinks (etches) it.
This implementation uses a "mitered" offset, shifting the planes of the
polyhedron and recalculating vertex positions.
Args:
poly: Input polyhedron in Schlegel representation.
delta: Offset distance.
miter_limit: Maximum allowed multiplier for displacement at sharp corners.
Returns:
Offsetted polyhedron.
Note:
- **Topology Preservation:** This operation preserves the graph topology.
It will not automatically merge components that collide or remove
holes that close up.
- **Self-Intersection:** Large offsets (especially inward) can cause
faces to pass through each other, creating "inside-out" geometry
with negative volume.
- **Cleanup Recommendation:** For robust results in simulators, it is
recommended to use boolean operations to "clean" the result:
- **Shrinking:** Use `intersect(original, result)` to ensure the result
remains strictly within the original bounds and to remove inverted geometry.
- **Expansion:** Use `union(original, result)` to ensure no "gaps" are created
between the original and expanded shape due to numerical drift, and
`intersect(boundary, result)` to keep the shape within a global domain.
- **Smoothing and Gap-Filling:**
- **Smoothing:** High-curvature areas can be smoothed by moving vertices
toward the average of their three neighbors.
- **Gap-Filling:** Small gaps or numerical "noise" can be filled using a
"Closing" operation: an expansion followed by a shrinking of the same
magnitude (or vice versa for small protrusions).
"""
def constant_rate(_n: NDArray) -> float:
return delta
return offset_anisotropic(poly, constant_rate, miter_limit)
def offset_anisotropic(poly: poly_t, rate_func: RateFunction, miter_limit: float = 10.0) -> poly_t:
"""
Offset a polyhedron with a direction-dependent rate.
Args:
poly: Input polyhedron.
rate_func: Function taking a unit normal (inward facing) and returning
the scalar offset for that face. Positive values expand against the normal.
miter_limit: Maximum allowed multiplier for displacement.
"""
if poly['vertices'].shape[0] == 0:
return poly
vertices = poly['vertices']
neighbors = poly['neighbors']
num_verts = vertices.shape[0]
# 1. Find all faces and their unit normals
faces = find_faces(neighbors)
# Map vertex to which faces it belongs to
vertex_to_faces: list[list[int]] = [[] for _ in range(num_verts)]
face_normals = []
face_deltas = []
for face_idx, face in enumerate(faces):
# planes_from_boundary handles robust normal calculation via Newell's method.
# Note: adze convention for boundary representation usually has
# INWARD facing normals for clipping.
plane = planes_from_boundary(vertices, [face])[0]
normal = plane[0]
face_normals.append(normal)
face_deltas.append(rate_func(normal))
for v_idx in face:
vertex_to_faces[v_idx].append(face_idx)
# 2. For each vertex, solve the 3x3 system
new_vertices = numpy.zeros_like(vertices)
for i in range(num_verts):
f_indices = vertex_to_faces[i]
if len(f_indices) != 3:
# Fallback if topology is non-manifold
new_vertices[i] = vertices[i]
continue
# Normal matrix A
A = numpy.array([face_normals[fi] for fi in f_indices])
# Target deltas for the 3 faces
deltas = numpy.array([face_deltas[fi] for fi in f_indices])
# If n is INWARD normal, then to EXPAND (positive delta) we want to move
# AGAINST the normal.
# n . (V' - V) = -delta
# A d = -deltas
# Max delta magnitude for miter limit check
max_delta = numpy.max(numpy.abs(deltas))
try:
# solve A d = -deltas
rhs = -deltas
d = numpy.linalg.solve(A, rhs)
# Check miter limit
d_norm = numpy.linalg.norm(d)
if max_delta > 1e-15 and d_norm > miter_limit * max_delta:
# Clamp displacement
avg_n = numpy.mean(A, axis=0)
avg_n_norm = numpy.linalg.norm(avg_n)
# Fallback direction is average normal
# Fallback magnitude is limited
if avg_n_norm > 1e-12:
# Move along average inward normal (negative for expansion)
# Use the average requested delta
avg_delta = numpy.mean(deltas)
new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * avg_delta
else:
new_vertices[i] = vertices[i] + d * (miter_limit * max_delta / d_norm)
else:
new_vertices[i] = vertices[i] + d
except numpy.linalg.LinAlgError:
# Singular matrix
avg_n = numpy.mean(A, axis=0)
avg_n_norm = numpy.linalg.norm(avg_n)
avg_delta = numpy.mean(deltas)
if avg_n_norm > 1e-12:
new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * avg_delta
else:
new_vertices[i] = vertices[i]
return {
'vertices': new_vertices,
'neighbors': neighbors.copy()
}
def smooth(poly: poly_t, factor: float = 0.5) -> poly_t:
"""
Perform Laplacian smoothing on the polyhedron vertices.
Each vertex is moved toward the average position of its three neighbors.
Args:
poly: Input polyhedron.
factor: Smoothing factor (0.0 to 1.0). 0.0 is no change, 1.0 is full move.
Returns:
Smoothed polyhedron.
"""
if poly['vertices'].shape[0] == 0:
return poly
vertices = poly['vertices']
neighbors = poly['neighbors']
# Average of 3 neighbors
neighbor_verts = vertices[neighbors] # [N x 3 x 3]
avg_neighbor_pos = numpy.mean(neighbor_verts, axis=1) # [N x 3]
new_vertices = vertices + factor * (avg_neighbor_pos - vertices)
return {
'vertices': new_vertices,
'neighbors': neighbors.copy()
}
def closing(poly: poly_t, delta: float, cleanup: bool = True) -> poly_t:
"""
Perform a morphological 'Closing' operation: Expansion followed by Shrinking.
Useful for filling small gaps or cracks.
Args:
poly: Input polyhedron.
delta: magnitude of offset (must be positive).
cleanup: Whether to perform boolean cleanup after expansion.
"""
if delta <= 0:
return poly
# 1. Expand
expanded = offset(poly, delta)
if cleanup:
from .boolean import union
expanded = union(poly, expanded)
# 2. Shrink
result = offset(expanded, -delta)
if cleanup:
from .boolean import intersect
result = intersect(expanded, result)
return result
def opening(poly: poly_t, delta: float, cleanup: bool = True) -> poly_t:
"""
Perform a morphological 'Opening' operation: Shrinking followed by Expansion.
Useful for removing small protrusions or 'noise'.
Args:
poly: Input polyhedron.
delta: magnitude of offset (must be positive).
cleanup: Whether to perform boolean cleanup after shrinking.
"""
if delta <= 0:
return poly
# 1. Shrink
shrunk = offset(poly, -delta)
if cleanup:
from .boolean import intersect
shrunk = intersect(poly, shrunk)
# 2. Expand
result = offset(shrunk, delta)
if cleanup:
from .boolean import union
result = union(shrunk, result)
return result

View file

@ -1,52 +1,19 @@
from typing import List
import numpy
from numpy.linalg import norm
from numpy.typing import ArrayLike
from . import poly_t, plane_t
from .util import AdzeError
def _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:
"""
def build_tetrahedron(vertices: numpy.ndarray) -> poly_t:
'''
Build a Schelegel-representation tetrahedron.
Args:
vertices: 4x3 array, representing the vertex coordinates. Vertices must
be ordered with the positive winding expected by this helper.
Returns:
Tetrahedron in Schelgel representation.
"""
vertices = _normalize_tetrahedron_vertices(vertices)
:param vertices: 4x3 array, representing the vertex coordinates.
:return: Tetrahedron in Schelgel representation.
'''
poly = {
'vertices': vertices,
'vertices': numpy.array(vertices, dtype=float),
'neighbors': numpy.array((
(1, 3, 2),
(2, 3, 0),
@ -56,19 +23,14 @@ def build_tetrahedron(vertices: ArrayLike) -> poly_t:
return poly
def build_box(box_corners: ArrayLike) -> poly_t:
"""
def build_box(box_corners: numpy.ndarray) -> poly_t:
'''
Build a Schelegel-representation box.
Args:
box_corners: 2x3 array, representing the vertex coordinates of
two diagonally-opposite corners of the box. `box_corners[0]` must be
the per-axis minimum corner and `box_corners[1]` the per-axis maximum.
Returns:
Box in Schelgel representation.
"""
box_corners = _normalize_box_corners(box_corners)
:param box_corners: 2x3 array, representing the vertex coordinates of
two diagonally-opposite corners of the box.
:return: Box in Schelgel representation.
'''
neighbors = [
[1, 4, 3],
[2, 5, 0],
@ -97,19 +59,15 @@ def build_box(box_corners: ArrayLike) -> poly_t:
}
def planes_from_box(box_corners: ArrayLike) -> list[plane_t]:
"""
def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]:
'''
Construct a list of planes corresponding to the faces of a box.
Args:
box_corners: 2x3 array, representing the vertex coordinates of
two diagonally-opposite corners of the box. `box_corners[0]` must be
the per-axis minimum corner and `box_corners[1]` the per-axis maximum.
Returns:
List of planes, facing inwards.
"""
box_corners = _normalize_box_corners(box_corners)
:param box_corners: 2x3 array, representing the vertex coordinates of
two diagonally-opposite corners of the box.
:return: List of planes, facing inwards.
'''
box_corners = numpy.array(box_corners)
faces = [
(( 0, 0, 1), -box_corners[0, 2]),
(( 0, 0, -1), box_corners[1, 2]),
@ -122,24 +80,20 @@ def planes_from_box(box_corners: ArrayLike) -> list[plane_t]:
return [(numpy.array(n), d) for n, d in faces]
def planes_from_tetrahedron(vertices: ArrayLike) -> list[plane_t]:
"""
def planes_from_tetrahedron(vertices: numpy.ndarray) -> List[plane_t]:
'''
Construct a list of planes corresponding to the faces of a tetrahedron.
Args:
vertices: 4x3 array, representing the vertex coordinates. Vertices must
be ordered with the positive winding expected by this helper.
Returns:
List of planes, facing inwards.
"""
verts = _normalize_tetrahedron_vertices(vertices)
:param vertices: 4x3 array, representing the vertex coordinates.
:return: List of planes, facing inwards.
'''
verts = numpy.array(vertices, dtype=float)
vset_inds = numpy.array((
[3, 1, 2, 1],
[2, 0, 3, 2],
[1, 3, 0, 3],
[0, 2, 1, 0]))
vertsets = numpy.moveaxis(numpy.dstack([verts[v] for v in vset_inds]), 2, 0)
vertsets = numpy.moveaxis(numpy.dstack(verts[v] for v in vset_inds), 2, 0)
ab = vertsets[:, 0, :] - vertsets[:, 1, :]
cd = vertsets[:, 2, :] - vertsets[:, 3, :]
@ -148,4 +102,4 @@ def planes_from_tetrahedron(vertices: ArrayLike) -> list[plane_t]:
centers = numpy.sum(vertsets[:, :3, :], axis=1) / 3
d = -numpy.sum(n * centers, axis=1)
return list(zip(n, d, strict=True))
return [plane for plane in zip(n, d)]

View file

@ -1,137 +1,71 @@
from typing import overload, Literal
import math
import numpy
from . import poly_t, plane_t
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')
from .util import build_empty, _get_map
try:
distance = float(plane[1])
except (TypeError, ValueError) as exc:
distance_shape = numpy.asarray(plane[1]).shape
raise AdzeError(f'Plane distance must be a scalar. Got {distance_shape}') from exc
if not math.isfinite(distance):
raise AdzeError('Plane distance must be finite')
return normal, float(distance)
# Check if running with line_profiler
profile
except NameError:
def profile(f):
return f
def clip(poly: poly_t, plane: plane_t, atol: float = 1e-12) -> poly_t:
"""
def clip(poly: poly_t, plane: plane_t) -> poly_t:
'''
Clip a polyhedron with a plane, keeping only the part which is on
the same side as the plane's normal vector.
This function is equivalent to calling _split(poly, plane, same_only=True).
This function is equivalent to calling split(poly, plane, same_only=True).
Args:
poly: Polyhedron to clip, in chiral Schlegel representation.
plane: Plane to clip against.
atol: Absolute tolerance for "on-plane" checks. Default 1e-12.
Returns:
Clipped polyhedron.
"""
left_poly = _split(poly, plane, same_only=True, atol=atol)
:param poly: Polyhedron to clip, in chiral Schlegel representation.
:param plane: Plane to clip against.
:return: Clipped polyhedron.
'''
left_poly = split(poly, plane, same_only=True)
return left_poly
def split(poly: poly_t, plane: plane_t, atol: float = 1e-12) -> tuple[poly_t, poly_t]:
"""
Clip a polyhedron with a plane, keeping both parts.
This function is equivalent to calling _split(poly, plane, same_only=False).
Args:
poly: Polyhedron to clip, in chiral Schlegel representation.
plane: Plane to clip against.
atol: Absolute tolerance for "on-plane" checks. Default 1e-12.
Returns:
same_side_poly, other_side_poly
The first polyhedron is on from the same side as the plane's normal vector.
"""
return _split(poly, plane, same_only=False, atol=atol)
@overload
def _split(poly: poly_t, plane: plane_t, same_only: Literal[True], atol: float = 1e-12) -> poly_t:
...
@overload
def _split(poly: poly_t, plane: plane_t, same_only: Literal[False], atol: float = 1e-12) -> tuple[poly_t, poly_t]:
...
@overload
def _split(poly: poly_t, plane: plane_t, same_only: bool, atol: float = 1e-12) -> tuple[poly_t, poly_t] | poly_t:
...
def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float = 1e-12) -> tuple[poly_t, poly_t] | poly_t:
"""
@profile
def split(poly, plane, same_only: bool = False):
'''
Clip a polyhedron with a plane.
If same_only is False (default), returns the tuple (same_side_poly, other_side_poly),
where same_side_poly is on the same side as the plane's normal vector. Otherwise,
returns only same_side_poly (somewhat faster).
Args:
poly: Polyhedron to clip, in chiral Schlegel representation.
plane: Plane to clip against.
same_only: If True, only returns the clipped poly from the same side as the
:param poly: Polyhedron to clip, in chiral Schlegel representation.
:param plane: Plane to clip against.
:param same_only: If True, only returns the clipped poly from the same side as the
plane's normal vector. Default False.
atol: Absolute tolerance for "on-plane" checks. Default 1e-12.
Returns:
(same_side_poly, other_side_poly) if same_only is False (default), otherwise
:return: (same_side_poly, other_side_poly) if same_only is False (default), otherwise
only returns same_side_poly.
"""
plane = _normalize_plane(plane)
'''
vertices = poly['vertices']
neighbors = poly['neighbors']
num_start = neighbors.shape[0]
if num_start == 0:
ret = build_empty(), build_empty()
return ret[0] if same_only else ret
dists = plane[1] + (vertices @ plane[0])
if (dists >= -atol).all():
ret = _copy_poly(poly), build_empty()
return ret[0] if same_only else ret
if (dists <= atol).all():
ret = build_empty(), _copy_poly(poly)
return ret[0] if same_only else ret
left = dists > 0
right = numpy.logical_not(left)
num_left = numpy.count_nonzero(left)
num_right = num_start - num_left
'''
if the poly lies entirely on one side of the plane, just return it
'''
if num_left == 0:
# if all on right or touching plane
ret = build_empty(), poly
return ret[0] if same_only else ret
elif dists.min() >= 0:
# if all on left or touching plane
# Can't reuse 'left' because <= vs <
ret = poly, build_empty()
return ret[0] if same_only else ret
right_inds = numpy.where(right)[0]
next_vertex = neighbors[right_inds, :].ravel()
@ -139,20 +73,20 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float =
far_vertex_left = left[next_vertex]
if not far_vertex_left.any():
#
# No edges cross the plane, but components exist on either side
#
rl_edge_inds = numpy.empty(0, dtype=int)
target_edge_inds = numpy.empty(0, dtype=int)
'''
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)
new_vertices = numpy.empty((0, 3), dtype=float)
src_pns = target_edge_inds.copy()
num_new_vertices = 0
rverts = numpy.empty(0, dtype=int)
lverts = rverts.copy()
else:
#
# Some edges cross the plane
#
'''
Some edges cross the plane
'''
# remove edges which don't also touch the left half-plane
which_edges_cross, rl_edge_inds = numpy.divmod(numpy.where(far_vertex_left)[0], 3)
rverts = right_inds[which_edges_cross]
@ -160,16 +94,16 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float =
num_new_vertices = rverts.size
#
# figure out new vertex positions
#
'''
figure out new vertex positions
'''
d_right = dists[rverts][:, None]
d_left = dists[lverts][:, None]
new_vertices = (d_right * vertices[lverts] - d_left * vertices[rverts]) / (d_right - d_left)
#
# walk to next crossing edge
#
'''
walk to next crossing edge
'''
prev_verts = rverts
cur_verts = lverts
edge_walk_inds = numpy.arange(num_new_vertices)
@ -202,25 +136,29 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float =
# figure out the index of each target edge using row-wise _get_map
dims = [num_start, num_start]
a1d = numpy.ravel_multi_index((rverts, lverts), dims)
b1d = numpy.ravel_multi_index(tuple(edge_walk_results), dims)
b1d = numpy.ravel_multi_index(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)
ind_map_left[left] = numpy.arange(num_left)
'''
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],
target_order + num_left,
ind_map_left[lverts], # update left vertices based on new indexing
target_order + num_left, # new vertex indices are same as edge indices + offset
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]]
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[(lverts, src_pns)] = num_left + numpy.arange(num_new_vertices)
old_neighbors_left = old_neighbors_left[left]
@ -236,8 +174,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],
target_edge_inds + num_right,
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
target_order + num_right))
old_vertices_right = vertices[right]
@ -253,3 +191,4 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False, atol: float =
}
return left_poly, right_poly

View file

@ -1,3 +0,0 @@
"""
Tests (run with `python3 -m pytest -rxPXs | tee results.txt`)
"""

View file

@ -1,10 +0,0 @@
from typing import Any
import pytest
FixtureRequest = Any
@pytest.fixture(scope='module', params=[0, 1, 2])
def poly_order(request: FixtureRequest) -> int:
return request.param

View file

@ -1,56 +0,0 @@
"""
Benchmarking, run with `python3 -m adze.test.benchmark`
TODO: Consider using pytest-benchmark?
"""
from collections.abc import Callable
import logging
import numpy
from numpy.typing import NDArray
import adze
import adze.util
from .utils import build_rand_tetrahedron, rand_tetrahedron_vertices
logger = logging.getLogger(__name__)
def test_split(benchmark: Callable) -> None:
poly = build_rand_tetrahedron()
faceset = adze.planes_from_tetrahedron(rand_tetrahedron_vertices())
benchmark(adze.clip, poly, faceset[0])
def test_split_bulk_1000(benchmark: Callable) -> None:
NUM_TRIALS = 1000
polys_bulk = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)]
faceset = adze.planes_from_tetrahedron(rand_tetrahedron_vertices())
bulk = {
'vertices': numpy.vstack([p['vertices'] for p in polys_bulk]),
'neighbors': numpy.vstack([p['neighbors'] for p in polys_bulk]) + numpy.arange(NUM_TRIALS).repeat(4)[:, None] * 4,
}
benchmark(adze.clip, bulk, faceset[0])
def get_intersection_moments(poly: adze.poly_t, faces: NDArray[numpy.intp], poly_order: int) -> NDArray[numpy.float64]:
# Clip the first tetrahedron using the faces of the second
for face in faces:
poly = adze.clip(poly, face)
# find the moments (up to quadratic order) of the clipped poly
om = adze.get_moments(poly, poly_order)
return om
def test_intersection(benchmark: Callable, poly_order: int = 0) -> None:
"""
Benchmark intersection between pairs of tetrahedra
"""
poly = build_rand_tetrahedron()
faces = adze.planes_from_tetrahedron(rand_tetrahedron_vertices())
benchmark(get_intersection_moments, poly, faces, poly_order)

View file

@ -1,163 +0,0 @@
import numpy
import adze
from adze.boolean import intersect, difference, union
from adze.shapes import build_box
from adze.util import check_poly
def test_intersect_cubes() -> None:
# Cube 1: (0,0,0) to (2,2,2), volume = 8
poly_a = build_box([[0, 0, 0], [2, 2, 2]])
# Cube 2: (1,1,1) to (3,3,3), volume = 8
poly_b = build_box([[1, 1, 1], [3, 3, 3]])
# Overlap is from (1,1,1) to (2,2,2), volume = 1
result = intersect(poly_a, poly_b)
check_poly(result)
volume = adze.get_volume(result)
assert numpy.isclose(volume, 1.0)
def test_intersect_no_overlap() -> None:
poly_a = build_box([[0, 0, 0], [1, 1, 1]])
poly_b = build_box([[2, 2, 2], [3, 3, 3]])
result = intersect(poly_a, poly_b)
check_poly(result)
assert result['vertices'].shape[0] == 0
assert adze.get_volume(result) == 0.0
def test_difference_cubes() -> None:
# Cube 1: (0,0,0) to (2,2,2), volume = 8
poly_a = build_box([[0, 0, 0], [2, 2, 2]])
# Cube 2: (1,1,1) to (3,3,3), volume = 8
poly_b = build_box([[1, 1, 1], [3, 3, 3]])
# A - B should be 8 - 1 = 7
result = difference(poly_a, poly_b)
check_poly(result)
volume = adze.get_volume(result)
assert numpy.isclose(volume, 7.0)
def test_union_cubes() -> None:
# Cube 1: (0,0,0) to (2,2,2), volume = 8
poly_a = build_box([[0, 0, 0], [2, 2, 2]])
# Cube 2: (1,1,1) to (3,3,3), volume = 8
poly_b = build_box([[1, 1, 1], [3, 3, 3]])
# A + B should be 8 + 8 - 1 = 15
result = union(poly_a, poly_b)
check_poly(result)
volume = adze.get_volume(result)
assert numpy.isclose(volume, 15.0)
def test_union_no_overlap() -> None:
poly_a = build_box([[0, 0, 0], [1, 1, 1]])
poly_b = build_box([[2, 2, 2], [3, 3, 3]])
# A + B should be 1 + 1 = 2
result = union(poly_a, poly_b)
check_poly(result)
volume = adze.get_volume(result)
assert numpy.isclose(volume, 2.0)
def test_intersect_nonconvex_lshape() -> None:
"""
Test intersection with a non-convex L-shaped object.
The L-shape is formed by two boxes:
B1: [0,2]x[0,1]x[0,1]
B2: [0,1]x[0,2]x[0,1]
Total volume = 2 + 2 - 1 (overlap [0,1]x[0,1]x[0,1]) = 3
"""
b1 = build_box([[0, 0, 0], [2, 1, 1]])
b2 = build_box([[0, 0, 0], [1, 2, 1]])
# union(b1, b2) will produce a non-convex polyhedron
l_shape = union(b1, b2)
check_poly(l_shape)
assert numpy.isclose(adze.get_volume(l_shape), 3.0)
b3 = build_box([[0.5, 0.5, 0], [1.5, 1.5, 1]])
# Test L-shape as poly_a
res1 = intersect(l_shape, b3)
check_poly(res1)
vol1 = adze.get_volume(res1)
assert numpy.isclose(vol1, 0.75)
# Test L-shape as poly_b
res2 = intersect(b3, l_shape)
check_poly(res2)
vol2 = adze.get_volume(res2)
assert numpy.isclose(vol2, 0.75)
def test_difference_nonconvex() -> None:
# B1: [0,2]x[0,1]x[0,1], vol=2
b1 = build_box([[0, 0, 0], [2, 1, 1]])
# B2: [0,1]x[0,2]x[0,1], vol=2
b2 = build_box([[0, 0, 0], [1, 2, 1]])
# B1 - B2 = [1, 2] x [0, 1] x [0, 1] -> vol=1
res = difference(b1, b2)
check_poly(res)
assert numpy.isclose(adze.get_volume(res), 1.0)
# L-shape - B3
# L-shape: B1 + B2
# B3: [0.5, 1.5] x [0.5, 1.5] x [0, 1]
# L-shape \cap B3 = 0.75
# L-shape - B3 = 3 - 0.75 = 2.25
l_shape = union(b1, b2)
b3 = build_box([[0.5, 0.5, 0], [1.5, 1.5, 1]])
res2 = difference(l_shape, b3)
check_poly(res2)
assert numpy.isclose(adze.get_volume(res2), 2.25)
def test_difference_hole() -> None:
"""
Test subtracting a small box strictly inside a larger box (Hole Drilling).
"""
outer = build_box([[0, 0, 0], [3, 3, 3]]) # Vol 27
inner = build_box([[1, 1, 1], [2, 2, 2]]) # Vol 1
diff = difference(outer, inner)
check_poly(diff)
assert numpy.isclose(adze.get_volume(diff), 26.0)
def test_robust_normals() -> None:
"""
Test that planes_from_boundary handles collinear vertices.
"""
# A flat square face with collinear points at the start
# [0,0,0], [1,0,0], [2,0,0] are collinear.
vertices = numpy.array([
[0, 0, 0],
[1, 0, 0],
[2, 0, 0],
[2, 2, 0],
[0, 2, 0],
# Add a top point to make it a pyramid (non-degenerate 3D shape)
[1, 1, 1]
])
# Pyramid faces
faces = [
[0, 1, 2, 3, 4], # Base (with collinear points)
[0, 5, 1],
[1, 5, 2],
[2, 5, 3],
[3, 5, 4],
[4, 5, 0]
]
# This should now succeed and produce correct planes
planes = adze.boundary.planes_from_boundary(vertices, faces)
# Check the base plane (first face)
# The normal should be [0, 0, -1] (facing inward for a CCW base viewed from below?)
# Let's check orientation. vertices 0,1,2,3,4 are CCW if viewed from +Z.
# Newell's method for CCW [0,0,0] -> [1,0,0] -> [2,0,0] -> [2,2,0] -> [0,2,0]
# produces [0, 0, Area*2]. So normal [0, 0, 1].
base_plane = planes[0]
assert numpy.allclose(base_plane[0], [0, 0, 1])
assert numpy.isclose(base_plane[1], 0.0)

View file

@ -1,341 +0,0 @@
import numpy
import pytest
from numpy.testing import assert_allclose
import adze
import adze.util
from adze.boundary import planes_from_boundary
def test_boundary_from_empty_poly() -> None:
assert adze.boundary_from_poly(adze.util.build_empty()) == []
@pytest.mark.parametrize('order', [0, 1, 2, 3])
def test_empty_poly_moments_shape(order: int) -> None:
moments = adze.get_moments(adze.util.build_empty(), order)
assert moments.shape == (adze.number_of_moments(order),)
assert_allclose(moments, numpy.zeros_like(moments))
@pytest.mark.parametrize('order', [-3, -2, -1])
def test_negative_moment_order_rejected(order: int) -> None:
poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
edges = [numpy.array([0.0, 1.0]) for _ in range(3)]
with pytest.raises(adze.AdzeError, match='Moment order must be non-negative'):
adze.number_of_moments(order)
with pytest.raises(adze.AdzeError, match='Moment order must be non-negative'):
adze.get_moments(poly, order)
with pytest.raises(adze.AdzeError, match='Moment order must be non-negative'):
adze.voxelize(poly, edges, order=order)
def test_planes_from_boundary_tetrahedron() -> None:
vertices = numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
])
faces = [
[0, 1, 2],
[0, 3, 1],
[0, 2, 3],
[1, 3, 2],
]
planes = planes_from_boundary(vertices, faces)
assert len(planes) == 4
for normal, distance in planes:
assert normal.shape == (3,)
assert numpy.isscalar(distance)
assert_allclose(numpy.linalg.norm(normal), 1.0)
def test_planes_from_boundary_nontriangular_face() -> None:
vertices = numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
])
faces = [
[0, 3, 2, 1],
[0, 1, 4],
[1, 2, 4],
[2, 3, 4],
[3, 0, 4],
]
normal, distance = planes_from_boundary(vertices, faces)[0]
assert_allclose(normal, [0.0, 0.0, -1.0])
assert_allclose(distance, 0.0)
def test_planes_from_boundary_rejects_zero_area_face() -> None:
vertices = numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[2.0, 0.0, 0.0],
])
with pytest.raises(adze.AdzeError, match='non-zero area'):
planes_from_boundary(vertices, [[0, 1, 2]])
@pytest.mark.parametrize('face', [[-1, 1, 2], [0, 1, 5]])
def test_planes_from_boundary_rejects_invalid_face_index(face: list[int]) -> None:
vertices = numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
])
with pytest.raises(adze.AdzeError, match='outside the provided vertex list'):
planes_from_boundary(vertices, [face])
def test_build_polyhedron_rejects_unused_vertices() -> None:
vertices = numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
[9.0, 9.0, 9.0],
])
faces = [
[0, 1, 2],
[0, 3, 1],
[0, 2, 3],
[1, 3, 2],
]
with pytest.raises(adze.AdzeError, match='unused by any face'):
adze.build_polyhedron(vertices, faces)
def test_build_polyhedron_accepts_box_with_quadrilateral_faces() -> None:
vertices = numpy.array([
[0.0, 0.0, 0.0],
[0.0, 0.0, 1.0],
[0.0, 1.0, 0.0],
[0.0, 1.0, 1.0],
[1.0, 0.0, 0.0],
[1.0, 0.0, 1.0],
[1.0, 1.0, 0.0],
[1.0, 1.0, 1.0],
])
faces = [
[0, 4, 6, 2],
[0, 1, 5, 4],
[0, 2, 3, 1],
[4, 5, 7, 6],
[6, 7, 3, 2],
[1, 3, 7, 5],
]
poly = adze.build_polyhedron(vertices, faces)
adze.util.check_poly(poly)
assert_allclose(adze.get_volume(poly), 1.0)
assert len(adze.boundary_from_poly(poly)) == 1
def test_build_polyhedron_rejects_invalid_face_index() -> None:
vertices = numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
])
faces = [
[0, 1, 2],
[0, 3, 1],
[0, 2, 3],
[1, 3, 5],
]
with pytest.raises(adze.AdzeError, match='outside the provided vertex list'):
adze.build_polyhedron(vertices, faces)
def test_build_polyhedron_rejects_inconsistent_face_winding() -> None:
vertices = numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
])
faces = [
[0, 1, 2],
[0, 1, 3],
[0, 3, 2],
[1, 2, 3],
]
with pytest.raises(adze.AdzeError, match='duplicate neighbors'):
adze.build_polyhedron(vertices, faces)
def test_build_polyhedron_rejects_invalid_high_degree_boundary() -> None:
vertices = numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[1.0, 1.0, 0.0],
[0.5, 0.5, 1.0],
])
faces = [
[0, 1, 2, 3],
[0, 1, 4],
[1, 3, 4],
[3, 2, 4],
[2, 0, 4],
]
with pytest.raises(adze.AdzeError, match='valid closed polyhedron boundary'):
adze.build_polyhedron(vertices, faces)
def test_check_poly_rejects_row_count_mismatch() -> None:
poly = {
'vertices': numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[9.0, 9.0, 9.0],
]),
'neighbors': numpy.array([
[1, 2, 0],
[2, 0, 1],
[0, 1, 2],
], dtype=int),
}
with pytest.raises(adze.AdzeError, match='Neighbors must have shape'):
adze.util.check_poly(poly, check_connectivity=False)
def test_voxelize_requires_three_axes() -> None:
poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
with pytest.raises(adze.AdzeError, match='exactly three plane axes'):
adze.voxelize(poly, [numpy.array([0.0, 1.0]), numpy.array([0.0, 1.0])], order=0)
def test_voxelize_requires_strictly_increasing_axes() -> None:
poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
with pytest.raises(adze.AdzeError, match='strictly increasing'):
adze.voxelize(
poly,
[numpy.array([1.0, 0.0]), numpy.array([0.0, 1.0]), numpy.array([0.0, 1.0])],
order=0,
)
def test_clip_rejects_zero_normal_plane() -> None:
poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
with pytest.raises(adze.AdzeError, match='Plane normal must be non-zero'):
adze.clip(poly, (numpy.array([0.0, 0.0, 0.0]), 0.0))
@pytest.mark.parametrize('normal', [numpy.array([1.0, 0.0]), numpy.array([1.0, 0.0, 0.0, 0.0])])
def test_split_rejects_wrong_plane_normal_shape(normal: numpy.ndarray) -> None:
poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
with pytest.raises(adze.AdzeError, match='Plane normal must have shape'):
adze.split(poly, (normal, 0.0))
def test_split_rejects_non_scalar_plane_distance() -> None:
poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
with pytest.raises(adze.AdzeError, match='Plane distance must be a scalar'):
adze.split(poly, (numpy.array([1.0, 0.0, 0.0]), numpy.array([0.0, 1.0])))
def test_boundary_from_poly_rejects_invalid_graph() -> None:
poly = {
'vertices': numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
]),
'neighbors': numpy.array([
[1, 2, 3],
[2, 3, 0],
[3, 0, 1],
[0, 1, 2],
], dtype=int),
}
with pytest.raises(adze.AdzeError, match='invalid neighbor ordering'):
adze.boundary_from_poly(poly)
def test_clip_noop_returns_independent_poly() -> None:
poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
clipped = adze.clip(poly, (numpy.array([1.0, 0.0, 0.0]), 0.0))
assert clipped is not poly
assert clipped['vertices'] is not poly['vertices']
clipped['vertices'][0, 0] = 999.0
assert poly['vertices'][0, 0] == 0.0
def test_split_noop_returns_independent_poly() -> None:
poly = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
empty_poly, kept_poly = adze.split(poly, (numpy.array([1.0, 0.0, 0.0]), -2.0))
assert empty_poly['vertices'].shape == (0, 3)
assert kept_poly is not poly
assert kept_poly['vertices'] is not poly['vertices']
kept_poly['vertices'][0, 0] = 999.0
assert poly['vertices'][0, 0] == 0.0
def test_split_handles_disconnected_components_without_cut_edges() -> None:
poly_left = adze.build_box([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
poly_right = adze.build_box([[3.0, 0.0, 0.0], [4.0, 1.0, 1.0]])
poly = {
'vertices': numpy.vstack((poly_left['vertices'], poly_right['vertices'])),
'neighbors': numpy.vstack((poly_left['neighbors'], poly_right['neighbors'] + poly_left['vertices'].shape[0])),
}
split_left, split_right = adze.split(poly, (numpy.array([1.0, 0.0, 0.0]), -2.0))
adze.util.check_poly(split_left)
adze.util.check_poly(split_right)
assert_allclose(adze.get_volume(split_left), 1.0)
assert_allclose(adze.get_volume(split_right), 1.0)
@pytest.mark.parametrize('box_fun', [adze.build_box, adze.planes_from_box])
def test_box_helpers_reject_inverted_corners(box_fun) -> None:
with pytest.raises(adze.AdzeError, match='box_corners\\[0\\] < box_corners\\[1\\]'):
box_fun([[1.0, 1.0, 1.0], [0.0, 0.0, 0.0]])
@pytest.mark.parametrize('tetra_fun', [adze.build_tetrahedron, adze.planes_from_tetrahedron])
def test_tetrahedron_helpers_reject_wrong_shape(tetra_fun) -> None:
with pytest.raises(adze.AdzeError, match='shape \\(4, 3\\)'):
tetra_fun([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
@pytest.mark.parametrize('tetra_fun', [adze.build_tetrahedron, adze.planes_from_tetrahedron])
def test_tetrahedron_helpers_reject_negative_winding(tetra_fun) -> None:
with pytest.raises(adze.AdzeError, match='positive winding'):
tetra_fun([
[0.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 0.0, 1.0],
])

View file

@ -1,91 +0,0 @@
import numpy
import adze
from adze.shapes import build_box
from adze.offset import offset, smooth, closing, offset_anisotropic
def test_offset_cube_expand() -> None:
# Unit cube: [0,1]x[0,1]x[0,1], vol=1
cube = build_box([[0, 0, 0], [1, 1, 1]])
expanded = offset(cube, 0.1)
vol = adze.get_volume(expanded)
assert numpy.isclose(vol, 1.728)
vmin, vmax = adze.util.get_aabb(expanded)
assert numpy.allclose(vmin, [-0.1, -0.1, -0.1])
assert numpy.allclose(vmax, [1.1, 1.1, 1.1])
def test_offset_cube_shrink() -> None:
# Unit cube: [0,1]x[0,1]x[0,1], vol=1
cube = build_box([[0, 0, 0], [1, 1, 1]])
shrunk = offset(cube, -0.1)
vol = adze.get_volume(shrunk)
assert numpy.isclose(vol, 0.512)
vmin, vmax = adze.util.get_aabb(shrunk)
assert numpy.allclose(vmin, [0.1, 0.1, 0.1])
assert numpy.allclose(vmax, [0.9, 0.9, 0.9])
def test_offset_zero() -> None:
cube = build_box([[0, 0, 0], [1, 1, 1]])
same = offset(cube, 0.0)
assert numpy.isclose(adze.get_volume(same), 1.0)
assert numpy.allclose(cube['vertices'], same['vertices'])
def test_smooth_cube() -> None:
# Smoothing a cube should move vertices toward the center
cube = build_box([[0, 0, 0], [1, 1, 1]])
# Centroid is [0.5, 0.5, 0.5]
smoothed = smooth(cube, factor=0.1)
# Check that volume decreased (cube is rounding in)
assert adze.get_volume(smoothed) < adze.get_volume(cube)
# Check one vertex: [0,0,0]
# Neighbors of [0,0,0] are [1,0,0], [0,1,0], [0,0,1] (for a unit box)
# Average of neighbors = [1/3, 1/3, 1/3]
# New V = [0,0,0] + 0.1 * ([1/3, 1/3, 1/3] - [0,0,0]) = [1/30, 1/30, 1/30]
assert numpy.allclose(smoothed['vertices'][0], [1/30, 1/30, 1/30])
def test_closing_cube() -> None:
# Closing a cube shouldn't change it much if delta is small and cube is simple
cube = build_box([[0, 0, 0], [1, 1, 1]])
closed = closing(cube, 0.1, cleanup=True)
# For a perfect cube, offset(0.1) then offset(-0.1) should return to original
assert numpy.isclose(adze.get_volume(closed), 1.0, atol=1e-7)
def test_anisotropic_etch() -> None:
# Unit cube [0,1]^3
cube = build_box([[0, 0, 0], [1, 1, 1]])
# Define an etch rate function:
# Fast vertical etch (-0.2), slow horizontal etch (-0.05)
# Note: Normals are inward facing for adze clipping convention?
# Wait, planes_from_box in shapes.py returns normals like (0,0,1) for z=0 face.
# Let's verify normal direction with a quick check if needed, but standard logic:
# offset uses inward normals. A negative return value from rate_func shrinks.
def vertical_etch_rate(normal: numpy.ndarray) -> float:
# Check if normal is primarily vertical (z-axis)
if abs(normal[2]) > 0.9:
return -0.2
return -0.05
etched = offset_anisotropic(cube, vertical_etch_rate)
# Expected bounds:
# Z: [0,1] -> [0.2, 0.8] (shrunk by 0.2 on both top and bottom) -> height 0.6
# X, Y: [0,1] -> [0.05, 0.95] (shrunk by 0.05 on sides) -> width 0.9
vmin, vmax = adze.util.get_aabb(etched)
assert numpy.allclose(vmin, [0.05, 0.05, 0.2])
assert numpy.allclose(vmax, [0.95, 0.95, 0.8])
# Volume = 0.9 * 0.9 * 0.6 = 0.486
assert numpy.isclose(adze.get_volume(etched), 0.486)

View file

@ -1,300 +0,0 @@
from collections.abc import Callable
import warnings
import logging
import pytest
import numpy
from numpy.typing import NDArray
from numpy import floating
from numpy.linalg import norm
from numpy.testing import assert_allclose
import adze
import adze.util
from .utils import TOL_FAIL, TOL_WARN, PRNG, MIN_VOLUME, flip_plane, tetrahedron_volume
from .utils import build_rand_tetrahedron, gen_plane_through_centroid, plane_generators, gen_torus_brep
logger = logging.getLogger(__name__)
def test_manual_tetrahedron(poly_order: int) -> None:
tet = adze.build_tetrahedron([
[0,0,0],
[2,0,0],
[0,2,0],
[0,0,2]])
volume = tetrahedron_volume(tet['vertices'])
logger.debug(f'Splitting manual tetrahedron {tet}')
logger.debug(f'volume {volume}')
plane = numpy.array((-1, 0, 0)), 1
p_left, p_right = adze.split(tet, plane)
logger.debug(f'left {p_left}')
logger.debug(f'right {p_right}')
adze.util.check_poly(tet)
adze.util.check_poly(p_left)
adze.util.check_poly(p_right)
m0 = adze.get_moments(tet, 0)
ml = adze.get_moments(p_left, 0)
mr = adze.get_moments(p_right, 0)
logger.debug(f'0th moments: tot {m0[0]}, left {ml[0]}, right {mr[0]}')
assert m0 == pytest.approx(volume, abs=TOL_FAIL)
check_split_moments(tet, p_left, p_right, poly_order)
def test_manual_pyramid(poly_order: int) -> None:
vertices = numpy.array([
[0, 0, 1],
[1, 1, 0],
[1, -1, 0],
[-1, -1, 0],
[-1, 1, 0],
])
faces = [
[0, 1, 2],
[0, 2, 3],
[0, 3, 4],
[0, 4, 1],
[4, 3, 2, 1],
]
# initialize a general polyhedron
poly = adze.build_polyhedron(vertices, faces) # type: ignore # (mypy error?)
adze.util.check_poly(poly)
brep = adze.boundary_from_poly(poly)
logger.info(f'Round-trip converted pyramid: {brep}')
#adze.util.plot_brep(brep)
stack_split(poly, poly_order)
def test_tetrahedrons_through_centroid(poly_order: int) -> None:
"""
Splits some tetrahedrons through their centroids and
checks if each two resulting volumes sum to the original
"""
# Generate random tetrahedrons and clip planes
ntets = 100
polys = [build_rand_tetrahedron() for _ in range(ntets)]
plane = gen_plane_through_centroid(polys[ntets//7])
# split them all with the same plane
poly12 = [adze.split(p, plane) for p in polys]
poly1, poly2 = zip(*poly12, strict=True)
for orig, p1, p2 in zip(polys, poly1, poly2, strict=True):
adze.util.check_poly(orig)
adze.util.check_poly(p1)
adze.util.check_poly(p2)
check_split_moments(orig, p1, p2, poly_order)
def test_manual_nonconvex(poly_order: int, n_zigs: int = 3, z_offset: float = 0.1) -> None:
"""
Splits a non-convex polyhedron and checks if the resulting
volumes add up to the original
"""
# manually create a non-convex polyhedron
num_verts = 4 * n_zigs
vertices = numpy.empty((num_verts, 3), dtype=float)
neighbors = numpy.empty((num_verts, 3), dtype=int)
for v in range(n_zigs):
m = n_zigs - v - 1
v0 = numpy.array([v, v % 2 + z_offset, 0])
v1 = numpy.array([m, m % 2, 0])
vertices[v + 0 * n_zigs] = v0
vertices[v + 1 * n_zigs] = v1
vertices[v + 2 * n_zigs] = v0 + (0, 0, 1)
vertices[v + 3 * n_zigs] = v1 + (0, 0, 1)
nz2 = 2 * n_zigs
for v in range(nz2):
neighbors[v] = ((v + 1) % nz2,
(v - 1) % nz2,
v + nz2)
neighbors[v + nz2] = neighbors[v][[1, 0, 2]] + (nz2, nz2, -nz2)
poly = {
'vertices': vertices,
'neighbors': neighbors,
}
logger.debug("Checking poly...")
adze.util.check_poly(poly)
logger.debug("poly is valid.")
#
# Perform splits along three axes
#
def split_and_check(poly: adze.poly_t, plane: adze.plane_t, poly_order: int = 0) -> None:
poly_l = adze.clip(poly, plane)
poly_r = adze.clip(poly, flip_plane(plane))
check_split_moments(poly, poly_l, poly_r, poly_order)
# split along the x-axis (two single connected components)
split_and_check(poly, (numpy.array((1, 0, 0)), -0.5 * (n_zigs - 1)), poly_order)
# split along the z-axis (two single connected components)
split_and_check(poly, (numpy.array((0, 0, 1)), -0.5), poly_order)
# split along the y-axis (multiple connected components)
split_and_check(poly, (numpy.array((0, 1, 0)), -0.5 * (1.0 + z_offset)), poly_order)
def test_clip_with_atol() -> None:
"""
Verify that atol correctly handles vertices very close to the plane.
"""
# Unit tetrahedron
tet = adze.build_tetrahedron([
[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
# Plane x = 0 (keeping x > 0)
plane = (numpy.array([1, 0, 0]), 0)
# Move one vertex slightly to x = -1e-13
tet['vertices'][0, 0] = -1e-13
# Without atol (default 1e-12), it should still keep the whole thing
# because -1e-13 > -1e-12.
clipped = adze.clip(tet, plane, atol=1e-12)
assert_allclose(adze.get_volume(tet), adze.get_volume(clipped))
# With a very small atol, it might clip it
clipped_small = adze.clip(tet, plane, atol=1e-15)
assert adze.get_volume(clipped_small) < adze.get_volume(tet)
def test_torus(poly_order: int) -> None:
"""
Recursively split a torus with random degenerate cut planes until the pieces
are smaller than `MIN_VOLUME`, then check that the moments add up properly.
This checks `build_polyhedron()` with for >3 edges per vertex and non-convex
geometry.
"""
vertices, faces = gen_torus_brep(n_theta=20, n_phi=20, r0=1.0, r1=0.1)
# Shift center away from the origin, to avoid 0-valued moments
vertices += (0.5, 0.7, 0.9)
opoly = adze.build_polyhedron(vertices, faces)
# adze.util.check_poly(opoly)
brep = adze.boundary_from_poly(opoly)
logger.debug(f'Round-trip converted torus: {brep}')
#adze.util.plot_brep(brep)
stack_split(opoly, poly_order)
def test_recursive(poly_order: int, num_trials: int = 10, max_depth: int = 6) -> None:
"""
Starting with a tetrahedron, recusively split until the pieces
are smaller than `MIN_VOLUME` or have been split more than `max_depth` times,
then check that the moments add up as expected.
"""
logger.info(f'Recursively splitting {num_trials} tetrahedra, maximum depth {max_depth}:')
logger.info(' - Through centroid')
for _ in range(num_trials):
stack_split(build_rand_tetrahedron(), poly_order, plane_fun=gen_plane_through_centroid, max_depth=max_depth)
logger.info(' - Through degenerate plane')
for _ in range(num_trials):
stack_split(build_rand_tetrahedron(), poly_order, max_depth=max_depth)
logger.info(' - Through perturbed plane')
for t in range(num_trials):
perturb = 10 ** -(1 + t % 16)
stack_split(build_rand_tetrahedron(), poly_order, perturb=perturb, max_depth=max_depth)
def check_split_moments(
original_poly: adze.poly_t,
left_poly: adze.poly_t,
right_poly: adze.poly_t,
poly_order: int = 0,
) -> tuple[NDArray[floating], NDArray[floating], NDArray[floating]]:
m0, ml, mr = (adze.get_moments(x, poly_order) for x in (original_poly, left_poly, right_poly))
logger.debug(f'Check: original {m0[0]} parts {(ml[0], mr[0])} sum {ml[0] + mr[0]}')
# Make sure each part is smaller than the whole
if not ml[0] < m0[0] * (1.0 + TOL_WARN):
warnings.warn('ml[0] < m0[0]', stacklevel=1)
assert(ml[0] < m0[0] * (1.0 + TOL_FAIL))
if not mr[0] < m0[0] * (1.0 + TOL_WARN):
warnings.warn('mr[0] < m0[0]', stacklevel=1)
assert(mr[0] < m0[0] * (1.0 + TOL_FAIL))
# make sure the sum of moments equals the original
mtot = ml + mr
assert_allclose(m0, mtot, atol=TOL_FAIL)
# if not numpy.all(diff < TOL_FAIL):
# logger.error(f'diff failed: {diff} \n original {m0} \n left {ml} \n right {mr}')
# assert(False)
if not numpy.allclose(m0, mtot, atol=TOL_WARN):
warnings.warn('Moments outside tolerance', stacklevel=1)
return m0, ml, mr
def stack_split(
poly: adze.poly_t,
poly_order: int,
plane_fun: Callable | None = None,
perturb: float = 0,
max_depth: int = 10,
) -> None:
stack = [(poly, 0)]
i = 0
while stack:
i += 1
poly, depth = stack.pop()
# pick a plane
if plane_fun is None:
pfun_used = PRNG.choice(plane_generators) # type: ignore
plane = pfun_used(poly)
while norm(plane[0]) == 0:
pfun_used = PRNG.choice(plane_generators) # type: ignore
plane = pfun_used(poly)
plane = list(plane)
logger.debug(f'used {pfun_used}')
else:
plane = list(plane_fun(poly))
# perturb the plane
plane[0] *= 1 + perturb * (PRNG.rand() - 0.5)
plane[1] *= 1 + perturb * (PRNG.rand() - 0.5)
# split the poly
poly_l = adze.clip(poly, tuple(plane))
poly_r = adze.clip(poly, flip_plane(tuple(plane)))
m0, ml, mr = check_split_moments(poly, poly_l, poly_r, poly_order)
logger.debug(f'nstack = {len(stack)}, depth = {depth}, '
f'opoly = {m0[0]:.10e}, p1 = {ml[0]:.10e}, p2 = {mr[0]:.10e}, '
f'err = {abs(1.0 - m0[0]/(ml[0] + mr[0])):.10e}')
# add the children to the stack if they are big enough
if depth < max_depth:
if ml[0] > MIN_VOLUME:
stack.append((poly_l, depth + 1))
if mr[0] > MIN_VOLUME:
stack.append((poly_r, depth + 1))
if i % 300 == 0:
logger.info(f'Stack split iter {i} length {len(stack)} depth {depth}')

View file

@ -1,178 +0,0 @@
import numpy
import pytest
from numpy.testing import assert_allclose
import adze
import adze.transform
def test_rotate_x_quarter_turn() -> None:
poly = {
'vertices': numpy.array([[0.0, 1.0, 0.0]]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
rotated = adze.transform.rotate(poly, numpy.pi / 2, axis=0)
assert_allclose(rotated['vertices'], [[0.0, 0.0, 1.0]], atol=1e-12)
def test_rotate_y_quarter_turn() -> None:
poly = {
'vertices': numpy.array([[0.0, 0.0, 1.0]]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
rotated = adze.transform.rotate(poly, numpy.pi / 2, axis=1)
assert_allclose(rotated['vertices'], [[1.0, 0.0, 0.0]], atol=1e-12)
def test_rotate_z_quarter_turn() -> None:
poly = {
'vertices': numpy.array([[1.0, 0.0, 0.0]]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
rotated = adze.transform.rotate(poly, numpy.pi / 2, axis=2)
assert_allclose(rotated['vertices'], [[0.0, 1.0, 0.0]], atol=1e-12)
def test_rotate_promotes_integer_vertices_to_float() -> None:
poly = {
'vertices': numpy.array([[1, 0, 0]], dtype=int),
'neighbors': numpy.empty((0, 3), dtype=int),
}
rotated = adze.transform.rotate(poly, numpy.pi / 4, axis=2)
assert numpy.issubdtype(rotated['vertices'].dtype, numpy.floating)
assert_allclose(rotated['vertices'], [[numpy.sqrt(0.5), numpy.sqrt(0.5), 0.0]], atol=1e-12)
@pytest.mark.parametrize('axis', [-1, 3, 4])
def test_rotate_rejects_invalid_axis(axis: int) -> None:
poly = {
'vertices': numpy.array([[1.0, 2.0, 3.0]]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
with pytest.raises(adze.AdzeError, match='Axis must be 0, 1, or 2'):
adze.transform.rotate(poly, numpy.pi / 2, axis=axis)
def test_affine_requires_4x4_matrix() -> None:
poly = {
'vertices': numpy.array([[1.0, 2.0, 3.0]]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
with pytest.raises(adze.AdzeError, match='shape \\(4, 4\\)'):
adze.transform.affine(poly, numpy.eye(3))
def test_affine_rejects_zero_homogeneous_coordinate() -> None:
poly = {
'vertices': numpy.array([[1.0, 2.0, 3.0]]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
xform = numpy.array([
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
])
with pytest.raises(adze.AdzeError, match='zero homogeneous coordinate'):
adze.transform.affine(poly, xform)
def test_affine_identity_preserves_multiple_vertices() -> None:
poly = {
'vertices': numpy.array([
[1.0, 0.0, 0.0],
[2.0, 1.0, 0.0],
]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
transformed = adze.transform.affine(poly, numpy.eye(4))
assert_allclose(transformed['vertices'], [[1.0, 0.0, 0.0], [2.0, 1.0, 0.0]])
def test_affine_translation_applies_to_multiple_vertices() -> None:
poly = {
'vertices': numpy.array([
[1.0, 0.0, 0.0],
[2.0, 1.0, 0.0],
]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
xform = numpy.array([
[1.0, 0.0, 0.0, 1.0],
[0.0, 1.0, 0.0, 2.0],
[0.0, 0.0, 1.0, 3.0],
[0.0, 0.0, 0.0, 1.0],
])
transformed = adze.transform.affine(poly, xform)
assert_allclose(transformed['vertices'], [[2.0, 2.0, 3.0], [3.0, 3.0, 3.0]])
def test_affine_promotes_integer_vertices_to_float() -> None:
poly = {
'vertices': numpy.array([[1, 1, 1]], dtype=int),
'neighbors': numpy.empty((0, 3), dtype=int),
}
xform = numpy.array([
[1.0, 0.0, 0.0, 0.5],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
transformed = adze.transform.affine(poly, xform)
assert numpy.issubdtype(transformed['vertices'].dtype, numpy.floating)
assert_allclose(transformed['vertices'], [[1.5, 1.0, 1.0]])
def test_translate_promotes_integer_vertices_to_float() -> None:
poly = {
'vertices': numpy.array([[1, 0, 0]], dtype=int),
'neighbors': numpy.empty((0, 3), dtype=int),
}
transformed = adze.transform.translate(poly, [0.5, 1.0, 0.0])
assert numpy.issubdtype(transformed['vertices'].dtype, numpy.floating)
assert_allclose(transformed['vertices'], [[1.5, 1.0, 0.0]])
def test_scale_promotes_integer_vertices_to_float() -> None:
poly = {
'vertices': numpy.array([[1, 1, 1]], dtype=int),
'neighbors': numpy.empty((0, 3), dtype=int),
}
transformed = adze.transform.scale(poly, 0.5)
assert numpy.issubdtype(transformed['vertices'].dtype, numpy.floating)
assert_allclose(transformed['vertices'], [[0.5, 0.5, 0.5]])
@pytest.mark.parametrize('shift', [[1.0, 2.0], [1.0, 2.0, 3.0, 4.0]])
def test_translate_rejects_invalid_shift_shape(shift: list[float]) -> None:
poly = {
'vertices': numpy.array([[1.0, 0.0, 0.0]]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
with pytest.raises(adze.AdzeError, match='Shift must have shape'):
adze.transform.translate(poly, shift)
@pytest.mark.parametrize('factor', [[1.0, 2.0], [1.0, 2.0, 3.0, 4.0]])
def test_scale_rejects_invalid_factor_shape(factor: list[float]) -> None:
poly = {
'vertices': numpy.array([[1.0, 0.0, 0.0]]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
with pytest.raises(adze.AdzeError, match='Scale factor must be a scalar or have shape'):
adze.transform.scale(poly, factor)

View file

@ -1,115 +0,0 @@
from typing import TYPE_CHECKING
import logging
import warnings
from time import perf_counter
import numpy
from numpy.typing import NDArray
from numpy.testing import assert_allclose
import adze
import adze.util
from .utils import TOL_FAIL, TOL_WARN, rand_tetrahedron_vertices
#from .utils import PRNG, MIN_VOLUME, flip_plane, tetrahedron_volume
#from .utils import build_rand_tetrahedron, gen_plane_through_centroid, plane_generators, gen_torus_brep
if TYPE_CHECKING:
import matplotlib
logger = logging.getLogger(__name__)
def test_voxelization(poly_order: int, grid_resolution: int | None = None) -> None:
"""
Test that the voxelized moments sum to those of the original input
"""
if grid_resolution is None:
grid_resolution = 250 if poly_order == 0 else 50
verts = 1.5 * (numpy.array(rand_tetrahedron_vertices()) + 1)
poly = adze.build_tetrahedron(verts)
moments = adze.get_moments(poly, poly_order)
edges = [numpy.linspace(-1, 3, grid_resolution) for _ in range(3)]
logger.info(f'Voxelizing a tetrahedron to a grid with moments of order {poly_order}')
t0 = perf_counter()
grid = adze.voxelize(poly, edges, order=poly_order)
logger.info(f'voxel time: {perf_counter() - t0}')
#visualize_isosurface(grid[:, :, :, 0], edges)
voxsum = numpy.sum(grid, axis=(0, 1, 2))
assert_allclose(moments, voxsum, atol=TOL_FAIL)
if not numpy.allclose(moments, voxsum, atol=TOL_WARN):
warnings.warn('Moments failed tolerance in voxels', stacklevel=1)
def test_voxelization_include_outside_keeps_axis_assignment() -> None:
poly = adze.build_box([[-1, 0, 0], [2, 1, 1]])
edges = [numpy.array([0.0, 1.0]) for _ in range(3)]
grid = adze.voxelize(poly, edges, include_outside=True, order=0)
voxels = grid[..., 0]
assert voxels.shape == (3, 3, 3)
assert_allclose(voxels.sum(axis=(1, 2)), [1.0, 1.0, 1.0])
assert_allclose(voxels.sum(axis=(0, 2)), [0.0, 3.0, 0.0])
assert_allclose(voxels.sum(axis=(0, 1)), [0.0, 3.0, 0.0])
def visualize_isosurface(
grid: NDArray[numpy.float64],
edges: NDArray[numpy.int64],
level: float | None = None,
show_edges: bool = True,
finalize: bool = True,
) -> tuple['matplotlib.figure.Figure', 'matplotlib.axes.Axes']:
"""
Draw an isosurface plot of the device.
Args:
level: Value at which to find isosurface. Default (None) uses mean value in grid.
show_edges: Whether to draw triangle edges. Default True
finalize: Whether to call pyplot.show() after constructing the plot. Default True
"""
from matplotlib import pyplot
import skimage.measure
# Claims to be unused, but needed for subplot(projection='3d')
from mpl_toolkits.mplot3d import Axes3D
del Axes3D # imported for side-effects only
if level is None:
level = grid.mean()
# Find isosurface with marching cubes
verts, faces, _normals, _values = skimage.measure.marching_cubes(grid, level)
xs, ys, zs = (edges[aa][verts[:, aa].astype(int)] for aa in range(3))
# Draw the plot
fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')
if show_edges:
ax.plot_trisurf(xs, ys, faces, zs)
else:
ax.plot_trisurf(xs, ys, faces, zs, edgecolor='none')
# Add a fake plot of a cube to force the axes to be equal lengths
max_range = numpy.array([xs.max() - xs.min(),
ys.max() - ys.min(),
zs.max() - zs.min()], dtype=float).max()
mg = numpy.mgrid[-1:2:2, -1:2:2, -1:2:2]
xbs = 0.5 * max_range * mg[0].flatten() + 0.5 * (xs.max() + xs.min())
ybs = 0.5 * max_range * mg[1].flatten() + 0.5 * (ys.max() + ys.min())
zbs = 0.5 * max_range * mg[2].flatten() + 0.5 * (zs.max() + zs.min())
# Comment or uncomment following both lines to test the fake bounding box:
for xb, yb, zb in zip(xbs, ybs, zbs, strict=True):
ax.plot([xb], [yb], [zb], 'w')
if finalize:
pyplot.show()
return fig, ax

Some files were not shown because too many files have changed in this diff Show more