Algorithm Search⌘K

Algorithmresearch

Go-ICP

Also called globally optimal ICP.

Finds the rigid motion that minimizes the ICP cost over a whole box of rotations and translations, within a gap eps, by nested branch and bound with local ICP for upper bounds.

Time
O(K T n m) worst · averageΘ(n m) best
Space
O(K + T + n) extra
Where
K = the number of rotation cubes examined; T = the largest number of translation cubes examined for one rotation cube; m = the number of target points; n = the number of source points
Properties
deterministicnot exactofflineiterative
Origin
Jiaolong Yang, Hongdong Li, Yunde Jia, Dylan Campbell, 2013

Go-ICP finds the rigid motion that best aligns a source point cloud PP to a target QQ under the cost of iterative closest point, the sum of squared closest-point distances, over a whole box of rotations and translations, not only near a start pose. It searches the rotations, written as angle-axis vectors in a cube, by best-first branch and bound. For each rotation cube, an inner branch and bound over the translations gives a lower bound of the cost on the cube. Local ICP, started from the best poses that the search finds, gives upper bounds. The search stops when the best cost found is within ϵ\epsilon of the least lower bound, so the result is within ϵ\epsilon of the global minimum over the box. The bounds come from two inequalities of Yang, Li, Campbell and Jia: how far a point can move when the rotation varies in a cube, and how much each residual can change. The price is time: the search can examine many thousands of cubes.

In plain words

Plain ICP walks downhill from where it starts and stops in the first valley. Go-ICP looks at every possible turn and slide, but in a clever way.

It splits the space of all turns into boxes. For a box, it asks: what is the best cost that any turn in this box could possibly reach? A short calculation gives a number that is sure to be at most that cost. If this number is already worse than the best answer found so far, the whole box is dropped. Otherwise the box is split into eight smaller boxes, and the question is asked again.

To find good answers early, it runs plain ICP from promising places. The search ends when no box left could beat the best answer by more than a small margin ϵ\epsilon.

The problem

Input. A source P=(p1,…,pn)P = (p_1, \ldots, p_n) and a target Q={q1,…,qm}Q = \{q_1, \ldots, q_m\} in R3\mathbb{R}^3, a cube CrC_r of angle-axis vectors (by default [−π,π]3[-\pi, \pi]^3), a cube CtC_t of translations, and a gap ϵ>0\epsilon > 0. Coordinates are unitless in the tests.

Output. A pose (R,t)(R, t) with R∈SO(3)R \in SO(3) and its cost E=E(R,t)E = E(R, t), where

E(R,t)=∑i=1nei(R,t)2,ei(R,t)=min⁡j∣Rpi+t−qj∣,E(R, t) = \sum_{i=1}^{n} e_i(R, t)^2, \qquad e_i(R, t) = \min_j |R p_i + t - q_j|,

such that E<m⋆+ϵE < m^\star + \epsilon, with m⋆m^\star the least cost over the rotations RrR_r, r∈Crr \in C_r with ∣r∣≤π|r| \le \pi, and the translations t∈Ctt \in C_t. Here RrR_r is the rotation by the angle ∣r∣|r| about the axis r/∣r∣r / |r| (see the axis-angle representation); the ball ∣r∣≤π|r| \le \pi holds every rotation.

The algorithm

The bounds rest on two facts. Let rr lie in a rotation cube of half side σr\sigma_r with center r0r_0, and tt in a translation cube of half side σt\sigma_t with center t0t_0.

  • Rotation uncertainty (Theorem 1 of the paper): ∣Rrx−Rr0x∣≤γr(x)=2sin⁡(min⁡(3σr/2,π/2)) ∣x∣|R_r x - R_{r_0} x| \le \gamma_r(x) = 2 \sin(\min(\sqrt{3}\sigma_r/2, \pi/2))\, |x|. The angle between RrxR_r x and Rr0xR_{r_0} x is at most ∣r−r0∣≤3σr|r - r_0| \le \sqrt{3}\sigma_r, a lemma that goes back to Hartley and Kahl (2009), and the chord of that angle is the bound.
  • Residual bound (Theorem 2 of the paper): with γt=3σt\gamma_t = \sqrt{3}\sigma_t, ei(Rr,t)≥max⁡(ei(Rr0,t0)−γr(pi)−γt,0)e_i(R_r, t) \ge \max(e_i(R_{r_0}, t_0) - \gamma_r(p_i) - \gamma_t, 0), by the triangle inequality.

For a rotation cube with center r0r_0, the inner search minimizes f(t)=∑imax⁡(ei(Rr0,t)−γi,0)2f(t) = \sum_i \max(e_i(R_{r_0}, t) - \gamma_i, 0)^2 with γi=γr(pi)\gamma_i = \gamma_r(p_i). Since E(Rr,t)≥f(t)E(R_r, t) \ge f(t) on the cube, a lower bound of ff over CtC_t is a lower bound of EE over the cube.

  1. GO-ICP(P, Q, ε, C_r, C_t)
  2. 1(R, t, E) ← LOCAL-ICP(P, Q) from the start pose ; queue ← {(0, C_r)}
  3. 2while the queue is not empty and E - (least bound in the queue) ≥ ε
  4. 3pop the cube of least bound ; h ← its half side / 2 ; γ_i ← 2 sin(min(√3 h / 2, π/2)) |p_i|
  5. 4for each of its 8 sub-cubes, with center r0 and half side h, skipping those with |r0| - √3 h > π
  6. 5(E_t, t_b, L) ← INNER-BNB(R_r0 P, γ, Q, C_t, E, ε/2, ε)
  7. 6if t_b ≠ none and E(R_r0, t_b) < E then update (R, t, E), then run LOCAL-ICP from (R_r0, t_b) and keep it if better
  8. 7if L < E then push (L, sub-cube)
  9. 8return R, t, E
  10. INNER-BNB(X, γ, Q, C_t, E_b, δ, enough) ▷ X = R_r0 P ; f(t) = Σ max(e_i(t) - γ_i, 0)²
  11. 9E_t ← E_b ; t_b ← none ; try the center of C_t ; push C_t with its bound if the bound < E_t
  12. 10while the queue is not empty and E_t - lb ≥ δ and E_b - lb ≥ enough ▷ lb = least bound
  13. 11pop the cube of least bound ; s ← its half side / 2 ; γ_t ← √3 s ; for each of its 8 sub-cubes, center c:
  14. 12if f(c) < E_t then E_t ← f(c) ; t_b ← c
  15. 13f_low ← Σ max(e_i(c) - γ_i - γ_t, 0)² ; if f_low < E_t then push (f_low, sub-cube)
  16. 14return E_t, t_b, L = min(E_t, least bound in the queue)

The outer search (lines L1 to L8) keeps the best cost EE and a queue of rotation cubes ordered by their lower bounds. Line L3 splits the cube of least bound. Line L4 drops sub-cubes that lie wholly outside the ball of radius π\pi, since they hold no new rotation. Line L5 runs the inner search over translations with the rotation uncertainties of the sub-cube. Line L6 evaluates the true cost at the center rotation and the best translation of the inner search. If it beats EE, it becomes the new EE, and a local ICP from there often lowers EE at once. Line L7 keeps the sub-cube only if its bound can still beat EE.

The inner search (lines L9 to L14) is the same idea over translations. It stops when its best value is within δ=ϵ/2\delta = \epsilon/2 of its least bound, or when its least bound is within ϵ\epsilon of the outer EE, which is enough for the outer test. It returns a true lower bound LL of ff over CtC_t.

The reference code differs from the paper in three ways. First, the paper runs a second inner search with γ=0\gamma = 0 for the upper bound; the code reads the upper bound off the lower-bound search in line L6, which keeps the guarantee, as the proof shows, and costs much less. Second, the inner search returns a certified lower bound and uses the two stop rules of line L10. Third, closest points are found by brute force, Θ(nm)\Theta(n m) per evaluation; the paper looks them up in a precomputed 3D distance transform, which makes each lookup O(1)O(1) but adds the error of the grid.

Example

The target is 20 points drawn uniformly in [−0.6,0.6]3[-0.6, 0.6]^3 (seed 5). The source is 10 of them, moved by the inverse of a rotation of 150 degrees about the axis (1,−1,2)(1, -1, 2) and the translation (0.1,−0.05,0.08)(0.1, -0.05, 0.08), without noise. So the true cost is 0.

  • Local ICP from the identity stops at the cost 0.7042, a wrong pose.
  • Go-ICP over Cr=[−π,π]3C_r = [-\pi, \pi]^3, Ct=[−0.5,0.5]3C_t = [-0.5, 0.5]^3 and ϵ=0.01\epsilon = 0.01 returns the cost 7.2×10−317.2 \times 10^{-31} and the true pose to within 10−610^{-6}. It examines 217 rotation cubes and runs local ICP 3 times, in about 0.36 s of pure Python.

Noise makes the certificate expensive. With 6 source points out of 10 target points and Gaussian noise of standard deviation 0.03 on each coordinate, the minimum is above ϵ\epsilon, so the bounds must prune instead of stopping at a zero cost. Over a rotation cube of half side 0.3 that holds the true rotation, with Ct=[−0.2,0.2]3C_t = [-0.2, 0.2]^3 and ϵ=0.014\epsilon = 0.014, Go-ICP returns the cost 0.015472 after 248 rotation cubes and one local ICP, in about 0.74 s. The test checks it against 61 runs of local ICP from random rotations and from the true one: none of them is lower by ϵ\epsilon or more. Over the full cube [−π,π]3[-\pi, \pi]^3 with ϵ=0.01\epsilon = 0.01, the same scene takes 3980 rotation cubes and about 27 s. These times are measurements of the reference code on one machine.

Correctness

Claim: Go-ICP stops, and returns (R,t,E)(R, t, E) with E=E(R,t)E = E(R, t), det⁡R=+1\det R = +1 and E<m⋆+ϵE < m^\star + \epsilon. The invariant is: every pose of the domain has its rotation in a cube of the queue, or has a cost of at least the current EE. Cubes leave the queue only by a split, by line L4 (no rotation of the ball), or by line L7 (a bound of at least EE, which stays valid because EE only falls). The bounds are valid by the two facts above. So when the least bound in the queue is above E−ϵE - \epsilon, so is m⋆m^\star. Termination holds because the gap between the true cost and the bound of a cube of half side hh shrinks in proportion to hh, so small cubes either are dropped or end the search when they reach the top of the queue. The full proof, with a proof of the rotation uncertainty bound, is in proofs/correctness.md.

Proof: Go-ICP returns a pose within eps of the global minimum over its domain, and stopsfull

We use the notation of the page. The source is P=(p1,…,pn)P = (p_1, \ldots, p_n) and the target is Q={q1,…,qm}Q = \{q_1, \ldots, q_m\} in R3\mathbb{R}^3. For an angle-axis vector r∈R3r \in \mathbb{R}^3, Rr=Exp⁡(r)R_r = \operatorname{Exp}(r) is the rotation by the angle ∣r∣|r| about r/∣r∣r / |r|. The residuals and the cost are

ei(R,t)=min⁡j∣Rpi+t−qj∣,E(R,t)=∑i=1nei(R,t)2.e_i(R, t) = \min_j |R p_i + t - q_j|, \qquad E(R, t) = \sum_{i=1}^n e_i(R, t)^2 .

The rotation domain is a cube CrC_r of angle-axis vectors, and the translation domain is a cube CtC_t with center tct_c and half side τ\tau. A cube of half side σ\sigma is the set of points whose coordinates differ from those of its center by at most σ\sigma, so every point of it is within 3σ\sqrt{3}\sigma of the center. Let D={(r,t):r∈Cr,∣r∣≤π,t∈Ct}D = \{(r, t) : r \in C_r, |r| \le \pi, t \in C_t\} and m⋆=min⁡DE(Rr,t)m^\star = \min_D E(R_r, t); the minimum exists because DD is compact and EE is continuous. We assume exact arithmetic and eps >0> 0.

Claim. GO-ICP stops after finitely many steps and returns (R,t,E)(R, t, E) with E=E(R,t)E = E(R, t), det⁡R=+1\det R = +1 and E<m⋆+epsE < m^\star + \text{eps}.

Lemma 1 (rotation uncertainty). Let r,r0r, r_0 lie in a cube of half side σ\sigma with center r0r_0. Then for every x∈R3x \in \mathbb{R}^3,

∣Rrx−Rr0x∣≤γ(σ,x):=2sin⁡(min⁡(3σ/2, π/2)) ∣x∣.|R_r x - R_{r_0} x| \le \gamma(\sigma, x) := 2 \sin\big(\min(\sqrt{3}\sigma/2,\, \pi/2)\big)\, |x| .

Proof. Let v(s)=r0+s(r−r0)v(s) = r_0 + s (r - r_0) for s∈[0,1]s \in [0, 1] and y(s)=Rv(s)xy(s) = R_{v(s)} x. The derivative of s↦Exp⁡(v(s))s \mapsto \operatorname{Exp}(v(s)) has the form R˙=[ω]×R\dot R = [\omega]_\times R with ω=J(v)v˙\omega = \mathcal{J}(v) \dot v, where for θ=∣v∣>0\theta = |v| > 0

J(v)=I+1−cos⁡θθ2[v]×+θ−sin⁡θθ3[v]×2\mathcal{J}(v) = I + \frac{1 - \cos\theta}{\theta^2} [v]_\times + \frac{\theta - \sin\theta}{\theta^3} [v]_\times^2

is the left Jacobian of the exponential map of SO(3)SO(3), and J(0)=I\mathcal{J}(0) = I. J(v)\mathcal{J}(v) maps vv to vv, since [v]×v=0[v]_\times v = 0. For a unit vector uu orthogonal to vv, with v^=v/θ\hat v = v/\theta and u′=v^×uu' = \hat v \times u, we get [v]×u=θu′[v]_\times u = \theta u' and [v]×2u=−θ2u[v]_\times^2 u = -\theta^2 u, so J(v)u=sin⁡θθu+1−cos⁡θθu′\mathcal{J}(v) u = \frac{\sin\theta}{\theta} u + \frac{1 - \cos\theta}{\theta} u'. This vector is orthogonal to vv, and its length is 2−2cos⁡θ/θ=2sin⁡(θ/2)/θ≤1\sqrt{2 - 2\cos\theta}/\theta = 2\sin(\theta/2)/\theta \le 1. So J(v)\mathcal{J}(v) maps the line of vv and the plane orthogonal to it into themselves, it is the identity on the line, and it multiplies lengths in the plane by 2sin⁡(θ/2)/θ≤12\sin(\theta/2)/\theta \le 1. Write zz as the sum of its parts on the line and in the plane; the images of the parts are orthogonal, so ∣J(v)z∣≤∣z∣|\mathcal{J}(v) z| \le |z| for all zz. Hence ∣ω(s)∣≤∣v˙∣=∣r−r0∣|\omega(s)| \le |\dot v| = |r - r_0|.

