adze/tpy_r3d.py
2018-03-21 12:01:35 -07:00

633 lines
19 KiB
Python

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 chop import pyr3d
from chop.shapes import build_tetrahedron, build_box, planes_from_tetrahedron, volume_of_tetrahedron
from chop.boundary import build_polyhedron, boundary_from_poly
from chop.util import check_poly, number_of_moments
from chop.voxel import voxelize
logger = logging.getLogger(__name__)
try:
profile
except NameError:
def profile(f):
return f
# 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
# maximum recursion depth allowed for recursive tests
MAX_DEPTH = 6
# order of polynomial integration for all tests
POLY_ORDER = 0
def check(om, m1, m2):
logger.debug(f'Check: original {om[0]} parts {(m1[0], m2[0])} sum {m1[0] + m2[0]}')
# Make sure each part is smaller than the whole
assert(m1[0] < om[0] * (1.0 + TOL_FAIL))
assert(m2[0] < om[0] * (1.0 + TOL_FAIL))
if not m1[0] < om[0] * (1.0 + TOL_WARN):
warnings.warn('m1[0] < om[0]')
if not m2[0] < om[0] * (1.0 + TOL_WARN):
warnings.warn('m2[0] < om[0]')
# make sure the sum of moments equals the original
diff = numpy.abs(om - (m1 + m2))
if not numpy.all(diff < TOL_FAIL):
logger.error(f'diff failed: {diff} \n original {om} \n left {m1} \n right {m2}')
assert(False)
if not numpy.all(diff < TOL_WARN):
warnings.warn('Moments outside tolerance')
def thru_cent_3d(poly):
# make a randomly-oriented plane passing through the centroid
centroid = get_centroid_3d(poly)
n = rand_uvec_3d()
d = -n @ centroid
return n, d
def thru_face_3d(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 point_plane_3d(*points)
def thru_edge_cent_3d(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_3d(poly)
return point_plane_3d(p0, p1, centroid)
def thru_edge_rand_3d(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 point_plane_3d(p0, p1, rand_uvec_3d())
def thru_vert_cent_3d(poly):
# make a plane coplanar with a vertex and the centroid, but otherwise randomly oriented
p0 = random.choice(poly['vertices'])
centroid = get_centroid_3d(poly)
return point_plane_3d(p0, centroid, rand_uvec_3d())
def thru_vert_rand_3d(poly):
# make a plane coplanar with a vertex, but otherwise randomly oriented
p0 = random.choice(poly['vertices'])
n = rand_uvec_3d()
d = -n @ p0
return n, d
def point_plane_3d(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_uvec_3d():
# generates a random, isotropically distributed unit vector
ntmp = 0
while ntmp == 0:
tmp = numpy.random.randn(3)
ntmp = norm(tmp)
return tmp / ntmp
def rand_tet_3d(minvol: float):
# generates a random tetrahedron with vertices on the unit sphere,
# guaranteeing a volume of at least MIN_VOL (to avoid degenerate cases)
tetvol = 0.0
while tetvol < minvol:
verts = [rand_uvec_3d() for _ in range(4)]
tetvol = volume_of_tetrahedron(verts)
if tetvol < 0.0:
verts[2], verts[3] = verts[3], verts[2]
tetvol = -tetvol
return verts
def get_centroid_3d(poly):
# get the "centroid" by averaging vertices
centroid = numpy.sum(poly['vertices'], axis=0) / poly['vertices'].shape[0]
return centroid
def test_split_tet_manual():
tet = build_tetrahedron([
[0,0,0],
[2,0,0],
[0,2,0],
[0,0,2]])
logger.debug(f'Splitting manual tetrahedron {tet}')
logger.debug(f'orient volume {volume_of_tetrahedron(tet["vertices"])}')
plane = numpy.array((-1,0,0)), 1
p_left, p_right = pyr3d.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)
om = pyr3d.reduce(tet, 0)
m1 = pyr3d.reduce(p_left, 0)
m2 = pyr3d.reduce(p_right, 0)
logger.debug(f'0th moments: tot {om}, left {m1}, right {m2}')
check(om, m1, m2)
om = pyr3d.reduce(tet, POLY_ORDER)
m1 = pyr3d.reduce(p_left, POLY_ORDER)
m2 = pyr3d.reduce(p_right, POLY_ORDER)
logger.debug(f'0th moments: tot {om}, left {m1}, right {m2}')
check(om, m1, m2)
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
opoly = [build_tetrahedron(rand_tet_3d(MIN_VOL)) for _ in range(ntets)]
plane = thru_cent_3d(opoly[ntets//7])
# split them all about the same plane
poly12 = [pyr3d.split(o, plane) for o in opoly]
poly1, poly2 = zip(*poly12)
for orig, p1, p2 in zip(opoly, poly1, poly2):
check_poly(orig)
check_poly(p1)
check_poly(p2)
# reduce the original and its two parts
om = pyr3d.reduce(orig, POLY_ORDER)
m1 = pyr3d.reduce(p1, POLY_ORDER)
m2 = pyr3d.reduce(p2, POLY_ORDER)
check(om, m1, m2)
def time_split():
NUM_TRIALS = int(10e3)
logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.')
polys = [build_tetrahedron(rand_tet_3d(MIN_VOL)) for _ in range(NUM_TRIALS)]
facesets = [planes_from_tetrahedron(rand_tet_3d(MIN_VOL)) for _ in range(NUM_TRIALS)]
t0 = perf_counter()
for t in range(NUM_TRIALS):
# clip the first tet against the faces of the second
poly = polys[t]
for face in facesets[t]:
_poly = pyr3d.clip(poly, face)
if (t+1) % 1000 == 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}')
bulk = {
'vertices': numpy.vstack(p['vertices'] for p in polys),
'neighbors': numpy.vstack(p['neighbors'] for p in polys) + numpy.arange(NUM_TRIALS).repeat(4)[:, None] * 4,
}
t1 = perf_counter()
poly = pyr3d.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 = int(10e3)
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_tetrahedron(rand_tet_3d(MIN_VOL))
# generate the second random tet
faces = planes_from_tetrahedron(rand_tet_3d(MIN_VOL))
# clip the first tet against the faces of the second
for face in faces:
poly = pyr3d.clip(poly, face)
# find the moments (up to quadratic order) of the clipped poly
_om = pyr3d.reduce(poly, POLY_ORDER)
if (t+1) % 1000 == 0:
t_each = (perf_counter() - t0) / (t + 1)
logger.info(f'time per split/reduce for {t+1} splits: {t_each}')
logger.info(f'done timing, time per split/reduce: {(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)
opoly = {
'vertices': vertices,
'neighbors': neighbors,
}
logger.debug('good: {}'.format(check_poly(opoly)))
# split along the x-axis (two single connected components this direction)
plane = [numpy.array((1, 0, 0)),
-0.5 * (NZIGS - 1)]
poly1 = pyr3d.clip(opoly, plane)
plane[0] *= -1
plane[1] *= -1
poly2 = pyr3d.clip(opoly, plane)
om = pyr3d.reduce(opoly, POLY_ORDER)
m1 = pyr3d.reduce(poly1, POLY_ORDER)
m2 = pyr3d.reduce(poly2, POLY_ORDER)
check(om, m1, m2)
# split along the z-axis (two single connected components this direction)
plane = [numpy.array((0, 0, 1)), -0.5]
poly1 = pyr3d.clip(opoly, plane)
plane[0] *= -1
plane[1] *= -1
poly2 = pyr3d.clip(opoly, plane)
om = pyr3d.reduce(opoly, POLY_ORDER)
m1 = pyr3d.reduce(poly1, POLY_ORDER)
m2 = pyr3d.reduce(poly2, POLY_ORDER)
check(om, m1, m2)
# split along the y-axis (multiple connected components this direction)
plane = [numpy.array((0, 1, 0)),
-0.5 * (1.0 + ZOFF)]
poly1 = pyr3d.clip(opoly, plane)
plane[0] *= -1
plane[1] *= -1
poly2 = pyr3d.clip(opoly, plane)
om = pyr3d.reduce(opoly, POLY_ORDER)
m1 = pyr3d.reduce(poly1, POLY_ORDER)
m2 = pyr3d.reduce(poly2, POLY_ORDER)
check(om, m1, m2)
def test_recursive_splitting_nondegenerate():
# recursively splits a polyhedron (starting from a tet) through the centroid,
# checking to see that the resulting volumes add up properly.
NUM_TRIALS = 10
logger.info(f'Recursively splitting {NUM_TRIALS} tetrahedra, maximum splits per tet is {MAX_DEPTH}.')
for _ in range(NUM_TRIALS):
# generate a random tet
opoly = build_tetrahedron(rand_tet_3d(MIN_VOL))
stack_split(opoly, plane_fun=thru_cent_3d)
def test_recursive_splitting_degenerate():
# recursively splits a polyhedron (starting from a tet) with a cut plane
# that is always degenerate with the tet in some way,
# checking to see that the resulting volumes add up properly.
NUM_TRIALS = 10
logger.info(f'Recursively splitting {NUM_TRIALS} tetrahedra, maximum splits per tet is {MAX_DEPTH}.')
for _ in range(NUM_TRIALS):
# generate a random tet
opoly = build_tetrahedron(rand_tet_3d(MIN_VOL))
stack_split(opoly)
def test_recursive_splitting_degenerate_perturbed():
# recursively splits a polyhedron (starting from a tet) with a cut plane
# that is always degenerate with the tet in some way,
# checking to see that the resulting volumes add up properly.
# In this one, the cut plane is perturbed by a small amount.
MIN_PERTURB_ORDER = -17
MAX_PERTURB_ORDER = -1
NUM_TRIALS = 10
logger.info(f'Recursively splitting {NUM_TRIALS} tetrahedra, maximum splits per tet is {MAX_DEPTH}.')
for t in range(NUM_TRIALS):
# generate a random tet
opoly = build_tetrahedron(rand_tet_3d(MIN_VOL))
# compute the order of magnitude by which to perturb the clip plane,
# determined by the trial number
perturb = pow(10, MIN_PERTURB_ORDER + t%(MAX_PERTURB_ORDER - MIN_PERTURB_ORDER))
# generate a random tet
opoly = build_tetrahedron(rand_tet_3d(MIN_VOL))
stack_split(opoly, perturb=perturb)
@profile
def test_voxelization():
# Test r3d_voxelize() by checking that the voxelized moments
# do indeed sum to those of the original input
POLY_ORDER = 4
NGRID = 25
# create a random tet in the unit box
verts = (numpy.array(rand_tet_3d(MIN_VOL)) + 1) / 2
poly = build_tetrahedron(verts)
# get its original moments for reference
moments = pyr3d.reduce(poly, POLY_ORDER)
# voxelize it
dx = numpy.ones((3,)) / NGRID
logger.info(f'Voxelizing a tetrahedron to a grid with dx = {dx} and moments of order {POLY_ORDER}')
# logger.info(f'Minimum index box = {ibox}')
grid = voxelize(poly, dx, poly_order=POLY_ORDER)
# visualize_voxels(grid)
# make sure the sum of each moment equals the original
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(opoly, plane_fun=None, perturb=0):
stack = [(opoly, 0)]
i = 0
# recursively split the poly
while stack:
i += 1
opoly, depth = stack.pop()
# generate a random plane from one of a few
# possible degenerate configurations, ensuring that it
# has a valid unit normal
if plane_fun is None:
while True:
pfun_used = random.choice(choptions_3d)
plane = pfun_used(opoly)
if norm(plane[0]) != 0:
break
plane = list(plane)
logger.debug(f'used {pfun_used}')
else:
plane = list(plane_fun(opoly))
# randomly perturb the plane
plane[0] *= 1 + perturb * (numpy.random.rand() - 0.5)
plane[1] *= 1 + perturb * (numpy.random.rand() - 0.5)
# split the poly by making two copies of the original poly
# and them clipping them against the same plane, with one
# oriented oppositely
poly1 = pyr3d.clip(opoly, plane)
plane[0] *= -1
plane[1] *= -1
poly2 = pyr3d.clip(opoly, plane)
# reduce the original and its two parts
om = pyr3d.reduce(opoly, POLY_ORDER)
m1 = pyr3d.reduce(poly1, POLY_ORDER)
m2 = pyr3d.reduce(poly2, POLY_ORDER)
check(om, m1, m2)
logger.debug(f'nstack = {len(stack)}, depth = {depth}, '
f'opoly = {om[0]:.10e}, p1 = {m1[0]:.10e}, p2 = {m2[0]:.10e}, '
f'err = {abs(1.0 - om[0]/(m1[0] + m2[0])):.10e}')
# push the children to the stack if they have
# an acceptably large volume
if depth < MAX_DEPTH:
if m1[0] > MIN_VOL:
stack.append((poly1, depth + 1))
if m2[0] > MIN_VOL:
stack.append((poly2, 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
opoly = build_polyhedron(vertices, faces)
check_poly(opoly)
stack_split(opoly)
brep = boundary_from_poly(opoly)
logger.debug(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)
choptions_3d = [thru_cent_3d, thru_face_3d,
thru_edge_cent_3d, thru_edge_rand_3d,
thru_vert_cent_3d, thru_vert_rand_3d]
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_nondegen')
test_recursive_splitting_nondegenerate()
logger.info('split_degen')
test_recursive_splitting_degenerate()
logger.info('split_degen_perturbed')
test_recursive_splitting_degenerate_perturbed()
logger.info('voxelization')
test_voxelization()
logger.info('test_tet_tet_timing')
test_tet_tet_timing()
logger.info('time_split')
time_split()
logger.info('success')