From d721e5431f8fd2b21ee164a662b7e7d179414620 Mon Sep 17 00:00:00 2001 From: jan Date: Fri, 9 Mar 2018 16:45:38 -0800 Subject: [PATCH] initial --- pyr3d.py | 879 +++++++++++++++++++++++++++++++++++++++++++++++++++++ tpy_r3d.py | 634 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 1513 insertions(+) create mode 100644 pyr3d.py create mode 100644 tpy_r3d.py diff --git a/pyr3d.py b/pyr3d.py new file mode 100644 index 0000000..8cafbd3 --- /dev/null +++ b/pyr3d.py @@ -0,0 +1,879 @@ +from typing import List, Dict, Tuple + +import numpy +from numpy import pi, cos, sin, sqrt +from numpy.linalg import norm + + +try: + profile +except: + def profile(f): + return f + + +def init_tet(verts: numpy.ndarray): + poly = { + 'vertices': numpy.array(verts, dtype=float), + 'neighbors': numpy.array(( + (1, 3, 2), + (2, 3, 0), + (0, 3, 1), + (1, 2, 0)), dtype=int), + } + return poly + + +def NUM_MOMENTS(order): + return ((order + 1) * (order + 2) * (order + 3)) // 6 + + +def empty_poly() -> Dict: + return { + 'vertices': numpy.empty((0, 3), dtype=float), + 'neighbors': numpy.empty((0, 3), dtype=int), + } + + +empty_partial_result = ( + numpy.empty((0, 3), dtype=int), + numpy.empty((0, 1), dtype=int), + numpy.empty((0, 3), dtype=float), + numpy.empty((0, 1), dtype=int), + ) + +@profile +def simple_clip(poly: Dict, plane: Tuple) -> Dict: + vertices = poly['vertices'] + neighbors = poly['neighbors'] + num_vertices = vertices.shape[0] + + dists = plane[1] + (vertices @ plane[0]) + left = dists > 0 + right = numpy.logical_not(left) + + # if the poly lies entirely on one side of the plane, just return the right/left masks + if not numpy.any(left): + # if all on right or touching plane + return (left,) + empty_partial_result + if numpy.min(dists) >= 0: + # if all on left or touching plane + # Can't reuse 'left' because <= vs < + return (numpy.ones_like(left),) + empty_partial_result + + num_left_vertices = numpy.count_nonzero(left) + num_right_vertices = num_vertices - num_left_vertices + + right_inds = numpy.where(right)[0] + right_inds3 = numpy.repeat(right_inds, 3) + pnbr_inds = numpy.tile(numpy.arange(3), right_inds.size) + + # array of [[clipped vertex (cv0), connected vertex pv00], [cv0, pv01], [cv0, pv02], [cv1, pv10], ...] + # which is effectively a list of all edges which touch the right half-plane + right_edges = numpy.column_stack((right_inds3, neighbors[right_inds, :].ravel(), pnbr_inds)) + + # remove edges which connect two same-side vertices + far_vertex_left = left[right_edges[:, 1]] + r2l_edges = right_edges[far_vertex_left, :] + + if r2l_edges.size == 0: + # No edges cross, but components on either side + return (left,) + empty_partial_result + + # sort now so we can use searchsorted later + r2l_edge_order = _argsort_rows(r2l_edges[:, :2]) + r2l_edges = r2l_edges[r2l_edge_order] + + num_new_vertices = r2l_edges.shape[0] + + # walk counter-clockwise to next crossing edge + edge_walk = r2l_edges[:, :2].copy() + edge_walk_inds = numpy.arange(num_new_vertices) + edge_walk_inds2 = numpy.arange(num_new_vertices) + edge_walk_results = numpy.empty_like(edge_walk) + src_pns = None + while edge_walk.size > 0: + prev_verts = edge_walk[:, 0] + cur_verts = edge_walk[:, 1].copy() + + # Get the list of our current neighbors, find which one points to the + # vertex we came from, and choose the next (ccw) one + cur_links = neighbors[cur_verts] + row, src_pn = numpy.where(cur_links == prev_verts[:, None]) + new_pn = (src_pn + 1) % 3 + + if src_pns is None: + src_pns = src_pn + + next_verts = cur_links[(row, new_pn)] + + # Save the current vertices as previous, and our chosen neighbors as current + # Save edges that cross back to right, and remove them from edge_walk + done = right[next_verts] + not_done = numpy.logical_not(done) + edge_walk_results[edge_walk_inds2[done], 0] = cur_verts[done] + edge_walk_results[edge_walk_inds2[done], 1] = next_verts[done] + edge_walk = numpy.column_stack((cur_verts[not_done], next_verts[not_done])) + edge_walk_inds2 = edge_walk_inds2[not_done] + + + # now edge_walk is list of [[target connected vertex, target clipped adjacent vertex], ...] + + # figure out the index of each target edge... + target_edge_inds = _searchsorted_rows(r2l_edges[:,:2], edge_walk_results[:, ::-1]) + + v_right = r2l_edges[:, 0] + v_left = r2l_edges[:, 1] + d_right = dists[v_right][:, None] + d_left = dists[v_left][:, None] + new_vertices = (d_right * vertices[v_left] - d_left * vertices[v_right]) / (d_right - d_left) + return left, r2l_edges, target_edge_inds, new_vertices, src_pns + + +def _argsort_rows(a): + dims = a.max(0) + 1 + a1d = numpy.ravel_multi_index(a.T, dims) + return numpy.argsort(a1d) + + +def _searchsorted_rows(a, b): + dims = numpy.maximum(a.max(0), b.max(0)) + 1 + a1d = numpy.ravel_multi_index(a.T, dims) + b1d = numpy.ravel_multi_index(b.T, dims) + return numpy.searchsorted(a1d, b1d) + + +def clip(poly, plane): + left_poly = split(poly, plane, left_only=True) + return left_poly + + +@profile +def split(poly, plane, left_only: bool = False): + left, r2l_edges, target_edge_inds, new_vertices, src_pn = simple_clip(poly, plane) + right = numpy.logical_not(left) + + # vertex counts + num_start = poly['vertices'].shape[0] + num_left = numpy.count_nonzero(left) + num_right = num_start - num_left + num_new = r2l_edges.shape[0] + + if num_left == 0 or num_right == 0: + if num_left == 0: + ret = empty_poly(), poly + else: + ret = poly, empty_poly() + + if left_only: + return ret[0] + else: + return ret + + ''' + map from old vertex ind to new + ''' + ind_map_left = numpy.zeros(num_start, dtype=int) + # current side vertices get new (equal or lower) indices from delete operation, remain in same order + ind_map_left[left] = numpy.arange(num_left) + # Hops across the boundary depend on (origin, destination) pair since that determines final vertex + + re, le = r2l_edges[:, 0], r2l_edges[:, 1] + + # use argsort to generate link from target edge to current edge + target_order = numpy.argsort(target_edge_inds) + new_neighbors_left = numpy.column_stack(( + ind_map_left[le], # update left vertices based on new indexing + target_order + num_left, # new vertex indices are same as edge indices + offset + target_edge_inds + num_left)) + + old_vertices_left = poly['vertices'][left] + + old_neighbors_left = poly['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[(le, src_pn)] = num_left + numpy.arange(num_new) + old_neighbors_left = old_neighbors_left[left] + + left_poly = { + 'vertices': numpy.vstack((old_vertices_left, new_vertices)), + 'neighbors': numpy.vstack((old_neighbors_left, new_neighbors_left)), + } + + if left_only: + return left_poly + + ind_map_right = numpy.zeros(num_start, dtype=int) + ind_map_right[right] = numpy.arange(num_right) + + new_neighbors_right = numpy.column_stack(( + ind_map_right[re], # update right vertices based on new indexing + target_edge_inds + num_right, # new vertex indices are same as edge indices + offset + target_order + num_right)) + + old_vertices_right = poly['vertices'][right] + + old_neighbors_right = poly['neighbors'].copy() + old_neighbors_right[right] = ind_map_right[old_neighbors_right[right]] + old_neighbors_right[(re, r2l_edges[:, 2])] = num_right + numpy.arange(num_new) + old_neighbors_right = old_neighbors_right[right] + + right_poly = { + 'vertices': numpy.vstack((old_vertices_right, new_vertices)), + 'neighbors': numpy.vstack((old_neighbors_right, new_neighbors_right)), + } + + return left_poly, right_poly + + +@profile +def reduce(poly, poly_order): + vertices = poly['vertices'] + neighbors = poly['neighbors'] + num_verts = vertices.shape[0] + + moments = numpy.zeros(NUM_MOMENTS(poly_order), dtype=float) + + if num_verts == 0: + return moments + + edge_visited= numpy.zeros((num_verts, 3), dtype=bool) + + #// Storage for coefficients keep two layers of the pyramid of coefficients + #// Note: Uses twice as much space as needed, but indexing is faster this way + prevlayer, curlayer = 0, 1 + S = numpy.zeros((3, poly_order + 1, poly_order + 1, 2) , dtype=float) + inds = numpy.arange(poly_order + 1) + mx, my = numpy.meshgrid(inds, inds, indexing='ij') + valid = numpy.zeros((2, poly_order + 1, poly_order + 1), dtype=bool) + cropped = numpy.zeros((poly_order + 1, poly_order + 1), dtype=bool) + + for vstart in range(num_verts): + for pstart in range(3): + if edge_visited[vstart, pstart]: + continue + + vcur = neighbors[vstart, pstart] + edge_visited[vstart, pstart] = 1 + + prv_edge = numpy.where(neighbors[vcur] == vstart)[0][0] + nxt_edge = (prv_edge + 1) % 3 + edge_visited[vcur, nxt_edge] = 1 + vnext = neighbors[vcur, nxt_edge] + + #// make a triangle fan using edges and first vertex + vecs = numpy.vstack(vertices[[vstart, vcur, vnext]]) + while vnext != vstart: + volume = -numpy.linalg.det(vecs) + S[:, 0, 0, prevlayer] = 1 + valid[prevlayer, :, :] = False + valid[prevlayer, 0, 0] = True + + moments[0] += volume / 6 + + #// calculate the moments using the fast recursive method of Koehl (2012) + #// essentially building a set of trinomial pyramids, one layer at a time + m = 1 + for c in range(1, poly_order+1): + valid[curlayer] = c >= mx + my + num_valid = (c + 1) * (c + 2) // 2 # always an int, see NUM_MOMENTS() + + S[:, 0, :, curlayer] = 0 + + cropped.fill(0) + cropped[1:, :] = valid[curlayer, 1:, :] + S[:, cropped, curlayer] = vecs[:, 0][:, None] * S[:, valid[prevlayer], prevlayer] + + cropped = numpy.moveaxis(cropped, 0, 1) + S[:, cropped, curlayer] += vecs[:, 1][:, None] * S[:, valid[prevlayer], prevlayer] + + S[:, valid[prevlayer], curlayer] += vecs[:, 2][:, None] * S[:, valid[prevlayer], prevlayer] + + S[1, valid[curlayer], curlayer] += S[0, valid[curlayer], curlayer] + S[2, valid[curlayer], curlayer] += S[1, valid[curlayer], curlayer] + + moments[m:m + num_valid] += volume * S[2, valid[curlayer], curlayer].ravel() + m += num_valid + prevlayer, curlayer = curlayer, prevlayer + + prv_edge = numpy.where(neighbors[vnext] == vcur)[0][0] + nxt_edge = (prv_edge + 1) % 3 + + vcur = vnext + edge_visited[vcur, nxt_edge] = 1 + vnext = neighbors[vcur, nxt_edge] + + vecs[1] = vertices[vcur] + vecs[2] = vertices[vnext] + + #// reuse S to recursively compute the leading multinomial coefficients + S[0, 0, 0, prevlayer] = 1 + m = 1 + valid[prevlayer, :, :] = False + valid[prevlayer, 0, 0] = True + for c in range(1, poly_order+1): + valid[curlayer] = c >= mx + my + num_valid = (c + 1) * (c + 2) // 2 # always an int, see NUM_MOMENTS() + + S[0, 0, :, curlayer] = 0 + + cropped.fill(0) + cropped[1:, :] = valid[curlayer, 1:, :] + S[0, cropped, curlayer] = S[0, valid[prevlayer], prevlayer] + + cropped = numpy.moveaxis(cropped, 0, 1) + S[0, cropped, curlayer] += S[0, valid[prevlayer], prevlayer] + + S[0, valid[prevlayer], curlayer] += S[0, valid[prevlayer], prevlayer] + + moments[m:m + num_valid] /= S[0, valid[curlayer], curlayer].ravel() * (c + 1) * (c + 2) * (c + 3) + m += num_valid + prevlayer, curlayer = curlayer, prevlayer + + return moments + +@profile +def is_good(poly) -> bool: + neighbors = poly['neighbors'] + vertices = poly['vertices'] + num_vertices = vertices.shape[0] + + out_of_bounds = numpy.logical_or(neighbors >= vertices.shape[0], neighbors < 0) + if numpy.any(out_of_bounds): + which_vertices = numpy.where(out_of_bounds)[0] + raise Exception(f'Vertices {which_vertices} have out-of-bounds neighbors') + + repeated_neighbors = neighbors == numpy.roll(neighbors, 1, axis=1) + if numpy.any(repeated_neighbors): + which_vertices = numpy.where(repeated_neighbors)[0] + raise Exception(f'Vertices {which_vertices} have duplicate neighbors') + + vertex_uses = numpy.bincount(neighbors.ravel()) + if numpy.any(vertex_uses != 3): + which_vertices = numpy.where(vertex_uses != 3)[0] + raise Exception(f'Vertices {which_vertices} are referenced {vertex_uses[which_vertices]} times,' + ' should be exactly 3') + + # check for 3-vertex-connectedness (slow, n^2) + + #// handle multiply-connected polyhedra by testing each component separately + #// Flood-fill starting from each vertex to give each connected region a unique ID. + rcur = 1 + regions = numpy.zeros(num_vertices, dtype=int) + stack = [] + for v in range(num_vertices): + if regions[v]: + continue + + nums = numpy.array([v], dtype=int) + while nums.size > 0: + regions[nums] = rcur + new_nums = numpy.unique(neighbors[nums]) + nums = new_nums[regions[new_nums] == 0] + + rcur += 1 + + # loop over unique pairs of verts + vct = numpy.empty_like(regions, dtype=bool) + for va in range(num_vertices): + rcur = regions[va] + vbs = numpy.arange(va + 1, num_vertices) + vbs_in_rcur = vbs[regions[vbs] == rcur] + + for vb in vbs: + # pick vc != va && vc != vb and in the same connected component as va and vb + for vc in numpy.where(regions == rcur)[0]: + if vc != va and vc != vb: + break + + # use vct to mark visited verts mask out va and vb + vct.fill(False) + vct[va] = True + vct[vb] = True + + # flood-fill from vc to make sure the graph is still connected when va and vb are masked + if not vct[vc]: + nums = numpy.array([vc], dtype=int) + while nums.size > 0: + vct[nums] = True + new_nums = numpy.unique(neighbors[nums]) + nums = new_nums[~vct[new_nums]] + + # if any verts in the region rcur were untouched, the graph is only + # 2-vertex-connected and hence an invalid polyhedron + if not vct[regions == rcur].all(): + raise Exception('Not 3-vertex connected') + return True + + +def orient(tet_verts): + ad, bd, cd = tet_verts[0:3] - tet_verts[3] + return -ad @ numpy.cross(bd, cd) / 6 + + +def tet_faces_from_verts(tet_verts): + verts = numpy.array(tet_verts, dtype=float) + vset_inds = numpy.array(( + [3, 1, 2, 1], + [2, 0, 3, 2], + [1, 3, 0, 3], + [0, 2, 1, 0])) + vertsets = numpy.moveaxis(numpy.dstack(verts[v] for v in vset_inds), 2, 0) + ab = vertsets[:, 0, :] - vertsets[:, 1, :] + cd = vertsets[:, 2, :] - vertsets[:, 3, :] + + n = numpy.cross(ab, cd) + n /= norm(n, axis=1)[:, None] + centers = numpy.sum(vertsets[:, :3, :], axis=1) / 3 + d = -numpy.sum(n * centers, axis=1) + + return [plane for plane in zip(n, d)] + + +def get_map(a, b): + # Assume all elements appear exactly once in each array + # Returns m, n such that a[m] == b, b[n] == a + assert(a.size == b.size) + if a.size == 0: + return numpy.array(()), numpy.array(()) + sa = a.argsort() + sb = b.argsort() + ra = numpy.empty_like(sa) + rb = numpy.empty_like(sa) + ra[sa] = numpy.arange(sa.size) + rb[sb] = numpy.arange(sa.size) + return sa[rb], sb[ra] + + +@profile +def init_poly(in_vertices, faces): + in_vertices = numpy.array(in_vertices, dtype=float) + faces = [numpy.array(face, dtype=int) for face in faces] + + edges_per_vertex = numpy.bincount(numpy.hstack(faces)) + + if edges_per_vertex.min() < 3: + raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges') + + if edges_per_vertex.max() == 3: + # Don't need to duplicate any vertices to make 3-connected graph + vertices = in_vertices + + # Link up the vertices + neighbors = numpy.empty_like(vertices, dtype=int).fill(vertices.size) + for face in faces: + # Check if each vertex in this face is already linked to its next or previous face-neighbor + prev_vert = numpy.roll(face, 1) + next_vert = numpy.roll(face, -1) + neighbor_rows = neighbors[face, :] + has_prev = (neighbor_rows == prev_vert).any(axis=1) + has_next = (neighbor_rows == next_vert).any(axis=1) + + # Each vertex touches 3 faces; each vertex triplet (neighbor_row) is a triangle on a face. + # Thus, we will never encounter a situation in which prv == nxt. + + # If the vertex hasn't been linked to anything yet, set its first two + # polyhedron-neighbors to its face-neighbors + empty = numpy.logical_not(numpy.logical_or(has_prev, has_next)) + neighbors[face[empty], 0] = next_vert[empty] + neighbors[face[empty], 1] = prev_vert[empty] + + # If the vertex has already been linked to something (by a different face), + # fill in the third neighbor + # Note that this causes excess writes; it might improve performace to check + # if the third neighbor is already filled + neighbors[face[has_prev], 2] = next_vert[has_prev] + neighbors[face[has_next], 2] = prev_vert[has_next] + + return {'vertices': vertices, 'neighbors': neighbors} + + else: + ''' + Some vertices link more than three edges. + We only allow three edges per vertex in the graph, so we need to make + degenerate copies of those vertices. + + For convenience, duplicate each vertex as many times as it has edges. + This creates 2 'excess' duplicates of each vertex (e.g. a vertex with + 3 edges will turn into 3 vertices, even though it was fine as-is). + + Link the "duplicate" vertices together, as follows: + - Each set of duplicates becomes a doubly-linked ring. + - Each duplicate has an additional, "third" pointer, pointing to one + of the duplicates created for a _different_ original vertex (i.e., this + pointer and its counterpart both correspond to the edge which caused + these two duplicates to be created). + + We perform this linkage by creating a list of 3 entries per duplicate, aiming + to eventually fill each row with the indices + [next_row, third_row, prev_row] + corresponding to the linked duplicates. + + We begin by filling columns (1, 2) with the (next, prev) _original_ vertex indices + for each face. The subset of the list corresponding to a single original vertex + thus looks like + + [???, f0_next, f0_prev] <-- (i.e., the angle fromed by the three points + [???, f3_next, f3_prev] [..., prev, me, next, ...], where 'me' is the + [???, f7_next, f7_prev] (original) vertex index corresponding to this row + ... and prev, next are original vertex indices as listed + in face 0's vertex list) + and so on, with a row and f# for each face the original vertex participates in. + The full list is just + [ rows for + original vertex 0 + ... + rows for + original vertex 1 + ... + etc + ] + (note that each original vertex takes as many rows as it has edges) + + Next, note that the newly filled columns will hold the same sets of numbers, just permuted. + Each row specifies two edges (an angle), and each edge is shared by two faces, and appears + once as a "previous" pointer and once as a "next" pointer. + + So, we can set column 0 to the (new) index of the row whose f_prev matches our row's f_next. + In other words, pick column 0 to ensure dn[i, 1] == dn[dn[i, 0], 2]. Our columns become + [next_row, f#_next, f#_prev] + Then, replace f#_prev with a back-pointer based on next_row, + [next_row, f#_next, prev_row] + which completes our doubly-linked duplicate vertex rings. + + To complete the linkage, we need to link to 'third_row'. We can do this by, + For each set of rows (corresponding to an original vertex V0), + - searching the sets of rows Vi corresponding to the listed f#_next values + for rows whose f#_next == V0 + - doubly linking each row (i) in V0 with its 'found' row in Vi + + Finally, we can remove the first two ('excess') duplicate vertices in each ring, and update + the links to reflect their removal. + ''' + # starting row for each original vertex + vstart = numpy.roll(numpy.cumsum(edges_per_vertex), 1) + vstart[0] = 0 + + # number of input vertices (v) and duplicates (d) + num_v = in_vertices.shape[0] + num_duplicates = edges_per_vertex.sum() + + # Linkage and aux array + neighbors = numpy.empty((num_duplicates, 3), dtype=int) + util = numpy.zeros(num_duplicates, dtype=int) + + ''' + Fill columns (1, 2) with original vertex inds (f#_next, f#_prev) + ''' + for face in faces: + # assume a face can't use the same vertex twice + v_inds = vstart[face] + util[face] + neighbors[v_inds, 1] = numpy.roll(face, -1) + neighbors[v_inds, 2] = numpy.roll(face, 1) + util[face] += 1 + + ''' + Fill columns (0, 2) with new vertex inds (next_row, prev_row) + to complete doubly-linked rings + ''' + for v in range(num_v): + v0 = vstart[v] + s = slice(v0, v0 + edges_per_vertex[v]) + m, n = get_map(neighbors[s, 2], neighbors[s, 1]) + neighbors[s, 0] = n + v0 + neighbors[s, 2] = m + v0 + + ''' + for each pair of original vertices, + find subvertices whose f#_next pointers point to each other's original vertices, + and link them using column 1 (i.e. set their third_row pointers to each other) + ''' + # Mapping from row to original vertex index + v0s = numpy.repeat(numpy.arange(len(edges_per_vertex)), edges_per_vertex) + + # Copy column 1 to save target info + target_vert = neighbors[:, 1].copy() + + # Preallocate mask arrays + src_mask = numpy.empty(num_duplicates, dtype=bool) + dst_mask = numpy.empty(num_duplicates, dtype=bool) + + for v in range(num_v): + s = vstart[v] + e = s + edges_per_vertex[v] + + src_mask.fill(False) + src_mask[e:] = target_vert[e:] == v # find rows which reference us + src_vert = v0s[src_mask] # figure out their original vertex numbers + + if src_vert.size == 0: + continue + + dst_mask.fill(False) + dst_mask[s:e] = target_vert[s:e] > v # mask out any references to verts >= current + dst_vert = target_vert[dst_mask] + + ma, mb = get_map(dst_vert, src_vert) + neighbors[dst_mask, 1] = numpy.where(src_mask)[0][mb] + neighbors[src_mask, 1] = numpy.where(dst_mask)[0][ma] + + ''' + Remove first two duplicates of each vertex (they aren't needed) + ''' + nxt, third, prv = neighbors[vstart, :].T + nxt_nxt, nxt_third, _nxt_prv = neighbors[nxt, :].T + + # Which vertex to link to + dest_map = numpy.arange(num_duplicates, dtype=int) # default maps to itself + dest_map[vstart] = prv # first maps to previous + dest_map[nxt] = nxt_nxt # second maps to next + + # Which backreference to modify + back_map = numpy.full_like(dest_map, 1) # default is 'third' + back_map[vstart] = 0 # if we mapped from a first vertex to its previous, set to 'next' + back_map[nxt] = 2 # if we mapped from a second vertex to its next, set to 'previous' + + # Map 'third' to where it should point to + dm_third = dest_map[third] + dm_nxt_third = dest_map[nxt_third] + + neighbors[prv, 0] = dm_third # previous's next reference points to third + neighbors[nxt_nxt, 2] = dm_nxt_third # next-next's previous reference points to next-third + + neighbors[dm_third, back_map[third]] = prv # third's backreference points to previous + neighbors[dm_nxt_third, back_map[nxt_third]] = nxt_nxt # next-third's backreference points to next-next + + # Mark for removal + util.fill(0) + util[vstart] = 1 + util[nxt] = 1 + + neighbors = neighbors[util == 0] + util[util == 0] = numpy.arange(neighbors.shape[0]) + neighbors[:] = util[neighbors] + + vertices = numpy.repeat(in_vertices, edges_per_vertex - 2, axis=0) + + return {'vertices': vertices, 'neighbors': neighbors} + + +def rotate(poly, theta: float, axis: int): + s, c = sin(theta), cos(theta) + v0 = poly['vertices'][:, axis - 2].copy() + v1 = poly['vertices'][:, axis - 1].copy() + poly['vertices'][:, axis - 2] = c * v0 - s * v1 + poly['vertices'][:, axis - 1] = s * v1 + c * v0 + + +def translate(poly, shift): + poly['vertices'] += shift + + +def scale(poly, scale): + poly['vertices'] *= scale + + +def shear(poly, shear: float, axb: int, axs: int): + poly['vertices'][:, axb] += poly['vertices'][:, axs] + + +def affine(poly, mat): + mat4x3 = mat[:, :3] + mat4x1 = mat[:, 3] + vh = mat4x3 @ poly['vertices'].T + mat4x1 + poly['vertices'] = vh[:3, :] / vh[3, :] + + +def init_box(rbounds): + neighbors = [ + [1, 4, 3], + [2, 5, 0], + [3, 6, 1], + [0, 7, 2], + [7, 0, 5], + [4, 1, 6], + [5, 2, 7], + [6, 3, 4], + ] + + vertices = [ + [rbounds[0, 0], rbounds[0, 1], rbounds[0, 2]], + [rbounds[1, 0], rbounds[0, 1], rbounds[0, 2]], + [rbounds[1, 0], rbounds[1, 1], rbounds[0, 2]], + [rbounds[0, 0], rbounds[1, 1], rbounds[0, 2]], + [rbounds[0, 0], rbounds[0, 1], rbounds[1, 2]], + [rbounds[1, 0], rbounds[0, 1], rbounds[1, 2]], + [rbounds[1, 0], rbounds[1, 1], rbounds[1, 2]], + [rbounds[0, 0], rbounds[1, 1], rbounds[1, 2]], + ] + + return { + 'neighbors': numpy.array(neighbors, dtype=int), + 'vertices': numpy.array(vertices, dtype=float), + } + + +def box_faces_from_verts(rbounds): + faces = [ + ((0,0,1), -rbounds[0, 2]), + ((0,0,-1), rbounds[1, 2]), + ((0,1,0), -rbounds[0, 1]), + ((0,-1,0), rbounds[1, 1]), + ((1,0,0), -rbounds[0, 0]), + ((-1,0,0), rbounds[1, 0]), + ] + + return [(numpy.array(n), d) for n, d in faces] + + +def poly_faces_from_verts(vertices, faces): + planes = [] + for face in faces: + face_verts = vertices[face] + + n = numpy.cross(numpy.diff(face_verts, n=1, axis=0), + numpy.diff(face_verts, n=2, axis=0)) + n /= norm(n) + centroid = numpy.sum(face_verts, axis=0) / len(face) + d = -n @ centroid + planes.append(n, d) + return planes + + +@profile +def init_brep(poly): + neighbors = poly['neighbors'] + vertices = poly['vertices'] + + unique_verts, unique_vertex_map = numpy.unique(vertices, axis=0, return_inverse=True) + + verts_in_component = numpy.empty(unique_verts.shape[0], dtype=bool) + component_map = numpy.empty_like(verts_in_component, dtype=int) + vert_visited = numpy.zeros(vertices.shape[0], dtype=numpy.int8) + edge_visited = numpy.zeros_like(vertices, dtype=bool) + + vstart = 0 + components = [] + while True: + verts_in_component.fill(0) + pedge = 0 + + faces = [] + while True: + vcur = vstart + uvcur = unique_vertex_map[vcur] + + face = [] + while True: + vert_visited[vcur] += 1 + edge_visited[vcur, pedge] = True + verts_in_component[uvcur] = True + + vnext = neighbors[vcur, pedge] + uvnext = unique_vertex_map[vnext] + + # don't append duplicates + if uvcur != uvnext: + face.append(uvcur) + + if vnext == vstart: + break + + # Figure out index of back-reference + # and go ccw to next edge (clockwise face traversal) + np = numpy.where(neighbors[vnext] == vcur)[0][0] + pedge = (np + 1) % 3 + + vcur = vnext + uvcur = uvnext + + faces.append(face) + + # Continue using a vertex touching a connected, unvisited face + # Any vertex visited only 1 or 2 times must be touching such a face + nv = numpy.where(numpy.logical_and(0 < vert_visited, vert_visited < 3))[0] + if len(nv) == 0: + # No more connected, unvisited faces! + break + vstart = nv[0] + + # Pick an unvisited edge + pedge = numpy.where(edge_visited[vstart] == 0)[0][0] + + component_map[verts_in_component] = numpy.arange(numpy.count_nonzero(verts_in_component)) + component = { + 'vertices': unique_verts[verts_in_component], + 'faces': [component_map[face] for face in faces], + } + components.append(component) + + # Continue from an unvisited vertex + np = numpy.where(vert_visited == 0)[0] + if len(np) == 0: + # Visited all vertices! + break + vstart = np[0] + + return components + + +def voxelize(poly, ibox, d, poly_order=0): + ibox = numpy.array(ibox, dtype=int) + d = numpy.array(d) + + grid_shape = ibox[1] - ibox[0] + num_moments = NUM_MOMENTS(poly_order) + dest_grid = numpy.zeros((*grid_shape, num_moments), dtype=float) + + if poly is None or poly['vertices'].shape[0] == 0 or (grid_shape <= 0).any(): + return dest_grid + + # Stack-based recursive split + stack = [(poly, ibox)] + while stack: + c_poly, c_ibox = stack.pop() + + # Base case 1: moments are 0 for this region + if c_poly['vertices'].shape[0] == 0: + continue + + box_size = c_ibox[1] - c_ibox[0] + split_axis = box_size.argmax() + max_dist = box_size[split_axis] + + # Base case 2: calculate moments for single voxel + if max_dist == 1: + moments = reduce(c_poly, poly_order) + offset = (c_ibox[0] - ibox[0]) + dest_grid[offset[0], offset[1], offset[2], :] += moments + continue + + # Recursion case: split along longest side + n = numpy.zeros(3) + n[split_axis] = -1 + + split_ind = c_ibox[0][split_axis] + max_dist // 2 + plane = (n, d[split_axis] * split_ind) + + children = split(c_poly, plane) + + split_plane = c_ibox.copy() + split_plane[:, split_axis] = split_ind + + stack.append((children[0], numpy.vstack((c_ibox[0], split_plane[1])) )) + stack.append((children[1], numpy.vstack((split_plane[0], c_ibox[1])) )) + return dest_grid + + +def get_ibox(poly, d): + min_box = numpy.floor(numpy.min(poly['vertices'], axis=0) / d) + max_box = numpy.ceil(numpy.max(poly['vertices'], axis=0) / d) + return numpy.array((min_box, max_box), dtype=int) + + +def clamp_ibox(poly, ibox, clampbox, d): + faces = box_faces_from_verts(clampbox) + for face in faces: + poly = clip(poly, plane) + ibox = get_ibox(poly, d) + return poly, ibox + diff --git a/tpy_r3d.py b/tpy_r3d.py new file mode 100644 index 0000000..41fc086 --- /dev/null +++ b/tpy_r3d.py @@ -0,0 +1,634 @@ +import warnings +from time import perf_counter +import copy +import random +import logging + +import numpy +from numpy import sin, cos, pi +from numpy.linalg import norm + +import pyr3d + +logger = logging.getLogger(__name__) + + +try: + profile +except: + 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 + +# for recursive tests, the stack capacity and +# maximum recursion depth allowed +STACK_SIZE = 64 +MAX_DEPTH = 6 #10 + +# 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 = pyr3d.orient(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 = pyr3d.init_tet([ + [0,0,0], + [2,0,0], + [0,2,0], + [0,0,2]]) + + logger.debug(f'Splitting manual tet {tet}') + logger.debug(f'orient volume {pyr3d.orient(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}') + + pyr3d.is_good(tet) + pyr3d.is_good(p_left) + pyr3d.is_good(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 = [pyr3d.init_tet(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): + pyr3d.is_good(orig) + pyr3d.is_good(p1) + pyr3d.is_good(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 = [pyr3d.init_tet(rand_tet_3d(MIN_VOL)) for _ in range(NUM_TRIALS)] + facesets = [pyr3d.tet_faces_from_verts(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(100e3) + t0 = perf_counter() + logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') + for t in range(NUM_TRIALS): + # generate the first random tet + poly = pyr3d.init_tet(rand_tet_3d(MIN_VOL)) + + # generate the second random tet + faces = pyr3d.tet_faces_from_verts(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 for {t+1} splits: {t_each}') + logger.info(f'done timing, time per split: {(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:', pyr3d.is_good(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 = pyr3d.init_tet(rand_tet_3d(MIN_VOL)) + stack_split(opoly, plane_fun=lambda p: thru_cent_3d(p)) + + +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 = pyr3d.init_tet(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 = pyr3d.init_tet(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 = pyr3d.init_tet(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 = pyr3d.init_tet(verts) + + # get its original moments for reference + moments = pyr3d.reduce(poly, POLY_ORDER) + + # voxelize it + dx = numpy.ones((3,)) / NGRID + ibox = pyr3d.get_ibox(poly, dx) + + 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 = pyr3d.voxelize(poly, ibox, dx, 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 % 100 == 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 = pyr3d.init_poly(vertices, faces) + pyr3d.is_good(opoly) + stack_split(opoly) + + brep = pyr3d.init_brep(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 r3d_init_poly() 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 = pyr3d.init_poly(vertices, faces) +# pyr3d.is_good(opoly) + stack_split(opoly) + + brep = pyr3d.init_brep(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')