Algorithm Search⌘K

Algorithmadvanced

4-points congruent sets

Also called 4PCS, Super4PCS.

Global rigid registration that finds coplanar four-point bases in one cloud and their affine-invariant ratio matches in the other, verified like RANSAC.

Time
O(N (n^2 + k n^2)) worstO(N (n^2 + k n)) averageΘ(N n^2) best
Space
O(n^2 + k) extra
Where
N = the number of trials; k = the number of candidate sets in a trial; n = the number of points in each cloud
Properties
randomizednot exactofflineiterative
Origin
Dror Aiger, Niloy J. Mitra, Daniel Cohen Or, 2008

4-points congruent sets (4PCS) aligns two point clouds PP and QQ that overlap only in part, from any start pose and without features or correspondences. It follows the RANSAC pattern: guess a motion from a small sample, then count how many points it explains. The sample is a base of four nearly coplanar points of PP whose two segments abab and cdcd cross at a point ee. The two ratios at which ee cuts the segments do not change under any affine map, and so not under a rigid motion. So 4PCS does not try all 4-tuples of QQ. It finds the pairs of QQ at the two segment lengths, computes on each pair the point that the ratio gives, and keeps the pairs of pairs whose points meet. Each such 4-tuple is a candidate image of the base. The best rigid motion from the base to the candidate is scored by the largest common pointset (LCP): the number of points of PP that land within δ\delta of a point of QQ. The best motion over several trials wins.

In plain words

Pick four points on the first scan that lie on one flat patch, like the corners of a kite, and draw its two crossing sticks. Note where the sticks cross: say a third of the way along one stick and half way along the other. These fractions stay the same however the kite is turned or moved.

In the second scan, find all pairs of points as far apart as the first stick, and mark the point a third of the way along each. Do the same for the second stick at half way. Where two marks meet, the four ends may be the kite.

For each such kite, move the first scan onto it and count how many points land on points of the second scan. Try a few kites and keep the best move.

The problem

Input. Two finite sets PP and QQ in R3\mathbb{R}^3, each with nn points, that sample overlapping parts of one surface; an error bound δ>0\delta > 0; and a number of trials NN.

Output. A rigid motion T=(R,t)T = (R, t) with R∈SO(3)R \in SO(3) that tries to maximize the LCP score

LCP⁡(T)=∣{p∈P:min⁡q∈Q∣Tp−q∣≤δ}∣.\operatorname{LCP}(T) = \left| \{ p \in P : \min_{q \in Q} |T p - q| \le \delta \} \right| .

4PCS is a randomized search for a large LCP. It gives no guarantee of the maximum. This is global point cloud registration: the result does not depend on the start pose.

The algorithm

The base and its invariants. Pick three points a,b,ca, b, c of PP, far apart but not farther than the expected size of the overlap. Pick a fourth point dd close to their plane, and pair the four points into two segments that cross: abab and cdcd meet at ee. Let

r1=∣a−e∣∣a−b∣,r2=∣c−e∣∣c−d∣,d1=∣a−b∣,d2=∣c−d∣.r_1 = \frac{|a - e|}{|a - b|}, \qquad r_2 = \frac{|c - e|}{|c - d|}, \qquad d_1 = |a - b|, \qquad d_2 = |c - d| .

If an affine map AA sends the base to A(a),A(b),A(c),A(d)A(a), A(b), A(c), A(d), then the image segments cross at A(e)A(e), at the same ratios r1r_1 and r2r_2.

The search in Q. For a pair (qi,qj)(q_i, q_j) at a distance near d1d_1, the image of ee would be e1=qi+r1(qj−qi)e_1 = q_i + r_1 (q_j - q_i). For a pair (qk,ql)(q_k, q_l) at a distance near d2d_2, it would be e2=qk+r2(ql−qk)e_2 = q_k + r_2 (q_l - q_k). A 4-tuple of QQ that is congruent to the base, up to δ\delta, has e1≈e2e_1 \approx e_2. Each pair is used in both orders, because the order of qiq_i and qjq_j is not known.

  1. 4PCS(P, Q, δ, N)
  2. 1for trial = 1 .. N
  3. 2(a, b, c, d) ← a wide, nearly coplanar base of P whose segments ab and cd meet at e
  4. 3r₁ ← |a - e| / |a - b| ; r₂ ← |c - e| / |c - d| ; d₁ ← |a - b| ; d₂ ← |c - d|
  5. 4R₁ ← ordered pairs of Q at distance d₁ ± δ ; R₂ ← ordered pairs at distance d₂ ± δ
  6. 5U ← {(i, j, k, l) : (i, j) ∈ R₁, (k, l) ∈ R₂, |q_i + r₁(q_j - q_i) - q_k - r₂(q_l - q_k)| ≤ δ}
  7. 6for each (i, j, k, l) in U: T ← best rigid motion from (a, b, c, d) to (q_i, q_j, q_k, q_l)
  8. 7if T fits the four points: score T by LCP(T) ; keep the best
  9. 8return the best T

