Algorithm Search⌘K

Algorithmresearch

TEASER

Also called truncated least squares estimation and semidefinite relaxation.

Registration from putative matches with most of them wrong: it solves scale, rotation and translation in turn under a truncated least squares cost, with exact voting, a maximum clique and an SDP.

Time
O(3^(m/3) + N m^2) worst · averageΘ(m^2) best
Space
Θ(m^2) extra
Where
N = the number of GNC iterations; m = the number of correspondences
Properties
deterministicnot exactofflineiterative
Origin
Heng Yang, Jingnan Shi, Luca Carlone, 2021

TEASER registers two point clouds from a list of putative correspondences, such as the matches of feature descriptors, when most of the matches are wrong. It needs no start pose. It uses the truncated least squares (TLS) cost, which counts each match by its squared error up to a cap, so an outlier costs a fixed amount however far away it is. The method splits the problem into three smaller ones. Differences of pairs of matches do not depend on the translation, and their lengths do not depend on the rotation either. TEASER first estimates the scale from the ratios of lengths by adaptive voting, an exact solver for one-dimensional TLS. It then keeps only the matches in a maximum clique of a graph of pairs that agree with this scale. It solves the rotation from the surviving differences by a semidefinite relaxation, and it can check a certificate that the rotation is the global TLS optimum. Last, it finds the translation by adaptive voting on each axis. TEASER++ replaces the relaxation with graduated non-convexity (GNC), which is faster but has no guarantee, and checks the result afterwards.

In plain words

You have a list of guessed matches between two scans, and most guesses are wrong. Take any two matches. If both are right, the distance between the two points in the first scan, times the scale, is about the same as the distance between their partners in the second scan, however the scan is turned or moved.

So first find the scale that the most pairs agree on. Then draw a line between every two matches that agree with this scale. Right matches all agree with each other, so they form a group in which everyone is joined to everyone. Find the largest such group and throw away the rest.

Now most of the wrong matches are gone. Find the turn that best fits the matches that are left, while still letting a few bad ones count only a fixed amount. Then find the shift.

The problem

Input. Points a1,…,ama_1, \ldots, a_m and b1,…,bmb_1, \ldots, b_m in R3\mathbb{R}^3, where (ai,bi)(a_i, b_i) is a putative correspondence; a noise bound β>0\beta > 0; and a cap cˉ>0\bar c > 0, usually 1. The model is

bi=sRai+t+oi+ϵi,∣ϵi∣≤β,b_i = s R a_i + t + o_i + \epsilon_i, \qquad |\epsilon_i| \le \beta ,

with a scale s>0s > 0, a rotation R∈SO(3)R \in SO(3) and a translation tt. The match ii is an inlier when oi=0o_i = 0; for an outlier, oio_i is arbitrary.

Output. An estimate (s^,R^,t^)(\hat s, \hat R, \hat t) that minimizes the TLS cost

∑i=1mmin⁡(∣bi−sRai−t∣2β2,cˉ2).\sum_{i=1}^{m} \min\left(\frac{|b_i - s R a_i - t|^2}{\beta^2}, \bar c^2\right).

TEASER does not minimize this cost jointly. It minimizes a TLS cost for each of the three unknowns in turn, on the invariant measurements below. The scale can also be known, which is the usual case for two scans of the same scene. This is a form of point cloud registration and of robust model fitting.

The algorithm

For a pair i<ji < j, the translation invariant measurement (TIM) is aˉij=aj−ai\bar a_{ij} = a_j - a_i and bˉij=bj−bi\bar b_{ij} = b_j - b_i. For two inliers, bˉij=sRaˉij+ϵj−ϵi\bar b_{ij} = s R \bar a_{ij} + \epsilon_j - \epsilon_i, so the translation is gone and the noise bound is 2β2\beta. The translation and rotation invariant measurement (TRIM) is the ratio sij=∣bˉij∣/∣aˉij∣s_{ij} = |\bar b_{ij}| / |\bar a_{ij}|; for two inliers it lies within αij=2β/∣aˉij∣\alpha_{ij} = 2\beta / |\bar a_{ij}| of ss.

Adaptive voting solves the scalar problem: minimize ∑kmin⁡((x−vk)2/bk2,cˉ2)\sum_k \min((x - v_k)^2 / b_k^2, \bar c^2) over xx. Each value vkv_k is an inlier of xx on the interval [vk−cˉbk,vk+cˉbk][v_k - \bar c b_k, v_k + \bar c b_k]. Sort the 2K2K interval ends. Between two consecutive ends the set of inliers is fixed, and the best xx for a fixed set is its weighted mean, with weights 1/bk21 / b_k^2. Adaptive voting computes the cost of every such piece and returns the best one.

  1. TEASER(A, B, β, c̄) ▷ pairs (a_i, b_i), i = 1 .. m, noise bound β
  2. 1for each pair i < j: ā_ij ← a_j - a_i ; b̄_ij ← b_j - b_i
  3. 2s_ij ← |b̄_ij| / |ā_ij| ; α_ij ← 2β / |ā_ij|
  4. 3ŝ ← ADAPTIVE-VOTING({s_ij}, {α_ij}, c̄) ▷ or the known scale
  5. 4E ← {(i, j) : |s_ij - ŝ| ≤ c̄ α_ij}
  6. 5C ← MAX-CLIQUE({1 .. m}, E)
  7. 6R̂ ← TLS rotation from the TIMs (ŝ ā_ij, b̄_ij) with i, j in C, bound 2β
  8. 7for each axis d: t̂_d ← ADAPTIVE-VOTING({(b_i - ŝ R̂ a_i)_d : i in C}, β, c̄)
  9. 8return ŝ, R̂, t̂