The point y(s)y(s) stays on the sphere of radius ∣x∣|x| about the origin, and ∣y˙∣=∣ω×y∣≤∣ω∣ ∣x∣|\dot y| = |\omega \times y| \le |\omega|\,|x|. So the length of the path yy is at most ∣r−r0∣ ∣x∣|r - r_0|\,|x|. The angle φ∈[0,π]\varphi \in [0, \pi] between y(0)y(0) and y(1)y(1) times ∣x∣|x| is the length of the shortest path on the sphere between them, so φ≤∣r−r0∣≤3σ\varphi \le |r - r_0| \le \sqrt{3}\sigma. Also φ≤π\varphi \le \pi. The chord is ∣y(1)−y(0)∣=2sin⁡(φ/2)∣x∣|y(1) - y(0)| = 2 \sin(\varphi / 2) |x|, and sin⁡\sin increases on [0,π/2][0, \pi/2], so the chord is at most 2sin⁡(min⁡(3σ,π)/2)∣x∣=γ(σ,x)2 \sin(\min(\sqrt{3}\sigma, \pi)/2) |x| = \gamma(\sigma, x). □\square

Lemma 2 (residual bound). Let rr lie in the rotation cube of half side σr\sigma_r with center r0r_0, and tt in the translation cube of half side σt\sigma_t with center t0t_0. Let γi=γ(σr,pi)\gamma_i = \gamma(\sigma_r, p_i) and γt=3σt\gamma_t = \sqrt{3}\sigma_t. Then ei(Rr,t)≥max⁡(ei(Rr0,t0)−γi−γt, 0)e_i(R_r, t) \ge \max(e_i(R_{r_0}, t_0) - \gamma_i - \gamma_t,\, 0) and ei(Rr,t)≥max⁡(ei(Rr0,t)−γi,0)e_i(R_r, t) \ge \max(e_i(R_{r_0}, t) - \gamma_i, 0).

Proof. For every jj, the triangle inequality and Lemma 1 give ∣Rrpi+t−qj∣≥∣Rr0pi+t0−qj∣−∣Rrpi−Rr0pi∣−∣t−t0∣≥ei(Rr0,t0)−γi−γt|R_r p_i + t - q_j| \ge |R_{r_0} p_i + t_0 - q_j| - |R_r p_i - R_{r_0} p_i| - |t - t_0| \ge e_i(R_{r_0}, t_0) - \gamma_i - \gamma_t. Take the minimum over jj, and use ei≥0e_i \ge 0. The second bound is the case t0=tt_0 = t, γt=0\gamma_t = 0. □\square

Fix a rotation cube with center r0r_0 and half side hh, and let γi=γ(h,pi)\gamma_i = \gamma(h, p_i). Define f(t)=∑imax⁡(ei(Rr0,t)−γi,0)2f(t) = \sum_i \max(e_i(R_{r_0}, t) - \gamma_i, 0)^2. Squaring keeps the order of nonnegative numbers, so Lemma 2 gives E(Rr,t)≥f(t)E(R_r, t) \ge f(t) for every rr in the cube, and, for a translation cube of half side ss and center cc, f(t)≥f‾(c,s):=∑imax⁡(ei(Rr0,c)−γi−3s,0)2f(t) \ge \underline f(c, s) := \sum_i \max(e_i(R_{r_0}, c) - \gamma_i - \sqrt{3}s, 0)^2 for every tt in it.

Lemma 3 (the inner search). INNER-BNB, called with the bound EbE_b, returns (Et,tb,L)(E_t, t_b, L) such that: Et≤EbE_t \le E_b; if tbt_b is not None, tb∈Ctt_b \in C_t and f(tb)=Etf(t_b) = E_t; and L≤min⁡(Et,min⁡t∈Ctf(t))L \le \min(E_t, \min_{t \in C_t} f(t)). It stops after finitely many steps.

Proof. The value EtE_t starts at EbE_b (line L9) and changes only to a value f(c)f(c) at an evaluated center cc with f(c)<Etf(c) < E_t (line L12), and then tb=ct_b = c. Centers of sub-cubes of CtC_t lie in CtC_t. This gives the first two parts.

For the third part, say that a cube was not pushed when its bound f‾\underline f was at least the value of EtE_t at the time it was made. Invariant: every t∈Ctt \in C_t lies in a cube in the queue, or in a cube that was not pushed. This holds at the start, because CtC_t is pushed or not pushed in line L9, and a popped cube is the union of its 8 children, each pushed or not pushed in line L13. If tt lies in a cube that was not pushed, then f(t)≥f‾≥Etthen≥Etf(t) \ge \underline f \ge E_t^{\text{then}} \ge E_t, since EtE_t never increases. If tt lies in a cube in the queue, f(t)f(t) is at least the bound of that cube, and so at least the least bound in the queue. Line L14 returns L=min⁡(Et,least bound in the queue)L = \min(E_t, \text{least bound in the queue}), or EtE_t if the queue is empty, so L≤f(t)L \le f(t) for every t∈Ctt \in C_t, and L≤EtL \le E_t.

Termination. Let AA bound ei(Rr0,t)e_i(R_{r_0}, t) over t∈Ctt \in C_t and all ii; it exists since CtC_t is bounded. For a,g≥0a, g \ge 0 and δ≥0\delta \ge 0, max⁡(a−g,0)2−max⁡(a−g−δ,0)2≤2δmax⁡(a−g,0)≤2δA\max(a - g, 0)^2 - \max(a - g - \delta, 0)^2 \le 2\delta \max(a - g, 0) \le 2 \delta A. So for a cube of half side ss and center cc, f(c)−f‾(c,s)≤23 nAsf(c) - \underline f(c, s) \le 2\sqrt{3}\, n A s. When a cube is pushed, Et≤f(c)E_t \le f(c) already holds (line L12 runs before line L13), and EtE_t never increases. So when a cube of half side ss is at the top of the queue, Et−lb≤23 nAsE_t - \text{lb} \le 2\sqrt{3}\, n A s. Once s<δ/(23 nA)s < \delta / (2\sqrt{3}\, n A) this is below δ\delta, and line L10 stops. There are 8k8^k cubes of half side τ/2k\tau / 2^k, so only finitely many cubes of half side at least that threshold can be popped. Hence the search stops. □\square

Lemma 4 (the outer lower bound). When line L7 pushes a rotation cube with center r0r_0 and half side hh and bound LL, then E(Rr,t)≥LE(R_r, t) \ge L for every rr in that cube and t∈Ctt \in C_t.

Proof. E(Rr,t)≥f(t)≥min⁡Ctf≥LE(R_r, t) \ge f(t) \ge \min_{C_t} f \ge L by the remark after Lemma 2 and Lemma 3. □\square

