Algorithm Search⌘K

Algorithmadvanced

Coherent point drift

Also called CPD.

Registers two point sets by fitting one as the centroids of a Gaussian mixture to the other with EM. It has rigid, affine and non-rigid forms; the non-rigid form keeps the motion smooth.

Time
Θ(N K n) worst · averageΘ(K n) best
Space
Θ(K n) extra
Where
K = the number of centroids; N = the number of iterations; n = the number of data points
Properties
deterministicnot exactofflineiterative
Origin
Andriy Myronenko, Xubo Song, Miguel Á. Carreira Perpiñán, 2010

Coherent point drift (CPD) registers two point sets by treating one of them as a Gaussian mixture model. The points of the moving set YY are the centroids of the mixture, all with the same variance σ2\sigma^2, and the points of the fixed set XX are the data. CPD moves the centroids so that the mixture explains the data as well as possible, by the expectation maximization (EM) algorithm. The E-step computes soft correspondences: for each data point, the probability that each centroid produced it. The M-step computes the transformation that best fits these weighted pairs, in closed form for a rigid motion with scale and for an affine map. A third form allows a smooth deformation, and so solves the non-rigid registration problem. A uniform component of weight ww absorbs outliers. Each iteration does not increase the negative log-likelihood, but, like iterative closest point, CPD is a local method.

In plain words

Put a soft, round cloud of fog around each point of the first set. Now look at the second set. Each of its points asks every fog cloud: how likely is it that I came from you? Near clouds get a large share of the point, far clouds get almost nothing.

With these shares fixed, find the turn, slide and stretch of the first set that makes the shares fit best. Move the first set. Then make the fog clouds a little smaller, because the sets now match better, and ask again.

At first the fog is wide, so every point pulls a little on every other point, and small details do not matter. As the fog shrinks, the matches become sharp. A point of the second set that is far from every cloud is counted as noise and pulls on nothing.

The problem

Input. A fixed set X=(x1,…,xn)X = (x_1, \ldots, x_n) and a moving set Y=(y1,…,yK)Y = (y_1, \ldots, y_K) in RD\mathbb{R}^D, with n≥1n \ge 1 and K≥1K \ge 1; an outlier weight 0≤w<10 \le w < 1; and a family of transformations TT. (The paper writes NN for nn and MM for KK.)

Output. A transformation TT and a variance σ2\sigma^2 at a stationary point of the EM iteration for the likelihood of XX under the mixture

p(x)=wn+1−wK∑k=1K(2πσ2)−D/2exp⁡ ⁣(−∣x−T(yk)∣22σ2).p(x) = \frac{w}{n} + \frac{1 - w}{K} \sum_{k=1}^{K} (2\pi\sigma^2)^{-D/2} \exp\!\left(-\frac{|x - T(y_k)|^2}{2\sigma^2}\right).

For the rigid form, T(y)=sRy+tT(y) = s R y + t with R∈SO(D)R \in SO(D), a scale s>0s > 0 and a translation tt. For the affine form, T(y)=By+tT(y) = B y + t with any D×DD \times D matrix BB. For the non-rigid form, T(Y)=Y+GWT(Y) = Y + G W, where GG is the K×KK \times K Gaussian kernel matrix Gjk=exp⁡(−∣yj−yk∣2/(2β2))G_{jk} = \exp(-|y_j - y_k|^2 / (2\beta^2)) and WW is a K×DK \times D matrix of coefficients. The non-rigid form also adds the penalty λ2tr⁡(WTGW)\frac{\lambda}{2} \operatorname{tr}(W^{\mathsf T} G W) to the negative log-likelihood, which is the motion coherence prior: it makes nearby centroids move together. CPD does not promise the global maximum of the likelihood. The problem is a form of point cloud registration with soft correspondences.

The algorithm

In the E-step, the posterior that data point xix_i comes from centroid kk is

Pki=exp⁡(−∣xi−T(yk)∣2/(2σ2))∑j=1Kexp⁡(−∣xi−T(yj)∣2/(2σ2))+c,c=(2πσ2)D/2 w1−w Kn.P_{ki} = \frac{\exp(-|x_i - T(y_k)|^2 / (2\sigma^2))}{\sum_{j=1}^{K} \exp(-|x_i - T(y_j)|^2 / (2\sigma^2)) + c}, \qquad c = (2\pi\sigma^2)^{D/2} \, \frac{w}{1 - w} \, \frac{K}{n} .

The constant cc comes from the uniform component. A point far from every centroid gets small values PkiP_{ki} for all kk, so it has little effect on the M-step. Below, 1\mathbf 1 is a vector of ones, d⁡(v)\operatorname{d}(v) is the diagonal matrix of a vector vv, XX is the n×Dn \times D matrix of the data and YY is the K×DK \times D matrix of the centroids. The pseudocode is the rigid form.

  1. CPD-RIGID(X, Y, w, tol) ▷ X = (x_1 .. x_n), Y = (y_1 .. y_K), in R^D
  2. 1R ← I ; s ← 1 ; t ← 0 ; σ² ← (1/(D n K)) Σ_k Σ_i |x_i - y_k|²
  3. 2repeat (up to an iteration cap)
  4. 3P_ki ← E-step with T(y) = s R y + t ; E ← -Σ_i log p(x_i)
  5. 4if E_prev - E ≤ tol · max(1, |E|) or σ² ≤ σ²_min then exit the loop
  6. 5N_P ← 1ᵀ P 1 ; μ_x ← Xᵀ Pᵀ 1 / N_P ; μ_y ← Yᵀ P 1 / N_P ; X̂ ← X - 1 μ_xᵀ ; Ŷ ← Y - 1 μ_yᵀ
  7. 6A ← X̂ᵀ Pᵀ Ŷ ; U Σ Vᵀ ← SVD(A)
  8. 7R ← U diag(1, .., 1, det(U Vᵀ)) Vᵀ ; s ← tr(Aᵀ R) / tr(Ŷᵀ d(P 1) Ŷ) ; t ← μ_x - s R μ_y
  9. 8σ² ← (tr(X̂ᵀ d(Pᵀ 1) X̂) - 2 s tr(Aᵀ R) + s² tr(Ŷᵀ d(P 1) Ŷ)) / (N_P D)
  10. 9return R, s, t