Lines L1 and L2 form all m(m−1)/2m(m-1)/2 TIMs and TRIMs. Line L3 estimates the scale by adaptive voting over the TRIMs. Line L4 builds the consistency graph: a pair is an edge when its ratio agrees with the scale. Line L5 keeps a maximum clique of this graph; the reference code uses Bron-Kerbosch with a pivot and a size bound. Line L6 solves the rotation. TEASER writes the rotation TLS problem with binary variables and a unit quaternion, relaxes it to a semidefinite program, and reads the rotation from the solution; a dual certificate then shows whether the relaxation was tight, which means the rotation is the global TLS optimum. TEASER++ and the reference code use GNC instead: they replace the TLS cost by a smooth surrogate controlled by a value μ\mu, solve a weighted Wahba problem by the SVD, update the weights from the residuals, and make the surrogate closer to TLS by μ←1.4μ\mu \leftarrow 1.4 \mu until the weights are all 0 or 1. Line L7 solves the translation one coordinate at a time by adaptive voting.

Example

First, adaptive voting alone. Take the values 1.0, 1.1, 0.9, 3.0 and 5.0, all with the bound 0.2, and cˉ=1\bar c = 1. The intervals are [0.8,1.2][0.8, 1.2], [0.9,1.3][0.9, 1.3], [0.7,1.1][0.7, 1.1], [2.8,3.2][2.8, 3.2] and [4.8,5.2][4.8, 5.2]. The sorted ends give 7 pieces with a nonempty inlier set, below the limit 2K−1=92K - 1 = 9.

piece inliers weighted mean cost
(0.7, 0.8) 0.9 0.9 4
(0.8, 0.9) 1.0, 0.9 0.95 3.125
(0.9, 1.1) 1.0, 1.1, 0.9 1.0 2.5
(1.1, 1.2) 1.0, 1.1 1.05 3.125
(1.2, 1.3) 1.1 1.1 4
(2.8, 3.2) 3.0 3.0 4
(4.8, 5.2) 5.0 5.0 4

The best piece gives x=1.0x = 1.0 with cost 2.5: three values fit, and the two others each pay the cap 1. The plain mean of the five values is 2.2, which no value supports.

Second, the whole method with the scale known. Random points in the cube [−1,1]3[-1, 1]^3 are turned by a random rotation, moved, and given Gaussian noise with standard deviation 0.005; then most of the matches are replaced by random points. The noise bound is β=0.03\beta = 0.03.

mm outliers TIMs edges kept inlier edges kept clique rotation error translation error
20 12 190 30 28 of 28 8, all inliers 0.26° 0.0016
60 51 1770 72 36 of 36 9, all inliers 0.19° 0.0011
100 90 4950 168 45 of 45 10, all inliers 0.31° 0.0035

With 90% outliers, the pruning keeps under 4% of the pairs, every inlier pair survives as the proof promises, and the maximum clique is exactly the set of inliers. The rotation and translation from the clique are then within the noise.

Correctness

Two steps are exact. First, adaptive voting returns a global minimizer of the scalar TLS cost. A minimizer x⋆x^\star exists and has cost below Kcˉ2K \bar c^2, so it lies inside some interval. Just to the left of x⋆x^\star there is a piece whose inlier set SS gives exactly the cost of x⋆x^\star. The weighted mean of SS is at least as good for the quadratic cost of SS, and the TLS cost is never above that quadratic cost. So the best piece is as good as x⋆x^\star. Second, every pair of inliers passes the test of line L4 when the scale is right: ∣∣bˉij∣−s∣aˉij∣∣≤∣bˉij−sRaˉij∣≤2β\big| |\bar b_{ij}| - s |\bar a_{ij}| \big| \le |\bar b_{ij} - s R \bar a_{ij}| \le 2\beta. So the inliers form a clique, and the maximum clique is at least as large. The full proof is in proofs/correctness.md.

The other steps have weaker claims. The maximum clique can still hold outliers. The semidefinite relaxation is not always tight; when it is, the certificate proves global optimality of the rotation, and the paper gives conditions under which it is tight. GNC has no guarantee. The paper also bounds the error of the estimate in terms of β\beta, under conditions on the inliers.

Proof: Adaptive voting is exact, and the inliers survive the pruningfull

We use the notation of the page. There are mm correspondences (ai,bi)(a_i, b_i) with bi=sRai+t+oi+ϵib_i = s R a_i + t + o_i + \epsilon_i, where oi=0o_i = 0 and ∣ϵi∣≤β|\epsilon_i| \le \beta for an inlier ii, and oio_i is arbitrary for an outlier. We prove two exact parts of the method. The rotation step of the reference code (GNC) is a heuristic, and we claim nothing for it; the semidefinite relaxation and the certificate of TEASER are covered by the theorems of the paper, which this file does not repeat.

