packagize
This commit is contained in:
parent
abb54935ad
commit
002e7963c9
7 changed files with 5 additions and 202 deletions
0
chop/__init__.py
Normal file
0
chop/__init__.py
Normal file
271
chop/boundary.py
Normal file
271
chop/boundary.py
Normal file
|
|
@ -0,0 +1,271 @@
|
|||
import numpy
|
||||
from numpy.linalg import norm
|
||||
|
||||
from .util import _get_map, find_components, find_faces
|
||||
|
||||
try:
|
||||
profile
|
||||
except NameError:
|
||||
def profile(f):
|
||||
return f
|
||||
|
||||
|
||||
def planes_from_boundary(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 build_polyhedron(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}
|
||||
|
||||
'''
|
||||
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}
|
||||
|
||||
|
||||
@profile
|
||||
def boundary_from_poly(poly):
|
||||
neighbors = poly['neighbors']
|
||||
vertices = poly['vertices']
|
||||
|
||||
owner_components = find_components(neighbors)
|
||||
faces = find_faces(neighbors)
|
||||
num_components = owner_components.max() + 1
|
||||
|
||||
components = [[] for _ in range(num_components)]
|
||||
for face in faces:
|
||||
component_ind = owner_components[face[0]]
|
||||
components[component_ind].append(face)
|
||||
|
||||
unique_verts, unique_vertex_map = numpy.unique(vertices, axis=0, return_inverse=True)
|
||||
umap = numpy.empty(unique_verts.shape[0], dtype=int)
|
||||
boundary_map = numpy.empty(vertices.shape[0], dtype=int)
|
||||
boundaries = []
|
||||
for i, component in enumerate(components):
|
||||
mask = owner_components == i
|
||||
umask = unique_vertex_map[mask]
|
||||
used_uverts = numpy.unique(umask)
|
||||
|
||||
umap[used_uverts] = numpy.arange(used_uverts.size) # map to account for deletion of unique verts not used in this component
|
||||
boundary_map[mask] = umap[umask] # map from non-unique verts in face to unique, in-use verts
|
||||
|
||||
boundary = {
|
||||
'vertices': unique_verts[used_uverts],
|
||||
'faces': [boundary_map[face] for face in component],
|
||||
}
|
||||
boundaries.append(boundary)
|
||||
|
||||
return boundaries
|
||||
|
||||
261
chop/pyr3d.py
Normal file
261
chop/pyr3d.py
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
from typing import Dict, Tuple
|
||||
import numpy
|
||||
|
||||
from .util import _searchsorted_rows, _argsort_rows, find_faces, number_of_moments
|
||||
|
||||
try:
|
||||
profile
|
||||
except NameError:
|
||||
def profile(f):
|
||||
return f
|
||||
|
||||
|
||||
def build_empty_poly() -> Dict:
|
||||
return {
|
||||
'vertices': numpy.empty((0, 3), dtype=float),
|
||||
'neighbors': numpy.empty((0, 3), dtype=int),
|
||||
}
|
||||
|
||||
|
||||
def clip(poly, plane):
|
||||
left_poly = split(poly, plane, left_only=True)
|
||||
return left_poly
|
||||
|
||||
|
||||
@profile
|
||||
def split(poly, plane, left_only: bool = False):
|
||||
vertices = poly['vertices']
|
||||
neighbors = poly['neighbors']
|
||||
|
||||
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 it
|
||||
ret = None
|
||||
if not numpy.any(left):
|
||||
# if all on right or touching plane
|
||||
ret = build_empty_poly(), poly
|
||||
elif numpy.min(dists) >= 0:
|
||||
# if all on left or touching plane
|
||||
# Can't reuse 'left' because <= vs <
|
||||
ret = poly, build_empty_poly()
|
||||
if ret is not None:
|
||||
return ret[0] if left_only else ret
|
||||
|
||||
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
|
||||
r2l_edges = numpy.empty((0, 3), dtype=int)
|
||||
target_edge_inds = numpy.empty((0, 1), dtype=int)
|
||||
new_vertices = numpy.empty((0, 3), dtype=float)
|
||||
src_pns = numpy.empty((0, 1), dtype=int)
|
||||
num_new_vertices = 0
|
||||
else:
|
||||
# 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_results = numpy.empty_like(edge_walk)
|
||||
src_pns = None
|
||||
while edge_walk.size > 0:
|
||||
prev_verts = edge_walk[:, 0]
|
||||
cur_verts = edge_walk[:, 1]
|
||||
|
||||
# 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_inds[done], 0] = cur_verts[done]
|
||||
edge_walk_results[edge_walk_inds[done], 1] = next_verts[done]
|
||||
edge_walk = numpy.column_stack((cur_verts[not_done], next_verts[not_done]))
|
||||
edge_walk_inds = edge_walk_inds[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)
|
||||
|
||||
# vertex counts
|
||||
num_start = poly['vertices'].shape[0]
|
||||
num_left = numpy.count_nonzero(left)
|
||||
num_right = num_start - num_left
|
||||
|
||||
'''
|
||||
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_pns)] = num_left + numpy.arange(num_new_vertices)
|
||||
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_vertices)
|
||||
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(number_of_moments(poly_order), dtype=float)
|
||||
|
||||
if num_verts == 0:
|
||||
return moments
|
||||
|
||||
faces = find_faces(neighbors)
|
||||
|
||||
triangle_fans = []
|
||||
max_face_len = max(len(face) for face in faces)
|
||||
triangle_inds = numpy.empty((max_face_len - 2, 3), dtype=int)
|
||||
for face in faces:
|
||||
ilen = len(face) - 2
|
||||
triangle_inds[:ilen, 0] = face[0]
|
||||
triangle_inds[:ilen, 1] = face[1:-1]
|
||||
triangle_inds[:ilen, 2] = face[2:]
|
||||
|
||||
triverts = vertices[triangle_inds[:ilen]]
|
||||
triangle_fans.append(triverts)
|
||||
|
||||
triangles = numpy.vstack(triangle_fans)
|
||||
volumes = -numpy.linalg.det(triangles)
|
||||
moments[0] = volumes.sum() / 6
|
||||
|
||||
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 i, vecs in enumerate(triangles):
|
||||
S[:, 0, 0, prevlayer] = 1
|
||||
valid[prevlayer, :, :] = False
|
||||
valid[prevlayer, 0, 0] = True
|
||||
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 number_of_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] += volumes[i] * S[2, valid[curlayer], curlayer].ravel()
|
||||
m += num_valid
|
||||
prevlayer, curlayer = curlayer, prevlayer
|
||||
|
||||
# reuse S[0] to compute the moments' 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 number_of_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
|
||||
|
||||
|
||||
82
chop/shapes.py
Normal file
82
chop/shapes.py
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import numpy
|
||||
from numpy.linalg import norm
|
||||
|
||||
|
||||
def build_tetrahedron(vertices: numpy.ndarray):
|
||||
poly = {
|
||||
'vertices': numpy.array(vertices, dtype=float),
|
||||
'neighbors': numpy.array((
|
||||
(1, 3, 2),
|
||||
(2, 3, 0),
|
||||
(0, 3, 1),
|
||||
(1, 2, 0)), dtype=int),
|
||||
}
|
||||
return poly
|
||||
|
||||
|
||||
def build_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 planes_from_box(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 planes_from_tetrahedron(vertices: numpy.ndarray):
|
||||
verts = numpy.array(vertices, 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 volume_of_tetrahedron(vertices):
|
||||
ad, bd, cd = vertices[0:3] - vertices[3]
|
||||
return -ad @ numpy.cross(bd, cd) / 6
|
||||
|
||||
|
||||
31
chop/transform.py
Normal file
31
chop/transform.py
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import numpy
|
||||
from numpy import sin, cos
|
||||
|
||||
|
||||
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, factor):
|
||||
poly['vertices'] *= factor
|
||||
|
||||
|
||||
def shear(poly, factor: float, axb: int, axs: int):
|
||||
poly['vertices'][:, axb] += factor * 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, :]
|
||||
|
||||
|
||||
151
chop/util.py
Normal file
151
chop/util.py
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
import numpy
|
||||
|
||||
try:
|
||||
profile
|
||||
except NameError:
|
||||
def profile(f):
|
||||
return f
|
||||
|
||||
|
||||
def number_of_moments(order):
|
||||
return ((order + 1) * (order + 2) * (order + 3)) // 6
|
||||
|
||||
|
||||
@profile
|
||||
def find_components(neighbors):
|
||||
num_vertices = neighbors.shape[0]
|
||||
current_component = 1
|
||||
component = numpy.zeros(num_vertices, dtype=int)
|
||||
for v_start in range(num_vertices):
|
||||
if component[v_start] != 0:
|
||||
continue
|
||||
|
||||
verts = numpy.array([v_start], dtype=int)
|
||||
while verts.size > 0:
|
||||
component[verts] = current_component
|
||||
next_verts = numpy.unique(neighbors[verts])
|
||||
verts = next_verts[component[next_verts] == 0]
|
||||
|
||||
current_component += 1
|
||||
return component - 1
|
||||
|
||||
|
||||
@profile
|
||||
def find_faces(neighbors):
|
||||
num_verts = neighbors.shape[0]
|
||||
|
||||
edge_id = numpy.arange(3 * num_verts)
|
||||
nxt_edge = numpy.tile(numpy.arange(3), num_verts)
|
||||
vstart = edge_id // 3
|
||||
vcur = vstart.copy()
|
||||
vnext = neighbors[vcur, nxt_edge]
|
||||
|
||||
faces = [[v] for v in vcur]
|
||||
mask = vstart # dummy for loop init, could use numpy.array([True]) instead
|
||||
remove = numpy.zeros_like(edge_id, dtype=bool)
|
||||
|
||||
while mask.any():
|
||||
for i, vn in zip(edge_id, vnext):
|
||||
faces[i].append(vn)
|
||||
|
||||
prv_edge = (neighbors[vnext, :] == vcur[:, None]).argmax(axis=1)
|
||||
nxt_edge = (prv_edge + 1) % 3
|
||||
vcur, vnext = vnext, neighbors[vnext, nxt_edge]
|
||||
|
||||
remove_mask = vcur < vstart
|
||||
remove[edge_id[remove_mask]] = True
|
||||
|
||||
mask = numpy.logical_and(vnext != vstart, ~remove_mask)
|
||||
edge_id = edge_id[mask]
|
||||
vcur = vcur[mask]
|
||||
vnext = vnext[mask]
|
||||
vstart = vstart[mask]
|
||||
|
||||
faces_set = []
|
||||
for i, do_remove in enumerate(remove):
|
||||
if not do_remove:
|
||||
faces_set.append(faces[i])
|
||||
|
||||
return faces_set
|
||||
|
||||
|
||||
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]
|
||||
|
||||
|
||||
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 check_poly(poly, check_connectivity=True) -> 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 (~n^3 because need bfs for each removed vertex pair)
|
||||
if check_connectivity:
|
||||
components = find_components(neighbors)
|
||||
|
||||
vert_ids = numpy.arange(num_vertices, dtype=int)
|
||||
visited = numpy.empty(num_vertices, dtype=bool)
|
||||
for part_id in numpy.unique(components):
|
||||
part_mask = components == part_id
|
||||
part_verts = vert_ids[part_mask]
|
||||
|
||||
vcs = set(part_verts[:3])
|
||||
for ia in range(part_verts.size):
|
||||
va = part_verts[ia]
|
||||
for vb in part_verts[ia + 1:]:
|
||||
# pick vc != {va, vb}
|
||||
vc = (vcs - set((va, vb))).pop()
|
||||
|
||||
# flood-fill from vc without passing through va, vb
|
||||
visited.fill(False)
|
||||
visited[[va, vb]] = True
|
||||
|
||||
nums = numpy.array([vc], dtype=int)
|
||||
while nums.size > 0:
|
||||
visited[nums] = True
|
||||
new_nums = numpy.unique(neighbors[nums])
|
||||
nums = new_nums[~visited[new_nums]]
|
||||
|
||||
# Make sure we touched all vertices in the component
|
||||
if not visited[components == part_id].all():
|
||||
raise Exception('Vertex graph is not 3-vertex-connected')
|
||||
return True
|
||||
73
chop/voxel.py
Normal file
73
chop/voxel.py
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import numpy
|
||||
|
||||
from .pyr3d import split, reduce
|
||||
from .util import number_of_moments
|
||||
|
||||
try:
|
||||
profile
|
||||
except NameError:
|
||||
def profile(f):
|
||||
return f
|
||||
|
||||
|
||||
@profile
|
||||
def voxelize(poly, d, ibox=None, poly_order=0):
|
||||
ibox = get_ibox(poly, d) if ibox is None else numpy.array(ibox, dtype=int)
|
||||
d = numpy.array(d)
|
||||
|
||||
grid_shape = ibox[1] - ibox[0]
|
||||
dest_grid = numpy.zeros((*grid_shape, number_of_moments(poly_order)), 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, face)
|
||||
ibox = get_ibox(poly, d)
|
||||
return poly, ibox
|
||||
|
||||
Loading…
Reference in a new issue