Proof of the claim: the returned value. EE is set in line L1 to the cost of the pose that local ICP returns, and later only to Eu=E(Rr0,tb)\text{Eu} = E(R_{r_0}, t_b), computed from the true residuals, or to the cost that local ICP returns, which it computes at the pose it returns. So E=E(R,t)E = E(R, t) at the end. Every rotation is Rr0R_{r_0}, the identity, or a Kabsch rotation with the sign fix, so det⁡R=+1\det R = +1.

Proof of the claim: the bound. Invariant of the outer loop: every (r,t)∈D(r, t) \in D has rr in a rotation cube in the queue, or E(Rr,t)≥EE(R_r, t) \ge E for the current EE. At the start the queue holds CrC_r with the bound 0, which is a valid lower bound. When a cube is popped, its 8 children cover it. A child that line L4 drops has ∣r0∣−3h>π|r_0| - \sqrt{3}h > \pi, so every rr in it has ∣r∣≥∣r0∣−∣r−r0∣>π|r| \ge |r_0| - |r - r_0| > \pi, and it holds no point of DD. A child that line L7 does not push has L≥EL \ge E at that time, so by Lemma 4 every (r,t)(r, t) with rr in it has E(Rr,t)≥L≥EE(R_r, t) \ge L \ge E; and EE never increases later. A child that is pushed is in the queue, with a valid bound by Lemma 4. So the invariant holds. At the stop, either the queue is empty and m⋆≥Em^\star \ge E, or the least bound lb in the queue has E−lb<epsE - \text{lb} < \text{eps}, and m⋆≥min⁡(E,lb)>E−epsm^\star \ge \min(E, \text{lb}) > E - \text{eps}. In both cases E<m⋆+epsE < m^\star + \text{eps}.

Proof of the claim: termination. Each call of INNER-BNB stops by Lemma 3; it uses δ=eps/2\delta = \text{eps}/2 and the extra stop rule Eb−lb<epsE_b - \text{lb} < \text{eps} with EbE_b the current EE. Let AA bound all residuals ei(R,t)e_i(R, t) over all rotations RR and t∈Ctt \in C_t. For a rotation cube of half side hh, γi≤3h∣pi∣\gamma_i \le \sqrt{3} h |p_i|, and so for every tt, E(Rr0,t)−f(t)≤∑i2γiA≤23 hA∑i∣pi∣=:β(h)E(R_{r_0}, t) - f(t) \le \sum_i 2\gamma_i A \le 2\sqrt{3}\, h A \sum_i |p_i| =: \beta(h), by the inequality of Lemma 3 with δ=γi\delta = \gamma_i. Consider a child cube whose inner search, called with EbE_b equal to the current EE, returns (Et,tb,L)(E_t, t_b, L) with L=min⁡(Et,lb)L = \min(E_t, \text{lb}), or L=EtL = E_t if the queue is empty. The search ends in one of three ways. If the queue is empty, L=EtL = E_t. If it breaks because Et−lb<eps/2E_t - \text{lb} < \text{eps}/2, then Et−L<eps/2E_t - L < \text{eps}/2. If it breaks because Eb−lb<epsE_b - \text{lb} < \text{eps}, then L=EtL = E_t or L=lb>Eb−epsL = \text{lb} > E_b - \text{eps}. So either (i) L>Eb−epsL > E_b - \text{eps}, or (ii) Et−L<eps/2E_t - L < \text{eps}/2.

In case (i), the cube is pushed only if L<E≤EbL < E \le E_b, and then E−L<epsE - L < \text{eps}. In case (ii) with tbt_b not None, line L6 leaves E≤Eu=E(Rr0,tb)≤f(tb)+β(h)=Et+β(h)<L+eps/2+β(h)E \le \text{Eu} = E(R_{r_0}, t_b) \le f(t_b) + \beta(h) = E_t + \beta(h) < L + \text{eps}/2 + \beta(h). In case (ii) with tbt_b None, Et=Eb=EE_t = E_b = E, so E−L<eps/2E - L < \text{eps}/2. So once β(h)<eps/2\beta(h) < \text{eps}/2, a child of half side hh is either not pushed, or pushed with E−L<epsE - L < \text{eps} for the EE of that moment. Later values of EE are not larger, so the gap stays below eps. When such a cube reaches the top of the queue, line L2 stops. Only finitely many cubes have β(h)≥eps/2\beta(h) \ge \text{eps}/2, since there are 8k8^k cubes at depth kk and β(h)→0\beta(h) \to 0 as h→0h \to 0. Each pop takes finitely many steps. Hence GO-ICP stops. ■\blacksquare

Remarks. The returned pose need not lie in DD, because the local ICP of line L6 can move outside the domain; the bound compares EE with the least cost over DD, and a pose outside DD with a smaller cost only helps. In floating point the bounds are computed with rounding, so the guarantee holds up to the rounding error of the sums. The upper bound of line L6 replaces the second inner search of Yang et al. with γ=0\gamma = 0; the proof above shows that the guarantee does not need that search.

Complexity

The model is the real RAM. Each evaluation of the residuals at one pose costs Θ(nm)\Theta(n m) by brute force. The inner search for one rotation cube evaluates 8 sub-cubes per pop, so it costs O(Tnm)O(T n m) if it examines at most TT translation cubes. The outer search examines KK rotation cubes, and each one costs one inner search, so the total is O(KTnm)O(K T n m) plus the local ICP runs, which cost Θ(nm)\Theta(n m) per ICP iteration. With a distance transform, each evaluation costs Θ(n)\Theta(n) after the preprocessing of a grid.

KK and TT are not polynomial in the input in the worst case. A cube must shrink until the gap between its bound and the cost is below about ϵ\epsilon, which needs a half side proportional to ϵ\epsilon, and there are about (1/h)3(1/h)^3 cubes of half side hh in a fixed box. So the worst case grows like ϵ−3\epsilon^{-3} for each of the two searches. In practice, local ICP finds a near-optimal cost early, and most cubes are dropped at large sizes. The counts in the example are benchmark results, not bounds. The space holds the two queues and the residuals, O(K+T+n)O(K + T + n).

Properties

  • Global within ϵ\epsilon. The result is within ϵ\epsilon of the least cost over the domain, as a proved bound, not a measured rate.
  • A certificate. The least bound in the queue at the stop is a lower bound of the optimal cost.
  • Deterministic. The same input gives the same output.
  • Slow in the worst case. The running time grows quickly as ϵ\epsilon falls and as noise lifts the optimal cost above zero.
  • Sensitive to outliers in the plain form. The plain cost sums all residuals, so points without partners lift the optimum; the trimmed form handles them.

Variants and improvements

  • Trimming. The paper extends the bounds to a trimmed cost that keeps a fixed fraction of the smallest residuals, as in trimmed ICP.
  • Distance transform. A precomputed 3D distance transform of the target replaces the nearest neighbor search by a table lookup.
  • Better bounds. Later work tightens the rotation bounds or searches rotations and translations jointly, which prunes more cubes.
  • Other global methods. TEASER certifies a robust pose from feature matches. Fast global registration and 4PCS are fast, but they give no certificate of the optimum.

When to use it