Part 1: adaptive voting solves the scalar TLS problem

Let v1,…,vKv_1, \ldots, v_K be real values with bounds bk>0b_k > 0, and let cˉ>0\bar c > 0. The scalar truncated least squares cost is

f(x)=∑k=1Kmin⁡((x−vk)2bk2,cˉ2).f(x) = \sum_{k=1}^{K} \min\left(\frac{(x - v_k)^2}{b_k^2}, \bar c^2\right).

For a set S⊆{1,…,K}S \subseteq \{1, \ldots, K\} define gS(x)=∑k∈S(x−vk)2/bk2+(K−∣S∣) cˉ2g_S(x) = \sum_{k \in S} (x - v_k)^2 / b_k^2 + (K - |S|)\, \bar c^2, and for S≠∅S \ne \emptyset let xˉS=∑k∈Svkbk−2/∑k∈Sbk−2\bar x_S = \sum_{k \in S} v_k b_k^{-2} / \sum_{k \in S} b_k^{-2} be the weighted mean, the unique minimizer of gSg_S.

The interval of kk is Ik=[vk−cˉbk,vk+cˉbk]I_k = [v_k - \bar c b_k, v_k + \bar c b_k], where the kk-th term of ff is below its cap. Sort the 2K2K ends. They cut the line into open pieces. On each piece of positive length, the set SS of the intervals that contain the piece is fixed. Adaptive voting computes gS(xˉS)g_S(\bar x_S) for every piece with S≠∅S \ne \emptyset and returns the xˉS\bar x_S of least value.

Claim 1. The returned x^\hat x is a global minimizer of ff.

Proof. (i) For every SS and xx, f(x)≤gS(x)f(x) \le g_S(x), because each term of ff is at most its quadratic term and at most cˉ2\bar c^2.

(ii) ff is continuous and tends to Kcˉ2K \bar c^2 far from all vkv_k, while f(v1)≤(K−1)cˉ2<Kcˉ2f(v_1) \le (K - 1)\bar c^2 < K \bar c^2. So ff has a global minimizer x⋆x^\star, and f(x⋆)<Kcˉ2f(x^\star) < K \bar c^2. Hence x⋆x^\star lies in the interior of some interval: if every IkI_k had x⋆x^\star outside or at an end, every term would equal cˉ2\bar c^2.

(iii) Since x⋆x^\star is not the least end of all intervals that contain it, take ε>0\varepsilon > 0 so small that no end lies in (x⋆−ε,x⋆)(x^\star - \varepsilon, x^\star). This open set lies in one piece of positive length; let SS be its set. For k∈Sk \in S, IkI_k contains (x⋆−ε,x⋆)(x^\star - \varepsilon, x^\star), and since IkI_k is closed, x⋆∈Ikx^\star \in I_k, so the kk-th term of f(x⋆)f(x^\star) is (x⋆−vk)2/bk2(x^\star - v_k)^2 / b_k^2. For k∉Sk \notin S, IkI_k does not meet (x⋆−ε,x⋆)(x^\star - \varepsilon, x^\star), so either x⋆∉Ikx^\star \notin I_k or x⋆x^\star is the left end of IkI_k; in both cases the kk-th term is cˉ2\bar c^2. So f(x⋆)=gS(x⋆)f(x^\star) = g_S(x^\star). The set SS is not empty, because x⋆x^\star is interior to some interval, and that interval contains a left neighborhood of x⋆x^\star.

(iv) Then f(x⋆)=gS(x⋆)≥gS(xˉS)≥min⁡piecesgS′(xˉS′)=gS^(x^)≥f(x^)f(x^\star) = g_S(x^\star) \ge g_S(\bar x_S) \ge \min_{\text{pieces}} g_{S'}(\bar x_{S'}) = g_{\hat S}(\hat x) \ge f(\hat x), using (i) last. So f(x^)≤f(x⋆)f(\hat x) \le f(x^\star), and x^\hat x is a global minimizer. □\square

The number of pieces with a nonempty set is at most 2K−12K - 1, the number of gaps between 2K2K sorted ends. The reference code keeps the running sums ∑bk−2\sum b_k^{-2}, ∑vkbk−2\sum v_k b_k^{-2} and ∑vk2bk−2\sum v_k^2 b_k^{-2} over the current set, so gS(xˉS)=∑vk2bk−2−(∑vkbk−2)2/∑bk−2+(K−∣S∣)cˉ2g_S(\bar x_S) = \sum v_k^2 b_k^{-2} - (\sum v_k b_k^{-2})^2 / \sum b_k^{-2} + (K - |S|)\bar c^2 costs O(1)O(1) per piece, and the whole sweep costs O(Klog⁡K)O(K \log K) for the sort.

Part 2: inlier pairs survive the pruning

For i<ji < j let aˉij=aj−ai\bar a_{ij} = a_j - a_i and bˉij=bj−bi\bar b_{ij} = b_j - b_i, with aˉij≠0\bar a_{ij} \ne 0, and let δ=2β\delta = 2\beta, sij=∣bˉij∣/∣aˉij∣s_{ij} = |\bar b_{ij}| / |\bar a_{ij}| and αij=δ/∣aˉij∣\alpha_{ij} = \delta / |\bar a_{ij}|.

