mostly comments, but broke something
This commit is contained in:
parent
fc82bc255c
commit
3f8b9bef06
9 changed files with 366 additions and 127 deletions
|
|
@ -1,4 +1,7 @@
|
||||||
|
from .util import poly_t, plane_t
|
||||||
|
|
||||||
from .split import split, clip
|
from .split import split, clip
|
||||||
from .moments import get_volume, get_moments, number_of_moments
|
from .moments import get_volume, get_moments, number_of_moments
|
||||||
from .boundary import build_polyhedron, boundary_from_poly
|
from .boundary import build_polyhedron, boundary_from_poly
|
||||||
from .shapes import build_tetrahedron, build_box, planes_from_tetrahedron, planes_from_box
|
from .shapes import build_tetrahedron, build_box, planes_from_tetrahedron, planes_from_box
|
||||||
|
|
||||||
|
|
|
||||||
102
chop/boundary.py
102
chop/boundary.py
|
|
@ -1,6 +1,8 @@
|
||||||
|
from typing import List, Dict
|
||||||
import numpy
|
import numpy
|
||||||
from numpy.linalg import norm
|
from numpy.linalg import norm
|
||||||
|
|
||||||
|
from . import poly_t, plane_t
|
||||||
from .util import _get_map, find_components, find_faces
|
from .util import _get_map, find_components, find_faces
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
@ -11,7 +13,18 @@ except NameError:
|
||||||
return f
|
return f
|
||||||
|
|
||||||
|
|
||||||
def planes_from_boundary(vertices, faces):
|
def planes_from_boundary(vertices: numpy.ndarray,
|
||||||
|
faces: List[numpy.ndarray]
|
||||||
|
) -> List[plane_t]:
|
||||||
|
'''
|
||||||
|
Generate a list of planes (normal, signed distance) from the faces of a boundary-
|
||||||
|
representation polyhedron.
|
||||||
|
|
||||||
|
:param vertices: Nx3 ndarray specifying the polyhedron's vertex positions.
|
||||||
|
:param faces: List of 1d ndarrays. Each ndarray is a list of vertex indices,
|
||||||
|
specifying a face.
|
||||||
|
:return: List of planes, represented by (normal vector, signed distance to origin) tuples.
|
||||||
|
'''
|
||||||
planes = []
|
planes = []
|
||||||
for face in faces:
|
for face in faces:
|
||||||
face_verts = vertices[face]
|
face_verts = vertices[face]
|
||||||
|
|
@ -26,8 +39,17 @@ def planes_from_boundary(vertices, faces):
|
||||||
|
|
||||||
|
|
||||||
@profile
|
@profile
|
||||||
def build_polyhedron(in_vertices, faces):
|
def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t:
|
||||||
in_vertices = numpy.array(in_vertices, dtype=float)
|
'''
|
||||||
|
Generate a 3-verted-connected Schlegel diagram corresponding to the
|
||||||
|
provided boundary-representation polyhedron.
|
||||||
|
|
||||||
|
:param vertices: Nx3 ndarray specifying the polyhedron's vertex positions.
|
||||||
|
:param faces: List of 1d ndarrays. Each ndarray is a list of vertex indices,
|
||||||
|
specifying a face.
|
||||||
|
:return: Schelgel-representation polyhedron
|
||||||
|
'''
|
||||||
|
vertices = numpy.array(vertices, dtype=float)
|
||||||
faces = [numpy.array(face, dtype=int) for face in faces]
|
faces = [numpy.array(face, dtype=int) for face in faces]
|
||||||
|
|
||||||
edges_per_vertex = numpy.bincount(numpy.hstack(faces))
|
edges_per_vertex = numpy.bincount(numpy.hstack(faces))
|
||||||
|
|
@ -36,10 +58,9 @@ def build_polyhedron(in_vertices, faces):
|
||||||
raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges')
|
raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges')
|
||||||
|
|
||||||
if edges_per_vertex.max() == 3:
|
if edges_per_vertex.max() == 3:
|
||||||
# Don't need to duplicate any vertices to make 3-connected graph
|
'''
|
||||||
vertices = in_vertices
|
In this case, we don't need to duplicate any vertices to make a 3-vertex-connected graph
|
||||||
|
'''
|
||||||
# Link up the vertices
|
|
||||||
neighbors = numpy.empty_like(vertices, dtype=int).fill(vertices.size)
|
neighbors = numpy.empty_like(vertices, dtype=int).fill(vertices.size)
|
||||||
for face in faces:
|
for face in faces:
|
||||||
# Check if each vertex in this face is already linked to its next or previous face-neighbor
|
# Check if each vertex in this face is already linked to its next or previous face-neighbor
|
||||||
|
|
@ -61,7 +82,7 @@ def build_polyhedron(in_vertices, faces):
|
||||||
# If the vertex has already been linked to something (by a different face),
|
# If the vertex has already been linked to something (by a different face),
|
||||||
# fill in the third neighbor
|
# fill in the third neighbor
|
||||||
# Note that this causes excess writes; it might improve performace to check
|
# Note that this causes excess writes; it might improve performace to check
|
||||||
# if the third neighbor is already filled
|
# if the third neighbor is already filled (maybe? TODO)
|
||||||
neighbors[face[has_prev], 2] = next_vert[has_prev]
|
neighbors[face[has_prev], 2] = next_vert[has_prev]
|
||||||
neighbors[face[has_next], 2] = prev_vert[has_next]
|
neighbors[face[has_next], 2] = prev_vert[has_next]
|
||||||
|
|
||||||
|
|
@ -130,33 +151,32 @@ def build_polyhedron(in_vertices, faces):
|
||||||
the links to reflect their removal.
|
the links to reflect their removal.
|
||||||
'''
|
'''
|
||||||
# starting row for each original vertex
|
# starting row for each original vertex
|
||||||
vstart = numpy.roll(numpy.cumsum(edges_per_vertex), 1)
|
start = numpy.roll(numpy.cumsum(edges_per_vertex), 1)
|
||||||
vstart[0] = 0
|
start[0] = 0
|
||||||
|
|
||||||
# number of input vertices (v) and duplicates (d)
|
# number of input vertices (v) and duplicates (d)
|
||||||
num_v = in_vertices.shape[0]
|
num_vertices = vertices.shape[0]
|
||||||
num_duplicates = edges_per_vertex.sum()
|
num_duplicates = edges_per_vertex.sum()
|
||||||
|
|
||||||
# Linkage and aux array
|
|
||||||
neighbors = numpy.empty((num_duplicates, 3), dtype=int)
|
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)
|
Fill columns (1, 2) with original vertex inds (f#_next, f#_prev)
|
||||||
'''
|
'''
|
||||||
|
num_filled_rows = numpy.zeros(num_duplicates, dtype=int)
|
||||||
for face in faces:
|
for face in faces:
|
||||||
# assume a face can't use the same vertex twice
|
# assume a face can't use the same vertex twice
|
||||||
v_inds = vstart[face] + util[face]
|
v_inds = start[face] + num_filled_rows[face]
|
||||||
neighbors[v_inds, 1] = numpy.roll(face, -1)
|
neighbors[v_inds, 1] = numpy.roll(face, -1)
|
||||||
neighbors[v_inds, 2] = numpy.roll(face, 1)
|
neighbors[v_inds, 2] = numpy.roll(face, 1)
|
||||||
util[face] += 1
|
num_filled_rows[face] += 1
|
||||||
|
|
||||||
'''
|
'''
|
||||||
Fill columns (0, 2) with new vertex inds (next_row, prev_row)
|
Fill columns (0, 2) with new vertex inds (next_row, prev_row)
|
||||||
to complete doubly-linked rings
|
to complete doubly-linked rings
|
||||||
'''
|
'''
|
||||||
for v in range(num_v):
|
for v in range(num_vertices):
|
||||||
v0 = vstart[v]
|
v0 = start[v]
|
||||||
s = slice(v0, v0 + edges_per_vertex[v])
|
s = slice(v0, v0 + edges_per_vertex[v])
|
||||||
m, n = _get_map(neighbors[s, 2], neighbors[s, 1])
|
m, n = _get_map(neighbors[s, 2], neighbors[s, 1])
|
||||||
neighbors[s, 0] = n + v0
|
neighbors[s, 0] = n + v0
|
||||||
|
|
@ -177,8 +197,8 @@ def build_polyhedron(in_vertices, faces):
|
||||||
src_mask = numpy.empty(num_duplicates, dtype=bool)
|
src_mask = numpy.empty(num_duplicates, dtype=bool)
|
||||||
dst_mask = numpy.empty(num_duplicates, dtype=bool)
|
dst_mask = numpy.empty(num_duplicates, dtype=bool)
|
||||||
|
|
||||||
for v in range(num_v):
|
for v in range(num_vertices):
|
||||||
s = vstart[v]
|
s = start[v]
|
||||||
e = s + edges_per_vertex[v]
|
e = s + edges_per_vertex[v]
|
||||||
|
|
||||||
src_mask.fill(False)
|
src_mask.fill(False)
|
||||||
|
|
@ -199,20 +219,20 @@ def build_polyhedron(in_vertices, faces):
|
||||||
'''
|
'''
|
||||||
Remove first two duplicates of each vertex (they aren't needed)
|
Remove first two duplicates of each vertex (they aren't needed)
|
||||||
'''
|
'''
|
||||||
nxt, third, prv = neighbors[vstart, :].T
|
nxt, third, prv = neighbors[start, :].T
|
||||||
nxt_nxt, nxt_third, _nxt_prv = neighbors[nxt, :].T
|
nxt_nxt, nxt_third, _nxt_prv = neighbors[nxt, :].T
|
||||||
|
|
||||||
# Which vertex to link to
|
# Which vertex to link to
|
||||||
dest_map = numpy.arange(num_duplicates, dtype=int) # default maps to itself
|
dest_map = numpy.arange(num_duplicates, dtype=int) # default maps to itself
|
||||||
dest_map[vstart] = prv # first maps to previous
|
dest_map[start] = prv # first maps to previous
|
||||||
dest_map[nxt] = nxt_nxt # second maps to next
|
dest_map[nxt] = nxt_nxt # second maps to next
|
||||||
|
|
||||||
# Which backreference to modify
|
# Which backreference to modify
|
||||||
back_map = numpy.full_like(dest_map, 1) # default is 'third'
|
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[start] = 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'
|
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
|
# Map 'third' to where it should point to. 'dm'~'dest_map'
|
||||||
dm_third = dest_map[third]
|
dm_third = dest_map[third]
|
||||||
dm_nxt_third = dest_map[nxt_third]
|
dm_nxt_third = dest_map[nxt_third]
|
||||||
|
|
||||||
|
|
@ -223,31 +243,41 @@ def build_polyhedron(in_vertices, faces):
|
||||||
neighbors[dm_nxt_third, back_map[nxt_third]] = nxt_nxt # next-third's backreference points to next-next
|
neighbors[dm_nxt_third, back_map[nxt_third]] = nxt_nxt # next-third's backreference points to next-next
|
||||||
|
|
||||||
# Mark for removal
|
# Mark for removal
|
||||||
util.fill(0)
|
keep_map = num_filled_rows # reuse to avoid reallocating
|
||||||
util[vstart] = 1
|
keep_map.fill(1)
|
||||||
util[nxt] = 1
|
keep_map[start] = 0
|
||||||
|
keep_map[nxt] = 0
|
||||||
|
|
||||||
neighbors = neighbors[util == 0]
|
neighbors = neighbors[keep_map != 0]
|
||||||
util[util == 0] = numpy.arange(neighbors.shape[0])
|
keep_map[keep_map != 0] = numpy.arange(neighbors.shape[0])
|
||||||
neighbors[:] = util[neighbors]
|
neighbors[:] = keep_map[neighbors]
|
||||||
|
|
||||||
vertices = numpy.repeat(in_vertices, edges_per_vertex - 2, axis=0)
|
final_vertices = numpy.repeat(vertices, edges_per_vertex - 2, axis=0)
|
||||||
|
|
||||||
return {'vertices': vertices, 'neighbors': neighbors}
|
return {'vertices': final_vertices, 'neighbors': neighbors}
|
||||||
|
|
||||||
|
|
||||||
@profile
|
@profile
|
||||||
def boundary_from_poly(poly):
|
def boundary_from_poly(poly: poly_t) -> Dict:
|
||||||
|
'''
|
||||||
|
Generate a boundary represeentation corresponding to the provided
|
||||||
|
3-vertex-connected Schlegel diagram.
|
||||||
|
|
||||||
|
:param poly: Polyhedron to convert, in Schlegel representation.
|
||||||
|
:return: Dict containing 'vertices' (Nx3 ndarray of vertex locations)
|
||||||
|
and 'faces' (list of ndarrays specifying the indices of vertices
|
||||||
|
used for constructing each face).
|
||||||
|
'''
|
||||||
neighbors = poly['neighbors']
|
neighbors = poly['neighbors']
|
||||||
vertices = poly['vertices']
|
vertices = poly['vertices']
|
||||||
|
|
||||||
owner_components = find_components(neighbors)
|
owning_component = find_components(neighbors)
|
||||||
faces = find_faces(neighbors)
|
faces = find_faces(neighbors)
|
||||||
num_components = owner_components.max() + 1
|
num_components = owning_component.max() + 1
|
||||||
|
|
||||||
components = [[] for _ in range(num_components)]
|
components = [[] for _ in range(num_components)]
|
||||||
for face in faces:
|
for face in faces:
|
||||||
component_ind = owner_components[face[0]]
|
component_ind = owning_component[face[0]]
|
||||||
components[component_ind].append(face)
|
components[component_ind].append(face)
|
||||||
|
|
||||||
unique_verts, unique_vertex_map = numpy.unique(vertices, axis=0, return_inverse=True)
|
unique_verts, unique_vertex_map = numpy.unique(vertices, axis=0, return_inverse=True)
|
||||||
|
|
@ -255,7 +285,7 @@ def boundary_from_poly(poly):
|
||||||
boundary_map = numpy.empty(vertices.shape[0], dtype=int)
|
boundary_map = numpy.empty(vertices.shape[0], dtype=int)
|
||||||
boundaries = []
|
boundaries = []
|
||||||
for i, component in enumerate(components):
|
for i, component in enumerate(components):
|
||||||
mask = owner_components == i
|
mask = owning_component == i
|
||||||
umask = unique_vertex_map[mask]
|
umask = unique_vertex_map[mask]
|
||||||
used_uverts = numpy.unique(umask)
|
used_uverts = numpy.unique(umask)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
from typing import Dict, Tuple
|
from typing import Dict, Tuple
|
||||||
import numpy
|
import numpy
|
||||||
|
|
||||||
|
from . import poly_t, plane_t
|
||||||
from .util import find_faces
|
from .util import find_faces
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
@ -11,56 +12,88 @@ except NameError:
|
||||||
return f
|
return f
|
||||||
|
|
||||||
|
|
||||||
def number_of_moments(order):
|
def number_of_moments(order: int) -> int:
|
||||||
|
'''
|
||||||
|
Returns the number of moments with a given order or below.
|
||||||
|
|
||||||
|
:param order: Maximum polynomial order for the moments.
|
||||||
|
:return: Number of moments with that order or fewer.
|
||||||
|
'''
|
||||||
return ((order + 1) * (order + 2) * (order + 3)) // 6
|
return ((order + 1) * (order + 2) * (order + 3)) // 6
|
||||||
|
|
||||||
|
|
||||||
def get_volume(poly):
|
def get_volume(poly: poly_t) -> float:
|
||||||
|
'''
|
||||||
|
Calculates the volume of a polyhedron (0th moment).
|
||||||
|
|
||||||
|
:param poly: Polyhedron to evaluate, in Schlegel representation.
|
||||||
|
:return: Volume of the polyhedron.
|
||||||
|
'''
|
||||||
return get_moments(poly, 0)[0]
|
return get_moments(poly, 0)[0]
|
||||||
|
|
||||||
|
|
||||||
@profile
|
@profile
|
||||||
def get_moments(poly, poly_order):
|
def get_moments(poly: poly_t, order: int) -> numpy.ndarray:
|
||||||
|
'''
|
||||||
|
Calculates the moments of a polyhedron, up to the specified polynomial order.
|
||||||
|
|
||||||
|
:param poly: Polyhedron to evaluate, in Schlegel representation.
|
||||||
|
:param order: Maximum polynomial order for moments.
|
||||||
|
:return: Moments, increasing polynomial order:
|
||||||
|
[1, x, y, z, xx, xy, xz, yy, yz, zz, xxx, xxy, xxz, ...]
|
||||||
|
'''
|
||||||
vertices = poly['vertices']
|
vertices = poly['vertices']
|
||||||
neighbors = poly['neighbors']
|
neighbors = poly['neighbors']
|
||||||
num_verts = vertices.shape[0]
|
num_verts = vertices.shape[0]
|
||||||
|
moments = numpy.zeros(number_of_moments(order), dtype=float)
|
||||||
moments = numpy.zeros(number_of_moments(poly_order), dtype=float)
|
|
||||||
|
|
||||||
if num_verts == 0:
|
if num_verts == 0:
|
||||||
return moments
|
return moments
|
||||||
|
|
||||||
|
'''
|
||||||
|
Decompose polyhedron into triangle fans
|
||||||
|
'''
|
||||||
faces = find_faces(neighbors)
|
faces = find_faces(neighbors)
|
||||||
|
|
||||||
triangle_fans = []
|
triangle_fans = []
|
||||||
max_face_len = max(len(face) for face in faces)
|
max_face_len = max(len(face) for face in faces)
|
||||||
triangle_inds = numpy.empty((max_face_len - 2, 3), dtype=int)
|
triangle_inds = numpy.empty((max_face_len - 2, 3), dtype=int)
|
||||||
for face in faces:
|
for face in faces:
|
||||||
|
# Build a triangle fan from each face
|
||||||
ilen = len(face) - 2
|
ilen = len(face) - 2
|
||||||
triangle_inds[:ilen, 0] = face[0] # this one broadcasts
|
triangle_inds[:ilen, 0] = face[0] # this assignment is a broadcast
|
||||||
triangle_inds[:ilen, 1] = face[1:-1]
|
triangle_inds[:ilen, 1] = face[1:-1]
|
||||||
triangle_inds[:ilen, 2] = face[2:]
|
triangle_inds[:ilen, 2] = face[2:]
|
||||||
|
|
||||||
triverts = vertices[triangle_inds[:ilen]]
|
triverts = vertices[triangle_inds[:ilen]]
|
||||||
triangle_fans.append(triverts)
|
triangle_fans.append(triverts)
|
||||||
|
|
||||||
|
'''
|
||||||
|
Calculate the 0th-order moment
|
||||||
|
'''
|
||||||
triangles = numpy.vstack(triangle_fans)
|
triangles = numpy.vstack(triangle_fans)
|
||||||
volumes = -numpy.linalg.det(triangles)
|
volumes = -numpy.linalg.det(triangles)
|
||||||
moments[0] = volumes.sum() / 6
|
moments[0] = volumes.sum() / 6
|
||||||
|
|
||||||
|
if order == 0:
|
||||||
|
return moments
|
||||||
|
|
||||||
|
'''
|
||||||
|
Iteratively calculate higher-order moments, as per Koehl (2012).
|
||||||
|
'''
|
||||||
prevlayer, curlayer = 0, 1
|
prevlayer, curlayer = 0, 1
|
||||||
S = numpy.zeros((3, poly_order + 1, poly_order + 1, 2), dtype=float)
|
S = numpy.zeros((3, order + 1, order + 1, 2), dtype=float)
|
||||||
inds = numpy.arange(poly_order + 1)
|
inds = numpy.arange(order + 1)
|
||||||
mx, my = numpy.meshgrid(inds, inds, indexing='ij')
|
mx, my = numpy.meshgrid(inds, inds, indexing='ij')
|
||||||
valid = numpy.zeros((2, poly_order + 1, poly_order + 1), dtype=bool)
|
valid = numpy.zeros((2, order + 1, order + 1), dtype=bool)
|
||||||
cropped = numpy.zeros((poly_order + 1, poly_order + 1), dtype=bool)
|
cropped = numpy.zeros((order + 1, order + 1), dtype=bool)
|
||||||
|
|
||||||
for i, vecs in enumerate(triangles):
|
for i, vecs in enumerate(triangles):
|
||||||
S[:, 0, 0, prevlayer] = 1
|
S[:, 0, 0, prevlayer] = 1
|
||||||
valid[prevlayer, :, :] = False
|
valid[prevlayer, :, :] = False
|
||||||
valid[prevlayer, 0, 0] = True
|
valid[prevlayer, 0, 0] = True
|
||||||
m = 1
|
m = 1
|
||||||
for c in range(1, poly_order+1):
|
for c in range(1, order + 1):
|
||||||
valid[curlayer] = c >= mx + my
|
valid[curlayer] = c >= mx + my
|
||||||
num_valid = (c + 1) * (c + 2) // 2 # always an int, see number_of_moments()
|
num_valid = (c + 1) * (c + 2) // 2 # always an int, see number_of_moments()
|
||||||
|
|
||||||
|
|
@ -87,7 +120,7 @@ def get_moments(poly, poly_order):
|
||||||
m = 1
|
m = 1
|
||||||
valid[prevlayer, :, :] = False
|
valid[prevlayer, :, :] = False
|
||||||
valid[prevlayer, 0, 0] = True
|
valid[prevlayer, 0, 0] = True
|
||||||
for c in range(1, poly_order+1):
|
for c in range(1, order + 1):
|
||||||
valid[curlayer] = c >= mx + my
|
valid[curlayer] = c >= mx + my
|
||||||
num_valid = (c + 1) * (c + 2) // 2 # always an int, see number_of_moments()
|
num_valid = (c + 1) * (c + 2) // 2 # always an int, see number_of_moments()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,17 @@
|
||||||
|
from typing import List
|
||||||
import numpy
|
import numpy
|
||||||
from numpy.linalg import norm
|
from numpy.linalg import norm
|
||||||
|
|
||||||
|
from . import poly_t, plane_t
|
||||||
|
|
||||||
def build_tetrahedron(vertices: numpy.ndarray):
|
|
||||||
|
def build_tetrahedron(vertices: numpy.ndarray) -> poly_t:
|
||||||
|
'''
|
||||||
|
Build a Schelegel-representation tetrahedron.
|
||||||
|
|
||||||
|
:param vertices: 4x3 array, representing the vertex coordinates.
|
||||||
|
:return: Tetrahedron in Schelgel representation.
|
||||||
|
'''
|
||||||
poly = {
|
poly = {
|
||||||
'vertices': numpy.array(vertices, dtype=float),
|
'vertices': numpy.array(vertices, dtype=float),
|
||||||
'neighbors': numpy.array((
|
'neighbors': numpy.array((
|
||||||
|
|
@ -14,7 +23,14 @@ def build_tetrahedron(vertices: numpy.ndarray):
|
||||||
return poly
|
return poly
|
||||||
|
|
||||||
|
|
||||||
def build_box(rbounds):
|
def build_box(box_corners: numpy.ndarray) -> poly_t:
|
||||||
|
'''
|
||||||
|
Build a Schelegel-representation box.
|
||||||
|
|
||||||
|
:param box_corners: 2x3 array, representing the vertex coordinates of
|
||||||
|
two diagonally-opposite corners of the box.
|
||||||
|
:return: Box in Schelgel representation.
|
||||||
|
'''
|
||||||
neighbors = [
|
neighbors = [
|
||||||
[1, 4, 3],
|
[1, 4, 3],
|
||||||
[2, 5, 0],
|
[2, 5, 0],
|
||||||
|
|
@ -27,14 +43,14 @@ def build_box(rbounds):
|
||||||
]
|
]
|
||||||
|
|
||||||
vertices = [
|
vertices = [
|
||||||
[rbounds[0, 0], rbounds[0, 1], rbounds[0, 2]],
|
[box_corners[0, 0], box_corners[0, 1], box_corners[0, 2]],
|
||||||
[rbounds[1, 0], rbounds[0, 1], rbounds[0, 2]],
|
[box_corners[1, 0], box_corners[0, 1], box_corners[0, 2]],
|
||||||
[rbounds[1, 0], rbounds[1, 1], rbounds[0, 2]],
|
[box_corners[1, 0], box_corners[1, 1], box_corners[0, 2]],
|
||||||
[rbounds[0, 0], rbounds[1, 1], rbounds[0, 2]],
|
[box_corners[0, 0], box_corners[1, 1], box_corners[0, 2]],
|
||||||
[rbounds[0, 0], rbounds[0, 1], rbounds[1, 2]],
|
[box_corners[0, 0], box_corners[0, 1], box_corners[1, 2]],
|
||||||
[rbounds[1, 0], rbounds[0, 1], rbounds[1, 2]],
|
[box_corners[1, 0], box_corners[0, 1], box_corners[1, 2]],
|
||||||
[rbounds[1, 0], rbounds[1, 1], rbounds[1, 2]],
|
[box_corners[1, 0], box_corners[1, 1], box_corners[1, 2]],
|
||||||
[rbounds[0, 0], rbounds[1, 1], rbounds[1, 2]],
|
[box_corners[0, 0], box_corners[1, 1], box_corners[1, 2]],
|
||||||
]
|
]
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
@ -43,20 +59,33 @@ def build_box(rbounds):
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def planes_from_box(rbounds: numpy.ndarray):
|
def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]:
|
||||||
|
'''
|
||||||
|
Construct a list of planes corresponding to the faces of a box.
|
||||||
|
|
||||||
|
:param box_corners: 2x3 array, representing the vertex coordinates of
|
||||||
|
two diagonally-opposite corners of the box.
|
||||||
|
:return: List of planes, facing inwards.
|
||||||
|
'''
|
||||||
faces = [
|
faces = [
|
||||||
(( 0, 0, 1), -rbounds[0, 2]),
|
(( 0, 0, 1), -box_corners[0, 2]),
|
||||||
(( 0, 0, -1), rbounds[1, 2]),
|
(( 0, 0, -1), box_corners[1, 2]),
|
||||||
(( 0, 1, 0), -rbounds[0, 1]),
|
(( 0, 1, 0), -box_corners[0, 1]),
|
||||||
(( 0, -1, 0), rbounds[1, 1]),
|
(( 0, -1, 0), box_corners[1, 1]),
|
||||||
(( 1, 0, 0), -rbounds[0, 0]),
|
(( 1, 0, 0), -box_corners[0, 0]),
|
||||||
((-1, 0, 0), rbounds[1, 0]),
|
((-1, 0, 0), box_corners[1, 0]),
|
||||||
]
|
]
|
||||||
|
|
||||||
return [(numpy.array(n), d) for n, d in faces]
|
return [(numpy.array(n), d) for n, d in faces]
|
||||||
|
|
||||||
|
|
||||||
def planes_from_tetrahedron(vertices: numpy.ndarray):
|
def planes_from_tetrahedron(vertices: numpy.ndarray) -> List[plane_t]:
|
||||||
|
'''
|
||||||
|
Construct a list of planes corresponding to the faces of a tetrahedron.
|
||||||
|
|
||||||
|
:param vertices: 4x3 array, representing the vertex coordinates.
|
||||||
|
:return: List of planes, facing inwards.
|
||||||
|
'''
|
||||||
verts = numpy.array(vertices, dtype=float)
|
verts = numpy.array(vertices, dtype=float)
|
||||||
vset_inds = numpy.array((
|
vset_inds = numpy.array((
|
||||||
[3, 1, 2, 1],
|
[3, 1, 2, 1],
|
||||||
|
|
@ -73,4 +102,3 @@ def planes_from_tetrahedron(vertices: numpy.ndarray):
|
||||||
d = -numpy.sum(n * centers, axis=1)
|
d = -numpy.sum(n * centers, axis=1)
|
||||||
|
|
||||||
return [plane for plane in zip(n, d)]
|
return [plane for plane in zip(n, d)]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
from typing import Dict, Tuple
|
|
||||||
import numpy
|
import numpy
|
||||||
|
|
||||||
from .util import _searchsorted_rows, _argsort_rows
|
from . import poly_t, plane_t
|
||||||
|
from .util import _searchsorted_rows, _argsort_rows, build_empty
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Check if running with line_profiler
|
# Check if running with line_profiler
|
||||||
|
|
@ -11,20 +11,37 @@ except NameError:
|
||||||
return f
|
return f
|
||||||
|
|
||||||
|
|
||||||
def build_empty_poly() -> Dict:
|
def clip(poly: poly_t, plane: plane_t) -> poly_t:
|
||||||
return {
|
'''
|
||||||
'vertices': numpy.empty((0, 3), dtype=float),
|
Clip a polyhedron with a plane, keeping only the part which is on
|
||||||
'neighbors': numpy.empty((0, 3), dtype=int),
|
the same side as the plane's normal vector.
|
||||||
}
|
|
||||||
|
|
||||||
|
This function is equivalent to calling split(poly, plane, same_only=True).
|
||||||
|
|
||||||
def clip(poly, plane):
|
:param poly: Polyhedron to clip, in chiral Schlegel representation.
|
||||||
left_poly = split(poly, plane, left_only=True)
|
:param plane: Plane to clip against.
|
||||||
|
:return: Clipped polyhedron.
|
||||||
|
'''
|
||||||
|
left_poly = split(poly, plane, same_only=True)
|
||||||
return left_poly
|
return left_poly
|
||||||
|
|
||||||
|
|
||||||
@profile
|
@profile
|
||||||
def split(poly, plane, left_only: bool = False):
|
def split(poly, plane, same_only: bool = False):
|
||||||
|
'''
|
||||||
|
Clip a polyhedron with a plane.
|
||||||
|
|
||||||
|
If same_only is False (default), returns the tuple (same_side_poly, other_side_poly),
|
||||||
|
where same_side_poly is on the same side as the plane's normal vector. Otherwise,
|
||||||
|
returns only same_side_poly (somewhat faster).
|
||||||
|
|
||||||
|
:param poly: Polyhedron to clip, in chiral Schlegel representation.
|
||||||
|
:param plane: Plane to clip against.
|
||||||
|
:param same_only: If True, only returns the clipped poly from the same side as the
|
||||||
|
plane's normal vector. Default False.
|
||||||
|
:return: (same_side_poly, other_side_poly) if same_only is False (default), otherwise
|
||||||
|
only returns same_side_poly.
|
||||||
|
'''
|
||||||
vertices = poly['vertices']
|
vertices = poly['vertices']
|
||||||
neighbors = poly['neighbors']
|
neighbors = poly['neighbors']
|
||||||
num_start = poly['vertices'].shape[0]
|
num_start = poly['vertices'].shape[0]
|
||||||
|
|
@ -36,17 +53,19 @@ def split(poly, plane, left_only: bool = False):
|
||||||
num_left = numpy.count_nonzero(left)
|
num_left = numpy.count_nonzero(left)
|
||||||
num_right = num_start - num_left
|
num_right = num_start - num_left
|
||||||
|
|
||||||
# if the poly lies entirely on one side of the plane, just return it
|
'''
|
||||||
|
if the poly lies entirely on one side of the plane, just return it
|
||||||
|
'''
|
||||||
ret = None
|
ret = None
|
||||||
if num_left == 0:
|
if num_left == 0:
|
||||||
# if all on right or touching plane
|
# if all on right or touching plane
|
||||||
ret = build_empty_poly(), poly
|
ret = build_empty(), poly
|
||||||
elif dists.min() >= 0:
|
elif dists.min() >= 0:
|
||||||
# if all on left or touching plane
|
# if all on left or touching plane
|
||||||
# Can't reuse 'left' because <= vs <
|
# Can't reuse 'left' because <= vs <
|
||||||
ret = poly, build_empty_poly()
|
ret = poly, build_empty()
|
||||||
if ret is not None:
|
if ret is not None:
|
||||||
return ret[0] if left_only else ret
|
return ret[0] if same_only else ret
|
||||||
|
|
||||||
right_inds = numpy.where(right)[0]
|
right_inds = numpy.where(right)[0]
|
||||||
next_vertex = neighbors[right_inds, :].ravel()
|
next_vertex = neighbors[right_inds, :].ravel()
|
||||||
|
|
@ -55,7 +74,9 @@ def split(poly, plane, left_only: bool = False):
|
||||||
far_vertex_left = left[next_vertex]
|
far_vertex_left = left[next_vertex]
|
||||||
|
|
||||||
if not far_vertex_left.any():
|
if not far_vertex_left.any():
|
||||||
# No edges cross, but components on either side
|
'''
|
||||||
|
No edges cross the plane, but components exist on either side
|
||||||
|
'''
|
||||||
r2l_edges = numpy.empty((0, 3), dtype=int)
|
r2l_edges = numpy.empty((0, 3), dtype=int)
|
||||||
target_edge_inds = numpy.empty((0, 1), dtype=int)
|
target_edge_inds = numpy.empty((0, 1), dtype=int)
|
||||||
new_vertices = numpy.empty((0, 3), dtype=float)
|
new_vertices = numpy.empty((0, 3), dtype=float)
|
||||||
|
|
@ -64,6 +85,9 @@ def split(poly, plane, left_only: bool = False):
|
||||||
re = numpy.empty(0, dtype=int)
|
re = numpy.empty(0, dtype=int)
|
||||||
le = re.copy()
|
le = re.copy()
|
||||||
else:
|
else:
|
||||||
|
'''
|
||||||
|
Some edges cross the plane
|
||||||
|
'''
|
||||||
right_inds3 = numpy.repeat(right_inds, 3)
|
right_inds3 = numpy.repeat(right_inds, 3)
|
||||||
pnbr_inds = numpy.arange(3 * num_right) % 3
|
pnbr_inds = numpy.arange(3 * num_right) % 3
|
||||||
|
|
||||||
|
|
@ -78,7 +102,9 @@ def split(poly, plane, left_only: bool = False):
|
||||||
|
|
||||||
num_new_vertices = r2l_edges.shape[0]
|
num_new_vertices = r2l_edges.shape[0]
|
||||||
|
|
||||||
# walk counter-clockwise to next crossing edge
|
'''
|
||||||
|
walk to next crossing edge
|
||||||
|
'''
|
||||||
prev_verts = r2l_edges[:, 0]
|
prev_verts = r2l_edges[:, 0]
|
||||||
cur_verts = r2l_edges[:, 1]
|
cur_verts = r2l_edges[:, 1]
|
||||||
edge_walk_inds = numpy.arange(num_new_vertices)
|
edge_walk_inds = numpy.arange(num_new_vertices)
|
||||||
|
|
@ -96,12 +122,13 @@ def split(poly, plane, left_only: bool = False):
|
||||||
|
|
||||||
next_verts = cur_links[(row, new_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 the list of verts
|
# Save edges that cross back to right, and remove them from the list of verts
|
||||||
done = right[next_verts]
|
done = right[next_verts]
|
||||||
not_done = numpy.logical_not(done)
|
|
||||||
edge_walk_results[edge_walk_inds[done], 1] = cur_verts[done]
|
edge_walk_results[edge_walk_inds[done], 1] = cur_verts[done]
|
||||||
edge_walk_results[edge_walk_inds[done], 0] = next_verts[done]
|
edge_walk_results[edge_walk_inds[done], 0] = next_verts[done]
|
||||||
|
|
||||||
|
# Save the current vertices as previous, and our chosen neighbors as current
|
||||||
|
not_done = numpy.logical_not(done)
|
||||||
prev_verts = cur_verts[not_done]
|
prev_verts = cur_verts[not_done]
|
||||||
cur_verts = next_verts[not_done]
|
cur_verts = next_verts[not_done]
|
||||||
edge_walk_inds = edge_walk_inds[not_done]
|
edge_walk_inds = edge_walk_inds[not_done]
|
||||||
|
|
@ -144,7 +171,7 @@ def split(poly, plane, left_only: bool = False):
|
||||||
'neighbors': numpy.vstack((old_neighbors_left, new_neighbors_left)),
|
'neighbors': numpy.vstack((old_neighbors_left, new_neighbors_left)),
|
||||||
}
|
}
|
||||||
|
|
||||||
if left_only:
|
if same_only:
|
||||||
return left_poly
|
return left_poly
|
||||||
|
|
||||||
ind_map_right = numpy.zeros(num_start, dtype=int)
|
ind_map_right = numpy.zeros(num_start, dtype=int)
|
||||||
|
|
|
||||||
|
|
@ -1,31 +1,65 @@
|
||||||
import numpy
|
import numpy
|
||||||
from numpy import sin, cos
|
from numpy import sin, cos
|
||||||
|
|
||||||
|
from . import poly_t, plane_t
|
||||||
|
|
||||||
def rotate(poly, theta: float, axis: int):
|
|
||||||
|
def rotate(poly: poly_t, theta: float, axis: int) -> poly_t:
|
||||||
|
'''
|
||||||
|
Rotate the polyhedron around an axis.
|
||||||
|
|
||||||
|
:param poly: Polyhedron to rotate. Changed in-place.
|
||||||
|
:param theta: Angle to rotate by (radians).
|
||||||
|
:param axis: Axis to rotate around (0-2).
|
||||||
|
:return: Rotated polyhedron.
|
||||||
|
Data is altered in-place but also returned for convenience.
|
||||||
|
'''
|
||||||
s, c = sin(theta), cos(theta)
|
s, c = sin(theta), cos(theta)
|
||||||
v0 = poly['vertices'][:, axis - 2].copy()
|
v0 = poly['vertices'][:, axis - 2].copy()
|
||||||
v1 = poly['vertices'][:, axis - 1].copy()
|
v1 = poly['vertices'][:, axis - 1].copy()
|
||||||
poly['vertices'][:, axis - 2] = c * v0 - s * v1
|
poly['vertices'][:, axis - 2] = c * v0 - s * v1
|
||||||
poly['vertices'][:, axis - 1] = s * v1 + c * v0
|
poly['vertices'][:, axis - 1] = s * v1 + c * v0
|
||||||
|
return poly
|
||||||
|
|
||||||
|
|
||||||
def translate(poly, shift):
|
def translate(poly: poly_t, shift: numpy.ndarray) -> poly_t:
|
||||||
|
'''
|
||||||
|
Translate the polyhedron by a vector.
|
||||||
|
|
||||||
|
:param poly: Polyhedron to translate. Changed in-place.
|
||||||
|
:param shift: Vector to translate by.
|
||||||
|
:return: Translated polyhedron.
|
||||||
|
Data is altered in-place but also returned for convenience.
|
||||||
|
'''
|
||||||
poly['vertices'] += shift
|
poly['vertices'] += shift
|
||||||
|
return poly
|
||||||
|
|
||||||
|
|
||||||
def scale(poly, factor):
|
def scale(poly: poly_t, factor: numpy.ndarray or float) -> poly_t:
|
||||||
|
'''
|
||||||
|
Scale the polyhedron.
|
||||||
|
Can scale by a single value, or scale each axis individually
|
||||||
|
|
||||||
|
:param poly: Polyhedron to scale. Changed in-place.
|
||||||
|
:param factor: Scalar or vector to scale by.
|
||||||
|
:return: Scaled polyhedron.
|
||||||
|
Data is altered in-place but also returned for convenience.
|
||||||
|
'''
|
||||||
poly['vertices'] *= factor
|
poly['vertices'] *= factor
|
||||||
|
return poly
|
||||||
|
|
||||||
|
|
||||||
def shear(poly, factor: float, axb: int, axs: int):
|
def affine(poly: poly_t, xform: numpy.ndarray) -> poly_t:
|
||||||
poly['vertices'][:, axb] += factor * poly['vertices'][:, axs]
|
'''
|
||||||
|
Perform arbitrary affine trasnformation on the polyhedron.
|
||||||
|
|
||||||
|
:param poly: Polyhedron to transform. Changed in-place.
|
||||||
def affine(poly, mat):
|
:param xform: 4x4 affine transformation matrix.
|
||||||
mat4x3 = mat[:, :3]
|
:return: Transformed polyhedron.
|
||||||
mat4x1 = mat[:, 3]
|
Data is altered in-place but also returned for convenience.
|
||||||
|
'''
|
||||||
|
mat4x3 = xform[:, :3]
|
||||||
|
mat4x1 = xform[:, 3]
|
||||||
vh = mat4x3 @ poly['vertices'].T + mat4x1
|
vh = mat4x3 @ poly['vertices'].T + mat4x1
|
||||||
poly['vertices'] = vh[:3, :] / vh[3, :]
|
poly['vertices'][:] = (vh[:3, :] / vh[3, :]).T
|
||||||
|
return poly
|
||||||
|
|
||||||
|
|
|
||||||
107
chop/util.py
107
chop/util.py
|
|
@ -1,3 +1,4 @@
|
||||||
|
from typing import Dict, Tuple, List
|
||||||
import numpy
|
import numpy
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
@ -8,8 +9,33 @@ except NameError:
|
||||||
return f
|
return f
|
||||||
|
|
||||||
|
|
||||||
|
plane_t = Tuple[numpy.ndarray, float]
|
||||||
|
poly_t = Dict[str, numpy.ndarray]
|
||||||
|
|
||||||
|
|
||||||
|
def build_empty() -> poly_t:
|
||||||
|
'''
|
||||||
|
Build an empty Schlegel representation (containing no vertices).
|
||||||
|
|
||||||
|
:return: Empty Schelegel representation.
|
||||||
|
'''
|
||||||
|
return {
|
||||||
|
'vertices': numpy.empty((0, 3), dtype=float),
|
||||||
|
'neighbors': numpy.empty((0, 3), dtype=int),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@profile
|
@profile
|
||||||
def find_components(neighbors):
|
def find_components(neighbors: numpy.ndarray) -> numpy.ndarray:
|
||||||
|
'''
|
||||||
|
Given an adjacency list, flood-fill to find and label connected components.
|
||||||
|
|
||||||
|
:param neighbors: NxM adjacency list. Each of the N vertices is assumed
|
||||||
|
to have the same number of neighbors, which are specified by their
|
||||||
|
indices.
|
||||||
|
:return: 1D ndarray with N entries. Entries are integer labels denoting
|
||||||
|
which connected component the vertex belongs to.
|
||||||
|
'''
|
||||||
num_vertices = neighbors.shape[0]
|
num_vertices = neighbors.shape[0]
|
||||||
current_component = 1
|
current_component = 1
|
||||||
component = numpy.zeros(num_vertices, dtype=int)
|
component = numpy.zeros(num_vertices, dtype=int)
|
||||||
|
|
@ -28,27 +54,39 @@ def find_components(neighbors):
|
||||||
|
|
||||||
|
|
||||||
@profile
|
@profile
|
||||||
def find_faces(neighbors: numpy.ndarray):
|
def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]:
|
||||||
'''
|
'''
|
||||||
|
Traverse the Schlegel diagram to find chordless cycles
|
||||||
|
(i.e., faces of the polyhedron). Assumes 3-vertex-connected
|
||||||
|
graph with exactly 3 neighbors per vertex. Neighbors are ordered
|
||||||
|
counter-clockwise.
|
||||||
|
|
||||||
|
:param neighbors: Nx3 adjacency list. Neighbors are specified by their
|
||||||
|
indices.
|
||||||
|
:return: List of ndarrays, each of which contains the indices in a given
|
||||||
|
face, starting with the lowest index in the face.
|
||||||
'''
|
'''
|
||||||
num_verts = neighbors.shape[0]
|
num_verts = neighbors.shape[0]
|
||||||
|
|
||||||
edge_id = numpy.arange(3 * num_verts)
|
edge_id = numpy.arange(3 * num_verts)
|
||||||
nxt_edge = numpy.arange(num_verts * 3) % 3
|
v_start, nxt_edge = numpy.divmod(edge_id, 3) # arange % 3 is faster than tile
|
||||||
vstart = edge_id // 3
|
v_current = v_start.copy()
|
||||||
vcur = vstart.copy()
|
v_next = neighbors[v_current, nxt_edge]
|
||||||
vnext = neighbors[vcur, nxt_edge]
|
|
||||||
|
|
||||||
mask = vstart # dummy for loop init, could use numpy.array([True]) instead
|
mask = v_start # dummy for loop init, could use numpy.array([True]) instead
|
||||||
remove = numpy.zeros_like(edge_id, dtype=bool)
|
remove = numpy.zeros_like(edge_id, dtype=bool)
|
||||||
|
|
||||||
|
'''
|
||||||
|
Choose a method for storing the face info based on expected
|
||||||
|
runtime vs unnecessary memory allocation
|
||||||
|
'''
|
||||||
if num_verts < 1000:
|
if num_verts < 1000:
|
||||||
# ~3n^2 in memory, but much faster in cases where n isn't prohibitively large
|
# ~3n^2 in memory, but much faster in cases where n isn't prohibitively large
|
||||||
faces = numpy.full((3*num_verts, num_verts-1), -1, dtype=int)
|
faces = numpy.full((3*num_verts, num_verts-1), -1, dtype=int)
|
||||||
faces[:, 0] = vcur
|
faces[:, 0] = v_current
|
||||||
|
|
||||||
def add_edges(edge_id, vnext, k):
|
def add_edges(edge_id, v_nxt, k):
|
||||||
faces[edge_id, k] = vnext
|
faces[edge_id, k] = v_nxt
|
||||||
|
|
||||||
def cleaned_faces(remove, k):
|
def cleaned_faces(remove, k):
|
||||||
faces_set = []
|
faces_set = []
|
||||||
|
|
@ -56,11 +94,11 @@ def find_faces(neighbors: numpy.ndarray):
|
||||||
faces_set.append(row[row >= 0])
|
faces_set.append(row[row >= 0])
|
||||||
return faces_set
|
return faces_set
|
||||||
else:
|
else:
|
||||||
# Alternative approach, less memory-intensive buy slower
|
# Alternative approach, less memory-intensive but slower
|
||||||
faces = [[v] for v in vcur]
|
faces = [[v] for v in v_current]
|
||||||
|
|
||||||
def add_edges(edge_id, vnext, _k):
|
def add_edges(edge_id, v_nxt, _k):
|
||||||
for i, vn in zip(edge_id, vnext):
|
for i, vn in zip(edge_id, v_nxt):
|
||||||
faces[i].append(vn)
|
faces[i].append(vn)
|
||||||
|
|
||||||
def cleaned_faces(remove, _k):
|
def cleaned_faces(remove, _k):
|
||||||
|
|
@ -69,8 +107,17 @@ def find_faces(neighbors: numpy.ndarray):
|
||||||
faces_set.append(faces[i])
|
faces_set.append(faces[i])
|
||||||
return faces_set
|
return faces_set
|
||||||
|
|
||||||
|
'''
|
||||||
|
Starting at all vertices, take a step along all edges.
|
||||||
|
If the vertex index decreases, stop traversal and mark the path for removal.
|
||||||
|
Otherwise, continue stepping along the _next_ edge each time, until
|
||||||
|
a) the vertex index decreases (stop and mark for removal)
|
||||||
|
b) we reach the original vertex (stop, done with this path)
|
||||||
|
'''
|
||||||
k = 1
|
k = 1
|
||||||
v = numpy.vstack((edge_id, vstart, vcur, vnext))
|
#init_mask = v_next > v_current
|
||||||
|
#v = numpy.vstack((edge_id, v_start, v_current, v_next))[:, init_mask]
|
||||||
|
v = numpy.vstack((edge_id, v_start, v_current, v_next))
|
||||||
while mask.any():
|
while mask.any():
|
||||||
add_edges(v[0], v[3], k)
|
add_edges(v[0], v[3], k)
|
||||||
|
|
||||||
|
|
@ -89,8 +136,10 @@ def find_faces(neighbors: numpy.ndarray):
|
||||||
|
|
||||||
|
|
||||||
def _get_map(a, b):
|
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
|
Returns m, n such that a[m] == b, b[n] == a
|
||||||
|
Assumes that all elements appear exactly once in each array
|
||||||
|
'''
|
||||||
assert(a.size == b.size)
|
assert(a.size == b.size)
|
||||||
if a.size == 0:
|
if a.size == 0:
|
||||||
return numpy.array(()), numpy.array(())
|
return numpy.array(()), numpy.array(())
|
||||||
|
|
@ -104,12 +153,18 @@ def _get_map(a, b):
|
||||||
|
|
||||||
|
|
||||||
def _argsort_rows(a):
|
def _argsort_rows(a):
|
||||||
|
'''
|
||||||
|
Row-wise argsort
|
||||||
|
'''
|
||||||
dims = a.max(0) + 1
|
dims = a.max(0) + 1
|
||||||
a1d = numpy.ravel_multi_index(a.T, dims)
|
a1d = numpy.ravel_multi_index(a.T, dims)
|
||||||
return numpy.argsort(a1d)
|
return numpy.argsort(a1d)
|
||||||
|
|
||||||
|
|
||||||
def _get_map_rows(a, b):
|
def _get_map_rows(a, b):
|
||||||
|
'''
|
||||||
|
Row-wise _get_map
|
||||||
|
'''
|
||||||
dims = numpy.maximum(a.max(0), b.max(0)) + 1
|
dims = numpy.maximum(a.max(0), b.max(0)) + 1
|
||||||
a1d = numpy.ravel_multi_index(a.T, dims)
|
a1d = numpy.ravel_multi_index(a.T, dims)
|
||||||
b1d = numpy.ravel_multi_index(b.T, dims)
|
b1d = numpy.ravel_multi_index(b.T, dims)
|
||||||
|
|
@ -117,13 +172,28 @@ def _get_map_rows(a, b):
|
||||||
|
|
||||||
|
|
||||||
def _searchsorted_rows(a, b):
|
def _searchsorted_rows(a, b):
|
||||||
|
'''
|
||||||
|
Row-wise searchsorted
|
||||||
|
'''
|
||||||
dims = numpy.maximum(a.max(0), b.max(0)) + 1
|
dims = numpy.maximum(a.max(0), b.max(0)) + 1
|
||||||
a1d = numpy.ravel_multi_index(a.T, dims)
|
a1d = numpy.ravel_multi_index(a.T, dims)
|
||||||
b1d = numpy.ravel_multi_index(b.T, dims)
|
b1d = numpy.ravel_multi_index(b.T, dims)
|
||||||
return numpy.searchsorted(a1d, b1d)
|
return numpy.searchsorted(a1d, b1d)
|
||||||
|
|
||||||
|
|
||||||
def check_poly(poly, check_connectivity=True) -> bool:
|
def check_poly(poly: poly_t, check_connectivity: bool = True):
|
||||||
|
'''
|
||||||
|
Verify that the polyhedron
|
||||||
|
- has no out-of-bounds neighbors
|
||||||
|
- has no duplicate neighbors
|
||||||
|
- has exactly 3 edges per vertex
|
||||||
|
- is 3-vertex-connected (if check_connectivity is True; slow!)
|
||||||
|
|
||||||
|
:param poly: Polyhedron to check.
|
||||||
|
:param check_connectivity: Whether to check for 3-vertex-connectedness.
|
||||||
|
This is slow! Default True.
|
||||||
|
:raises: Exception if the polyhedron fails a check
|
||||||
|
'''
|
||||||
neighbors = poly['neighbors']
|
neighbors = poly['neighbors']
|
||||||
vertices = poly['vertices']
|
vertices = poly['vertices']
|
||||||
num_vertices = vertices.shape[0]
|
num_vertices = vertices.shape[0]
|
||||||
|
|
@ -174,4 +244,3 @@ def check_poly(poly, check_connectivity=True) -> bool:
|
||||||
# Make sure we touched all vertices in the component
|
# Make sure we touched all vertices in the component
|
||||||
if not visited[components == part_id].all():
|
if not visited[components == part_id].all():
|
||||||
raise Exception('Vertex graph is not 3-vertex-connected')
|
raise Exception('Vertex graph is not 3-vertex-connected')
|
||||||
return True
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
|
from typing import Tuple
|
||||||
import numpy
|
import numpy
|
||||||
|
|
||||||
|
from . import poly_t, plane_t
|
||||||
from .split import split
|
from .split import split
|
||||||
from .moments import get_moments, number_of_moments
|
from .moments import get_moments, number_of_moments
|
||||||
|
|
||||||
|
|
@ -12,12 +14,21 @@ except NameError:
|
||||||
|
|
||||||
|
|
||||||
@profile
|
@profile
|
||||||
def voxelize(poly, d, box=None, poly_order=0):
|
def voxelize(poly: poly_t,
|
||||||
|
d: numpy.ndarray,
|
||||||
|
box: numpy.ndarray = None,
|
||||||
|
order: int = 0
|
||||||
|
) -> numpy.ndarray:
|
||||||
|
'''
|
||||||
|
Voxelize a Schelegel-representation polyhedron
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
box = get_box(poly, d) if box is None else numpy.array(box, dtype=int)
|
box = get_box(poly, d) if box is None else numpy.array(box, dtype=int)
|
||||||
d = numpy.array(d)
|
d = numpy.array(d)
|
||||||
|
|
||||||
grid_shape = box[1] - box[0]
|
grid_shape = box[1] - box[0]
|
||||||
dest_grid = numpy.zeros((*grid_shape, number_of_moments(poly_order)), dtype=float)
|
dest_grid = numpy.zeros((*grid_shape, number_of_moments(order)), dtype=float)
|
||||||
|
|
||||||
if poly is None or poly['vertices'].shape[0] == 0 or (grid_shape <= 0).any():
|
if poly is None or poly['vertices'].shape[0] == 0 or (grid_shape <= 0).any():
|
||||||
return dest_grid
|
return dest_grid
|
||||||
|
|
@ -37,7 +48,7 @@ def voxelize(poly, d, box=None, poly_order=0):
|
||||||
|
|
||||||
# Base case 2: calculate moments for single voxel
|
# Base case 2: calculate moments for single voxel
|
||||||
if max_dist == 1:
|
if max_dist == 1:
|
||||||
moments = get_moments(c_poly, poly_order)
|
moments = get_moments(c_poly, order)
|
||||||
offset = (c_box[0] - box[0])
|
offset = (c_box[0] - box[0])
|
||||||
dest_grid[offset[0], offset[1], offset[2], :] += moments
|
dest_grid[offset[0], offset[1], offset[2], :] += moments
|
||||||
continue
|
continue
|
||||||
|
|
@ -59,13 +70,17 @@ def voxelize(poly, d, box=None, poly_order=0):
|
||||||
return dest_grid
|
return dest_grid
|
||||||
|
|
||||||
|
|
||||||
def get_box(poly, d):
|
def get_box(poly: poly_t, d: numpy.ndarray) -> numpy.ndarray:
|
||||||
min_box = numpy.floor(numpy.min(poly['vertices'], axis=0) / d)
|
min_box = numpy.floor(numpy.min(poly['vertices'], axis=0) / d)
|
||||||
max_box = numpy.ceil(numpy.max(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)
|
return numpy.array((min_box, max_box), dtype=int)
|
||||||
|
|
||||||
|
|
||||||
def clamp_box(poly, box, clampbox, d):
|
def clamp_box(poly: poly_t,
|
||||||
|
box: numpy.ndarray,
|
||||||
|
clampbox: numpy.ndarray,
|
||||||
|
d: numpy.ndarray
|
||||||
|
) -> Tuple[poly_t, numpy.ndarray]:
|
||||||
faces = box_faces_from_verts(clampbox)
|
faces = box_faces_from_verts(clampbox)
|
||||||
for face in faces:
|
for face in faces:
|
||||||
poly = clip(poly, face)
|
poly = clip(poly, face)
|
||||||
|
|
|
||||||
10
tpy_r3d.py
10
tpy_r3d.py
|
|
@ -425,12 +425,12 @@ def test_poly_pyramid():
|
||||||
]
|
]
|
||||||
|
|
||||||
# initialize a general polyhedron
|
# initialize a general polyhedron
|
||||||
opoly = build_polyhedron(vertices, faces)
|
poly = build_polyhedron(vertices, faces)
|
||||||
check_poly(opoly)
|
check_poly(poly)
|
||||||
stack_split(opoly)
|
stack_split(poly)
|
||||||
|
|
||||||
brep = boundary_from_poly(opoly)
|
brep = boundary_from_poly(poly)
|
||||||
logger.debug(f'Round-trip converted pyramid: {brep}')
|
logger.info(f'Round-trip converted pyramid: {brep}')
|
||||||
#plot_brep(brep)
|
#plot_brep(brep)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue