various linter-related fixes
Some type annotations are still wrong
This commit is contained in:
parent
5cf4b826c7
commit
d5ed7a1298
14 changed files with 251 additions and 138 deletions
|
|
@ -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 .split import (
|
||||||
from .moments import get_volume, get_moments, number_of_moments
|
split as split,
|
||||||
from .boundary import build_polyhedron, boundary_from_poly
|
clip as clip,
|
||||||
from .shapes import build_tetrahedron, build_box, planes_from_tetrahedron, planes_from_box
|
)
|
||||||
from .voxel import voxelize
|
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'
|
__author__ = 'Jan Petykiewicz'
|
||||||
__version__ = '0.1'
|
__version__ = '0.1'
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ from numpy.linalg import norm
|
||||||
from numpy.typing import ArrayLike, NDArray
|
from numpy.typing import ArrayLike, NDArray
|
||||||
|
|
||||||
from . import poly_t, plane_t
|
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(
|
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))
|
edges_per_vertex = numpy.bincount(numpy.hstack(afaces))
|
||||||
|
|
||||||
if edges_per_vertex.min() < 3:
|
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:
|
if edges_per_vertex.max() == 3:
|
||||||
#
|
#
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import numpy
|
import numpy
|
||||||
from numpy.typing import NDArray
|
from numpy.typing import NDArray
|
||||||
|
|
||||||
from . import poly_t, plane_t
|
from . import poly_t
|
||||||
from .util import find_faces
|
from .util import find_faces
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -95,7 +95,7 @@ def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]:
|
||||||
moment_list = [moment0]
|
moment_list = [moment0]
|
||||||
for c in range(1, order + 1):
|
for c in range(1, order + 1):
|
||||||
valid[curlayer] = c >= mx + my
|
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_prev = Q[:, :, valid[prevlayer], prevlayer]
|
||||||
Q[:, :, 0, :, curlayer] = 0
|
Q[:, :, 0, :, curlayer] = 0
|
||||||
|
|
|
||||||
|
|
@ -115,4 +115,4 @@ def planes_from_tetrahedron(vertices: ArrayLike) -> list[plane_t]:
|
||||||
centers = numpy.sum(vertsets[:, :3, :], axis=1) / 3
|
centers = numpy.sum(vertsets[:, :3, :], axis=1) / 3
|
||||||
d = -numpy.sum(n * centers, axis=1)
|
d = -numpy.sum(n * centers, axis=1)
|
||||||
|
|
||||||
return [plane for plane in zip(n, d)]
|
return list(zip(n, d, strict=True))
|
||||||
|
|
|
||||||
|
|
@ -73,7 +73,7 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False):
|
||||||
# if all on right or touching plane
|
# if all on right or touching plane
|
||||||
ret = build_empty(), poly
|
ret = build_empty(), poly
|
||||||
return ret[0] if same_only else ret
|
return ret[0] if same_only else ret
|
||||||
elif dists.min() >= 0:
|
if dists.min() >= 0:
|
||||||
# if all on left or touching plane
|
# if all on left or touching plane
|
||||||
# Can't reuse 'left' because <= vs <
|
# Can't reuse 'left' because <= vs <
|
||||||
ret = poly, build_empty()
|
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
|
# 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)
|
target_edge_inds = numpy.empty((0, 1), dtype=int)
|
||||||
new_vertices = numpy.empty((0, 3), dtype=float)
|
new_vertices = numpy.empty((0, 3), dtype=float)
|
||||||
src_pns = target_edge_inds.copy()
|
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_vertices_left = vertices[left]
|
||||||
|
|
||||||
old_neighbors_left = neighbors.copy()
|
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[(lverts, src_pns)] = num_left + numpy.arange(num_new_vertices)
|
||||||
old_neighbors_left = old_neighbors_left[left]
|
old_neighbors_left = old_neighbors_left[left]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,10 @@
|
||||||
|
from typing import Any
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
FixtureRequest = Any
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope='module', params=[0, 1, 2])
|
@pytest.fixture(scope='module', params=[0, 1, 2])
|
||||||
def poly_order(request):
|
def poly_order(request: FixtureRequest) -> int:
|
||||||
yield request.param
|
return request.param
|
||||||
|
|
|
||||||
|
|
@ -3,31 +3,28 @@ Benchmarking, run with `python3 -m adze.test.benchmark`
|
||||||
|
|
||||||
TODO: Consider using pytest-benchmark?
|
TODO: Consider using pytest-benchmark?
|
||||||
"""
|
"""
|
||||||
import warnings
|
from collections.abc import Callable
|
||||||
from time import perf_counter
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
import numpy
|
import numpy
|
||||||
from numpy import sin, cos, pi
|
from numpy.typing import NDArray
|
||||||
from numpy.linalg import norm
|
|
||||||
|
|
||||||
import adze
|
import adze
|
||||||
import adze.util
|
import adze.util
|
||||||
|
|
||||||
from .utils import TOL_FAIL, TOL_WARN, PRNG, MIN_VOLUME, flip_plane, tetrahedron_volume
|
from .utils import build_rand_tetrahedron, rand_tetrahedron_vertices
|
||||||
from .utils import build_rand_tetrahedron, plane_generators, rand_tetrahedron_vertices
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def test_split(benchmark):
|
def test_split(benchmark: Callable) -> None:
|
||||||
poly = build_rand_tetrahedron()
|
poly = build_rand_tetrahedron()
|
||||||
faceset = adze.planes_from_tetrahedron(rand_tetrahedron_vertices())
|
faceset = adze.planes_from_tetrahedron(rand_tetrahedron_vertices())
|
||||||
benchmark(adze.clip, poly, faceset[0])
|
benchmark(adze.clip, poly, faceset[0])
|
||||||
|
|
||||||
|
|
||||||
def test_split_bulk_1000(benchmark):
|
def test_split_bulk_1000(benchmark: Callable) -> None:
|
||||||
NUM_TRIALS = 1000
|
NUM_TRIALS = 1000
|
||||||
polys_bulk = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)]
|
polys_bulk = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)]
|
||||||
faceset = adze.planes_from_tetrahedron(rand_tetrahedron_vertices())
|
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
|
# Clip the first tetrahedron using the faces of the second
|
||||||
for face in faces:
|
for face in faces:
|
||||||
poly = adze.clip(poly, face)
|
poly = adze.clip(poly, face)
|
||||||
|
|
@ -49,7 +46,7 @@ def get_intersection_moments(poly, faces, poly_order):
|
||||||
return om
|
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
|
Benchmark intersection between pairs of tetrahedra
|
||||||
"""
|
"""
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,13 @@
|
||||||
|
from collections.abc import Callable
|
||||||
|
import warnings
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from pytest import approx
|
from pytest import approx
|
||||||
|
|
||||||
import numpy
|
import numpy
|
||||||
from numpy.linalg import norm
|
from numpy.linalg import norm
|
||||||
from numpy.testing import assert_allclose, assert_array_equal
|
from numpy.testing import assert_allclose
|
||||||
|
|
||||||
import adze
|
import adze
|
||||||
import adze.util
|
import adze.util
|
||||||
|
|
@ -15,7 +19,7 @@ from .utils import build_rand_tetrahedron, gen_plane_through_centroid, plane_gen
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def test_manual_tetrahedron(poly_order):
|
def test_manual_tetrahedron(poly_order: int) -> None:
|
||||||
tet = adze.build_tetrahedron([
|
tet = adze.build_tetrahedron([
|
||||||
[0,0,0],
|
[0,0,0],
|
||||||
[2,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)
|
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([
|
vertices = numpy.array([
|
||||||
[0, 0, 1],
|
[0, 0, 1],
|
||||||
[1, 1, 0],
|
[1, 1, 0],
|
||||||
|
|
@ -72,7 +76,7 @@ def test_manual_pyramid(poly_order):
|
||||||
stack_split(poly, 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
|
Splits some tetrahedrons through their centroids and
|
||||||
checks if each two resulting volumes sum to the original
|
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
|
# split them all with the same plane
|
||||||
poly12 = [adze.split(p, plane) for p in polys]
|
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(orig)
|
||||||
adze.util.check_poly(p1)
|
adze.util.check_poly(p1)
|
||||||
adze.util.check_poly(p2)
|
adze.util.check_poly(p2)
|
||||||
check_split_moments(orig, p1, p2, poly_order)
|
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
|
Splits a non-convex polyhedron and checks if the resulting
|
||||||
volumes add up to the original
|
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)
|
adze.util.check_poly(poly)
|
||||||
logger.debug("poly is valid.")
|
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_l = adze.clip(poly, plane)
|
||||||
poly_r = adze.clip(poly, flip_plane(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)
|
||||||
|
|
@ -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)
|
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
|
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.
|
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)
|
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
|
Starting with a tetrahedron, recusively split until the pieces
|
||||||
are smaller than `MIN_VOLUME` or have been split more than `max_depth` times,
|
are smaller than `MIN_VOLUME` or have been split more than `max_depth` times,
|
||||||
then check that the moments add up as expected.
|
then check that the moments add up as expected.
|
||||||
'''
|
"""
|
||||||
logger.info(f'Recursively splitting {num_trials} tetrahedra, maximum depth {max_depth}:')
|
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):
|
for _ in range(num_trials):
|
||||||
stack_split(build_rand_tetrahedron(), poly_order, plane_fun=gen_plane_through_centroid, max_depth=max_depth)
|
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):
|
for _ in range(num_trials):
|
||||||
stack_split(build_rand_tetrahedron(), poly_order, max_depth=max_depth)
|
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):
|
for t in range(num_trials):
|
||||||
perturb = 10 ** -(1 + t % 16)
|
perturb = 10 ** -(1 + t % 16)
|
||||||
stack_split(build_rand_tetrahedron(), poly_order, perturb=perturb, max_depth=max_depth)
|
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))
|
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]}')
|
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
|
# Make sure each part is smaller than the whole
|
||||||
if not ml[0] < m0[0] * (1.0 + TOL_WARN):
|
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))
|
assert(ml[0] < m0[0] * (1.0 + TOL_FAIL))
|
||||||
if not mr[0] < m0[0] * (1.0 + TOL_WARN):
|
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))
|
assert(mr[0] < m0[0] * (1.0 + TOL_FAIL))
|
||||||
|
|
||||||
# make sure the sum of moments equals the original
|
# 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}')
|
# logger.error(f'diff failed: {diff} \n original {m0} \n left {ml} \n right {mr}')
|
||||||
# assert(False)
|
# assert(False)
|
||||||
if not numpy.allclose(m0, mtot, atol=TOL_WARN):
|
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
|
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)]
|
stack = [(poly, 0)]
|
||||||
|
|
||||||
i = 0
|
i = 0
|
||||||
|
|
|
||||||
|
|
@ -2,17 +2,18 @@ from typing import TYPE_CHECKING
|
||||||
import logging
|
import logging
|
||||||
import warnings
|
import warnings
|
||||||
from time import perf_counter
|
from time import perf_counter
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from pytest import approx
|
|
||||||
import numpy
|
import numpy
|
||||||
from numpy.linalg import norm
|
from numpy.typing import NDArray
|
||||||
from numpy.testing import assert_allclose, assert_array_equal
|
from numpy.testing import assert_allclose
|
||||||
|
|
||||||
import adze
|
import adze
|
||||||
import adze.util
|
import adze.util
|
||||||
|
|
||||||
from .utils import TOL_FAIL, TOL_WARN, PRNG, MIN_VOLUME, flip_plane, tetrahedron_volume
|
from .utils import TOL_FAIL, TOL_WARN, rand_tetrahedron_vertices
|
||||||
from .utils import build_rand_tetrahedron, gen_plane_through_centroid, plane_generators, gen_torus_brep, 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:
|
if TYPE_CHECKING:
|
||||||
import matplotlib
|
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)
|
assert_allclose(moments, voxsum, atol=TOL_FAIL)
|
||||||
if not numpy.allclose(moments, voxsum, atol=TOL_WARN):
|
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(
|
def visualize_isosurface(
|
||||||
grid,
|
grid: NDArray[numpy.float64],
|
||||||
edges,
|
edges: NDArray[numpy.int64],
|
||||||
level: float | None = None,
|
level: float | None = None,
|
||||||
show_edges: bool = True,
|
show_edges: bool = True,
|
||||||
finalize: bool = True,
|
finalize: bool = True,
|
||||||
|
|
@ -62,10 +63,11 @@ def visualize_isosurface(
|
||||||
show_edges: Whether to draw triangle edges. Default True
|
show_edges: Whether to draw triangle edges. Default True
|
||||||
finalize: Whether to call pyplot.show() after constructing the plot. Default True
|
finalize: Whether to call pyplot.show() after constructing the plot. Default True
|
||||||
"""
|
"""
|
||||||
from matplotlib import pyplot # type: ignore
|
from matplotlib import pyplot
|
||||||
import skimage.measure # type: ignore
|
import skimage.measure
|
||||||
# Claims to be unused, but needed for subplot(projection='3d')
|
# Claims to be unused, but needed for subplot(projection='3d')
|
||||||
from mpl_toolkits.mplot3d import Axes3D
|
from mpl_toolkits.mplot3d import Axes3D
|
||||||
|
del Axes3D # imported for side-effects only
|
||||||
|
|
||||||
if level is None:
|
if level is None:
|
||||||
level = grid.mean()
|
level = grid.mean()
|
||||||
|
|
@ -92,7 +94,7 @@ def visualize_isosurface(
|
||||||
ybs = 0.5 * max_range * mg[1].flatten() + 0.5 * (ys.max() + ys.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())
|
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:
|
# 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')
|
ax.plot([xb], [yb], [zb], 'w')
|
||||||
|
|
||||||
if finalize:
|
if finalize:
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import numpy
|
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
|
from numpy.linalg import norm
|
||||||
import random
|
import random
|
||||||
|
|
||||||
|
|
@ -21,7 +22,12 @@ MIN_VOLUME = 1e-8
|
||||||
POLY_ORDER = 0
|
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
|
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
|
return vertices, faces
|
||||||
|
|
||||||
|
|
||||||
def tetrahedron_volume(vertices):
|
def tetrahedron_volume(vertices: NDArray[numpy.float64]) -> float:
|
||||||
ad, bd, cd = vertices[0:3] - vertices[3]
|
ad, bd, cd = vertices[0:3] - vertices[3]
|
||||||
return -ad @ numpy.cross(bd, cd) / 6
|
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])
|
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,
|
# generates a random tetrahedron with vertices on the unit sphere,
|
||||||
# guaranteeing a volume of at least min_volume
|
# guaranteeing a volume of at least min_volume
|
||||||
volume = 0
|
volume = 0
|
||||||
|
|
@ -77,11 +83,11 @@ def rand_tetrahedron_vertices(min_volume: float = MIN_VOLUME):
|
||||||
return verts
|
return verts
|
||||||
|
|
||||||
|
|
||||||
def build_rand_tetrahedron(min_volume: float = MIN_VOLUME):
|
def build_rand_tetrahedron(min_volume: float = MIN_VOLUME) -> adze.poly_t:
|
||||||
return adze.build_tetrahedron(rand_tetrahedron_vertices())
|
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
|
# generates a random, isotropically distributed unit vector
|
||||||
s = 0
|
s = 0
|
||||||
while s == 0:
|
while s == 0:
|
||||||
|
|
@ -90,7 +96,7 @@ def rand_unit_vector():
|
||||||
return v / s
|
return v / s
|
||||||
|
|
||||||
|
|
||||||
def get_centroid(poly):
|
def get_centroid(poly: adze.poly_t) -> NDArray[numpy.floating]:
|
||||||
"""
|
"""
|
||||||
Average the vertices to get the centroid
|
Average the vertices to get the centroid
|
||||||
"""
|
"""
|
||||||
|
|
@ -98,7 +104,9 @@ def get_centroid(poly):
|
||||||
return centroid
|
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
|
Generate a randomly-oriented plane passing through the polyhedron's centroid
|
||||||
"""
|
"""
|
||||||
|
|
@ -108,7 +116,9 @@ def gen_plane_through_centroid(poly):
|
||||||
return n, d
|
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
|
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)
|
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
|
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)
|
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
|
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())
|
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
|
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())
|
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
|
Generate a plane passing through a vertex, but otherwise randomly oriented
|
||||||
"""
|
"""
|
||||||
|
|
@ -163,7 +181,11 @@ def gen_plane_through_vertex(poly):
|
||||||
return n, d
|
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
|
Generate a plane passing through three given points
|
||||||
"""
|
"""
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import numpy
|
||||||
from numpy import sin, cos
|
from numpy import sin, cos
|
||||||
from numpy.typing import ArrayLike
|
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:
|
def rotate(poly: poly_t, theta: float, axis: int) -> poly_t:
|
||||||
|
|
|
||||||
120
adze/util.py
120
adze/util.py
|
|
@ -1,11 +1,21 @@
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from collections.abc import Sequence
|
||||||
import numpy
|
import numpy
|
||||||
from numpy.typing import ArrayLike, NDArray
|
from numpy.typing import NDArray
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
import stl
|
||||||
|
|
||||||
|
|
||||||
plane_t = tuple[NDArray, float]
|
plane_t = tuple[NDArray, float]
|
||||||
poly_t = dict[str, NDArray]
|
poly_t = dict[str, NDArray]
|
||||||
|
|
||||||
|
|
||||||
|
class AdzeError(Exception):
|
||||||
|
""" Custom error for Adze """
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def build_empty() -> poly_t:
|
def build_empty() -> poly_t:
|
||||||
"""
|
"""
|
||||||
Build an empty Schlegel representation (containing no vertices).
|
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]
|
faces: list[list[NDArray[numpy.integer]]] | NDArray[numpy.integer]
|
||||||
if num_verts < 1000:
|
if num_verts < 1000:
|
||||||
# ~3n^2 in memory, but much faster in cases where n isn't prohibitively large
|
# ~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
|
faces[:, 0] = v_current
|
||||||
|
|
||||||
def add_edges(edge_id, v_nxt, k):
|
def add_edges(edge_id: NDArray[numpy.intp], v_nxt: NDArray[numpy.intp], kk: int) -> None:
|
||||||
faces[edge_id, k] = v_nxt
|
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 = []
|
faces_set = []
|
||||||
for row in faces[~remove, :k]:
|
for row in faces[~remove, :kk]:
|
||||||
faces_set.append(row[row >= 0])
|
faces_set.append(row[row >= 0])
|
||||||
return faces_set
|
return faces_set
|
||||||
else:
|
else:
|
||||||
# Alternative approach, less memory-intensive but slower
|
# 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):
|
def add_edges(edge_id: NDArray[numpy.intp], v_nxt: NDArray[numpy.intp], kk: int) -> None: # noqa: ARG001
|
||||||
for i, vn in zip(edge_id, v_nxt):
|
for ii, vn in zip(edge_id, v_nxt, strict=True):
|
||||||
faces[i].append(vn)
|
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 = []
|
faces_set = []
|
||||||
for i in numpy.where(~remove)[0]:
|
for ii in numpy.where(~remove)[0]:
|
||||||
faces_set.append(faces[i])
|
faces_set.append(faces[ii])
|
||||||
return faces_set
|
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)
|
a) the vertex index decreases (stop and mark for removal)
|
||||||
b) we reach the original vertex (stop, done with this path)
|
b) we reach the original vertex (stop, done with this path)
|
||||||
"""
|
"""
|
||||||
k = 1
|
kk = 1
|
||||||
mask = v_next > v_current
|
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)
|
remove = numpy.logical_not(mask)
|
||||||
|
|
||||||
while mask.any():
|
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
|
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_mask = vv[2] < vv[1]
|
||||||
remove[v[0][remove_mask]] = True
|
remove[vv[0][remove_mask]] = True
|
||||||
|
|
||||||
mask = numpy.logical_and(v[3] != v[1], ~remove_mask)
|
mask = numpy.logical_and(vv[3] != vv[1], ~remove_mask)
|
||||||
v = v[:, mask]
|
vv = vv[:, mask]
|
||||||
k += 1
|
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
|
Returns m such that a[m] == b
|
||||||
Assumes that all elements appear exactly once in each array
|
Assumes that all elements appear exactly once in each array
|
||||||
|
|
@ -146,17 +156,17 @@ def _get_map(a, b):
|
||||||
return sa[r]
|
return sa[r]
|
||||||
|
|
||||||
|
|
||||||
def _get_map_rows(a, b):
|
def _get_map_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]:
|
||||||
"""
|
"""
|
||||||
Row-wise _get_map
|
Row-wise _get_map
|
||||||
"""
|
"""
|
||||||
dims = numpy.maximum(a.max(0), b.max(0)) + 1
|
dims = numpy.maximum(a.max(0), b.max(0)) + 1
|
||||||
a1d = numpy.ravel_multi_index(a.T, dims)
|
a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore
|
||||||
b1d = numpy.ravel_multi_index(b.T, dims)
|
b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore
|
||||||
return _get_map(a1d, b1d)
|
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
|
Returns m, n such that a[m] == b, b[n] == a
|
||||||
Assumes that all elements appear exactly once in each array
|
Assumes that all elements appear exactly once in each array
|
||||||
|
|
@ -173,32 +183,32 @@ def _get_maps(a, b):
|
||||||
return m, n
|
return m, n
|
||||||
|
|
||||||
|
|
||||||
def _get_maps_rows(a, b):
|
def _get_maps_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]:
|
||||||
"""
|
"""
|
||||||
Row-wise _get_maps
|
Row-wise _get_maps
|
||||||
"""
|
"""
|
||||||
dims = numpy.maximum(a.max(0), b.max(0)) + 1
|
dims = numpy.maximum(a.max(0), b.max(0)) + 1
|
||||||
a1d = numpy.ravel_multi_index(a.T, dims)
|
a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore
|
||||||
b1d = numpy.ravel_multi_index(b.T, dims)
|
b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore
|
||||||
return _get_maps(a1d, b1d)
|
return _get_maps(a1d, b1d)
|
||||||
|
|
||||||
|
|
||||||
def _argsort_rows(a):
|
def _argsort_rows(a: NDArray) -> NDArray[numpy.intp]:
|
||||||
"""
|
"""
|
||||||
Row-wise argsort
|
Row-wise argsort
|
||||||
"""
|
"""
|
||||||
dims = a.max(0) + 1
|
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)
|
return numpy.argsort(a1d)
|
||||||
|
|
||||||
|
|
||||||
def _searchsorted_rows(a, b):
|
def _searchsorted_rows(a: NDArray, b: NDArray) -> NDArray[numpy.intp]:
|
||||||
"""
|
"""
|
||||||
Row-wise searchsorted
|
Row-wise searchsorted
|
||||||
"""
|
"""
|
||||||
dims = numpy.maximum(a.max(0), b.max(0)) + 1
|
dims = numpy.maximum(a.max(0), b.max(0)) + 1
|
||||||
a1d = numpy.ravel_multi_index(a.T, dims)
|
a1d = numpy.ravel_multi_index(a.T, dims) # type: ignore
|
||||||
b1d = numpy.ravel_multi_index(b.T, dims)
|
b1d = numpy.ravel_multi_index(b.T, dims) # type: ignore
|
||||||
return numpy.searchsorted(a1d, b1d)
|
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`.
|
This is slow! Default `True`.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
Exception if the polyhedron fails a check
|
AdzeError if the polyhedron fails a check
|
||||||
"""
|
"""
|
||||||
neighbors = poly['neighbors']
|
neighbors = poly['neighbors']
|
||||||
vertices = poly['vertices']
|
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)
|
out_of_bounds = numpy.logical_or(neighbors >= vertices.shape[0], neighbors < 0)
|
||||||
if numpy.any(out_of_bounds):
|
if numpy.any(out_of_bounds):
|
||||||
which_vertices = numpy.where(out_of_bounds)[0]
|
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)
|
repeated_neighbors = neighbors == numpy.roll(neighbors, 1, axis=1)
|
||||||
if numpy.any(repeated_neighbors):
|
if numpy.any(repeated_neighbors):
|
||||||
which_vertices = numpy.where(repeated_neighbors)[0]
|
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())
|
vertex_uses = numpy.bincount(neighbors.ravel())
|
||||||
if numpy.any(vertex_uses != 3):
|
if numpy.any(vertex_uses != 3):
|
||||||
which_vertices = numpy.where(vertex_uses != 3)[0]
|
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')
|
' should be exactly 3')
|
||||||
|
|
||||||
# check for 3-vertex-connectedness (~n^3 because need bfs for each removed vertex pair)
|
# 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]
|
va = part_verts[ia]
|
||||||
for vb in part_verts[ia + 1:]:
|
for vb in part_verts[ia + 1:]:
|
||||||
# pick vc != {va, vb}
|
# pick vc != {va, vb}
|
||||||
vc = (vcs - set((va, vb))).pop()
|
vc = (vcs - {va, vb}).pop()
|
||||||
|
|
||||||
# flood-fill from vc without passing through va, vb
|
# flood-fill from vc without passing through va, vb
|
||||||
visited.fill(False)
|
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
|
# Make sure we touched all vertices in the component
|
||||||
if not visited[components == part_id].all():
|
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
|
Plot a boundary representation
|
||||||
"""
|
"""
|
||||||
|
|
@ -292,22 +302,22 @@ def plot_brep(brep) -> None:
|
||||||
pyplot.show()
|
pyplot.show()
|
||||||
|
|
||||||
|
|
||||||
def brep_to_stls(brep):
|
def brep_to_stls(brep: Sequence[dict[str, NDArray]]) -> list['stl.mesh.Mesh']:
|
||||||
import stl
|
import stl
|
||||||
|
|
||||||
meshes = []
|
meshes = []
|
||||||
for component in brep:
|
for component in brep:
|
||||||
triangles = []
|
tri_list = []
|
||||||
for face in component['faces']:
|
for face in component['faces']:
|
||||||
for i in range(1, len(face) - 1):
|
for ii in range(1, len(face) - 1):
|
||||||
triangles.append([face[0], face[i], face[i+1]])
|
tri_list.append([face[0], face[ii], face[ii + 1]])
|
||||||
triangles = numpy.array(triangles, dtype=int)
|
triangles = numpy.asarray(tri_list, dtype=int)
|
||||||
|
|
||||||
m = stl.mesh.Mesh(numpy.empty(triangles.shape[0], dtype=stl.mesh.Mesh.dtype))
|
mm = stl.mesh.Mesh(numpy.empty(triangles.shape[0], dtype=stl.mesh.Mesh.dtype))
|
||||||
for i, f in enumerate(triangles):
|
for ii, ff in enumerate(triangles):
|
||||||
for j in range(3):
|
for jj in range(3):
|
||||||
m.vectors[i, j] = component['vertices'][f[j], :]
|
mm.vectors[ii, jj] = component['vertices'][ff[jj], :]
|
||||||
|
|
||||||
# m.save('pyr.stl')
|
# mm.save('pyr.stl')
|
||||||
meshes.append(m)
|
meshes.append(mm)
|
||||||
return meshes
|
return meshes
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,11 @@ from collections.abc import Sequence
|
||||||
import numpy
|
import numpy
|
||||||
from numpy.typing import ArrayLike, NDArray
|
from numpy.typing import ArrayLike, NDArray
|
||||||
|
|
||||||
from . import poly_t, plane_t
|
from . import poly_t
|
||||||
from .split import split, clip
|
from .split import split, clip
|
||||||
from .moments import get_moments, number_of_moments
|
from .moments import get_moments, number_of_moments
|
||||||
from .shapes import planes_from_box
|
from .shapes import planes_from_box
|
||||||
|
from .util import AdzeError
|
||||||
|
|
||||||
|
|
||||||
def voxelize(
|
def voxelize(
|
||||||
|
|
@ -45,8 +46,7 @@ def voxelize(
|
||||||
|
|
||||||
num_planes = numpy.array([e.size for e in aplanes], dtype=int)
|
num_planes = numpy.array([e.size for e in aplanes], dtype=int)
|
||||||
if (num_planes < 2).any():
|
if (num_planes < 2).any():
|
||||||
# TODO raw exception
|
raise AdzeError(f'Need at least two planes per dimension. Got {num_planes} planes.')
|
||||||
raise Exception(f'Need at least two planes per dimension. Got {num_planes} planes.')
|
|
||||||
|
|
||||||
if include_outside:
|
if include_outside:
|
||||||
grid_shape = num_planes + 1
|
grid_shape = num_planes + 1
|
||||||
|
|
|
||||||
|
|
@ -36,10 +36,10 @@ classifiers = [
|
||||||
"Topic :: Multimedia :: Graphics",
|
"Topic :: Multimedia :: Graphics",
|
||||||
"Topic :: Scientific/Engineering",
|
"Topic :: Scientific/Engineering",
|
||||||
]
|
]
|
||||||
requires-python = ">=3.8"
|
requires-python = ">=3.11"
|
||||||
dynamic = ["version"]
|
dynamic = ["version"]
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"numpy~=1.21",
|
"numpy>=1.26",
|
||||||
]
|
]
|
||||||
|
|
||||||
[tool.hatch.version]
|
[tool.hatch.version]
|
||||||
|
|
@ -47,3 +47,45 @@ path = "adze/__init__.py"
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
stl = ["stl"]
|
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
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue