Algorithm Search⌘K

Algorithmadvanced

Lie-algebraic rotation averaging

Also called Govindu rotation averaging.

Average rotations by repeated linear least squares on their logarithms in the Lie algebra so(3). Robust versions start from an L1 solution and then run IRLS with a robust cost.

Time
O(k (E + N^3)) totalO(E + N^3) per_iteration
Space
O(E + N^2) extra
Where
E = the number of edges of the view graph; N = the number of cameras; k = the number of iterations
Properties
deterministiciterativelocalnot monotoneiterative
Origin
Venu Madhav Govindu, Avishek Chatterjee, 2004

Lie-algebraic rotation averaging is an iterative algorithm for rotation averaging: given measured relative rotations Rij≈RjRiTR_{ij} \approx R_j R_i^{\mathsf T} on the edges of a view graph, it finds absolute rotations RkR_k that fit them. Rotations do not form a vector space, so the algorithm works in the tangent space, the Lie algebra so(3)\mathfrak{so}(3), which is R3\mathbb{R}^3. At each step it measures the disagreement of each edge as a rotation vector with the logarithm map, solves one linear least squares problem for a small rotation of every camera, which is a system with the graph Laplacian, and applies the small rotations. With unit weights this is the Gauss-Newton method for the squared geodesic cost, as given by Govindu (2004). Chatterjee and Govindu made it robust: they start from an L1L_1 solution and then run iteratively reweighted least squares with a robust cost, which removes the effect of wrong edges. It is the rotation step of many global structure from motion systems.

In plain words

Each camera has an unknown direction, and for many pairs you have measured how much one camera is turned compared with the other. Start with a guess for every camera, for example by chaining the measurements along a tree. For each pair, compute how far the guess is from the measurement, as a small turn. Then ask: what small extra turn of every camera would make all these differences as small as possible together? That question has a straight answer from one set of linear equations, because small turns behave almost like ordinary vectors. Apply the turns and repeat. To stop a few bad measurements from pulling everything, give each pair a weight that gets smaller when its difference is large, and recompute the weights each time.

The problem

Input. A connected graph on the cameras 1,…,N1, \dots, N with EE edges, a measured rotation Rij∈SO(3)R_{ij} \in SO(3) for each edge (i,j)(i, j), in the convention Xj=RijXi+tijX_j = R_{ij} X_i + t_{ij}, a loss (squared, L1L_1 or Geman-McClure), its scale σ\sigma, a floor δ\delta for the L1L_1 weights, a start (optional), a tolerance ε\varepsilon and an iteration limit kmax⁡k_{\max}.

Output. Rotations R1,…,RNR_1, \dots, R_N with R1=IR_1 = I at a stationary point of

F(R)=∑(i,j)ρ(∥rij∥),rij=log⁡(RjTRijRi)∈R3,F(R) = \sum_{(i,j)} \rho(\|r_{ij}\|), \qquad r_{ij} = \log\big(R_j^{\mathsf T} R_{ij} R_i\big) \in \mathbb{R}^3,

where log⁡\log returns the rotation vector of angle in [0,π][0, \pi]. The residual rijr_{ij} is zero when the edge agrees with the estimate, and ∥rij∥\|r_{ij}\| is the geodesic distance between RijR_{ij} and RjRiTR_j R_i^{\mathsf T}. The losses are ρ(x)=x2\rho(x) = x^2, ρ(x)=x\rho(x) = x and ρ(x)=x2/(x2+σ2)\rho(x) = x^2 / (x^2 + \sigma^2).

Update. Each camera gets a small rotation ωk\omega_k applied on the right, Rk←Rkexp⁡([ωk]×)R_k \leftarrow R_k \exp([\omega_k]_\times). Then the residual of the edge (i,j)(i, j) becomes log⁡(exp⁡(−[ωj]×)exp⁡([rij]×)exp⁡([ωi]×))≈rij+ωi−ωj\log(\exp(-[\omega_j]_\times) \exp([r_{ij}]_\times) \exp([\omega_i]_\times)) \approx r_{ij} + \omega_i - \omega_j, to first order in all three vectors. So the linear model asks for ωj−ωi≈rij\omega_j - \omega_i \approx r_{ij} on every edge.

The algorithm

  1. LIE-AVERAGE(G, {R_ij}, loss, σ, δ, ε, k_max)
  2. 1R <- the start, or the rotations chained from R_1 = I along a breadth-first spanning tree
  3. 2for it <- 1 to k_max
  4. 3for each edge (i, j): r_ij <- log(R_j^T R_ij R_i)
  5. 4w_ij <- 1 (squared), 1 / max(||r_ij||, δ) (L1), or σ² / (||r_ij||² + σ²)² (Geman-McClure)
  6. 5solve L ω = b with ω_1 = 0, where L is the weighted graph Laplacian without row and column 1, and b_k = Σ_(i,k) w_ik r_ik - Σ_(k,j) w_kj r_kj
  7. 6for each camera k: R_k <- R_k exp([ω_k]_x)
  8. 7if max_k ||ω_k|| < ε then stop
  9. 8return R

Line L1 gives a start that fits the tree edges exactly. Lines L3 and L4 compute the residuals and the weights of iteratively reweighted least squares: the weight ρ′(x)/(2x)\rho'(x) / (2x) of the loss, up to a constant factor. Line L5 is the normal equation of min⁡ω∑wij∥ωj−ωi−rij∥2\min_\omega \sum w_{ij} \|\omega_j - \omega_i - r_{ij}\|^2 with ω1=0\omega_1 = 0. Its matrix is the same (N−1)×(N−1)(N - 1) \times (N - 1) Laplacian for the three coordinates of ω\omega, so one factorization serves three right-hand sides. Line L6 applies the step on the right, which matches the linear model. The robust run of Chatterjee and Govindu is LIE-AVERAGE with the L1L_1 loss from the tree start, followed by LIE-AVERAGE with a robust loss from its result. The reference code runs 30 iterations of each, with Geman-McClure as the robust loss.

Example

Take three cameras and rotations about the ZZ axis: R12R_{12} by 10∘10^\circ, R23R_{23} by 20∘20^\circ and R13R_{13} by 33∘33^\circ. The cycle does not close: 10+20−33=−310 + 20 - 33 = -3 degrees. Write θk\theta_k for the angle of RkR_k.

  • Start (line L1). The breadth-first tree from camera 1 uses the edges (1,2)(1, 2) and (1,3)(1, 3), so θ2=10∘\theta_2 = 10^\circ and θ3=33∘\theta_3 = 33^\circ. The residual of the edge (2,3)(2, 3) is 20−23=−320 - 23 = -3 degrees, and the other two residuals are 0.
  • Squared loss. All rotations share one axis, so they commute, the linear model is exact, and line L5 solves 2ω2−ω3=32\omega_2 - \omega_3 = 3, −ω2+2ω3=−3-\omega_2 + 2\omega_3 = -3 (in degrees): ω2=1\omega_2 = 1, ω3=−1\omega_3 = -1. After one step, θ2=11∘\theta_2 = 11^\circ and θ3=32∘\theta_3 = 32^\circ, each edge has a residual of 1∘1^\circ in size, and the cost drops from 99 to 33 square degrees (0.000910.00091 rad squared). The second iteration finds ω=0\omega = 0 and stops.
  • L1L_1 loss. From the start, the two exact edges get the weight 1/δ=1061/\delta = 10^6 and the third gets 1/(3∘)1 / (3^\circ), so the solve keeps the exact edges almost fixed, and the iteration stays within 10−410^{-4} degrees of the start. The start is one of the L1L_1 minimizers, with the cost 3∘=0.052363^\circ = 0.05236 rad, but the whole error sits on one edge.
  • Geman-McClure loss, σ=0.1\sigma = 0.1 rad. All residuals are small compared with σ\sigma, so the loss behaves like the squared loss, and the run ends at θ2=11∘\theta_2 = 11^\circ, θ3=32∘\theta_3 = 32^\circ after 13 iterations.

The reference code gives these numbers. On a larger test with 15 cameras and 62 edges, with 0.010.01 rad of noise and about 15% of the edges replaced by random rotations, the squared loss ends with a largest relative rotation error of 1.901.90 rad, worse than the tree start, and the robust run ends with 0.0220.022 rad (a benchmark result on this test).

Correctness

The update is exact to first order: for the squared loss, line L5 solves the Gauss-Newton system of FF in the local coordinates ω\omega (theorem). The gradient of ∑∥rij∥2\sum \|r_{ij}\|^2 with respect to ωk\omega_k at ω=0\omega = 0 is exactly −2bk-2 b_k, because the derivative of ∥log⁡Q∥2\|\log Q\|^2 along a small rotation uu is 2⟨log⁡Q,u⟩2 \langle \log Q, u \rangle (theorem). The grounded Laplacian of a connected graph with positive weights is positive definite, so line L5 has a unique solution, and ω\omega is a descent direction whenever b≠0b \ne 0 (theorem). The solution is ω=0\omega = 0 if and only if b=0b = 0, which is the stationarity condition, so a stop at line L7 with ε→0\varepsilon \to 0 means a stationary point (theorem). On exact data, the tree start already has all residuals 0, so the algorithm returns the true rotations up to the gauge after one iteration (theorem). The full step has no line search, so the cost need not decrease at every step; in practice it does from a good start (heuristic). The proof file below gives the details.

Proof: The Lie-algebraic update is a well defined descent step that stops exactly at stationary points, and the tree start is exact on consistent datafull

We use the notation of the page. The graph is connected, with cameras 1,…,N1, \dots, N. For an edge (i,j)(i, j) the residual is rij=log⁡(RjTRijRi)r_{ij} = \log(R_j^{\mathsf T} R_{ij} R_i), and the cost with the squared loss is F(R)=∑(i,j)∥rij∥2F(R) = \sum_{(i,j)} \|r_{ij}\|^2. The update is Rk←Rkexp⁡([ωk]×)R_k \leftarrow R_k \exp([\omega_k]_\times) with ω1=0\omega_1 = 0. Line L5 solves Lω=bL \omega = b, where LL is the weighted graph Laplacian with row and column 1 removed, applied to each coordinate of ω\omega, and bk=∑(i,k)wikrik−∑(k,j)wkjrkjb_k = \sum_{(i,k)} w_{ik} r_{ik} - \sum_{(k,j)} w_{kj} r_{kj}. All angles of the residuals are below π\pi, so the logarithm is smooth at every residual.

Claim. (a) The grounded Laplacian LL is positive definite when all weights are positive, so line L5 has exactly one solution. (b) With unit weights, the gradient of FF with respect to ωk\omega_k at ω=0\omega = 0 is −2bk-2 b_k, and line L5 is the Gauss-Newton step of FF. (c) If b≠0b \ne 0, the step ω\omega of line L5 is a descent direction of FF, and ω=0\omega = 0 if and only if b=0b = 0, which holds if and only if RR is a stationary point of FF. The same holds for the reweighted cost ∑wij∥rij∥2\sum w_{ij} \|r_{ij}\|^2 with the weights fixed. (d) If the edges are exact, Rij=Rjtrue(Ritrue)TR_{ij} = R_j^{\mathrm{true}} (R_i^{\mathrm{true}})^{\mathsf T}, then the tree start of line L1 has all residuals equal to 0, and the algorithm returns Rk=Rktrue(R1true)TR_k = R_k^{\mathrm{true}} (R_1^{\mathrm{true}})^{\mathsf T}, the true rotations up to the gauge.

Proof of (a). For a vector x∈RNx \in \mathbb{R}^N, the weighted Laplacian Lˉ\bar L satisfies xTLˉx=∑(i,j)wij(xj−xi)2≥0x^{\mathsf T} \bar L x = \sum_{(i,j)} w_{ij} (x_j - x_i)^2 \ge 0. The grounded matrix LL is Lˉ\bar L restricted to the vectors with x1=0x_1 = 0. Let x1=0x_1 = 0 and xTLˉx=0x^{\mathsf T} \bar L x = 0. Every weight is positive, so xi=xjx_i = x_j on every edge. The graph is connected, so xx is constant, and x1=0x_1 = 0 gives x=0x = 0. So LL is positive definite and invertible. □\square

Proof of (b). Fix an edge (i,j)(i, j) and put Q=RjTRijRiQ = R_j^{\mathsf T} R_{ij} R_i, so rij=log⁡Qr_{ij} = \log Q. After the update, the residual is log⁡(exp⁡(−[ωj]×) Q exp⁡([ωi]×))\log(\exp(-[\omega_j]_\times) \, Q \, \exp([\omega_i]_\times)). We use one fact about SO(3)SO(3): for a rotation QQ with angle below π\pi and a small rotation vector uu, ∥log⁡(Qexp⁡([u]×))∥2=∥log⁡Q∥2+2⟨log⁡Q,u⟩+O(∥u∥2)\|\log(Q \exp([u]_\times))\|^2 = \|\log Q\|^2 + 2 \langle \log Q, u \rangle + O(\|u\|^2), and ∥log⁡(exp⁡([u]×)Q)∥2=∥log⁡Q∥2+2⟨log⁡Q,u⟩+O(∥u∥2)\|\log(\exp([u]_\times) Q)\|^2 = \|\log Q\|^2 + 2 \langle \log Q, u \rangle + O(\|u\|^2). To see it, write ϕ=log⁡Q\phi = \log Q. The squared geodesic distance d(Q,I)2=∥ϕ∥2d(Q, I)^2 = \|\phi\|^2 has the Riemannian gradient −2log⁡(QT)=2ϕ-2\log(Q^{\mathsf T}) = 2\phi at QQ, in the body frame of the right action and also in the space frame of the left action, because ϕ\phi is fixed by QQ: Qϕ=ϕQ \phi = \phi, as ϕ\phi is the axis of QQ. So both directional derivatives along uu are 2⟨ϕ,u⟩2 \langle \phi, u \rangle.

Apply this with u=ωiu = \omega_i on the right and u=−ωju = -\omega_j on the left. To first order, the residual norm squared is ∥rij∥2+2⟨rij,ωi−ωj⟩\|r_{ij}\|^2 + 2 \langle r_{ij}, \omega_i - \omega_j \rangle. Summing over the edges, the coefficient of ωk\omega_k is 2∑(k,j)rkj−2∑(i,k)rik=−2bk2 \sum_{(k,j)} r_{kj} - 2 \sum_{(i,k)} r_{ik} = -2 b_k with unit weights. So ∇ωkF=−2bk\nabla_{\omega_k} F = -2 b_k.

The same first order expansion of the residual vector itself is rij+Jij(ωi−ωj)r_{ij} + J_{ij} (\omega_i - \omega_j) with Jij=I+O(∥rij∥)J_{ij} = I + O(\|r_{ij}\|). Gauss-Newton replaces each residual by its linear model. The page uses the model with Jij=IJ_{ij} = I, the form of Govindu (2004): min⁡ω∑∥rij+ωi−ωj∥2\min_\omega \sum \|r_{ij} + \omega_i - \omega_j\|^2 with ω1=0\omega_1 = 0. Setting the derivative with respect to ωk\omega_k, k≠1k \ne 1, to zero gives ∑(i,k)(ωk−ωi−rik)+∑(k,j)(ωk−ωj+rkj)=0\sum_{(i,k)} (\omega_k - \omega_i - r_{ik}) + \sum_{(k,j)} (\omega_k - \omega_j + r_{kj}) = 0, which is row kk of Lω=bL \omega = b. So line L5 solves the linear least squares problem of the model, and its right side is exactly −12-\frac{1}{2} times the true gradient. □\square

Proof of (c). By (a), ω=L−1b\omega = L^{-1} b. The directional derivative of FF along ω\omega is ∑k⟨∇ωkF,ωk⟩=−2 bTω=−2 bTL−1b\sum_k \langle \nabla_{\omega_k} F, \omega_k \rangle = -2 \, b^{\mathsf T} \omega = -2 \, b^{\mathsf T} L^{-1} b, where the sum and the products run over the cameras k≠1k \ne 1 and the three coordinates. The matrix L−1L^{-1} is positive definite, so this value is negative when b≠0b \ne 0. So ω\omega is a descent direction. Since LL is invertible, ω=0\omega = 0 exactly when b=0b = 0. The gauge fixes ω1=0\omega_1 = 0, and FF does not change when all rotations are multiplied on the right by one rotation, so the gradient with respect to ω1\omega_1 is minus the sum of the other gradients; hence the full gradient is zero if and only if bk=0b_k = 0 for all k≠1k \ne 1. So b=0b = 0 is the stationarity condition. With fixed positive weights wijw_{ij}, every step above holds with wijw_{ij} as a factor in each sum, and LL is the weighted Laplacian. □\square