Line L1 starts at the identity, with a large variance: the mean squared distance over all pairs, divided by DD. Line L3 is the E-step; it also gives the negative log-likelihood EE of the current parameters at no extra cost, because the denominators of PP are the mixture densities up to a constant. Line L4 stops when EE no longer falls by more than a relative tol, or when σ2\sigma^2 reaches a floor. Lines L5 to L8 are the M-step. Line L5 computes the weighted means and centers both sets. Line L6 forms the weighted cross-covariance AA and its SVD. Line L7 is the weighted form of the Kabsch algorithm with the sign fix of Umeyama, followed by the best scale and translation. Line L8 is the best variance for the new pose. With the scale fixed to 1, line L7 skips the scale, and line L8 keeps the same formula with s=1s = 1. The paper writes line L8 as (tr⁡(X^Td⁡(PT1)X^)−str⁡(ATR))/(NPD)(\operatorname{tr}(\hat X^{\mathsf T} \operatorname{d}(P^{\mathsf T} \mathbf 1) \hat X) - s \operatorname{tr}(A^{\mathsf T} R)) / (N_P D), which is the same value when ss is the optimal scale.

The other forms change only lines L5 to L8.

  • Affine. B=A(Y^Td⁡(P1)Y^)−1B = A (\hat Y^{\mathsf T} \operatorname{d}(P\mathbf 1) \hat Y)^{-1}, t=μx−Bμyt = \mu_x - B \mu_y and σ2=(tr⁡(X^Td⁡(PT1)X^)−tr⁡(ABT))/(NPD)\sigma^2 = (\operatorname{tr}(\hat X^{\mathsf T} \operatorname{d}(P^{\mathsf T}\mathbf 1) \hat X) - \operatorname{tr}(A B^{\mathsf T})) / (N_P D).
  • Non-rigid. Solve (G+λσ2d⁡(P1)−1)W=d⁡(P1)−1PX−Y(G + \lambda \sigma^2 \operatorname{d}(P\mathbf 1)^{-1}) W = \operatorname{d}(P\mathbf 1)^{-1} P X - Y for WW, set T(Y)=Y+GWT(Y) = Y + G W, and set σ2=(tr⁡(XTd⁡(PT1)X)−2tr⁡((PX)TT)+tr⁡(TTd⁡(P1)T))/(NPD)\sigma^2 = (\operatorname{tr}(X^{\mathsf T} \operatorname{d}(P^{\mathsf T}\mathbf 1) X) - 2 \operatorname{tr}((P X)^{\mathsf T} T) + \operatorname{tr}(T^{\mathsf T} \operatorname{d}(P\mathbf 1) T)) / (N_P D). The reference code multiplies the linear system by d⁡(P1)\operatorname{d}(P\mathbf 1), which gives (d⁡(P1)G+λσ2I)W=PX−d⁡(P1)Y(\operatorname{d}(P\mathbf 1) G + \lambda \sigma^2 I) W = P X - \operatorname{d}(P\mathbf 1) Y and avoids a division by a small entry of P1P\mathbf 1.

The width β\beta of the kernel sets how far the motion of one centroid spreads to its neighbors, and λ\lambda sets how much the method prefers smooth motion to a close fit. Both are tuning values that the user must choose.

Example

Take the moving set y1=(0,0)y_1 = (0, 0), y2=(2,0)y_2 = (2, 0), y3=(0,1)y_3 = (0, 1), y4=(1,1)y_4 = (1, 1) in the plane. The data are the same points turned by 60 degrees and moved by (0.5,0)(0.5, 0): x1=(0.5,0)x_1 = (0.5, 0), x2=(1.5,1.7321)x_2 = (1.5, 1.7321), x3=(−0.366,0.5)x_3 = (-0.366, 0.5), x4=(0.134,1.366)x_4 = (0.134, 1.366). Run rigid CPD with scale, w=0w = 0. The start variance is σ2=1.0647\sigma^2 = 1.0647. With this wide variance the first E-step spreads each point over all centroids; for example, x1x_1 gives the weights 0.379, 0.148, 0.237 and 0.237 to y1,…,y4y_1, \ldots, y_4.

M-steps angle of RR ss σ2\sigma^2 EE after the step
0 0 1 1.0647 10.5804
1 12.31° 0.3778 0.4206 8.3821
2 30.97° 0.3761 0.4058 8.2040
3 46.52° 0.4534 0.3728 7.9732
4 55.16° 0.5869 0.3040 7.5036
5 58.75° 0.7437 0.2004 6.4142
6 59.38° 0.8986 0.0821 3.1250
7 59.95° 0.9973 0.00226 -11.4655
8 60.00° 1.0000 10−1210^{-12} (the floor) -97.6274

The negative log-likelihood EE falls at every step. The scale first drops to about 0.38: with a wide variance, every data point pulls on every centroid, so the best fit squeezes the moving set toward the weighted mean. As σ2\sigma^2 falls, the soft matches become sharp, the scale returns to 1, and the eighth M-step gives the exact pose. The data fit exactly, so σ2\sigma^2 goes to 0 and the code stops at its floor 10−1210^{-12}.

CPD is local. With the same four points and the scale fixed to 1, a true rotation of 90 degrees ends at 32.6 degrees, and a true rotation of 150 degrees ends at -30.1 degrees. Both are stationary points of EM that are not the truth.

Correctness

Claim: each iteration does not increase the negative log-likelihood EE, provided NP>0N_P > 0, s>0s > 0 and the new σ2>0\sigma^2 > 0. The proof has two parts. First, the EM bound: by Jensen's inequality, E(θ)−E(θold)≤Q(θ)−Q(θold)E(\theta) - E(\theta_{\text{old}}) \le Q(\theta) - Q(\theta_{\text{old}}), where Q(θ)=12σ2∑k,iPki∣xi−T(yk)∣2+NPD2log⁡σ2Q(\theta) = \frac{1}{2\sigma^2} \sum_{k,i} P_{ki} |x_i - T(y_k)|^2 + \frac{N_P D}{2} \log \sigma^2 uses the posteriors PP of the old parameters. Second, lines L5 to L8 minimize QQ exactly. The translation drops out by centering. For a fixed scale, the rotation must maximize tr⁡(ATR)\operatorname{tr}(A^{\mathsf T} R) over SO(D)SO(D), which the SVD with the sign fix does (Umeyama's theorem). The scale and the variance then have closed forms. The affine M-step is a least squares solve. The non-rigid M-step minimizes a convex function of WW and then σ2\sigma^2, so it is a generalized EM step, and the bound holds for EE plus the penalty. The full proof is in proofs/correctness.md. The claim does not give the global maximum of the likelihood, and it does not bound the number of iterations.