Use Go-ICP when no start pose is known, the clouds are small (hundreds to a few thousand points), and a proof of near-optimality matters, for example to check other methods or in safety reviews. For large clouds or when time is short, get a rough pose by feature matching with RANSAC or by a fast global method, then refine it with ICP. If the clouds overlap only in part, use the trimmed cost. Limit the rotation and translation domains when prior knowledge allows: the example shows that a small rotation cube is much cheaper than the full one.

Pitfalls

  • A translation box that is too small in line L5. The guarantee holds only over CtC_t. If the true translation lies outside it, Go-ICP returns the best pose inside, which can be wrong. Center the clouds and choose CtC_t large enough.
  • The rotation bound without the min in line L3. Using 3h∣pi∣\sqrt{3} h |p_i| for large cubes is valid but loose; using 2sin⁡(3h/2)∣pi∣2 \sin(\sqrt{3} h / 2) |p_i| without the min is wrong when 3h>π\sqrt{3} h > \pi, because the sine then falls. Use 2sin⁡(min⁡(3h/2,π/2))∣pi∣2 \sin(\min(\sqrt{3} h/2, \pi/2)) |p_i|.
  • A best value in place of a lower bound in line L14. If the inner search returns its best value EtE_t instead of min⁡(Et,least bound)\min(E_t, \text{least bound}), the outer bound is not valid, and the search can drop the cube that holds the optimum.
  • Too small an ϵ\epsilon in line L2. With noise, a tiny gap makes the search split cubes until rounding error, and the time explodes. Choose ϵ\epsilon on the scale of the noise times the number of points.
  • Uncentered clouds. The rotation bound grows with ∣pi∣|p_i|. Center PP at its centroid first, so that the bounds are tight.

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.

cvgeom.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Camera geometry and synthetic scenes for the computer vision pages.

Conventions (prompts of the area, also stated on the pages):
- The camera frame has X to the right, Y down and Z forward. A point is in
  front of the camera if Z > 0.
- K = [[fx, s, cx], [0, fy, cy], [0, 0, 1]] in pixels.
- A world point Xw maps to the camera frame by Xc = R Xw + t. The camera
  matrix is P = K [R | t], and the center is C = -R^T t.
- Rotations are active and right-handed. Quaternions are (w, x, y, z) in the
  Hamilton convention.

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

from __future__ import annotations

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

from cvla import det, matvec, mul, solve, transpose

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


def to_h(x: Sequence[float]) -> Vector:
    """Append a 1: the homogeneous vector of a point."""
    return [float(v) for v in x] + [1.0]


def from_h(x: Sequence[float]) -> Vector:
    """Divide by the last entry and drop it. Raises ValueError if the last
    entry is zero (a point at infinity)."""
    w = x[-1]
    if w == 0:
        raise ValueError("from_h: point at infinity")
    return [v / w for v in x[:-1]]


def make_K(fx: float, fy: float, cx: float, cy: float, s: float = 0.0) -> Matrix:
    """The intrinsic matrix [[fx, s, cx], [0, fy, cy], [0, 0, 1]]."""
    return [[float(fx), float(s), float(cx)],
            [0.0, float(fy), float(cy)],
            [0.0, 0.0, 1.0]]


def camera_matrix(K: Sequence[Sequence[float]], R: Sequence[Sequence[float]],
                  t: Sequence[float]) -> Matrix:
    """The 3 x 4 camera matrix P = K [R | t]."""
    rt = [list(R[i]) + [t[i]] for i in range(3)]
    return mul(K, rt)


def project(P: Sequence[Sequence[float]], X):
    """Pixel coordinates (u, v) of a point X under the camera P.

    X is a 3D point (3 entries) or a homogeneous point (4 entries). If X is
    a list of points, the result is the list of their projections."""
    if len(X) > 0 and isinstance(X[0], (list, tuple)):
        return [project(P, x) for x in X]
    xh = to_h(X) if len(X) == 3 else list(X)
    return from_h(matvec(P, xh))


def camera_center(P: Sequence[Sequence[float]]) -> Vector:
    """The center C of a finite camera P = [M | p4]: C = -M^-1 p4, so that
    P (C, 1) = 0."""
    m = [list(row[:3]) for row in P]
    p4 = [row[3] for row in P]
    return [-v for v in solve(m, p4)]


