Skip to content
Open
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
13 changes: 10 additions & 3 deletions spatialmath/base/transforms3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -1566,19 +1566,22 @@ def trexp(S, theta=None, check=True):


@overload # pragma: no cover
def trnorm(R: SO3Array) -> SO3Array:
def trnorm(R: SO3Array, tol: float = 20) -> SO3Array:
...


def trnorm(T: SE3Array) -> SE3Array:
def trnorm(T: SE3Array, tol: float = 20) -> SE3Array:
r"""
Normalize an SO(3) or SE(3) matrix

:param T: SE(3) or SO(3) matrix
:type T: ndarray(4,4) or ndarray(3,3)
:param tol: tolerance in units of machine epsilon, an axis with a norm
below this is considered to be zero, defaults to 20
:type tol: float, optional
:return: normalized SE(3) or SO(3) matrix
:rtype: ndarray(4,4) or ndarray(3,3)
:raises ValueError: bad arguments
:raises ValueError: bad arguments or a zero-norm axis during normalization

- ``trnorm(R)`` is guaranteed to be a proper orthogonal matrix rotation
matrix (3x3) which is *close* to the input matrix R (3x3).
Expand Down Expand Up @@ -1633,6 +1636,10 @@ def trnorm(T: SE3Array) -> SE3Array:
o_norm = (o0 * o0 + o1 * o1 + o2 * o2) ** 0.5
a_norm = (a0 * a0 + a1 * a1 + a2 * a2) ** 0.5

# Retain the zero-norm checks previously performed by unitvec on each axis.
if not (n_norm > tol * _eps and o_norm > tol * _eps and a_norm > tol * _eps):
raise ValueError("zero norm vector")

is_hom = ishom(T)
R = np.empty((4, 4) if is_hom else (3, 3))
R[0, 0], R[1, 0], R[2, 0] = n0 / n_norm, n1 / n_norm, n2 / n_norm
Expand Down
85 changes: 85 additions & 0 deletions tests/test_trnorm_degenerate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import warnings
import numpy as np
import pytest
from numpy.testing import assert_allclose, assert_array_equal
from spatialmath import SO3, SE3
from spatialmath.base import trnorm, unitvec, rotx, roty, rotz


def previous_normalization(matrix):
o, a = matrix[:3, 1], matrix[:3, 2]
n = np.cross(o, a)
o = np.cross(a, n)
return np.stack((unitvec(n), unitvec(o), unitvec(a)), axis=1)


@pytest.mark.parametrize("homogeneous", [False, True])
@pytest.mark.parametrize(
"rotation",
[
np.zeros((3, 3)),
np.array([[1.0, 1, 1], [0, 0, 0], [0, 0, 0]]),
np.diag([1.0, 0, 1]),
np.diag([1.0, 1, 0]),
np.diag([1.0, 1e-16, 1]),
np.diag([1.0, 1, 1e-8]),
],
)
def test_degenerate_axes_raise_without_runtime_warning(rotation, homogeneous):
matrix = np.eye(4) if homogeneous else rotation.copy()
if homogeneous:
matrix[:3, :3] = rotation
matrix[:3, 3] = [1, -2, 3]
original = matrix.copy()
with pytest.raises(ValueError):
previous_normalization(matrix)
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
with pytest.raises(ValueError, match="zero norm vector"):
trnorm(matrix)
assert_array_equal(matrix, original)


@pytest.mark.parametrize("homogeneous", [False, True])
@pytest.mark.parametrize("angle", [0.0, 0.2, -1.3, np.pi])
def test_valid_drift_matches_previous_algorithm(angle, homogeneous):
rotation = rotx(angle) @ roty(0.4) @ rotz(-0.7)
rotation[:, 1] *= 1.0001
rotation[:, 2] += 1e-5 * rotation[:, 1]
matrix = np.eye(4) if homogeneous else rotation.copy()
if homogeneous:
matrix[:3, :3] = rotation
matrix[:3, 3] = [1, -2, 3]
original = matrix.copy()
actual = trnorm(matrix)
assert_allclose(actual[:3, :3], previous_normalization(matrix), atol=1e-15)
assert_allclose(actual[:3, :3].T @ actual[:3, :3], np.eye(3), atol=1e-15)
assert_allclose(np.linalg.det(actual[:3, :3]), 1, atol=1e-15)
if homogeneous:
assert_array_equal(actual[:3, 3], matrix[:3, 3])
assert_array_equal(actual[3], [0, 0, 0, 1])
assert_array_equal(matrix, original)


@pytest.mark.parametrize("cls, size", [(SO3, 3), (SE3, 4)])
def test_pose_norm_propagates_failure(cls, size):
matrix = np.eye(size)
matrix[:3, :3] = 0
pose = cls(matrix, check=False)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
with pytest.raises(ValueError):
pose.norm()


def test_tolerance_parameter():
matrix = np.diag([1.0, 1e-15, 1])
# the default tolerance of 20 * eps treats this axis as zero
with pytest.raises(ValueError, match="zero norm vector"):
trnorm(matrix)
# a smaller tolerance accepts it
assert_allclose(trnorm(matrix, tol=1), np.eye(3), atol=1e-15)
# a larger tolerance rejects a matrix accepted by default
with pytest.raises(ValueError, match="zero norm vector"):
trnorm(np.diag([1.0, 1e-12, 1]), tol=1e6)
assert_allclose(trnorm(np.diag([1.0, 1e-12, 1])), np.eye(3), atol=1e-15)