Claim 2. If ii and jj are both inliers, then ∣sij−s∣≤αij|s_{ij} - s| \le \alpha_{ij}, where ss is the true scale. So with the known scale and cˉ≥1\bar c \ge 1, the edge (i,j)(i, j) passes the test of line L4, and the inliers form a clique of the pruned graph. In particular a maximum clique has at least as many vertices as there are inliers.

Proof. For inliers, bˉij=sRaˉij+(ϵj−ϵi)\bar b_{ij} = s R \bar a_{ij} + (\epsilon_j - \epsilon_i): the translation cancels. By the triangle inequality and since ∣Raˉij∣=∣aˉij∣|R \bar a_{ij}| = |\bar a_{ij}|,

∣ ∣bˉij∣−s∣aˉij∣ ∣≤∣bˉij−sRaˉij∣=∣ϵj−ϵi∣≤2β=δ.\big|\, |\bar b_{ij}| - s |\bar a_{ij}| \,\big| \le |\bar b_{ij} - s R \bar a_{ij}| = |\epsilon_j - \epsilon_i| \le 2\beta = \delta .

Divide by ∣aˉij∣|\bar a_{ij}| to get ∣sij−s∣≤αij≤cˉ αij|s_{ij} - s| \le \alpha_{ij} \le \bar c\, \alpha_{ij}. Every pair of inliers is joined, so the inliers form a clique. □\square

What the claims do not say.

  • With an unknown scale, the test uses the estimate s^\hat s of line L3, not ss. Claim 1 shows that s^\hat s minimizes the TLS cost of the ratios, but it can differ from ss, and then an inlier edge can fail the test. The paper bounds the error of s^\hat s under conditions on the inliers; this file does not.
  • A maximum clique can hold outliers, or, in rare cases, be a set of outliers larger than the set of inliers. Line L5 keeps the maximum clique as a strong filter, not as a proof that it is the inlier set. The rotation step must still be robust, which is why it uses the TLS cost.
  • The rotation step of the reference code uses graduated non-convexity. It often finds the global TLS minimizer, but it has no guarantee. TEASER instead solves a semidefinite relaxation of the rotation TLS problem and checks a certificate of optimality.

Complexity

The model is the real RAM. Lines L1 and L2 take Θ(m2)\Theta(m^2) time. Adaptive voting on KK values sorts 2K2K ends and sweeps them with running sums, O(Klog⁡K)O(K \log K); on the TRIMs this is O(m2log⁡m)O(m^2 \log m), and with a known scale line L3 costs nothing. Line L4 takes Θ(m2)\Theta(m^2). Line L5 solves an NP-hard problem; Bron-Kerbosch with a pivot takes O(3m/3)O(3^{m/3}) time in the worst case, but the consistency graph is sparse after pruning, and practical clique solvers are fast on it. Each GNC iteration of line L6 solves a 3×33 \times 3 SVD over at most m(m−1)/2m(m-1)/2 TIMs, so NN iterations take O(Nm2)O(N m^2). Line L7 takes O(mlog⁡m)O(m \log m). The front matter states the cost with the known scale; the unknown scale adds O(m2log⁡m)O(m^2 \log m). The space is Θ(m2)\Theta(m^2) for the TIMs and the graph.

The semidefinite program of TEASER has a matrix of side 4(K+1)4(K + 1), where KK is the number of TIMs it uses, so its cost grows fast with KK. This is why TEASER++ uses GNC and checks optimality afterwards with a cheaper certifier.

Properties

  • Needs no start pose. All steps are global; no step starts from a guess of the pose.
  • Robust to very high outlier rates. The paper reports correct results with more than 99% outliers in its benchmarks. This is a measured result, not a bound.
  • Certifiable. TEASER can prove that its rotation is the global TLS optimum when the relaxation is tight. TEASER++ checks the GNC result with the certifier.
  • Decoupled. Scale, rotation and translation are found one at a time. The translation does not affect the TIMs, and neither translation nor rotation affects the TRIMs.
  • Needs a noise bound. The user must give β\beta. The method uses it to decide what is an inlier.
  • Needs correspondences. TEASER does not look for matches; it only sorts good matches from bad ones.
  • Deterministic. The same input gives the same output, unlike RANSAC.

Variants and improvements

  • TEASER++. GNC for the rotation, a fast parallel maximum clique solver, and a separate certifier. It is the form most people use.
  • Known scale. Skip line L3 and prune with ss. The reference code does this when the scale is given.
  • Without the clique. Line L5 can be skipped, so the rotation step sees all TIMs that pass line L4. The clique step costs time, but it removes most outliers before the rotation step, which is the slowest and the least robust step.
  • Other robust costs. The same split into invariant measurements works with other robust costs in place of TLS, but adaptive voting and the certificate are specific to TLS.

When to use it

Use TEASER or TEASER++ for global registration from feature matches when many of the matches are wrong, for example in loop closure or object pose estimation from 3D descriptors, and when a guarantee or a check of the result matters. With a few hundred matches it is fast; with many thousands the Θ(m2)\Theta(m^2) pairs and the clique step become costly, so keep only the best matches first. When most matches are good, RANSAC or fast global registration are simpler. When no matches exist, use a method that searches over poses, such as Go-ICP or 4-points congruent sets. Refine the result with ICP on the full clouds, because TEASER uses only the matched points.