Line L2 chooses the base. The reference code takes the widest of a few random triangles whose sides are at most a given width, then the point nearest to their plane for which one of the three ways to pair the four points gives two segments that meet within δ\delta. Line L3 computes the invariants. Line L4 finds the pairs by brute force over all pairs; the paper uses a faster search. Line L5 puts the points e1e_1 in a grid of cubes of side δ\delta, a hash table of cells, and looks up each e2e_2 in its cube and the 26 around it. Line L6 fits the motion by the SVD with the sign fix of Umeyama. Line L7 drops a candidate if a base point is more than 2δ2\delta from its partner after the fit, since the ratios also accept affine images that are not congruent, and then scores the rest with the same grid on QQ. The paper scores on a random sample of PP to save time.

Example

Take the base a=(0,0,0)a = (0, 0, 0), b=(4,2,0)b = (4, 2, 0), c=(0,3,0)c = (0, 3, 0), d=(3,0,0)d = (3, 0, 0) in the plane z=0z = 0. The segment abab is (4s,2s,0)(4s, 2s, 0) and the segment cdcd is (3u,3−3u,0)(3u, 3 - 3u, 0). They meet where 4s=3u4s = 3u and 2s=3−3u2s = 3 - 3u, so s=1/2s = 1/2, u=2/3u = 2/3, and e=(2,1,0)e = (2, 1, 0). So r1=0.5r_1 = 0.5, r2=2/3r_2 = 2/3, d1=20≈4.472d_1 = \sqrt{20} \approx 4.472 and d2=18≈4.243d_2 = \sqrt{18} \approx 4.243.

Let PP be the base and four more points, (1,1,2)(1, 1, 2), (3,3,1)(3, 3, 1), (−1,2,1)(-1, 2, 1) and (2,−1,2)(2, -1, 2). Let QQ be PP turned by 90 degrees about the zz axis and moved by (5,0,1)(5, 0, 1), plus two outliers (0,0,0)(0, 0, 0) and (6,4,1)(6, 4, 1). So q0,…,q3q_0, \ldots, q_3 are the images of a,b,c,da, b, c, d: (5,0,1)(5, 0, 1), (3,4,1)(3, 4, 1), (2,0,1)(2, 0, 1), (5,3,1)(5, 3, 1). With δ=0.01\delta = 0.01:

  • QQ has 45 pairs. Only {q0,q1}\{q_0, q_1\} is at the distance 4.472, so R1R_1 holds (0,1)(0, 1) and (1,0)(1, 0).
  • Three pairs are at the distance 4.243: {q2,q3}\{q_2, q_3\}, {q5,q7}\{q_5, q_7\}, and {q5,q9}\{q_5, q_9\}, where q9q_9 is an outlier. R2R_2 holds the six ordered pairs.
  • With r1=0.5r_1 = 0.5, both orders of (q0,q1)(q_0, q_1) give the midpoint (4,2,1)(4, 2, 1). The pair (q2,q3)(q_2, q_3) gives (2,0,1)+23(3,3,0)=(4,2,1)(2, 0, 1) + \frac{2}{3}(3, 3, 0) = (4, 2, 1) as well. No other point of R2R_2 is near. So UU has two tuples: (0,1,2,3)(0, 1, 2, 3) and (1,0,2,3)(1, 0, 2, 3).
  • The tuple (0,1,2,3)(0, 1, 2, 3) fits exactly: the 90 degree turn and the shift (5,0,1)(5, 0, 1), with LCP 8 of 8.
  • The tuple (1,0,2,3)(1, 0, 2, 3) has the same ratios, because r1=0.5r_1 = 0.5 is symmetric, but it is only an affine image of the base, a mirror image. The best rigid fit leaves a residual of 0.81, so line L7 drops it. Its LCP would be 0.

On a larger case, a curved patch of 200 points split into two clouds of 100 points that share about half their points, with noise of standard deviation 0.003 and δ=0.03\delta = 0.03, 30 trials found between 2300 and 4100 candidate sets, and the best LCP gave a rotation error between 0.27 and 1.17 degrees in each of six random cases.

Correctness

If a trial picks a base that lies in the overlap, then that trial finds the image of the base. Suppose each base point has a partner in QQ within ε\varepsilon of its image under the true motion TT, and 2ε2\varepsilon plus the gap between the two segments is at most δ\delta. A rigid motion keeps distances, so both pairs pass line L4. The point qi+r1(qj−qi)q_i + r_1 (q_j - q_i) is a weighted mean of points within ε\varepsilon of TaT a and TbT b, so it is within ε\varepsilon of Te1T e_1; the same holds for the other pair, so the two points meet within δ\delta in line L5. The Kabsch fit of the four points has a residual at most 2ε2\varepsilon, because TT itself has a sum of squares at most 4ε24 \varepsilon^2. So line L7 scores a motion close to TT. The full proof is in proofs/correctness.md.

The method is still randomized: the claim needs a good base, which each trial finds only with some probability. And the motion with the best LCP need not be the true one when the shape has symmetries or the overlap is small.

Proof: A trial whose base lies in the overlap finds the image of the basefull

We use the notation of the page and of the reference code. A trial picks a base a,b,c,da, b, c, d from PP. The lines abab and cdcd have closest points e1=a+r1(b−a)e_1 = a + r_1 (b - a) and e2=c+r2(d−c)e_2 = c + r_2 (d - c), with 0<r1,r2<10 < r_1, r_2 < 1, and the base is accepted when the gap γ=∣e1−e2∣\gamma = |e_1 - e_2| is at most δ\delta. Let d1=∣a−b∣d_1 = |a - b| and d2=∣c−d∣d_2 = |c - d|. Line L4 collects the ordered pairs (i,j)(i, j) of QQ with ∣∣qi−qj∣−d1∣≤δ\big| |q_i - q_j| - d_1 \big| \le \delta, and the same for d2d_2. Line L5 keeps a 4-tuple (i,j,k,l)(i, j, k, l) when ∣(qi+r1(qj−qi))−(qk+r2(ql−qk))∣≤δ|(q_i + r_1 (q_j - q_i)) - (q_k + r_2 (q_l - q_k))| \le \delta. Line L6 fits a rigid motion by the Kabsch method and drops the tuple if a base point is more than 2δ2\delta from its partner after the fit. Line L7 scores the motion by the LCP.

Lemma 1: the ratios are affine invariant

Let A(x)=Mx+tA(x) = M x + t be an affine map with MM invertible. If a,b,c,da, b, c, d are coplanar and the segments abab and cdcd meet at e=a+r1(b−a)=c+r2(d−c)e = a + r_1 (b - a) = c + r_2 (d - c), then the segments A(a)A(b)A(a)A(b) and A(c)A(d)A(c)A(d) meet at A(e)A(e), with the same r1r_1 and r2r_2.

Proof. A(a+r(b−a))=A(a)+r(A(b)−A(a))A(a + r(b - a)) = A(a) + r (A(b) - A(a)), because AA maps a weighted mean (1−r)a+rb(1 - r) a + r b to (1−r)A(a)+rA(b)(1 - r) A(a) + r A(b). So A(e)A(e) lies on both image segments at the parameters r1r_1 and r2r_2. The image lines are not parallel, because MM is invertible and the lines abab and cdcd are not parallel, so they meet in one point, which is A(e)A(e). □\square

A rigid motion is an affine map, so the ratios are rigid invariants too. The ratios do not determine the base up to a rigid motion: any affine image of the base has the same ratios. This is why line L6 checks the rigid fit.

Lemma 2: completeness of the extraction

Suppose TT is a rigid motion and QQ contains points qi,qj,qk,qlq_i, q_j, q_k, q_l with ∣qi−Ta∣|q_i - T a|, ∣qj−Tb∣|q_j - T b|, ∣qk−Tc∣|q_k - T c| and ∣ql−Td∣|q_l - T d| all at most ε\varepsilon. If 2ε+γ≤δ2 \varepsilon + \gamma \le \delta, then (i,j,k,l)(i, j, k, l) is among the tuples of line L5.

Proof. TT keeps distances, so ∣Ta−Tb∣=d1|T a - T b| = d_1, and by the triangle inequality ∣∣qi−qj∣−d1∣≤2ε≤δ\big| |q_i - q_j| - d_1 \big| \le 2 \varepsilon \le \delta. So (i,j)(i, j) passes line L4; the same holds for (k,l)(k, l) with d2d_2. Next, TT is affine, so Te1=(1−r1)Ta+r1TbT e_1 = (1 - r_1) T a + r_1 T b, and

∣(1−r1)qi+r1qj−Te1∣≤(1−r1)∣qi−Ta∣+r1∣qj−Tb∣≤ε.|(1 - r_1) q_i + r_1 q_j - T e_1| \le (1 - r_1) |q_i - T a| + r_1 |q_j - T b| \le \varepsilon .

In the same way the point of the pair (k,l)(k, l) is within ε\varepsilon of Te2T e_2. Since ∣Te1−Te2∣=γ|T e_1 - T e_2| = \gamma, the two points are within 2ε+γ≤δ2 \varepsilon + \gamma \le \delta of each other, so line L5 keeps the tuple. □\square

The reference code finds every such tuple, because the grid query of line L5 returns all stored points within δ\delta: a point within δ\delta of the query lies in one of the 27 cubes of side δ\delta around the cube of the query.

Lemma 3: the true tuple passes the rigid check