Proof: Each CPD iteration does not increase the negative log-likelihoodfull

We use the notation of the page. The data points are X=(x1,…,xn)X = (x_1, \ldots, x_n) and the centroids are Y=(y1,…,yK)Y = (y_1, \ldots, y_K), all in RD\mathbb{R}^D. For a transformation TT and a variance σ2>0\sigma^2 > 0, the mixture density is

p(x∣T,σ2)=wn+1−wK∑k=1Kgk(x),gk(x)=(2πσ2)−D/2exp⁡ ⁣(−∣x−T(yk)∣22σ2),p(x \mid T, \sigma^2) = \frac{w}{n} + \frac{1 - w}{K} \sum_{k=1}^{K} g_k(x), \qquad g_k(x) = (2\pi\sigma^2)^{-D/2} \exp\!\left(-\frac{|x - T(y_k)|^2}{2\sigma^2}\right),

with a fixed outlier weight 0≤w<10 \le w < 1. The negative log-likelihood is E(T,σ2)=−∑ilog⁡p(xi∣T,σ2)E(T, \sigma^2) = -\sum_{i} \log p(x_i \mid T, \sigma^2). We assume exact arithmetic.

Claim. Let (Tj,σj2)(T_j, \sigma_j^2) be the parameters before one iteration of the rigid loop (lines L3 to L8) and (Tj+1,σj+12)(T_{j+1}, \sigma_{j+1}^2) the parameters after it. If the weight sum NP=∑k,iPkiN_P = \sum_{k,i} P_{ki} is positive, the new scale ss is positive and the new variance is positive, then E(Tj+1,σj+12)≤E(Tj,σj2)E(T_{j+1}, \sigma_{j+1}^2) \le E(T_j, \sigma_j^2). The same holds for the affine M-step, and for the non-rigid M-step when EE is replaced by E+λ2tr⁡(WTGW)E + \frac{\lambda}{2} \operatorname{tr}(W^{\mathsf T} G W) and GG is positive definite.

Lemma 1 (the EM bound). Fix the old parameters θj=(Tj,σj2)\theta_j = (T_j, \sigma_j^2) and let PkiP_{ki} be the posteriors of line L3, that is Pki=1−wKgk(xi)/p(xi∣θj)P_{ki} = \frac{1 - w}{K} g_k(x_i) / p(x_i \mid \theta_j) evaluated at θj\theta_j, and P0i=wn/p(xi∣θj)P_{0i} = \frac{w}{n} / p(x_i \mid \theta_j) for the outlier component. Define

Q(θ)=12σ2∑k,iPki∣xi−T(yk)∣2+NPD2log⁡σ2.Q(\theta) = \frac{1}{2\sigma^2} \sum_{k,i} P_{ki} |x_i - T(y_k)|^2 + \frac{N_P D}{2} \log \sigma^2 .

Then E(θ)−E(θj)≤Q(θ)−Q(θj)E(\theta) - E(\theta_j) \le Q(\theta) - Q(\theta_j) for every θ\theta.

