cleanup and rename

This commit is contained in:
jan 2018-03-28 10:54:15 -07:00
commit 1f332614f2
8 changed files with 153 additions and 216 deletions

View file

@ -0,0 +1,4 @@
from .split import split, clip
from .moments import get_volume, get_moments, number_of_moments
from .boundary import build_polyhedron, boundary_from_poly
from .shapes import build_tetrahedron, build_box, planes_from_tetrahedron, planes_from_box

View file

@ -4,6 +4,7 @@ from numpy.linalg import norm
from .util import _get_map, find_components, find_faces from .util import _get_map, find_components, find_faces
try: try:
# Check if running with line_profiler
profile profile
except NameError: except NameError:
def profile(f): def profile(f):

View file

@ -4,6 +4,7 @@ import numpy
from .util import find_faces from .util import find_faces
try: try:
# Check if running with line_profiler
profile profile
except NameError: except NameError:
def profile(f): def profile(f):
@ -14,6 +15,10 @@ def number_of_moments(order):
return ((order + 1) * (order + 2) * (order + 3)) // 6 return ((order + 1) * (order + 2) * (order + 3)) // 6
def get_volume(poly):
return get_moments(poly, 0)[0]
@profile @profile
def get_moments(poly, poly_order): def get_moments(poly, poly_order):
vertices = poly['vertices'] vertices = poly['vertices']
@ -102,5 +107,3 @@ def get_moments(poly, poly_order):
prevlayer, curlayer = curlayer, prevlayer prevlayer, curlayer = curlayer, prevlayer
return moments return moments

View file

