adze/adze/test/test_voxel.py

115 lines
4 KiB
Python
Raw Normal View History

2024-07-30 23:45:47 -07:00
from typing import TYPE_CHECKING
2020-03-15 22:18:02 -07:00
import logging
2024-07-30 23:45:47 -07:00
import warnings
from time import perf_counter
2022-08-18 23:49:48 -07:00
import numpy
from numpy.typing import NDArray
from numpy.testing import assert_allclose
2020-03-15 22:18:02 -07:00
import adze
import adze.util
from .utils import TOL_FAIL, TOL_WARN, rand_tetrahedron_vertices
#from .utils import PRNG, MIN_VOLUME, flip_plane, tetrahedron_volume
#from .utils import build_rand_tetrahedron, gen_plane_through_centroid, plane_generators, gen_torus_brep
2020-03-15 22:18:02 -07:00
2024-07-30 23:45:47 -07:00
if TYPE_CHECKING:
import matplotlib
2020-03-15 22:18:02 -07:00
logger = logging.getLogger(__name__)
2024-07-30 23:45:47 -07:00
def test_voxelization(poly_order: int, grid_resolution: int | None = None) -> None:
2020-03-15 22:18:02 -07:00
"""
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
2020-03-15 22:18:02 -07:00
verts = 1.5 * (numpy.array(rand_tetrahedron_vertices()) + 1)
poly = adze.build_tetrahedron(verts)
moments = adze.get_moments(poly, poly_order)
edges = [numpy.linspace(-1, 3, grid_resolution) for _ in range(3)]
logger.info(f'Voxelizing a tetrahedron to a grid with moments of order {poly_order}')
t0 = perf_counter()
grid = adze.voxelize(poly, edges, order=poly_order)
logger.info(f'voxel time: {perf_counter() - t0}')
#visualize_isosurface(grid[:, :, :, 0], edges)
voxsum = numpy.sum(grid, axis=(0, 1, 2))
assert_allclose(moments, voxsum, atol=TOL_FAIL)
if not numpy.allclose(moments, voxsum, atol=TOL_WARN):
warnings.warn('Moments failed tolerance in voxels', stacklevel=1)
2020-03-15 22:18:02 -07:00
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])
2024-07-30 23:45:47 -07:00
def visualize_isosurface(
grid: NDArray[numpy.float64],
edges: NDArray[numpy.int64],
2024-07-30 23:45:47 -07:00
level: float | None = None,
show_edges: bool = True,
finalize: bool = True,
2026-03-07 07:53:02 -08:00
) -> tuple['matplotlib.figure.Figure', 'matplotlib.axes.Axes']:
2020-03-15 22:18:02 -07:00
"""
Draw an isosurface plot of the device.
2021-02-07 19:28:37 -08:00
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
2020-03-15 22:18:02 -07:00
"""
from matplotlib import pyplot
import skimage.measure
2020-03-15 22:18:02 -07:00
# Claims to be unused, but needed for subplot(projection='3d')
from mpl_toolkits.mplot3d import Axes3D
del Axes3D # imported for side-effects only
2020-03-15 22:18:02 -07:00
if level is None:
level = grid.mean()
# Find isosurface with marching cubes
2024-07-30 23:46:43 -07:00
verts, faces, _normals, _values = skimage.measure.marching_cubes(grid, level)
2020-03-15 22:18:02 -07:00
xs, ys, zs = (edges[aa][verts[:, aa].astype(int)] for aa in range(3))
# Draw the plot
fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')
if show_edges:
ax.plot_trisurf(xs, ys, faces, zs)
else:
ax.plot_trisurf(xs, ys, faces, zs, edgecolor='none')
# Add a fake plot of a cube to force the axes to be equal lengths
max_range = numpy.array([xs.max() - xs.min(),
ys.max() - ys.min(),
zs.max() - zs.min()], dtype=float).max()
mg = numpy.mgrid[-1:2:2, -1:2:2, -1:2:2]
xbs = 0.5 * max_range * mg[0].flatten() + 0.5 * (xs.max() + xs.min())
ybs = 0.5 * max_range * mg[1].flatten() + 0.5 * (ys.max() + ys.min())
zbs = 0.5 * max_range * mg[2].flatten() + 0.5 * (zs.max() + zs.min())
# Comment or uncomment following both lines to test the fake bounding box:
for xb, yb, zb in zip(xbs, ybs, zbs, strict=True):
2020-03-15 22:18:02 -07:00
ax.plot([xb], [yb], [zb], 'w')
if finalize:
pyplot.show()
return fig, ax