Techniquecore
Pose compounding operators
Also called Smith-Self-Cheeseman compounding, head-to-tail composition.
The oplus and ominus operators that compose and invert uncertain relative poses and carry their covariances to first order.
The pose compounding operators of Smith, Self and Cheeseman are two operations on relative poses with uncertainty: chains two relative poses head to tail, and reverses one. Each operator returns a mean pose and a covariance matrix, which it gets by a first-order Taylor expansion of the exact pose formula, so the covariance is a linearization and not the exact spread. With these two operators and the rule for correlated inputs, every relation between frames in a network of uncertain poses can be computed step by step. They are the basis of stochastic maps, EKF SLAM and the edges of a pose graph.
In plain words
A robot knows where it is only roughly. It drives a short way, and it knows that step only roughly too. To find where it is now, you add the step to the old place, but the step is measured in the robot's own direction, so you must first turn it by the robot's heading. The doubt in the new place comes from the doubt in the old place and the doubt in the step. A doubt in the heading swings the step to the side, so it adds doubt across the path, more for a longer step. The operators do this sum and this turn, and they spread the doubts with straight-line rules. The straight-line rules are good for small doubts and wrong for large heading doubts.
When it applies
- Poses are planar, , the pose of frame in frame , or spatial with a fixed parametrization (Appendix A of Smith, Self and Cheeseman uses Euler angles and roll-pitch-yaw angles).
- Each uncertain pose is summarized by a mean and a covariance, and the covariance of is written in the axes of frame .
- The uncertainty is small compared with the curvature of the pose formula, mainly the heading standard deviation times the distance that it swings. Then the first-order answer is close, as the examples show.
- The cross-covariances between inputs are known. If two poses share an error source, the cross term must be carried.
The template
Let and . The compound is the product of the two planar transforms:
Its Jacobian , written with the result as in the paper, is
COMPOUND(x1, C1, x2, C2, C12) ▷ x1 = x_ij, x2 = x_jk, C12 = cov(x1, x2)- 1
(x1, y1, φ1) ← x1 ; c ← cos φ1 ; s ← sin φ1 - 2
x3 ← (x1 + c x2 - s y2, y1 + s x2 + c y2, wrap(φ1 + φ2)) - 3
J1 ← [[1, 0, -(y3 - y1)], [0, 1, x3 - x1], [0, 0, 1]] - 4
J2 ← [[c, -s, 0], [s, c, 0], [0, 0, 1]] - 5
C3 ← J1 C1 J1ᵀ + J2 C2 J2ᵀ + J1 C12 J2ᵀ + J2 C12ᵀ J1ᵀ - 6
return (x3, C3)
Line L5 is , the first-order covariance of a function of a random vector, the multivariate delta method. For independent inputs, , and only the first two terms remain.
The inverse is the pose of frame in frame :
INVERT(x1, C1)I1 (x, y, φ) ← x1 ; c ← cos φ ; s ← sin φI2 x' ← (-c x - s y, s x - c y, wrap(-φ))I3 J ← [[-c, -s, y'], [s, -c, -x'], [0, 0, -1]]I4 return (x', J C1 Jᵀ)
In the words of the paper, the uncertainty is not inverted, but expressed from the opposite point of view.
Composite relations. Two poses that share their head frame give (head to head). Two poses that share their tail frame give (tail to tail), with the Jacobian . Applying the operators step by step along a chain gives the same answer as the first-order expansion of the whole chain at once, because the chain rule of derivatives composes the Jacobians in the same way.
Cost. Each operator is a fixed number of operations on matrices, so a chain of relative poses costs time and extra space in the real RAM, if the inputs are independent.
Classic examples
A hand example. Let and , both with covariance , that is 0.1 m in position and 0.05 rad in heading, independent.
- Mean: .
- Jacobians: , since and , and is the quarter-turn rotation.
- , and because is the same in all directions of the plane.
- Sum: .
The heading error of swings the 1 m step, which points along in frame , so it adds variance along and a negative correlation between and . A Monte Carlo run with 100000 samples (seed 5) gives the sample mean and the sample covariance , within the sampling error of the first-order answer.
The inverse. : the frame origin is 1 m behind frame and 2 m to its left. With the same , , and the covariance is .
Order matters. , not . The operator is associative but not commutative, like the matrix product it comes from.
Where the linearization fails. Start at with heading variance (0.5 rad) and drive with no error. The true end point is with , on an arc. Its exact moments are , and . The first-order answer is the mean , and . It misses the mean by more than 1 m, and its ellipse is a flat bar where the samples form a curved banana. Uncertainty on Lie groups fixes much of this by putting the Gaussian in exponential coordinates.
Dead reckoning. A robot compounds its odometry steps, , as in dead reckoning and the odometry motion model. The steps are independent, so each step adds and swings the old heading variance through , and the position covariance grows without bound.
Landmarks and loop closures. In a stochastic map or EKF SLAM, a landmark seen from the robot is placed by , with the cross-covariance between robot and landmark kept in the joint state. The relative pose of two robot poses that are both in the map is the tail-to-tail relation , which is the prediction of a pose graph edge.
Variations
- Six degrees of freedom. Appendix A of the paper gives the same operators for poses with Euler angles or roll-pitch-yaw angles. These angles have a singular set (gimbal lock), where the Jacobians blow up.
- Lie group form. With a pose as a mean in SE(3) times the exponential of a small Gaussian twist, compounding becomes for the right perturbation, with no singular set. See uncertainty on Lie groups and the adjoint map.
- Higher order and sampling. Barfoot and Furgale (2014) add fourth-order terms on SE(3). The unscented transform and plain Monte Carlo avoid derivatives, at the cost of more evaluations.
- Merging. Smith and Cheeseman (1986) also merge two estimates of the same relation with the Kalman update, the step that a Kalman filter makes.
Pitfalls
- Dropped correlations. is the identity pose and has no uncertainty. With the full correlation, the operators return the zero covariance. If the two inputs are treated as independent, the same example gives , which is pure error. Keep the cross-covariance whenever two poses share an error source.
- The linearization. The covariance is first order. With a heading standard deviation of tenths of a radian over meters of travel, the mean moves inside the arc and the true spread is curved, as the example shows. Check the result with samples when the heading is uncertain.
- Angle wrapping. Wrap after each operation, and compute means of angles and residuals with wrapped differences. A naive mean of and rad is 0.
- The frame of the covariance. The covariance of is in the axes of frame . A covariance in the robot's own axes must be turned first, which is exactly what does.
- The order of the arguments. uses the result and the first pose. Swapping the arguments of gives a different pose and different Jacobians.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pose-compounding-operators/. The authors are listed in prov/Z8QZF9.jsonl.
"""The compounding operators of Smith, Self and Cheeseman for planar poses.
A planar pose is a list (x, y, phi), with phi in radians, wrapped to
[-pi, pi). x_ij is the pose of frame j in frame i.
- oplus(a, b) is the head-to-tail compound x_ik = x_ij (+) x_jk.
- ominus(a) is the inverse x_ji = (-) x_ij.
- jac_oplus and jac_ominus are their Jacobians, written with the result
as in the paper.
- compound(...) and invert(...) carry a mean and a covariance through the
operators to first order. This is a linearization: it is exact only
when the operators are linear over the spread of the inputs.
- tail_to_tail(...) gives x_jk = (-) x_ij (+) x_ik from two poses that
share their first frame.
Matrices are lists of rows.
"""
import math
def wrap(a):
"""Return a + 2 pi k in [-pi, pi)."""
w = math.fmod(a + math.pi, 2.0 * math.pi)
if w < 0.0:
w += 2.0 * math.pi
w -= math.pi
if w >= math.pi:
w -= 2.0 * math.pi
return w
def _mul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(len(b))) for j in range(len(b[0]))] for i in range(len(a))]
def _t(a):
return [list(c) for c in zip(*a)]
def _add(*ms):
return [[sum(m[i][j] for m in ms) for j in range(len(ms[0][0]))] for i in range(len(ms[0]))]
def _sandwich(j, c, k=None):
"""Return j c k^T (k = j if not given)."""
return _mul(_mul(j, c), _t(j if k is None else k))
def oplus(a, b):
"""Return the head-to-tail compound a (+) b."""
xa, ya, pa = a
xb, yb, pb = b
c, s = math.cos(pa), math.sin(pa)
return [xa + c * xb - s * yb, ya + s * xb + c * yb, wrap(pa + pb)]
def ominus(a):
"""Return the inverse (-) a, the pose of frame i in frame j."""
x, y, p = a
c, s = math.cos(p), math.sin(p)
return [-c * x - s * y, s * x - c * y, wrap(-p)]
def jac_oplus(a, b):
"""Return (J1, J2), the 3x3 Jacobians of a (+) b in a and in b."""
xa, ya, pa = a
x3, y3, _ = oplus(a, b)
c, s = math.cos(pa), math.sin(pa)
j1 = [[1.0, 0.0, -(y3 - ya)], [0.0, 1.0, x3 - xa], [0.0, 0.0, 1.0]]
j2 = [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
return j1, j2
def jac_ominus(a):
"""Return the 3x3 Jacobian of (-) a."""
c, s = math.cos(a[2]), math.sin(a[2])
xi, yi, _ = ominus(a)
return [[-c, -s, yi], [s, -c, -xi], [0.0, 0.0, -1.0]]
def compound(a, ca, b, cb, cab=None):
"""Return (mean, covariance) of x_ik = x_ij (+) x_jk to first order.
a = x_ij with covariance ca, b = x_jk with covariance cb, and cab the
cross-covariance E[(a - mean a)(b - mean b)^T] (zero if not given).
"""
xa, ya, pa = a # @line L1
c, s = math.cos(pa), math.sin(pa) # @line L1
x3 = oplus(a, b) # @line L2
j1 = [[1.0, 0.0, -(x3[1] - ya)], [0.0, 1.0, x3[0] - xa], [0.0, 0.0, 1.0]] # @line L3
j2 = [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]] # @line L4
c3 = _add(_sandwich(j1, ca), _sandwich(j2, cb)) # @line L5
if cab is not None: # @line L5
cross = _sandwich(j1, cab, j2) # @line L5
c3 = _add(c3, cross, _t(cross)) # @line L5
return x3, c3 # @line L6
def invert(a, ca):
"""Return (mean, covariance) of x_ji = (-) x_ij to first order."""
c, s = math.cos(a[2]), math.sin(a[2]) # @line I1
xi = [-c * a[0] - s * a[1], s * a[0] - c * a[1], wrap(-a[2])] # @line I2
j = [[-c, -s, xi[1]], [s, -c, -xi[0]], [0.0, 0.0, -1.0]] # @line I3
return xi, _sandwich(j, ca) # @line I4
def tail_to_tail(a, ca, b, cb, cab=None):
"""Return (mean, covariance) of x_jk = (-) x_ij (+) x_ik to first order.
a = x_ij and b = x_ik share the frame i; cab is their cross-covariance.
The Jacobian in (a, b) is [J1 Jm, J2], with Jm = jac_ominus(a).
"""
ai = ominus(a)
j1, j2 = jac_oplus(ai, b)
jm = jac_ominus(a)
ja = _mul(j1, jm)
out = _add(_sandwich(ja, ca), _sandwich(j2, cb))
if cab is not None:
cross = _sandwich(ja, cab, j2)
out = _add(out, cross, _t(cross))
return oplus(ai, b), out
def head_to_head(a, ca, b, cb, cab=None):
"""Return (mean, covariance) of x_ik = x_ij (+) (-) x_kj to first order.
a = x_ij and b = x_kj share the frame j; cab is their cross-covariance.
"""
bi, cbi = invert(b, cb)
jm = jac_ominus(b)
cross = None if cab is None else _mul(cab, _t(jm))
return compound(a, ca, bi, cbi, cross)
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.
Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.
The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""
import math
# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2
# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2
# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12
# ---------------------------------------------------------------- matrices
def zeros(n, m):
"""Return the n by m zero matrix."""
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(a, s):
"""Return s * a for a vector or a matrix a and a number s."""
if _is_matrix(a):
return [[s * x for x in row] for row in a]
return [s * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def mul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(p * q for p, q in zip(row, x)) for row in a]
def dot(x, y):
"""Return the dot product of two vectors."""
return sum(p * q for p, q in zip(x, y))
def norm(x):
"""Return the Euclidean norm of a vector."""
return math.sqrt(dot(x, x))
def cross(a, b):
"""Return the cross product a x b of two 3-vectors."""
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
def _max_abs(a):
return max((abs(x) for row in a for x in row), default=0.0)
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
a is a square matrix. b is a vector or a matrix with one column per
right-hand side; the result has the same shape as b. Raise ValueError
if a pivot is at most PIVOT_TOL times the largest entry of a.
"""
n = len(a)
vec = not _is_matrix(b)
rhs = [[x] for x in b] if vec else [list(row) for row in b]
m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
k = len(rhs[0]) if rhs else 0
tol = PIVOT_TOL * _max_abs(a)
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
raise ValueError("matrix is singular to working precision")
m[c], m[piv] = m[piv], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
if f != 0.0:
row_r, row_c = m[r], m[c]
for j in range(c, n + k):
row_r[j] -= f * row_c[j]
x = [[0.0] * k for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(k):
s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def inv(a):
"""Return the inverse of the square matrix a (see solve for errors)."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a by elimination."""
n = len(a)
m = [list(map(float, row)) for row in a]
d = 1.0
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[piv][c] == 0.0:
return 0.0
if piv != c:
m[c], m[piv] = m[piv], m[c]
d = -d
d *= m[c][c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
for j in range(c, n):
m[r][j] -= f * m[c][j]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T.
a must be symmetric positive definite. Raise ValueError if a diagonal
entry of the factor is not positive.
"""
n = len(a)
low = zeros(n, n)
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
if i == j:
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[i][i] = math.sqrt(s)
else:
low[i][j] = s / low[j][j]
return low
def pinv_right(j):
"""Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
jt = transpose(j)
return mul(jt, inv(mul(j, jt)))
# ---------------------------------------------------------------- hat and vee
def hat3(w):
"""Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
return [
[0.0, -w[2], w[1]],
[w[2], 0.0, -w[0]],
[-w[1], w[0], 0.0],
]
def vee3(m):
"""Return the 3-vector w of a skew-symmetric matrix m = [w]."""
return [m[2][1], m[0][2], m[1][0]]
def hat6(v):
"""Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
w = hat3(v[:3])
return [
[w[0][0], w[0][1], w[0][2], v[3]],
[w[1][0], w[1][1], w[1][2], v[4]],
[w[2][0], w[2][1], w[2][2], v[5]],
[0.0, 0.0, 0.0, 0.0],
]
def vee6(m):
"""Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]
# ---------------------------------------------------------------- rotations
def rot_x(a):
"""Return the rotation by a radians about the x axis."""
c, s = math.cos(a), math.sin(a)
return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
def rot_y(a):
"""Return the rotation by a radians about the y axis."""
c, s = math.cos(a), math.sin(a)
return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]
def rot_z(a):
"""Return the rotation by a radians about the z axis."""
c, s = math.cos(a), math.sin(a)
return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
def rpy(roll, pitch, yaw):
"""Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))
def so3_exp(w):
"""Return exp([w]) for exponential coordinates w = omega_hat * theta.
Rodrigues' formula in the form I + A [w] + B [w]^2 with
A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
"""
t = norm(w)
if t < SERIES_THETA:
t2 = t * t
a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
else:
a = math.sin(t) / t
b = (1.0 - math.cos(t)) / (t * t)
k = hat3(w)
k2 = mul(k, k)
return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]
def so3_log(r):
"""Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].
theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
above pi - NEAR_PI, the axis comes from the symmetric part
((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
from s. At theta = pi both signs are valid; the sign is then chosen so
that the largest component of the axis is positive.
"""
c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
c = max(-1.0, min(1.0, c))
s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
sn = norm(s)
t = math.atan2(sn, c)
if t < SERIES_THETA:
t2 = t * t
f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
return [f * x for x in s]
if t <= math.pi - NEAR_PI:
return [t / sn * x for x in s]
b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
# b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
# diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
k = max(range(3), key=lambda i: b[i][i])
col = [b[i][k] for i in range(3)]
axis = [x / norm(col) for x in col]
if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
axis = [-x for x in axis]
return [t * x for x in axis]
# ---------------------------------------------------------------- poses
def make_T(r, p):
"""Return the 4x4 pose [[r, p], [0, 1]]."""
return [
[r[0][0], r[0][1], r[0][2], p[0]],
[r[1][0], r[1][1], r[1][2], p[1]],
[r[2][0], r[2][1], r[2][2], p[2]],
[0.0, 0.0, 0.0, 1.0],
]
def _rp(t):
return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]
def T_inv(t):
"""Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
r, p = _rp(t)
rt = transpose(r)
return make_T(rt, [-x for x in matvec(rt, p)])
def T_apply(t, x):
"""Return R x + p, the image of the point x under the pose t."""
r, p = _rp(t)
return add(matvec(r, x), p)
def se3_exp(xi):
"""Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.
The rotation is so3_exp(w). The translation is G v with
G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
translation by v.
"""
w, v = xi[:3], xi[3:]
t = norm(w)
if t < SERIES_THETA:
t2 = t * t
b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
else:
b = (1.0 - math.cos(t)) / (t * t)
c = (t - math.sin(t)) / (t * t * t)
k = hat3(w)
k2 = mul(k, k)
g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
return make_T(so3_exp(w), matvec(g, v))
def se3_log(t):
"""Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].
w = so3_log(R) and v = G^(-1) p with
G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
"""
r, p = _rp(t)
w = so3_log(r)
th = norm(w)
if th < SERIES_THETA:
t2 = th * th
d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
else:
half = th / 2.0
d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
k = hat3(w)
k2 = mul(k, k)
gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
return w + matvec(gi, p)
def adjoint(t):
"""Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
r, p = _rp(t)
pr = mul(hat3(p), r)
out = zeros(6, 6)
for i in range(3):
for j in range(3):
out[i][j] = r[i][j]
out[i + 3][j + 3] = r[i][j]
out[i + 3][j] = pr[i][j]
return out
# ---------------------------------------------------------------- quaternions
def quat_mul(q, r):
"""Return the Hamilton product q r of quaternions (w, x, y, z)."""
a1, b1, c1, d1 = q
a2, b2, c2, d2 = r
return [
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
]
def quat_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return [q[0], -q[1], -q[2], -q[3]]
def quat_to_rot(q):
"""Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.
q need not be of unit length; the result is the rotation of q / |q|.
"""
w, x, y, z = q
n = w * w + x * x + y * y + z * z
s = 2.0 / n
return [
[1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
[s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
[s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
]
def quat_from_axis_angle(axis, angle):
"""Return (cos(angle / 2), sin(angle / 2) axis / |axis|).
A zero axis is allowed only with angle 0 (the identity); otherwise
raise ValueError.
"""
n = norm(axis)
if n == 0.0:
if angle == 0.0:
return [1.0, 0.0, 0.0, 0.0]
raise ValueError("zero axis with a nonzero angle")
s = math.sin(angle / 2.0) / n
return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]
# ---------------------------------------------------------------- derivatives
def num_jacobian(f, x, h=1e-6):
"""Return the Jacobian of f at x by central differences with step h.
f maps a list of n numbers to a list of m numbers; the result is m by n.
"""
cols = []
for i in range(len(x)):
xp = list(x)
xm = list(x)
xp[i] += h
xm[i] -= h
fp, fm = f(xp), f(xm)
cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
return transpose(cols)
# ---------------------------------------------------------------- self-test
def self_test():
"""Check the area check values; return True or raise AssertionError."""
r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
w = so3_log(want)
assert abs(norm(w) - 2.0943951) < 1e-7
assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
return True
test_pose_compounding_operators.py 181 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pose-compounding-operators/. The authors are listed in prov/Z8QZF9.jsonl.
"""Tests of the compounding operators against SE(3) products, finite
differences, the hand example of the page and Monte Carlo estimates."""
import math
import random
import rbm
from pose_compounding_operators import (
compound,
head_to_head,
invert,
jac_ominus,
jac_oplus,
ominus,
oplus,
tail_to_tail,
wrap,
)
def maxdiff(a, b):
if a and isinstance(a[0], list):
return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
return max(abs(x - y) for x, y in zip(a, b))
def pose_diff(a, b):
return max(abs(a[0] - b[0]), abs(a[1] - b[1]), abs(wrap(a[2] - b[2])))
def to_T(a):
return rbm.make_T(rbm.rot_z(a[2]), [a[0], a[1], 0.0])
def from_T(t):
return [t[0][3], t[1][3], math.atan2(t[1][0], t[0][0])]
def random_pose(rng, ang=3.0):
return [rng.uniform(-5.0, 5.0), rng.uniform(-5.0, 5.0), rng.uniform(-ang, ang)]
def sample_cov(points, mean):
n = len(points)
return [[sum((p[i] - mean[i]) * (p[j] - mean[j]) for p in points) / (n - 1) for j in range(3)] for i in range(3)]
def sampler(rng, mean, cov):
low = rbm.cholesky(cov)
def draw():
z = [rng.gauss(0.0, 1.0) for _ in range(3)]
return [mean[i] + sum(low[i][k] * z[k] for k in range(i + 1)) for i in range(3)]
return draw
def test_oplus_and_ominus_match_se3_products():
rng = random.Random(1)
for _ in range(200):
a, b = random_pose(rng), random_pose(rng)
assert pose_diff(oplus(a, b), from_T(rbm.mul(to_T(a), to_T(b)))) < 1e-12
assert pose_diff(ominus(a), from_T(rbm.T_inv(to_T(a)))) < 1e-12
assert pose_diff(oplus(ominus(a), a), [0.0, 0.0, 0.0]) < 1e-12
assert pose_diff(oplus(a, ominus(a)), [0.0, 0.0, 0.0]) < 1e-12
def test_associative_not_commutative():
rng = random.Random(2)
for _ in range(100):
a, b, c = random_pose(rng), random_pose(rng), random_pose(rng)
assert pose_diff(oplus(oplus(a, b), c), oplus(a, oplus(b, c))) < 1e-12
a, b = [2.0, 1.0, math.pi / 2], [1.0, 0.0, 0.0]
assert pose_diff(oplus(b, a), [3.0, 1.0, math.pi / 2]) < 1e-12
assert pose_diff(oplus(a, b), oplus(b, a)) > 0.5
def test_hand_example():
a, b = [2.0, 1.0, math.pi / 2], [1.0, 0.0, 0.0]
ca = [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.0025]]
m, c = compound(a, ca, b, ca)
assert pose_diff(m, [2.0, 2.0, math.pi / 2]) < 1e-12
want = [[0.0225, 0.0, -0.0025], [0.0, 0.02, 0.0], [-0.0025, 0.0, 0.005]]
assert maxdiff(c, want) < 1e-12
mi, ci = invert(a, ca)
assert pose_diff(mi, [-1.0, 2.0, -math.pi / 2]) < 1e-12
want_i = [[0.02, 0.005, -0.005], [0.005, 0.0125, -0.0025], [-0.005, -0.0025, 0.0025]]
assert maxdiff(ci, want_i) < 1e-12
def test_jacobians_match_finite_differences():
rng = random.Random(3)
for _ in range(50):
a, b = random_pose(rng, 1.4), random_pose(rng, 1.4)
j1, j2 = jac_oplus(a, b)
assert maxdiff(j1, rbm.num_jacobian(lambda u: oplus(u, b), a)) < 1e-6
assert maxdiff(j2, rbm.num_jacobian(lambda u: oplus(a, u), b)) < 1e-6
assert maxdiff(jac_ominus(a), rbm.num_jacobian(ominus, a)) < 1e-6
def test_head_to_head_and_tail_to_tail():
rng = random.Random(4)
c1 = [[0.02, 0.003, 0.0], [0.003, 0.01, 0.001], [0.0, 0.001, 0.004]]
c2 = [[0.01, 0.0, 0.002], [0.0, 0.03, 0.0], [0.002, 0.0, 0.005]]
c12 = [[0.002, 0.0, 0.0], [0.0, 0.001, 0.0], [0.0, 0.0, 0.0005]]
for _ in range(20):
a, b = random_pose(rng, 1.4), random_pose(rng, 1.4)
m, c = tail_to_tail(a, c1, b, c2, c12)
assert pose_diff(m, oplus(ominus(a), b)) < 1e-12
f = lambda u: oplus(ominus(u[:3]), u[3:])
j = rbm.num_jacobian(f, a + b)
big = [row[:3] + [0.0] * 3 for row in c1] + [row[:] + [0.0] * 3 for row in rbm.transpose(c12)]
for i in range(3):
big[i][3:] = c12[i]
big[i + 3][3:] = c2[i]
want = rbm.mul(rbm.mul(j, big), rbm.transpose(j))
assert maxdiff(c, want) < 1e-6
m, c = head_to_head(a, c1, b, c2, c12)
assert pose_diff(m, oplus(a, ominus(b))) < 1e-12
g = lambda u: oplus(u[:3], ominus(u[3:]))
j = rbm.num_jacobian(g, a + b)
want = rbm.mul(rbm.mul(j, big), rbm.transpose(j))
assert maxdiff(c, want) < 1e-6
def test_correlation_must_be_kept():
a = [2.0, 1.0, math.pi / 2]
ca = [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.0025]]
# x_ij (+) (-) x_ij is the identity pose, with no uncertainty at all.
m, c = head_to_head(a, ca, a, ca, ca)
assert pose_diff(m, [0.0, 0.0, 0.0]) < 1e-12
assert maxdiff(c, rbm.zeros(3, 3)) < 1e-15
# Dropping the cross-covariance gives a large wrong covariance.
m, c = head_to_head(a, ca, a, ca)
want = [[0.025, -0.01, 0.005], [-0.01, 0.04, -0.01], [0.005, -0.01, 0.005]]
assert maxdiff(c, want) < 1e-12
def test_small_noise_matches_monte_carlo():
rng = random.Random(5)
a, b = [2.0, 1.0, math.pi / 2], [1.0, 0.0, 0.0]
ca = [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.0025]]
m, c = compound(a, ca, b, ca)
da, db = sampler(rng, a, ca), sampler(rng, b, ca)
pts = [oplus(da(), db()) for _ in range(20000)]
mean = [sum(p[i] for p in pts) / len(pts) for i in range(3)]
assert maxdiff(mean, m) < 0.01
assert maxdiff(sample_cov(pts, mean), c) < 0.05 * 0.0225
mi, ci = invert(a, ca)
pts = [ominus(da()) for _ in range(20000)]
mean = [sum(p[i] for p in pts) / len(pts) for i in range(3)]
assert maxdiff(mean, mi) < 0.01
assert maxdiff(sample_cov(pts, mean), ci) < 0.05 * 0.0225
def test_large_heading_noise_breaks_the_linearization():
# Drive 10 m with a heading error of standard deviation 0.5 rad.
rng = random.Random(6)
tiny = 1e-10
a, ca = [0.0, 0.0, 0.0], [[tiny, 0.0, 0.0], [0.0, tiny, 0.0], [0.0, 0.0, 0.25]]
b, cb = [10.0, 0.0, 0.0], [[tiny, 0.0, 0.0], [0.0, tiny, 0.0], [0.0, 0.0, tiny]]
m, c = compound(a, ca, b, cb)
assert maxdiff(m, [10.0, 0.0, 0.0]) < 1e-12
assert abs(c[0][0]) < 1e-8 and abs(c[1][1] - 25.0) < 1e-8
# Exact moments of (10 cos phi, 10 sin phi) with phi ~ N(0, 0.25).
ex = 10.0 * math.exp(-0.125)
vx = 100.0 * ((1.0 + math.exp(-0.5)) / 2.0 - math.exp(-0.25))
vy = 100.0 * (1.0 - math.exp(-0.5)) / 2.0
da, db = sampler(rng, a, ca), sampler(rng, b, cb)
pts = [oplus(da(), db()) for _ in range(20000)]
mean = [sum(p[i] for p in pts) / len(pts) for i in range(3)]
cov = sample_cov(pts, mean)
assert abs(mean[0] - ex) < 0.05
assert abs(cov[0][0] - vx) < 0.15
assert abs(cov[1][1] - vy) < 0.8
# The first-order answer misses the mean by more than 1 m and the
# variance across the track by more than 5 m^2.
assert m[0] - mean[0] > 1.0
assert c[1][1] - cov[1][1] > 5.0
Exercises
- Show that , and that .
- For , show that has the entries and in its last column, and explain them as the motion of the end point when the start frame turns by a small angle.
- Compute the first-order covariance of for with and with , and compare it with the exact covariance of . For which is the difference in below 10 percent?
- Use the chain rule to show that compounding a chain in either grouping gives the same first-order covariance.
References
- Randall Smith, Matthew Self and Peter Cheeseman, Estimating uncertain spatial relationships in robotics, in I. J. Cox and G. T. Wilfong (eds.), Autonomous Robot Vehicles, Springer, 1990, 167 to 193, the whole chapter (the compounding and inverse operations, their Jacobians and the first-order covariance)
- Randall Smith, Matthew Self and Peter Cheeseman, Estimating uncertain spatial relationships in robotics, Uncertainty in Artificial Intelligence 2, 1988, 435 to 461, Section 3.2 (3.2.1 compounding, 3.2.2 the inverse relationship, 3.2.3 composite relationships) and Appendix A (the six degree of freedom case)
- Randall C. Smith and Peter Cheeseman, On the representation and estimation of spatial uncertainty, The International Journal of Robotics Research 5(4), 56 to 68, 1986, the whole paper (approximate transformations, their compounding and merging)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag Z8QZF9 Edit this page History Report an error Markdown