Proof of (d). Line L1 chains the rotations along a spanning tree from R1=IR_1 = I, setting Rj=RijRiR_j = R_{ij} R_i for each tree edge from the parent ii to the child jj. By induction on the depth, Rk=Rktrue(R1true)TR_k = R_k^{\mathrm{true}} (R_1^{\mathrm{true}})^{\mathsf T}: this holds for the root, and if it holds for ii, then Rj=Rjtrue(Ritrue)TRitrue(R1true)T=Rjtrue(R1true)TR_j = R_j^{\mathrm{true}} (R_i^{\mathrm{true}})^{\mathsf T} R_i^{\mathrm{true}} (R_1^{\mathrm{true}})^{\mathsf T} = R_j^{\mathrm{true}} (R_1^{\mathrm{true}})^{\mathsf T}. Then for every edge (i,j)(i, j), tree edge or not, RjTRijRi=R1true(Rjtrue)TRjtrue(Ritrue)TRitrue(R1true)T=IR_j^{\mathsf T} R_{ij} R_i = R_1^{\mathrm{true}} (R_j^{\mathrm{true}})^{\mathsf T} R_j^{\mathrm{true}} (R_i^{\mathrm{true}})^{\mathsf T} R_i^{\mathrm{true}} (R_1^{\mathrm{true}})^{\mathsf T} = I, so rij=0r_{ij} = 0. Then b=0b = 0, line L5 gives ω=0\omega = 0 by (a), and line L7 stops in the first iteration with the start unchanged. Every loss gives a finite positive weight at r=0r = 0, with the floor δ\delta for the L1L_1 weight, so this holds for all three losses. ■\blacksquare

Complexity

In the real RAM model, line L3 costs O(E)O(E): one logarithm and two 3×33 \times 3 products per edge. Line L5 assembles the Laplacian in O(E)O(E) and solves it. The reference code uses a dense solve, O(N3)O(N^3) per iteration. The Laplacian has one nonzero block per edge, so a sparse Cholesky factorization with a fill-reducing order, or the conjugate gradient method, makes the solve close to linear in EE for the view graphs of SfM. Line L6 costs O(N)O(N). So one iteration costs O(E+N3)O(E + N^3) dense or about O(E)O(E) sparse, and kk iterations cost kk times that. The squared loss usually stops in a handful of iterations; the reweighted runs need tens. The space is O(E)O(E) for the residuals plus the space of the solver, O(N2)O(N^2) dense.

Properties

  • Local (theorem). The method converges to a stationary point near its start, not to the global minimum. A good start, such as a maximum spanning tree on the inlier counts, matters.
  • Not monotone. There is no line search, so a step can raise the cost far from a minimum. A damping term with a test that rejects steps which raise the cost, as in Levenberg-Marquardt, makes it monotone.
  • Gauge. Fixing ω1=0\omega_1 = 0 removes the gauge. Without it the Laplacian is singular, with the constant vector in its null space.
  • Exact on exact data (theorem). A consistent set of edges is fitted exactly.
  • Robustness. The L1L_1 start is less affected by wrong edges than the squared loss, and the bounded Geman-McClure weights almost ignore edges with large residuals. Both are heuristics with good benchmark results, not guarantees.

Variants and improvements

  • Chordal and quaternion costs. The same scheme works with other distances; the chordal cost leads to the linear relaxation of Martinec and Pajdla (2007).
  • L1L_1 by linear programming. Chatterjee and Govindu (2013) solve the L1L_1 problem in the Lie algebra with a linear solver for L1L_1 problems, then refine with reweighted least squares. The reference code solves the L1L_1 part by reweighting too, which is simpler but can stall at the start, as in the example.
  • Weiszfeld iterations. Hartley, Aftab and Trumpf (2011) update one rotation at a time towards the geodesic L1L_1 median of its neighbors.
  • Certifiable methods. The semidefinite relaxation of the chordal cost, solved directly or by Shonan averaging, gives a certificate of global optimality when it is tight.
  • Pose averaging. The same linearization on SE(3)SE(3) averages full motions, as in pose graph optimization.

When to use it

Use it for the rotation step of global SfM, and for any rotation averaging problem on a sparse graph with a decent start. Use the robust form whenever the edges come from two-view geometry, since some of them are always wrong. If a certificate of global optimality is needed, use a semidefinite method such as SE-Sync on the chordal cost. If the graph is a chain with few loops, there is little to average, and the result is close to the chained start.

Pitfalls

  • Left and right updates. The step Rkexp⁡([ωk]×)R_k \exp([\omega_k]_\times) must match the residual. With rij=log⁡(RjTRijRi)r_{ij} = \log(R_j^{\mathsf T} R_{ij} R_i), the linear model is rij+ωi−ωjr_{ij} + \omega_i - \omega_j. With a left update or another residual, the signs or the frames of ω\omega change.
  • Angles near π\pi. The logarithm is not smooth at angle π\pi, and its axis is ambiguous there. Residuals that large mean a wrong edge or a bad start; a robust loss limits their effect.
  • The L1L_1 weight floor. With weights 1/∥r∥1/\|r\|, an edge with a zero residual gets an infinite weight. The floor δ\delta prevents a division by zero, but large weights freeze the start, as the example shows.
  • Disconnected graphs. The grounded Laplacian is singular if the graph is not connected. Check the components of the view graph first; the reference code raises an error.
  • Units of σ\sigma. The Geman-McClure scale is an angle in radians. Too small a value treats good edges as outliers, and too large a value gives the squared loss.

Implementations

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.

cvla.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.

A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.

Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
  that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
  1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
  imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
  of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
  1e-8.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import cmath
import math
from typing import List, Sequence, Tuple

Matrix = List[List[float]]
Vector = List[float]

_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100


# ---------------------------------------------------------------- basics