Under the conditions of Lemma 2, the Kabsch fit (R^,t^)(\hat R, \hat t) from (a,b,c,d)(a, b, c, d) to (qi,qj,qk,ql)(q_i, q_j, q_k, q_l) has every residual at most 2ε≤2δ2 \varepsilon \le 2\delta.

Proof. The Kabsch method returns a rigid motion that minimizes the sum of squared residuals over all rigid motions. The motion TT has sum at most 4ε24 \varepsilon^2. So the fit has sum at most 4ε24 \varepsilon^2, and each residual is at most 2ε2 \varepsilon. □\square

If a,b,ca, b, c are not on one line, which the base selection ensures, then four exact correspondences determine the rigid motion, so for ε=0\varepsilon = 0 the fit equals TT.

Theorem

If in some trial the base lies in the overlap, in the sense of Lemma 2 with 2ε+γ≤δ2 \varepsilon + \gamma \le \delta, then that trial scores a motion T^\hat T whose residuals on the base are at most 2ε2 \varepsilon, and the result of 4PCS has an LCP score at least the score of T^\hat T.

Proof. Lemmas 2 and 3 show that the tuple is extracted and survives the check, so line L7 scores T^\hat T. The best score over all trials is kept. □\square

What this does not prove

  • The theorem needs a trial whose base lies in the overlap. The base is random, so this holds only with some probability. If a fraction ff of the points of PP lie in the overlap and the base were four independent uniform picks, the chance per trial would be about f4f^4, and the number of trials for a success probability pp would follow the RANSAC bound. The reference code picks wide bases, which are not uniform, so this is a guide, not a bound.
  • A motion with the best LCP need not be the true motion. A small δ\delta, a symmetric shape or a small overlap can make a wrong motion score higher.
  • The motion T^\hat T is fit to four points only, so its error grows with the noise and with a small base. A refinement such as ICP on all points is usual.

Complexity

The model is the real RAM. Line L2 takes O(n)O(n) time. Line L4 takes Θ(n2)\Theta(n^2) time by brute force over the pairs. Line L5 builds the grid in time linear in ∣R1∣|R_1| and finds the kk candidate sets with one grid query for each pair of R2R_2; when the points are spread evenly, each query looks at O(1)O(1) stored points, so the extraction takes O(n2+k)O(n^2 + k), the bound stated in the paper. Each candidate costs O(1)O(1) for the fit and O(n)O(n) grid queries for the LCP, each O(1)O(1) when the points are spread evenly and O(n)O(n) in the worst case. So NN trials take O(N(n2+kn))O(N(n^2 + k n)) time on evenly spread points and O(N(n2+kn2))O(N(n^2 + k n^2)) in the worst case. The space is O(n2+k)O(n^2 + k) for the pairs and the candidates.

The number kk depends on the data and on δ\delta. With exact data and δ=0\delta = 0, the number of pairs at one distance is far below n2n^2 for points in general position, so kk is small; with a large δ\delta or a regular shape, many pairs pass, and kk can be large. The number of trials NN follows the RANSAC bound: if a trial picks a base in the overlap with probability ww, then N≥log⁡(1−p)/log⁡(1−w)N \ge \log(1 - p) / \log(1 - w) trials succeed with probability at least pp. A base needs only 4 points in the overlap, and wide bases are allowed, so ww is much larger than for methods that need more points.

Properties

  • Global. The start pose does not matter.
  • No features. It uses only the positions of the points, so it works on surfaces with little texture or with noisy normals.
  • Randomized. The result depends on the random bases. More trials give a higher chance of success.
  • Robust to partial overlap and outliers. The LCP score counts only the points that fit, and the base needs only 4 points in the overlap.
  • Approximate. The motion comes from four points. A local method such as ICP usually refines it.
  • Quadratic per trial. The brute force pair search costs Θ(n2)\Theta(n^2), so the clouds are usually downsampled first.

Variants and improvements

  • Faster extraction. Mellado, Aiger and Mitra (2014) find the pairs at a given distance with a spatial index instead of a scan of all pairs, and filter the pairs of pairs by the angle between the two segments, which the ratios alone do not fix. The authors report a cost per trial close to linear in nn plus the size of the output.
  • Sampling of the score. Scoring on a random sample of PP and stopping a candidate early when it cannot beat the best score saves much time.
  • Other bases. Later methods in the same family use bases that are not coplanar.

When to use it

Use 4PCS to align two scans with an unknown start pose when features are not reliable, for example on smooth or noisy surfaces, and when the overlap is moderate. Downsample the clouds first, for example with a voxel grid, because the cost grows as n2n^2 per trial, and refine the result with ICP. When good features exist, fast global registration or TEASER are usually faster. When a proof of the global optimum is needed, use Go-ICP. For recognition of many models in one scene, geometric hashing stores bases of the models in advance.

