From c1442960b2afd1b75b4c9e35e79ba00bf139bf13 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 15 Mar 2020 22:18:02 -0700 Subject: [PATCH] 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')