def zeros(m: int, n: int) -> Matrix:
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n: int) -> Matrix:
    """The n x 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) -> bool:
    return len(a) > 0 and isinstance(a[0], (list, tuple))


def transpose(a: Sequence[Sequence[float]]) -> Matrix:
    """The transpose of a matrix."""
    return [list(col) for col in zip(*a)]


def add(a, b):
    """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):
    """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, c):
    """c times a, for a vector or a matrix a and a number c."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    """The matrix product a b."""
    if len(a[0]) != len(b):
        raise ValueError("mul: shapes do not match")
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """The product a x of a matrix and a vector."""
    if len(a[0]) != len(x):
        raise ValueError("matvec: shapes do not match")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    """The inner product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(a) -> float:
    """The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
    if _is_matrix(a):
        return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
    return math.sqrt(sum(float(x) * float(x) for x in a))


def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
    """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 skew(a: Sequence[float]) -> Matrix:
    """The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
    z = a[0] - a[0]
    return [[z, -a[2], a[1]],
            [a[2], z, -a[0]],
            [-a[1], a[0], z]]


# ---------------------------------------------------- Gaussian elimination

def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
    """Reduce [a | b] to upper triangular form with partial pivoting.

    Works in place on copies made by the caller. Returns a, b and the sign
    of the row permutation.
    """
    n = len(a)
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("singular matrix")
        if p != k:
            a[k], a[p] = a[p], a[k]
            b[k], b[p] = b[p], b[k]
            sign = -sign
        piv = a[k][k]
        for i in range(k + 1, n):
            f = a[i][k] / piv
            if f == 0:
                continue
            ai, ak = a[i], a[k]
            for j in range(k, n):
                ai[j] = ai[j] - f * ak[j]
            bi, bk = b[i], b[k]
            for j in range(len(bi)):
                bi[j] = bi[j] - f * bk[j]
    return a, b, sign


def solve(a: Sequence[Sequence[float]], b):
    """Solve a x = b for a square a, by Gaussian elimination with partial
    pivoting. b is a vector or a matrix (several right-hand sides); the
    result has the same form. Raises ValueError on an exact zero pivot."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("solve: matrix is not square")
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: shapes do not match")
    u, c, _ = _eliminate([list(row) for row in a], rhs)
    m = len(c[0]) if n else 0
    x = [[0.0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = c[i][j]
            for k in range(i + 1, n):
                s = s - u[i][k] * x[k][j]
            x[i][j] = s / u[i][i]
    return [row[0] for row in x] if vec else x


def inv(a: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of a square matrix. Raises ValueError if it is singular."""
    n = len(a)
    one = a[0][0] - a[0][0] + 1 if n else 1.0
    ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
    return solve(a, ident)


def det(a: Sequence[Sequence[float]]) -> float:
    """The determinant of a square matrix, by Gaussian elimination."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("det: matrix is not square")
    if n == 0:
        return 1.0
    try:
        u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
    except ValueError:
        return a[0][0] - a[0][0]
    d = u[0][0] - u[0][0] + sign
    for i in range(n):
        d = d * u[i][i]
    return d


# ------------------------------------------------------- Jacobi methods

def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
    """Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
    Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
    eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
    a is read (the lower triangle is taken as its mirror)."""
    n = len(a)
    s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
    v = eye(n)
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = s[p][q]
                if apq == 0.0:
                    continue
                app, aqq = s[p][p], s[q][q]
                if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
                        abs(apq) < 1e-300:
                    s[p][q] = s[q][p] = 0.0
                    continue
                rotated = True
                theta = (aqq - app) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                s[p][q] = s[q][p] = 0.0
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
        if not rotated:
            break
    order = sorted(range(n), key=lambda i: s[i][i])
    w = [s[i][i] for i in order]
    vs = [[v[k][i] for i in order] for k in range(n)]
    return w, vs


def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
    """Replace the columns with index in need by unit vectors orthogonal to
    all other columns (Gram-Schmidt on the standard basis)."""
    keep = [c for i, c in enumerate(cols) if i not in need]
    for i in need:
        best, best_norm = None, -1.0
        for e in range(m):
            x = [0.0] * m
            x[e] = 1.0
            for _ in range(2):
                for c in keep:
                    d = dot(c, x)
                    x = [xi - d * ci for xi, ci in zip(x, c)]
            nx = norm(x)
            if nx > best_norm:
                best, best_norm = x, nx
        u = [xi / best_norm for xi in best]
        cols[i] = u
        keep.append(u)


def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    m, n = len(a), len(a[0])
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                cp, cq = cols[p], cols[q]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cq)
                gamma = sum(x * y for x, y in zip(cp, cq))
                if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
                cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
                vp, vq = vcols[p], vcols[q]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
                vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
        if not rotated:
            break
    sv = [norm(c) for c in cols]
    order = sorted(range(n), key=lambda i: -sv[i])
    sv = [sv[i] for i in order]
    cols = [cols[i] for i in order]
    vcols = [vcols[i] for i in order]
    smax = sv[0] if sv else 0.0
    ucols: List[Vector] = []
    need: List[int] = []
    for i, c in enumerate(cols):
        if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
            ucols.append([x / sv[i] for x in c])
        else:
            ucols.append([0.0] * m)
            need.append(i)
    if need:
        _complete_basis(ucols, m, need)
    return transpose(ucols), sv, transpose(vcols)


def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    """Thin singular value decomposition by the one-sided Jacobi method.

    For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
    size m x k, S a list of k values in descending order and V of size
    n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
    For m >= n, V is square (n x n)."""
    m, n = len(a), len(a[0])
    if m >= n:
        return _svd_tall(a)
    u, s, v = _svd_tall(transpose(a))
    return v, s, u


def nullvec(a: Sequence[Sequence[float]]) -> Vector:
    """A unit vector x that minimizes ||a x||: the right singular vector of
    the smallest singular value. If a has fewer rows than columns, zero rows
    are added first, so the result is in the null space. The sign is not
    fixed."""
    m, n = len(a), len(a[0])
    rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
    _, _, v = _svd_tall(rows)
    return [v[i][n - 1] for i in range(n)]


# ---------------------------------------------- orthogonal factorizations

def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """QR factorization by Householder reflections. For an m x n matrix a,
    returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
    a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
    m, n = len(a), len(a[0])
    r = [[float(x) for x in row] for row in a]
    q = eye(m)
    for k in range(min(m - 1, n)):
        x = [r[i][k] for i in range(k, m)]
        nx = norm(x)
        if nx == 0.0:
            continue
        alpha = -nx if x[0] >= 0 else nx
        v = list(x)
        v[0] -= alpha
        nv = norm(v)
        if nv == 0.0:
            continue
        v = [vi / nv for vi in v]
        for j in range(n):
            d = sum(v[i - k] * r[i][j] for i in range(k, m))
            if d != 0.0:
                for i in range(k, m):
                    r[i][j] -= 2.0 * v[i - k] * d
        for i in range(m):
            d = sum(q[i][l] * v[l - k] for l in range(k, m))
            if d != 0.0:
                for l in range(k, m):
                    q[i][l] -= 2.0 * d * v[l - k]
    for k in range(min(m, n)):
        if r[k][k] < 0:
            r[k] = [-x for x in r[k]]
            for i in range(m):
                q[i][k] = -q[i][k]
    for i in range(m):
        for j in range(min(i, n)):
            r[i][j] = 0.0
    return q, r


def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """RQ factorization of a square matrix: returns R (upper triangular,
    with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
    from the QR factorization of the transpose of the row-reversed matrix."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("rq: matrix is not square")
    flipped = transpose([list(row) for row in reversed(a)])
    q1, r1 = qr(flipped)
    rt = transpose(r1)
    r = [list(reversed(row)) for row in reversed(rt)]
    q = [list(row) for row in reversed(transpose(q1))]
    return r, q


def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
    """The lower triangular L with a = L L^T, for a symmetric positive
    definite a. Raises ValueError if a pivot is not positive."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
        if d <= 0:
            raise ValueError("cholesky: matrix is not positive definite")
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return low


# ---------------------------------------------------------- polynomials

def _horner(c: Sequence[complex], x):
    p = 0.0
    for ci in c:
        p = p * x + ci
    return p


def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
    """Real roots of the polynomial with the given coefficients, highest
    power first. All complex roots are found by the Durand-Kerner method.
    A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
    part is then polished by Newton steps on the real polynomial. Returns
    the real roots in ascending order, with repeats for multiple roots."""
    c = [float(x) for x in coeffs]
    while c and c[0] == 0.0:
        c.pop(0)
    n = len(c) - 1
    if n < 1:
        return []
    c = [x / c[0] for x in c]
    rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
    if rho == 0.0:
        return [0.0] * n
    z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
    for _ in range(2000):
        moved = 0.0
        for k in range(n):
            den = 1.0 + 0j
            for j in range(n):
                if j != k:
                    den *= z[k] - z[j]
            if den == 0:
                den = 1e-12 * rho
            step = _horner(c, z[k]) / den
            z[k] -= step
            moved = max(moved, abs(step) / max(1.0, abs(z[k])))
        if moved <= 1e-15:
            break
    deriv = [c[i] * (n - i) for i in range(n)]
    roots = []
    for zk in z:
        if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
            continue
        x = zk.real
        px = _horner(c, x)
        for _ in range(8):
            dp = _horner(deriv, x)
            if dp == 0.0 or px == 0.0:
                break
            xn = x - px / dp
            pn = _horner(c, xn)
            if abs(pn) >= abs(px):
                break
            x, px = xn, pn
        roots.append(x)
    return sorted(roots)


# ------------------------------------------------------------ self-test

def self_test() -> None:
    """Check svd, sym_eig and polyroots_real. Raises AssertionError."""
    import random
    rng = random.Random(7)
    for _ in range(3):
        a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
        u, s, v = svd(a)
        rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
        assert norm(sub(rec, a)) <= 1e-10
        assert all(s[i] >= s[i + 1] for i in range(4))
        sym = add(a, transpose(a))
        w, vv = sym_eig(sym)
        rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
        assert norm(sub(rec, sym)) <= 1e-10
        assert all(w[i] <= w[i + 1] for i in range(4))
    r = polyroots_real([1.0, -6.0, 11.0, -6.0])
    assert len(r) == 3
    assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))


if __name__ == "__main__":
    self_test()
lie_algebraic_rotation_averaging.py 168 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lie-algebraic-rotation-averaging/. The authors are listed in prov/XFRXH0.jsonl.

"""Lie-algebraic rotation averaging (Govindu; Chatterjee and Govindu).

There are N absolute rotations R_0, ..., R_(N-1) to find and a list of
edges (i, j, R_ij), each a measurement of the relative rotation
R_ij ~ R_j R_i^T. The residual of an edge is the rotation vector
r_ij = log(R_j^T R_ij R_i), which is zero when the edge agrees with the
estimate. Each iteration linearizes r_ij - w_j + w_i for the update
R_k <- R_k exp([w_k]_x), solves the weighted least squares problem in the
w_k (a graph Laplacian system with w_0 = 0) and applies the update.

The weights give the cost: "l2" weights 1 (the squared geodesic cost),
"l1" weights 1 / max(||r||, delta) (the sum of geodesic distances, by
iteratively reweighted least squares) and "gm" weights
sigma^2 / (||r||^2 + sigma^2)^2 (the Geman-McClure cost).
"""

import math
from collections import deque
from typing import Dict, List, Sequence, Tuple

from cvla import mul, solve, transpose

Vector = List[float]
Matrix = List[List[float]]
Edge = Tuple[int, int, Matrix]


def so3_exp(w: Sequence[float]) -> Matrix:
    """exp([w]_x) by the Rodrigues formula."""
    th = math.sqrt(w[0] * w[0] + w[1] * w[1] + w[2] * w[2])
    if th < 1e-8:
        a, b = 1.0 - th * th / 6.0, 0.5 - th * th / 24.0
    else:
        a, b = math.sin(th) / th, (1.0 - math.cos(th)) / (th * th)
    x, y, z = w
    k = [[0.0, -z, y], [z, 0.0, -x], [-y, x, 0.0]]
    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: Sequence[Sequence[float]]) -> Vector:
    """The rotation vector w with exp([w]_x) = R and ||w|| <= pi."""
    c = max(-1.0, min(1.0, (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0))
    v = [r[2][1] - r[1][2], r[0][2] - r[2][0], r[1][0] - r[0][1]]
    th = math.acos(c)
    if th < 1e-6:
        return [x * (0.5 + th * th / 12.0) for x in v]
    if th < math.pi - 1e-4:
        return [x * th / (2.0 * math.sin(th)) for x in v]
    # near pi: (R + R^T)/2 - cos(th) I = (1 - cos(th)) a a^T
    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)]
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    nc = math.sqrt(sum(x * x for x in col))
    a = [x / nc for x in col]
    if sum(x * y for x, y in zip(a, v)) < 0:
        a = [-x for x in a]
    return [th * x for x in a]


def angle(r1: Sequence[Sequence[float]], r2: Sequence[Sequence[float]]) -> float:
    """The angle of R1^T R2, in radians."""
    tr = sum(r1[k][i] * r2[k][i] for i in range(3) for k in range(3))
    return math.acos(max(-1.0, min(1.0, (tr - 1.0) / 2.0)))


def residual(rots: Sequence[Matrix], e: Edge) -> Vector:
    """r_ij = log(R_j^T R_ij R_i)."""
    i, j, rij = e
    return so3_log(mul(mul(transpose(rots[j]), rij), rots[i]))


def tree_init(n: int, edges: Sequence[Edge], root: int = 0) -> List[Matrix]:
    """Rotations from a breadth-first spanning tree: R_root = I and
    R_j = R_ij R_i along tree edges. Raises ValueError if the graph is not
    connected."""
    adj: Dict[int, List[Tuple[int, Matrix]]] = {k: [] for k in range(n)}
    for i, j, rij in edges:
        adj[i].append((j, rij))
        adj[j].append((i, transpose(rij)))
    rots: List = [None] * n
    rots[root] = [[1.0 if a == b else 0.0 for b in range(3)] for a in range(3)]
    queue = deque([root])
    while queue:
        i = queue.popleft()
        for j, rij in adj[i]:
            if rots[j] is None:
                rots[j] = mul(rij, rots[i])
                queue.append(j)
    if any(r is None for r in rots):
        raise ValueError("tree_init: the view graph is not connected")
    return rots


def weight(rnorm: float, loss: str, sigma: float, delta: float) -> float:
    """The IRLS weight psi(||r||) / ||r|| of a residual norm."""
    if loss == "l2":
        return 1.0
    if loss == "l1":
        return 1.0 / max(rnorm, delta)
    if loss == "gm":
        return sigma * sigma / (rnorm * rnorm + sigma * sigma) ** 2
    raise ValueError("unknown loss " + loss)


def laplacian_system(n: int, edges: Sequence[Edge], res: Sequence[Vector],
                     wts: Sequence[float]) -> Tuple[Matrix, Matrix]:
    """The grounded weighted Laplacian (node 0 removed) and the right-hand
    sides b_k = sum over edges (i, k) of w r - sum over edges (k, j) of w r."""
    lap = [[0.0] * n for _ in range(n)]
    b = [[0.0] * 3 for _ in range(n)]
    for (i, j, _), r, w in zip(edges, res, wts):
        lap[i][i] += w
        lap[j][j] += w
        lap[i][j] -= w
        lap[j][i] -= w
        for a in range(3):
            b[j][a] += w * r[a]
            b[i][a] -= w * r[a]
    return [row[1:] for row in lap[1:]], b[1:]


def lie_algebraic_rotation_averaging(n: int, edges: Sequence[Edge], loss: str = "l2",
                                     init: Sequence[Matrix] = None, sigma: float = 0.1,
                                     delta: float = 1e-6, max_iter: int = 100,
                                     eps: float = 1e-12) -> Tuple[List[Matrix], int]:
    """Average the relative rotations. Returns (R, iterations); R_0 = I
    unless init says otherwise."""
    rots = [list(map(list, r)) for r in init] if init is not None else tree_init(n, edges)  # @line L1
    it = 0
    for it in range(1, max_iter + 1):  # @line L2
        res = [residual(rots, e) for e in edges]  # @line L3
        wts = [weight(math.sqrt(sum(x * x for x in r)), loss, sigma, delta) for r in res]  # @line L4
        lap, b = laplacian_system(n, edges, res, wts)  # @line L5
        omega = [[0.0, 0.0, 0.0]] + solve(lap, b)
        rots = [mul(r, so3_exp(w)) for r, w in zip(rots, omega)]  # @line L6
        if max(math.sqrt(sum(x * x for x in w)) for w in omega) < eps:  # @line L7
            break
    return rots, it  # @line L8


def robust_rotation_averaging(n: int, edges: Sequence[Edge], sigma: float = 0.1,
                              l1_iter: int = 30, gm_iter: int = 30) -> List[Matrix]:
    """A robust run in the style of Chatterjee and Govindu: a few l1
    iterations from the tree start, then Geman-McClure iterations."""
    rots, _ = lie_algebraic_rotation_averaging(n, edges, loss="l1", max_iter=l1_iter, eps=1e-9)
    rots, _ = lie_algebraic_rotation_averaging(n, edges, loss="gm", init=rots, sigma=sigma,
                                               max_iter=gm_iter, eps=1e-10)
    return rots


def cost(rots: Sequence[Matrix], edges: Sequence[Edge], loss: str = "l2",
         sigma: float = 0.1) -> float:
    """sum ||r||^2 (l2), sum ||r|| (l1) or sum ||r||^2 / (||r||^2 + sigma^2) (gm)."""
    total = 0.0
    for e in edges:
        r = residual(rots, e)
        s = sum(x * x for x in r)
        if loss == "l2":
            total += s
        elif loss == "l1":
            total += math.sqrt(s)
        else:
            total += s / (s + sigma * sigma)
    return total
test_lie_algebraic_rotation_averaging.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lie-algebraic-rotation-averaging/. The authors are listed in prov/XFRXH0.jsonl.

import math
import random

import pytest

from cvla import mul, transpose
from lie_algebraic_rotation_averaging import (angle, cost, laplacian_system,
                                              lie_algebraic_rotation_averaging, residual,
                                              robust_rotation_averaging, so3_exp, so3_log,
                                              tree_init)


def random_rot(rng):
    w = [rng.gauss(0, 1) for _ in range(3)]
    n = math.sqrt(sum(x * x for x in w))
    return so3_exp([x / n * rng.uniform(0, math.pi) for x in w])


def make_problem(seed, n=12, p=0.5, noise=0.0, outliers=0.0):
    rng = random.Random(seed)
    rots = [random_rot(rng) for _ in range(n)]
    edges = [(k, k + 1) for k in range(n - 1)]
    edges += [(i, j) for i in range(n) for j in range(i + 2, n) if rng.random() < p]
    out = []
    for i, j in edges:
        rij = mul(rots[j], transpose(rots[i]))
        if rng.random() < outliers:
            rij = random_rot(rng)
        elif noise > 0:
            rij = mul(so3_exp([rng.gauss(0, noise) for _ in range(3)]), rij)
        out.append((i, j, rij))
    return rots, out


def relative_error(est, true):
    """The largest angle between R_j R_i^T of the estimate and of the truth."""
    worst = 0.0
    for i in range(len(true)):
        for j in range(i + 1, len(true)):
            a = mul(est[j], transpose(est[i]))
            b = mul(true[j], transpose(true[i]))
            worst = max(worst, angle(a, b))
    return worst


def test_exp_and_log_are_inverse():
    rng = random.Random(1)
    for _ in range(50):
        w = [rng.gauss(0, 1) for _ in range(3)]
        n = math.sqrt(sum(x * x for x in w))
        th = rng.uniform(0, math.pi - 1e-3)
        w = [x / n * th for x in w]
        assert max(abs(a - b) for a, b in zip(so3_log(so3_exp(w)), w)) < 1e-8
    w = [0.0, math.pi - 1e-6, 0.0]
    assert max(abs(a - b) for a, b in zip(so3_log(so3_exp(w)), w)) < 1e-5


def test_exact_data_is_recovered_up_to_the_gauge():
    true, edges = make_problem(2)
    est, it = lie_algebraic_rotation_averaging(len(true), edges)
    # acos near 1 limits the angle to about 1e-8
    assert relative_error(est, true) < 1e-7
    assert it <= 2


def test_gradient_is_minus_two_b():
    true, edges = make_problem(3, n=6, noise=0.2)
    rots = tree_init(6, edges)
    res = [residual(rots, e) for e in edges]
    _, b = laplacian_system(6, edges, res, [1.0] * len(edges))
    h = 1e-6
    for k in range(1, 6):
        for a in range(3):
            d = [0.0, 0.0, 0.0]
            d[a] = h
            plus = [mul(r, so3_exp(d)) if m == k else r for m, r in enumerate(rots)]
            d[a] = -h
            minus = [mul(r, so3_exp(d)) if m == k else r for m, r in enumerate(rots)]
            fd = (cost(plus, edges) - cost(minus, edges)) / (2 * h)
            assert abs(fd + 2 * b[k - 1][a]) < 1e-5


def test_l2_reaches_a_stationary_point_below_the_tree_start():
    true, edges = make_problem(4, n=15, noise=0.05)
    start = tree_init(15, edges)
    est, it = lie_algebraic_rotation_averaging(15, edges, max_iter=50, eps=1e-11)
    assert it < 50
    assert cost(est, edges) < cost(start, edges)
    res = [residual(est, e) for e in edges]
    _, b = laplacian_system(15, edges, res, [1.0] * len(edges))
    assert max(abs(x) for row in b for x in row) < 1e-9
    assert relative_error(est, true) < 0.15


def test_robust_cost_handles_outliers():
    true, edges = make_problem(5, n=15, p=0.6, noise=0.01, outliers=0.15)
    l2, _ = lie_algebraic_rotation_averaging(15, edges, max_iter=50)
    robust = robust_rotation_averaging(15, edges, sigma=0.05)
    assert relative_error(robust, true) < 0.1
    assert relative_error(l2, true) > 3 * relative_error(robust, true)


def test_disconnected_graph_is_rejected():
    _, edges = make_problem(6, n=5)
    with pytest.raises(ValueError):
        tree_init(7, edges)

History

Govindu (2001) combined the relative motions of many image pairs into consistent global motions, and in 2004 he formulated the averaging in the Lie algebra and gave the iterative scheme on this page, for rotations and for full motions. Martinec and Pajdla (2007) proposed a linear method for the rotations based on the chordal distance. Hartley, Aftab and Trumpf (2011) gave the Weiszfeld method for L1L_1 averaging, and Hartley, Trumpf, Dai and Li (2013) surveyed the field. Chatterjee and Govindu (2013) combined an L1L_1 start with reweighted least squares for large scale robust averaging, and extended the analysis of the robust costs in their 2018 journal paper.

References

  1. Venu Madhav Govindu, Lie-algebraic averaging for globally consistent motion estimation, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2004), vol. 1, 684-691, the whole paper (the averaging of relative motions in the Lie algebra, the linear update and the iteration)
  2. Venu Madhav Govindu, Combining two-view constraints for motion estimation, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2001), vol. 2, 218-225, the averaging of relative rotations over a graph of views
  3. Avishek Chatterjee and Venu Madhav Govindu, Efficient and robust large-scale rotation averaging, IEEE International Conference on Computer Vision (ICCV 2013), 521-528, the whole paper (the L1 averaging in the Lie algebra and the reweighted refinement)
  4. Avishek Chatterjee and Venu Madhav Govindu, Robust relative rotation averaging, IEEE Transactions on Pattern Analysis and Machine Intelligence 40(4), 2018, 958-972, the robust cost functions, the iteratively reweighted least squares method and the experiments
  5. Richard Hartley, Jochen Trumpf, Yuchao Dai and Hongdong Li, Rotation averaging, International Journal of Computer Vision 103(3), 2013, 267-305, the sections on the Lie-algebraic and the L1 methods for multiple rotation averaging

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_iteration
  • a full proof of time.total
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example