Proof. For each ii, the posteriors P0i,P1i,…,PKiP_{0i}, P_{1i}, \ldots, P_{Ki} are positive and sum to 1. Write aki(θ)a_{ki}(\theta) for the term of component kk in p(xi∣θ)p(x_i \mid \theta), so p(xi∣θ)=∑k=0Kaki(θ)p(x_i \mid \theta) = \sum_{k=0}^{K} a_{ki}(\theta) and Pki=aki(θj)/p(xi∣θj)P_{ki} = a_{ki}(\theta_j) / p(x_i \mid \theta_j). By the concavity of the logarithm (Jensen's inequality),

log⁡p(xi∣θ)p(xi∣θj)=log⁡∑k=0KPkiaki(θ)aki(θj)≥∑k=0KPkilog⁡aki(θ)aki(θj).\log \frac{p(x_i \mid \theta)}{p(x_i \mid \theta_j)} = \log \sum_{k=0}^{K} P_{ki} \frac{a_{ki}(\theta)}{a_{ki}(\theta_j)} \ge \sum_{k=0}^{K} P_{ki} \log \frac{a_{ki}(\theta)}{a_{ki}(\theta_j)} .

The outlier term a0i=w/na_{0i} = w/n does not depend on θ\theta, so its log ratio is 0. For k≥1k \ge 1, log⁡aki(θ)=log⁡1−wK−D2log⁡(2πσ2)−∣xi−T(yk)∣22σ2\log a_{ki}(\theta) = \log\frac{1-w}{K} - \frac{D}{2} \log(2\pi\sigma^2) - \frac{|x_i - T(y_k)|^2}{2\sigma^2}. Sum over ii and change the sign. The constants cancel, and what is left is E(θ)−E(θj)≤Q(θ)−Q(θj)E(\theta) - E(\theta_j) \le Q(\theta) - Q(\theta_j). □\square

So any step that does not increase QQ does not increase EE. It remains to show that each M-step does not increase QQ.

Lemma 2 (the rigid M-step). Lines L5 to L8 return a global minimizer of QQ over R∈SO(D)R \in SO(D), s>0s > 0, t∈RDt \in \mathbb{R}^D and σ2>0\sigma^2 > 0, when NP>0N_P > 0, the new ss is positive and the new σ2\sigma^2 is positive.

Proof. Fix RR and ss. The sum ∑k,iPki∣xi−sRyk−t∣2\sum_{k,i} P_{ki} |x_i - s R y_k - t|^2 is a convex quadratic in tt. Its gradient is zero at t=μx−sRμyt = \mu_x - s R \mu_y, with the weighted means of line L5, so this tt is optimal for every RR and ss. Put it in. With the centered points x^i=xi−μx\hat x_i = x_i - \mu_x and y^k=yk−μy\hat y_k = y_k - \mu_y, the sum becomes

S(R,s)=∑i(PT1)i∣x^i∣2−2str⁡(ATR)+s2∑k(P1)k∣y^k∣2,A=X^TPTY^,S(R, s) = \sum_i (P^{\mathsf T}\mathbf 1)_i |\hat x_i|^2 - 2 s \operatorname{tr}(A^{\mathsf T} R) + s^2 \sum_k (P \mathbf 1)_k |\hat y_k|^2, \qquad A = \hat X^{\mathsf T} P^{\mathsf T} \hat Y,

because ∣Ry^k∣=∣y^k∣|R \hat y_k| = |\hat y_k|. For every fixed s>0s > 0, SS is least when tr⁡(ATR)\operatorname{tr}(A^{\mathsf T} R) is greatest. With the SVD A=UΣVTA = U \Sigma V^{\mathsf T}, the maximum of tr⁡(ATR)\operatorname{tr}(A^{\mathsf T} R) over SO(D)SO(D) is attained at R=UCVTR = U C V^{\mathsf T} with C=diag⁡(1,…,1,det⁡(UVT))C = \operatorname{diag}(1, \ldots, 1, \det(U V^{\mathsf T})). This is the theorem of Umeyama (1991), proved on the Kabsch algorithm page. Line L7 computes this RR, and it does not depend on ss. For this RR, SS is a quadratic in ss with a positive leading term, least at s=tr⁡(ATR)/∑k(P1)k∣y^k∣2s = \operatorname{tr}(A^{\mathsf T} R) / \sum_k (P\mathbf 1)_k |\hat y_k|^2, which is the ss of line L7. (With the scale fixed to 1, this step is skipped and s=1s = 1 is the only choice.) Finally, for a fixed value S>0S > 0, the function S/(2σ2)+(NPD/2)log⁡σ2S / (2\sigma^2) + (N_P D / 2) \log \sigma^2 has the derivative −S/(2σ4)+NPD/(2σ2)-S/(2\sigma^4) + N_P D/(2\sigma^2), which is negative below σ2=S/(NPD)\sigma^2 = S/(N_P D) and positive above it. Line L8 sets σ2=S/(NPD)\sigma^2 = S/(N_P D) with the least value of SS. For every fixed σ2\sigma^2, QQ increases with SS, so no other choice of (R,s,t,σ2)(R, s, t, \sigma^2) gives a smaller QQ. □\square

Lemma 3 (the affine M-step). The step B=A(Y^Td⁡(P1)Y^)−1B = A (\hat Y^{\mathsf T} \operatorname{d}(P\mathbf 1) \hat Y)^{-1}, t=μx−Bμyt = \mu_x - B \mu_y, σ2=S(B)/(NPD)\sigma^2 = S(B)/(N_P D) minimizes QQ over all BB, tt and σ2\sigma^2, when Y^Td⁡(P1)Y^\hat Y^{\mathsf T} \operatorname{d}(P\mathbf 1) \hat Y is invertible.

Proof. The translation is eliminated as in Lemma 2. What is left, ∑k,iPki∣x^i−By^k∣2\sum_{k,i} P_{ki} |\hat x_i - B \hat y_k|^2, is a convex quadratic in BB whose gradient −2(A−BY^Td⁡(P1)Y^)-2(A - B \hat Y^{\mathsf T} \operatorname{d}(P\mathbf 1)\hat Y) vanishes at the stated BB. The variance step is as in Lemma 2. □\square

Lemma 4 (the non-rigid M-step). Let GG be positive definite and let σ2\sigma^2 be fixed. The WW that solves (d⁡(P1)G+λσ2I)W=PX−d⁡(P1)Y(\operatorname{d}(P\mathbf 1) G + \lambda \sigma^2 I) W = P X - \operatorname{d}(P\mathbf 1) Y minimizes Q(Y+GW,σ2)+λ2tr⁡(WTGW)Q(Y + G W, \sigma^2) + \frac{\lambda}{2} \operatorname{tr}(W^{\mathsf T} G W) over WW.

Proof. The function is 12σ2∑k,iPki∣xi−yk−(GW)k∣2+λ2tr⁡(WTGW)\frac{1}{2\sigma^2}\sum_{k,i} P_{ki}|x_i - y_k - (GW)_k|^2 + \frac{\lambda}{2}\operatorname{tr}(W^{\mathsf T} G W) plus a constant. It is convex in WW: the first part is a convex quadratic of the linear map W↦GWW \mapsto GW, and the second part is convex because GG is positive semidefinite. Its gradient is G[1σ2(d⁡(P1)(Y+GW)−PX)+λW]G \left[ \frac{1}{\sigma^2}(\operatorname{d}(P\mathbf 1)(Y + GW) - P X) + \lambda W \right]. The stated WW makes the bracket zero, so the gradient is zero, and a stationary point of a convex function is a global minimizer. □\square

The non-rigid loop then sets σ2\sigma^2 to the minimizer for the new WW, as in Lemma 2. Two steps that each do not increase Q+λ2tr⁡(WTGW)Q + \frac{\lambda}{2}\operatorname{tr}(W^{\mathsf T} G W) give a total step that does not increase it. The penalty does not depend on σ2\sigma^2 or on PP, so Lemma 1 holds with the penalty added to both EE and QQ.

Proof of the claim. The old parameters are one candidate of each M-step, so by Lemmas 2, 3 and 4, Q(θj+1)≤Q(θj)Q(\theta_{j+1}) \le Q(\theta_j) (with the penalty in the non-rigid case). By Lemma 1, E(θj+1)−E(θj)≤Q(θj+1)−Q(θj)≤0E(\theta_{j+1}) - E(\theta_j) \le Q(\theta_{j+1}) - Q(\theta_j) \le 0. □\square

What the claim does not say. The values of EE do not increase, and they are bounded below while σ2\sigma^2 stays away from 0, so they converge. This does not mean that the parameters converge to the global minimum of EE. EM can stop at a local minimum or a saddle point, and the result depends on the start, as the example on the page shows. When the data fit exactly, σ2\sigma^2 goes to 0 and EE goes to −∞-\infty; the code stops at the floor sigma2_min.

Floating point. The code computes the sums of line L3 with a shift by the least squared distance, so the posteriors are finite even when all the Gaussian terms underflow. The tests check the nonincreasing property with a relative slack of 10−910^{-9}.

Complexity

The model is the real RAM, and DD is a constant. Line L3 computes KnK n squared distances and exponentials, Θ(Kn)\Theta(K n) time. Lines L5 and L6 compute the row sums, the column sums and AA, also Θ(Kn)\Theta(K n), and the SVD of the D×DD \times D matrix AA takes O(1)O(1) time. So a rigid or affine iteration takes Θ(Kn)\Theta(K n) time, and NN iterations take Θ(NKn)\Theta(N K n). The best case stops after the second E-step, Θ(Kn)\Theta(K n). The matrix PP needs Θ(Kn)\Theta(K n) extra space; an implementation that never stores PP can make two passes over the pairs and use Θ(K+n)\Theta(K + n) space.

The non-rigid form also forms GG in Θ(K2)\Theta(K^2) time and solves a dense K×KK \times K system in each iteration, Θ(K3)\Theta(K^3) by Gaussian elimination, so an iteration takes Θ(Kn+K3)\Theta(K n + K^3) time and Θ(Kn+K2)\Theta(K n + K^2) space. The paper lowers these costs with the fast Gauss transform for the sums of line L3 and a low-rank approximation of GG; these are approximations with their own error. The number of iterations NN has no useful bound. EM usually converges linearly, and the rate gets worse when the mixture components overlap much.

Properties

  • Monotone. The negative log-likelihood (plus the penalty in the non-rigid form) never increases.
  • Local. The result depends on the start. The example has wrong stationary points at 90 and 150 degrees.
  • Soft correspondences. No hard nearest neighbor decision is made. Every pair has a weight, which makes the cost smooth in the parameters.
  • Coarse to fine without a schedule. The variance σ2\sigma^2 is estimated, not set. It starts large and shrinks as the fit improves, which gives a coarse-to-fine search similar to the annealing of robust point matching, but driven by the data.
  • Robust to outliers in X. The uniform component with weight ww gives a data point far from all centroids a small total weight.
  • Not symmetric. XX and YY play different roles: every centroid is a mixture component, but data points can be outliers.
  • Deterministic. The same input gives the same output.

Variants and improvements

  • Fast sums. The paper uses the fast Gauss transform for the E-step and a low-rank approximation of GG for the non-rigid solve, which makes large sets practical.
  • Other kernels and priors. The motion coherence prior uses a Gaussian kernel. Other kernels, such as the thin plate spline kernel of robust point matching, give other kinds of smooth motion.
  • Fixed scale. Rigid CPD without scale is a probabilistic form of ICP with soft matches. As σ2→0\sigma^2 \to 0, each posterior becomes a hard match to the closest centroid.
  • Features. The posteriors can be multiplied by a feature similarity, so that points with different colors or descriptors do not match.
  • Bayesian forms. Later work gives a Bayesian form of CPD with a prior on the transformation and a variational EM; it is outside this page.

When to use it

Use CPD for small and medium point sets with noise and some outliers when a rough start is known. It is a good default for non-rigid registration of shapes such as contours, faces or organs, where the motion is smooth. For the rigid case on large clouds, ICP with a k-d tree is cheaper, because CPD looks at all KnK n pairs in each iteration unless the fast sums are used. Without a rough start, use a global method first, such as fast global registration or TEASER. When most of YY has no partner in XX, the model is wrong: every centroid is a component that must explain some data, so the outlier term protects only against extra points in XX.

Pitfalls

  • The roles of X and Y. YY moves and is the mixture; XX is the data and may hold outliers. Swapping them changes the result and the meaning of ww.
  • A wrong sign in line L7. Without diag⁡(1,…,1,det⁡(UVT))\operatorname{diag}(1, \ldots, 1, \det(U V^{\mathsf T})), the rotation can be a reflection.
  • Underflow in line L3. When σ2\sigma^2 is small, all terms of a column can underflow to 0, and the posterior becomes 0/0. Shift each column by its least squared distance before the exponential, as the reference code does.
  • Sigma squared reaching zero. On exact data σ2→0\sigma^2 \to 0 and log⁡σ2→−∞\log \sigma^2 \to -\infty. Use a floor and stop there.
  • Shrinking scale. In the first iterations, the rigid form with scale can shrink YY by a large factor, as in the example. It recovers on good data, but with many outliers it can stay small. Fix the scale if it is known.
  • Choice of w, beta and lambda. These are tuning values. A ww that is too large makes CPD ignore real points; a small β\beta or λ\lambda lets the non-rigid form overfit noise.
  • Units. σ2\sigma^2, β\beta and the outlier constant depend on the units. Normalize both sets to zero mean and unit variance first, and undo the normalization after.

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.

coherent_point_drift.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coherent-point-drift/. The authors are listed in prov/HWYJKB.jsonl.
"""Coherent point drift (CPD) of Myronenko and Song, 2010.

The moving set Y = [y_1, ..., y_K] gives the centroids of a Gaussian
mixture with one shared isotropic variance sigma2. The fixed set X = [x_1,
..., x_n] holds the data points. (The paper writes M for K and N for n; the
code keeps the paper's letters M and N as variable names.) A uniform
component of weight w models outliers. EM alternates two steps:

- E-step: the posterior P[k][i] that the point x_i comes from the centroid
  T(y_k).
- M-step: the transformation T and sigma2 that maximize the expected
  complete log-likelihood for this P.

Three kinds of T are given: rigid with scale (R, s, t), affine (B, t), and
non-rigid T(Y) = Y + G W with a Gaussian kernel matrix G and a penalty
(lam / 2) tr(W^T G W) on the motion field. All points are in R^D for any
D >= 1. Each iteration costs Theta(K n D) for the E-step; the non-rigid
M-step adds a dense K x K solve, Theta(K^3).

Every fit returns the negative log-likelihood of each iteration (plus the
penalty in the non-rigid case). EM makes this list nonincreasing.
"""

from __future__ import annotations

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

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

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


def _d2(a: Sequence[float], b: Sequence[float]) -> float:
    return sum((p - q) * (p - q) for p, q in zip(a, b))


def initial_sigma2(X: Sequence[Sequence[float]], TY: Sequence[Sequence[float]]) -> float:
    """sigma2 = (1 / (D N M)) sum_{m, n} |x_n - T(y_m)|^2, the start value."""
    N, M, D = len(X), len(TY), len(X[0])
    return sum(_d2(x, y) for x in X for y in TY) / (D * N * M)


def e_step(X: Sequence[Sequence[float]], TY: Sequence[Sequence[float]],
           sigma2: float, w: float) -> Tuple[Matrix, float]:
    """The posterior matrix P (M rows, N columns) and the negative
    log-likelihood of X under the mixture with centroids TY.

    P[m][n] = exp(-|x_n - T(y_m)|^2 / (2 sigma2)) / (sum_k exp(...) + c),
    with c = (2 pi sigma2)^(D/2) (w / (1 - w)) (M / N). The sums are done
    with a shift by the least distance, so no column underflows to 0 / 0."""
    N, M, D = len(X), len(TY), len(X[0])
    if not 0.0 <= w < 1.0:
        raise ValueError("w must be in [0, 1)")
    if w > 0.0:
        log_c = 0.5 * D * math.log(2.0 * math.pi * sigma2) + math.log(w / (1.0 - w)) + math.log(M / N)
    else:
        log_c = -math.inf
    base = math.log((1.0 - w) / M) - 0.5 * D * math.log(2.0 * math.pi * sigma2)
    P = [[0.0] * N for _ in range(M)]
    nll = 0.0
    for n, x in enumerate(X):
        d2 = [_d2(x, y) for y in TY]
        dmin = min(d2)
        e = [math.exp(-(d - dmin) / (2.0 * sigma2)) for d in d2]
        log_sum = math.log(sum(e))
        lc = log_c + dmin / (2.0 * sigma2)
        hi, lo = max(log_sum, lc), min(log_sum, lc)
        log_den = hi + math.log1p(math.exp(lo - hi)) if lo > -math.inf else hi
        for m in range(M):
            P[m][n] = math.exp(-(d2[m] - dmin) / (2.0 * sigma2) - log_den)
        nll -= base - dmin / (2.0 * sigma2) + log_den
    return P, nll


def _sums(P: Matrix) -> Tuple[Vector, Vector, float]:
    P1 = [sum(row) for row in P]
    Pt1 = [sum(col) for col in zip(*P)]
    return P1, Pt1, sum(P1)


def _centered(X, Y, P1, Pt1, Np):
    D = len(X[0])
    mux = [sum(Pt1[n] * X[n][d] for n in range(len(X))) / Np for d in range(D)]
    muy = [sum(P1[m] * Y[m][d] for m in range(len(Y))) / Np for d in range(D)]
    Xh = [[x[d] - mux[d] for d in range(D)] for x in X]
    Yh = [[y[d] - muy[d] for d in range(D)] for y in Y]
    return mux, muy, Xh, Yh


def _cross_cov(P: Matrix, Xh: Matrix, Yh: Matrix) -> Matrix:
    """A = Xh^T P^T Yh, a D x D matrix."""
    D = len(Xh[0])
    PXh = [[sum(row[n] * Xh[n][d] for n in range(len(Xh))) for d in range(D)] for row in P]
    return [[sum(PXh[m][i] * Yh[m][j] for m in range(len(Yh))) for j in range(D)] for i in range(D)]


def _apply_rigid(R, s, t, Y):
    return [[s * sum(R[i][k] * y[k] for k in range(len(y))) + t[i] for i in range(len(t))] for y in Y]


def _converged(hist: List[float], tol: float) -> bool:
    return len(hist) >= 2 and hist[-2] - hist[-1] <= tol * max(1.0, abs(hist[-1]))


def cpd_rigid(X: Sequence[Sequence[float]], Y: Sequence[Sequence[float]],
              w: float = 0.0, scale: bool = True, max_iter: int = 200,
              tol: float = 1e-10, sigma2_min: float = 1e-12) -> Dict[str, object]:
    """Rigid CPD: find R (det R = +1), s > 0 and t so that s R y_m + t fit X.

    With scale=False, s stays 1. Returns a dict with "R", "s", "t",
    "sigma2", "P" (the last posterior), "TY" (the moved Y) and "nll" (the
    negative log-likelihood at the start of each iteration)."""
    D = len(X[0])
    R = [[1.0 if i == j else 0.0 for j in range(D)] for i in range(D)]  # @line L1
    s, t = 1.0, [0.0] * D
    TY = [list(map(float, y)) for y in Y]
    sigma2 = initial_sigma2(X, TY)
    hist: List[float] = []
    P: Matrix = []
    for _ in range(max_iter):  # @line L2
        P, nll = e_step(X, TY, sigma2, w)  # @line L3
        hist.append(nll)
        if _converged(hist, tol) or sigma2 <= sigma2_min:  # @line L4
            break
        P1, Pt1, Np = _sums(P)  # @line L5
        mux, muy, Xh, Yh = _centered(X, Y, P1, Pt1, Np)
        A = _cross_cov(P, Xh, Yh)  # @line L6
        U, _, V = svd(A)
        C = [[1.0 if i == j else 0.0 for j in range(D)] for i in range(D)]
        C[D - 1][D - 1] = 1.0 if det(mul(U, transpose(V))) > 0.0 else -1.0
        R = mul(mul(U, C), transpose(V))  # @line L7
        trAR = sum(A[i][j] * R[i][j] for i in range(D) for j in range(D))
        yPy = sum(P1[m] * sum(v * v for v in Yh[m]) for m in range(len(Y)))
        xPx = sum(Pt1[n] * sum(v * v for v in Xh[n]) for n in range(len(X)))
        s = trAR / yPy if scale else 1.0
        t = [mux[i] - s * sum(R[i][k] * muy[k] for k in range(D)) for i in range(D)]
        sigma2 = (xPx - 2.0 * s * trAR + s * s * yPy) / (Np * D)  # @line L8
        sigma2 = max(sigma2, sigma2_min)
        TY = _apply_rigid(R, s, t, Y)
    return {"R": R, "s": s, "t": t, "sigma2": sigma2, "P": P, "TY": TY, "nll": hist}  # @line L9


def cpd_affine(X: Sequence[Sequence[float]], Y: Sequence[Sequence[float]],
               w: float = 0.0, max_iter: int = 200, tol: float = 1e-10,
               sigma2_min: float = 1e-12) -> Dict[str, object]:
    """Affine CPD: find B and t so that B y_m + t fit X. The M-step is
    B = (Xh^T P^T Yh)(Yh^T d(P1) Yh)^-1 and t = mu_x - B mu_y."""
    D = len(X[0])
    B = [[1.0 if i == j else 0.0 for j in range(D)] for i in range(D)]
    t = [0.0] * D
    TY = [list(map(float, y)) for y in Y]
    sigma2 = initial_sigma2(X, TY)
    hist: List[float] = []
    for _ in range(max_iter):
        P, nll = e_step(X, TY, sigma2, w)
        hist.append(nll)
        if _converged(hist, tol) or sigma2 <= sigma2_min:
            break
        P1, Pt1, Np = _sums(P)
        mux, muy, Xh, Yh = _centered(X, Y, P1, Pt1, Np)
        A = _cross_cov(P, Xh, Yh)
        YdY = [[sum(P1[m] * Yh[m][i] * Yh[m][j] for m in range(len(Y))) for j in range(D)] for i in range(D)]
        B = transpose(solve(YdY, transpose(A)))
        xPx = sum(Pt1[n] * sum(v * v for v in Xh[n]) for n in range(len(X)))
        trAB = sum(A[i][j] * B[i][j] for i in range(D) for j in range(D))
        t = [mux[i] - sum(B[i][k] * muy[k] for k in range(D)) for i in range(D)]
        sigma2 = max((xPx - trAB) / (Np * D), sigma2_min)
        TY = _apply_rigid(B, 1.0, t, Y)
    return {"B": B, "t": t, "sigma2": sigma2, "TY": TY, "nll": hist}


def gaussian_kernel(Y: Sequence[Sequence[float]], beta: float) -> Matrix:
    """G[i][j] = exp(-|y_i - y_j|^2 / (2 beta^2))."""
    return [[math.exp(-_d2(a, b) / (2.0 * beta * beta)) for b in Y] for a in Y]


def cpd_nonrigid(X: Sequence[Sequence[float]], Y: Sequence[Sequence[float]],
                 beta: float = 2.0, lam: float = 2.0, w: float = 0.0,
                 max_iter: int = 100, tol: float = 1e-8,
                 sigma2_min: float = 1e-12) -> Dict[str, object]:
    """Non-rigid CPD: T(Y) = Y + G W. The M-step solves
    (d(P1) G + lam sigma2 I) W = P X - d(P1) Y, the form of the paper's
    equation multiplied by d(P1), so no entry of P1 is divided by. The
    list "nll" holds the negative log-likelihood plus (lam / 2) tr(W^T G W)."""
    M, D = len(Y), len(X[0])
    G = gaussian_kernel(Y, beta)
    W = [[0.0] * D for _ in range(M)]
    TY = [list(map(float, y)) for y in Y]
    sigma2 = initial_sigma2(X, TY)
    hist: List[float] = []
    for _ in range(max_iter):
        P, nll = e_step(X, TY, sigma2, w)
        GW = mul(G, W)
        pen = 0.5 * lam * sum(W[m][d] * GW[m][d] for m in range(M) for d in range(D))
        hist.append(nll + pen)
        if _converged(hist, tol) or sigma2 <= sigma2_min:
            break
        P1, Pt1, Np = _sums(P)
        PX = [[sum(row[n] * X[n][d] for n in range(len(X))) for d in range(D)] for row in P]
        lhs = [[P1[i] * G[i][j] + (lam * sigma2 if i == j else 0.0) for j in range(M)] for i in range(M)]
        rhs = [[PX[m][d] - P1[m] * Y[m][d] for d in range(D)] for m in range(M)]
        W = solve(lhs, rhs)
        GW = mul(G, W)
        TY = [[Y[m][d] + GW[m][d] for d in range(D)] for m in range(M)]
        xPx = sum(Pt1[n] * sum(v * v for v in X[n]) for n in range(len(X)))
        cross = sum(PX[m][d] * TY[m][d] for m in range(M) for d in range(D))
        tPt = sum(P1[m] * sum(v * v for v in TY[m]) for m in range(M))
        sigma2 = max((xPx - 2.0 * cross + tPt) / (Np * D), sigma2_min)
    return {"W": W, "G": G, "TY": TY, "sigma2": sigma2, "nll": hist}
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()
test_coherent_point_drift.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coherent-point-drift/. The authors are listed in prov/HWYJKB.jsonl.
import math
import random
import unittest

from cvla import det, mul, transpose
from coherent_point_drift import (cpd_affine, cpd_nonrigid, cpd_rigid, e_step,
                                  gaussian_kernel, initial_sigma2)


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


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


def cloud(rng, n, d=3):
    return [[rng.uniform(-1.0, 1.0) for _ in range(d)] for _ in range(n)]


def move(R, s, t, Y):
    return [[s * sum(R[i][k] * y[k] for k in range(len(y))) + t[i] for i in range(len(t))] for y in Y]


def nonincreasing(hist, rel=1e-9):
    return all(b <= a + rel * max(1.0, abs(a)) for a, b in zip(hist, hist[1:]))


class TestEStep(unittest.TestCase):
    def test_columns_sum_to_one_without_outliers(self):
        rng = random.Random(1)
        X, Y = cloud(rng, 12), cloud(rng, 9)
        P, _ = e_step(X, Y, 0.3, 0.0)
        for n in range(12):
            self.assertAlmostEqual(sum(P[m][n] for m in range(9)), 1.0, places=12)

    def test_matches_direct_formula(self):
        rng = random.Random(2)
        X, Y = cloud(rng, 7), cloud(rng, 5)
        sigma2, w, D = 0.4, 0.25, 3
        P, nll = e_step(X, Y, sigma2, w)
        c = (2 * math.pi * sigma2) ** (D / 2) * w / (1 - w) * 5 / 7
        ref_nll = 0.0
        for n, x in enumerate(X):
            e = [math.exp(-sum((a - b) ** 2 for a, b in zip(x, y)) / (2 * sigma2)) for y in Y]
            for m in range(5):
                self.assertAlmostEqual(P[m][n], e[m] / (sum(e) + c), places=12)
            p = w / 7 + (1 - w) / 5 * (2 * math.pi * sigma2) ** (-D / 2) * sum(e)
            ref_nll -= math.log(p)
        self.assertAlmostEqual(nll, ref_nll, places=9)

    def test_far_point_does_not_underflow(self):
        X = [[0.0, 0.0], [1000.0, 0.0]]
        Y = [[0.0, 0.0], [0.1, 0.0]]
        P, nll = e_step(X, Y, 1e-4, 0.1)
        self.assertTrue(math.isfinite(nll))
        self.assertTrue(all(math.isfinite(v) for row in P for v in row))
        self.assertLess(P[0][1] + P[1][1], 1e-12)


class TestRigid(unittest.TestCase):
    def test_exact_recovery(self):
        rng = random.Random(3)
        Y = cloud(rng, 30)
        R0 = rotation([1.0, 2.0, -0.5], math.radians(50))
        s0, t0 = 1.3, [0.4, -0.2, 0.3]
        X = move(R0, s0, t0, Y)
        rng.shuffle(X)
        out = cpd_rigid(X, Y)
        self.assertLess(rot_angle(out["R"], R0), 1e-5)
        self.assertAlmostEqual(out["s"], s0, places=5)
        for a, b in zip(out["t"], t0):
            self.assertAlmostEqual(a, b, places=5)
        self.assertAlmostEqual(det(out["R"]), 1.0, places=12)

    def test_without_scale(self):
        rng = random.Random(4)
        Y = cloud(rng, 25)
        R0 = rotation([0.0, 0.0, 1.0], math.radians(35))
        X = move(R0, 1.0, [0.1, 0.2, 0.0], Y)
        out = cpd_rigid(X, Y, scale=False)
        self.assertEqual(out["s"], 1.0)
        self.assertLess(rot_angle(out["R"], R0), 1e-5)

    def test_noise_and_outliers(self):
        rng = random.Random(5)
        Y = cloud(rng, 40)
        R0 = rotation([0.3, -1.0, 0.4], math.radians(40))
        t0 = [0.2, 0.1, -0.3]
        X = [[v + rng.gauss(0.0, 0.01) for v in p] for p in move(R0, 1.0, t0, Y)]
        X += [[rng.uniform(-2.0, 2.0) for _ in range(3)] for _ in range(15)]
        out = cpd_rigid(X, Y, w=0.3, scale=False)
        self.assertLess(rot_angle(out["R"], R0), math.radians(1.0))
        self.assertTrue(nonincreasing(out["nll"]))

    def test_likelihood_never_rises(self):
        rng = random.Random(6)
        Y = cloud(rng, 20)
        X = [[v + rng.gauss(0.0, 0.05) for v in p]
             for p in move(rotation([1.0, 1.0, 1.0], 0.6), 0.9, [0.3, 0.0, 0.1], Y)]
        out = cpd_rigid(X, Y, w=0.1)
        self.assertGreater(len(out["nll"]), 5)
        self.assertTrue(nonincreasing(out["nll"]))

    def test_two_dimensions(self):
        rng = random.Random(7)
        Y = cloud(rng, 20, 2)
        a = math.radians(30)
        R0 = [[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]]
        X = move(R0, 1.0, [0.5, -0.5], Y)
        out = cpd_rigid(X, Y)
        self.assertAlmostEqual(out["R"][1][0], math.sin(a), places=5)
        self.assertAlmostEqual(out["s"], 1.0, places=5)

    def test_initial_sigma2(self):
        X = [[0.0, 0.0], [2.0, 0.0]]
        Y = [[0.0, 1.0]]
        self.assertAlmostEqual(initial_sigma2(X, Y), (1.0 + 5.0) / (2 * 2 * 1))


class TestAffine(unittest.TestCase):
    def test_exact_recovery(self):
        rng = random.Random(8)
        Y = cloud(rng, 30)
        B0 = [[1.1, 0.2, 0.0], [-0.1, 0.9, 0.15], [0.05, 0.0, 1.2]]
        t0 = [0.1, -0.1, 0.2]
        X = move(B0, 1.0, t0, Y)
        out = cpd_affine(X, Y)
        for i in range(3):
            for j in range(3):
                self.assertAlmostEqual(out["B"][i][j], B0[i][j], places=4)
        self.assertTrue(nonincreasing(out["nll"]))


class TestNonRigid(unittest.TestCase):
    def test_kernel(self):
        G = gaussian_kernel([[0.0], [1.0]], 1.0)
        self.assertAlmostEqual(G[0][1], math.exp(-0.5))
        self.assertEqual(G[0][0], 1.0)

    def test_objective_never_rises_and_fit_improves(self):
        rng = random.Random(9)
        Y = [[math.cos(2 * math.pi * k / 20), math.sin(2 * math.pi * k / 20)] for k in range(20)]
        X = [[y[0] + 0.15 * math.sin(3 * y[1]), y[1] + 0.1 * y[0] * y[0]] for y in Y]
        X = [[v + rng.gauss(0.0, 0.005) for v in p] for p in X]
        out = cpd_nonrigid(X, Y, beta=1.0, lam=1.0)
        self.assertTrue(nonincreasing(out["nll"]))
        before = sum(min(sum((a - b) ** 2 for a, b in zip(x, y)) for y in Y) for x in X)
        after = sum(min(sum((a - b) ** 2 for a, b in zip(x, y)) for y in out["TY"]) for x in X)
        self.assertLess(after, 0.1 * before)


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

History

Myronenko, Song and Carreira-Perpiñán presented the non-rigid method at NIPS in 2006. Myronenko and Song published the full method in IEEE TPAMI in 2010, with the rigid, affine and non-rigid forms, the uniform outlier term and fast implementations. The non-rigid prior follows the motion coherence theory of Yuille and Grzywacz, which asks that nearby points move together. Earlier methods that also used soft correspondences include the softassign method of Gold, Rangarajan and others (1998), and its thin plate spline form by Chui and Rangarajan (2003), see robust point matching. The EM algorithm itself is due to Dempster, Laird and Rubin (1977).

References

  1. Andriy Myronenko and Xubo Song, Point set registration: Coherent point drift, IEEE Transactions on Pattern Analysis and Machine Intelligence 32(12), 2010, 2262-2275, The Gaussian mixture model with the uniform outlier term, the E-step, and the closed-form M-steps of the rigid, affine and non-rigid forms; the motion coherence prior and the fast Gauss transform and low-rank speed-ups
  2. A. P. Dempster, N. M. Laird and D. B. Rubin, Maximum likelihood from incomplete data via the EM algorithm, Journal of the Royal Statistical Society, Series B 39(1), 1977, 1-38, The EM algorithm and the proof that each iteration does not decrease the likelihood
  3. Shinji Umeyama, Least-squares estimation of transformation parameters between two point patterns, IEEE Transactions on Pattern Analysis and Machine Intelligence 13(4), 1991, 376-380, The main theorem: the best rotation and scale by the SVD, with the sign of the determinant, used in the rigid M-step

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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