Pitfalls

  • A bad noise bound. If β\beta is too small, true inlier pairs fail line L4, the clique breaks up, and the method fails. If β\beta is too large, many outlier pairs pass, and the clique grows with outliers. Set β\beta from the sensor noise and the descriptor accuracy, in the units of the points.
  • Symmetric scenes. If the scene has a symmetry, a set of wrong matches can be as consistent as the right ones, and the largest clique can be the wrong one. No method that uses only the matches can tell them apart.
  • Too few inliers. The rotation needs at least three inliers that are not on one line. With fewer, the clique is too small to fix the rotation.
  • Close points. A pair with a short ∣aˉij∣|\bar a_{ij}| has a large bound αij\alpha_{ij}, so it agrees with almost any scale and adds weak edges. The reference code skips pairs with ∣aˉij∣=0|\bar a_{ij}| = 0.
  • The clique as the answer. The clique is a filter, not a proof that its members are inliers. The rotation step must still use a robust cost.
  • Trusting GNC. GNC can fail without notice. Use the certifier when the result matters.

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()
teaser_registration.py 223 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/teaser-registration/. The authors are listed in prov/E0TQ57.jsonl.
"""TEASER registration (Yang, Shi and Carlone, IEEE T-RO 2021), in the
TEASER++ form.

Input: m putative correspondences (a_i, b_i) in R^3 with the model
b_i = s R a_i + t + o_i + eps_i, where |eps_i| <= beta for the inliers and
o_i is an arbitrary error for the outliers. The cost is truncated least
squares (TLS): sum_i min(r_i^2 / beta^2, cbar^2).

The steps:
1. Translation invariant measurements (TIMs): abar_ij = a_j - a_i and
   bbar_ij = b_j - b_i, with the noise bound delta_ij = 2 beta.
2. Translation and rotation invariant measurements (TRIMs): the ratios
   s_ij = |bbar_ij| / |abar_ij| with the bounds alpha_ij = delta_ij / |abar_ij|.
3. The scale by adaptive voting: the exact minimizer of the scalar TLS cost.
4. Pruning: keep the edges (i, j) with |s_ij - s| <= cbar alpha_ij, and
   keep only the vertices of a maximum clique of this graph.
5. The rotation from the TIMs of the clique, by graduated non-convexity
   (GNC) on the TLS cost with weighted Wahba steps. TEASER solves this step
   with a semidefinite relaxation and a certificate of optimality; this file
   does not, so it gives no certificate.
6. The translation component by component, by adaptive voting.

The scalar TLS solver and the maximum clique solver are exact. GNC is a
heuristic without a guarantee of global optimality.
"""

from __future__ import annotations

import math
from typing import Dict, List, Optional, Sequence, Set, Tuple

from cvla import det, mul, svd, transpose

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


def _sub(a, b):
    return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]


def _norm(a) -> float:
    return math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2])


def _rot(R, a):
    return [R[0][0] * a[0] + R[0][1] * a[1] + R[0][2] * a[2],
            R[1][0] * a[0] + R[1][1] * a[1] + R[1][2] * a[2],
            R[2][0] * a[0] + R[2][1] * a[1] + R[2][2] * a[2]]


# ------------------------------------------------------------ scalar TLS

def tls_cost(x: float, values: Sequence[float], bounds: Sequence[float], cbar: float = 1.0) -> float:
    """sum_k min((x - v_k)^2 / b_k^2, cbar^2)."""
    c2 = cbar * cbar
    return sum(min((x - v) ** 2 / (b * b), c2) for v, b in zip(values, bounds))


def adaptive_voting(values: Sequence[float], bounds: Sequence[float],
                    cbar: float = 1.0) -> Tuple[float, List[int]]:
    """The exact minimizer of the scalar TLS cost and its consensus set.

    Each measurement v_k is an inlier of x when |x - v_k| <= cbar b_k. The
    2K interval ends cut the line into at most 2K - 1 bounded pieces; on
    each piece the consensus set is fixed, and the best x for it is the
    weighted mean sum(v / b^2) / sum(1 / b^2). Sweeping the sorted ends with
    running sums takes O(K log K) time. Ties go to the leftmost piece."""
    K = len(values)
    if K == 0:
        raise ValueError("adaptive_voting: no values")
    c2 = cbar * cbar
    events = []
    for k, (v, b) in enumerate(zip(values, bounds)):
        if b <= 0.0:
            raise ValueError("adaptive_voting: bounds must be positive")
        events.append((v - cbar * b, 0, k))  # 0: the interval opens
        events.append((v + cbar * b, 1, k))  # 1: the interval closes
    events.sort()
    sw = swv = swv2 = 0.0
    count = 0
    best_x, best_cost = values[0], math.inf
    for e in range(len(events)):
        pos, kind, k = events[e]
        wk = 1.0 / (bounds[k] * bounds[k])
        sign = 1.0 if kind == 0 else -1.0
        count += 1 if kind == 0 else -1
        sw += sign * wk
        swv += sign * wk * values[k]
        swv2 += sign * wk * values[k] * values[k]
        if count == 0:
            sw = swv = swv2 = 0.0  # clear the rounding drift of the running sums
        if count == 0 or e + 1 == len(events) or events[e + 1][0] == pos:
            continue
        # The open piece (pos, next end) has a fixed consensus set S. The
        # cost of S at its weighted mean is sum_S w (x - v)^2 + (K - |S|) c2.
        x = swv / sw
        cost = max(swv2 - swv * x, 0.0) + (K - count) * c2
        if cost < best_cost:
            best_x, best_cost = x, cost
    best_set = [k for k in range(K) if (best_x - values[k]) ** 2 <= c2 * bounds[k] ** 2]
    return best_x, best_set


