[transform] improve handling of integer coordinates and general input handling

This commit is contained in:
Jan Petykiewicz 2026-04-01 22:02:52 -07:00
commit 30b96107f4
2 changed files with 134 additions and 8 deletions

View file

@ -33,6 +33,18 @@ def test_rotate_z_quarter_turn() -> None:
assert_allclose(rotated['vertices'], [[0.0, 1.0, 0.0]], atol=1e-12)
def test_rotate_promotes_integer_vertices_to_float() -> None:
poly = {
'vertices': numpy.array([[1, 0, 0]], dtype=int),
'neighbors': numpy.empty((0, 3), dtype=int),
}
rotated = adze.transform.rotate(poly, numpy.pi / 4, axis=2)
assert numpy.issubdtype(rotated['vertices'].dtype, numpy.floating)
assert_allclose(rotated['vertices'], [[numpy.sqrt(0.5), numpy.sqrt(0.5), 0.0]], atol=1e-12)
@pytest.mark.parametrize('axis', [-1, 3, 4])
def test_rotate_rejects_invalid_axis(axis: int) -> None:
poly = {
@ -100,3 +112,67 @@ def test_affine_translation_applies_to_multiple_vertices() -> None:
transformed = adze.transform.affine(poly, xform)
assert_allclose(transformed['vertices'], [[2.0, 2.0, 3.0], [3.0, 3.0, 3.0]])
def test_affine_promotes_integer_vertices_to_float() -> None:
poly = {
'vertices': numpy.array([[1, 1, 1]], dtype=int),
'neighbors': numpy.empty((0, 3), dtype=int),
}
xform = numpy.array([
[1.0, 0.0, 0.0, 0.5],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
transformed = adze.transform.affine(poly, xform)
assert numpy.issubdtype(transformed['vertices'].dtype, numpy.floating)
assert_allclose(transformed['vertices'], [[1.5, 1.0, 1.0]])
def test_translate_promotes_integer_vertices_to_float() -> None:
poly = {
'vertices': numpy.array([[1, 0, 0]], dtype=int),
'neighbors': numpy.empty((0, 3), dtype=int),
}
transformed = adze.transform.translate(poly, [0.5, 1.0, 0.0])
assert numpy.issubdtype(transformed['vertices'].dtype, numpy.floating)
assert_allclose(transformed['vertices'], [[1.5, 1.0, 0.0]])
def test_scale_promotes_integer_vertices_to_float() -> None:
poly = {
'vertices': numpy.array([[1, 1, 1]], dtype=int),
'neighbors': numpy.empty((0, 3), dtype=int),
}
transformed = adze.transform.scale(poly, 0.5)
assert numpy.issubdtype(transformed['vertices'].dtype, numpy.floating)
assert_allclose(transformed['vertices'], [[0.5, 0.5, 0.5]])
@pytest.mark.parametrize('shift', [[1.0, 2.0], [1.0, 2.0, 3.0, 4.0]])
def test_translate_rejects_invalid_shift_shape(shift: list[float]) -> None:
poly = {
'vertices': numpy.array([[1.0, 0.0, 0.0]]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
with pytest.raises(adze.AdzeError, match='Shift must have shape'):
adze.transform.translate(poly, shift)
@pytest.mark.parametrize('factor', [[1.0, 2.0], [1.0, 2.0, 3.0, 4.0]])
def test_scale_rejects_invalid_factor_shape(factor: list[float]) -> None:
poly = {
'vertices': numpy.array([[1.0, 0.0, 0.0]]),
'neighbors': numpy.empty((0, 3), dtype=int),
}
with pytest.raises(adze.AdzeError, match='Scale factor must be a scalar or have shape'):
adze.transform.scale(poly, factor)

View file

@ -6,6 +6,51 @@ from . import poly_t
from .util import AdzeError
def _normalize_vertices(poly: poly_t) -> numpy.ndarray:
vertices = numpy.asarray(poly['vertices'])
if vertices.ndim != 2 or vertices.shape[1] != 3:
raise AdzeError(f"Vertices must have shape (N, 3). Got {vertices.shape}")
if not numpy.isfinite(vertices).all():
raise AdzeError('Vertices must contain only finite values')
if not numpy.issubdtype(vertices.dtype, numpy.floating):
vertices = vertices.astype(float)
poly['vertices'] = vertices
return vertices
def _normalize_theta(theta: float) -> float:
try:
angle = float(theta)
except (TypeError, ValueError) as exc:
raise AdzeError('Rotation angle must be a scalar') from exc
if not numpy.isfinite(angle):
raise AdzeError('Rotation angle must be finite')
return angle
def _normalize_vector(value: ArrayLike, name: str) -> numpy.ndarray:
vector = numpy.asarray(value, dtype=float)
if vector.shape != (3,):
raise AdzeError(f'{name} must have shape (3,). Got {vector.shape}')
if not numpy.isfinite(vector).all():
raise AdzeError(f'{name} must contain only finite values')
return vector
def _normalize_scale_factor(factor: ArrayLike | float) -> float | numpy.ndarray:
afactor = numpy.asarray(factor, dtype=float)
if afactor.shape == ():
scalar = float(afactor)
if not numpy.isfinite(scalar):
raise AdzeError('Scale factor must be finite')
return scalar
if afactor.shape != (3,):
raise AdzeError(f'Scale factor must be a scalar or have shape (3,). Got {afactor.shape}')
if not numpy.isfinite(afactor).all():
raise AdzeError('Scale factor must contain only finite values')
return afactor
def rotate(poly: poly_t, theta: float, axis: int) -> poly_t:
"""
Rotate the polyhedron around an axis.
@ -22,11 +67,13 @@ def rotate(poly: poly_t, theta: float, axis: int) -> poly_t:
if axis not in (0, 1, 2):
raise AdzeError(f'Axis must be 0, 1, or 2. Got {axis}')
vertices = _normalize_vertices(poly)
theta = _normalize_theta(theta)
s, c = sin(theta), cos(theta)
v0 = poly['vertices'][:, axis - 2].copy()
v1 = poly['vertices'][:, axis - 1]
poly['vertices'][:, axis - 2] = c * v0 - s * v1
poly['vertices'][:, axis - 1] = s * v0 + c * v1
v0 = vertices[:, axis - 2].copy()
v1 = vertices[:, axis - 1]
vertices[:, axis - 2] = c * v0 - s * v1
vertices[:, axis - 1] = s * v0 + c * v1
return poly
@ -42,7 +89,8 @@ def translate(poly: poly_t, shift: ArrayLike) -> poly_t:
Translated polyhedron.
Data is altered in-place but also returned for convenience.
"""
poly['vertices'] += shift
vertices = _normalize_vertices(poly)
vertices += _normalize_vector(shift, 'Shift')
return poly
@ -59,7 +107,8 @@ def scale(poly: poly_t, factor: ArrayLike | float) -> poly_t:
Scaled polyhedron.
Data is altered in-place but also returned for convenience.
"""
poly['vertices'] *= factor
vertices = _normalize_vertices(poly)
vertices *= _normalize_scale_factor(factor)
return poly
@ -77,6 +126,7 @@ def affine(poly: poly_t, xform: ArrayLike) -> poly_t:
Transformed polyhedron.
Data is altered in-place but also returned for convenience.
"""
vertices = _normalize_vertices(poly)
xform = numpy.array(xform, copy=False)
if xform.shape != (4, 4):
raise AdzeError(f'Affine transform matrix must have shape (4, 4). Got {xform.shape}')
@ -85,8 +135,8 @@ def affine(poly: poly_t, xform: ArrayLike) -> poly_t:
mat4x3 = xform[:, :3]
mat4x1 = xform[:, 3:4]
vh = mat4x3 @ poly['vertices'].T + mat4x1
vh = mat4x3 @ vertices.T + mat4x1
if numpy.any(vh[3, :] == 0):
raise AdzeError('Affine transform produced points with zero homogeneous coordinate')
poly['vertices'][:] = (vh[:3, :] / vh[3, :]).T
vertices[:] = (vh[:3, :] / vh[3, :]).T
return poly