def rot_x(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the X axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def axis_angle_to_R(axis: Sequence[float], theta: Optional[float] = None) -> Matrix:
    """Rotation by theta (radians) about the axis, by the right-hand rule
    (Rodrigues formula). The axis need not be a unit vector. If theta is
    None, axis is the rotation vector w = theta a, with theta = ||w||."""
    n = math.sqrt(sum(float(v) * float(v) for v in axis))
    if theta is None:
        theta = n
    if n == 0.0 or theta == 0.0:
        return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    x, y, z = (float(v) / n for v in axis)
    c, s = math.cos(theta), math.sin(theta)
    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 quat_to_R(q: Sequence[float]) -> Matrix:
    """Rotation matrix of the quaternion q = (w, x, y, z), Hamilton
    convention. q is normalized first; q and -q give the same matrix."""
    n = math.sqrt(sum(float(v) * float(v) for v in q))
    if n == 0.0:
        raise ValueError("quat_to_R: zero quaternion")
    w, x, y, z = (float(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 random_rotation(rng: random.Random) -> Matrix:
    """A rotation drawn from the uniform (Haar) distribution: a uniform
    random unit quaternion by the method of Shoemake (1992)."""
    u1, u2, u3 = rng.random(), rng.random(), rng.random()
    a, b = math.sqrt(1.0 - u1), math.sqrt(u1)
    q = (b * math.cos(2 * math.pi * u3), a * math.sin(2 * math.pi * u2),
         a * math.cos(2 * math.pi * u2), b * math.sin(2 * math.pi * u3))
    return quat_to_R(q)


def _small_rotation(rng: random.Random, max_angle: float) -> Matrix:
    axis = [rng.gauss(0.0, 1.0) for _ in range(3)]
    return axis_angle_to_R(axis, rng.uniform(0.0, max_angle))


def random_scene(rng: random.Random, n: int = 20, n_cams: int = 2,
                 K: Optional[Sequence[Sequence[float]]] = None,
                 cams: Optional[Sequence[Tuple]] = None,
                 radius: float = 1.0, distance: float = 5.0,
                 max_angle: float = 0.3, planar: bool = False,
                 first_identity: bool = False,
                 size: Optional[Tuple[float, float]] = None,
                 min_depth: float = 0.1) -> Dict[str, list]:
    """A synthetic scene with known cameras and points.

    Cameras: if cams is given, it is a list of (K, R, t) and is used as it
    is. Otherwise n_cams cameras look at the world origin from the distance
    `distance`. Each one is the camera at center (0, 0, -distance) with
    R = I, turned about the origin by a random rotation of angle at most
    max_angle (radians). K defaults to make_K(800, 800, 320, 240). With
    first_identity, the world frame is moved to the frame of camera 0, so
    that camera 0 has R = I and t = 0 (the points move with it).

    Points: n points drawn uniformly in the cube [-radius, radius]^3 (with
    Z = 0 if planar, before any move of the world frame). A point is kept
    only if its depth is at least min_depth in every camera, and, if size =
    (W, H) is given, if its projection lies in [0, W] x [0, H] in every
    camera. Raises ValueError if 1000 n draws are not enough.

    Returns a dict with lists "K", "R", "t", "P" (one entry per camera),
    "X" (the 3D points) and "x" (x[i][j] is the pixel of point j in
    camera i, without noise)."""
    if cams is not None:
        Ks = [[list(r) for r in c[0]] for c in cams]
        Rs = [[list(r) for r in c[1]] for c in cams]
        ts = [list(c[2]) for c in cams]
    else:
        k0 = [list(r) for r in K] if K is not None else make_K(800, 800, 320, 240)
        Ks, Rs, ts = [], [], []
        c0 = [0.0, 0.0, -float(distance)]
        for _ in range(n_cams):
            q = _small_rotation(rng, max_angle)
            r = transpose(q)
            center = matvec(q, c0)
            Ks.append([list(row) for row in k0])
            Rs.append(r)
            ts.append([-v for v in matvec(r, center)])
    pts: List[Vector] = []
    tries = 0
    while len(pts) < n:
        tries += 1
        if tries > 1000 * max(n, 1):
            raise ValueError("random_scene: cannot place the points")
        x = [rng.uniform(-radius, radius) for _ in range(3)]
        if planar:
            x[2] = 0.0
        ok = True
        for k, r, t in zip(Ks, Rs, ts):
            xc = [a + b for a, b in zip(matvec(r, x), t)]
            if xc[2] < min_depth:
                ok = False
                break
            if size is not None:
                u = (k[0][0] * xc[0] + k[0][1] * xc[1]) / xc[2] + k[0][2]
                v = k[1][1] * xc[1] / xc[2] + k[1][2]
                if not (0.0 <= u <= size[0] and 0.0 <= v <= size[1]):
                    ok = False
                    break
        if ok:
            pts.append(x)
    if first_identity and Rs:
        r0, t0 = Rs[0], ts[0]
        pts = [[a + b for a, b in zip(matvec(r0, x), t0)] for x in pts]
        r0t = transpose(r0)
        newR, newt = [], []
        for r, t in zip(Rs, ts):
            rr = mul(r, r0t)
            newR.append(rr)
            newt.append([a - b for a, b in zip(t, matvec(rr, t0))])
        Rs, ts = newR, newt
        Rs[0] = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
        ts[0] = [0.0, 0.0, 0.0]
    Ps = [camera_matrix(k, r, t) for k, r, t in zip(Ks, Rs, ts)]
    xs = [[project(p, x) for x in pts] for p in Ps]
    return {"K": Ks, "R": Rs, "t": ts, "P": Ps, "X": pts, "x": xs}


def add_noise(rng: random.Random, pts: Sequence[Sequence[float]], sigma: float) -> List[Vector]:
    """A copy of the points with independent Gaussian noise of standard
    deviation sigma added to every coordinate."""
    return [[float(v) + rng.gauss(0.0, sigma) for v in p] for p in pts]


def self_test() -> None:
    """Check random_scene and quat_to_R. Raises AssertionError."""
    rng = random.Random(11)
    scene = random_scene(rng, n=30, n_cams=4)
    for r, t in zip(scene["R"], scene["t"]):
        for x in scene["X"]:
            assert matvec(r, x)[2] + t[2] > 0.0
    for _ in range(5):
        q = [rng.gauss(0.0, 1.0) for _ in range(4)]
        r = quat_to_R(q)
        rtr = mul(transpose(r), r)
        assert all(abs(rtr[i][j] - (1.0 if i == j else 0.0)) <= 1e-12
                   for i in range(3) for j in range(3))
        assert abs(det(r) - 1.0) <= 1e-12


if __name__ == "__main__":
    self_test()
cvla.py 494 lines
# 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()
go_icp.py 214 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/go-icp/. The authors are listed in prov/AT1CTF.jsonl.
"""Go-ICP of Yang, Li, Campbell and Jia: globally optimal ICP by nested
branch and bound.

The cost is E(R, t) = sum_i e_i^2, with e_i = min_j ||R p_i + t - q_j||.
Rotations are angle-axis vectors r in a cube (by default [-pi, pi]^3, which
holds the pi-ball of all rotations). Translations are in a cube given by
its center and half side.

For a rotation cube of half side sigma_r with center r0, and a translation
cube of half side sigma_t with center t0, every (r, t) in the two cubes has

    e_i(R_r, t) >= max(e_i(R_r0, t0) - gamma_ri - gamma_t, 0),
    gamma_ri = 2 sin(min(sqrt(3) sigma_r / 2, pi / 2)) ||p_i||,
    gamma_t = sqrt(3) sigma_t.

The outer search splits rotation cubes, best first. For each cube it runs
an inner search over translation with the gamma_r of the cube, which
gives a lower bound for the whole cube. The true cost at the center
rotation and the best translation of that search is an upper bound; if it
beats the best cost E*, a local ICP starts there, which often lowers E* at
once. The search stops when E* minus the least lower bound in the queue is
below eps, so E* is within eps of the global minimum over the domain.

Three choices differ from the paper. The paper runs a second inner search
with gamma_r = 0 for the upper bound; here the upper bound is read off the
lower-bound search, which keeps the guarantee and costs much less. The
inner search returns a true lower bound (the least of its best value and
the bounds left in its queue). It stops when that bound is within eps / 2
of its best value, or within eps of E*, so the outer stop rule is always
reached and no work is spent past it. Closest points are found by brute force,
Theta(n m) per evaluation; the paper uses a distance transform.
"""

from __future__ import annotations

import heapq
import itertools
import math
from typing import Dict, List, Optional, Sequence, Tuple

from cvgeom import axis_angle_to_R
from cvla import det, mul, svd, transpose

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

SQRT3 = math.sqrt(3.0)
_SIGNS = [(a, b, c) for a in (-1.0, 1.0) for b in (-1.0, 1.0) for c in (-1.0, 1.0)]


def transform(R, t, pts) -> List[Vector]:
    """The points R p + t."""
    return [[sum(R[i][k] * p[k] for k in range(3)) + t[i] for i in range(3)] for p in pts]


def residuals(moved, t, Q) -> List[float]:
    """e_i = distance from moved[i] + t to its closest point of Q (brute force)."""
    out = []
    tx, ty, tz = t
    for x, y, z in moved:
        x, y, z = x + tx, y + ty, z + tz
        best = min((x - a) * (x - a) + (y - b) * (y - b) + (z - c) * (z - c) for a, b, c in Q)
        out.append(math.sqrt(best))
    return out


def cost(R, t, P, Q) -> float:
    """E(R, t) = sum of squared closest-point distances."""
    return sum(e * e for e in residuals(transform(R, [0.0, 0.0, 0.0], P), t, Q))


def rotation_uncertainty(norm_p: float, sigma_r: float) -> float:
    """gamma_r of Theorem 1: a bound on ||R_r p - R_r0 p|| for every r in the
    cube of half side sigma_r around r0."""
    return 2.0 * math.sin(min(SQRT3 * sigma_r / 2.0, math.pi / 2.0)) * norm_p


def _closest_index(pts, Q) -> List[int]:
    idx = []
    for x, y, z in pts:
        best, bj = float("inf"), -1
        for j, (a, b, c) in enumerate(Q):
            d = (x - a) * (x - a) + (y - b) * (y - b) + (z - c) * (z - c)
            if d < best:
                best, bj = d, j
        idx.append(bj)
    return idx


def _kabsch(P, Y) -> Tuple[Matrix, Vector]:
    n = len(P)
    pc = [sum(p[k] for p in P) / n for k in range(3)]
    yc = [sum(y[k] for y in Y) / n for k in range(3)]
    H = [[sum((p[i] - pc[i]) * (y[j] - yc[j]) for p, y in zip(P, Y)) for j in range(3)] for i in range(3)]
    U, _, V = svd(H)
    d = 1.0 if det(mul(V, transpose(U))) >= 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))
    return R, [yc[i] - sum(R[i][k] * pc[k] for k in range(3)) for i in range(3)]


def local_icp(P, Q, R, t, max_iter: int = 50) -> Tuple[Matrix, Vector, float]:
    """Point-to-point ICP from (R, t). Returns (R, t, E) with E the cost at
    the returned pose. The cost never goes up."""
    R, t = [list(r) for r in R], list(t)
    E = cost(R, t, P, Q)
    prev = None
    for _ in range(max_iter):
        idx = _closest_index(transform(R, t, P), Q)
        if idx == prev:
            break
        R2, t2 = _kabsch(P, [Q[j] for j in idx])
        E2 = cost(R2, t2, P, Q)
        if E2 >= E:
            break
        R, t, E, prev = R2, t2, E2, idx
    return R, t, E


def inner_bnb(moved, gammas, Q, t_center, t_half, E_bound, delta, enough=0.0):
    """Branch and bound over the translation cube for one rotation.

    moved holds R_r0 p_i, and gammas the rotation uncertainties gamma_ri
    (zeros to minimize the cost itself). The function to minimize is
    f(t) = sum_i max(e_i(R_r0, t) - gamma_ri, 0)^2. The search stops when
    the least bound in the queue is within delta of the best value found, or
    within enough of E_bound. Returns (E_t, t_best, L):
    E_t = min(E_bound, least f found), t_best its translation (None if no
    value below E_bound was found), and L <= min over the cube of f."""
    Et, tbest = E_bound, None  # @line L9
    e = residuals(moved, t_center, Q)
    up = sum(max(a - g, 0.0) ** 2 for a, g in zip(e, gammas))
    if up < Et:
        Et, tbest = up, list(t_center)
    gt = SQRT3 * t_half
    lb = sum(max(a - g - gt, 0.0) ** 2 for a, g in zip(e, gammas))
    count = itertools.count()
    heap = [(lb, next(count), list(t_center), t_half)] if lb < Et else []  # @line L9
    while heap:  # @line L10
        lb, _, c, s = heap[0]
        if Et - lb < delta or E_bound - lb < enough:  # @line L10
            break
        heapq.heappop(heap)
        h = s / 2.0  # @line L11
        gt = SQRT3 * h  # @line L11
        for sx, sy, sz in _SIGNS:  # @line L11
            c2 = [c[0] + sx * h, c[1] + sy * h, c[2] + sz * h]
            e = residuals(moved, c2, Q)
            up = sum(max(a - g, 0.0) ** 2 for a, g in zip(e, gammas))  # @line L12
            if up < Et:  # @line L12
                Et, tbest = up, c2
            low = sum(max(a - g - gt, 0.0) ** 2 for a, g in zip(e, gammas))  # @line L13
            if low < Et:  # @line L13
                heapq.heappush(heap, (low, next(count), c2, h))
    L = min(Et, heap[0][0]) if heap else Et  # @line L14
    return Et, tbest, L  # @line L14


def go_icp(P: Sequence[Sequence[float]], Q: Sequence[Sequence[float]], eps: float,
           t_center: Sequence[float] = (0.0, 0.0, 0.0), t_half: float = 1.0,
           r_center: Sequence[float] = (0.0, 0.0, 0.0), r_half: float = math.pi,
           R0: Optional[Sequence[Sequence[float]]] = None,
           t0: Optional[Sequence[float]] = None,
           stats: Optional[Dict[str, int]] = None) -> Tuple[Matrix, Vector, float]:
    """Globally optimal registration of P to Q by nested branch and bound.

    The rotation domain is the cube of angle-axis vectors with center
    r_center and half side r_half; the translation domain is the cube with
    center t_center and half side t_half. Sub-cubes that lie wholly outside
    the ball of radius pi are dropped, since that ball already holds every
    rotation. Returns (R, t, E) with E = cost(R, t, P, Q) and E <= m + eps,
    where m is the least cost over the domain poses whose angle-axis vector
    has norm at most pi.
    If stats is a dict, it receives the number of rotation cubes looked at
    and the number of local ICP runs."""
    if eps <= 0:
        raise ValueError("go_icp: eps must be positive")
    eye = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    R, t, E = local_icp(P, Q, R0 if R0 is not None else eye,  # @line L1
                        t0 if t0 is not None else [0.0, 0.0, 0.0])
    norms = [math.sqrt(sum(v * v for v in p)) for p in P]
    count = itertools.count()
    heap = [(0.0, next(count), list(r_center), r_half)]  # @line L1
    cubes = icp_runs = 0
    while heap:  # @line L2
        lb, _, c, s = heap[0]
        if E - lb < eps:  # @line L2
            break
        heapq.heappop(heap)
        h = s / 2.0  # @line L3
        gammas = [rotation_uncertainty(n, h) for n in norms]  # @line L3
        for sx, sy, sz in _SIGNS:  # @line L4
            r0 = [c[0] + sx * h, c[1] + sy * h, c[2] + sz * h]
            if math.sqrt(sum(v * v for v in r0)) - SQRT3 * h > math.pi:  # @line L4
                continue
            cubes += 1
            Rr = axis_angle_to_R(r0)
            moved = transform(Rr, [0.0, 0.0, 0.0], P)
            _, tb, low = inner_bnb(moved, gammas, Q, t_center, t_half, E, eps / 2.0, eps)  # @line L5
            if tb is not None:
                Eu = sum(e * e for e in residuals(moved, tb, Q))  # @line L6
                if Eu < E:  # @line L6
                    R, t, E = Rr, tb, Eu
                    icp_runs += 1
                    R2, t2, E2 = local_icp(P, Q, Rr, tb)  # @line L6
                    if E2 < E:
                        R, t, E = R2, t2, E2
            if low < E:  # @line L7
                heapq.heappush(heap, (low, next(count), r0, h))  # @line L7
    if stats is not None:
        stats["rotation_cubes"] = cubes
        stats["icp_runs"] = icp_runs
    return R, t, E  # @line L8
test_go_icp.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/go-icp/. The authors are listed in prov/AT1CTF.jsonl.
import math
import random
import unittest

from cvgeom import axis_angle_to_R, random_rotation
from cvla import det, mul, transpose
from go_icp import (cost, go_icp, inner_bnb, local_icp, residuals,
                    rotation_uncertainty, transform)

EYE = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
ZERO3 = [0.0, 0.0, 0.0]


def rot_angle(R1, R2):
    """The angle of R1^T R2: arccos((tr - 1) / 2), computed with atan2."""
    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 scene(n, m, seed, noise=0.0):
    """m target points in [-0.6, 0.6]^3. The source is n of them, moved by
    the inverse of a 150 degree rotation and a translation, plus noise.
    Returns (P, Q, R, t, r) with r the angle-axis vector of R."""
    rng = random.Random(seed)
    Q = [[rng.uniform(-0.6, 0.6) for _ in range(3)] for _ in range(m)]
    sel = rng.sample(range(m), n)
    axis = [1.0, -1.0, 2.0]
    angle = math.radians(150.0)
    R = axis_angle_to_R(axis, angle)
    t = [0.1, -0.05, 0.08]
    P = [[sum(R[k][i] * (Q[s][k] - t[k]) for k in range(3)) + rng.gauss(0.0, noise) for i in range(3)]
         for s in sel]
    na = math.sqrt(sum(a * a for a in axis))
    return P, Q, R, t, [angle * a / na for a in axis]


class TestGoICP(unittest.TestCase):
    def test_global_where_icp_fails(self):
        P, Q, R, t, _ = scene(10, 20, 5)
        self.assertGreater(local_icp(P, Q, EYE, ZERO3)[2], 0.1)
        Rg, tg, E = go_icp(P, Q, 0.01, t_half=0.5)
        self.assertLess(E, 1e-12)
        self.assertLess(rot_angle(R, Rg), 1e-6)
        self.assertLess(max(abs(a - b) for a, b in zip(t, tg)), 1e-6)
        self.assertAlmostEqual(det(Rg), 1.0, places=12)
        self.assertAlmostEqual(cost(Rg, tg, P, Q), E, places=12)

    def test_eps_optimal_against_many_icp_starts(self):
        # Noisy data, so the optimum is above eps and the bounds must prune.
        P, Q, _, _, r = scene(6, 10, 5, noise=0.03)
        eps = 0.014
        rc = [r[0] + 0.2, r[1] - 0.1, r[2] + 0.15]
        Rg, tg, E = go_icp(P, Q, eps, t_half=0.2, r_center=rc, r_half=0.3)
        self.assertGreater(E, eps)
        rng = random.Random(8)
        starts = [random_rotation(rng) for _ in range(60)] + [axis_angle_to_R(r)]
        best = min(local_icp(P, Q, R0, ZERO3)[2] for R0 in starts)
        self.assertLessEqual(E, best + eps)
        self.assertGreaterEqual(best, E - eps)
        self.assertAlmostEqual(cost(Rg, tg, P, Q), E, places=12)

    def test_rotation_uncertainty(self):
        # Theorem 1: ||R_r x - R_r0 x|| <= gamma_r for r in the cube.
        rng = random.Random(3)
        for _ in range(400):
            sigma = rng.choice([0.05, 0.3, 1.0, 2.0])
            r0 = [rng.uniform(-2.0, 2.0) for _ in range(3)]
            r = [c + rng.uniform(-sigma, sigma) for c in r0]
            x = [rng.uniform(-1.0, 1.0) for _ in range(3)]
            nx = math.sqrt(sum(v * v for v in x))
            a = transform(axis_angle_to_R(r), ZERO3, [x])[0]
            b = transform(axis_angle_to_R(r0), ZERO3, [x])[0]
            dist = math.sqrt(sum((p - q) ** 2 for p, q in zip(a, b)))
            self.assertLessEqual(dist, rotation_uncertainty(nx, sigma) + 1e-12)

    def test_residual_lower_bound(self):
        # Theorem 2: e_i(R_r, t) >= e_i(R_r0, t0) - gamma_ri - gamma_t.
        P, Q, _, _, _ = scene(6, 10, 2)
        rng = random.Random(4)
        for _ in range(100):
            sr, st = rng.uniform(0.01, 0.5), rng.uniform(0.01, 0.3)
            r0 = [rng.uniform(-1.5, 1.5) for _ in range(3)]
            t0 = [rng.uniform(-0.3, 0.3) for _ in range(3)]
            r = [c + rng.uniform(-sr, sr) for c in r0]
            t = [c + rng.uniform(-st, st) for c in t0]
            e0 = residuals(transform(axis_angle_to_R(r0), ZERO3, P), t0, Q)
            e = residuals(transform(axis_angle_to_R(r), ZERO3, P), t, Q)
            for p, a, b in zip(P, e, e0):
                g = rotation_uncertainty(math.sqrt(sum(v * v for v in p)), sr) + math.sqrt(3.0) * st
                self.assertGreaterEqual(a, b - g - 1e-12)

    def test_inner_search_against_grid(self):
        # Brute force over a grid of translations: L is below every value
        # and the best value found is within delta of the grid minimum.
        P, Q, _, _, _ = scene(6, 10, 2)
        moved = transform(axis_angle_to_R([0.3, -0.2, 0.5]), ZERO3, P)
        delta = 0.02
        for gam in (0.0, 0.05):
            gammas = [gam] * len(P)
            Et, tb, L = inner_bnb(moved, gammas, Q, ZERO3, 0.4, float("inf"), delta)
            grid = [-0.4 + 0.8 * k / 12 for k in range(13)]
            vals = [sum(max(e - gam, 0.0) ** 2 for e in residuals(moved, [x, y, z], Q))
                    for x in grid for y in grid for z in grid]
            self.assertLessEqual(L, min(vals) + 1e-12)
            self.assertLessEqual(Et, min(vals) + delta)
            self.assertAlmostEqual(sum(max(e - gam, 0.0) ** 2 for e in residuals(moved, tb, Q)), Et, places=12)

    def test_bad_eps(self):
        P, Q, _, _, _ = scene(4, 6, 1)
        with self.assertRaises(ValueError):
            go_icp(P, Q, 0.0)


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

History

Yang, Li and Jia presented Go-ICP at ICCV in 2013. The journal version, with Campbell, appeared in IEEE TPAMI in 2016, with the trimmed cost for outliers and more tests. It was the first globally optimal method for the ICP cost of 3D registration with both rotation and translation unknown. The rotation search builds on the branch and bound over rotation space of Hartley and Kahl (2009), and the trimming on the trimmed ICP of Chetverikov et al. (2002).

References

  1. Jiaolong Yang, Hongdong Li, Dylan Campbell and Yunde Jia, Go-ICP: A globally optimal solution to 3D ICP point-set registration, IEEE Transactions on Pattern Analysis and Machine Intelligence 38(11), 2016, 2241-2254, The angle-axis parametrization of rotations in the cube [-pi, pi]^3, Theorem 1 (the uncertainty radius of a rotation cube), Theorem 2 (the bounds of the residuals), the nested branch and bound with ICP for the upper bounds, the trimmed extension for outliers, and the 3D distance transform for closest-point distances
  2. Paul J. Besl and Neil D. McKay, A method for registration of 3-D shapes, IEEE Transactions on Pattern Analysis and Machine Intelligence 14(2), 1992, 239-256, The ICP algorithm and its cost, which Go-ICP minimizes globally
  3. Dmitry Chetverikov, Dmitry Svirko, Dmitry Stepanov and Pavel Krsek, The Trimmed Iterative Closest Point algorithm, Proceedings of the 16th International Conference on Pattern Recognition (ICPR 2002), volume 3, The trimmed cost that Go-ICP adopts for outliers

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