# ---------------------------------------------------------- maximum clique

def max_clique(n: int, adj: Sequence[Set[int]]) -> List[int]:
    """A maximum clique of the graph on vertices 0 .. n-1 with the given
    adjacency sets. Bron-Kerbosch with a pivot, cut off when the current
    clique plus all candidates cannot beat the best clique. Exact; the
    worst case is exponential, as the problem is NP-hard."""
    best: List[int] = []

    def expand(r: List[int], p: Set[int], x: Set[int]) -> None:
        nonlocal best
        if not p and not x:
            if len(r) > len(best):
                best = list(r)
            return
        if len(r) + len(p) <= len(best):
            return
        pivot = max(p | x, key=lambda u: len(adj[u] & p))
        for v in sorted(p - adj[pivot]):
            expand(r + [v], p & adj[v], x & adj[v])
            p = p - {v}
            x = x | {v}
            if len(r) + len(p) <= len(best):
                return

    expand([], set(range(n)), set())
    return sorted(best)


# -------------------------------------------------------- rotation by GNC

def weighted_wahba(U: Sequence[Sequence[float]], V: Sequence[Sequence[float]],
                   w: Sequence[float]) -> Matrix:
    """The rotation R that minimizes sum_k w_k |v_k - R u_k|^2 (no
    translation): H = sum w u v^T = U S V^T and R = V diag(1, 1, d) U^T."""
    H = [[sum(wk * u[i] * v[j] for wk, u, v in zip(w, U, V)) for j in range(3)] for i in range(3)]
    Uh, _, Vh = svd(H)
    d = 1.0 if det(mul(Vh, transpose(Uh))) > 0.0 else -1.0
    return mul(mul(Vh, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, d]]), transpose(Uh))


def gnc_tls_rotation(U: Sequence[Sequence[float]], V: Sequence[Sequence[float]],
                     bounds: Sequence[float], cbar: float = 1.0, factor: float = 1.4,
                     max_iter: int = 100, tol: float = 1e-12) -> Tuple[Matrix, List[float]]:
    """Graduated non-convexity for min_R sum min(|v_k - R u_k|^2 / b_k^2, cbar^2),
    after Yang, Antonante, Tzoumas and Carlone (2020). Returns R and the final
    weights (near 0 or 1)."""
    m = len(U)
    c2 = cbar * cbar
    w = [1.0] * m
    R = weighted_wahba(U, V, w)

    def residuals(R):
        return [sum(x * x for x in _sub(v, _rot(R, u))) / (b * b) for u, v, b in zip(U, V, bounds)]

    r2 = residuals(R)
    rmax = max(r2)
    if rmax <= c2:
        return R, w
    mu = c2 / (2.0 * rmax - c2)
    prev = math.inf
    for _ in range(max_iter):
        lo, hi = mu / (mu + 1.0) * c2, (mu + 1.0) / mu * c2
        w = [1.0 if r <= lo else 0.0 if r >= hi else cbar / math.sqrt(r) * math.sqrt(mu * (mu + 1.0)) - mu
             for r in r2]
        R = weighted_wahba(U, V, w)
        r2 = residuals(R)
        cost = sum(wk * r for wk, r in zip(w, r2))
        if abs(prev - cost) <= tol and all(wk in (0.0, 1.0) for wk in w):
            break
        prev = cost
        mu *= factor
    return R, w


# --------------------------------------------------------------- pipeline