Pitfalls

  • The choice of delta. δ\delta must cover the noise and the sampling: two scans of the same surface do not sample the same points, so the image of a base point is only near some point of QQ. A too small δ\delta misses the true candidates; a too large one lets kk and the cost explode.
  • Base width. A narrow base gives a poor estimate of the rotation. A base wider than the overlap cannot lie in it. The paper sets the width from an estimate of the overlap.
  • Affine but not rigid. The ratios accept every affine image of the base. Check the rigid fit, or the score of many wrong candidates is wasted, and a wrong one may win on a degenerate shape.
  • Mirror images. With r1=0.5r_1 = 0.5 or r2=0.5r_2 = 0.5, both orders of a pair give the same point, which doubles the candidates.
  • Flat or symmetric shapes. A plane, a sphere or a cylinder has many motions with the same LCP. No score based on point positions alone can pick the right one.
  • Coplanar base in a curved scene. On a strongly curved surface, few wide quadruples are coplanar within δ\delta, so base selection fails often.

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()
four_points_congruent_sets.py 213 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-points-congruent-sets/. The authors are listed in prov/2MMXJS.jsonl.
"""4-points congruent sets (Aiger, Mitra and Cohen-Or, SIGGRAPH 2008).

Input: two point clouds P and Q in R^3 that overlap, an error bound delta
and a number of trials. Output: a rigid motion T = (R, t) with T P close to
Q on as many points as possible: the largest common pointset (LCP) score,
the number of points p of P with a point of Q within delta of T p.

Each trial picks a wide, nearly coplanar base (a, b, c, d) from P, whose
segments ab and cd meet at a point e. The two ratios
r1 = |a - e| / |a - b| and r2 = |c - e| / |c - d| do not change under an
affine map, so they also hold for the image of the base in Q. The trial
finds all pairs of Q at the distances |a - b| and |c - d|, computes the
points that the ratios give on each pair, and matches these points. Each
match is a 4-point set of Q that is congruent to the base up to delta. The
best rigid motion from the base to each set is then scored by the LCP.

The extraction uses brute force over pairs, O(n^2) per trial, and a grid
for the matching of points, as the reference stand-in for the range search
of the paper.
"""

from __future__ import annotations

import math
import random
from typing import Dict, List, Optional, Sequence, 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 _dot(a, b):
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def _dist(a, b) -> float:
    return math.sqrt(_dot(_sub(a, b), _sub(a, b)))


def _cross(a, b):
    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 apply(R: Matrix, t: Sequence[float], p: Sequence[float]) -> Vector:
    return [R[i][0] * p[0] + R[i][1] * p[1] + R[i][2] * p[2] + t[i] for i in range(3)]


def kabsch(A: Sequence[Sequence[float]], B: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector]:
    """The rigid motion (R, t) that minimizes sum |R a + t - b|^2, by the SVD
    of the cross-covariance with the sign fix, so that det R = +1."""
    n = len(A)
    ca = [sum(a[i] for a in A) / n for i in range(3)]
    cb = [sum(b[i] for b in B) / n for i in range(3)]
    H = [[sum((a[i] - ca[i]) * (b[j] - cb[j]) for a, b in zip(A, B)) for j in range(3)] for i in range(3)]
    U, _, V = svd(H)
    d = 1.0 if det(mul(V, transpose(U))) > 0.0 else -1.0
    R = mul(mul(V, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, d]]), transpose(U))
    Rc = [sum(R[i][k] * ca[k] for k in range(3)) for i in range(3)]
    return R, [cb[i] - Rc[i] for i in range(3)]


def base_invariants(a, b, c, d) -> Optional[Tuple[float, float, float, float, float]]:
    """For the segments ab and cd, the parameters r1, r2 of the closest
    points e1 = a + r1 (b - a) and e2 = c + r2 (d - c) of the two lines, the
    lengths d1 = |a - b| and d2 = |c - d|, and the gap |e1 - e2|. Returns
    None if the lines are parallel or the closest points are not inside
    both segments."""
    u, v, w = _sub(b, a), _sub(d, c), _sub(a, c)
    A, B, C = _dot(u, u), _dot(u, v), _dot(v, v)
    D, E = _dot(u, w), _dot(v, w)
    den = A * C - B * B
    if den <= 1e-12 * A * C:
        return None
    r1 = (B * E - C * D) / den
    r2 = (A * E - B * D) / den
    if not (0.0 < r1 < 1.0 and 0.0 < r2 < 1.0):
        return None
    e1 = [a[i] + r1 * u[i] for i in range(3)]
    e2 = [c[i] + r2 * v[i] for i in range(3)]
    return r1, r2, math.sqrt(A), math.sqrt(C), _dist(e1, e2)