@ -43,7 +43,7 @@ def build_box(rbounds):
} }
def planes_from_box(rbounds): def planes_from_box(rbounds: numpy.ndarray):
faces = [ faces = [
(( 0, 0, 1), -rbounds[0, 2]), (( 0, 0, 1), -rbounds[0, 2]),
(( 0, 0, -1), rbounds[1, 2]), (( 0, 0, -1), rbounds[1, 2]),
@ -74,9 +74,3 @@ def planes_from_tetrahedron(vertices: numpy.ndarray):
return [plane for plane in zip(n, d)] return [plane for plane in zip(n, d)]
def volume_of_tetrahedron(vertices):
ad, bd, cd = vertices[0:3] - vertices[3]
return -ad @ numpy.cross(bd, cd) / 6

View file

@ -4,6 +4,7 @@ import numpy
from .util import _searchsorted_rows, _argsort_rows from .util import _searchsorted_rows, _argsort_rows
try: try:
# Check if running with line_profiler
profile profile
except NameError: except NameError:
def profile(f): def profile(f):

View file

@ -1,6 +1,7 @@
import numpy import numpy
try: try:
# Check if running with line_profiler
profile profile
except NameError: except NameError:
def profile(f): def profile(f):

View file

@ -4,6 +4,7 @@ from .split import split
from .moments import get_moments, number_of_moments from .moments import get_moments, number_of_moments
try: try:
# Check if running with line_profiler
profile profile
except NameError: except NameError:
def profile(f): def profile(f):

View file

@ -9,20 +9,22 @@ from numpy.linalg import norm
from chop.moments import number_of_moments, get_moments from chop.moments import number_of_moments, get_moments
from chop.split import split, clip from chop.split import split, clip
from chop.shapes import build_tetrahedron, build_box, planes_from_tetrahedron, volume_of_tetrahedron from chop.shapes import build_tetrahedron, build_box, planes_from_tetrahedron
from chop.boundary import build_polyhedron, boundary_from_poly from chop.boundary import build_polyhedron, boundary_from_poly
from chop.util import check_poly from chop.util import check_poly
from chop.voxel import voxelize from chop.voxel import voxelize
logger = logging.getLogger(__name__)
try: try:
# Check if running with line_profiler
profile profile
except NameError: except NameError:
def profile(f): def profile(f):
return f return f
logger = logging.getLogger(__name__)
# numerical tolerances for pass/warn/fail tests # numerical tolerances for pass/warn/fail tests
TOL_WARN = 1e-8 TOL_WARN = 1e-8
TOL_FAIL = 1e-4 TOL_FAIL = 1e-4
@ -30,83 +32,93 @@ TOL_FAIL = 1e-4
# minimum volume allowed for test polyhedra # minimum volume allowed for test polyhedra
MIN_VOL = 1e-8 MIN_VOL = 1e-8
# maximum recursion depth allowed for recursive tests
MAX_DEPTH = 6
# order of polynomial integration for all tests # order of polynomial integration for all tests
POLY_ORDER = 0 POLY_ORDER = 2
def check(om, m1, m2): def tetrahedron_volume(vertices):
logger.debug(f'Check: original {om[0]} parts {(m1[0], m2[0])} sum {m1[0] + m2[0]}') 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 # Make sure each part is smaller than the whole
assert(m1[0] < om[0] * (1.0 + TOL_FAIL)) if not ml[0] < m0[0] * (1.0 + TOL_WARN):
assert(m2[0] < om[0] * (1.0 + TOL_FAIL)) warnings.warn('ml[0] < m0[0]')
if not m1[0] < om[0] * (1.0 + TOL_WARN): assert(ml[0] < m0[0] * (1.0 + TOL_FAIL))
warnings.warn('m1[0] < om[0]') if not mr[0] < m0[0] * (1.0 + TOL_WARN):
if not m2[0] < om[0] * (1.0 + TOL_WARN): warnings.warn('mr[0] < m0[0]')
warnings.warn('m2[0] < om[0]') 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
diff = numpy.abs(om - (m1 + m2)) diff = numpy.abs(m0 - (ml + mr))
if not numpy.all(diff < TOL_FAIL): if not numpy.all(diff < TOL_FAIL):
logger.error(f'diff failed: {diff} \n original {om} \n left {m1} \n right {m2}') logger.error(f'diff failed: {diff} \n original {m0} \n left {ml} \n right {mr}')
assert(False) assert(False)
if not numpy.all(diff < TOL_WARN): if not numpy.all(diff < TOL_WARN):
warnings.warn('Moments outside tolerance') warnings.warn('Moments outside tolerance')
return m0, ml, mr
def thru_cent_3d(poly):
def plane_centroid(poly):
# make a randomly-oriented plane passing through the centroid # make a randomly-oriented plane passing through the centroid
centroid = get_centroid_3d(poly) centroid = get_centroid_3d(poly)
n = rand_uvec_3d() n = rand_unit_vector()
d = -n @ centroid d = -n @ centroid
return n, d return n, d
def thru_face_3d(poly): def plane_face(poly):
# make a plane coplanar with a face of the poly # make a plane coplanar with a face of the poly
v0 = numpy.random.randint(poly['vertices'].shape[0]) v0 = numpy.random.randint(poly['vertices'].shape[0])
v1, v2 = random.sample(list(poly['neighbors'][v0]), 2) v1, v2 = random.sample(list(poly['neighbors'][v0]), 2)
points = (poly['vertices'][vi] for vi in (v0, v1, v2)) points = (poly['vertices'][vi] for vi in (v0, v1, v2))
return point_plane_3d(*points) return plane_points(*points)
def thru_edge_cent_3d(poly): def plane_centroid_edge(poly):
# make a plane coplanar with an edge and the centroid of the poly # make a plane coplanar with an edge and the centroid of the poly
v0 = numpy.random.randint(poly['vertices'].shape[0]) v0 = numpy.random.randint(poly['vertices'].shape[0])
v1 = random.choice(poly['neighbors'][v0]) v1 = random.choice(poly['neighbors'][v0])
p0 = poly['vertices'][v0] p0 = poly['vertices'][v0]
p1 = poly['vertices'][v1] p1 = poly['vertices'][v1]
centroid = get_centroid_3d(poly) centroid = get_centroid_3d(poly)
return point_plane_3d(p0, p1, centroid) return plane_points(p0, p1, centroid)
def thru_edge_rand_3d(poly): def plane_edge(poly):
# make a plane coplanar with an edge, but otherwise randomly oriented # make a plane coplanar with an edge, but otherwise randomly oriented
v0 = numpy.random.randint(poly['vertices'].shape[0]) v0 = numpy.random.randint(poly['vertices'].shape[0])
v1 = random.choice(poly['neighbors'][v0]) v1 = random.choice(poly['neighbors'][v0])
p0 = poly['vertices'][v0] p0 = poly['vertices'][v0]
p1 = poly['vertices'][v1] p1 = poly['vertices'][v1]
return point_plane_3d(p0, p1, rand_uvec_3d()) return plane_points(p0, p1, rand_unit_vector())
def thru_vert_cent_3d(poly): def plane_centroid_vertex(poly):
# make a plane coplanar with a vertex and the centroid, but otherwise randomly oriented # make a plane coplanar with a vertex and the centroid, but otherwise randomly oriented
p0 = random.choice(poly['vertices']) p0 = random.choice(poly['vertices'])
centroid = get_centroid_3d(poly) centroid = get_centroid_3d(poly)
return point_plane_3d(p0, centroid, rand_uvec_3d()) return plane_points(p0, centroid, rand_unit_vector())
def thru_vert_rand_3d(poly): def plane_vertex(poly):
# make a plane coplanar with a vertex, but otherwise randomly oriented # make a plane coplanar with a vertex, but otherwise randomly oriented
p0 = random.choice(poly['vertices']) p0 = random.choice(poly['vertices'])
n = rand_uvec_3d() n = rand_unit_vector()
d = -n @ p0 d = -n @ p0
return n, d return n, d
def point_plane_3d(p0, p1, p2): def plane_points(p0, p1, p2):
# generate a plane passing through the three points given # generate a plane passing through the three points given
n = numpy.cross(p1 - p0, p2 - p0) n = numpy.cross(p1 - p0, p2 - p0)
n /= norm(n) + 1e-40 n /= norm(n) + 1e-40
@ -114,28 +126,32 @@ def point_plane_3d(p0, p1, p2):
return n, d return n, d
def rand_uvec_3d(): def rand_unit_vector():
# generates a random, isotropically distributed unit vector # generates a random, isotropically distributed unit vector
ntmp = 0 s = 0
while ntmp == 0: while s == 0:
tmp = numpy.random.randn(3) v = numpy.random.randn(3)
ntmp = norm(tmp) s = norm(v)
return tmp / ntmp return v / s
def rand_tet_3d(minvol: float): def rand_tetrahedron_vertices(min_volume: float = MIN_VOL):
# 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_VOL (to avoid degenerate cases) # guaranteeing a volume of at least min_volume
tetvol = 0.0 volume = 0
while tetvol < minvol: while volume < min_volume:
verts = [rand_uvec_3d() for _ in range(4)] verts = [rand_unit_vector() for _ in range(4)]
tetvol = volume_of_tetrahedron(verts) volume = tetrahedron_volume(verts)
if tetvol < 0.0: if volume < 0:
verts[2], verts[3] = verts[3], verts[2] verts[2], verts[3] = verts[3], verts[2]
tetvol = -tetvol volume = -volume
return verts return verts
def build_rand_tetrahedron(min_volume: float = MIN_VOL):
return build_tetrahedron(rand_tetrahedron_vertices())
def get_centroid_3d(poly): def get_centroid_3d(poly):
# get the "centroid" by averaging vertices # get the "centroid" by averaging vertices
centroid = numpy.sum(poly['vertices'], axis=0) / poly['vertices'].shape[0] centroid = numpy.sum(poly['vertices'], axis=0) / poly['vertices'].shape[0]
@ -149,10 +165,11 @@ def test_split_tet_manual():
[0,2,0], [0,2,0],
[0,0,2]]) [0,0,2]])
volume = tetrahedron_volume(tet['vertices'])
logger.debug(f'Splitting manual tetrahedron {tet}') logger.debug(f'Splitting manual tetrahedron {tet}')
logger.debug(f'orient volume {volume_of_tetrahedron(tet["vertices"])}') logger.debug(f'volume {volume}')
plane = numpy.array((-1,0,0)), 1 plane = numpy.array((-1, 0, 0)), 1
p_left, p_right = split(tet, plane) p_left, p_right = split(tet, plane)
logger.debug(f'left {p_left}') logger.debug(f'left {p_left}')
@ -162,19 +179,13 @@ def test_split_tet_manual():
check_poly(p_left) check_poly(p_left)
check_poly(p_right) check_poly(p_right)
om = get_moments(tet, 0) m0 = get_moments(tet, 0)
m1 = get_moments(p_left, 0) ml = get_moments(p_left, 0)
m2 = get_moments(p_right, 0) mr = get_moments(p_right, 0)
logger.debug(f'0th moments: tot {om}, left {m1}, right {m2}') logger.debug(f'0th moments: tot {m0}, left {ml}, right {mr}')
check(om, m1, m2) assert(abs(m0 - volume) < TOL_FAIL)
check_split_moments(tet, p_left, p_right, POLY_ORDER)
om = get_moments(tet, POLY_ORDER)
m1 = get_moments(p_left, POLY_ORDER)
m2 = get_moments(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(): def test_split_tets_thru_centroid():
@ -183,10 +194,10 @@ def test_split_tets_thru_centroid():
# generate a random tet and clip plane # generate a random tet and clip plane
ntets = 1 ntets = 1
opoly = [build_tetrahedron(rand_tet_3d(MIN_VOL)) for _ in range(ntets)] opoly = [build_rand_tetrahedron() for _ in range(ntets)]
plane = thru_cent_3d(opoly[ntets//7]) plane = plane_centroid(opoly[ntets//7])
# split them all about the same plane # split them all with the same plane
poly12 = [split(o, plane) for o in opoly] poly12 = [split(o, plane) for o in opoly]
poly1, poly2 = zip(*poly12) poly1, poly2 = zip(*poly12)
@ -194,20 +205,14 @@ def test_split_tets_thru_centroid():
check_poly(orig) check_poly(orig)
check_poly(p1) check_poly(p1)
check_poly(p2) check_poly(p2)
check_split_moments(orig, p1, p2, POLY_ORDER)
# reduce the original and its two parts
om = get_moments(orig, POLY_ORDER)
m1 = get_moments(p1, POLY_ORDER)
m2 = get_moments(p2, POLY_ORDER)
check(om, m1, m2)
def time_split(): def time_split():
NUM_TRIALS = int(10e3) NUM_TRIALS = 1000
logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.')
polys = [build_tetrahedron(rand_tet_3d(MIN_VOL)) for _ in range(NUM_TRIALS)] polys = [build_rand_tetrahedron() for _ in range(NUM_TRIALS)]
facesets = [planes_from_tetrahedron(rand_tet_3d(MIN_VOL)) for _ in range(NUM_TRIALS)] facesets = [planes_from_tetrahedron(rand_tetrahedron_vertices()) for _ in range(NUM_TRIALS)]
t0 = perf_counter() t0 = perf_counter()
for t in range(NUM_TRIALS): for t in range(NUM_TRIALS):
# clip the first tet against the faces of the second # clip the first tet against the faces of the second
@ -233,15 +238,15 @@ def test_tet_tet_timing():
# Intersects pairs of tetrahedra, for timing purposes only. # Intersects pairs of tetrahedra, for timing purposes only.
# for timing only, no assertions # for timing only, no assertions
NUM_TRIALS = int(10e3) NUM_TRIALS = 1000
t0 = perf_counter() t0 = perf_counter()
logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.')
for t in range(NUM_TRIALS): for t in range(NUM_TRIALS):
# generate the first random tet # generate the first random tet
poly = build_tetrahedron(rand_tet_3d(MIN_VOL)) poly = build_rand_tetrahedron()
# generate the second random tet # generate the second random tet
faces = planes_from_tetrahedron(rand_tet_3d(MIN_VOL)) faces = planes_from_tetrahedron(rand_tetrahedron_vertices())
# clip the first tet against the faces of the second # clip the first tet against the faces of the second
for face in faces: for face in faces:
@ -282,127 +287,68 @@ def test_split_nonconvex():
(v - 1) % nz2, (v - 1) % nz2,
v + nz2) v + nz2)
neighbors[v + nz2] = neighbors[v][[1, 0, 2]] + (nz2, nz2, -nz2) neighbors[v + nz2] = neighbors[v][[1, 0, 2]] + (nz2, nz2, -nz2)
opoly = { poly = {
'vertices': vertices, 'vertices': vertices,
'neighbors': neighbors, 'neighbors': neighbors,
} }
logger.debug('good: {}'.format(check_poly(opoly))) 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 along the x-axis (two single connected components this direction)
plane = [numpy.array((1, 0, 0)), split_and_check(poly, [numpy.array((1, 0, 0)), -0.5 * (NZIGS - 1)], POLY_ORDER)
-0.5 * (NZIGS - 1)]
poly1 = clip(opoly, plane)
plane[0] *= -1
plane[1] *= -1
poly2 = clip(opoly, plane)
om = get_moments(opoly, POLY_ORDER)
m1 = get_moments(poly1, POLY_ORDER)
m2 = get_moments(poly2, POLY_ORDER)
check(om, m1, m2)
# split along the z-axis (two single connected components this direction) # split along the z-axis (two single connected components this direction)
plane = [numpy.array((0, 0, 1)), -0.5] split_and_check(poly, [numpy.array((0, 0, 1)), -0.5], POLY_ORDER)
poly1 = clip(opoly, plane)
plane[0] *= -1
plane[1] *= -1
poly2 = clip(opoly, plane)
om = get_moments(opoly, POLY_ORDER)
m1 = get_moments(poly1, POLY_ORDER)
m2 = get_moments(poly2, POLY_ORDER)
check(om, m1, m2)
# split along the y-axis (multiple connected components this direction) # split along the y-axis (multiple connected components this direction)
plane = [numpy.array((0, 1, 0)), split_and_check(poly, [numpy.array((0, 1, 0)), -0.5 * (1.0 + ZOFF)], POLY_ORDER)
-0.5 * (1.0 + ZOFF)]
poly1 = clip(opoly, plane)
plane[0] *= -1
plane[1] *= -1
poly2 = clip(opoly, plane)
om = get_moments(opoly, POLY_ORDER)
m1 = get_moments(poly1, POLY_ORDER)
m2 = get_moments(poly2, POLY_ORDER)
check(om, m1, m2)
def test_recursive_splitting_nondegenerate(): def test_recursive_split(num_trials: int = 10, max_depth: int = 6 ):
# recursively splits a polyhedron (starting from a tet) through the centroid, '''
# checking to see that the resulting volumes add up properly. 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)
NUM_TRIALS = 10 logger.info(f' - Through degenerate plane')
logger.info(f'Recursively splitting {NUM_TRIALS} tetrahedra, maximum splits per tet is {MAX_DEPTH}.') for _ in range(num_trials):
for _ in range(NUM_TRIALS): stack_split(build_rand_tetrahedron(), max_depth=max_depth)
# generate a random tet
opoly = build_tetrahedron(rand_tet_3d(MIN_VOL))
stack_split(opoly, plane_fun=thru_cent_3d)
logger.info(f' - Through perturbed plane')
def test_recursive_splitting_degenerate(): for t in range(num_trials):
# recursively splits a polyhedron (starting from a tet) with a cut plane perturb = 10 ** -(1 + t % 16)
# that is always degenerate with the tet in some way, stack_split(build_rand_tetrahedron(), perturb=perturb, max_depth=max_depth)
# 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 @profile
def test_voxelization(): def test_voxelization():
# Test r3d_voxelize() by checking that the voxelized moments # Test r3d_voxelize() by checking that the voxelized moments
# do indeed sum to those of the original input # sum to those of the original input
POLY_ORDER = 4 POLY_ORDER = 4
NGRID = 25 grid_size = 25
# create a random tet in the unit box dx = numpy.ones(3) / grid_size
verts = (numpy.array(rand_tet_3d(MIN_VOL)) + 1) / 2
verts = 1.5 * (numpy.array(rand_tetrahedron_vertices()) + 1)
poly = build_tetrahedron(verts) poly = build_tetrahedron(verts)
# get its original moments for reference
moments = get_moments(poly, POLY_ORDER) moments = get_moments(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'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) grid = voxelize(poly, dx, poly_order=POLY_ORDER)
# visualize_voxels(grid) # visualize_voxels(grid)
# make sure the sum of each moment equals the original
voxsum = numpy.sum(grid, axis=(0, 1, 2)) voxsum = numpy.sum(grid, axis=(0, 1, 2))
assert(numpy.all(numpy.abs(moments - voxsum) < TOL_FAIL)) assert(numpy.all(numpy.abs(moments - voxsum) < TOL_FAIL))
@ -418,59 +364,45 @@ def visualize_voxels(grid):
@profile @profile
def stack_split(opoly, plane_fun=None, perturb=0): def stack_split(poly, plane_fun=None, perturb=0, max_depth=10):
stack = [(opoly, 0)] stack = [(poly, 0)]
i = 0 i = 0
# recursively split the poly
while stack: while stack:
i += 1 i += 1
opoly, depth = stack.pop() poly, depth = stack.pop()
# generate a random plane from one of a few # pick a plane
# possible degenerate configurations, ensuring that it
# has a valid unit normal
if plane_fun is None: if plane_fun is None:
while True: pfun_used = random.choice(plane_gen)
pfun_used = random.choice(choptions_3d) plane = pfun_used(poly)
plane = pfun_used(opoly) while norm(plane[0]) != 0:
if norm(plane[0]) != 0: pfun_used = random.choice(plane_gen)
break plane = pfun_used(poly)
plane = list(plane) plane = list(plane)
logger.debug(f'used {pfun_used}') logger.debug(f'used {pfun_used}')
else: else:
plane = list(plane_fun(opoly)) plane = list(plane_fun(poly))
# randomly perturb the plane # perturb the plane
plane[0] *= 1 + perturb * (numpy.random.rand() - 0.5) plane[0] *= 1 + perturb * (numpy.random.rand() - 0.5)
plane[1] *= 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 # split the poly
# and them clipping them against the same plane, with one poly_l = clip(poly, plane)
# oriented oppositely poly_r = clip(poly, flip_plane(plane))
poly1 = clip(opoly, plane) m0, ml, mr = check_split_moments(poly, poly_l, poly_r, POLY_ORDER)
plane[0] *= -1
plane[1] *= -1
poly2 = clip(opoly, plane)
# reduce the original and its two parts
om = get_moments(opoly, POLY_ORDER)
m1 = get_moments(poly1, POLY_ORDER)
m2 = get_moments(poly2, POLY_ORDER)
check(om, m1, m2)
logger.debug(f'nstack = {len(stack)}, depth = {depth}, ' logger.debug(f'nstack = {len(stack)}, depth = {depth}, '
f'opoly = {om[0]:.10e}, p1 = {m1[0]:.10e}, p2 = {m2[0]:.10e}, ' f'opoly = {m0[0]:.10e}, p1 = {ml[0]:.10e}, p2 = {mr[0]:.10e}, '
f'err = {abs(1.0 - om[0]/(m1[0] + m2[0])):.10e}') f'err = {abs(1.0 - m0[0]/(ml[0] + mr[0])):.10e}')
# push the children to the stack if they have # add the children to the stack if they are big enough
# an acceptably large volume if depth < max_depth:
if depth < MAX_DEPTH: if ml[0] > MIN_VOL:
if m1[0] > MIN_VOL: stack.append((poly_l, depth + 1))
stack.append((poly1, depth + 1)) if mr[0] > MIN_VOL:
if m2[0] > MIN_VOL: stack.append((poly_r, depth + 1))
stack.append((poly2, depth + 1))
if i % 300 == 0: if i % 300 == 0:
logger.info(f'Stack split iter {i} length {len(stack)} depth {depth}') logger.info(f'Stack split iter {i} length {len(stack)} depth {depth}')
@ -590,9 +522,9 @@ def test_torus_load_and_chop():
#plot_brep(brep) #plot_brep(brep)
choptions_3d = [thru_cent_3d, thru_face_3d, plane_gen = [plane_centroid, plane_face,
thru_edge_cent_3d, thru_edge_rand_3d, plane_centroid_edge, plane_edge,
thru_vert_cent_3d, thru_vert_rand_3d] plane_centroid_vertex, plane_vertex]
if __name__ == '__main__': if __name__ == '__main__':