def teaser(A: Sequence[Sequence[float]], B: Sequence[Sequence[float]], beta: float,
           cbar: float = 1.0, scale: Optional[float] = None) -> Dict[str, object]:
    """Estimate (s, R, t) from the correspondences (A[i], B[i]).

    beta is the noise bound of the inliers. If scale is given, the scale is
    known and the pruning uses it. Returns a dict with "s", "R", "t",
    "clique" (the indices kept by the maximum clique) and "inliers" (the
    indices whose final residual is at most cbar beta)."""
    m = len(A)
    pairs = []
    for i in range(m):  # @line L1
        for j in range(i + 1, m):
            ab, bb = _sub(A[j], A[i]), _sub(B[j], B[i])
            na = _norm(ab)
            if na > 0.0:
                pairs.append((i, j, ab, bb, _norm(bb) / na, 2.0 * beta / na))  # @line L2
    if scale is None:
        s_hat, _ = adaptive_voting([p[4] for p in pairs], [p[5] for p in pairs], cbar)  # @line L3
    else:
        s_hat = float(scale)
    adj: List[Set[int]] = [set() for _ in range(m)]
    for i, j, _, _, sij, aij in pairs:  # @line L4
        if abs(sij - s_hat) <= cbar * aij:
            adj[i].add(j)
            adj[j].add(i)
    clique = max_clique(m, adj)  # @line L5
    cs = set(clique)
    U = [[s_hat * x for x in p[2]] for p in pairs if p[0] in cs and p[1] in cs]
    V = [p[3] for p in pairs if p[0] in cs and p[1] in cs]
    if U:
        R, _ = gnc_tls_rotation(U, V, [2.0 * beta] * len(U), cbar)  # @line L6
    else:
        R = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    t = []
    for d in range(3):  # @line L7
        vals = [B[i][d] - s_hat * _rot(R, A[i])[d] for i in clique]
        t.append(adaptive_voting(vals, [beta] * len(vals), cbar)[0])
    inliers = [i for i in range(m)
               if _norm(_sub(B[i], [s_hat * x + y for x, y in zip(_rot(R, A[i]), t)])) <= cbar * beta]
    return {"s": s_hat, "R": R, "t": t, "clique": clique, "inliers": inliers}  # @line L8
test_teaser_registration.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/teaser-registration/. The authors are listed in prov/E0TQ57.jsonl.
import itertools
import math
import random
import unittest

from cvla import det, mul, transpose
from teaser_registration import (adaptive_voting, gnc_tls_rotation, max_clique,
                                 teaser, tls_cost, weighted_wahba)


def rotation(axis, angle):
    n = math.sqrt(sum(a * a for a in axis))
    x, y, z = (a / n for a in axis)
    c, s = math.cos(angle), math.sin(angle)
    d = 1.0 - c
    return [[c + x * x * d, x * y * d - z * s, x * z * d + y * s],
            [y * x * d + z * s, c + y * y * d, y * z * d - x * s],
            [z * x * d - y * s, z * y * d + x * s, c + z * z * d]]


def random_rotation(rng):
    q = [rng.gauss(0.0, 1.0) for _ in range(4)]
    n = math.sqrt(sum(v * v for v in q))
    w, x, y, z = (v / n for v in q)
    return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
            [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
            [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]


def rot_angle(R1, R2):
    m = mul(transpose(R1), R2)
    c = (m[0][0] + m[1][1] + m[2][2] - 1.0) / 2.0
    s = 0.5 * math.sqrt((m[2][1] - m[1][2]) ** 2 + (m[0][2] - m[2][0]) ** 2 + (m[1][0] - m[0][1]) ** 2)
    return math.atan2(s, c)


def make_problem(rng, m, n_out, noise, s=1.0):
    R = random_rotation(rng)
    t = [rng.uniform(-1.0, 1.0) for _ in range(3)]
    A = [[rng.uniform(-1.0, 1.0) for _ in range(3)] for _ in range(m)]
    B = []
    for a in A:
        Ra = [sum(R[i][k] * a[k] for k in range(3)) for i in range(3)]
        B.append([s * Ra[i] + t[i] + rng.gauss(0.0, noise) for i in range(3)])
    out = rng.sample(range(m), n_out)
    for i in out:
        B[i] = [rng.uniform(-2.0, 2.0) for _ in range(3)]
    return R, t, A, B, set(range(m)) - set(out)


class TestAdaptiveVoting(unittest.TestCase):
    def brute(self, values, bounds, cbar):
        best = math.inf
        for r in range(1, len(values) + 1):
            for S in itertools.combinations(range(len(values)), r):
                w = [1.0 / bounds[k] ** 2 for k in S]
                x = sum(wk * values[k] for wk, k in zip(w, S)) / sum(w)
                best = min(best, tls_cost(x, values, bounds, cbar))
        return best

    def test_against_all_subsets(self):
        rng = random.Random(1)
        for _ in range(40):
            K = rng.randint(1, 8)
            values = [rng.uniform(-3.0, 3.0) for _ in range(K)]
            bounds = [rng.uniform(0.1, 1.0) for _ in range(K)]
            cbar = rng.choice([0.5, 1.0, 2.0])
            x, S = adaptive_voting(values, bounds, cbar)
            self.assertAlmostEqual(tls_cost(x, values, bounds, cbar), self.brute(values, bounds, cbar), places=9)

    def test_no_grid_point_is_better(self):
        rng = random.Random(2)
        for _ in range(20):
            K = rng.randint(2, 12)
            values = [rng.uniform(-3.0, 3.0) for _ in range(K)]
            bounds = [rng.uniform(0.1, 1.0) for _ in range(K)]
            x, _ = adaptive_voting(values, bounds)
            f = tls_cost(x, values, bounds)
            grid = min(tls_cost(-5.0 + 10.0 * g / 4000, values, bounds) for g in range(4001))
            self.assertLessEqual(f, grid + 1e-12)

    def test_example_from_page(self):
        x, S = adaptive_voting([1.0, 1.1, 0.9, 3.0, 5.0], [0.2] * 5)
        self.assertAlmostEqual(x, 1.0, places=12)
        self.assertEqual(S, [0, 1, 2])

    def test_single_value(self):
        self.assertEqual(adaptive_voting([2.5], [0.1]), (2.5, [0]))


class TestMaxClique(unittest.TestCase):
    def test_against_brute_force(self):
        rng = random.Random(3)
        for _ in range(30):
            n = rng.randint(1, 11)
            p = rng.uniform(0.2, 0.8)
            adj = [set() for _ in range(n)]
            for i in range(n):
                for j in range(i + 1, n):
                    if rng.random() < p:
                        adj[i].add(j)
                        adj[j].add(i)
            C = max_clique(n, adj)
            for i, j in itertools.combinations(C, 2):
                self.assertIn(j, adj[i])
            best = 1
            for r in range(2, n + 1):
                if any(all(j in adj[i] for i, j in itertools.combinations(S, 2))
                       for S in itertools.combinations(range(n), r)):
                    best = r
            self.assertEqual(len(C), best)


class TestRotation(unittest.TestCase):
    def test_wahba_exact(self):
        rng = random.Random(4)
        R = random_rotation(rng)
        U = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(6)]
        V = [[sum(R[i][k] * u[k] for k in range(3)) for i in range(3)] for u in U]
        Rh = weighted_wahba(U, V, [1.0] * 6)
        self.assertLess(rot_angle(R, Rh), 1e-9)
        self.assertAlmostEqual(det(Rh), 1.0, places=12)

    def test_gnc_rejects_outliers(self):
        rng = random.Random(5)
        R = random_rotation(rng)
        U = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(40)]
        V = [[sum(R[i][k] * u[k] for k in range(3)) + rng.gauss(0, 0.005) for i in range(3)] for u in U]
        for k in range(16):
            V[k] = [rng.uniform(-1.5, 1.5) for _ in range(3)]
        Rh, w = gnc_tls_rotation(U, V, [0.05] * 40)
        self.assertLess(rot_angle(R, Rh), math.radians(1.0))
        self.assertEqual(sum(1 for x in w[16:] if x > 0.5), 24)


