From 37f705db21bc8c96951d3ab481f8d1a202058014 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Fri, 30 Aug 2019 22:28:00 -0700 Subject: [PATCH 01/69] minor comment updates --- adze/__init__.py | 3 +-- adze/boundary.py | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/adze/__init__.py b/adze/__init__.py index e45d3d7..afffb3e 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -47,8 +47,7 @@ In the polyhedron representation returned by the build_* functions and accepted TODO - This - representation looks like + This representation looks like poly = {'neighbors': ndarray[Px3, int], 'vertices': ndarray[Px3, float]} where poly['neighbors'] contains diff --git a/adze/boundary.py b/adze/boundary.py index e9e283f..84205db 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -41,8 +41,8 @@ def planes_from_boundary(vertices: numpy.ndarray, @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. + Generate a 3-verted-connected Schlegel diagram representation + corresponding to the provided boundary-representation polyhedron. :param vertices: Nx3 ndarray specifying the polyhedron's vertex positions. :param faces: List of 1d ndarrays. Each ndarray is a list of vertex indices, From e497895ae3fbdbd6986ef52f1c38a2b8a3cee4c4 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 15 Mar 2020 22:17:05 -0700 Subject: [PATCH 02/69] fix deprecated use of generator as index --- adze/shapes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adze/shapes.py b/adze/shapes.py index 3b7817c..05d0c5e 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -93,7 +93,7 @@ def planes_from_tetrahedron(vertices: numpy.ndarray) -> List[plane_t]: [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, :] From ad4ee12b1c26abe6aec50385f6fedd101f9d7654 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 15 Mar 2020 22:17:29 -0700 Subject: [PATCH 03/69] add some util functions for dealing with boundary representations --- adze/util.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/adze/util.py b/adze/util.py index c7c14b7..ee179b8 100644 --- a/adze/util.py +++ b/adze/util.py @@ -270,3 +270,46 @@ def check_poly(poly: poly_t, check_connectivity: bool = True): # Make sure we touched all vertices in the component if not visited[components == part_id].all(): raise Exception('Vertex graph is not 3-vertex-connected') + + +def plot_brep(brep): + """ + Plot a boundary representation + """ + from matplotlib import pyplot + from mpl_toolkits import mplot3d + + meshes = brep_to_stls(brep) + + figure = pyplot.figure() + axes = mplot3d.Axes3D(figure) + scales = [] + for mesh in meshes: + coll = mplot3d.art3d.Poly3DCollection(mesh.vectors) + coll.set_edgecolors('black') + axes.add_collection3d(coll) + scales.append(mesh.points.flatten()) + scale = numpy.hstack(scales) + axes.auto_scale_xyz(scale, scale, scale) + pyplot.show() + + +def brep_to_stls(brep): + import stl + + meshes = [] + for component in brep: + triangles = [] + for face in component['faces']: + for i in range(1, len(face) - 1): + triangles.append([face[0], face[i], face[i+1]]) + triangles = numpy.array(triangles, dtype=int) + + m = stl.mesh.Mesh(numpy.empty(triangles.shape[0], dtype=stl.mesh.Mesh.dtype)) + for i, f in enumerate(triangles): + for j in range(3): + m.vectors[i, j] = component['vertices'][f[j], :] + +# m.save('pyr.stl') + meshes.append(m) + return meshes From c1442960b2afd1b75b4c9e35e79ba00bf139bf13 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 15 Mar 2020 22:18:02 -0700 Subject: [PATCH 04/69] Use pytest for tests --- adze/test/__init__.py | 3 + adze/test/benchmark.py | 92 +++++++ adze/test/conftest.py | 6 + adze/test/test_split.py | 255 ++++++++++++++++++ adze/test/test_voxel.py | 90 +++++++ adze/test/utils.py | 179 +++++++++++++ adze/test_results.txt | 129 ++++++++++ tpy_r3d.py | 558 ---------------------------------------- 8 files changed, 754 insertions(+), 558 deletions(-) create mode 100644 adze/test/__init__.py create mode 100644 adze/test/benchmark.py create mode 100644 adze/test/conftest.py create mode 100644 adze/test/test_split.py create mode 100644 adze/test/test_voxel.py create mode 100644 adze/test/utils.py create mode 100644 adze/test_results.txt delete mode 100644 tpy_r3d.py diff --git a/adze/test/__init__.py b/adze/test/__init__.py new file mode 100644 index 0000000..e02b636 --- /dev/null +++ b/adze/test/__init__.py @@ -0,0 +1,3 @@ +""" +Tests (run with `python3 -m pytest -rxPXs | tee results.txt`) +""" diff --git a/adze/test/benchmark.py b/adze/test/benchmark.py new file mode 100644 index 0000000..9db34be --- /dev/null +++ b/adze/test/benchmark.py @@ -0,0 +1,92 @@ +""" +Benchmarking, run with `python3 -m adze.test.benchmark` + +TODO: Consider using pytest-benchmark? +""" +import warnings +from time import perf_counter +import random +import logging + +import numpy +from numpy import sin, cos, pi +from numpy.linalg import norm + +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, plane_generators, rand_tetrahedron_vertices + + +logger = logging.getLogger(__name__) + + +try: + # Check if running with line_profiler + profile +except NameError: + def profile(f): + return f + + +@profile +def time_split(): + NUM_TRIALS = 10_000 + logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') + polys = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)] + facesets = [adze.planes_from_tetrahedron(rand_tetrahedron_vertices()) for _ in range(NUM_TRIALS)] + t0 = perf_counter() + for t in range(NUM_TRIALS): + # clip the first tet against the faces of the second + for face in facesets[t]: + polys[t] = adze.clip(polys[t], face) + if (t + 1) % (NUM_TRIALS // 10) == 0: + t_each = (perf_counter() - t0) / (t + 1) + logger.info(f'time per split for {t+1} splits: {t_each}') + logger.info(f'done timing, time per split: {(perf_counter() - t0) / NUM_TRIALS}') + + polys_bulk = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)] + bulk = { + 'vertices': numpy.vstack([p['vertices'] for p in polys_bulk]), + 'neighbors': numpy.vstack([p['neighbors'] for p in polys_bulk]) + numpy.arange(NUM_TRIALS).repeat(4)[:, None] * 4, + } + t1 = perf_counter() + poly = adze.clip(bulk, facesets[0][0]) + logger.info(f'bulked split time per tet: {(perf_counter() - t1) / NUM_TRIALS}') + + +@profile +def time_intersection(poly_order=0): + """ + Benchmark intersection between pairs of tetrahedra + """ + NUM_TRIALS = 1000 + + t0 = perf_counter() + logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') + for t in range(NUM_TRIALS): + poly = build_rand_tetrahedron() + faces = adze.planes_from_tetrahedron(rand_tetrahedron_vertices()) + + # 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) + + if (t+1) % 10000 == 0: + t_each = (perf_counter() - t0) / (t + 1) + logger.info(f'time per split+get_moments for {t+1} iterations: {t_each}') + logger.info(f'done timing, time per split+get_moments: {(perf_counter() - t0) / NUM_TRIALS}') + + +if __name__ == '__main__': + logging.basicConfig(level=logging.INFO) + + logger.info('time_intersection') + time_intersection() + + logger.info('time_split') + time_split() diff --git a/adze/test/conftest.py b/adze/test/conftest.py new file mode 100644 index 0000000..195ab5f --- /dev/null +++ b/adze/test/conftest.py @@ -0,0 +1,6 @@ +import pytest + + +@pytest.fixture(scope='module', params=[0, 1, 2]) +def poly_order(request): + yield request.param diff --git a/adze/test/test_split.py b/adze/test/test_split.py new file mode 100644 index 0000000..3e8b197 --- /dev/null +++ b/adze/test/test_split.py @@ -0,0 +1,255 @@ +import logging +import pytest +from pytest import approx +import numpy +from numpy.linalg import norm +from numpy.testing import assert_allclose, assert_array_equal + +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): + 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}, left {ml}, right {mr}') + assert m0 == approx(volume, abs=TOL_FAIL) + check_split_moments(tet, p_left, p_right, poly_order) + + +def test_manual_pyramid(poly_order): + 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) + 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): + """ + 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) + + for orig, p1, p2 in zip(polys, poly1, poly2): + 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, n_zigs=3, z_offset=0.1): + """ + 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, plane, poly_order=0): + poly_l = adze.clip(poly, plane) + poly_r = adze.clip(poly, flip_plane(plane)) + check_split_moments(poly, poly_l, poly_r) + + # 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_torus(poly_order): + """ + 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, num_trials: int = 10, max_depth: int = 6): + ''' + 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(f' - 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(f' - Through degenerate plane') + for _ in range(num_trials): + stack_split(build_rand_tetrahedron(), poly_order, max_depth=max_depth) + + logger.info(f' - Through perturbed plane') + for t in range(num_trials): + perturb = 10 ** -(1 + t % 16) + stack_split(build_rand_tetrahedron(), poly_order, perturb=perturb, max_depth=max_depth) + + +def check_split_moments(original_poly, left_poly, right_poly, poly_order=0): + 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]') + assert(ml[0] < m0[0] * (1.0 + TOL_FAIL)) + if not mr[0] < m0[0] * (1.0 + TOL_WARN): + warnings.warn('mr[0] < m0[0]') + assert(mr[0] < m0[0] * (1.0 + TOL_FAIL)) + + # make sure the sum of moments equals the original + 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') + + return m0, ml, mr + + +def stack_split(poly, poly_order, plane_fun=None, perturb=0, max_depth=10): + stack = [(poly, 0)] + + i = 0 + while stack: + i += 1 + poly, depth = stack.pop() + + # pick a plane + if plane_fun is None: + pfun_used = PRNG.choice(plane_generators) + plane = pfun_used(poly) + while norm(plane[0]) == 0: + pfun_used = PRNG.choice(plane_generators) + 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, plane) + poly_r = adze.clip(poly, flip_plane(plane)) + m0, ml, mr = check_split_moments(poly, poly_l, poly_r, poly_order) + + logger.debug(f'nstack = {len(stack)}, depth = {depth}, ' + f'opoly = {m0[0]:.10e}, p1 = {ml[0]:.10e}, p2 = {mr[0]:.10e}, ' + f'err = {abs(1.0 - m0[0]/(ml[0] + mr[0])):.10e}') + + # add the children to the stack if they are big enough + if depth < max_depth: + if ml[0] > MIN_VOLUME: + stack.append((poly_l, depth + 1)) + if mr[0] > MIN_VOLUME: + stack.append((poly_r, depth + 1)) + if i % 300 == 0: + logger.info(f'Stack split iter {i} length {len(stack)} depth {depth}') diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py new file mode 100644 index 0000000..e876428 --- /dev/null +++ b/adze/test/test_voxel.py @@ -0,0 +1,90 @@ +import logging +import pytest +from pytest import approx +import numpy +from numpy.linalg import norm +from numpy.testing import assert_allclose, assert_array_equal +from time import perf_counter + +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, rand_tetrahedron_vertices + + +logger = logging.getLogger(__name__) + + +def test_voxelization(poly_order, grid_resolution=250): + """ + Test that the voxelized moments sum to those of the original input + """ + 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') + + +def visualize_isosurface(grid, + edges, + level: float = None, + show_edges: bool = True, + finalize: bool = True): + """ + Draw an isosurface plot of the device. + + :param level: Value at which to find isosurface. Default (None) uses mean value in grid. + :param show_edges: Whether to draw triangle edges. Default True + :param 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 + + if level is None: + level = grid.mean() + + # Find isosurface with marching cubes + verts, faces, _normals, _values = skimage.measure.marching_cubes_lewiner(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): + ax.plot([xb], [yb], [zb], 'w') + + if finalize: + pyplot.show() + + return fig, ax diff --git a/adze/test/utils.py b/adze/test/utils.py new file mode 100644 index 0000000..f99c9f0 --- /dev/null +++ b/adze/test/utils.py @@ -0,0 +1,179 @@ +import numpy +from numpy import pi, cos, sin +from numpy.linalg import norm +import random + +import adze + + +PRNG = numpy.random.RandomState(12345) +PRNG_PYRANDOM = random.Random(12345) + + +# numerical tolerances for pass/warn/fail tests +TOL_WARN = 1e-8 +TOL_FAIL = 1e-4 + +# minimum volume allowed for test polyhedra +MIN_VOLUME = 1e-8 + +# order of polynomial integration for all tests +POLY_ORDER = 0 + + +def gen_torus_brep(n_theta=20, n_phi=20, r0=1.0, r1=0.1): + """ + Generate a boundary representation for an elliptical torus + """ + # Generate vertices + theta, phi = numpy.meshgrid( + numpy.linspace(0, 2*pi, n_theta, endpoint=False), + numpy.linspace(0, 2*pi, n_phi, endpoint=False), + ) + theta = theta.ravel(order='F') + phi = phi.ravel(order='F') + + vertices = numpy.column_stack(( + (r0 + r1 * cos(theta)) * cos(phi), + (r0 + r1 * cos(theta)) * sin(phi), + r1 * sin(theta), + )) + + # Generate faces + i, j = numpy.meshgrid(numpy.arange(n_phi), numpy.arange(n_theta), indexing='ij') + + a = i * n_theta + j + b = ((i + 1) % n_phi) * n_theta + c = (j + 1) % n_theta + + aa = numpy.hstack((a, a)).ravel() + bb = numpy.hstack((b + j, b + c)).ravel() + cc = numpy.hstack((b + c, c + i * n_theta)).ravel() + + faces = numpy.column_stack((aa, bb, cc)) + + return vertices, faces + + +def tetrahedron_volume(vertices): + ad, bd, cd = vertices[0:3] - vertices[3] + return -ad @ numpy.cross(bd, cd) / 6 + + +def flip_plane(plane): + return (-plane[0], -plane[1]) + + +def rand_tetrahedron_vertices(min_volume: float = MIN_VOLUME): + # generates a random tetrahedron with vertices on the unit sphere, + # guaranteeing a volume of at least min_volume + volume = 0 + while volume < min_volume: + verts = [rand_unit_vector() for _ in range(4)] + volume = tetrahedron_volume(verts) + if volume < 0: + verts[2], verts[3] = verts[3], verts[2] + volume = -volume + return verts + + +def build_rand_tetrahedron(min_volume: float = MIN_VOLUME): + return adze.build_tetrahedron(rand_tetrahedron_vertices()) + + +def rand_unit_vector(): + # generates a random, isotropically distributed unit vector + s = 0 + while s == 0: + v = PRNG.randn(3) + s = norm(v) + return v / s + + +def get_centroid(poly): + """ + Average the vertices to get the centroid + """ + centroid = numpy.sum(poly['vertices'], axis=0) / poly['vertices'].shape[0] + return centroid + + +def gen_plane_through_centroid(poly): + """ + Generate a randomly-oriented plane passing through the polyhedron's centroid + """ + centroid = get_centroid(poly) + n = rand_unit_vector() + d = -n @ centroid + return n, d + + +def gen_plane_from_face(poly): + """ + Generate a plane coplanar with one of the polyhedron's faces + """ + # make a plane coplanar with a face of the poly + v0 = PRNG.randint(poly['vertices'].shape[0]) + v1, v2 = PRNG_PYRANDOM.sample(list(poly['neighbors'][v0]), 2) + points = (poly['vertices'][vi] for vi in (v0, v1, v2)) + return gen_plane_through_points(*points) + + +def gen_plane_through_centroid_and_edge(poly): + """ + Generate a plane through an edge of the polyhedron and the polyhedron's centroid + """ + v0 = PRNG.randint(poly['vertices'].shape[0]) + v1 = PRNG.choice(poly['neighbors'][v0]) + p0 = poly['vertices'][v0] + p1 = poly['vertices'][v1] + centroid = get_centroid(poly) + return gen_plane_through_points(p0, p1, centroid) + + +def gen_plane_through_edge(poly): + """ + Generate a plane through an edge of the polyhedron, but otherwise randomly oriented + """ + v0 = PRNG.randint(poly['vertices'].shape[0]) + v1 = PRNG.choice(poly['neighbors'][v0]) + p0 = poly['vertices'][v0] + p1 = poly['vertices'][v1] + return gen_plane_through_points(p0, p1, rand_unit_vector()) + + +def gen_plane_through_centroid_and_vertex(poly): + """ + Generate a plane through a vertex and the centroid, but otherwise randomly oriented + """ + vertices = poly['vertices'] + p0 = vertices[PRNG.choice(vertices.shape[0])] + centroid = get_centroid(poly) + return gen_plane_through_points(p0, centroid, rand_unit_vector()) + + +def gen_plane_through_vertex(poly): + """ + Generate a plane passing through a vertex, but otherwise randomly oriented + """ + vertices = poly['vertices'] + p0 = vertices[PRNG.choice(vertices.shape[0])] + n = rand_unit_vector() + d = -n @ p0 + return n, d + + +def gen_plane_through_points(p0, p1, p2): + """ + Generate a plane passing through three given points + """ + n = numpy.cross(p1 - p0, p2 - p0) + n /= norm(n) + 1e-40 + d = -n @ p0 + return n, d + + +plane_generators = [gen_plane_through_centroid, gen_plane_from_face, + gen_plane_through_centroid_and_edge, gen_plane_through_edge, + gen_plane_through_centroid_and_vertex, gen_plane_through_vertex] + diff --git a/adze/test_results.txt b/adze/test_results.txt new file mode 100644 index 0000000..e89dde7 --- /dev/null +++ b/adze/test_results.txt @@ -0,0 +1,129 @@ +============================= test session starts ============================== +platform linux -- Python 3.8.2, pytest-4.6.9, py-1.8.1, pluggy-0.13.0 +rootdir: /d/home/jan/projects/adze +collected 6 items + +test/test_split.py FFFFFF [100%] + +=================================== FAILURES =================================== +__________________________ test_manual_tetrahedron[0] __________________________ + +poly_order = 0 + + def test_manual_tetrahedron(poly_order): +> tet = build_tetrahedron([ + [0,0,0], + [2,0,0], + [0,2,0], + [0,0,2]]) +E NameError: name 'build_tetrahedron' is not defined + +test/test_split.py:20: NameError +____________________ test_tetrahedrons_through_centroid[0] _____________________ + +poly_order = 0 + + def test_tetrahedrons_through_centroid(poly_order): + """ + Splits some tetrahedrons through their centroids and + checks if the two resulting volumes sum up to the original + """ + + # Generate random tetrahedrons and clip planes + ntets = 100 +> polys = [build_rand_tetrahedron() for _ in range(ntets)] + +test/test_split.py:57: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +test/test_split.py:57: in + polys = [build_rand_tetrahedron() for _ in range(ntets)] +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +min_volume = 1e-08 + + def build_rand_tetrahedron(min_volume: float = MIN_VOL): +> return build_tetrahedron(rand_tetrahedron_vertices()) +E NameError: name 'build_tetrahedron' is not defined + +test/utils.py:42: NameError +__________________________ test_manual_tetrahedron[1] __________________________ + +poly_order = 1 + + def test_manual_tetrahedron(poly_order): +> tet = build_tetrahedron([ + [0,0,0], + [2,0,0], + [0,2,0], + [0,0,2]]) +E NameError: name 'build_tetrahedron' is not defined + +test/test_split.py:20: NameError +____________________ test_tetrahedrons_through_centroid[1] _____________________ + +poly_order = 1 + + def test_tetrahedrons_through_centroid(poly_order): + """ + Splits some tetrahedrons through their centroids and + checks if the two resulting volumes sum up to the original + """ + + # Generate random tetrahedrons and clip planes + ntets = 100 +> polys = [build_rand_tetrahedron() for _ in range(ntets)] + +test/test_split.py:57: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +test/test_split.py:57: in + polys = [build_rand_tetrahedron() for _ in range(ntets)] +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +min_volume = 1e-08 + + def build_rand_tetrahedron(min_volume: float = MIN_VOL): +> return build_tetrahedron(rand_tetrahedron_vertices()) +E NameError: name 'build_tetrahedron' is not defined + +test/utils.py:42: NameError +__________________________ test_manual_tetrahedron[2] __________________________ + +poly_order = 2 + + def test_manual_tetrahedron(poly_order): +> tet = build_tetrahedron([ + [0,0,0], + [2,0,0], + [0,2,0], + [0,0,2]]) +E NameError: name 'build_tetrahedron' is not defined + +test/test_split.py:20: NameError +____________________ test_tetrahedrons_through_centroid[2] _____________________ + +poly_order = 2 + + def test_tetrahedrons_through_centroid(poly_order): + """ + Splits some tetrahedrons through their centroids and + checks if the two resulting volumes sum up to the original + """ + + # Generate random tetrahedrons and clip planes + ntets = 100 +> polys = [build_rand_tetrahedron() for _ in range(ntets)] + +test/test_split.py:57: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +test/test_split.py:57: in + polys = [build_rand_tetrahedron() for _ in range(ntets)] +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +min_volume = 1e-08 + + def build_rand_tetrahedron(min_volume: float = MIN_VOL): +> return build_tetrahedron(rand_tetrahedron_vertices()) +E NameError: name 'build_tetrahedron' is not defined + +test/utils.py:42: NameError +=========================== 6 failed in 2.42 seconds =========================== diff --git a/tpy_r3d.py b/tpy_r3d.py deleted file mode 100644 index 988eb18..0000000 --- a/tpy_r3d.py +++ /dev/null @@ -1,558 +0,0 @@ -import warnings -from time import perf_counter -import random -import logging - -import numpy -from numpy import sin, cos, pi -from numpy.linalg import norm - -from adze import (number_of_moments, get_moments, split, clip, build_tetrahedron, - build_box, planes_from_tetrahedron, build_polyhedron, boundary_from_poly, - voxelize) -from adze.util import check_poly - -try: - # Check if running with line_profiler - profile -except NameError: - def profile(f): - return f - - -logger = logging.getLogger(__name__) - - -# numerical tolerances for pass/warn/fail tests -TOL_WARN = 1e-8 -TOL_FAIL = 1e-4 - -# minimum volume allowed for test polyhedra -MIN_VOL = 1e-8 - -# order of polynomial integration for all tests -POLY_ORDER = 0 - - -def test_split_tet_manual(): - tet = build_tetrahedron([ - [0,0,0], - [2,0,0], - [0,2,0], - [0,0,2]]) - - volume = tetrahedron_volume(tet['vertices']) - logger.debug(f'Splitting manual tetrahedron {tet}') - logger.debug(f'volume {volume}') - - plane = numpy.array((-1, 0, 0)), 1 - p_left, p_right = split(tet, plane) - - logger.debug(f'left {p_left}') - logger.debug(f'right {p_right}') - - check_poly(tet) - check_poly(p_left) - check_poly(p_right) - - m0 = get_moments(tet, 0) - ml = get_moments(p_left, 0) - mr = get_moments(p_right, 0) - - logger.debug(f'0th moments: tot {m0}, left {ml}, right {mr}') - assert(abs(m0 - volume) < TOL_FAIL) - check_split_moments(tet, p_left, p_right, POLY_ORDER) - - -def test_split_tets_thru_centroid(): - # a very basic sanity check. Splits a tet through its centroid - # and checks to see whether the two resulting volumes add up to equal the original - - # generate a random tet and clip plane - ntets = 1 - polys = [build_rand_tetrahedron() for _ in range(ntets)] - plane = plane_centroid(polys[ntets//7]) - - # split them all with the same plane - poly12 = [split(p, plane) for p in polys] - poly1, poly2 = zip(*poly12) - - for orig, p1, p2 in zip(polys, poly1, poly2): - check_poly(orig) - check_poly(p1) - check_poly(p2) - check_split_moments(orig, p1, p2, POLY_ORDER) - - -def time_split(): - NUM_TRIALS = 10_000 - logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') - polys = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)] - facesets = [planes_from_tetrahedron(rand_tetrahedron_vertices()) for _ in range(NUM_TRIALS)] - t0 = perf_counter() - for t in range(NUM_TRIALS): - # clip the first tet against the faces of the second - for face in facesets[t]: - polys[t] = clip(polys[t], face) - if (t+1) % (NUM_TRIALS // 10) == 0: - t_each = (perf_counter() - t0) / (t + 1) - logger.info(f'time per split for {t+1} splits: {t_each}') - logger.info(f'done timing, time per split: {(perf_counter() - t0) / NUM_TRIALS}') - - polys_bulk = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)] - bulk = { - 'vertices': numpy.vstack(p['vertices'] for p in polys_bulk), - 'neighbors': numpy.vstack(p['neighbors'] for p in polys_bulk) + numpy.arange(NUM_TRIALS).repeat(4)[:, None] * 4, - } - t1 = perf_counter() - poly = clip(bulk, facesets[0][0]) - logger.info(f'bulked split time per tet: {(perf_counter() - t1) / NUM_TRIALS}') - - -@profile -def test_tet_tet_timing(): - # Intersects pairs of tetrahedra, for timing purposes only. - - # for timing only, no assertions - NUM_TRIALS = 1000 - t0 = perf_counter() - logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') - for t in range(NUM_TRIALS): - # generate the first random tet - poly = build_rand_tetrahedron() - - # generate the second random tet - faces = planes_from_tetrahedron(rand_tetrahedron_vertices()) - - # clip the first tet against the faces of the second - for face in faces: - poly = clip(poly, face) - - # find the moments (up to quadratic order) of the clipped poly - _om = get_moments(poly, POLY_ORDER) - - if (t+1) % 10000 == 0: - t_each = (perf_counter() - t0) / (t + 1) - logger.info(f'time per split+get_moments for {t+1} iterations: {t_each}') - logger.info(f'done timing, time per split+get_moments: {(perf_counter() - t0) / NUM_TRIALS}') - - -def test_split_nonconvex(): - # a very basic sanity check. Splits a nonconvex poly (a zig-zag prism of sorts) - # and checks to see whether the two resulting volumes add up to equal the original - NZIGS = 3 - ZOFF = 0.1 - - # explicitly create the nonconvex poly - num_verts = 4 * NZIGS - vertices = numpy.empty((num_verts, 3), dtype=float) - neighbors = numpy.empty((num_verts, 3), dtype=int) - - for v in range(NZIGS): - m = NZIGS - v - 1 - v0 = numpy.array([v, v % 2 + ZOFF, 0]) - v1 = numpy.array([m, m % 2, 0]) - vertices[v + 0 * NZIGS] = v0 - vertices[v + 1 * NZIGS] = v1 - vertices[v + 2 * NZIGS] = v0 + (0, 0, 1) - vertices[v + 3 * NZIGS] = v1 + (0, 0, 1) - - nz2 = 2 * NZIGS - for v in range(nz2): - neighbors[v] = ((v + 1) % nz2, - (v - 1) % nz2, - v + nz2) - neighbors[v + nz2] = neighbors[v][[1, 0, 2]] + (nz2, nz2, -nz2) - poly = { - 'vertices': vertices, - 'neighbors': neighbors, - } - - logger.debug("Checking poly...") - check_poly(poly) - logger.debug("poly is valid.") - - def split_and_check(poly, plane, poly_order=0): - poly_l = clip(poly, plane) - poly_r = clip(poly, flip_plane(plane)) - check_split_moments(poly, poly_l, poly_r) - - # split along the x-axis (two single connected components this direction) - split_and_check(poly, [numpy.array((1, 0, 0)), -0.5 * (NZIGS - 1)], POLY_ORDER) - - # split along the z-axis (two single connected components this direction) - split_and_check(poly, [numpy.array((0, 0, 1)), -0.5], POLY_ORDER) - - # split along the y-axis (multiple connected components this direction) - split_and_check(poly, [numpy.array((0, 1, 0)), -0.5 * (1.0 + ZOFF)], POLY_ORDER) - - -def test_recursive_split(num_trials: int = 10, max_depth: int = 6 ): - ''' - Starting with a tetrahedron, recusively split until the pieces - are smaller than MIN_VOL or have been split more than max_depth times - ''' - logger.info(f'Recursively splitting {num_trials} tetrahedra, maximum depth {max_depth}:') - logger.info(f' - Through centroid') - for _ in range(num_trials): - stack_split(build_rand_tetrahedron(), plane_fun=plane_centroid, max_depth=max_depth) - - logger.info(f' - Through degenerate plane') - for _ in range(num_trials): - stack_split(build_rand_tetrahedron(), max_depth=max_depth) - - logger.info(f' - Through perturbed plane') - for t in range(num_trials): - perturb = 10 ** -(1 + t % 16) - stack_split(build_rand_tetrahedron(), perturb=perturb, max_depth=max_depth) - - -@profile -def test_voxelization(): - # Test r3d_voxelize() by checking that the voxelized moments - # sum to those of the original input - POLY_ORDER = 0 - grid_resolution = 250 - - verts = 1.5 * (numpy.array(rand_tetrahedron_vertices()) + 1) - poly = build_tetrahedron(verts) - moments = get_moments(poly, POLY_ORDER) - - edges = [numpy.linspace(-1, 3, grid_resolution) for _ in range(3)] - logger.info(f'Voxelizing a tetrahedron to a grid with moments of order {POLY_ORDER}') - t0 = perf_counter() - grid = voxelize(poly, edges, order=POLY_ORDER) - print(f'voxel time: {perf_counter() - t0}') - - #visualize_voxels(grid) - - voxsum = numpy.sum(grid, axis=(0, 1, 2)) - - assert(numpy.all(numpy.abs(moments - voxsum) < TOL_FAIL)) - if not numpy.all(numpy.abs(moments - voxsum) < TOL_WARN): - warnings.warn('Moments failed tolerance in voxels') - - -def visualize_voxels(grid): - import gridlock - g = gridlock.Grid([numpy.arange(n+1) for n in grid.shape], shifts=[[0, 0, 0]]) - g.grids[0][:] = grid[:, :, :, 0] - g.visualize_isosurface() - - -@profile -def stack_split(poly, plane_fun=None, perturb=0, max_depth=10): - stack = [(poly, 0)] - - i = 0 - while stack: - i += 1 - poly, depth = stack.pop() - - # pick a plane - if plane_fun is None: - pfun_used = random.choice(plane_gen) - plane = pfun_used(poly) - while norm(plane[0]) == 0: - pfun_used = random.choice(plane_gen) - plane = pfun_used(poly) - plane = list(plane) - logger.debug(f'used {pfun_used}') - else: - plane = list(plane_fun(poly)) - - # perturb the plane - plane[0] *= 1 + perturb * (numpy.random.rand() - 0.5) - plane[1] *= 1 + perturb * (numpy.random.rand() - 0.5) - - # split the poly - poly_l = clip(poly, plane) - poly_r = clip(poly, flip_plane(plane)) - m0, ml, mr = check_split_moments(poly, poly_l, poly_r, POLY_ORDER) - - logger.debug(f'nstack = {len(stack)}, depth = {depth}, ' - f'opoly = {m0[0]:.10e}, p1 = {ml[0]:.10e}, p2 = {mr[0]:.10e}, ' - f'err = {abs(1.0 - m0[0]/(ml[0] + mr[0])):.10e}') - - # add the children to the stack if they are big enough - if depth < max_depth: - if ml[0] > MIN_VOL: - stack.append((poly_l, depth + 1)) - if mr[0] > MIN_VOL: - stack.append((poly_r, depth + 1)) - if i % 300 == 0: - logger.info(f'Stack split iter {i} length {len(stack)} depth {depth}') - - -@profile -def test_poly_pyramid(): - vertices = numpy.array([ - [0, 0, 1], - [1, 1, 0], - [1, -1, 0], - [-1, -1, 0], - [-1, 1, 0], - ]) - faces = [ - [0, 1, 2], - [0, 2, 3], - [0, 3, 4], - [0, 4, 1], - [4, 3, 2, 1], - ] - - # initialize a general polyhedron - poly = build_polyhedron(vertices, faces) - check_poly(poly) - stack_split(poly) - - brep = boundary_from_poly(poly) - logger.info(f'Round-trip converted pyramid: {brep}') - #plot_brep(brep) - - -def plot_brep(brep): - import stl - from matplotlib import pyplot - from mpl_toolkits import mplot3d - - meshes = [] - for component in brep: - triangles = [] - for face in component['faces']: - for i in range(1, len(face) - 1): - triangles.append([face[0], face[i], face[i+1]]) - triangles = numpy.array(triangles, dtype=int) - - m = stl.mesh.Mesh(numpy.empty(triangles.shape[0], dtype=stl.mesh.Mesh.dtype)) - for i, f in enumerate(triangles): - for j in range(3): - m.vectors[i, j] = component['vertices'][f[j], :] - -# m.save('pyr.stl') - meshes.append(m) - - figure = pyplot.figure() - axes = mplot3d.Axes3D(figure) - scales = [] - for mesh in meshes: - coll = mplot3d.art3d.Poly3DCollection(m.vectors) - coll.set_edgecolors('black') - axes.add_collection3d(coll) - scales.append(mesh.points.flatten()) - scale = numpy.hstack(scales) - axes.auto_scale_xyz(scale, scale, scale) - pyplot.show() - - -@profile -def test_torus_load_and_chop(): - # Recursively splits a polyhedron (starting from a torus) with a cut plane - # that is always degenerate with the poly in some way, - # checking to see that the resulting volumes add up properly. - # This checks non-convex geometry, and also build_polyhedron() when more than - # three edges per vertex are needed. - - n_th = 20 - n_phi = 20 - r_maj = 1.0 - r_min = 0.1 - - # make vertices - th, phi = numpy.meshgrid( - numpy.linspace(0, 2*pi, n_th, endpoint=False), - numpy.linspace(0, 2*pi, n_phi, endpoint=False), - ) - th, phi = th.ravel(order='F'), phi.ravel(order='F') - - vertices = numpy.column_stack(( - (r_maj + r_min * cos(th)) * cos(phi), - (r_maj + r_min * cos(th)) * sin(phi), - r_min * sin(th), - )) - - # shift away from the origin so that none of the moments are identically zero - vertices += (0.5, 0.7, 0.9) - - # make faces - i, j = numpy.meshgrid(numpy.arange(n_phi), numpy.arange(n_th), indexing='ij') - - a = i * n_th + j - b = ((i + 1) % n_phi) * n_th - c = (j + 1) % n_th - - aa = numpy.hstack((a, a)).ravel() - bb = numpy.hstack((b + j, b + c)).ravel() - cc = numpy.hstack((b + c, c + i * n_th)).ravel() - - faces = numpy.column_stack((aa, bb, cc)) - - - # initialize a general polyhedron - opoly = build_polyhedron(vertices, faces) -# check_poly(opoly) - stack_split(opoly) - - brep = boundary_from_poly(opoly) - logger.debug(f'Round-trip converted torus: {brep}') - #plot_brep(brep) - - -def tetrahedron_volume(vertices): - ad, bd, cd = vertices[0:3] - vertices[3] - return -ad @ numpy.cross(bd, cd) / 6 - - -def flip_plane(plane): - return (-plane[0], -plane[1]) - - -def check_split_moments(original_poly, left_poly, right_poly, poly_order=0): - m0, ml, mr = (get_moments(x, poly_order) for x in (original_poly, left_poly, right_poly)) - logger.debug(f'Check: original {m0[0]} parts {(ml[0], mr[0])} sum {ml[0] + mr[0]}') - - # Make sure each part is smaller than the whole - if not ml[0] < m0[0] * (1.0 + TOL_WARN): - warnings.warn('ml[0] < m0[0]') - assert(ml[0] < m0[0] * (1.0 + TOL_FAIL)) - if not mr[0] < m0[0] * (1.0 + TOL_WARN): - warnings.warn('mr[0] < m0[0]') - assert(mr[0] < m0[0] * (1.0 + TOL_FAIL)) - - # make sure the sum of moments equals the original - diff = numpy.abs(m0 - (ml + mr)) - if not numpy.all(diff < TOL_FAIL): - logger.error(f'diff failed: {diff} \n original {m0} \n left {ml} \n right {mr}') - assert(False) - if not numpy.all(diff < TOL_WARN): - warnings.warn('Moments outside tolerance') - - return m0, ml, mr - - -def plane_centroid(poly): - # make a randomly-oriented plane passing through the centroid - centroid = get_centroid(poly) - n = rand_unit_vector() - d = -n @ centroid - return n, d - - -def plane_face(poly): - # make a plane coplanar with a face of the poly - v0 = numpy.random.randint(poly['vertices'].shape[0]) - v1, v2 = random.sample(list(poly['neighbors'][v0]), 2) - points = (poly['vertices'][vi] for vi in (v0, v1, v2)) - return plane_points(*points) - - -def plane_centroid_edge(poly): - # make a plane coplanar with an edge and the centroid of the poly - v0 = numpy.random.randint(poly['vertices'].shape[0]) - v1 = random.choice(poly['neighbors'][v0]) - p0 = poly['vertices'][v0] - p1 = poly['vertices'][v1] - centroid = get_centroid(poly) - return plane_points(p0, p1, centroid) - - -def plane_edge(poly): - # make a plane coplanar with an edge, but otherwise randomly oriented - v0 = numpy.random.randint(poly['vertices'].shape[0]) - v1 = random.choice(poly['neighbors'][v0]) - p0 = poly['vertices'][v0] - p1 = poly['vertices'][v1] - return plane_points(p0, p1, rand_unit_vector()) - - -def plane_centroid_vertex(poly): - # make a plane coplanar with a vertex and the centroid, but otherwise randomly oriented - p0 = random.choice(poly['vertices']) - centroid = get_centroid(poly) - return plane_points(p0, centroid, rand_unit_vector()) - - -def plane_vertex(poly): - # make a plane coplanar with a vertex, but otherwise randomly oriented - p0 = random.choice(poly['vertices']) - n = rand_unit_vector() - d = -n @ p0 - return n, d - - -def plane_points(p0, p1, p2): - # generate a plane passing through the three points given - n = numpy.cross(p1 - p0, p2 - p0) - n /= norm(n) + 1e-40 - d = -n @ p0 - return n, d - - -def rand_unit_vector(): - # generates a random, isotropically distributed unit vector - s = 0 - while s == 0: - v = numpy.random.randn(3) - s = norm(v) - return v / s - - -def rand_tetrahedron_vertices(min_volume: float = MIN_VOL): - # generates a random tetrahedron with vertices on the unit sphere, - # guaranteeing a volume of at least min_volume - volume = 0 - while volume < min_volume: - verts = [rand_unit_vector() for _ in range(4)] - volume = tetrahedron_volume(verts) - if volume < 0: - verts[2], verts[3] = verts[3], verts[2] - volume = -volume - return verts - - -def build_rand_tetrahedron(min_volume: float = MIN_VOL): - return build_tetrahedron(rand_tetrahedron_vertices()) - - -def get_centroid(poly): - # get the centroid by averaging vertices - centroid = numpy.sum(poly['vertices'], axis=0) / poly['vertices'].shape[0] - return centroid - - -plane_gen = [plane_centroid, plane_face, - plane_centroid_edge, plane_edge, - plane_centroid_vertex, plane_vertex] - - -if __name__ == '__main__': - logging.basicConfig(level=logging.INFO) - - logger.info('poly_pyramid') - test_poly_pyramid() - - logger.info('load_chop_torus') - test_torus_load_and_chop() - - logger.info('test_split_tet_manual') - test_split_tet_manual() - - logger.info('test_split_tets_thru_centroid') - test_split_tets_thru_centroid() - - logger.info('test_split_nonconvex') - test_split_nonconvex() - - logger.info('split_recursive') - test_recursive_split() - - logger.info('voxelization') -# test_voxelization() - - logger.info('test_tet_tet_timing') - test_tet_tet_timing() - - logger.info('time_split') - time_split() - - logger.info('success') From 675d1b2aef2b712b842eddd4a7352894810409d4 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 15 Mar 2020 23:15:06 -0700 Subject: [PATCH 05/69] speed up voxelization tests for higher-order polynomials --- adze/test/test_voxel.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py index e876428..5e6dd36 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -16,10 +16,13 @@ from .utils import build_rand_tetrahedron, gen_plane_through_centroid, plane_gen logger = logging.getLogger(__name__) -def test_voxelization(poly_order, grid_resolution=250): +def test_voxelization(poly_order, grid_resolution=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) From aae542c8e511d360d1fe98715c34ca4cdf947612 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 15 Mar 2020 23:15:18 -0700 Subject: [PATCH 06/69] some readme updates --- README.md | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 0e60000..f131432 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# adze +# adze **adze** is a Python package for accurate polyhedron clipping and anti-aliased voxelization. @@ -9,24 +9,25 @@ - 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.5 or newer +* python 3.6 or newer * numpy - +* pytest (optional, testing) +* pytest-benchmark (optional, benchmarking) Install with pip from PyPi (preferred): ```bash -pip install adze +pip3 install adze ``` Install directly from git repository: ```bash -pip install git+https://mpxd.net/code/jan/adze.git@release +pip3 install git+https://mpxd.net/code/jan/adze.git@release ``` ## Documentation @@ -38,18 +39,3 @@ 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) -``` From cd0ca442b2a64ee62f1299bfc30edd178d10c216 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 15 Mar 2020 23:15:30 -0700 Subject: [PATCH 07/69] Use pytest-benchmark for benchmarking --- adze/test/benchmark.py | 92 ------------------------------------ adze/test/test_benchmarks.py | 60 +++++++++++++++++++++++ 2 files changed, 60 insertions(+), 92 deletions(-) delete mode 100644 adze/test/benchmark.py create mode 100644 adze/test/test_benchmarks.py diff --git a/adze/test/benchmark.py b/adze/test/benchmark.py deleted file mode 100644 index 9db34be..0000000 --- a/adze/test/benchmark.py +++ /dev/null @@ -1,92 +0,0 @@ -""" -Benchmarking, run with `python3 -m adze.test.benchmark` - -TODO: Consider using pytest-benchmark? -""" -import warnings -from time import perf_counter -import random -import logging - -import numpy -from numpy import sin, cos, pi -from numpy.linalg import norm - -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, plane_generators, rand_tetrahedron_vertices - - -logger = logging.getLogger(__name__) - - -try: - # Check if running with line_profiler - profile -except NameError: - def profile(f): - return f - - -@profile -def time_split(): - NUM_TRIALS = 10_000 - logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') - polys = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)] - facesets = [adze.planes_from_tetrahedron(rand_tetrahedron_vertices()) for _ in range(NUM_TRIALS)] - t0 = perf_counter() - for t in range(NUM_TRIALS): - # clip the first tet against the faces of the second - for face in facesets[t]: - polys[t] = adze.clip(polys[t], face) - if (t + 1) % (NUM_TRIALS // 10) == 0: - t_each = (perf_counter() - t0) / (t + 1) - logger.info(f'time per split for {t+1} splits: {t_each}') - logger.info(f'done timing, time per split: {(perf_counter() - t0) / NUM_TRIALS}') - - polys_bulk = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)] - bulk = { - 'vertices': numpy.vstack([p['vertices'] for p in polys_bulk]), - 'neighbors': numpy.vstack([p['neighbors'] for p in polys_bulk]) + numpy.arange(NUM_TRIALS).repeat(4)[:, None] * 4, - } - t1 = perf_counter() - poly = adze.clip(bulk, facesets[0][0]) - logger.info(f'bulked split time per tet: {(perf_counter() - t1) / NUM_TRIALS}') - - -@profile -def time_intersection(poly_order=0): - """ - Benchmark intersection between pairs of tetrahedra - """ - NUM_TRIALS = 1000 - - t0 = perf_counter() - logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') - for t in range(NUM_TRIALS): - poly = build_rand_tetrahedron() - faces = adze.planes_from_tetrahedron(rand_tetrahedron_vertices()) - - # 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) - - if (t+1) % 10000 == 0: - t_each = (perf_counter() - t0) / (t + 1) - logger.info(f'time per split+get_moments for {t+1} iterations: {t_each}') - logger.info(f'done timing, time per split+get_moments: {(perf_counter() - t0) / NUM_TRIALS}') - - -if __name__ == '__main__': - logging.basicConfig(level=logging.INFO) - - logger.info('time_intersection') - time_intersection() - - logger.info('time_split') - time_split() diff --git a/adze/test/test_benchmarks.py b/adze/test/test_benchmarks.py new file mode 100644 index 0000000..f899353 --- /dev/null +++ b/adze/test/test_benchmarks.py @@ -0,0 +1,60 @@ +""" +Benchmarking, run with `python3 -m adze.test.benchmark` + +TODO: Consider using pytest-benchmark? +""" +import warnings +from time import perf_counter +import random +import logging + +import numpy +from numpy import sin, cos, pi +from numpy.linalg import norm + +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, plane_generators, rand_tetrahedron_vertices + + +logger = logging.getLogger(__name__) + + +def test_split(benchmark): + poly = build_rand_tetrahedron() + faceset = adze.planes_from_tetrahedron(rand_tetrahedron_vertices()) + benchmark(adze.clip, poly, faceset[0]) + + +def test_split_bulk_1000(benchmark): + 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, faces, poly_order): + # 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, poly_order=0): + """ + 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) + From a7bb9a4fa7d331eff55367c020280a4ebf594422 Mon Sep 17 00:00:00 2001 From: jan Date: Sun, 7 Feb 2021 19:28:37 -0800 Subject: [PATCH 08/69] modify function docstring style --- adze/boundary.py | 29 +++++++++++++++++++---------- adze/moments.py | 24 +++++++++++++++--------- adze/shapes.py | 32 ++++++++++++++++++++++---------- adze/split.py | 23 ++++++++++++++--------- adze/test/test_voxel.py | 7 ++++--- adze/transform.py | 38 +++++++++++++++++++++++++------------- adze/util.py | 34 ++++++++++++++++++++++------------ adze/voxel.py | 29 ++++++++++++++++------------- 8 files changed, 137 insertions(+), 79 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index 84205db..cf3a346 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -20,10 +20,13 @@ def planes_from_boundary(vertices: numpy.ndarray, Generate a list of planes (normal, signed distance) from the faces of a boundary- representation polyhedron. - :param vertices: Nx3 ndarray specifying the polyhedron's vertex positions. - :param faces: List of 1d ndarrays. Each ndarray is a list of vertex indices, - specifying a face. - :return: List of planes, represented by (normal vector, signed distance to origin) tuples. + Args: + vertices: Nx3 ndarray specifying the polyhedron's vertex positions. + faces: List of 1d ndarrays. Each ndarray is a list of vertex indices, + specifying a face. + + Returns: + List of planes, represented by (normal vector, signed distance to origin) tuples. ''' planes = [] for face in faces: @@ -44,10 +47,13 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: Generate a 3-verted-connected Schlegel diagram representation corresponding to the provided boundary-representation polyhedron. - :param vertices: Nx3 ndarray specifying the polyhedron's vertex positions. - :param faces: List of 1d ndarrays. Each ndarray is a list of vertex indices, - specifying a face. - :return: Schelgel-representation polyhedron + Args: + vertices: Nx3 ndarray specifying the polyhedron's vertex positions. + faces: List of 1d ndarrays. Each ndarray is a list of vertex indices, + specifying a face. + + Returns: + Schelgel-representation polyhedron ''' vertices = numpy.array(vertices, dtype=float) faces = [numpy.array(face, dtype=int) for face in faces] @@ -263,8 +269,11 @@ def boundary_from_poly(poly: poly_t) -> Dict: Generate a boundary represeentation corresponding to the provided 3-vertex-connected Schlegel diagram. - :param poly: Polyhedron to convert, in Schlegel representation. - :return: Dict containing 'vertices' (Nx3 ndarray of vertex locations) + Args: + poly: Polyhedron to convert, in Schlegel representation. + + Returns: + Dict containing 'vertices' (Nx3 ndarray of vertex locations) and 'faces' (list of ndarrays specifying the indices of vertices used for constructing each face). ''' diff --git a/adze/moments.py b/adze/moments.py index 794e465..d362d14 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -9,15 +9,16 @@ try: 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. - :param order: Maximum polynomial order for the moments. - :return: Number of moments with that order or fewer. + Args: + order: Maximum polynomial order for the moments. + + Returns: + Number of moments with that order or fewer. ''' return ((order + 1) * (order + 2) * (order + 3)) // 6 @@ -26,8 +27,11 @@ def get_volume(poly: poly_t) -> float: ''' Calculates the volume of a polyhedron (0th moment). - :param poly: Polyhedron to evaluate, in Schlegel representation. - :return: Volume of the polyhedron. + Args: + poly: Polyhedron to evaluate, in Schlegel representation. + + Returns: + Volume of the polyhedron. ''' return get_moments(poly, 0)[0] @@ -37,9 +41,11 @@ def get_moments(poly: poly_t, order: int) -> numpy.ndarray: ''' Calculates the moments of a polyhedron, up to the specified polynomial order. - :param poly: Polyhedron to evaluate, in Schlegel representation. - :param order: Maximum polynomial order for moments. - :return: Moments, increasing polynomial order: + Args: + poly: Polyhedron to evaluate, in Schlegel representation. + order: Maximum polynomial order for moments. + + Returns: Moments, increasing polynomial order: [1, x, y, z, xx, xy, xz, yy, yz, zz, xxx, xxy, xxz, ...] ''' vertices = poly['vertices'] diff --git a/adze/shapes.py b/adze/shapes.py index 05d0c5e..20f422e 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -9,8 +9,11 @@ def build_tetrahedron(vertices: numpy.ndarray) -> poly_t: ''' Build a Schelegel-representation tetrahedron. - :param vertices: 4x3 array, representing the vertex coordinates. - :return: Tetrahedron in Schelgel representation. + Args: + vertices: 4x3 array, representing the vertex coordinates. + + Returns: + Tetrahedron in Schelgel representation. ''' poly = { 'vertices': numpy.array(vertices, dtype=float), @@ -27,9 +30,12 @@ def build_box(box_corners: numpy.ndarray) -> poly_t: ''' Build a Schelegel-representation box. - :param box_corners: 2x3 array, representing the vertex coordinates of - two diagonally-opposite corners of the box. - :return: Box in Schelgel representation. + Args: + box_corners: 2x3 array, representing the vertex coordinates of + two diagonally-opposite corners of the box. + + Returns: + Box in Schelgel representation. ''' neighbors = [ [1, 4, 3], @@ -63,9 +69,12 @@ def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]: ''' Construct a list of planes corresponding to the faces of a box. - :param box_corners: 2x3 array, representing the vertex coordinates of - two diagonally-opposite corners of the box. - :return: List of planes, facing inwards. + Args: + box_corners: 2x3 array, representing the vertex coordinates of + two diagonally-opposite corners of the box. + + Returns: + List of planes, facing inwards. ''' box_corners = numpy.array(box_corners) faces = [ @@ -84,8 +93,11 @@ def planes_from_tetrahedron(vertices: numpy.ndarray) -> List[plane_t]: ''' Construct a list of planes corresponding to the faces of a tetrahedron. - :param vertices: 4x3 array, representing the vertex coordinates. - :return: List of planes, facing inwards. + Args: + vertices: 4x3 array, representing the vertex coordinates. + + Returns: + List of planes, facing inwards. ''' verts = numpy.array(vertices, dtype=float) vset_inds = numpy.array(( diff --git a/adze/split.py b/adze/split.py index 71715a9..1924dce 100644 --- a/adze/split.py +++ b/adze/split.py @@ -18,9 +18,12 @@ def clip(poly: poly_t, plane: plane_t) -> poly_t: This function is equivalent to calling split(poly, plane, same_only=True). - :param poly: Polyhedron to clip, in chiral Schlegel representation. - :param plane: Plane to clip against. - :return: Clipped polyhedron. + Args: + poly: Polyhedron to clip, in chiral Schlegel representation. + plane: Plane to clip against. + + Returns: + Clipped polyhedron. ''' left_poly = split(poly, plane, same_only=True) return left_poly @@ -35,12 +38,14 @@ def split(poly, plane, same_only: bool = False): where same_side_poly is on the same side as the plane's normal vector. Otherwise, returns only same_side_poly (somewhat faster). - :param poly: Polyhedron to clip, in chiral Schlegel representation. - :param plane: Plane to clip against. - :param same_only: If True, only returns the clipped poly from the same side as the - plane's normal vector. Default False. - :return: (same_side_poly, other_side_poly) if same_only is False (default), otherwise - only returns same_side_poly. + Args: + poly: Polyhedron to clip, in chiral Schlegel representation. + plane: Plane to clip against. + same_only: If True, only returns the clipped poly from the same side as the + plane's normal vector. Default False. + Returns: + (same_side_poly, other_side_poly) if same_only is False (default), otherwise + only returns same_side_poly. ''' vertices = poly['vertices'] neighbors = poly['neighbors'] diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py index 5e6dd36..c537e59 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -50,9 +50,10 @@ def visualize_isosurface(grid, """ Draw an isosurface plot of the device. - :param level: Value at which to find isosurface. Default (None) uses mean value in grid. - :param show_edges: Whether to draw triangle edges. Default True - :param finalize: Whether to call pyplot.show() after constructing the plot. Default True + 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 diff --git a/adze/transform.py b/adze/transform.py index 8c77c71..56e6faa 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -8,10 +8,13 @@ def rotate(poly: poly_t, theta: float, axis: int) -> poly_t: ''' Rotate the polyhedron around an axis. - :param poly: Polyhedron to rotate. Changed in-place. - :param theta: Angle to rotate by (radians). - :param axis: Axis to rotate around (0-2). - :return: Rotated polyhedron. + Args: + poly: Polyhedron to rotate. Changed in-place. + theta: Angle to rotate by (radians). + axis: Axis to rotate around (0-2). + + Returns: + Rotated polyhedron. Data is altered in-place but also returned for convenience. ''' s, c = sin(theta), cos(theta) @@ -26,9 +29,12 @@ def translate(poly: poly_t, shift: numpy.ndarray) -> poly_t: ''' Translate the polyhedron by a vector. - :param poly: Polyhedron to translate. Changed in-place. - :param shift: Vector to translate by. - :return: Translated polyhedron. + Args: + poly: Polyhedron to translate. Changed in-place. + shift: Vector to translate by. + + Returns: + Translated polyhedron. Data is altered in-place but also returned for convenience. ''' poly['vertices'] += shift @@ -40,9 +46,12 @@ def scale(poly: poly_t, factor: numpy.ndarray or float) -> poly_t: Scale the polyhedron. Can scale by a single value, or scale each axis individually - :param poly: Polyhedron to scale. Changed in-place. - :param factor: Scalar or vector to scale by. - :return: Scaled polyhedron. + Args: + poly: Polyhedron to scale. Changed in-place. + factor: Scalar or vector to scale by. + + Returns: + Scaled polyhedron. Data is altered in-place but also returned for convenience. ''' poly['vertices'] *= factor @@ -53,9 +62,12 @@ def affine(poly: poly_t, xform: numpy.ndarray) -> poly_t: ''' Perform arbitrary affine trasnformation on the polyhedron. - :param poly: Polyhedron to transform. Changed in-place. - :param xform: 4x4 affine transformation matrix. - :return: Transformed polyhedron. + Args: + poly: Polyhedron to transform. Changed in-place. + xform: 4x4 affine transformation matrix. + + Returns: + Transformed polyhedron. Data is altered in-place but also returned for convenience. ''' mat4x3 = xform[:, :3] diff --git a/adze/util.py b/adze/util.py index ee179b8..4df2ad0 100644 --- a/adze/util.py +++ b/adze/util.py @@ -17,7 +17,8 @@ def build_empty() -> poly_t: ''' Build an empty Schlegel representation (containing no vertices). - :return: Empty Schelegel representation. + Returns: + Empty Schelegel representation. ''' return { 'vertices': numpy.empty((0, 3), dtype=float), @@ -30,10 +31,13 @@ def find_components(neighbors: numpy.ndarray) -> numpy.ndarray: ''' Given an adjacency list, flood-fill to find and label connected components. - :param neighbors: NxM adjacency list. Each of the N vertices is assumed - to have the same number of neighbors, which are specified by their - indices. - :return: 1D ndarray with N entries. Entries are integer labels denoting + Args: + neighbors: NxM adjacency list. Each of the N vertices is assumed + to have the same number of neighbors, which are specified by their + indices. + + Returns: + 1D ndarray with N entries. Entries are integer labels denoting which connected component the vertex belongs to. ''' num_vertices = neighbors.shape[0] @@ -61,9 +65,12 @@ def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]: graph with exactly 3 neighbors per vertex. Neighbors are ordered counter-clockwise. - :param neighbors: Nx3 adjacency list. Neighbors are specified by their - indices. - :return: List of ndarrays, each of which contains the indices in a given + Args: + neighbors: Nx3 adjacency list. Neighbors are specified by their + indices. + + Returns: + List of ndarrays, each of which contains the indices in a given face, starting with the lowest index in the face. ''' num_verts = neighbors.shape[0] @@ -215,10 +222,13 @@ def check_poly(poly: poly_t, check_connectivity: bool = True): - has exactly 3 edges per vertex - is 3-vertex-connected (if check_connectivity is True; slow!) - :param poly: Polyhedron to check. - :param check_connectivity: Whether to check for 3-vertex-connectedness. - This is slow! Default True. - :raises: Exception if the polyhedron fails a check + Args: + poly: Polyhedron to check. + check_connectivity: Whether to check for 3-vertex-connectedness. + This is slow! Default `True`. + + Raises: + Exception if the polyhedron fails a check ''' neighbors = poly['neighbors'] vertices = poly['vertices'] diff --git a/adze/voxel.py b/adze/voxel.py index 79f91a0..67e8b90 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -24,25 +24,28 @@ def voxelize(poly: poly_t, Voxelize a Schelegel-representation polyhedron on an arbitrary rectangular grid. The grid is specified by supplying 3 sets of axis-aligned planes, in the form - [[x0, x1, x2, ..., xX], [y0, y1, y2, ..., yY], [z0, z1, ..., zZ]] + `[[x0, x1, x2, ..., xX], [y0, y1, y2, ..., yY], [z0, z1, ..., zZ]]` The output array has size [X-1, Y-1, Z-1, N] (include_outside False) or - [X+1, Y+1, Z+1, N] (include_outside True), where N is the number of moments + `[X+1, Y+1, Z+1, N]` (`include_outside` True), where `N` is the number of moments corresponding to the requested order. If include_outside is true, the outer borders of the first three dimensions of the output correspond to portions of the polyhedron that protruded outside the provided grid. - :param poly: Polyhedron to voxelize. - :param planes: List of coordinate lists, specifying the axis-aligned planes - which form the voxel grid: - [[x0, x1, ..., xX], [y0, y1, ..., yY], [z0, z1, ..., zZ]] - :param include_outside: Whether to include cells corresponding to portions of the - polyhedron that fall outside of the grid. Default False. - :param order: Polynomial order of moments to calculate. Default 0. - :return: (X - 1) x (Y - 1) x (Z - 1) x N (include_outside False) or - (X + 1) x (Y + 1) x (Z + 1) x N (include_outside True) ndarray. - If include_outside is true, the outer borders of the first three dimensions + Args: + poly: Polyhedron to voxelize. + planes: List of coordinate lists, specifying the axis-aligned planes + which form the voxel grid: + `[[x0, x1, ..., xX], [y0, y1, ..., yY], [z0, z1, ..., zZ]]` + include_outside: Whether to include cells corresponding to portions of the + polyhedron that fall outside of the grid. Default `False`. + order: Polynomial order of moments to calculate. Default `0`. + + Returns: + (X - 1) x (Y - 1) x (Z - 1) x N (`include_outside` False) or + (X + 1) x (Y + 1) x (Z + 1) x N (`include_outside` True) ndarray. + If include_outside is True, the outer borders of the first three dimensions correspond to portions of the polyhedron that protruded outside the outermost - planes. N is number_of_moments(order). + planes. N is `number_of_moments(order)`. ''' planes = [numpy.array(p) for p in planes] From bc86b759d11dd30f3cd8f97e5ab4447defd3556d Mon Sep 17 00:00:00 2001 From: jan Date: Sun, 7 Feb 2021 19:29:20 -0800 Subject: [PATCH 09/69] remove @profile markers --- adze/boundary.py | 9 --------- adze/moments.py | 6 ------ adze/split.py | 8 -------- adze/util.py | 13 ------------- adze/voxel.py | 8 -------- 5 files changed, 44 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index cf3a346..2fd498d 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -5,13 +5,6 @@ from numpy.linalg import norm from . import poly_t, plane_t from .util import _get_maps, find_components, find_faces -try: - # Check if running with line_profiler - profile -except NameError: - def profile(f): - return f - def planes_from_boundary(vertices: numpy.ndarray, faces: List[numpy.ndarray] @@ -41,7 +34,6 @@ def planes_from_boundary(vertices: numpy.ndarray, return planes -@profile def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: ''' Generate a 3-verted-connected Schlegel diagram representation @@ -263,7 +255,6 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: return {'vertices': final_vertices, 'neighbors': neighbors} -@profile def boundary_from_poly(poly: poly_t) -> Dict: ''' Generate a boundary represeentation corresponding to the provided diff --git a/adze/moments.py b/adze/moments.py index d362d14..93b79d3 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -4,11 +4,6 @@ import numpy from . import poly_t, plane_t from .util import find_faces -try: - # Check if running with line_profiler - profile -except NameError: - def profile(f): def number_of_moments(order: int) -> int: ''' @@ -36,7 +31,6 @@ def get_volume(poly: poly_t) -> float: return get_moments(poly, 0)[0] -@profile def get_moments(poly: poly_t, order: int) -> numpy.ndarray: ''' Calculates the moments of a polyhedron, up to the specified polynomial order. diff --git a/adze/split.py b/adze/split.py index 1924dce..03b54c7 100644 --- a/adze/split.py +++ b/adze/split.py @@ -3,13 +3,6 @@ import numpy from . import poly_t, plane_t from .util import build_empty, _get_map -try: - # Check if running with line_profiler - profile -except NameError: - def profile(f): - return f - def clip(poly: poly_t, plane: plane_t) -> poly_t: ''' @@ -29,7 +22,6 @@ def clip(poly: poly_t, plane: plane_t) -> poly_t: return left_poly -@profile def split(poly, plane, same_only: bool = False): ''' Clip a polyhedron with a plane. diff --git a/adze/util.py b/adze/util.py index 4df2ad0..4942379 100644 --- a/adze/util.py +++ b/adze/util.py @@ -1,13 +1,6 @@ from typing import Dict, Tuple, List import numpy -try: - # Check if running with line_profiler - profile -except NameError: - def profile(f): - return f - plane_t = Tuple[numpy.ndarray, float] poly_t = Dict[str, numpy.ndarray] @@ -26,7 +19,6 @@ def build_empty() -> poly_t: } -@profile def find_components(neighbors: numpy.ndarray) -> numpy.ndarray: ''' Given an adjacency list, flood-fill to find and label connected components. @@ -57,7 +49,6 @@ def find_components(neighbors: numpy.ndarray) -> numpy.ndarray: return component - 1 -@profile def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]: ''' Traverse the Schlegel diagram to find chordless cycles @@ -140,7 +131,6 @@ def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]: return cleaned_faces(remove, k) -@profile def _get_map(a, b): ''' Returns m such that a[m] == b @@ -155,7 +145,6 @@ def _get_map(a, b): return sa[r] -@profile def _get_map_rows(a, b): ''' Row-wise _get_map @@ -166,7 +155,6 @@ def _get_map_rows(a, b): return _get_map(a1d, b1d) -@profile def _get_maps(a, b): ''' Returns m, n such that a[m] == b, b[n] == a @@ -184,7 +172,6 @@ def _get_maps(a, b): return m, n -@profile def _get_maps_rows(a, b): ''' Row-wise _get_maps diff --git a/adze/voxel.py b/adze/voxel.py index 67e8b90..cb775c9 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -6,15 +6,7 @@ from .split import split, clip from .moments import get_moments, number_of_moments from .shapes import planes_from_box -try: - # Check if running with line_profiler - profile -except NameError: - def profile(f): - return f - -@profile def voxelize(poly: poly_t, planes: List[numpy.ndarray], include_outside: bool = False, From a9281d3db75a016963e0be2e7422341d8dcba177 Mon Sep 17 00:00:00 2001 From: jan Date: Sun, 7 Feb 2021 19:29:27 -0800 Subject: [PATCH 10/69] update type hints --- adze/split.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adze/split.py b/adze/split.py index 03b54c7..07a1e36 100644 --- a/adze/split.py +++ b/adze/split.py @@ -22,7 +22,7 @@ def clip(poly: poly_t, plane: plane_t) -> poly_t: return left_poly -def split(poly, plane, same_only: bool = False): +def split(poly: poly_t, plane: plane_t, same_only: bool = False) -> Tuple[poly_t, poly_t]: ''' Clip a polyhedron with a plane. From d5d7663ac883c791e904f391babea2bc2b076575 Mon Sep 17 00:00:00 2001 From: jan Date: Sun, 7 Feb 2021 19:46:36 -0800 Subject: [PATCH 11/69] comment updates --- adze/boundary.py | 2 +- adze/voxel.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index 2fd498d..9be0f03 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -69,7 +69,7 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: 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 prv == nxt. + # Thus, we will never encounter a situation in which prev == next. # If the vertex hasn't been linked to anything yet, set its first two # polyhedron-neighbors to its face-neighbors diff --git a/adze/voxel.py b/adze/voxel.py index cb775c9..78e7096 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -20,7 +20,7 @@ def voxelize(poly: poly_t, The output array has size [X-1, Y-1, Z-1, N] (include_outside False) or `[X+1, Y+1, Z+1, N]` (`include_outside` True), where `N` is the number of moments corresponding to the requested order. If include_outside is true, the outer borders - of the first three dimensions of the output correspond to portions of the polyhedron + of the first three dimensions of the output correspond to portions of the polyhedron that protruded outside the provided grid. Args: From 1a034002fb99d213a3c6d4f7e8168ec576937af2 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 13 Feb 2021 15:47:44 -0800 Subject: [PATCH 12/69] planes should be tuples --- adze/boundary.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adze/boundary.py b/adze/boundary.py index 9be0f03..4199868 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -30,7 +30,7 @@ def planes_from_boundary(vertices: numpy.ndarray, 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 From b791d3c854f6fda128614a0c1a198ddc2abcf37f Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 13 Feb 2021 16:48:28 -0800 Subject: [PATCH 13/69] Rename split() to _split() and make new split() function with known return type --- adze/split.py | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/adze/split.py b/adze/split.py index 07a1e36..201171c 100644 --- a/adze/split.py +++ b/adze/split.py @@ -1,4 +1,5 @@ -import numpy +from typing import Tuple, Union +import numpy # type: ignore from . import poly_t, plane_t from .util import build_empty, _get_map @@ -9,7 +10,7 @@ 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. @@ -18,11 +19,26 @@ def clip(poly: poly_t, plane: plane_t) -> poly_t: Returns: Clipped polyhedron. ''' - left_poly = split(poly, plane, same_only=True) + left_poly = _split(poly, plane, same_only=True) return left_poly -def split(poly: poly_t, plane: plane_t, same_only: bool = False) -> Tuple[poly_t, poly_t]: +def split(poly: poly_t, plane: plane_t) -> 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. + Returns: + same_side_poly, other_side_poly + The first polyhedron is on from the same side as the plane's normal vector. + ''' + + +def _split(poly: poly_t, plane: plane_t, same_only: bool = False): ''' Clip a polyhedron with a plane. From ac574547633db77836d3a982c83e1b5cf901730d Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 13 Feb 2021 16:48:53 -0800 Subject: [PATCH 14/69] type fixes and ignores --- adze/boundary.py | 10 +++++----- adze/moments.py | 2 +- adze/shapes.py | 4 ++-- adze/test/test_benchmarks.py | 4 ++-- adze/test/test_split.py | 6 +++--- adze/test/test_voxel.py | 10 +++++----- adze/test/utils.py | 4 ++-- adze/transform.py | 5 +++-- adze/util.py | 6 +++--- adze/voxel.py | 2 +- 10 files changed, 27 insertions(+), 26 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index 4199868..427f984 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -1,6 +1,6 @@ -from typing import List, Dict -import numpy -from numpy.linalg import norm +from typing import List, Dict, Any +import numpy # type: ignore +from numpy.linalg import norm # type: ignore from . import poly_t, plane_t from .util import _get_maps, find_components, find_faces @@ -255,7 +255,7 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: return {'vertices': final_vertices, 'neighbors': neighbors} -def boundary_from_poly(poly: poly_t) -> Dict: +def boundary_from_poly(poly: poly_t) -> List[Dict[str, Any]]: ''' Generate a boundary represeentation corresponding to the provided 3-vertex-connected Schlegel diagram. @@ -275,7 +275,7 @@ def boundary_from_poly(poly: poly_t) -> Dict: faces = find_faces(neighbors) num_components = owning_component.max() + 1 - components = [[] for _ in range(num_components)] + components: List[List[numpy.ndarray]] = [[] for _ in range(num_components)] for face in faces: component_ind = owning_component[face[0]] components[component_ind].append(face) diff --git a/adze/moments.py b/adze/moments.py index 93b79d3..2c2aafd 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -1,5 +1,5 @@ from typing import Dict, Tuple -import numpy +import numpy # type: ignore from . import poly_t, plane_t from .util import find_faces diff --git a/adze/shapes.py b/adze/shapes.py index 20f422e..c9215c7 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -1,6 +1,6 @@ from typing import List -import numpy -from numpy.linalg import norm +import numpy # type: ignore +from numpy.linalg import norm # type: ignore from . import poly_t, plane_t diff --git a/adze/test/test_benchmarks.py b/adze/test/test_benchmarks.py index f899353..dfeca5d 100644 --- a/adze/test/test_benchmarks.py +++ b/adze/test/test_benchmarks.py @@ -8,9 +8,9 @@ from time import perf_counter import random import logging -import numpy +import numpy # type: ignore from numpy import sin, cos, pi -from numpy.linalg import norm +from numpy.linalg import norm # type: ignore import adze import adze.util diff --git a/adze/test/test_split.py b/adze/test/test_split.py index 3e8b197..0671fe0 100644 --- a/adze/test/test_split.py +++ b/adze/test/test_split.py @@ -1,9 +1,9 @@ import logging import pytest from pytest import approx -import numpy -from numpy.linalg import norm -from numpy.testing import assert_allclose, assert_array_equal +import numpy # type: ignore +from numpy.linalg import norm # type: ignore +from numpy.testing import assert_allclose, assert_array_equal # type: ignore import adze import adze.util diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py index c537e59..4dabdeb 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -1,9 +1,9 @@ import logging import pytest from pytest import approx -import numpy -from numpy.linalg import norm -from numpy.testing import assert_allclose, assert_array_equal +import numpy # type: ignore +from numpy.linalg import norm # type: ignore +from numpy.testing import assert_allclose, assert_array_equal # type: ignore from time import perf_counter import adze @@ -55,8 +55,8 @@ def visualize_isosurface(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 + from matplotlib import pyplot # type: ignore + import skimage.measure # type: ignore # Claims to be unused, but needed for subplot(projection='3d') from mpl_toolkits.mplot3d import Axes3D diff --git a/adze/test/utils.py b/adze/test/utils.py index f99c9f0..0613fa2 100644 --- a/adze/test/utils.py +++ b/adze/test/utils.py @@ -1,6 +1,6 @@ -import numpy +import numpy # type: ignore from numpy import pi, cos, sin -from numpy.linalg import norm +from numpy.linalg import norm # type: ignore import random import adze diff --git a/adze/transform.py b/adze/transform.py index 56e6faa..df83cd5 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -1,4 +1,5 @@ -import numpy +from typing import Union +import numpy # type: ignore from numpy import sin, cos from . import poly_t, plane_t @@ -41,7 +42,7 @@ def translate(poly: poly_t, shift: numpy.ndarray) -> poly_t: return poly -def scale(poly: poly_t, factor: numpy.ndarray or float) -> poly_t: +def scale(poly: poly_t, factor: Union[numpy.ndarray, float]) -> poly_t: ''' Scale the polyhedron. Can scale by a single value, or scale each axis individually diff --git a/adze/util.py b/adze/util.py index 4942379..6a2c6df 100644 --- a/adze/util.py +++ b/adze/util.py @@ -1,5 +1,5 @@ from typing import Dict, Tuple, List -import numpy +import numpy # type: ignore plane_t = Tuple[numpy.ndarray, float] @@ -92,11 +92,11 @@ def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]: # Alternative approach, less memory-intensive but slower faces = [[v] for v in v_current] - def add_edges(edge_id, v_nxt, _k): + def add_edges(edge_id, v_nxt, k): for i, vn in zip(edge_id, v_nxt): faces[i].append(vn) - def cleaned_faces(remove, _k): + def cleaned_faces(remove, k): faces_set = [] for i in numpy.where(~remove)[0]: faces_set.append(faces[i]) diff --git a/adze/voxel.py b/adze/voxel.py index 78e7096..6b35808 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -1,5 +1,5 @@ from typing import Tuple, List -import numpy +import numpy # type: ignore from . import poly_t, plane_t from .split import split, clip From 3499ed8c72aeb53f2153dec75840a72100077277 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 11 Jul 2021 17:24:13 -0700 Subject: [PATCH 15/69] update email --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index b2c6582..c057451 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,7 @@ setup(name='adze', version='0.1', description='Polyhedron clipping and antialiased voxelization', author='Jan Petykiewicz', - author_email='anewusername@gmail.com', + author_email='jan@mpxd.net', url='https://mpxd.net/code/jan/adze', keywords=[ 'geometry', From 2bb33188014d00fedf7b31ec3f770f25d10c0663 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Thu, 18 Aug 2022 23:47:26 -0700 Subject: [PATCH 16/69] move to hatch-based build --- MANIFEST.in | 2 -- adze/LICENSE.md | 1 + adze/README.md | 1 + adze/__init__.py | 2 ++ pyproject.toml | 46 ++++++++++++++++++++++++++++++++++++++++++++++ setup.py | 48 ------------------------------------------------ 6 files changed, 50 insertions(+), 50 deletions(-) delete mode 100644 MANIFEST.in create mode 120000 adze/LICENSE.md create mode 120000 adze/README.md create mode 100644 pyproject.toml delete mode 100644 setup.py diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index c28ab72..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -include README.md -include LICENSE.md diff --git a/adze/LICENSE.md b/adze/LICENSE.md new file mode 120000 index 0000000..7eabdb1 --- /dev/null +++ b/adze/LICENSE.md @@ -0,0 +1 @@ +../LICENSE.md \ No newline at end of file diff --git a/adze/README.md b/adze/README.md new file mode 120000 index 0000000..32d46ee --- /dev/null +++ b/adze/README.md @@ -0,0 +1 @@ +../README.md \ No newline at end of file diff --git a/adze/__init__.py b/adze/__init__.py index afffb3e..34a5a11 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -61,3 +61,5 @@ 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 +__author__ = 'Jan Petykiewicz' +__version__ = '0.1' diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a3535b3 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,46 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "adze" +description = "Polyhedron clipping and antialiased voxelization" +readme = "README.md" +license = { file = "LICENSE.md" } +authors = [ + { name="Jan Petykiewicz", email="jan@mpxd.net" }, + ] +homepage = "https://mpxd.net/code/jan/adze" +repository = "https://mpxd.net/code/jan/adze" +keywords = [ + "geometry", + "geometric", + "polyhedron", + "voxel", + "voxelize", + "clip", + "clipping", + "split", + "moment", + "schlegel", + "3D", + "boolean", + ] +classifiers = [ + "Programming Language :: Python :: 3", + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: GNU Affero General Public License v3", + "Operating System :: OS Independent", + "Topic :: Multimedia :: Graphics", + "Topic :: Scientific/Engineering", + ] +requires-python = ">=3.8" +dynamic = ["version"] +dependencies = [ + "numpy~=1.21", + ] + +[tool.hatch.version] +path = "adze/__init__.py" diff --git a/setup.py b/setup.py deleted file mode 100644 index c057451..0000000 --- a/setup.py +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env python3 - -from setuptools import setup, find_packages - -setup(name='adze', - version='0.1', - description='Polyhedron clipping and antialiased voxelization', - author='Jan Petykiewicz', - author_email='jan@mpxd.net', - url='https://mpxd.net/code/jan/adze', - keywords=[ - 'geometry', - 'geometric', - 'polyhedron', - 'voxel', - 'voxelize', - 'clip', - 'clipping', - 'split', - 'moment', - 'schlegel', - '3D', - 'boolean', - ], - classifiers=[ - 'Programming Language :: Python', - 'Programming Language :: Python :: 3', - 'Development Status :: 4 - Beta', - 'Environment :: Other Environment', - 'Intended Audience :: Developers', - 'Intended Audience :: Science/Research', - 'License :: OSI Approved', - 'License :: OSI Approved :: GNU Affero General Public License v3', - 'Operating System :: OS Independent', - 'Topic :: Multimedia :: Graphics', - 'Topic :: Scientific/Engineering', - 'Topic :: Scientific/Engineering :: Mathematics', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - packages=find_packages(), - install_requires=[ - 'typing', - 'numpy', - ], - extras_require={ - }, - ) - From 09ce6d67222a663ed5cd0b0607a33a1b29b61203 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Thu, 18 Aug 2022 23:49:48 -0700 Subject: [PATCH 17/69] stop ignoring numpy types --- adze/boundary.py | 4 ++-- adze/moments.py | 2 +- adze/shapes.py | 4 ++-- adze/split.py | 2 +- adze/test/test_benchmarks.py | 4 ++-- adze/test/test_split.py | 6 +++--- adze/test/test_voxel.py | 6 +++--- adze/test/utils.py | 4 ++-- adze/transform.py | 2 +- adze/util.py | 2 +- adze/voxel.py | 2 +- 11 files changed, 19 insertions(+), 19 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index 427f984..4263e3d 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -1,6 +1,6 @@ from typing import List, Dict, Any -import numpy # type: ignore -from numpy.linalg import norm # type: ignore +import numpy +from numpy.linalg import norm from . import poly_t, plane_t from .util import _get_maps, find_components, find_faces diff --git a/adze/moments.py b/adze/moments.py index 2c2aafd..93b79d3 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -1,5 +1,5 @@ from typing import Dict, Tuple -import numpy # type: ignore +import numpy from . import poly_t, plane_t from .util import find_faces diff --git a/adze/shapes.py b/adze/shapes.py index c9215c7..20f422e 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -1,6 +1,6 @@ from typing import List -import numpy # type: ignore -from numpy.linalg import norm # type: ignore +import numpy +from numpy.linalg import norm from . import poly_t, plane_t diff --git a/adze/split.py b/adze/split.py index 201171c..32e807b 100644 --- a/adze/split.py +++ b/adze/split.py @@ -1,5 +1,5 @@ from typing import Tuple, Union -import numpy # type: ignore +import numpy from . import poly_t, plane_t from .util import build_empty, _get_map diff --git a/adze/test/test_benchmarks.py b/adze/test/test_benchmarks.py index dfeca5d..f899353 100644 --- a/adze/test/test_benchmarks.py +++ b/adze/test/test_benchmarks.py @@ -8,9 +8,9 @@ from time import perf_counter import random import logging -import numpy # type: ignore +import numpy from numpy import sin, cos, pi -from numpy.linalg import norm # type: ignore +from numpy.linalg import norm import adze import adze.util diff --git a/adze/test/test_split.py b/adze/test/test_split.py index 0671fe0..3e8b197 100644 --- a/adze/test/test_split.py +++ b/adze/test/test_split.py @@ -1,9 +1,9 @@ import logging import pytest from pytest import approx -import numpy # type: ignore -from numpy.linalg import norm # type: ignore -from numpy.testing import assert_allclose, assert_array_equal # type: ignore +import numpy +from numpy.linalg import norm +from numpy.testing import assert_allclose, assert_array_equal import adze import adze.util diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py index 4dabdeb..f433f28 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -1,9 +1,9 @@ import logging import pytest from pytest import approx -import numpy # type: ignore -from numpy.linalg import norm # type: ignore -from numpy.testing import assert_allclose, assert_array_equal # type: ignore +import numpy +from numpy.linalg import norm +from numpy.testing import assert_allclose, assert_array_equal from time import perf_counter import adze diff --git a/adze/test/utils.py b/adze/test/utils.py index 0613fa2..f99c9f0 100644 --- a/adze/test/utils.py +++ b/adze/test/utils.py @@ -1,6 +1,6 @@ -import numpy # type: ignore +import numpy from numpy import pi, cos, sin -from numpy.linalg import norm # type: ignore +from numpy.linalg import norm import random import adze diff --git a/adze/transform.py b/adze/transform.py index df83cd5..1b3f91d 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -1,5 +1,5 @@ from typing import Union -import numpy # type: ignore +import numpy from numpy import sin, cos from . import poly_t, plane_t diff --git a/adze/util.py b/adze/util.py index 6a2c6df..0d0b24b 100644 --- a/adze/util.py +++ b/adze/util.py @@ -1,5 +1,5 @@ from typing import Dict, Tuple, List -import numpy # type: ignore +import numpy plane_t = Tuple[numpy.ndarray, float] diff --git a/adze/voxel.py b/adze/voxel.py index 6b35808..78e7096 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -1,5 +1,5 @@ from typing import Tuple, List -import numpy # type: ignore +import numpy from . import poly_t, plane_t from .split import split, clip From 140dccfbe52378b893320b5772dd020fc0f9d700 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Thu, 18 Aug 2022 23:50:04 -0700 Subject: [PATCH 18/69] drop unused import --- adze/test/test_benchmarks.py | 1 - 1 file changed, 1 deletion(-) diff --git a/adze/test/test_benchmarks.py b/adze/test/test_benchmarks.py index f899353..f4306a5 100644 --- a/adze/test/test_benchmarks.py +++ b/adze/test/test_benchmarks.py @@ -5,7 +5,6 @@ TODO: Consider using pytest-benchmark? """ import warnings from time import perf_counter -import random import logging import numpy From 073f233775be201c226ea262932e4b8f121ec937 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Fri, 19 Aug 2022 00:17:49 -0700 Subject: [PATCH 19/69] Fixup numpy typing info --- adze/boundary.py | 31 +++++++++++++++++-------------- adze/moments.py | 3 ++- adze/shapes.py | 14 ++++++++------ adze/split.py | 2 +- adze/transform.py | 8 +++++--- adze/util.py | 15 ++++++++------- adze/voxel.py | 17 +++++++++-------- 7 files changed, 50 insertions(+), 40 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index 4263e3d..bef0e7a 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -1,13 +1,14 @@ from typing import List, Dict, Any 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 -def planes_from_boundary(vertices: numpy.ndarray, - faces: List[numpy.ndarray] +def planes_from_boundary(vertices: ArrayLike, + faces: List[ArrayLike] ) -> List[plane_t]: ''' Generate a list of planes (normal, signed distance) from the faces of a boundary- @@ -21,8 +22,10 @@ def planes_from_boundary(vertices: numpy.ndarray, Returns: List of planes, represented by (normal vector, signed distance to origin) tuples. ''' + vertices = numpy.array(vertices, copy=False) + afaces = [numpy.array(ff, copy=False) for ff in faces] planes = [] - for face in faces: + for face in afaces: face_verts = vertices[face] n = numpy.cross(numpy.diff(face_verts, n=1, axis=0), @@ -34,7 +37,7 @@ def planes_from_boundary(vertices: numpy.ndarray, return planes -def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: +def build_polyhedron(vertices: ArrayLike, faces: List[ArrayLike]) -> poly_t: ''' Generate a 3-verted-connected Schlegel diagram representation corresponding to the provided boundary-representation polyhedron. @@ -48,9 +51,9 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: Schelgel-representation polyhedron ''' vertices = numpy.array(vertices, dtype=float) - faces = [numpy.array(face, dtype=int) for face in faces] + afaces = [numpy.array(face, dtype=int) for face in faces] - edges_per_vertex = numpy.bincount(numpy.hstack(faces)) + edges_per_vertex = numpy.bincount(numpy.hstack(afaces)) if edges_per_vertex.min() < 3: raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges') @@ -59,8 +62,8 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: ''' 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: + neighbors = numpy.full_like(vertices, vertices.size, dtype=int) + for face in afaces: # Check if each vertex in this face is already linked to its next or previous face-neighbor prev_vert = numpy.roll(face, 1) next_vert = numpy.roll(face, -1) @@ -162,7 +165,7 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: Fill columns (1, 2) with original vertex inds (f#_next, f#_prev) ''' num_filled_rows = numpy.zeros(num_duplicates, dtype=int) - for face in faces: + for face in afaces: # assume a face can't use the same vertex twice v_inds = start[face] + num_filled_rows[face] neighbors[v_inds, 1] = numpy.roll(face, -1) @@ -196,18 +199,18 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: dst_mask = numpy.empty(num_duplicates, dtype=bool) for v in range(num_vertices): - s = start[v] - e = s + edges_per_vertex[v] + ss = start[v] + ee = ss + edges_per_vertex[v] src_mask.fill(False) - src_mask[e:] = target_vert[e:] == v # find rows which reference us + src_mask[ee:] = target_vert[ee:] == v # find rows which reference us src_vert = v0s[src_mask] # figure out their original vertex numbers if src_vert.size == 0: continue dst_mask.fill(False) - dst_mask[s:e] = target_vert[s:e] > v # mask out any references to verts >= current + dst_mask[ss:ee] = target_vert[ss:ee] > v # mask out any references to verts >= current dst_vert = target_vert[dst_mask] ma, mb = _get_maps(dst_vert, src_vert) @@ -275,7 +278,7 @@ def boundary_from_poly(poly: poly_t) -> List[Dict[str, Any]]: faces = find_faces(neighbors) num_components = owning_component.max() + 1 - components: List[List[numpy.ndarray]] = [[] for _ in range(num_components)] + components: List[List[NDArray[numpy.int_]]] = [[] for _ in range(num_components)] for face in faces: component_ind = owning_component[face[0]] components[component_ind].append(face) diff --git a/adze/moments.py b/adze/moments.py index 93b79d3..e61dd18 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -1,5 +1,6 @@ from typing import Dict, Tuple import numpy +from numpy.typing import NDArray from . import poly_t, plane_t from .util import find_faces @@ -31,7 +32,7 @@ def get_volume(poly: poly_t) -> float: return get_moments(poly, 0)[0] -def get_moments(poly: poly_t, order: int) -> numpy.ndarray: +def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]: ''' Calculates the moments of a polyhedron, up to the specified polynomial order. diff --git a/adze/shapes.py b/adze/shapes.py index 20f422e..cfd45b9 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -1,11 +1,12 @@ from typing import List import numpy from numpy.linalg import norm +from numpy.typing import ArrayLike from . import poly_t, plane_t -def build_tetrahedron(vertices: numpy.ndarray) -> poly_t: +def build_tetrahedron(vertices: ArrayLike) -> poly_t: ''' Build a Schelegel-representation tetrahedron. @@ -26,7 +27,7 @@ def build_tetrahedron(vertices: numpy.ndarray) -> poly_t: return poly -def build_box(box_corners: numpy.ndarray) -> poly_t: +def build_box(box_corners: ArrayLike) -> poly_t: ''' Build a Schelegel-representation box. @@ -48,6 +49,7 @@ def build_box(box_corners: numpy.ndarray) -> poly_t: [6, 3, 4], ] + box_corners = numpy.array(box_corners, copy=False) 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]], @@ -65,7 +67,7 @@ def build_box(box_corners: numpy.ndarray) -> poly_t: } -def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]: +def planes_from_box(box_corners: ArrayLike) -> List[plane_t]: ''' Construct a list of planes corresponding to the faces of a box. @@ -76,7 +78,7 @@ def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]: Returns: List of planes, facing inwards. ''' - box_corners = numpy.array(box_corners) + box_corners = numpy.array(box_corners, copy=False) faces = [ (( 0, 0, 1), -box_corners[0, 2]), (( 0, 0, -1), box_corners[1, 2]), @@ -89,7 +91,7 @@ def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]: return [(numpy.array(n), d) for n, d in faces] -def planes_from_tetrahedron(vertices: numpy.ndarray) -> List[plane_t]: +def planes_from_tetrahedron(vertices: ArrayLike) -> List[plane_t]: ''' Construct a list of planes corresponding to the faces of a tetrahedron. @@ -99,7 +101,7 @@ def planes_from_tetrahedron(vertices: numpy.ndarray) -> List[plane_t]: Returns: List of planes, facing inwards. ''' - verts = numpy.array(vertices, dtype=float) + verts = numpy.array(vertices, dtype=float, copy=False) vset_inds = numpy.array(( [3, 1, 2, 1], [2, 0, 3, 2], diff --git a/adze/split.py b/adze/split.py index 32e807b..9bed779 100644 --- a/adze/split.py +++ b/adze/split.py @@ -149,7 +149,7 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False): # figure out the index of each target edge using row-wise _get_map dims = [num_start, num_start] a1d = numpy.ravel_multi_index((rverts, lverts), dims) - b1d = numpy.ravel_multi_index(edge_walk_results, dims) + b1d = numpy.ravel_multi_index(tuple(edge_walk_results), dims) target_edge_inds = _get_map(a1d, b1d) diff --git a/adze/transform.py b/adze/transform.py index 1b3f91d..453494b 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -1,6 +1,7 @@ from typing import Union import numpy from numpy import sin, cos +from numpy.typing import ArrayLike from . import poly_t, plane_t @@ -26,7 +27,7 @@ def rotate(poly: poly_t, theta: float, axis: int) -> poly_t: return poly -def translate(poly: poly_t, shift: numpy.ndarray) -> poly_t: +def translate(poly: poly_t, shift: ArrayLike) -> poly_t: ''' Translate the polyhedron by a vector. @@ -42,7 +43,7 @@ def translate(poly: poly_t, shift: numpy.ndarray) -> poly_t: return poly -def scale(poly: poly_t, factor: Union[numpy.ndarray, float]) -> poly_t: +def scale(poly: poly_t, factor: Union[ArrayLike, float]) -> poly_t: ''' Scale the polyhedron. Can scale by a single value, or scale each axis individually @@ -59,7 +60,7 @@ def scale(poly: poly_t, factor: Union[numpy.ndarray, float]) -> poly_t: return poly -def affine(poly: poly_t, xform: numpy.ndarray) -> poly_t: +def affine(poly: poly_t, xform: ArrayLike) -> poly_t: ''' Perform arbitrary affine trasnformation on the polyhedron. @@ -71,6 +72,7 @@ def affine(poly: poly_t, xform: numpy.ndarray) -> poly_t: Transformed polyhedron. Data is altered in-place but also returned for convenience. ''' + xform = numpy.array(xform, copy=False) mat4x3 = xform[:, :3] mat4x1 = xform[:, 3] vh = mat4x3 @ poly['vertices'].T + mat4x1 diff --git a/adze/util.py b/adze/util.py index 0d0b24b..8bb1d3e 100644 --- a/adze/util.py +++ b/adze/util.py @@ -1,9 +1,10 @@ from typing import Dict, Tuple, List import numpy +from numpy.typing import ArrayLike, NDArray -plane_t = Tuple[numpy.ndarray, float] -poly_t = Dict[str, numpy.ndarray] +plane_t = Tuple[NDArray, float] +poly_t = Dict[str, NDArray] def build_empty() -> poly_t: @@ -19,7 +20,7 @@ def build_empty() -> poly_t: } -def find_components(neighbors: numpy.ndarray) -> numpy.ndarray: +def find_components(neighbors: NDArray[numpy.int_]) -> NDArray[numpy.int_]: ''' Given an adjacency list, flood-fill to find and label connected components. @@ -49,7 +50,7 @@ def find_components(neighbors: numpy.ndarray) -> numpy.ndarray: return component - 1 -def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]: +def find_faces(neighbors: NDArray[numpy.int_]) -> List[NDArray[numpy.int_]]: ''' Traverse the Schlegel diagram to find chordless cycles (i.e., faces of the polyhedron). Assumes 3-vertex-connected @@ -90,7 +91,7 @@ def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]: return faces_set else: # Alternative approach, less memory-intensive but slower - faces = [[v] for v in v_current] + faces = numpy.array([[v] for v in v_current], dtype=int) def add_edges(edge_id, v_nxt, k): for i, vn in zip(edge_id, v_nxt): @@ -201,7 +202,7 @@ def _searchsorted_rows(a, b): return numpy.searchsorted(a1d, b1d) -def check_poly(poly: poly_t, check_connectivity: bool = True): +def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: ''' Verify that the polyhedron - has no out-of-bounds neighbors @@ -269,7 +270,7 @@ def check_poly(poly: poly_t, check_connectivity: bool = True): raise Exception('Vertex graph is not 3-vertex-connected') -def plot_brep(brep): +def plot_brep(brep) -> None: """ Plot a boundary representation """ diff --git a/adze/voxel.py b/adze/voxel.py index 78e7096..99f64de 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -1,5 +1,6 @@ from typing import Tuple, List import numpy +from numpy.typing import ArrayLike, NDArray from . import poly_t, plane_t from .split import split, clip @@ -8,10 +9,10 @@ from .shapes import planes_from_box def voxelize(poly: poly_t, - planes: List[numpy.ndarray], + planes: List[ArrayLike], include_outside: bool = False, order: int = 0, - ) -> numpy.ndarray: + ) -> NDArray[numpy.float64]: ''' Voxelize a Schelegel-representation polyhedron on an arbitrary rectangular grid. @@ -39,9 +40,9 @@ def voxelize(poly: poly_t, correspond to portions of the polyhedron that protruded outside the outermost planes. N is `number_of_moments(order)`. ''' - planes = [numpy.array(p) for p in planes] + aplanes = [numpy.array(p, copy=False) for p in planes] - num_planes = numpy.array([e.size for e in planes], dtype=int) + num_planes = numpy.array([e.size for e in aplanes], dtype=int) if (num_planes < 2).any(): # TODO raw exception raise Exception(f'Need at least two planes per dimension. Got {num_planes} planes.') @@ -50,8 +51,8 @@ def voxelize(poly: poly_t, grid_shape = num_planes + 1 if not include_outside: grid_shape = num_planes - 1 - for face in planes_from_box([[p[0] for p in planes], - [p[-1] for p in planes]]): + for face in planes_from_box([[p[0] for p in aplanes], + [p[-1] for p in aplanes]]): poly = clip(poly, face) grid = numpy.zeros((*grid_shape, number_of_moments(order)), dtype=float) @@ -59,7 +60,7 @@ def voxelize(poly: poly_t, if poly['vertices'].shape[0] == 0: return grid - slices = numpy.array([(0, e.size) for e in planes], dtype=int) + slices = numpy.array([(0, e.size) for e in aplanes], dtype=int) stack = [(poly, slices)] while stack: poly, slices = stack.pop() @@ -80,7 +81,7 @@ def voxelize(poly: poly_t, # Recursion case: split along longest side axis = num_planes_remaining.argmax() plane_ind = num_planes_remaining[axis] // 2 + slices[axis, 0] - plane_pos = planes[axis][plane_ind] + plane_pos = aplanes[axis][plane_ind] plane = (numpy.roll([-1, 0, 0], axis), plane_pos) poly_left, poly_right = split(poly, plane) From 7d90a5db98eaaca6760cc897b12492abe0f8f959 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Fri, 19 Aug 2022 00:17:57 -0700 Subject: [PATCH 20/69] add stl to optional deps --- pyproject.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index a3535b3..bc0e248 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,3 +44,6 @@ dependencies = [ [tool.hatch.version] path = "adze/__init__.py" + +[project.optional-dependencies] +stl = ["stl"] From a34c052b6ea3296819669c67d463acd66b5eaece Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Fri, 19 Aug 2022 00:25:51 -0700 Subject: [PATCH 21/69] fix regression from overzealous typing --- adze/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adze/util.py b/adze/util.py index 8bb1d3e..a888c58 100644 --- a/adze/util.py +++ b/adze/util.py @@ -91,7 +91,7 @@ def find_faces(neighbors: NDArray[numpy.int_]) -> List[NDArray[numpy.int_]]: return faces_set else: # Alternative approach, less memory-intensive but slower - faces = numpy.array([[v] for v in v_current], dtype=int) + faces = [[v] for v in v_current] def add_edges(edge_id, v_nxt, k): for i, vn in zip(edge_id, v_nxt): From b9018a74619d21a387ea50ceccbaf51efc170155 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Fri, 19 Aug 2022 00:25:58 -0700 Subject: [PATCH 22/69] add missing call to _split() --- adze/split.py | 1 + 1 file changed, 1 insertion(+) diff --git a/adze/split.py b/adze/split.py index 9bed779..8e07b1a 100644 --- a/adze/split.py +++ b/adze/split.py @@ -36,6 +36,7 @@ def split(poly: poly_t, plane: plane_t) -> Tuple[poly_t, poly_t]: 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) def _split(poly: poly_t, plane: plane_t, same_only: bool = False): From f38e27d33d9e47bfbed72d3efb36cd4b37ca58f7 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Fri, 19 Aug 2022 00:27:52 -0700 Subject: [PATCH 23/69] use alternate arg formatting --- adze/boundary.py | 7 ++++--- adze/voxel.py | 11 ++++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index bef0e7a..1c31ba1 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -7,9 +7,10 @@ from . import poly_t, plane_t from .util import _get_maps, find_components, find_faces -def planes_from_boundary(vertices: ArrayLike, - faces: List[ArrayLike] - ) -> List[plane_t]: +def planes_from_boundary( + vertices: ArrayLike, + faces: List[ArrayLike] + ) -> List[plane_t]: ''' Generate a list of planes (normal, signed distance) from the faces of a boundary- representation polyhedron. diff --git a/adze/voxel.py b/adze/voxel.py index 99f64de..38851e7 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -8,11 +8,12 @@ from .moments import get_moments, number_of_moments from .shapes import planes_from_box -def voxelize(poly: poly_t, - planes: List[ArrayLike], - include_outside: bool = False, - order: int = 0, - ) -> NDArray[numpy.float64]: +def voxelize( + poly: poly_t, + planes: List[ArrayLike], + include_outside: bool = False, + order: int = 0, + ) -> NDArray[numpy.float64]: ''' Voxelize a Schelegel-representation polyhedron on an arbitrary rectangular grid. From 6f5335dcc1e49c4a5ec840634cf5bdaaac31d77b Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 30 Jul 2024 23:45:47 -0700 Subject: [PATCH 24/69] type annotation improvements --- adze/boundary.py | 12 ++++++------ adze/moments.py | 1 - adze/shapes.py | 5 ++--- adze/split.py | 3 +-- adze/test/test_voxel.py | 21 ++++++++++++++------- adze/transform.py | 3 +-- adze/util.py | 22 +++++++++++----------- adze/voxel.py | 6 +++--- 8 files changed, 38 insertions(+), 35 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index 1c31ba1..03ee744 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -1,4 +1,4 @@ -from typing import List, Dict, Any +from typing import Any import numpy from numpy.linalg import norm from numpy.typing import ArrayLike, NDArray @@ -9,8 +9,8 @@ from .util import _get_maps, find_components, find_faces def planes_from_boundary( vertices: ArrayLike, - faces: List[ArrayLike] - ) -> List[plane_t]: + faces: list[ArrayLike] + ) -> list[plane_t]: ''' Generate a list of planes (normal, signed distance) from the faces of a boundary- representation polyhedron. @@ -38,7 +38,7 @@ def planes_from_boundary( return planes -def build_polyhedron(vertices: ArrayLike, faces: List[ArrayLike]) -> poly_t: +def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: ''' Generate a 3-verted-connected Schlegel diagram representation corresponding to the provided boundary-representation polyhedron. @@ -259,7 +259,7 @@ def build_polyhedron(vertices: ArrayLike, faces: List[ArrayLike]) -> poly_t: return {'vertices': final_vertices, 'neighbors': neighbors} -def boundary_from_poly(poly: poly_t) -> List[Dict[str, Any]]: +def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: ''' Generate a boundary represeentation corresponding to the provided 3-vertex-connected Schlegel diagram. @@ -279,7 +279,7 @@ def boundary_from_poly(poly: poly_t) -> List[Dict[str, Any]]: faces = find_faces(neighbors) num_components = owning_component.max() + 1 - components: List[List[NDArray[numpy.int_]]] = [[] for _ in range(num_components)] + components: list[list[NDArray[numpy.integer]]] = [[] for _ in range(num_components)] for face in faces: component_ind = owning_component[face[0]] components[component_ind].append(face) diff --git a/adze/moments.py b/adze/moments.py index e61dd18..c3a81e9 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -1,4 +1,3 @@ -from typing import Dict, Tuple import numpy from numpy.typing import NDArray diff --git a/adze/shapes.py b/adze/shapes.py index cfd45b9..fd42c69 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -1,4 +1,3 @@ -from typing import List import numpy from numpy.linalg import norm from numpy.typing import ArrayLike @@ -67,7 +66,7 @@ def build_box(box_corners: ArrayLike) -> poly_t: } -def planes_from_box(box_corners: ArrayLike) -> List[plane_t]: +def planes_from_box(box_corners: ArrayLike) -> list[plane_t]: ''' Construct a list of planes corresponding to the faces of a box. @@ -91,7 +90,7 @@ 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: ArrayLike) -> list[plane_t]: ''' Construct a list of planes corresponding to the faces of a tetrahedron. diff --git a/adze/split.py b/adze/split.py index 8e07b1a..b43310f 100644 --- a/adze/split.py +++ b/adze/split.py @@ -1,4 +1,3 @@ -from typing import Tuple, Union import numpy from . import poly_t, plane_t @@ -23,7 +22,7 @@ def clip(poly: poly_t, plane: plane_t) -> poly_t: return left_poly -def split(poly: poly_t, plane: plane_t) -> Tuple[poly_t, poly_t]: +def split(poly: poly_t, plane: plane_t) -> tuple[poly_t, poly_t]: ''' Clip a polyhedron with a plane, keeping both parts. diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py index f433f28..ead5b04 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -1,10 +1,12 @@ +from typing import TYPE_CHECKING import logging +import warnings +from time import perf_counter import pytest from pytest import approx import numpy from numpy.linalg import norm from numpy.testing import assert_allclose, assert_array_equal -from time import perf_counter import adze import adze.util @@ -12,11 +14,14 @@ 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, rand_tetrahedron_vertices +if TYPE_CHECKING: + import matplotlib + logger = logging.getLogger(__name__) -def test_voxelization(poly_order, grid_resolution=None): +def test_voxelization(poly_order: int, grid_resolution: int | None = None) -> None: """ Test that the voxelized moments sum to those of the original input """ @@ -42,11 +47,13 @@ def test_voxelization(poly_order, grid_resolution=None): warnings.warn('Moments failed tolerance in voxels') -def visualize_isosurface(grid, - edges, - level: float = None, - show_edges: bool = True, - finalize: bool = True): +def visualize_isosurface( + grid, + edges, + level: float | None = None, + show_edges: bool = True, + finalize: bool = True, + ) -> tuple['matplotlib.Figure', 'matplotlib.Axes']: """ Draw an isosurface plot of the device. diff --git a/adze/transform.py b/adze/transform.py index 453494b..6150d80 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -1,4 +1,3 @@ -from typing import Union import numpy from numpy import sin, cos from numpy.typing import ArrayLike @@ -43,7 +42,7 @@ def translate(poly: poly_t, shift: ArrayLike) -> poly_t: return poly -def scale(poly: poly_t, factor: Union[ArrayLike, float]) -> poly_t: +def scale(poly: poly_t, factor: ArrayLike | float) -> poly_t: ''' Scale the polyhedron. Can scale by a single value, or scale each axis individually diff --git a/adze/util.py b/adze/util.py index a888c58..15862c4 100644 --- a/adze/util.py +++ b/adze/util.py @@ -1,10 +1,9 @@ -from typing import Dict, Tuple, List import numpy from numpy.typing import ArrayLike, NDArray -plane_t = Tuple[NDArray, float] -poly_t = Dict[str, NDArray] +plane_t = tuple[NDArray, float] +poly_t = dict[str, NDArray] def build_empty() -> poly_t: @@ -20,8 +19,8 @@ def build_empty() -> poly_t: } -def find_components(neighbors: NDArray[numpy.int_]) -> NDArray[numpy.int_]: - ''' +def find_components(neighbors: NDArray[numpy.integer]) -> NDArray[numpy.integer]: + """ Given an adjacency list, flood-fill to find and label connected components. Args: @@ -32,7 +31,7 @@ def find_components(neighbors: NDArray[numpy.int_]) -> NDArray[numpy.int_]: Returns: 1D ndarray with N entries. Entries are integer labels denoting which connected component the vertex belongs to. - ''' + """ num_vertices = neighbors.shape[0] current_component = 1 component = numpy.zeros(num_vertices, dtype=int) @@ -50,8 +49,8 @@ def find_components(neighbors: NDArray[numpy.int_]) -> NDArray[numpy.int_]: return component - 1 -def find_faces(neighbors: NDArray[numpy.int_]) -> List[NDArray[numpy.int_]]: - ''' +def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.integer]]: + """ Traverse the Schlegel diagram to find chordless cycles (i.e., faces of the polyhedron). Assumes 3-vertex-connected graph with exactly 3 neighbors per vertex. Neighbors are ordered @@ -64,7 +63,7 @@ def find_faces(neighbors: NDArray[numpy.int_]) -> List[NDArray[numpy.int_]]: Returns: List of ndarrays, each of which contains the indices in a given face, starting with the lowest index in the face. - ''' + """ num_verts = neighbors.shape[0] edge_id = numpy.arange(3 * num_verts) @@ -72,10 +71,11 @@ def find_faces(neighbors: NDArray[numpy.int_]) -> List[NDArray[numpy.int_]]: v_current = v_start.copy() v_next = neighbors[v_current, nxt_edge] - ''' + """ Choose a method for storing the face info based on expected runtime vs unnecessary memory allocation - ''' + """ + faces: list[list[NDArray[numpy.integer]]] | NDArray[numpy.integer] if num_verts < 1000: # ~3n^2 in memory, but much faster in cases where n isn't prohibitively large faces = numpy.full((3*num_verts, num_verts-1), -1, dtype=int) diff --git a/adze/voxel.py b/adze/voxel.py index 38851e7..3e1e8fa 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -1,4 +1,4 @@ -from typing import Tuple, List +from collections.abc import Sequence import numpy from numpy.typing import ArrayLike, NDArray @@ -10,7 +10,7 @@ from .shapes import planes_from_box def voxelize( poly: poly_t, - planes: List[ArrayLike], + planes: Sequence[ArrayLike], include_outside: bool = False, order: int = 0, ) -> NDArray[numpy.float64]: @@ -41,7 +41,7 @@ def voxelize( correspond to portions of the polyhedron that protruded outside the outermost planes. N is `number_of_moments(order)`. ''' - aplanes = [numpy.array(p, copy=False) for p in planes] + aplanes = [numpy.asarray(p) for p in planes] num_planes = numpy.array([e.size for e in aplanes], dtype=int) if (num_planes < 2).any(): From 3abf1e137fa124573081819196db6c4c959a9f2e Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 30 Jul 2024 23:46:10 -0700 Subject: [PATCH 25/69] use asarray() in place of array(copy=False) --- adze/boundary.py | 4 ++-- adze/shapes.py | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index 03ee744..73de8b2 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -23,8 +23,8 @@ def planes_from_boundary( Returns: List of planes, represented by (normal vector, signed distance to origin) tuples. ''' - vertices = numpy.array(vertices, copy=False) - afaces = [numpy.array(ff, copy=False) for ff in faces] + vertices = numpy.asarray(vertices) + afaces = [numpy.asarray(ff) for ff in faces] planes = [] for face in afaces: face_verts = vertices[face] diff --git a/adze/shapes.py b/adze/shapes.py index fd42c69..ef313c2 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -48,7 +48,7 @@ def build_box(box_corners: ArrayLike) -> poly_t: [6, 3, 4], ] - box_corners = numpy.array(box_corners, copy=False) + box_corners = numpy.asarray(box_corners) vertices = [ [box_corners[0, 0], box_corners[0, 1], box_corners[0, 2]], [box_corners[1, 0], box_corners[0, 1], box_corners[0, 2]], @@ -77,7 +77,7 @@ def planes_from_box(box_corners: ArrayLike) -> list[plane_t]: Returns: List of planes, facing inwards. ''' - box_corners = numpy.array(box_corners, copy=False) + box_corners = numpy.asarray(box_corners) faces = [ (( 0, 0, 1), -box_corners[0, 2]), (( 0, 0, -1), box_corners[1, 2]), @@ -100,7 +100,7 @@ def planes_from_tetrahedron(vertices: ArrayLike) -> list[plane_t]: Returns: List of planes, facing inwards. ''' - verts = numpy.array(vertices, dtype=float, copy=False) + verts = numpy.asarray(vertices, dtype=float) vset_inds = numpy.array(( [3, 1, 2, 1], [2, 0, 3, 2], From 2fdafc1f69b336b571bd8addec9def0f2851251e Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 30 Jul 2024 23:46:21 -0700 Subject: [PATCH 26/69] use double quotes for docstrings --- adze/util.py | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/adze/util.py b/adze/util.py index 15862c4..693c228 100644 --- a/adze/util.py +++ b/adze/util.py @@ -7,12 +7,12 @@ poly_t = dict[str, NDArray] def build_empty() -> poly_t: - ''' + """ Build an empty Schlegel representation (containing no vertices). Returns: Empty Schelegel representation. - ''' + """ return { 'vertices': numpy.empty((0, 3), dtype=float), 'neighbors': numpy.empty((0, 3), dtype=int), @@ -103,13 +103,13 @@ def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.integer] faces_set.append(faces[i]) return faces_set - ''' + """ Starting at all vertices, take a step along all edges. If the vertex index decreases, stop traversal and mark the path for removal. Otherwise, continue stepping along the _next_ edge each time, until a) the vertex index decreases (stop and mark for removal) b) we reach the original vertex (stop, done with this path) - ''' + """ k = 1 mask = v_next > v_current v = numpy.vstack((edge_id, v_start, v_current, v_next))[:, mask] @@ -133,10 +133,10 @@ def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.integer] def _get_map(a, b): - ''' + """ Returns m such that a[m] == b Assumes that all elements appear exactly once in each array - ''' + """ if a.size == 0: return numpy.array(()), numpy.array(()) sa = a.argsort() @@ -147,9 +147,9 @@ def _get_map(a, b): def _get_map_rows(a, b): - ''' + """ Row-wise _get_map - ''' + """ dims = numpy.maximum(a.max(0), b.max(0)) + 1 a1d = numpy.ravel_multi_index(a.T, dims) b1d = numpy.ravel_multi_index(b.T, dims) @@ -157,10 +157,10 @@ def _get_map_rows(a, b): def _get_maps(a, b): - ''' + """ Returns m, n such that a[m] == b, b[n] == a Assumes that all elements appear exactly once in each array - ''' + """ if a.size == 0: return numpy.array(()), numpy.array(()) sa = a.argsort() @@ -174,9 +174,9 @@ def _get_maps(a, b): def _get_maps_rows(a, b): - ''' + """ Row-wise _get_maps - ''' + """ dims = numpy.maximum(a.max(0), b.max(0)) + 1 a1d = numpy.ravel_multi_index(a.T, dims) b1d = numpy.ravel_multi_index(b.T, dims) @@ -184,18 +184,18 @@ def _get_maps_rows(a, b): def _argsort_rows(a): - ''' + """ Row-wise argsort - ''' + """ dims = a.max(0) + 1 a1d = numpy.ravel_multi_index(a.T, dims) return numpy.argsort(a1d) def _searchsorted_rows(a, b): - ''' + """ Row-wise searchsorted - ''' + """ dims = numpy.maximum(a.max(0), b.max(0)) + 1 a1d = numpy.ravel_multi_index(a.T, dims) b1d = numpy.ravel_multi_index(b.T, dims) @@ -203,7 +203,7 @@ def _searchsorted_rows(a, b): def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: - ''' + """ Verify that the polyhedron - has no out-of-bounds neighbors - has no duplicate neighbors @@ -217,7 +217,7 @@ def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: Raises: Exception if the polyhedron fails a check - ''' + """ neighbors = poly['neighbors'] vertices = poly['vertices'] num_vertices = vertices.shape[0] From dbe915febaf28bb4cb22beaf841f984e20cbe6d1 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 30 Jul 2024 23:46:43 -0700 Subject: [PATCH 27/69] marching_cubes_lewiner was deprecated --- adze/test/test_voxel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py index ead5b04..735eab9 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -71,7 +71,7 @@ def visualize_isosurface( level = grid.mean() # Find isosurface with marching cubes - verts, faces, _normals, _values = skimage.measure.marching_cubes_lewiner(grid, level) + verts, faces, _normals, _values = skimage.measure.marching_cubes(grid, level) xs, ys, zs = (edges[aa][verts[:, aa].astype(int)] for aa in range(3)) From 9d7fd2af6babcdf6ff54e102e44e3560d378ddc3 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 30 Jul 2024 23:55:41 -0700 Subject: [PATCH 28/69] comment styles --- adze/__init__.py | 4 ++-- adze/boundary.py | 51 ++++++++++++++++++++++++----------------------- adze/moments.py | 30 ++++++++++++++-------------- adze/shapes.py | 16 +++++++-------- adze/split.py | 48 ++++++++++++++++++++++---------------------- adze/transform.py | 16 +++++++-------- adze/voxel.py | 4 ++-- 7 files changed, 85 insertions(+), 84 deletions(-) diff --git a/adze/__init__.py b/adze/__init__.py index 34a5a11..de3636f 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -1,4 +1,4 @@ -''' +""" adze is a library for accurate polyhedron clipping and anti-aliased voxelization. Written with python + numpy. @@ -51,7 +51,7 @@ In the polyhedron representation returned by the build_* functions and accepted poly = {'neighbors': ndarray[Px3, int], 'vertices': ndarray[Px3, float]} where poly['neighbors'] contains -''' +""" from .util import poly_t, plane_t diff --git a/adze/boundary.py b/adze/boundary.py index 73de8b2..c6aefcc 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -11,7 +11,7 @@ def planes_from_boundary( vertices: ArrayLike, faces: list[ArrayLike] ) -> list[plane_t]: - ''' + """ Generate a list of planes (normal, signed distance) from the faces of a boundary- representation polyhedron. @@ -22,7 +22,7 @@ def planes_from_boundary( Returns: List of planes, represented by (normal vector, signed distance to origin) tuples. - ''' + """ vertices = numpy.asarray(vertices) afaces = [numpy.asarray(ff) for ff in faces] planes = [] @@ -39,7 +39,7 @@ def planes_from_boundary( def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: - ''' + """ Generate a 3-verted-connected Schlegel diagram representation corresponding to the provided boundary-representation polyhedron. @@ -50,7 +50,7 @@ def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: Returns: Schelgel-representation polyhedron - ''' + """ vertices = numpy.array(vertices, dtype=float) afaces = [numpy.array(face, dtype=int) for face in faces] @@ -60,9 +60,9 @@ def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges') if edges_per_vertex.max() == 3: - ''' - In this case, we don't need to duplicate any vertices to make a 3-vertex-connected graph - ''' + # + # In this case, we don't need to duplicate any vertices to make a 3-vertex-connected graph + # neighbors = numpy.full_like(vertices, vertices.size, dtype=int) for face in afaces: # Check if each vertex in this face is already linked to its next or previous face-neighbor @@ -90,7 +90,7 @@ def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: 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. @@ -151,7 +151,8 @@ def build_polyhedron(vertices: ArrayLike, faces: list[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 @@ -162,9 +163,9 @@ def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: 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: # assume a face can't use the same vertex twice @@ -173,10 +174,10 @@ def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: 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]) @@ -184,11 +185,11 @@ def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: 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) @@ -218,9 +219,9 @@ def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: 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 @@ -260,7 +261,7 @@ def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: - ''' + """ Generate a boundary represeentation corresponding to the provided 3-vertex-connected Schlegel diagram. @@ -271,7 +272,7 @@ def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: 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'] diff --git a/adze/moments.py b/adze/moments.py index c3a81e9..0f7dcbc 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -6,7 +6,7 @@ from .util import find_faces def number_of_moments(order: int) -> int: - ''' + """ Returns the number of moments with a given order or below. Args: @@ -14,12 +14,12 @@ def number_of_moments(order: int) -> int: Returns: 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: @@ -27,12 +27,12 @@ def get_volume(poly: poly_t) -> float: Returns: Volume of the polyhedron. - ''' + """ return get_moments(poly, 0)[0] def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]: - ''' + """ Calculates the moments of a polyhedron, up to the specified polynomial order. Args: @@ -41,7 +41,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, ...] - ''' + """ vertices = poly['vertices'] neighbors = poly['neighbors'] num_verts = vertices.shape[0] @@ -49,9 +49,9 @@ def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]: if num_verts == 0: return numpy.array([0], dtype=float) - ''' - Decompose polyhedron into triangle fans - ''' + # + # Decompose polyhedron into triangle fans + # faces = find_faces(neighbors) triangle_fans = [] @@ -67,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]) @@ -77,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') diff --git a/adze/shapes.py b/adze/shapes.py index ef313c2..89f24aa 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -6,7 +6,7 @@ from . import poly_t, plane_t def build_tetrahedron(vertices: ArrayLike) -> poly_t: - ''' + """ Build a Schelegel-representation tetrahedron. Args: @@ -14,7 +14,7 @@ def build_tetrahedron(vertices: ArrayLike) -> poly_t: Returns: Tetrahedron in Schelgel representation. - ''' + """ poly = { 'vertices': numpy.array(vertices, dtype=float), 'neighbors': numpy.array(( @@ -27,7 +27,7 @@ def build_tetrahedron(vertices: ArrayLike) -> poly_t: def build_box(box_corners: ArrayLike) -> poly_t: - ''' + """ Build a Schelegel-representation box. Args: @@ -36,7 +36,7 @@ def build_box(box_corners: ArrayLike) -> poly_t: Returns: Box in Schelgel representation. - ''' + """ neighbors = [ [1, 4, 3], [2, 5, 0], @@ -67,7 +67,7 @@ def build_box(box_corners: ArrayLike) -> poly_t: def planes_from_box(box_corners: ArrayLike) -> list[plane_t]: - ''' + """ Construct a list of planes corresponding to the faces of a box. Args: @@ -76,7 +76,7 @@ def planes_from_box(box_corners: ArrayLike) -> list[plane_t]: Returns: List of planes, facing inwards. - ''' + """ box_corners = numpy.asarray(box_corners) faces = [ (( 0, 0, 1), -box_corners[0, 2]), @@ -91,7 +91,7 @@ def planes_from_box(box_corners: ArrayLike) -> list[plane_t]: def planes_from_tetrahedron(vertices: ArrayLike) -> list[plane_t]: - ''' + """ Construct a list of planes corresponding to the faces of a tetrahedron. Args: @@ -99,7 +99,7 @@ def planes_from_tetrahedron(vertices: ArrayLike) -> list[plane_t]: Returns: List of planes, facing inwards. - ''' + """ verts = numpy.asarray(vertices, dtype=float) vset_inds = numpy.array(( [3, 1, 2, 1], diff --git a/adze/split.py b/adze/split.py index b43310f..6b2be0b 100644 --- a/adze/split.py +++ b/adze/split.py @@ -5,7 +5,7 @@ from .util import build_empty, _get_map 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. @@ -17,13 +17,13 @@ def clip(poly: poly_t, plane: plane_t) -> poly_t: Returns: Clipped polyhedron. - ''' + """ left_poly = _split(poly, plane, same_only=True) return left_poly def split(poly: poly_t, plane: plane_t) -> 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). @@ -34,12 +34,12 @@ def split(poly: poly_t, plane: plane_t) -> tuple[poly_t, poly_t]: 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) def _split(poly: poly_t, plane: plane_t, 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), @@ -54,7 +54,7 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False): Returns: (same_side_poly, other_side_poly) if same_only is False (default), otherwise only returns same_side_poly. - ''' + """ vertices = poly['vertices'] neighbors = poly['neighbors'] num_start = neighbors.shape[0] @@ -66,9 +66,9 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False): 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 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 @@ -86,9 +86,9 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False): far_vertex_left = left[next_vertex] if not far_vertex_left.any(): - ''' - No edges cross the plane, but components exist on either side - ''' + # + # 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) @@ -97,9 +97,9 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False): 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] @@ -107,16 +107,16 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False): num_new_vertices = rverts.size - ''' - figure out new vertex positions - ''' + # + # figure out new vertex positions + # d_right = dists[rverts][:, None] d_left = dists[lverts][:, None] new_vertices = (d_right * vertices[lverts] - d_left * vertices[rverts]) / (d_right - d_left) - ''' - walk to next crossing edge - ''' + # + # walk to next crossing edge + # prev_verts = rverts cur_verts = lverts edge_walk_inds = numpy.arange(num_new_vertices) @@ -153,9 +153,9 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False): target_edge_inds = _get_map(a1d, b1d) - ''' - map from old vertex ind to new - ''' + # + # map from old vertex ind to new + # ind_map_left = numpy.zeros(num_start, dtype=int) # current side vertices get new (equal or lower) indices from delete operation, remain in same order ind_map_left[left] = numpy.arange(num_left) diff --git a/adze/transform.py b/adze/transform.py index 6150d80..6b05130 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -6,7 +6,7 @@ from . import poly_t, plane_t def rotate(poly: poly_t, theta: float, axis: int) -> poly_t: - ''' + """ Rotate the polyhedron around an axis. Args: @@ -17,7 +17,7 @@ def rotate(poly: poly_t, theta: float, axis: int) -> poly_t: Returns: Rotated polyhedron. Data is altered in-place but also returned for convenience. - ''' + """ s, c = sin(theta), cos(theta) v0 = poly['vertices'][:, axis - 2].copy() v1 = poly['vertices'][:, axis - 1] @@ -27,7 +27,7 @@ def rotate(poly: poly_t, theta: float, axis: int) -> poly_t: def translate(poly: poly_t, shift: ArrayLike) -> poly_t: - ''' + """ Translate the polyhedron by a vector. Args: @@ -37,13 +37,13 @@ def translate(poly: poly_t, shift: ArrayLike) -> poly_t: Returns: Translated polyhedron. Data is altered in-place but also returned for convenience. - ''' + """ poly['vertices'] += shift return poly def scale(poly: poly_t, factor: ArrayLike | float) -> poly_t: - ''' + """ Scale the polyhedron. Can scale by a single value, or scale each axis individually @@ -54,13 +54,13 @@ def scale(poly: poly_t, factor: ArrayLike | float) -> poly_t: Returns: Scaled polyhedron. Data is altered in-place but also returned for convenience. - ''' + """ poly['vertices'] *= factor return poly def affine(poly: poly_t, xform: ArrayLike) -> poly_t: - ''' + """ Perform arbitrary affine trasnformation on the polyhedron. Args: @@ -70,7 +70,7 @@ def affine(poly: poly_t, xform: ArrayLike) -> poly_t: Returns: Transformed polyhedron. Data is altered in-place but also returned for convenience. - ''' + """ xform = numpy.array(xform, copy=False) mat4x3 = xform[:, :3] mat4x1 = xform[:, 3] diff --git a/adze/voxel.py b/adze/voxel.py index 3e1e8fa..291c600 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -14,7 +14,7 @@ def voxelize( include_outside: bool = False, order: int = 0, ) -> NDArray[numpy.float64]: - ''' + """ Voxelize a Schelegel-representation polyhedron on an arbitrary rectangular grid. The grid is specified by supplying 3 sets of axis-aligned planes, in the form @@ -40,7 +40,7 @@ def voxelize( If include_outside is True, the outer borders of the first three dimensions correspond to portions of the polyhedron that protruded outside the outermost planes. N is `number_of_moments(order)`. - ''' + """ aplanes = [numpy.asarray(p) for p in planes] num_planes = numpy.array([e.size for e in aplanes], dtype=int) From 5cf4b826c77153e8a067a0fa98e949e2b205b763 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 30 Jul 2024 23:55:58 -0700 Subject: [PATCH 29/69] index to avoid complaint about scalarizing an array --- adze/voxel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adze/voxel.py b/adze/voxel.py index 291c600..2bc8eab 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -81,7 +81,7 @@ def voxelize( # Recursion case: split along longest side axis = num_planes_remaining.argmax() - plane_ind = num_planes_remaining[axis] // 2 + slices[axis, 0] + plane_ind = (num_planes_remaining[axis] // 2 + slices[axis, 0])[0] plane_pos = aplanes[axis][plane_ind] plane = (numpy.roll([-1, 0, 0], axis), plane_pos) From d5ed7a129891c9b59dbdd4f94a2d6a0fc484b707 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 31 Jul 2024 00:59:09 -0700 Subject: [PATCH 30/69] various linter-related fixes Some type annotations are still wrong --- adze/__init__.py | 31 +++++++-- adze/boundary.py | 4 +- adze/moments.py | 4 +- adze/shapes.py | 2 +- adze/split.py | 6 +- adze/test/conftest.py | 8 ++- adze/test/test_benchmarks.py | 17 ++--- adze/test/test_split.py | 59 +++++++++++------ adze/test/test_voxel.py | 24 +++---- adze/test/utils.py | 58 +++++++++++------ adze/transform.py | 2 +- adze/util.py | 120 +++++++++++++++++++---------------- adze/voxel.py | 6 +- pyproject.toml | 46 +++++++++++++- 14 files changed, 250 insertions(+), 137 deletions(-) diff --git a/adze/__init__.py b/adze/__init__.py index de3636f..2212c1a 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -53,13 +53,32 @@ In the polyhedron representation returned by the build_* functions and accepted """ -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 __author__ = 'Jan Petykiewicz' __version__ = '0.1' diff --git a/adze/boundary.py b/adze/boundary.py index c6aefcc..d87a417 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -4,7 +4,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 +from .util import _get_maps, find_components, find_faces, AdzeError def planes_from_boundary( @@ -57,7 +57,7 @@ def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: edges_per_vertex = numpy.bincount(numpy.hstack(afaces)) if edges_per_vertex.min() < 3: - raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges') + raise AdzeError(f'Vertex {edges_per_vertex.argmin()} has < 3 edges') if edges_per_vertex.max() == 3: # diff --git a/adze/moments.py b/adze/moments.py index 0f7dcbc..5ba50df 100644 --- a/adze/moments.py +++ b/adze/moments.py @@ -1,7 +1,7 @@ import numpy from numpy.typing import NDArray -from . import poly_t, plane_t +from . import poly_t from .util import find_faces @@ -95,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 diff --git a/adze/shapes.py b/adze/shapes.py index 89f24aa..0f2ae68 100644 --- a/adze/shapes.py +++ b/adze/shapes.py @@ -115,4 +115,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 [plane for plane in zip(n, d)] + return list(zip(n, d, strict=True)) diff --git a/adze/split.py b/adze/split.py index 6b2be0b..41f2226 100644 --- a/adze/split.py +++ b/adze/split.py @@ -73,7 +73,7 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False): # if all on right or touching plane ret = build_empty(), poly return ret[0] if same_only else ret - elif dists.min() >= 0: + if dists.min() >= 0: # if all on left or touching plane # Can't reuse 'left' because <= vs < ret = poly, build_empty() @@ -89,7 +89,7 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False): # # No edges cross the plane, but components exist on either side # - r2l_edges = numpy.empty((0, 3), dtype=int) + # 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() @@ -171,7 +171,7 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False): 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]] # 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] diff --git a/adze/test/conftest.py b/adze/test/conftest.py index 195ab5f..c1bf7c0 100644 --- a/adze/test/conftest.py +++ b/adze/test/conftest.py @@ -1,6 +1,10 @@ +from typing import Any import pytest +FixtureRequest = Any + + @pytest.fixture(scope='module', params=[0, 1, 2]) -def poly_order(request): - yield request.param +def poly_order(request: FixtureRequest) -> int: + return request.param diff --git a/adze/test/test_benchmarks.py b/adze/test/test_benchmarks.py index f4306a5..56aaa7c 100644 --- a/adze/test/test_benchmarks.py +++ b/adze/test/test_benchmarks.py @@ -3,31 +3,28 @@ Benchmarking, run with `python3 -m adze.test.benchmark` TODO: Consider using pytest-benchmark? """ -import warnings -from time import perf_counter +from collections.abc import Callable import logging import numpy -from numpy import sin, cos, pi -from numpy.linalg import norm +from numpy.typing import NDArray 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, plane_generators, rand_tetrahedron_vertices +from .utils import build_rand_tetrahedron, rand_tetrahedron_vertices logger = logging.getLogger(__name__) -def test_split(benchmark): +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): +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()) @@ -39,7 +36,7 @@ def test_split_bulk_1000(benchmark): -def get_intersection_moments(poly, faces, poly_order): +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) @@ -49,7 +46,7 @@ def get_intersection_moments(poly, faces, poly_order): return om -def test_intersection(benchmark, poly_order=0): +def test_intersection(benchmark: Callable, poly_order: int = 0) -> None: """ Benchmark intersection between pairs of tetrahedra """ diff --git a/adze/test/test_split.py b/adze/test/test_split.py index 3e8b197..63885b7 100644 --- a/adze/test/test_split.py +++ b/adze/test/test_split.py @@ -1,9 +1,13 @@ +from collections.abc import Callable +import warnings import logging + import pytest from pytest import approx + import numpy from numpy.linalg import norm -from numpy.testing import assert_allclose, assert_array_equal +from numpy.testing import assert_allclose import adze import adze.util @@ -15,7 +19,7 @@ from .utils import build_rand_tetrahedron, gen_plane_through_centroid, plane_gen logger = logging.getLogger(__name__) -def test_manual_tetrahedron(poly_order): +def test_manual_tetrahedron(poly_order: int) -> None: tet = adze.build_tetrahedron([ [0,0,0], [2,0,0], @@ -45,7 +49,7 @@ def test_manual_tetrahedron(poly_order): check_split_moments(tet, p_left, p_right, poly_order) -def test_manual_pyramid(poly_order): +def test_manual_pyramid(poly_order: int) -> None: vertices = numpy.array([ [0, 0, 1], [1, 1, 0], @@ -72,7 +76,7 @@ def test_manual_pyramid(poly_order): stack_split(poly, poly_order) -def test_tetrahedrons_through_centroid(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 @@ -85,16 +89,16 @@ def test_tetrahedrons_through_centroid(poly_order): # split them all with the same plane poly12 = [adze.split(p, plane) for p in polys] - poly1, poly2 = zip(*poly12) + poly1, poly2 = zip(*poly12, strict=True) - for orig, p1, p2 in zip(polys, poly1, poly2): + 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, n_zigs=3, z_offset=0.1): +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 @@ -128,8 +132,10 @@ def test_manual_nonconvex(poly_order, n_zigs=3, z_offset=0.1): adze.util.check_poly(poly) logger.debug("poly is valid.") - ''' Perform splits along three axes ''' - def split_and_check(poly, plane, poly_order=0): + # + # 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) @@ -144,7 +150,7 @@ def test_manual_nonconvex(poly_order, n_zigs=3, z_offset=0.1): split_and_check(poly, [numpy.array((0, 1, 0)), -0.5 * (1.0 + z_offset)], poly_order) -def test_torus(poly_order): +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. @@ -167,37 +173,42 @@ def test_torus(poly_order): stack_split(opoly, poly_order) -def test_recursive(poly_order, num_trials: int = 10, max_depth: int = 6): - ''' +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(f' - Through centroid') + 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(f' - Through degenerate plane') + logger.info(' - Through degenerate plane') for _ in range(num_trials): stack_split(build_rand_tetrahedron(), poly_order, max_depth=max_depth) - logger.info(f' - Through perturbed plane') + 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, left_poly, right_poly, poly_order=0): +def check_split_moments( + original_poly: adze.poly_t, + left_poly: adze.poly_t, + right_poly: adze.poly_t, + poly_order: int = 0, + ) -> None: 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]') + 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]') + 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 @@ -207,12 +218,18 @@ def check_split_moments(original_poly, left_poly, right_poly, poly_order=0): # 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') + warnings.warn('Moments outside tolerance', stacklevel=1) return m0, ml, mr -def stack_split(poly, poly_order, plane_fun=None, perturb=0, max_depth=10): +def stack_split( + poly: adze.poly_t, + poly_order: adze.poly_t, + plane_fun: Callable | None = None, + perturb: float = 0, + max_depth: int = 10, + ) -> None: stack = [(poly, 0)] i = 0 diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py index 735eab9..e6c678c 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -2,17 +2,18 @@ from typing import TYPE_CHECKING import logging import warnings from time import perf_counter + import pytest -from pytest import approx import numpy -from numpy.linalg import norm -from numpy.testing import assert_allclose, assert_array_equal +from numpy.typing import NDArray +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, rand_tetrahedron_vertices +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 @@ -44,12 +45,12 @@ def test_voxelization(poly_order: int, grid_resolution: int | None = None) -> No assert_allclose(moments, voxsum, atol=TOL_FAIL) if not numpy.allclose(moments, voxsum, atol=TOL_WARN): - warnings.warn('Moments failed tolerance in voxels') + warnings.warn('Moments failed tolerance in voxels', stacklevel=1) def visualize_isosurface( - grid, - edges, + grid: NDArray[numpy.float64], + edges: NDArray[numpy.int64], level: float | None = None, show_edges: bool = True, finalize: bool = True, @@ -62,10 +63,11 @@ def visualize_isosurface( 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 # type: ignore - import skimage.measure # type: ignore + 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() @@ -92,7 +94,7 @@ def visualize_isosurface( 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): + for xb, yb, zb in zip(xbs, ybs, zbs, strict=True): ax.plot([xb], [yb], [zb], 'w') if finalize: diff --git a/adze/test/utils.py b/adze/test/utils.py index f99c9f0..e612a36 100644 --- a/adze/test/utils.py +++ b/adze/test/utils.py @@ -1,5 +1,6 @@ import numpy -from numpy import pi, cos, sin +from numpy.typing import NDArray +from numpy import pi, cos, sin, floating from numpy.linalg import norm import random @@ -21,7 +22,12 @@ MIN_VOLUME = 1e-8 POLY_ORDER = 0 -def gen_torus_brep(n_theta=20, n_phi=20, r0=1.0, r1=0.1): +def gen_torus_brep( + n_theta: int = 20, + n_phi: int = 20, + r0: float = 1.0, + r1: float = 0.1, + ) -> tuple[NDArray[numpy.float64], NDArray[numpy.intp]]: """ Generate a boundary representation for an elliptical torus """ @@ -55,16 +61,16 @@ def gen_torus_brep(n_theta=20, n_phi=20, r0=1.0, r1=0.1): return vertices, faces -def tetrahedron_volume(vertices): - ad, bd, cd = vertices[0:3] - vertices[3] - return -ad @ numpy.cross(bd, cd) / 6 +def tetrahedron_volume(vertices: NDArray[numpy.float64]) -> float: + ad, bd, cd = vertices[0:3] - vertices[3] + return -ad @ numpy.cross(bd, cd) / 6 -def flip_plane(plane): +def flip_plane(plane: adze.plane_t) -> adze.plane_t: return (-plane[0], -plane[1]) -def rand_tetrahedron_vertices(min_volume: float = MIN_VOLUME): +def rand_tetrahedron_vertices(min_volume: float = MIN_VOLUME) -> NDArray[numpy.float64]: # generates a random tetrahedron with vertices on the unit sphere, # guaranteeing a volume of at least min_volume volume = 0 @@ -77,11 +83,11 @@ def rand_tetrahedron_vertices(min_volume: float = MIN_VOLUME): return verts -def build_rand_tetrahedron(min_volume: float = MIN_VOLUME): - return adze.build_tetrahedron(rand_tetrahedron_vertices()) +def build_rand_tetrahedron(min_volume: float = MIN_VOLUME) -> adze.poly_t: + return adze.build_tetrahedron(rand_tetrahedron_vertices(min_volume=min_volume)) -def rand_unit_vector(): +def rand_unit_vector() -> NDArray[numpy.float64]: # generates a random, isotropically distributed unit vector s = 0 while s == 0: @@ -90,7 +96,7 @@ def rand_unit_vector(): return v / s -def get_centroid(poly): +def get_centroid(poly: adze.poly_t) -> NDArray[numpy.floating]: """ Average the vertices to get the centroid """ @@ -98,7 +104,9 @@ def get_centroid(poly): return centroid -def gen_plane_through_centroid(poly): +def gen_plane_through_centroid( + poly: adze.poly_t, + ) -> adze.plane_t: """ Generate a randomly-oriented plane passing through the polyhedron's centroid """ @@ -108,7 +116,9 @@ def gen_plane_through_centroid(poly): return n, d -def gen_plane_from_face(poly): +def gen_plane_from_face( + poly: adze.poly_t, + ) -> adze.plane_t: """ Generate a plane coplanar with one of the polyhedron's faces """ @@ -119,7 +129,9 @@ def gen_plane_from_face(poly): return gen_plane_through_points(*points) -def gen_plane_through_centroid_and_edge(poly): +def gen_plane_through_centroid_and_edge( + poly: adze.poly_t, + ) -> adze.plane_t: """ Generate a plane through an edge of the polyhedron and the polyhedron's centroid """ @@ -131,7 +143,9 @@ def gen_plane_through_centroid_and_edge(poly): return gen_plane_through_points(p0, p1, centroid) -def gen_plane_through_edge(poly): +def gen_plane_through_edge( + poly: adze.poly_t, + ) -> adze.plane_t: """ Generate a plane through an edge of the polyhedron, but otherwise randomly oriented """ @@ -142,7 +156,9 @@ def gen_plane_through_edge(poly): return gen_plane_through_points(p0, p1, rand_unit_vector()) -def gen_plane_through_centroid_and_vertex(poly): +def gen_plane_through_centroid_and_vertex( + poly: adze.poly_t, + ) -> adze.plane_t: """ Generate a plane through a vertex and the centroid, but otherwise randomly oriented """ @@ -152,7 +168,9 @@ def gen_plane_through_centroid_and_vertex(poly): return gen_plane_through_points(p0, centroid, rand_unit_vector()) -def gen_plane_through_vertex(poly): +def gen_plane_through_vertex( + poly: adze.poly_t, + ) -> adze.plane_t: """ Generate a plane passing through a vertex, but otherwise randomly oriented """ @@ -163,7 +181,11 @@ def gen_plane_through_vertex(poly): return n, d -def gen_plane_through_points(p0, p1, p2): +def gen_plane_through_points( + p0: NDArray[floating], + p1: NDArray[floating], + p2: NDArray[floating], + ) -> adze.plane_t: """ Generate a plane passing through three given points """ diff --git a/adze/transform.py b/adze/transform.py index 6b05130..1c3dfdd 100644 --- a/adze/transform.py +++ b/adze/transform.py @@ -2,7 +2,7 @@ import numpy from numpy import sin, cos from numpy.typing import ArrayLike -from . import poly_t, plane_t +from . import poly_t def rotate(poly: poly_t, theta: float, axis: int) -> poly_t: diff --git a/adze/util.py b/adze/util.py index 693c228..1cf728f 100644 --- a/adze/util.py +++ b/adze/util.py @@ -1,11 +1,21 @@ +from typing import TYPE_CHECKING +from collections.abc import Sequence import numpy -from numpy.typing import ArrayLike, NDArray +from numpy.typing import NDArray + +if TYPE_CHECKING: + import stl plane_t = tuple[NDArray, float] poly_t = dict[str, NDArray] +class AdzeError(Exception): + """ Custom error for Adze """ + pass + + def build_empty() -> poly_t: """ Build an empty Schlegel representation (containing no vertices). @@ -78,29 +88,29 @@ def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.integer] faces: list[list[NDArray[numpy.integer]]] | NDArray[numpy.integer] if num_verts < 1000: # ~3n^2 in memory, but much faster in cases where n isn't prohibitively large - faces = numpy.full((3*num_verts, num_verts-1), -1, dtype=int) + faces = numpy.full((3 * num_verts, num_verts - 1), -1, dtype=int) faces[:, 0] = v_current - def add_edges(edge_id, v_nxt, k): - faces[edge_id, k] = v_nxt + def add_edges(edge_id: NDArray[numpy.intp], v_nxt: NDArray[numpy.intp], kk: int) -> None: + faces[edge_id, kk] = v_nxt - def cleaned_faces(remove, k): + def cleaned_faces(remove: NDArray[numpy.int8], kk: int) -> list[NDArray[numpy.intp]]: faces_set = [] - for row in faces[~remove, :k]: + for row in faces[~remove, :kk]: faces_set.append(row[row >= 0]) return faces_set else: # Alternative approach, less memory-intensive but slower - faces = [[v] for v in v_current] + faces = [[vv] for vv in v_current] - def add_edges(edge_id, v_nxt, k): - for i, vn in zip(edge_id, v_nxt): - faces[i].append(vn) + def add_edges(edge_id: NDArray[numpy.intp], v_nxt: NDArray[numpy.intp], kk: int) -> None: # noqa: ARG001 + for ii, vn in zip(edge_id, v_nxt, strict=True): + faces[ii].append(vn) - def cleaned_faces(remove, k): + def cleaned_faces(remove: NDArray[numpy.int8], kk: int) -> list[NDArray[numpy.intp]]: # noqa: ARG001 faces_set = [] - for i in numpy.where(~remove)[0]: - faces_set.append(faces[i]) + for ii in numpy.where(~remove)[0]: + faces_set.append(faces[ii]) return faces_set """ @@ -110,29 +120,29 @@ def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.integer] a) the vertex index decreases (stop and mark for removal) b) we reach the original vertex (stop, done with this path) """ - k = 1 + kk = 1 mask = v_next > v_current - v = numpy.vstack((edge_id, v_start, v_current, v_next))[:, mask] + vv = numpy.vstack((edge_id, v_start, v_current, v_next))[:, mask] remove = numpy.logical_not(mask) while mask.any(): - add_edges(v[0], v[3], k) + add_edges(vv[0], vv[3], kk) - prv_edge = (neighbors[v[3], :] == v[2][:, None]).argmax(axis=1) + prv_edge = (neighbors[vv[3], :] == vv[2][:, None]).argmax(axis=1) nxt_edge = (prv_edge + 1) % 3 - v[2:4] = v[3], neighbors[v[3], nxt_edge] + vv[2:4] = vv[3], neighbors[vv[3], nxt_edge] - remove_mask = v[2] < v[1] - remove[v[0][remove_mask]] = True + remove_mask = vv[2] < vv[1] + remove[vv[0][remove_mask]] = True - mask = numpy.logical_and(v[3] != v[1], ~remove_mask) - v = v[:, mask] - k += 1 + mask = numpy.logical_and(vv[3] != vv[1], ~remove_mask) + vv = vv[:, mask] + kk += 1 - return cleaned_faces(remove, k) + return cleaned_faces(remove, kk) -def _get_map(a, b): +def _get_map(a: NDArray, b: NDArray) -> NDArray[numpy.intp]: """ Returns m such that a[m] == b Assumes that all elements appear exactly once in each array @@ -146,17 +156,17 @@ def _get_map(a, b): return sa[r] -def _get_map_rows(a, b): +def _get_map_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]: """ Row-wise _get_map """ dims = numpy.maximum(a.max(0), b.max(0)) + 1 - a1d = numpy.ravel_multi_index(a.T, dims) - b1d = numpy.ravel_multi_index(b.T, dims) + a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore + b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore return _get_map(a1d, b1d) -def _get_maps(a, b): +def _get_maps(a: NDArray, b: NDArray) -> tuple[int, int]: """ Returns m, n such that a[m] == b, b[n] == a Assumes that all elements appear exactly once in each array @@ -173,32 +183,32 @@ def _get_maps(a, b): return m, n -def _get_maps_rows(a, b): +def _get_maps_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]: """ Row-wise _get_maps """ dims = numpy.maximum(a.max(0), b.max(0)) + 1 - a1d = numpy.ravel_multi_index(a.T, dims) - b1d = numpy.ravel_multi_index(b.T, dims) + a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore + b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore return _get_maps(a1d, b1d) -def _argsort_rows(a): +def _argsort_rows(a: NDArray) -> NDArray[numpy.intp]: """ Row-wise argsort """ dims = a.max(0) + 1 - a1d = numpy.ravel_multi_index(a.T, dims) + a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore return numpy.argsort(a1d) -def _searchsorted_rows(a, b): +def _searchsorted_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]: """ Row-wise searchsorted """ dims = numpy.maximum(a.max(0), b.max(0)) + 1 - a1d = numpy.ravel_multi_index(a.T, dims) - b1d = numpy.ravel_multi_index(b.T, dims) + a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore + b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore return numpy.searchsorted(a1d, b1d) @@ -216,7 +226,7 @@ def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: This is slow! Default `True`. Raises: - Exception if the polyhedron fails a check + AdzeError if the polyhedron fails a check """ neighbors = poly['neighbors'] vertices = poly['vertices'] @@ -225,17 +235,17 @@ def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: out_of_bounds = numpy.logical_or(neighbors >= vertices.shape[0], neighbors < 0) if numpy.any(out_of_bounds): which_vertices = numpy.where(out_of_bounds)[0] - raise Exception(f'Vertices {which_vertices} have out-of-bounds neighbors') + raise AdzeError(f'Vertices {which_vertices} have out-of-bounds neighbors') repeated_neighbors = neighbors == numpy.roll(neighbors, 1, axis=1) if numpy.any(repeated_neighbors): which_vertices = numpy.where(repeated_neighbors)[0] - raise Exception(f'Vertices {which_vertices} have duplicate neighbors') + raise AdzeError(f'Vertices {which_vertices} have duplicate neighbors') vertex_uses = numpy.bincount(neighbors.ravel()) if numpy.any(vertex_uses != 3): which_vertices = numpy.where(vertex_uses != 3)[0] - raise Exception(f'Vertices {which_vertices} are referenced {vertex_uses[which_vertices]} times,' + raise AdzeError(f'Vertices {which_vertices} are referenced {vertex_uses[which_vertices]} times,' ' should be exactly 3') # check for 3-vertex-connectedness (~n^3 because need bfs for each removed vertex pair) @@ -253,7 +263,7 @@ def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: va = part_verts[ia] for vb in part_verts[ia + 1:]: # pick vc != {va, vb} - vc = (vcs - set((va, vb))).pop() + vc = (vcs - {va, vb}).pop() # flood-fill from vc without passing through va, vb visited.fill(False) @@ -267,10 +277,10 @@ def check_poly(poly: poly_t, check_connectivity: bool = True) -> None: # Make sure we touched all vertices in the component if not visited[components == part_id].all(): - raise Exception('Vertex graph is not 3-vertex-connected') + raise AdzeError('Vertex graph is not 3-vertex-connected') -def plot_brep(brep) -> None: +def plot_brep(brep: Sequence[dict[str, NDArray]]) -> None: """ Plot a boundary representation """ @@ -292,22 +302,22 @@ def plot_brep(brep) -> None: pyplot.show() -def brep_to_stls(brep): +def brep_to_stls(brep: Sequence[dict[str, NDArray]]) -> list['stl.mesh.Mesh']: import stl meshes = [] for component in brep: - triangles = [] + tri_list = [] for face in component['faces']: - for i in range(1, len(face) - 1): - triangles.append([face[0], face[i], face[i+1]]) - triangles = numpy.array(triangles, dtype=int) + for ii in range(1, len(face) - 1): + tri_list.append([face[0], face[ii], face[ii + 1]]) + triangles = numpy.asarray(tri_list, dtype=int) - m = stl.mesh.Mesh(numpy.empty(triangles.shape[0], dtype=stl.mesh.Mesh.dtype)) - for i, f in enumerate(triangles): - for j in range(3): - m.vectors[i, j] = component['vertices'][f[j], :] + mm = stl.mesh.Mesh(numpy.empty(triangles.shape[0], dtype=stl.mesh.Mesh.dtype)) + for ii, ff in enumerate(triangles): + for jj in range(3): + mm.vectors[ii, jj] = component['vertices'][ff[jj], :] -# m.save('pyr.stl') - meshes.append(m) +# mm.save('pyr.stl') + meshes.append(mm) return meshes diff --git a/adze/voxel.py b/adze/voxel.py index 2bc8eab..a2e09cb 100644 --- a/adze/voxel.py +++ b/adze/voxel.py @@ -2,10 +2,11 @@ from collections.abc import Sequence import numpy from numpy.typing import ArrayLike, NDArray -from . import poly_t, plane_t +from . import poly_t from .split import split, clip from .moments import get_moments, number_of_moments from .shapes import planes_from_box +from .util import AdzeError def voxelize( @@ -45,8 +46,7 @@ def voxelize( num_planes = numpy.array([e.size for e in aplanes], dtype=int) if (num_planes < 2).any(): - # TODO raw exception - raise Exception(f'Need at least two planes per dimension. Got {num_planes} planes.') + raise AdzeError(f'Need at least two planes per dimension. Got {num_planes} planes.') if include_outside: grid_shape = num_planes + 1 diff --git a/pyproject.toml b/pyproject.toml index bc0e248..5e5a093 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,10 +36,10 @@ classifiers = [ "Topic :: Multimedia :: Graphics", "Topic :: Scientific/Engineering", ] -requires-python = ">=3.8" +requires-python = ">=3.11" dynamic = ["version"] dependencies = [ - "numpy~=1.21", + "numpy>=1.26", ] [tool.hatch.version] @@ -47,3 +47,45 @@ path = "adze/__init__.py" [project.optional-dependencies] stl = ["stl"] + +[tool.ruff] +exclude = [ + ".git", + "dist", + ] +line-length = 145 +indent-width = 4 +lint.dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" +lint.select = [ + "NPY", "E", "F", "W", "B", "ANN", "UP", "SLOT", "SIM", "LOG", + "C4", "ISC", "PIE", "PT", "RET", "TCH", "PTH", "INT", + "ARG", "PL", "R", "TRY", + "G010", "G101", "G201", "G202", + "Q002", "Q003", "Q004", + ] +lint.ignore = [ + #"ANN001", # No annotation + "ANN002", # *args + "ANN003", # **kwargs + "ANN401", # Any + "ANN101", # self: Self + "SIM108", # single-line if / else assignment + "RET504", # x=y+z; return x + "PIE790", # unnecessary pass + "ISC003", # non-implicit string concatenation + "C408", # dict(x=y) instead of {'x': y} + "PLR09", # Too many xxx + "PLR2004", # magic number + "PLC0414", # import x as x + "TRY003", # Long exception message + ] + + +[[tool.mypy.overrides]] +module = [ + "matplotlib", + "mpl_toolkits", + "mpl_toolkits.mplot3d", + "stl", + ] +ignore_missing_imports = true From b957ac7abebf410a53cf678ca38faf9d4da75dd0 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 31 Jul 2024 22:38:24 -0700 Subject: [PATCH 31/69] improve type annotations --- adze/boundary.py | 3 ++- adze/split.py | 18 +++++++++++++++++- adze/test/test_split.py | 18 ++++++++++-------- adze/test/utils.py | 13 +++++++------ adze/util.py | 27 +++++++++++++-------------- 5 files changed, 49 insertions(+), 30 deletions(-) diff --git a/adze/boundary.py b/adze/boundary.py index d87a417..150030b 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -1,4 +1,5 @@ from typing import Any +from collections.abc import Iterable import numpy from numpy.linalg import norm from numpy.typing import ArrayLike, NDArray @@ -38,7 +39,7 @@ def planes_from_boundary( return planes -def build_polyhedron(vertices: ArrayLike, faces: list[ArrayLike]) -> poly_t: +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. diff --git a/adze/split.py b/adze/split.py index 41f2226..c0c2643 100644 --- a/adze/split.py +++ b/adze/split.py @@ -1,3 +1,4 @@ +from typing import overload, Literal import numpy from . import poly_t, plane_t @@ -38,7 +39,22 @@ def split(poly: poly_t, plane: plane_t) -> tuple[poly_t, poly_t]: return _split(poly, plane, same_only=False) -def _split(poly: poly_t, plane: plane_t, same_only: bool = False): +@overload +def _split(poly: poly_t, plane: plane_t, same_only: Literal[True]) -> poly_t: + ... + + +@overload +def _split(poly: poly_t, plane: plane_t, same_only: Literal[False]) -> 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 = False) -> tuple[poly_t, poly_t] | poly_t: """ Clip a polyhedron with a plane. diff --git a/adze/test/test_split.py b/adze/test/test_split.py index 63885b7..0e92ff7 100644 --- a/adze/test/test_split.py +++ b/adze/test/test_split.py @@ -6,6 +6,8 @@ import pytest from pytest import approx import numpy +from numpy.typing import NDArray +from numpy import floating from numpy.linalg import norm from numpy.testing import assert_allclose @@ -66,7 +68,7 @@ def test_manual_pyramid(poly_order: int) -> None: ] # initialize a general polyhedron - poly = adze.build_polyhedron(vertices, faces) + poly = adze.build_polyhedron(vertices, faces) # type: ignore # (mypy error?) adze.util.check_poly(poly) brep = adze.boundary_from_poly(poly) @@ -141,13 +143,13 @@ def test_manual_nonconvex(poly_order: int, n_zigs: int = 3, z_offset: float = 0. check_split_moments(poly, poly_l, poly_r) # 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_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_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) + split_and_check(poly, (numpy.array((0, 1, 0)), -0.5 * (1.0 + z_offset)), poly_order) def test_torus(poly_order: int) -> None: @@ -199,7 +201,7 @@ def check_split_moments( left_poly: adze.poly_t, right_poly: adze.poly_t, poly_order: int = 0, - ) -> None: + ) -> 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]}') @@ -225,7 +227,7 @@ def check_split_moments( def stack_split( poly: adze.poly_t, - poly_order: adze.poly_t, + poly_order: int, plane_fun: Callable | None = None, perturb: float = 0, max_depth: int = 10, @@ -239,10 +241,10 @@ def stack_split( # pick a plane if plane_fun is None: - pfun_used = PRNG.choice(plane_generators) + pfun_used = PRNG.choice(plane_generators) # type: ignore plane = pfun_used(poly) while norm(plane[0]) == 0: - pfun_used = PRNG.choice(plane_generators) + pfun_used = PRNG.choice(plane_generators) # type: ignore plane = pfun_used(poly) plane = list(plane) logger.debug(f'used {pfun_used}') diff --git a/adze/test/utils.py b/adze/test/utils.py index e612a36..3f4764f 100644 --- a/adze/test/utils.py +++ b/adze/test/utils.py @@ -1,3 +1,4 @@ +from typing import cast import numpy from numpy.typing import NDArray from numpy import pi, cos, sin, floating @@ -61,7 +62,7 @@ def gen_torus_brep( return vertices, faces -def tetrahedron_volume(vertices: NDArray[numpy.float64]) -> float: +def tetrahedron_volume(vertices: NDArray[numpy.floating] | list[NDArray[numpy.floating]]) -> float: ad, bd, cd = vertices[0:3] - vertices[3] return -ad @ numpy.cross(bd, cd) / 6 @@ -73,14 +74,14 @@ def flip_plane(plane: adze.plane_t) -> adze.plane_t: def rand_tetrahedron_vertices(min_volume: float = MIN_VOLUME) -> NDArray[numpy.float64]: # generates a random tetrahedron with vertices on the unit sphere, # guaranteeing a volume of at least min_volume - volume = 0 + volume = 0.0 while volume < min_volume: verts = [rand_unit_vector() for _ in range(4)] volume = tetrahedron_volume(verts) if volume < 0: verts[2], verts[3] = verts[3], verts[2] volume = -volume - return verts + return numpy.asarray(verts) def build_rand_tetrahedron(min_volume: float = MIN_VOLUME) -> adze.poly_t: @@ -89,8 +90,8 @@ def build_rand_tetrahedron(min_volume: float = MIN_VOLUME) -> adze.poly_t: def rand_unit_vector() -> NDArray[numpy.float64]: # generates a random, isotropically distributed unit vector - s = 0 - while s == 0: + s: numpy.floating | float = 0.0 + while s == 0.0: v = PRNG.randn(3) s = norm(v) return v / s @@ -112,7 +113,7 @@ def gen_plane_through_centroid( """ centroid = get_centroid(poly) n = rand_unit_vector() - d = -n @ centroid + d = cast(numpy.floating, -n @ centroid) return n, d diff --git a/adze/util.py b/adze/util.py index 1cf728f..5df0ad5 100644 --- a/adze/util.py +++ b/adze/util.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: import stl -plane_t = tuple[NDArray, float] +plane_t = tuple[NDArray[numpy.floating], float | numpy.floating] poly_t = dict[str, NDArray] @@ -59,7 +59,7 @@ def find_components(neighbors: NDArray[numpy.integer]) -> NDArray[numpy.integer] return component - 1 -def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.integer]]: +def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.intp]]: """ Traverse the Schlegel diagram to find chordless cycles (i.e., faces of the polyhedron). Assumes 3-vertex-connected @@ -85,32 +85,31 @@ def find_faces(neighbors: NDArray[numpy.integer]) -> list[NDArray[numpy.integer] Choose a method for storing the face info based on expected runtime vs unnecessary memory allocation """ - faces: list[list[NDArray[numpy.integer]]] | NDArray[numpy.integer] if num_verts < 1000: # ~3n^2 in memory, but much faster in cases where n isn't prohibitively large - faces = numpy.full((3 * num_verts, num_verts - 1), -1, dtype=int) - faces[:, 0] = v_current + faces_arr = numpy.full((3 * num_verts, num_verts - 1), -1, dtype=int) + faces_arr[:, 0] = v_current def add_edges(edge_id: NDArray[numpy.intp], v_nxt: NDArray[numpy.intp], kk: int) -> None: - faces[edge_id, kk] = v_nxt + faces_arr[edge_id, kk] = v_nxt def cleaned_faces(remove: NDArray[numpy.int8], kk: int) -> list[NDArray[numpy.intp]]: faces_set = [] - for row in faces[~remove, :kk]: + for row in faces_arr[~remove, :kk]: faces_set.append(row[row >= 0]) return faces_set else: # Alternative approach, less memory-intensive but slower - faces = [[vv] for vv in v_current] + faces_list = [[vv] for vv in v_current] def add_edges(edge_id: NDArray[numpy.intp], v_nxt: NDArray[numpy.intp], kk: int) -> None: # noqa: ARG001 for ii, vn in zip(edge_id, v_nxt, strict=True): - faces[ii].append(vn) + faces_list[ii].append(vn) def cleaned_faces(remove: NDArray[numpy.int8], kk: int) -> list[NDArray[numpy.intp]]: # noqa: ARG001 faces_set = [] for ii in numpy.where(~remove)[0]: - faces_set.append(faces[ii]) + faces_set.append(numpy.asarray(faces_list[ii], dtype=numpy.intp)) return faces_set """ @@ -148,7 +147,7 @@ def _get_map(a: NDArray, b: NDArray) -> NDArray[numpy.intp]: Assumes that all elements appear exactly once in each array """ if a.size == 0: - return numpy.array(()), numpy.array(()) + return numpy.array((), dtype=numpy.intp) sa = a.argsort() sb = b.argsort() r = numpy.empty_like(sa) @@ -166,13 +165,13 @@ def _get_map_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]: return _get_map(a1d, b1d) -def _get_maps(a: NDArray, b: NDArray) -> tuple[int, int]: +def _get_maps(a: NDArray, b: NDArray) -> tuple[NDArray[numpy.intp], NDArray[numpy.intp]]: """ Returns m, n such that a[m] == b, b[n] == a Assumes that all elements appear exactly once in each array """ if a.size == 0: - return numpy.array(()), numpy.array(()) + return numpy.array((), dtype=numpy.intp), numpy.array((), dtype=numpy.intp) sa = a.argsort() sb = b.argsort() r = numpy.empty_like(sa) @@ -183,7 +182,7 @@ def _get_maps(a: NDArray, b: NDArray) -> tuple[int, int]: return m, n -def _get_maps_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]: +def _get_maps_rows(a: NDArray, b: NDArray) -> tuple[NDArray[numpy.intp], NDArray[numpy.intp]]: """ Row-wise _get_maps """ From 07a7c37eabdaf77ac2d968561037ffb6e904ee50 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 31 Jul 2024 22:39:12 -0700 Subject: [PATCH 32/69] misc fixes (mostly imports) --- adze/test/test_split.py | 5 ++--- adze/test/test_voxel.py | 1 - adze/test/utils.py | 13 +++++++++---- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/adze/test/test_split.py b/adze/test/test_split.py index 0e92ff7..17d6711 100644 --- a/adze/test/test_split.py +++ b/adze/test/test_split.py @@ -3,7 +3,6 @@ import warnings import logging import pytest -from pytest import approx import numpy from numpy.typing import NDArray @@ -46,8 +45,8 @@ def test_manual_tetrahedron(poly_order: int) -> None: ml = adze.get_moments(p_left, 0) mr = adze.get_moments(p_right, 0) - logger.debug(f'0th moments: tot {m0}, left {ml}, right {mr}') - assert m0 == approx(volume, abs=TOL_FAIL) + 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) diff --git a/adze/test/test_voxel.py b/adze/test/test_voxel.py index e6c678c..51ac5d4 100644 --- a/adze/test/test_voxel.py +++ b/adze/test/test_voxel.py @@ -3,7 +3,6 @@ import logging import warnings from time import perf_counter -import pytest import numpy from numpy.typing import NDArray from numpy.testing import assert_allclose diff --git a/adze/test/utils.py b/adze/test/utils.py index 3f4764f..2192325 100644 --- a/adze/test/utils.py +++ b/adze/test/utils.py @@ -1,9 +1,9 @@ from typing import cast +import random import numpy from numpy.typing import NDArray from numpy import pi, cos, sin, floating from numpy.linalg import norm -import random import adze @@ -196,7 +196,12 @@ def gen_plane_through_points( return n, d -plane_generators = [gen_plane_through_centroid, gen_plane_from_face, - gen_plane_through_centroid_and_edge, gen_plane_through_edge, - gen_plane_through_centroid_and_vertex, gen_plane_through_vertex] +plane_generators = [ + gen_plane_through_centroid, + gen_plane_from_face, + gen_plane_through_centroid_and_edge, + gen_plane_through_edge, + gen_plane_through_centroid_and_vertex, + gen_plane_through_vertex, + ] From 46cd73a22a1f018d50f97199735cb66961777abf Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 31 Jul 2024 22:39:39 -0700 Subject: [PATCH 33/69] pass poly_order into check_* call --- adze/test/test_split.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adze/test/test_split.py b/adze/test/test_split.py index 17d6711..5a0c64d 100644 --- a/adze/test/test_split.py +++ b/adze/test/test_split.py @@ -139,7 +139,7 @@ def test_manual_nonconvex(poly_order: int, n_zigs: int = 3, z_offset: float = 0. 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) + 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) From 227511afd6c0389fd6903cd544807b238cee150d Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 31 Jul 2024 22:40:23 -0700 Subject: [PATCH 34/69] bump version to v0.2 --- adze/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adze/__init__.py b/adze/__init__.py index 2212c1a..76b138e 100644 --- a/adze/__init__.py +++ b/adze/__init__.py @@ -81,4 +81,4 @@ from .shapes import ( from .voxel import voxelize as voxelize __author__ = 'Jan Petykiewicz' -__version__ = '0.1' +__version__ = '0.2' From bf057e25052744b68201e9f26777b060790fb560 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 7 Mar 2026 00:46:27 -0800 Subject: [PATCH 35/69] 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 36/69] 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 37/69] [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 38/69] [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 39/69] [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 40/69] [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 41/69] [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 42/69] [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 43/69] [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 44/69] [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 45/69] 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 46/69] [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 47/69] [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 48/69] [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 49/69] [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 50/69] [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 51/69] [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 52/69] [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 53/69] [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 54/69] [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 55/69] [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 56/69] [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 57/69] 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 58/69] [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 59/69] [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 60/69] [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 61/69] [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 62/69] 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 63/69] [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 64/69] [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 65/69] 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 66/69] [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 67/69] [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 68/69] [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 69/69] [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\\]'):