def select_base(P: Sequence[Sequence[float]], rng: random.Random, delta: float,
                tries: int = 30, max_width: float = math.inf
                ) -> Optional[Tuple[Tuple[int, int, int, int], Tuple[float, float, float, float]]]:
    """A wide base: the widest of `tries` random triangles (a, b, c) with
    sides at most max_width, then the point d nearest to their plane, within
    max_width of a, for which one of the three pairings of the four points
    into two segments gives segments that meet within delta. Returns
    ((ia, ib, ic, id), (r1, r2, d1, d2)) or None."""
    n = len(P)
    best, best_area = None, 0.0
    for _ in range(tries):
        i, j, k = rng.sample(range(n), 3)
        if max(_dist(P[i], P[j]), _dist(P[i], P[k]), _dist(P[j], P[k])) > max_width:
            continue
        nrm = _cross(_sub(P[j], P[i]), _sub(P[k], P[i]))
        area = math.sqrt(_dot(nrm, nrm))
        if area > best_area:
            best, best_area = (i, j, k), area
    if best is None or best_area == 0.0:
        return None
    i, j, k = best
    normal = _cross(_sub(P[j], P[i]), _sub(P[k], P[i]))
    nn = math.sqrt(_dot(normal, normal))
    order = sorted((abs(_dot(_sub(P[l], P[i]), normal)) / nn, l) for l in range(n)
                   if l not in best and _dist(P[l], P[i]) <= max_width)
    for h, l in order:
        if h > delta:
            break
        for ia, ib, ic, id_ in ((i, j, k, l), (i, k, j, l), (i, l, j, k)):
            inv = base_invariants(P[ia], P[ib], P[ic], P[id_])
            if inv is not None and inv[4] <= delta:
                return (ia, ib, ic, id_), inv[:4]
    return None


class Grid:
    """Points hashed into cubes of side `cell`, for radius queries with a
    radius of at most `cell`."""

    def __init__(self, points: Sequence[Sequence[float]], cell: float):
        self.cell = cell
        self.points = points
        self.cells: Dict[Tuple[int, int, int], List[int]] = {}
        for idx, p in enumerate(points):
            self.cells.setdefault(self._key(p), []).append(idx)

    def _key(self, p):
        return (math.floor(p[0] / self.cell), math.floor(p[1] / self.cell), math.floor(p[2] / self.cell))

    def near(self, x: Sequence[float], radius: float) -> List[int]:
        kx, ky, kz = self._key(x)
        r2 = radius * radius
        out = []
        for dx in (-1, 0, 1):
            for dy in (-1, 0, 1):
                for dz in (-1, 0, 1):
                    for idx in self.cells.get((kx + dx, ky + dy, kz + dz), ()):
                        p = self.points[idx]
                        if (p[0] - x[0]) ** 2 + (p[1] - x[1]) ** 2 + (p[2] - x[2]) ** 2 <= r2:
                            out.append(idx)
        return out


def pairs_at_distance(Q: Sequence[Sequence[float]], dist: float, eps: float) -> List[Tuple[int, int]]:
    """All ordered pairs (i, j), i != j, with | |q_i - q_j| - dist | <= eps."""
    out = []
    for i in range(len(Q)):
        for j in range(i + 1, len(Q)):
            if abs(_dist(Q[i], Q[j]) - dist) <= eps:
                out.append((i, j))
                out.append((j, i))
    return out


def congruent_sets(Q: Sequence[Sequence[float]], r1: float, r2: float, d1: float, d2: float,
                   eps: float) -> List[Tuple[int, int, int, int]]:
    """All (i, j, k, l) with |q_i q_j| = d1 and |q_k q_l| = d2 up to eps and
    |(q_i + r1 (q_j - q_i)) - (q_k + r2 (q_l - q_k))| <= eps."""
    R1 = pairs_at_distance(Q, d1, eps)  # @line L4
    R2 = pairs_at_distance(Q, d2, eps)
    E1 = [[Q[i][c] + r1 * (Q[j][c] - Q[i][c]) for c in range(3)] for i, j in R1]
    grid = Grid(E1, max(eps, 1e-12))
    out = []
    for k, l in R2:  # @line L5
        e2 = [Q[k][c] + r2 * (Q[l][c] - Q[k][c]) for c in range(3)]
        for s in grid.near(e2, eps):
            i, j = R1[s]
            if len({i, j, k, l}) == 4:
                out.append((i, j, k, l))
    return out


def lcp_score(P: Sequence[Sequence[float]], grid_q: Grid, R: Matrix, t: Sequence[float], delta: float) -> int:
    """The number of points p with a point of Q within delta of R p + t."""
    return sum(1 for p in P if grid_q.near(apply(R, t, p), delta))


