Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/pyrecest/utils/point_set_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,31 @@ def apply(self, points) -> Any:
raise ValueError("Point dimension does not match transform dimension.")
return (self.matrix @ points_array.T).T + self.offset

def inverse(self) -> "AffineTransform":
"""Return the inverse affine transform.

For a transform ``y = A x + b``, the inverse is
``x = A^{-1} y - A^{-1} b``.
"""
inverse_matrix = linalg.inv(self.matrix)
inverse_offset = -(inverse_matrix @ self.offset)
return AffineTransform(inverse_matrix, inverse_offset)

def compose(self, other: "AffineTransform") -> "AffineTransform":
"""Return the composition of this transform with ``other``.

The returned transform is equivalent to applying ``other`` first and
this transform second, i.e. ``self.apply(other.apply(points))``.
"""
if not isinstance(other, AffineTransform):
raise TypeError("other must be an AffineTransform.")
if other.dim != self.dim:
raise ValueError("Transform dimensions must match.")
return AffineTransform(
self.matrix @ other.matrix,
self.matrix @ other.offset + self.offset,
)

def homogeneous_matrix(self) -> Any:
"""Return the homogeneous representation of the affine transform."""
transform = eye(self.dim + 1)
Expand Down
50 changes: 50 additions & 0 deletions tests/test_affine_transform_algebra.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import unittest

import numpy.testing as npt

from pyrecest.backend import array
from pyrecest.utils.point_set_registration import AffineTransform


class TestAffineTransformAlgebra(unittest.TestCase):
def test_inverse_round_trips_points(self):
points = array([[0.0, 0.0], [1.0, -2.0], [3.0, 4.0]])
transform = AffineTransform(
array([[1.2, 0.3], [-0.4, 0.8]]),
array([2.0, -1.5]),
)

recovered = transform.inverse().apply(transform.apply(points))

npt.assert_allclose(recovered, points, atol=1e-10)

def test_compose_matches_sequential_application(self):
points = array([[0.0, 0.0], [1.0, -2.0], [3.0, 4.0]])
first = AffineTransform(
array([[0.8, -0.1], [0.2, 1.1]]),
array([1.0, 0.5]),
)
second = AffineTransform(
array([[1.3, 0.4], [-0.2, 0.7]]),
array([-2.0, 1.5]),
)

composed = second.compose(first)

npt.assert_allclose(
composed.apply(points),
second.apply(first.apply(points)),
atol=1e-10,
)

def test_compose_rejects_dimension_mismatch(self):
with self.assertRaises(ValueError):
AffineTransform.identity(2).compose(AffineTransform.identity(3))

def test_compose_rejects_non_transform(self):
with self.assertRaises(TypeError):
AffineTransform.identity(2).compose(object())


if __name__ == "__main__":
unittest.main()
Loading