From d5ed7a129891c9b59dbdd4f94a2d6a0fc484b707 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 31 Jul 2024 00:59:09 -0700 Subject: [PATCH] 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