Fixup numpy typing info

This commit is contained in:
Jan Petykiewicz 2022-08-19 00:17:49 -07:00
commit 073f233775
7 changed files with 50 additions and 40 deletions

View file

@ -1,13 +1,14 @@
from typing import List, Dict, Any from typing import List, Dict, Any
import numpy import numpy
from numpy.linalg import norm from numpy.linalg import norm
from numpy.typing import ArrayLike, NDArray
from . import poly_t, plane_t from . import poly_t, plane_t
from .util import _get_maps, find_components, find_faces from .util import _get_maps, find_components, find_faces
def planes_from_boundary(vertices: numpy.ndarray, def planes_from_boundary(vertices: ArrayLike,
faces: List[numpy.ndarray] faces: List[ArrayLike]
) -> List[plane_t]: ) -> List[plane_t]:
''' '''
Generate a list of planes (normal, signed distance) from the faces of a boundary- Generate a list of planes (normal, signed distance) from the faces of a boundary-
@ -21,8 +22,10 @@ def planes_from_boundary(vertices: numpy.ndarray,
Returns: Returns:
List of planes, represented by (normal vector, signed distance to origin) tuples. List of planes, represented by (normal vector, signed distance to origin) tuples.
''' '''
vertices = numpy.array(vertices, copy=False)
afaces = [numpy.array(ff, copy=False) for ff in faces]
planes = [] planes = []
for face in faces: for face in afaces:
face_verts = vertices[face] face_verts = vertices[face]
n = numpy.cross(numpy.diff(face_verts, n=1, axis=0), n = numpy.cross(numpy.diff(face_verts, n=1, axis=0),
@ -34,7 +37,7 @@ def planes_from_boundary(vertices: numpy.ndarray,
return planes return planes
def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t: def build_polyhedron(vertices: ArrayLike, faces: List[ArrayLike]) -> poly_t:
''' '''
Generate a 3-verted-connected Schlegel diagram representation Generate a 3-verted-connected Schlegel diagram representation
corresponding to the provided boundary-representation polyhedron. corresponding to the provided boundary-representation polyhedron.
@ -48,9 +51,9 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t:
Schelgel-representation polyhedron Schelgel-representation polyhedron
''' '''
vertices = numpy.array(vertices, dtype=float) vertices = numpy.array(vertices, dtype=float)
faces = [numpy.array(face, dtype=int) for face in faces] afaces = [numpy.array(face, dtype=int) for face in faces]
edges_per_vertex = numpy.bincount(numpy.hstack(faces)) edges_per_vertex = numpy.bincount(numpy.hstack(afaces))
if edges_per_vertex.min() < 3: if edges_per_vertex.min() < 3:
raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges') raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges')
@ -59,8 +62,8 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t:
''' '''
In this case, we don't need to duplicate any vertices to make a 3-vertex-connected graph In this case, we don't need to duplicate any vertices to make a 3-vertex-connected graph
''' '''
neighbors = numpy.empty_like(vertices, dtype=int).fill(vertices.size) neighbors = numpy.full_like(vertices, vertices.size, dtype=int)
for face in faces: for face in afaces:
# 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
prev_vert = numpy.roll(face, 1) prev_vert = numpy.roll(face, 1)
next_vert = numpy.roll(face, -1) next_vert = numpy.roll(face, -1)
@ -162,7 +165,7 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t:
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) num_filled_rows = numpy.zeros(num_duplicates, dtype=int)
for face in faces: for face in afaces:
# assume a face can't use the same vertex twice # assume a face can't use the same vertex twice
v_inds = start[face] + num_filled_rows[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)
@ -196,18 +199,18 @@ def build_polyhedron(vertices: numpy.ndarray, faces: numpy.ndarray) -> poly_t:
dst_mask = numpy.empty(num_duplicates, dtype=bool) dst_mask = numpy.empty(num_duplicates, dtype=bool)
for v in range(num_vertices): for v in range(num_vertices):
s = start[v] ss = start[v]
e = s + edges_per_vertex[v] ee = ss + edges_per_vertex[v]
src_mask.fill(False) src_mask.fill(False)
src_mask[e:] = target_vert[e:] == v # find rows which reference us src_mask[ee:] = target_vert[ee:] == v # find rows which reference us
src_vert = v0s[src_mask] # figure out their original vertex numbers src_vert = v0s[src_mask] # figure out their original vertex numbers
if src_vert.size == 0: if src_vert.size == 0:
continue continue
dst_mask.fill(False) dst_mask.fill(False)
dst_mask[s:e] = target_vert[s:e] > v # mask out any references to verts >= current dst_mask[ss:ee] = target_vert[ss:ee] > v # mask out any references to verts >= current
dst_vert = target_vert[dst_mask] dst_vert = target_vert[dst_mask]
ma, mb = _get_maps(dst_vert, src_vert) ma, mb = _get_maps(dst_vert, src_vert)
@ -275,7 +278,7 @@ def boundary_from_poly(poly: poly_t) -> List[Dict[str, Any]]:
faces = find_faces(neighbors) faces = find_faces(neighbors)
num_components = owning_component.max() + 1 num_components = owning_component.max() + 1
components: List[List[numpy.ndarray]] = [[] for _ in range(num_components)] components: List[List[NDArray[numpy.int_]]] = [[] for _ in range(num_components)]
for face in faces: for face in faces:
component_ind = owning_component[face[0]] component_ind = owning_component[face[0]]
components[component_ind].append(face) components[component_ind].append(face)

View file

@ -1,5 +1,6 @@
from typing import Dict, Tuple from typing import Dict, Tuple
import numpy import numpy
from numpy.typing import NDArray
from . import poly_t, plane_t from . import poly_t, plane_t
from .util import find_faces from .util import find_faces
@ -31,7 +32,7 @@ def get_volume(poly: poly_t) -> float:
return get_moments(poly, 0)[0] return get_moments(poly, 0)[0]
def get_moments(poly: poly_t, order: int) -> numpy.ndarray: def get_moments(poly: poly_t, order: int) -> NDArray[numpy.float64]:
''' '''
Calculates the moments of a polyhedron, up to the specified polynomial order. Calculates the moments of a polyhedron, up to the specified polynomial order.

View file

@ -1,11 +1,12 @@
from typing import List from typing import List
import numpy import numpy
from numpy.linalg import norm from numpy.linalg import norm
from numpy.typing import ArrayLike
from . import poly_t, plane_t from . import poly_t, plane_t
def build_tetrahedron(vertices: numpy.ndarray) -> poly_t: def build_tetrahedron(vertices: ArrayLike) -> poly_t:
''' '''
Build a Schelegel-representation tetrahedron. Build a Schelegel-representation tetrahedron.
@ -26,7 +27,7 @@ def build_tetrahedron(vertices: numpy.ndarray) -> poly_t:
return poly return poly
def build_box(box_corners: numpy.ndarray) -> poly_t: def build_box(box_corners: ArrayLike) -> poly_t:
''' '''
Build a Schelegel-representation box. Build a Schelegel-representation box.
@ -48,6 +49,7 @@ def build_box(box_corners: numpy.ndarray) -> poly_t:
[6, 3, 4], [6, 3, 4],
] ]
box_corners = numpy.array(box_corners, copy=False)
vertices = [ vertices = [
[box_corners[0, 0], box_corners[0, 1], box_corners[0, 2]], [box_corners[0, 0], box_corners[0, 1], box_corners[0, 2]],
[box_corners[1, 0], box_corners[0, 1], box_corners[0, 2]], [box_corners[1, 0], box_corners[0, 1], box_corners[0, 2]],
@ -65,7 +67,7 @@ def build_box(box_corners: numpy.ndarray) -> poly_t:
} }
def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]: def planes_from_box(box_corners: ArrayLike) -> List[plane_t]:
''' '''
Construct a list of planes corresponding to the faces of a box. Construct a list of planes corresponding to the faces of a box.
@ -76,7 +78,7 @@ def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]:
Returns: Returns:
List of planes, facing inwards. List of planes, facing inwards.
''' '''
box_corners = numpy.array(box_corners) box_corners = numpy.array(box_corners, copy=False)
faces = [ faces = [
(( 0, 0, 1), -box_corners[0, 2]), (( 0, 0, 1), -box_corners[0, 2]),
(( 0, 0, -1), box_corners[1, 2]), (( 0, 0, -1), box_corners[1, 2]),
@ -89,7 +91,7 @@ def planes_from_box(box_corners: numpy.ndarray) -> List[plane_t]:
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) -> List[plane_t]: def planes_from_tetrahedron(vertices: ArrayLike) -> List[plane_t]:
''' '''
Construct a list of planes corresponding to the faces of a tetrahedron. Construct a list of planes corresponding to the faces of a tetrahedron.
@ -99,7 +101,7 @@ def planes_from_tetrahedron(vertices: numpy.ndarray) -> List[plane_t]:
Returns: Returns:
List of planes, facing inwards. List of planes, facing inwards.
''' '''
verts = numpy.array(vertices, dtype=float) verts = numpy.array(vertices, dtype=float, copy=False)
vset_inds = numpy.array(( vset_inds = numpy.array((
[3, 1, 2, 1], [3, 1, 2, 1],
[2, 0, 3, 2], [2, 0, 3, 2],

View file

@ -149,7 +149,7 @@ def _split(poly: poly_t, plane: plane_t, same_only: bool = False):
# figure out the index of each target edge using row-wise _get_map # figure out the index of each target edge using row-wise _get_map
dims = [num_start, num_start] dims = [num_start, num_start]
a1d = numpy.ravel_multi_index((rverts, lverts), dims) a1d = numpy.ravel_multi_index((rverts, lverts), dims)
b1d = numpy.ravel_multi_index(edge_walk_results, dims) b1d = numpy.ravel_multi_index(tuple(edge_walk_results), dims)
target_edge_inds = _get_map(a1d, b1d) target_edge_inds = _get_map(a1d, b1d)

View file

@ -1,6 +1,7 @@
from typing import Union from typing import Union
import numpy import numpy
from numpy import sin, cos from numpy import sin, cos
from numpy.typing import ArrayLike
from . import poly_t, plane_t from . import poly_t, plane_t
@ -26,7 +27,7 @@ def rotate(poly: poly_t, theta: float, axis: int) -> poly_t:
return poly return poly
def translate(poly: poly_t, shift: numpy.ndarray) -> poly_t: def translate(poly: poly_t, shift: ArrayLike) -> poly_t:
''' '''
Translate the polyhedron by a vector. Translate the polyhedron by a vector.
@ -42,7 +43,7 @@ def translate(poly: poly_t, shift: numpy.ndarray) -> poly_t:
return poly return poly
def scale(poly: poly_t, factor: Union[numpy.ndarray, float]) -> poly_t: def scale(poly: poly_t, factor: Union[ArrayLike, float]) -> poly_t:
''' '''
Scale the polyhedron. Scale the polyhedron.
Can scale by a single value, or scale each axis individually Can scale by a single value, or scale each axis individually
@ -59,7 +60,7 @@ def scale(poly: poly_t, factor: Union[numpy.ndarray, float]) -> poly_t:
return poly return poly
def affine(poly: poly_t, xform: numpy.ndarray) -> poly_t: def affine(poly: poly_t, xform: ArrayLike) -> poly_t:
''' '''
Perform arbitrary affine trasnformation on the polyhedron. Perform arbitrary affine trasnformation on the polyhedron.
@ -71,6 +72,7 @@ def affine(poly: poly_t, xform: numpy.ndarray) -> poly_t:
Transformed polyhedron. Transformed polyhedron.
Data is altered in-place but also returned for convenience. Data is altered in-place but also returned for convenience.
''' '''
xform = numpy.array(xform, copy=False)
mat4x3 = xform[:, :3] mat4x3 = xform[:, :3]
mat4x1 = xform[:, 3] mat4x1 = xform[:, 3]
vh = mat4x3 @ poly['vertices'].T + mat4x1 vh = mat4x3 @ poly['vertices'].T + mat4x1

View file

@ -1,9 +1,10 @@
from typing import Dict, Tuple, List from typing import Dict, Tuple, List
import numpy import numpy
from numpy.typing import ArrayLike, NDArray
plane_t = Tuple[numpy.ndarray, float] plane_t = Tuple[NDArray, float]
poly_t = Dict[str, numpy.ndarray] poly_t = Dict[str, NDArray]
def build_empty() -> poly_t: def build_empty() -> poly_t:
@ -19,7 +20,7 @@ def build_empty() -> poly_t:
} }
def find_components(neighbors: numpy.ndarray) -> numpy.ndarray: def find_components(neighbors: NDArray[numpy.int_]) -> NDArray[numpy.int_]:
''' '''
Given an adjacency list, flood-fill to find and label connected components. Given an adjacency list, flood-fill to find and label connected components.
@ -49,7 +50,7 @@ def find_components(neighbors: numpy.ndarray) -> numpy.ndarray:
return component - 1 return component - 1
def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]: def find_faces(neighbors: NDArray[numpy.int_]) -> List[NDArray[numpy.int_]]:
''' '''
Traverse the Schlegel diagram to find chordless cycles Traverse the Schlegel diagram to find chordless cycles
(i.e., faces of the polyhedron). Assumes 3-vertex-connected (i.e., faces of the polyhedron). Assumes 3-vertex-connected
@ -90,7 +91,7 @@ def find_faces(neighbors: numpy.ndarray) -> List[numpy.ndarray]:
return faces_set return faces_set
else: else:
# Alternative approach, less memory-intensive but slower # Alternative approach, less memory-intensive but slower
faces = [[v] for v in v_current] faces = numpy.array([[v] for v in v_current], dtype=int)
def add_edges(edge_id, v_nxt, k): def add_edges(edge_id, v_nxt, k):
for i, vn in zip(edge_id, v_nxt): for i, vn in zip(edge_id, v_nxt):
@ -201,7 +202,7 @@ def _searchsorted_rows(a, b):
return numpy.searchsorted(a1d, b1d) return numpy.searchsorted(a1d, b1d)
def check_poly(poly: poly_t, check_connectivity: bool = True): def check_poly(poly: poly_t, check_connectivity: bool = True) -> None:
''' '''
Verify that the polyhedron Verify that the polyhedron
- has no out-of-bounds neighbors - has no out-of-bounds neighbors
@ -269,7 +270,7 @@ def check_poly(poly: poly_t, check_connectivity: bool = True):
raise Exception('Vertex graph is not 3-vertex-connected') raise Exception('Vertex graph is not 3-vertex-connected')
def plot_brep(brep): def plot_brep(brep) -> None:
""" """
Plot a boundary representation Plot a boundary representation
""" """

View file

@ -1,5 +1,6 @@
from typing import Tuple, List from typing import Tuple, List
import numpy import numpy
from numpy.typing import ArrayLike, NDArray
from . import poly_t, plane_t from . import poly_t, plane_t
from .split import split, clip from .split import split, clip
@ -8,10 +9,10 @@ from .shapes import planes_from_box
def voxelize(poly: poly_t, def voxelize(poly: poly_t,
planes: List[numpy.ndarray], planes: List[ArrayLike],
include_outside: bool = False, include_outside: bool = False,
order: int = 0, order: int = 0,
) -> numpy.ndarray: ) -> NDArray[numpy.float64]:
''' '''
Voxelize a Schelegel-representation polyhedron on an arbitrary rectangular grid. Voxelize a Schelegel-representation polyhedron on an arbitrary rectangular grid.
@ -39,9 +40,9 @@ def voxelize(poly: poly_t,
correspond to portions of the polyhedron that protruded outside the outermost correspond to portions of the polyhedron that protruded outside the outermost
planes. N is `number_of_moments(order)`. planes. N is `number_of_moments(order)`.
''' '''
planes = [numpy.array(p) for p in planes] aplanes = [numpy.array(p, copy=False) for p in planes]
num_planes = numpy.array([e.size for e in planes], dtype=int) num_planes = numpy.array([e.size for e in aplanes], dtype=int)
if (num_planes < 2).any(): if (num_planes < 2).any():
# TODO raw exception # TODO raw exception
raise Exception(f'Need at least two planes per dimension. Got {num_planes} planes.') raise Exception(f'Need at least two planes per dimension. Got {num_planes} planes.')
@ -50,8 +51,8 @@ def voxelize(poly: poly_t,
grid_shape = num_planes + 1 grid_shape = num_planes + 1
if not include_outside: if not include_outside:
grid_shape = num_planes - 1 grid_shape = num_planes - 1
for face in planes_from_box([[p[0] for p in planes], for face in planes_from_box([[p[0] for p in aplanes],
[p[-1] for p in planes]]): [p[-1] for p in aplanes]]):
poly = clip(poly, face) poly = clip(poly, face)
grid = numpy.zeros((*grid_shape, number_of_moments(order)), dtype=float) grid = numpy.zeros((*grid_shape, number_of_moments(order)), dtype=float)
@ -59,7 +60,7 @@ def voxelize(poly: poly_t,
if poly['vertices'].shape[0] == 0: if poly['vertices'].shape[0] == 0:
return grid return grid
slices = numpy.array([(0, e.size) for e in planes], dtype=int) slices = numpy.array([(0, e.size) for e in aplanes], dtype=int)
stack = [(poly, slices)] stack = [(poly, slices)]
while stack: while stack:
poly, slices = stack.pop() poly, slices = stack.pop()
@ -80,7 +81,7 @@ def voxelize(poly: poly_t,
# Recursion case: split along longest side # Recursion case: split along longest side
axis = num_planes_remaining.argmax() axis = num_planes_remaining.argmax()
plane_ind = num_planes_remaining[axis] // 2 + slices[axis, 0] plane_ind = num_planes_remaining[axis] // 2 + slices[axis, 0]
plane_pos = planes[axis][plane_ind] plane_pos = aplanes[axis][plane_ind]
plane = (numpy.roll([-1, 0, 0], axis), plane_pos) plane = (numpy.roll([-1, 0, 0], axis), plane_pos)
poly_left, poly_right = split(poly, plane) poly_left, poly_right = split(poly, plane)