# Copyright 2025-2026 Thousand Brains Project
# Copyright 2023-2024 Numenta Inc.
#
# Copyright may exist in Contributors' modifications
# and/or contributions to the work.
#
# Use of this source code is governed by the MIT
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
from __future__ import annotations
import logging
import sys
from typing import cast
import numpy as np
import numpy.typing as npt
from numpy.typing import ArrayLike
from tbp.monty.geometry import GazeDirection, Rotation, SurfacePoseVectors
from tbp.monty.math import DEFAULT_TOLERANCE
logger = logging.getLogger(__name__)
[docs]
class TangentFrame:
"""Orthonormal tangent frame on a surface.
Maintains a right-handed (u, v, n) basis where n is the surface normal,
u is the horizontal tangent direction, and v is the vertical tangent
direction. As the sensor moves across a curved surface, `transport()`
rotates the tangent frame to match the new normal.
See:
https://en.wikipedia.org/wiki/Parallel_transport
Args:
surface_normal: Unit surface normal at the initial point.
"""
[docs]
def __init__(self, surface_normal: np.ndarray) -> None:
"""Initialize an orthonormal (u, v) basis in the tangent plane of a surface.
A surface normal defines a tangent plane but not a unique basis. We choose
`basis_u` as the cross product of `some_axis` and the `surface_normal`, giving
a horizontal tangent direction. `basis_v` follows as the cross product of
the `surface_normal` and `basis_u`.
If the `surface_normal` is nearly parallel to some_axis (|cos(theta)| > 0.95),
we fall back to using [0, 0, 1] to avoid a degenerate cross product.
Args:
surface_normal: Unit surface normal at the initial point.
"""
# some_axis is arbitrarily chosen
some_axis = np.array([0.0, 1.0, 0.0], dtype=np.float32)
self._normal = normalize(surface_normal)
if is_parallel(some_axis, self._normal):
some_axis = np.array([0.0, 0.0, 1.0], dtype=np.float32)
self._u = normalize(np.cross(some_axis, self._normal))
self._v = normalize(np.cross(self._normal, self._u))
@property
def basis_u(self) -> np.ndarray:
"""Horizontal tangent basis vector."""
return self._u
@property
def basis_v(self) -> np.ndarray:
"""Vertical tangent basis vector."""
return self._v
@property
def normal(self) -> np.ndarray:
"""Surface normal associated with this tangent frame."""
return self._normal
[docs]
def transport(self, new_normal: np.ndarray) -> None:
"""Parallel-transport the frame to a new surface normal.
As the sensor moves along a curved surface, the tangent plane
rotates with the curvature (e.g. around a cylinder). Parallel
transport transforms the basis (u, v) by exactly the rotation needed
to stay in the new tangent plane. This is analogous to "unrolling"
the curved surface.
Args:
new_normal: Unit surface normal at the new point.
"""
old_normal = self._normal
if not is_parallel(old_normal, new_normal):
cos_angle = np.clip(np.dot(old_normal, new_normal), -1.0, 1.0)
rotation_axis = normalize(np.cross(old_normal, new_normal))
rotation = Rotation.from_rotvec(rotation_axis * np.arccos(cos_angle))
self._u = rotation.apply(self._u)
# Re-orthonormalize to prevent cumulative floating point error
self._u = normalize(project_onto_tangent_plane(self._u, new_normal))
self._v = np.cross(new_normal, self._u)
self._normal = new_normal.copy()
[docs]
def normalize(v: ArrayLike, epsilon: float = DEFAULT_TOLERANCE) -> np.ndarray:
"""Normalize a vector to unit length.
Args:
v: Input vector to normalize.
epsilon: Small epsilon value below which the vector is considered zero.
Returns:
Unit vector in the direction of v in v's dtype.
Raises:
ValueError: If the vector has near-zero length (norm < epsilon).
"""
v = np.asarray(v)
n = np.linalg.norm(v)
if n < epsilon:
raise ValueError(f"Cannot normalize near-zero vector (norm={n:.2e})")
return v / n
[docs]
def project_onto_tangent_plane(v: ArrayLike, n: ArrayLike) -> np.ndarray:
"""Project a vector onto the tangent plane perpendicular to a normal.
Removes the component of v that is parallel to n, leaving only the
component that lies in the plane perpendicular to n.
Args:
v: Vector to project.
n: Normal vector defining the tangent plane. Normalized internally.
Returns:
The projection of v onto the plane perpendicular to n.
"""
n = normalize(n)
return v - np.dot(v, n) * n
[docs]
def is_parallel(
v1: ArrayLike, v2: ArrayLike, tolerance: float = DEFAULT_TOLERANCE
) -> bool:
"""True when v1 and v2 point in the same or opposite direction.
Assumes unit-length inputs. The metric 1 - |cos(theta)| is compared
against tolerance.
Args:
v1: First unit vector.
v2: Second unit vector.
tolerance: Maximum value of 1 - |cos(theta)| to consider parallel.
Returns:
True if v1 and v2 are parallel (same or opposite direction).
"""
v1 = np.asarray(v1)
v2 = np.asarray(v2)
return 1.0 - abs(np.dot(v1, v2)) < tolerance
[docs]
def rotations_to_quats(rotations, invert=False):
# We get euler rotations from feature LM
if rotations.ndim == 2:
quats = euler_to_quats(rotations, invert=invert)
# We get rotation matrices from evidence LM
elif rotations.ndim == 3:
quats = rot_mats_to_quats(rotations, invert=invert)
else:
raise ValueError("Invalid rotation matrix shape")
return quats
[docs]
def rot_mats_to_quats(rot_mats, invert=False):
"""Convert rotation matrices to quaternions.
Args:
rot_mats: Rotation matrices
invert: Whether to invert the rotation. Defaults to False.
Returns:
Quaternions
"""
quats = []
for rotation_matrix in rot_mats:
rotation = Rotation.from_matrix(rotation_matrix)
if invert:
rotation = rotation.inv()
quats.append(rotation.as_quat())
return quats
[docs]
def euler_to_quats(euler_rots, invert=False):
"""Convert Euler rotations to quaternions.
Args:
euler_rots: Euler rotations
invert: Whether to invert the rotation. Defaults to False.
Returns:
Quaternions
"""
quats = []
for euler_rot in euler_rots:
rot_mat = Rotation.from_euler("xyz", euler_rot, degrees=True)
if invert:
rot_mat = rot_mat.inv()
quats.append(rot_mat.as_quat())
return quats
[docs]
def get_angle(vec1, vec2):
"""Get angle between two vectors.
NOTE: For efficiency reasons we assume vec1 and vec2 are already
normalized (which is the case for surface normals and curvature
directions).
Args:
vec1: Vector 1
vec2: Vector 2
Returns:
angle in radians
"""
dot_product = np.dot(vec1, vec2)
return np.arccos(np.clip(dot_product, -1, 1))
[docs]
def get_angle_beefed_up(v1, v2):
"""Return the angle in radians between vectors 'v1' and 'v2'.
If one of the vectors is undefined, return an arbitrarily large distance.
If one of the vectors is the zero vector, return an arbitrarily large distance.
Also enforces that vectors are unit vectors, which makes it less efficient than
the standard get_angle.
>>> angle_between_vecs((1, 0, 0), (0, 1, 0))
1.5707963267948966
>>> angle_between_vecs((1, 0, 0), (1, 0, 0))
0.0
>>> angle_between_vecs((1, 0, 0), (-1, 0, 0))
3.141592653589793
"""
if v1 is None or v2 is None:
return np.inf
if np.linalg.norm(v1) < DEFAULT_TOLERANCE or np.linalg.norm(v2) < DEFAULT_TOLERANCE:
return np.inf
v1_u = normalize(v1)
v2_u = normalize(v2)
result = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
if np.isnan(result):
result = np.inf
assert result >= 0, f"Angle between is negative : {result}"
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
[docs]
def get_angles_for_all_hypotheses(hyp_f, query_f):
"""Get all angles for hypotheses and their neighbors at once.
hyp_f shape = (num_hyp, num_nn, 3)
query_f shape = (num_hyp, 3)
for each hypothesis we want to get num_nn angles.
Return shape = (num_hyp, num_nn)
Args:
hyp_f: Hypotheses features three pose vectors
query_f: Query features three pose vectors
Returns:
Angles between hypotheses and query pose vectors
"""
dot_product = np.einsum("ijk,ik->ij", hyp_f, query_f)
return np.arccos(np.clip(dot_product, -1, 1))
[docs]
def get_angle_between(
v1: npt.NDArray[np.float64], v2: npt.NDArray[np.float64]
) -> float:
"""Get the angle between two 3D vectors.
Uses the atan2 formulation. Unlike ``get_angle``, this does
not assume the inputs are unit vectors: the vectors' magnitudes
cancel in the ratio, so the result is correct for vectors of any
length.
A zero-length input yields 0.0, and there is no None handling.
See get_angle_beefed_up for the guarded variant.
Args:
v1: Vector 1 (3D)
v2: Vector 2 (3D)
Returns:
angle in radians
TODO: Consolidate angle helpers around the NumPy atan2 supporting
(..., 3) inputs with broadcasting and reductions over axis=-1. In
the near term, get_angle_between can replace get_angle without
further changes. This function can merge with get_angle_beefed_up
by adding handling for zero-length vectors and None. For
get_angles_for_all_hypotheses, add support for broadcasting, e.g.
get_angle_between(hyp_f, query_f[:, None, :]) and adding axis=-1
for reduction. Note that when broadcasting is added, it might
make sense to make a separate get_angles_beetween function to support
typing.
"""
return float(np.arctan2(np.linalg.norm(np.cross(v1, v2)), np.dot(v1, v2)))
[docs]
def check_orthonormal(matrix):
is_orthogonal = np.mean(np.abs(np.linalg.inv(matrix) - matrix.T)) < 0.01
if not is_orthogonal:
logger.debug(
"not orthogonal. Error: "
f"{np.mean(np.abs(np.linalg.inv(matrix) - matrix.T))}"
)
is_normal = np.mean(np.abs(np.linalg.norm(matrix, axis=1) - [1, 1, 1])) < 0.01
if not is_normal:
logger.debug(
"not normal. Error: "
f"{np.mean(np.abs(np.linalg.norm(matrix, axis=1) - [1, 1, 1]))}"
)
return is_orthogonal and is_normal
[docs]
def align_orthonormal_vectors(m1, m2, as_scipy=True):
"""Calculate the rotation that aligns two sets of orthonormal vectors.
Args:
m1: First set of orthonormal vectors.
m2: Second set of orthonormal vectors to align with.
as_scipy: Whether to return a scipy rotation object or a rotation matrix.
Defaults to True.
Returns:
If `as_scipy` is True, a tuple `(Rotation, float)` containing the
alignment rotation and the corresponding alignment error.
Otherwise returns `(np.ndarray, None)`, where the array is the rotation
matrix aligning the vectors.
"""
# assert check_orthonormal(m1), "m1 is not orthonormal"
# assert check_orthonormal(m2), "m2 is not orthonormal"
# to get rotation matrix between m1 and m2 calculate
# m1*m2.T (can do m2.T instead of m2.inv because vectors
# are orthogonal). Since vectors here are rows instead
# of columns we apply T to m1 instead of m2.
rot_mat = np.matmul(m1.T, m2)
if as_scipy:
rotation = Rotation.from_matrix(rot_mat)
# Check that recovered rotation actually works
# Error will be there if orthonormal vectors are mirrored
# (right hand vs, left hand side). This is just left in here for
# backward compatibility. The Evidence LM doesn't use the error anymore
# and mirrored vectors will be corrected by the sensor module.
error = np.mean(np.abs(rotation.inv().apply(m1) - m2))
return rotation, error
return rot_mat, None
[docs]
def align_multiple_orthonormal_vectors(ms1, ms2, as_scipy=True):
"""Calculate rotations between multiple orthonormal vector sets.
Args:
ms1: Multiple orthonormal vector sets with shape = (N, 3, 3).
ms2: Orthonormal vectors to align with, shape = (3, 3).
as_scipy: Whether to return a list of N scipy.Rotation objects or
a np.array of rotation matrices (N, 3, 3).
Returns:
List of N Rotations that align ms2 with each element in ms1.
"""
transpose_mts1 = np.transpose(ms1, axes=[0, 2, 1])
rot_mats = np.matmul(transpose_mts1, ms2)
if as_scipy:
all_rotations = []
for rot_mat in rot_mats:
all_rotations.append(Rotation.from_matrix(rot_mat))
return all_rotations
return rot_mats
[docs]
def get_right_hand_angle(v1, v2, surface_normal):
# some numpy bug (https://github.com/microsoft/pylance-release/issues/3277)
# cp = lambda v1, v2: np.cross(v1, v2)
# a = np.dot(cp(v1, v2), surface_normal)
a = np.dot(np.cross(v1, v2), surface_normal)
b = np.dot(v1, v2)
return np.arctan2(a, b)
[docs]
def non_singular_mat(a):
"""Return True if a matrix is non-singular, i.e. can be inverted.
Uses the condition number of the matrix, which will approach
a very large value, given by (1 / sys.float_info.epsilon)
(where epsilon is the smallest possible floating-point difference)
"""
return np.linalg.cond(a) < 1 / sys.float_info.epsilon
[docs]
def get_more_directions_in_plane(
vecs: npt.NDArray[np.float64], n_poses: int
) -> list[npt.NDArray[np.float64]]:
"""Get a list of unit vectors, evenly spaced in a plane orthogonal to vecs[0].
This is used to sample possible poses orthogonal to the surface normal when the
curvature directions are undefined (like on a flat surface).
Args:
vecs: Vector to get more directions in plane for
n_poses: Number of poses to get
Returns:
List of vectors evenly spaced in a plane orthogonal to vecs[0]
"""
new_vecs = [vecs]
angles: npt.NDArray[np.float64] = np.linspace(0, 2 * np.pi, n_poses, endpoint=False)
for angle in angles:
new_vec = np.cos(angle) * vecs[1] + np.sin(angle) * vecs[2]
new_vec2 = np.cross(vecs[0], new_vec)
new_vecs.append(np.asarray([vecs[0], new_vec, new_vec2]))
return new_vecs[1:]
[docs]
def get_unique_rotations(poses, similarity_th, get_reverse_r=True):
"""Get unique scipy.Rotations out of a list, given a similarity threshold.
Args:
poses: List of poses to get unique rotations from
similarity_th: Similarity threshold
get_reverse_r: Whether to get the reverse rotation. Defaults to True.
Returns:
euler_poses: Unique euler poses
r_poses: Unique rotations corresponding to euler_poses
"""
unique_poses = []
euler_poses = []
r_poses = []
for path_poses in poses:
for pose in path_poses:
if pose_is_new(unique_poses, pose, similarity_th):
unique_poses.append(pose)
if get_reverse_r:
r_pose = pose.inv()
euler_pose = pose.inv().as_euler("xyz", degrees=True)
euler_pose = np.round(euler_pose, 3) % 360
else:
r_pose = pose
euler_pose = pose.as_euler("xyz", degrees=True)
euler_pose = np.round(euler_pose, 3) % 360
r_poses.append(r_pose)
euler_poses.append(euler_pose)
return euler_poses, r_poses
[docs]
def pose_is_new(all_poses, new_pose, similarity_th) -> bool:
"""Check if a pose is different from a list of poses.
Use the magnitude of the difference between quaternions as a measure for
similarity and check that it is below pose_similarity_threshold.
Returns:
True if the pose is new, False otherwise
"""
for pose in all_poses:
d = new_pose * pose.inv()
if d.magnitude() < similarity_th:
return False
return True
[docs]
def batch_rotate_pose_vectors(
pose_vectors: SurfacePoseVectors, rotations: npt.NDArray[np.float64]
) -> npt.NDArray[np.float64]:
"""Rotate pose vectors given multiple rotation matrices in (N, 3, 3) numpy array.
Args:
pose_vectors: Pose vectors to rotate.
rotations: (N, 3, 3) numpy array of rotation matrices.
Returns:
(N, 3, 3) of original pose vectors rotated by every rotation.
Raises:
TypeError: If the pose vectors represent GazeDirection.
"""
# TODO: Replace with match statement
if isinstance(pose_vectors, GazeDirection):
raise TypeError("GazeDirection type is not supported for rotation.")
# Transpose pose vectors so each vector is a column (otherwise .dot matmul
# produces slightly different results)
rotated_pv = rotations.dot(pose_vectors.value.T)
# Transpose last two axies so each pose vector is a row again
rotated_pv = rotated_pv.transpose((0, 2, 1))
return cast("npt.NDArray[np.float64]", rotated_pv)
[docs]
def rotate_pose_vectors(
pose_vectors: SurfacePoseVectors, rotation: Rotation
) -> SurfacePoseVectors:
"""Rotate pose vectors given a Rotation object.
Args:
pose_vectors: Pose vectors to rotate.
rotation: Rotation matrix to rotate pose vectors by.
Returns:
Original features but with the pose_vectors rotated.
Raises:
TypeError: If the pose vectors represent GazeDirection.
"""
# TODO: Replace with match statement
if isinstance(pose_vectors, GazeDirection):
raise TypeError("GazeDirection type is not supported for rotation.")
return SurfacePoseVectors(rotation.apply(pose_vectors.value))
[docs]
def rotate_multiple_pose_vectors(
pose_vecs: npt.NDArray[np.float64], ref_frame_rot: Rotation
) -> npt.NDArray[np.float64]:
"""Rotate surface normal and curve dirs given a rotation matrix.
Args:
pose_vecs: Pose vectors to rotate. Shape (N, 9)
ref_frame_rot: rotation to rotate pose vectors with.
Returns:
Rotated pose vectors with shape (N, 9)
"""
num_pose_vecs = pose_vecs.shape[0]
assert pose_vecs.shape[-1] == 9, "pose_vectors in features should be flattened."
# Reshape to (num_pose_vecs * 3, 3) to be able to rotate all vectors at once
pose_vecs = pose_vecs.reshape((-1, 3))
# rotate all vectors by ref_frame_rot
rotated_pose_vecs = ref_frame_rot.apply(pose_vecs)
# shape back to original shape (num_pose_vecs, 9)
return rotated_pose_vecs.reshape((num_pose_vecs, 9))