class TestTeaser(unittest.TestCase):
    def test_inliers_form_a_clique(self):
        rng = random.Random(6)
        R, t, A, B, inl = make_problem(rng, 40, 20, 0.005)
        out = teaser(A, B, beta=0.03, scale=1.0)
        self.assertGreaterEqual(len(out["clique"]), len(inl))

    def test_known_scale_high_outlier_rate(self):
        rng = random.Random(7)
        R, t, A, B, inl = make_problem(rng, 60, 51, 0.005)
        out = teaser(A, B, beta=0.03, scale=1.0)
        self.assertLess(rot_angle(R, out["R"]), math.radians(2.0))
        for a, b in zip(out["t"], t):
            self.assertLess(abs(a - b), 0.03)
        self.assertTrue(inl <= set(out["inliers"]))

    def test_unknown_scale(self):
        rng = random.Random(8)
        R, t, A, B, inl = make_problem(rng, 40, 24, 0.002, s=1.7)
        out = teaser(A, B, beta=0.01)
        self.assertLess(abs(out["s"] - 1.7), 0.02)
        self.assertLess(rot_angle(R, out["R"]), math.radians(1.0))

    def test_exact_data(self):
        rng = random.Random(9)
        R, t, A, B, _ = make_problem(rng, 12, 0, 0.0)
        out = teaser(A, B, beta=1e-6, scale=1.0)
        self.assertLess(rot_angle(R, out["R"]), 1e-6)
        self.assertEqual(out["clique"], list(range(12)))


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

History

Yang and Carlone gave a first form of the method in 2019, with the TLS cost and the semidefinite relaxation of the rotation. Yang, Shi and Carlone published TEASER and TEASER++ in IEEE Transactions on Robotics in 2021, with the decoupling by invariant measurements, adaptive voting, the maximum clique step, the certifier, the error bounds and an open source C++ library. The GNC method for TLS that TEASER++ uses is from Yang, Antonante, Tzoumas and Carlone (2020), building on the graduated non-convexity of Blake and Zisserman for robust costs. The use of a clique of pairwise consistent matches to remove outliers is older, and was used for example in point cloud registration and in the matching of features before RANSAC.

References

  1. Heng Yang, Jingnan Shi and Luca Carlone, TEASER: Fast and certifiable point cloud registration, IEEE Transactions on Robotics 37(2), 2021, 314-333, The truncated least squares cost, the translation and rotation invariant measurements, adaptive voting and its exactness (Theorem 7), the inlier clique (Theorem 6), the semidefinite relaxation of the rotation (Proposition 12) with its tightness results, the optimality certifier (Theorem 14), and the error bounds (Theorem 17)
  2. Heng Yang, Pasquale Antonante, Vasileios Tzoumas and Luca Carlone, Graduated non-convexity for robust spatial perception: From non-minimal solvers to global outlier rejection, IEEE Robotics and Automation Letters, 2020, Graduated non-convexity for the truncated least squares cost: the weight update and the schedule of the control parameter, used by TEASER++ for the rotation
  3. Shinji Umeyama, Least-squares estimation of transformation parameters between two point patterns, IEEE Transactions on Pattern Analysis and Machine Intelligence 13(4), 1991, 376-380, The best rotation for weighted point pairs by the SVD, with the sign of the determinant, used in each GNC step

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.average
  • a full proof of time.best
  • a full proof of time.worst
  • 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