def four_pcs(P: Sequence[Sequence[float]], Q: Sequence[Sequence[float]], delta: float,
             n_trials: int = 20, rng: Optional[random.Random] = None,
             sample: Optional[int] = None, tries: int = 30,
             max_width: float = math.inf) -> Dict[str, object]:
    """Align P to Q. `sample` limits the points of P used for the LCP score;
    `tries` and `max_width` control the base, see select_base. Returns R,
    t, the LCP score, and the number of candidate sets tried."""
    rng = rng or random.Random(0)
    grid_q = Grid(Q, delta)
    Ps = list(P) if sample is None or sample >= len(P) else rng.sample(list(P), sample)
    best = {"R": [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], "t": [0.0, 0.0, 0.0],
            "score": -1, "candidates": 0}
    for _ in range(n_trials):  # @line L1
        found = select_base(P, rng, delta, tries, max_width)  # @line L2
        if found is None:
            continue
        base, (r1, r2, d1, d2) = found  # @line L3
        for i, j, k, l in congruent_sets(Q, r1, r2, d1, d2, delta):
            best["candidates"] += 1
            R, t = kabsch([P[x] for x in base], [Q[i], Q[j], Q[k], Q[l]])  # @line L6
            if max(_dist(apply(R, t, P[x]), Q[y]) for x, y in zip(base, (i, j, k, l))) > 2.0 * delta:
                continue
            score = lcp_score(Ps, grid_q, R, t, delta)  # @line L7
            if score > best["score"]:
                best.update(R=R, t=t, score=score)
    return best  # @line L8
test_four_points_congruent_sets.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-points-congruent-sets/. The authors are listed in prov/2MMXJS.jsonl.
import itertools
import math
import random
import unittest

from cvla import det, mul, transpose
from four_points_congruent_sets import (Grid, apply, base_invariants, congruent_sets, four_pcs,
                                        kabsch, lcp_score, pairs_at_distance, select_base)


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 = max(-1.0, min(1.0, (m[0][0] + m[1][1] + m[2][2] - 1.0) / 2.0))
    return math.acos(c)


def surface(rng, n, x0=-1.0, x1=1.0):
    pts = []
    for _ in range(n):
        x, y = rng.uniform(x0, x1), rng.uniform(-1.0, 1.0)
        pts.append([x, y, 0.3 * x * y + 0.2 * x * x - 0.1 * y])
    return pts


EXAMPLE_P = [[0.0, 0.0, 0.0], [4.0, 2.0, 0.0], [0.0, 3.0, 0.0], [3.0, 0.0, 0.0],
             [1.0, 1.0, 2.0], [3.0, 3.0, 1.0], [-1.0, 2.0, 1.0], [2.0, -1.0, 2.0]]


class TestInvariants(unittest.TestCase):
    def test_example_base(self):
        r1, r2, d1, d2, gap = base_invariants(*EXAMPLE_P[:4])
        self.assertAlmostEqual(r1, 0.5)
        self.assertAlmostEqual(r2, 2.0 / 3.0)
        self.assertAlmostEqual(d1, math.sqrt(20.0))
        self.assertAlmostEqual(d2, math.sqrt(18.0))
        self.assertAlmostEqual(gap, 0.0)

    def test_ratios_are_affine_invariant(self):
        rng = random.Random(1)
        for _ in range(50):
            a, b = [rng.uniform(-1, 1) for _ in range(3)], [rng.uniform(-1, 1) for _ in range(3)]
            c = [rng.uniform(-1, 1) for _ in range(3)]
            s, u = rng.uniform(0.1, 0.9), rng.uniform(0.1, 0.9)
            e = [a[i] + s * (b[i] - a[i]) for i in range(3)]
            d = [c[i] + (e[i] - c[i]) / u for i in range(3)]  # so that e = c + u (d - c)
            M = [[rng.uniform(-2, 2) for _ in range(3)] for _ in range(3)]
            if abs(det(M)) < 0.1:
                continue
            tt = [rng.uniform(-1, 1) for _ in range(3)]
            img = [apply(M, tt, p) for p in (a, b, c, d)]
            for pts in ((a, b, c, d), img):
                inv = base_invariants(*pts)
                self.assertIsNotNone(inv)
                self.assertAlmostEqual(inv[0], s, places=8)
                self.assertAlmostEqual(inv[1], u, places=8)
                self.assertLess(inv[4], 1e-8)

    def test_segments_that_miss(self):
        self.assertIsNone(base_invariants([0, 0, 0], [1, 0, 0], [2, 1, 0], [2, -1, 0]))
        self.assertIsNone(base_invariants([0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]))


class TestSearch(unittest.TestCase):
    def test_pairs_at_distance(self):
        rng = random.Random(2)
        Q = [[rng.uniform(0, 1) for _ in range(3)] for _ in range(30)]
        got = set(pairs_at_distance(Q, 0.5, 0.05))
        want = {(i, j) for i, j in itertools.permutations(range(30), 2)
                if abs(math.dist(Q[i], Q[j]) - 0.5) <= 0.05}
        self.assertEqual(got, want)

    def test_example_congruent_sets(self):
        R = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]
        Q = [apply(R, [5.0, 0.0, 1.0], p) for p in EXAMPLE_P] + [[0.0, 0.0, 0.0], [6.0, 4.0, 1.0]]
        cands = congruent_sets(Q, 0.5, 2.0 / 3.0, math.sqrt(20.0), math.sqrt(18.0), 0.01)
        self.assertEqual(sorted(cands), [(0, 1, 2, 3), (1, 0, 2, 3)])
        Rk, tk = kabsch(EXAMPLE_P[:4], [Q[i] for i in (0, 1, 2, 3)])
        self.assertLess(rot_angle(R, Rk), 1e-9)
        self.assertEqual(lcp_score(EXAMPLE_P, Grid(Q, 0.01), Rk, tk, 0.01), 8)
        Rk, tk = kabsch(EXAMPLE_P[:4], [Q[i] for i in (1, 0, 2, 3)])
        self.assertEqual(lcp_score(EXAMPLE_P, Grid(Q, 0.01), Rk, tk, 0.01), 0)

    def test_true_image_of_base_is_found(self):
        rng = random.Random(3)
        P = surface(rng, 80)
        R, t = random_rotation(rng), [rng.uniform(-1, 1) for _ in range(3)]
        Q = [apply(R, t, p) for p in P]
        found = select_base(P, rng, 0.02)
        self.assertIsNotNone(found)
        base, (r1, r2, d1, d2) = found
        self.assertIn(base, congruent_sets(Q, r1, r2, d1, d2, 0.02))

    def test_grid_matches_brute_force(self):
        rng = random.Random(4)
        pts = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(200)]
        g = Grid(pts, 0.2)
        for _ in range(30):
            x = [rng.uniform(-1, 1) for _ in range(3)]
            want = sorted(i for i, p in enumerate(pts) if math.dist(p, x) <= 0.15)
            self.assertEqual(sorted(g.near(x, 0.15)), want)


class TestKabsch(unittest.TestCase):
    def test_exact_and_proper(self):
        rng = random.Random(5)
        R, t = random_rotation(rng), [1.0, -2.0, 0.5]
        A = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(4)]
        Rk, tk = kabsch(A, [apply(R, t, a) for a in A])
        self.assertLess(rot_angle(R, Rk), 1e-9)
        self.assertAlmostEqual(det(Rk), 1.0, places=12)
        for x, y in zip(tk, t):
            self.assertAlmostEqual(x, y, places=9)


class TestFourPCS(unittest.TestCase):
    def test_full_overlap_with_noise_and_outliers(self):
        rng = random.Random(6)
        P = surface(rng, 80)
        R, t = random_rotation(rng), [rng.uniform(-1, 1) for _ in range(3)]
        Q = [[v + rng.gauss(0.0, 0.003) for v in apply(R, t, p)] for p in P]
        Q += [[rng.uniform(-2, 2) for _ in range(3)] for _ in range(20)]
        rng.shuffle(Q)
        out = four_pcs(P, Q, 0.03, n_trials=3, rng=random.Random(7))
        self.assertLess(rot_angle(R, out["R"]), math.radians(2.0))
        self.assertGreaterEqual(out["score"], 76)

    def test_partial_overlap(self):
        rng = random.Random(8)
        S = surface(rng, 90)
        P = [p for p in S if p[0] < 0.4]
        R, t = random_rotation(rng), [rng.uniform(-1, 1) for _ in range(3)]
        Q = [[v + rng.gauss(0.0, 0.003) for v in apply(R, t, p)] for p in S if p[0] > -0.4]
        out = four_pcs(P, Q, 0.03, n_trials=40, rng=random.Random(9), tries=5, max_width=0.8)
        self.assertLess(rot_angle(R, out["R"]), math.radians(3.0))


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

History

Aiger, Mitra and Cohen-Or presented 4PCS at SIGGRAPH 2008. It belongs to a long line of methods that align shapes by matching small sets of points, from RANSAC and the alignment method of object recognition to geometric hashing. The key step of 4PCS is the use of affine invariant ratios, which lets it extract all congruent 4-point sets from the pairs of points, instead of trying all 4-tuples. Mellado, Aiger and Mitra (2014) gave a much faster way to extract these sets, which made the method practical on large scans. Open source versions of 4PCS and its faster forms exist, and they are a common first step of scan registration before ICP.

References

  1. Dror Aiger, Niloy J. Mitra and Daniel Cohen-Or, 4-points congruent sets for robust pairwise surface registration, ACM Transactions on Graphics 27(3), Article 85, 2008 (SIGGRAPH 2008), The affine invariant ratios of a coplanar four-point base, the extraction of the congruent sets from the pairs at the two base distances, the largest common pointset score, the number of trials, and the experiments on scans with noise, outliers and partial overlap
  2. 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 rigid motion between point sets by the SVD with the sign fix, used to fit each candidate set

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
  • at least three sources
  • a scene preset for the example