Algorithm Search⌘K

Algorithmresearch

Bundle adjustment in the large

Also called inexact Newton bundle adjustment, preconditioned conjugate gradient bundle adjustment.

Solve the reduced camera system of very large bundle adjustments approximately by conjugate gradients with block Jacobi or Schur preconditioners.

Time
O(k (m + N)) per_iteration
Space
O(m + n + N) extra
Where
N = the number of cameras; k = the number of CG iterations in one step; m = the number of observations; n = the number of points
Properties
deterministiciterativelocalmonotoneiterative
Origin
Sameer Agarwal, Noah Snavely, Steven M. Seitz, Richard Szeliski, 2010

Bundle adjustment in the large is Levenberg-Marquardt for bundle adjustment in which each damped step is computed only approximately. It keeps the point elimination of sparse bundle adjustment, but it does not form or factor the reduced camera system Sδa=eS \delta_a = e. It runs the preconditioned conjugate gradient method on that system instead. Each product Sx=U∗x−WV∗−1WTxS x = U^* x - W V^{*-1} W^{\mathsf T} x is computed block by block from the per-observation blocks, so the work and memory per CG iteration are linear in the number of observations. The preconditioner is block Jacobi on SS: the inverses of its 6×66 \times 6 diagonal blocks. CG stops early, when the residual is a fraction η\eta of the right side, as in the inexact Newton methods of Dembo, Eisenstat and Steihaug. The point steps are then recovered exactly. This is the method of choice when the number of cameras NN is so large that the dense 6N×6N6N \times 6N matrix SS, or its Cholesky factor, does not fit in memory. Among the close pages, sparse bundle adjustment solves the same system exactly, and the reduced camera system page describes the elimination itself.

In plain words

Sparse bundle adjustment shrinks the big bundle adjustment system to a system about the cameras only, and solves that exactly. With tens of thousands of cameras even that small system is too big to store and solve. This method never writes it down. It only needs to know what the system does to a vector, and it can work that out from the many tiny blocks that each photo measurement gives. With that, it solves the system roughly, by a few steps of the conjugate gradient method, which improves a guess one direction at a time. A rough answer is good enough, because the outer loop corrects it at the next step, and the usual Levenberg-Marquardt test still rejects any step that does not lower the error.

The problem

Input. As for sparse bundle adjustment: a shared intrinsic matrix KK, start values for NN cameras (Ri,ti)(R_i, t_i) and nn points XjX_j, mm observations (i,j,xij)(i, j, x_{ij}), the fixed cameras, and a damping factor τ\tau. In addition, a forcing parameter η∈(0,1)\eta \in (0, 1) and an optional cap kmax⁡k_{\max} on the CG iterations of one step. The camera frame has XX right, YY down and ZZ forward, Xc=RiXj+tiX_c = R_i X_j + t_i, and pixel centers are at integer coordinates.

Output. Cameras and points at a local minimizer of F=12∑(i,j)∥π(K(RiXj+ti))−xij∥2F = \tfrac12 \sum_{(i, j)} \|\pi(K (R_i X_j + t_i)) - x_{ij}\|^2, with FF no larger than at the start.

The algorithm

  1. INEXACT-NEWTON-BA(K, cameras, points, observations, τ, η, k_max)
  2. 1ν <- 2 ; build U_i, V_j, W_ij, g_a, g_b from the observation blocks
  3. 2μ <- τ · max diagonal entry of U and V
  4. 3loop
  5. 4if ||g||_∞ <= ε_1 then return
  6. 5V*_j^-1 <- (V_j + μ I)^-1 for each point ; e <- -g_a + W V*^-1 g_b
  7. 6P_i <- (U_i + μ I - Σ_j W_ij V*_j^-1 W_ij^T)^-1 for each free camera ▷ block Jacobi
  8. 7δa <- PCG from 0 on S δa = e, with S x computed as U* x - W (V*^-1 (W^T x)) and preconditioner P, until ||e - S δa|| <= η ||e|| or k_max iterations
  9. 8for each point j: δb_j <- -V*_j^-1 (g_b,j + Σ_i W_ij^T δa_i)
  10. 9if ||δ|| <= ε_2 (||x|| + ε_2) then return
  11. 10pred <- -g^T δ - ½ ||J δ||^2 ; ρ <- (F(x) - F(x ⊕ δ)) / pred
  12. 11if ρ > 0 then x <- x ⊕ δ ; rebuild the blocks ; μ <- μ · max(1/3, 1 - (2ρ - 1)^3) ; ν <- 2
  13. 12else μ <- μ ν ; ν <- 2 ν
  14. 13return cameras, points

Lines L1 to L4 and L9 to L12 are the Levenberg-Marquardt loop of sparse bundle adjustment. Line L5 inverts the 3×33 \times 3 point blocks and forms the right side of the reduced system. Line L6 builds the block Jacobi preconditioner: each diagonal block SiiS_{ii} gets one 6×66 \times 6 term for each point that camera ii sees, so this costs O(m)O(m). Line L7 is the inexact solve. A product with SS first gathers WTxW^{\mathsf T} x point by point, multiplies by the 3×33 \times 3 inverses, and scatters the result back to the cameras. Line L8 is the exact back-substitution. Line L10 computes the predicted reduction from its definition, with ∥Jδ∥2=δaTUδa+2δaTWδb+δbTVδb\|J \delta\|^2 = \delta_a^{\mathsf T} U \delta_a + 2 \delta_a^{\mathsf T} W \delta_b + \delta_b^{\mathsf T} V \delta_b. The short formula 12δT(μδ−g)\tfrac12 \delta^{\mathsf T} (\mu \delta - g) of exact Levenberg-Marquardt is wrong here, because the step does not solve the damped system.

Example

The test scene is the one of the sparse bundle adjustment page: 4 cameras, camera 0 fixed, 20 points, 80 observations, an 18×1818 \times 18 matrix SS, and a start with an RMS reprojection error of 34.1 pixels. With τ=10−3\tau = 10^{-3}:

setting steps tried accepted CG iterations in all final RMS (pixels)
η=10−10\eta = 10^{-10}, no cap 13 12 226 4.6⋅10−134.6 \cdot 10^{-13}
η=0.1\eta = 0.1, no cap 13 12 68 7.9⋅10−127.9 \cdot 10^{-12}
η=0.5\eta = 0.5, at most 3 per step 42 41 97 7.5⋅10−117.5 \cdot 10^{-11}

With η=10−10\eta = 10^{-10} the costs agree with the exact solve of sparse bundle adjustment to the printed digits (1.240⋅1021.240 \cdot 10^{2}, 1.739⋅1011.739 \cdot 10^{1}, 3.413.41 after the first three steps), and CG uses up to 18 iterations, the size of SS. With η=0.1\eta = 0.1 the costs after the first three steps are 1.201⋅1021.201 \cdot 10^{2}, 1.551⋅1011.551 \cdot 10^{1} and 3.283.28: almost the same progress for a third of the CG work. The CG count per step grows from 2 near the start to 8 near the end, because the right side becomes small and the same relative accuracy needs more iterations. With a loose η=0.5\eta = 0.5 and a cap of 3, the method still converges and every accepted step lowers the cost, but it needs three times as many outer steps, each with a full rebuild of the blocks. On the first reduced system, block Jacobi preconditioning reaches a relative residual of 10−310^{-3} in 4 CG iterations and 10−610^{-6} in 9, against 9 and 15 without a preconditioner. These numbers are measurements on this small scene; on large scenes the counts and the trade-offs differ.

Correctness

The implicit product equals SxS x, and SS and the block Jacobi preconditioner are symmetric positive definite for μ>0\mu > 0 (theorem). With the exact back-substitution, the full step is the minimizer of the damped model over δb\delta_b for the given δa\delta_a, so the damped model equals a quadratic q(δa)q(\delta_a) in the cameras; CG from 00 never increases qq, and so the damped model at the step is at most q(0)≤0q(0) \le 0, and below it when g≠0g \ne 0. It follows that the predicted reduction is at least 12μ∥δ∥2>0\tfrac12 \mu \|\delta\|^2 > 0 for any number of CG iterations, that accepted steps lower FF strictly, and that a non-stationary point is left after finitely many rejections (theorems). The forcing parameter η\eta only affects the speed. For Newton's method on systems of equations, Dembo, Eisenstat and Steihaug proved local linear convergence for a relative residual bounded by a constant below 1, and superlinear convergence when it tends to 0 (theorem, for that setting). The proof file below gives the details.

Proof: Inexact Newton bundle adjustment computes the reduced camera system correctly and every truncated step is safefull

We use the notation of the page and of the sparse bundle adjustment page. The parameters are ordered as the free cameras (6 each) and then the points (3 each). JJ is the Jacobian of the residual at the current parameters with respect to the local update, g=JTrg = J^{\mathsf T} r, and

JTJ=(UWWTV),U∗=U+μI,V∗=V+μI,μ>0.J^{\mathsf T} J = \begin{pmatrix} U & W \\ W^{\mathsf T} & V \end{pmatrix}, \qquad U^* = U + \mu I, \quad V^* = V + \mu I, \quad \mu > 0.

UU and VV are block diagonal, with 6×66 \times 6 blocks UiU_i and 3×33 \times 3 blocks VjV_j, and WW has the 6×36 \times 3 block WijW_{ij} when camera ii sees point jj. The reduced camera matrix is S=U∗−WV∗−1WTS = U^* - W V^{*-1} W^{\mathsf T}, and the right side is e=−ga+WV∗−1gbe = -g_a + W V^{*-1} g_b.

Claim. (a) apply returns SxS x and rhs returns ee. (b) SS and its diagonal blocks are symmetric positive definite, so the block Jacobi preconditioner of line L6 exists and is positive definite, and in exact arithmetic PCG reaches the exact solution in at most 6Nf6N_f iterations, where NfN_f is the number of free cameras. (c) Let δ=(δa,δb)\delta = (\delta_a, \delta_b), where δa\delta_a is the PCG iterate after any number k≥1k \ge 1 of iterations (or k=0k = 0 when e=0e = 0) and δb\delta_b comes from line L8. Then the damped model mμ(δ)=gTδ+12δT(JTJ+μI)δm_\mu(\delta) = g^{\mathsf T} \delta + \tfrac12 \delta^{\mathsf T} (J^{\mathsf T} J + \mu I) \delta satisfies mμ(δ)≤0m_\mu(\delta) \le 0, and if g≠0g \ne 0 then mμ(δ)<0m_\mu(\delta) < 0 and the predicted reduction pred⁡=−gTδ−12∥Jδ∥2\operatorname{pred} = -g^{\mathsf T} \delta - \tfrac12 \|J \delta\|^2 computed in line L10 is positive. (d) Accepted steps lower FF strictly, and at a point with g≠0g \ne 0 only finitely many steps are rejected before one is accepted.

Proof of (a). For a vector xx over the free cameras, (WTx)j=∑i sees jWijTxi(W^{\mathsf T} x)_j = \sum_{i \text{ sees } j} W_{ij}^{\mathsf T} x_i, then zj=Vj∗−1(WTx)jz_j = V_j^{*-1} (W^{\mathsf T} x)_j because V∗V^* is block diagonal, and (Wz)i=∑j seen by iWijzj(W z)_i = \sum_{j \text{ seen by } i} W_{ij} z_j. The code computes zjz_j for each point from the cameras that see it, and subtracts WijzjW_{ij} z_j from the block of camera ii for each such camera. Together with Ui∗xiU_i^* x_i this is U∗x−WV∗−1WTx=SxU^* x - W V^{*-1} W^{\mathsf T} x = S x. The same argument with xx replaced by gbg_b in the point space gives ee. □\square

Proof of (b). M=JTJ+μIM = J^{\mathsf T} J + \mu I is positive definite because vTMv=∥Jv∥2+μ∥v∥2v^{\mathsf T} M v = \|J v\|^2 + \mu \|v\|^2. Each Vj∗V_j^* is a diagonal block of MM, so it is positive definite and invertible. For a≠0a \ne 0 put b=−V∗−1WTab = -V^{*-1} W^{\mathsf T} a; then (a,b)TM(a,b)=aTSa(a, b)^{\mathsf T} M (a, b) = a^{\mathsf T} S a, as on the sparse bundle adjustment page, so SS is positive definite. A diagonal block Sii=EiTSEiS_{ii} = E_i^{\mathsf T} S E_i, with EiE_i the 66 columns of camera ii in the identity, is positive definite too, and so is its inverse. So the preconditioner P=diag⁡(Sii−1)P = \operatorname{diag}(S_{ii}^{-1}) is positive definite. PCG with a symmetric positive definite matrix SS and preconditioner PP is the conjugate gradient method applied to LTSLL^{\mathsf T} S L with P=LLTP = L L^{\mathsf T}, and conjugate gradients on a positive definite matrix of order 6Nf6N_f reach the exact solution in at most 6Nf6N_f iterations in exact arithmetic (Nocedal and Wright, Theorem 5.1 and Section 5.1). The check pTSp≤0p^{\mathsf T} S p \le 0 in pcg therefore never fires in exact arithmetic. □\square

Proof of (c). Fix δa\delta_a and minimize mμ(δa,δb)m_\mu(\delta_a, \delta_b) over δb\delta_b. The terms with δb\delta_b are gbTδb+δaTWδb+12δbTV∗δbg_b^{\mathsf T} \delta_b + \delta_a^{\mathsf T} W \delta_b + \tfrac12 \delta_b^{\mathsf T} V^* \delta_b, a strictly convex quadratic whose minimizer is δb=−V∗−1(gb+WTδa)\delta_b = -V^{*-1} (g_b + W^{\mathsf T} \delta_a). This is line L8. Putting it back gives

mμ(δa,δb)=q(δa):=12δaTSδa−eTδa−12gbTV∗−1gb,m_\mu(\delta_a, \delta_b) = q(\delta_a) := \tfrac12 \delta_a^{\mathsf T} S \delta_a - e^{\mathsf T} \delta_a - \tfrac12 g_b^{\mathsf T} V^{*-1} g_b,

which one checks by expanding: the cross terms collect to −12(gb+WTδa)TV∗−1(gb+WTδa)-\tfrac12 (g_b + W^{\mathsf T} \delta_a)^{\mathsf T} V^{*-1} (g_b + W^{\mathsf T} \delta_a), and δaTWV∗−1WTδa\delta_a^{\mathsf T} W V^{*-1} W^{\mathsf T} \delta_a together with 12δaTU∗δa\tfrac12 \delta_a^{\mathsf T} U^* \delta_a gives 12δaTSδa\tfrac12 \delta_a^{\mathsf T} S \delta_a, while gaTδa−δaTWV∗−1gb=−eTδag_a^{\mathsf T} \delta_a - \delta_a^{\mathsf T} W V^{*-1} g_b = -e^{\mathsf T} \delta_a.

PCG started at 00 produces iterates xkx_k that minimize qq over the nested affine sets Kk=span⁡{Pe,(PS)Pe,…,(PS)k−1Pe}\mathcal{K}_k = \operatorname{span}\{P e, (P S) P e, \dots, (P S)^{k-1} P e\} (the minimization property of conjugate gradients, applied to the transformed system; Nocedal and Wright, Theorem 5.2). Since 0∈Kk0 \in \mathcal{K}_k, q(xk)≤q(0)=−12gbTV∗−1gb≤0q(x_k) \le q(0) = -\tfrac12 g_b^{\mathsf T} V^{*-1} g_b \le 0. If e≠0e \ne 0 and k≥1k \ge 1, the first iterate is x1=α0Pex_1 = \alpha_0 P e with α0=eTPe/(eTPSPe)>0\alpha_0 = e^{\mathsf T} P e / (e^{\mathsf T} P S P e) > 0, and q(x1)−q(0)=−12(eTPe)2/(eTPSPe)<0q(x_1) - q(0) = -\tfrac12 (e^{\mathsf T} P e)^2 / (e^{\mathsf T} P S P e) < 0, so then q(xk)<q(0)q(x_k) < q(0).

So mμ(δ)≤0m_\mu(\delta) \le 0. Now let g≠0g \ne 0. If gb≠0g_b \ne 0, then q(0)<0q(0) < 0 because V∗−1V^{*-1} is positive definite. If gb=0g_b = 0, then ga≠0g_a \ne 0 and e=−ga≠0e = -g_a \ne 0, and q(xk)<q(0)=0q(x_k) < q(0) = 0 by the last remark. In both cases mμ(δ)<0m_\mu(\delta) < 0, so δ≠0\delta \ne 0. Finally

pred⁡=−gTδ−12∥Jδ∥2=−mμ(δ)+12μ∥δ∥2>0.\operatorname{pred} = -g^{\mathsf T} \delta - \tfrac12 \|J \delta\|^2 = -m_\mu(\delta) + \tfrac12 \mu \|\delta\|^2 > 0.

The code computes ∥Jδ∥2=δaTUδa+2δaTWδb+δbTVδb\|J \delta\|^2 = \delta_a^{\mathsf T} U \delta_a + 2 \delta_a^{\mathsf T} W \delta_b + \delta_b^{\mathsf T} V \delta_b from the blocks, which is δTJTJδ\delta^{\mathsf T} J^{\mathsf T} J \delta. □\square

Note that the formula 12δT(μδ−g)\tfrac12 \delta^{\mathsf T} (\mu \delta - g) used for exact Levenberg-Marquardt steps is wrong here: it uses (JTJ+μI)δ=−g(J^{\mathsf T} J + \mu I) \delta = -g, which an inexact step does not satisfy, so it would give a wrong ρ\rho. This is why line L10 computes the reduction directly.

Proof of (d). A step is accepted only if ρ>0\rho > 0, that is F(x⊕δ)<F(x)F(x \oplus \delta) < F(x) because pred⁡>0\operatorname{pred} > 0. So accepted costs decrease strictly.

Let g≠0g \ne 0. Each rejection multiplies μ\mu by at least 22, so μ→∞\mu \to \infty along a run of rejections. From mμ(δ)≤0m_\mu(\delta) \le 0 we get 12μ∥δ∥2≤12δT(JTJ+μI)δ≤−gTδ≤∥g∥∥δ∥\tfrac12 \mu \|\delta\|^2 \le \tfrac12 \delta^{\mathsf T} (J^{\mathsf T} J + \mu I) \delta \le -g^{\mathsf T} \delta \le \|g\| \|\delta\|, so ∥δ∥≤2∥g∥/μ→0\|\delta\| \le 2 \|g\| / \mu \to 0. The function ϕ(δ)=12∥r(x⊕δ)∥2\phi(\delta) = \tfrac12 \|r(x \oplus \delta)\|^2 is twice continuously differentiable near 00 (for points in front of the cameras), with ϕ(0)=F\phi(0) = F, ∇ϕ(0)=g\nabla \phi(0) = g. So there is a constant CC with ∣ϕ(δ)−F−gTδ∣≤C∥δ∥2|\phi(\delta) - F - g^{\mathsf T} \delta| \le C \|\delta\|^2 for small δ\delta, and hence

∣F(x)−F(x⊕δ)−pred⁡∣=∣ϕ(δ)−F−gTδ−12∥Jδ∥2∣≤(C+12∥J∥2)∥δ∥2.|F(x) - F(x \oplus \delta) - \operatorname{pred}| = |\phi(\delta) - F - g^{\mathsf T} \delta - \tfrac12 \|J \delta\|^2| \le (C + \tfrac12 \|J\|^2) \|\delta\|^2.

By (c), pred⁡≥12μ∥δ∥2\operatorname{pred} \ge \tfrac12 \mu \|\delta\|^2. Dividing, ∣ρ−1∣≤(2C+∥J∥2)/μ→0|\rho - 1| \le (2C + \|J\|^2) / \mu \to 0. So after finitely many rejections ρ>0\rho > 0 and the step is accepted. □\square

Remarks. The argument of (c) and (d) uses only mμ(δ)≤0m_\mu(\delta) \le 0, δ≠0\delta \ne 0 and the exact back-substitution, not the size of the CG residual. So the forcing parameter η\eta and the cap on the CG iterations only affect the speed, never the safety. The speed is a separate question: for Newton's method on a system of equations, Dembo, Eisenstat and Steihaug (1982) prove local linear convergence when the relative residual stays below a constant ηmax⁡<1\eta_{\max} < 1, and superlinear convergence when it tends to 00. The same rates for Levenberg-Marquardt with μ\mu and η\eta both tending to 00 need further conditions, which this proof does not cover.

Complexity

In the real RAM model, with m≥nm \ge n and m≥Nm \ge N (every point and camera is observed): building the blocks costs O(m)O(m), line L5 costs O(m)O(m), and line L6 costs O(m+N)O(m + N) for the products and the NN inversions of 6×66 \times 6 blocks. One product with SS costs O(m+N)O(m + N), and one preconditioner application O(N)O(N). So one outer step with kk CG iterations costs O((k+1)(m+N))O((k + 1)(m + N)), written O(k(m+N))O(k (m + N)) for k≥1k \ge 1. The memory is O(m+n+N)O(m + n + N): the blocks WijW_{ij}, VjV_j, UiU_i and a few vectors. Nothing of size N2N^2 is stored. Sparse bundle adjustment needs O(m+∑jcj2+N3)O(m + \sum_j c_j^2 + N^3) time and O(N2)O(N^2) memory per step instead. In exact arithmetic CG needs at most 6N6N iterations, but the point of the method is to stop much earlier; the count depends on the conditioning of the preconditioned SS, which in turn depends on the scene.

Properties

  • Matrix free. Only products with SS are needed; SS is never formed.
  • Safe at any accuracy (theorem). Any number of CG iterations gives a step with positive predicted reduction, as long as the points are back-substituted exactly.
  • Monotone (theorem). Accepted costs decrease strictly.
  • Slower final convergence. With a fixed η\eta the last steps are only as accurate as η\eta allows; to get a fast final rate, η\eta must go to 00.
  • Parallel. The products and the preconditioner are sums over observations and points, and parallelize well.

Variants and improvements

  • Explicit Schur complement. Form SS as a sparse matrix and run CG on it. This saves work per iteration when SS is sparse, at the price of storing it.
  • Other preconditioners. Agarwal et al. compare several preconditioners, among them the block diagonal of SS, which they call Schur-Jacobi and which is the one used here. Visibility based preconditioners group the cameras by the points they share, and incomplete Cholesky of SS is another option.
  • CG on the full system. Byröd and Åström (2010) run preconditioned conjugate gradients on the least squares problem itself instead of on the reduced system.
  • Adaptive forcing. Choose η\eta per step, for example smaller as the gradient shrinks, so that the final convergence is fast. The ideas come from the inexact Newton literature, such as the choices of Eisenstat and Walker.
  • Trust region version. Run truncated CG inside a trust region, stopping when the iterate reaches the boundary, as in the Steihaug method; this fits Powell's dog leg method and other trust region frameworks.
  • Software. The Ceres Solver library provides an iterative Schur solver of this kind, next to the direct sparse solvers.

When to use it

Use it for bundle adjustment with many thousands of cameras, such as global structure from motion on large internet photo collections, where SS is too large to factor or its factor too dense. For up to a few thousand cameras, the exact solve of sparse bundle adjustment, with a sparse Cholesky factorization when SS is sparse, is usually faster and more robust, because it needs fewer outer steps and does not depend on the conditioning. For small windows in real time systems, such as sliding window bundle adjustment, a direct dense solve is simplest.

Pitfalls

  • Using the exact pred formula. 12δT(μδ−g)\tfrac12 \delta^{\mathsf T} (\mu \delta - g) assumes the damped system is solved exactly. With an inexact step it gives a wrong ρ\rho. Compute −gTδ−12∥Jδ∥2-g^{\mathsf T} \delta - \tfrac12 \|J \delta\|^2.
  • Approximate back-substitution. The safety argument needs the exact point steps of line L8. Computing them only roughly can give a step with a negative predicted reduction.
  • Poor conditioning. Scenes with long camera chains, such as a street sequence, give an SS with a large condition number, and CG with block Jacobi needs many iterations. A stronger preconditioner helps.
  • Too strict a tolerance. A tiny η\eta throws away the advantage: the example needs 226 CG iterations with η=10−10\eta = 10^{-10} against 68 with η=0.1\eta = 0.1, for the same outer steps.
  • Too loose a tolerance. A large η\eta or a small cap makes each step cheap but increases the number of outer steps, each of which rebuilds all blocks.
  • Gauge. As in sparse bundle adjustment, the undamped SS is singular when the gauge is not fixed. CG with a small μ\mu then works on a nearly singular matrix and converges slowly in the gauge directions.

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()
inexact_newton_bundle_adjustment.py 310 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/inexact-newton-bundle-adjustment/. The authors are listed in prov/HF6T4X.jsonl.

"""Inexact Newton bundle adjustment: Levenberg-Marquardt whose reduced
camera system is solved approximately by preconditioned conjugate gradients.

The scene and the cost are those of the sparse bundle adjustment page. There
are N cameras with a shared, known intrinsic matrix K and n 3D points. Camera
i maps a world point X to X_c = R_i X + t_i and to the pixel pi(K X_c). An
observation (i, j, u, v) says that point j is seen at pixel (u, v) in camera
i, and F = 1/2 sum ||pi(K (R_i X_j + t_i)) - (u, v)||^2.

Each outer step builds the blocks U_i, V_j and W_ij of J^T J. It does not
form the reduced camera matrix S = U* - W V*^-1 W^T. It runs preconditioned
conjugate gradients on S da = e, with products by S computed block by block
and with the inverses of the 6 x 6 diagonal blocks of S as a block Jacobi
preconditioner. CG stops when ||e - S da|| <= eta ||e||. The point steps are
then recovered exactly, and the predicted reduction is computed for the step
that was actually taken.
"""

from typing import Callable, Dict, List, Sequence, Tuple

from cvgeom import axis_angle_to_R
from cvla import inv, matvec, mul, skew

Vector = List[float]
Matrix = List[List[float]]
Camera = Tuple[Matrix, Vector]
Observation = Tuple[int, int, float, float]


# ------------------------------------------------------------- the model

def to_camera_frame(R: Matrix, t: Vector, X: Sequence[float]) -> Vector:
    """X_c = R X + t."""
    return [sum(R[a][b] * X[b] for b in range(3)) + t[a] for a in range(3)]


def project_point(K: Matrix, R: Matrix, t: Vector, X: Sequence[float]) -> Vector:
    """The pixel (u, v) of X; pixel centers are at integer coordinates."""
    x, y, z = to_camera_frame(R, t, X)
    return [(K[0][0] * x + K[0][1] * y) / z + K[0][2], K[1][1] * y / z + K[1][2]]


def observation_blocks(K: Matrix, R: Matrix, t: Vector, X: Sequence[float]) -> Tuple[Matrix, Matrix]:
    """The Jacobian blocks of one residual: A (2 x 6, for (w, dt)) and B (2 x 3, for dX)."""
    rx = matvec(R, X)
    x, y, z = rx[0] + t[0], rx[1] + t[1], rx[2] + t[2]
    fx, s, fy = K[0][0], K[0][1], K[1][1]
    dpi = [[fx / z, s / z, -(fx * x + s * y) / (z * z)],
           [0.0, fy / z, -fy * y / (z * z)]]
    dw = mul(dpi, [[-v for v in row] for row in skew(rx)])  # d X_c / d w = -[R X]_x
    a = [dw[k] + dpi[k] for k in range(2)]  # d X_c / d t = I
    b = mul(dpi, R)  # d X_c / d X = R
    return a, b


def cost(K: Matrix, cams: Sequence[Camera], pts: Sequence[Vector], obs: Sequence[Observation]) -> float:
    """F = 1/2 sum of the squared reprojection errors."""
    f = 0.0
    for i, j, u, v in obs:
        p = project_point(K, cams[i][0], cams[i][1], pts[j])
        f += 0.5 * ((p[0] - u) ** 2 + (p[1] - v) ** 2)
    return f


def reprojection_rms(K, cams, pts, obs) -> float:
    """The root mean square of the residual vectors, in pixels."""
    return (2.0 * cost(K, cams, pts, obs) / len(obs)) ** 0.5


def _tmul(a: Matrix, b: Matrix) -> Matrix:
    """a^T b."""
    return [[sum(a[k][p] * b[k][q] for k in range(len(a))) for q in range(len(b[0]))] for p in range(len(a[0]))]


def _tvec(a: Matrix, r: Vector) -> Vector:
    """a^T r."""
    return [sum(a[k][p] * r[k] for k in range(len(a))) for p in range(len(a[0]))]


def _dot(x: Sequence[float], y: Sequence[float]) -> float:
    return sum(p * q for p, q in zip(x, y))


def build_blocks(K, cams, pts, obs, free):
    """The blocks of J^T J and J^T r. Returns (U, V, W, ga, gb), with U and
    ga keyed by the free camera index and W keyed by (i, j)."""
    U = {i: [[0.0] * 6 for _ in range(6)] for i in free}
    ga = {i: [0.0] * 6 for i in free}
    V = [[[0.0] * 3 for _ in range(3)] for _ in pts]
    gb = [[0.0] * 3 for _ in pts]
    W = {}
    for i, j, u, v in obs:
        R, t = cams[i]
        p = project_point(K, R, t, pts[j])
        r = [p[0] - u, p[1] - v]
        a, b = observation_blocks(K, R, t, pts[j])
        btb, btr = _tmul(b, b), _tvec(b, r)
        for p_ in range(3):
            gb[j][p_] += btr[p_]
            for q in range(3):
                V[j][p_][q] += btb[p_][q]
        if i in U:
            ata, atr = _tmul(a, a), _tvec(a, r)
            for p_ in range(6):
                ga[i][p_] += atr[p_]
                for q in range(6):
                    U[i][p_][q] += ata[p_][q]
            W[(i, j)] = _tmul(a, b)
    return U, V, W, ga, gb


def apply_step(cams, pts, da, db):
    """x (+) delta: R <- exp([w]_x) R, t <- t + dt, X <- X + dX."""
    new_cams = []
    for i, (R, t) in enumerate(cams):
        if i in da:
            d = da[i]
            new_cams.append((mul(axis_angle_to_R(d[:3]), R), [t[k] + d[3 + k] for k in range(3)]))
        else:
            new_cams.append(([list(row) for row in R], list(t)))
    new_pts = [[x[k] + d[k] for k in range(3)] for x, d in zip(pts, db)]
    return new_cams, new_pts


# ------------------------------------------- the reduced camera system

class ReducedSystem:
    """The damped reduced camera system S da = e, kept in block form.

    S = U* - W V*^-1 W^T with U* = U + mu I and V* = V + mu I, and
    e = -ga + W V*^-1 gb. Vectors over the free cameras are flat lists of
    length 6 len(free), in the order of `free`."""

    def __init__(self, U, V, W, ga, gb, mu, free):
        self.U, self.W, self.ga, self.gb, self.mu = U, W, ga, gb, mu
        self.free = list(free)
        self.pos = {i: 6 * k for k, i in enumerate(self.free)}
        self.size = 6 * len(self.free)
        self.seen: Dict[int, List[int]] = {}
        for (i, j) in W:
            self.seen.setdefault(j, []).append(i)
        self.vinv = [inv([[V[j][p][q] + (mu if p == q else 0.0) for q in range(3)] for p in range(3)])
                     for j in range(len(V))]

    def rhs(self) -> Vector:
        """e = -ga + W V*^-1 gb."""
        e = [0.0] * self.size
        for i in self.free:
            for p in range(6):
                e[self.pos[i] + p] = -self.ga[i][p]
        for j, cams_j in self.seen.items():
            y = matvec(self.vinv[j], self.gb[j])
            for i in cams_j:
                wy = matvec(self.W[(i, j)], y)
                for p in range(6):
                    e[self.pos[i] + p] += wy[p]
        return e

    def apply(self, x: Vector) -> Vector:
        """S x = U* x - W (V*^-1 (W^T x)), without forming S."""
        y = [0.0] * self.size
        for i in self.free:
            o, ui = self.pos[i], self.U[i]
            for p in range(6):
                y[o + p] = sum(ui[p][q] * x[o + q] for q in range(6)) + self.mu * x[o + p]
        for j, cams_j in self.seen.items():
            z = [0.0, 0.0, 0.0]
            for i in cams_j:
                wt = _tvec(self.W[(i, j)], x[self.pos[i]:self.pos[i] + 6])
                z = [a + b for a, b in zip(z, wt)]
            z = matvec(self.vinv[j], z)
            for i in cams_j:
                wz = matvec(self.W[(i, j)], z)
                o = self.pos[i]
                for p in range(6):
                    y[o + p] -= wz[p]
        return y

    def block_jacobi(self) -> Dict[int, Matrix]:
        """The inverses of the 6 x 6 diagonal blocks S_ii = U*_i - sum_j W_ij V*_j^-1 W_ij^T."""
        diag = {i: [[self.U[i][p][q] + (self.mu if p == q else 0.0) for q in range(6)] for p in range(6)]
                for i in self.free}
        for j, cams_j in self.seen.items():
            for i in cams_j:
                w = self.W[(i, j)]
                y = mul(w, self.vinv[j])
                for p in range(6):
                    for q in range(6):
                        diag[i][p][q] -= sum(y[p][k] * w[q][k] for k in range(3))
        return {i: inv(d) for i, d in diag.items()}

    def precondition(self, blocks: Dict[int, Matrix], r: Vector) -> Vector:
        """M^-1 r with M the block diagonal of S."""
        z = [0.0] * self.size
        for i in self.free:
            o = self.pos[i]
            zi = matvec(blocks[i], r[o:o + 6])
            z[o:o + 6] = zi
        return z

    def back_substitute(self, da: Dict[int, Vector]) -> List[Vector]:
        """db_j = -V*_j^-1 (gb_j + sum_i W_ij^T da_i)."""
        db = []
        for j in range(len(self.vinv)):
            acc = list(self.gb[j])
            for i in self.seen.get(j, []):
                wt = _tvec(self.W[(i, j)], da[i])
                acc = [a + b for a, b in zip(acc, wt)]
            db.append([-v for v in matvec(self.vinv[j], acc)])
        return db


def pcg(apply_a: Callable[[Vector], Vector], apply_m: Callable[[Vector], Vector], b: Vector,
        eta: float, max_iter: int) -> Tuple[Vector, int]:
    """Preconditioned conjugate gradients for A x = b from x = 0. Stops when
    ||b - A x|| <= eta ||b|| or after max_iter iterations. Returns (x, iterations)."""
    x = [0.0] * len(b)
    r = list(b)
    bnorm = _dot(b, b) ** 0.5
    if bnorm == 0.0:
        return x, 0
    z = apply_m(r)
    p = list(z)
    rz = _dot(r, z)
    for k in range(max_iter):
        ap = apply_a(p)
        pap = _dot(p, ap)
        if pap <= 0.0:  # cannot happen for a positive definite A, except by rounding
            return x, k
        alpha = rz / pap
        x = [xi + alpha * pi for xi, pi in zip(x, p)]
        r = [ri - alpha * qi for ri, qi in zip(r, ap)]
        if _dot(r, r) ** 0.5 <= eta * bnorm:
            return x, k + 1
        z = apply_m(r)
        rz_new = _dot(r, z)
        beta = rz_new / rz
        rz = rz_new
        p = [zi + beta * pi for zi, pi in zip(z, p)]
    return x, max_iter


def quadratic_form(U, V, W, free, da: Dict[int, Vector], db: List[Vector]) -> float:
    """delta^T J^T J delta = ||J delta||^2, from the blocks."""
    s = 0.0
    for i in free:
        s += _dot(da[i], matvec(U[i], da[i]))
    for j, d in enumerate(db):
        s += _dot(d, matvec(V[j], d))
    for (i, j), w in W.items():
        s += 2.0 * _dot(da[i], matvec(w, db[j]))
    return s


def inexact_newton_step(U, V, W, ga, gb, mu, free, eta=0.1, max_cg=None):
    """One damped step with an inexact solve. Returns (da, db, cg_iterations)."""
    system = ReducedSystem(U, V, W, ga, gb, mu, free)
    e = system.rhs()  # @line L5
    blocks = system.block_jacobi()  # @line L6
    limit = max_cg if max_cg is not None else max(1, system.size)
    x, its = pcg(system.apply, lambda r: system.precondition(blocks, r), e, eta, limit)  # @line L7
    da = {i: x[system.pos[i]:system.pos[i] + 6] for i in free}
    db = system.back_substitute(da)  # @line L8
    return da, db, its


def inexact_newton_bundle_adjustment(K, cams, pts, obs, fixed=(0,), tau=1e-3, eta=0.1,
                                     max_cg=None, eps1=1e-10, eps2=1e-12, max_iter=100):
    """Run Levenberg-Marquardt with inexact steps. Returns (cams, pts, info):
    info["costs"] holds the cost at the start and after each accepted step,
    info["iterations"] the number of steps tried and info["cg"] the number of
    CG iterations of each step tried."""
    free = [i for i in range(len(cams)) if i not in fixed]
    cams = [([list(r) for r in R], list(t)) for R, t in cams]
    pts = [list(x) for x in pts]
    nu = 2.0
    f = cost(K, cams, pts, obs)
    U, V, W, ga, gb = build_blocks(K, cams, pts, obs, free)  # @line L1
    diag = [U[i][p][p] for i in free for p in range(6)] + [v[p][p] for v in V for p in range(3)]
    mu = tau * max(diag)  # @line L2
    info = {"costs": [f], "iterations": 0, "cg": []}
    for k in range(max_iter):  # @line L3
        g = [x for i in free for x in ga[i]] + [x for gj in gb for x in gj]
        if max(abs(x) for x in g) <= eps1:  # @line L4
            break
        info["iterations"] = k + 1
        da, db, its = inexact_newton_step(U, V, W, ga, gb, mu, free, eta, max_cg)
        info["cg"].append(its)
        delta = [x for i in free for x in da[i]] + [x for d in db for x in d]
        size = _dot(delta, delta) ** 0.5
        xsize = (sum(x * x for _, t in cams for x in t) + sum(x * x for p in pts for x in p)) ** 0.5
        if size <= eps2 * (xsize + eps2):  # @line L9
            break
        new_cams, new_pts = apply_step(cams, pts, da, db)
        f_new = cost(K, new_cams, new_pts, obs)
        predicted = -_dot(g, delta) - 0.5 * quadratic_form(U, V, W, free, da, db)
        rho = (f - f_new) / predicted if predicted > 0 else -1.0  # @line L10
        if rho > 0:  # @line L11
            cams, pts, f = new_cams, new_pts, f_new
            U, V, W, ga, gb = build_blocks(K, cams, pts, obs, free)
            info["costs"].append(f)
            mu *= max(1.0 / 3.0, 1.0 - (2.0 * rho - 1.0) ** 3)
            nu = 2.0
        else:
            mu *= nu  # @line L12
            nu *= 2.0
    return cams, pts, info  # @line L13
test_inexact_newton_bundle_adjustment.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/inexact-newton-bundle-adjustment/. The authors are listed in prov/HF6T4X.jsonl.

import math
import random

from cvgeom import add_noise, axis_angle_to_R, random_scene
from cvla import inv, mul, solve, transpose
from inexact_newton_bundle_adjustment import (ReducedSystem, build_blocks, cost,
                                              inexact_newton_bundle_adjustment,
                                              inexact_newton_step, observation_blocks,
                                              pcg, project_point, quadratic_form,
                                              reprojection_rms)


def make_problem(seed, n_cams=4, n_pts=20, noise=0.0):
    rng = random.Random(seed)
    sc = random_scene(rng, n=n_pts, n_cams=n_cams, first_identity=True)
    obs = []
    for i in range(n_cams):
        pix = add_noise(rng, sc["x"][i], noise) if noise > 0 else sc["x"][i]
        for j in range(n_pts):
            obs.append((i, j, pix[j][0], pix[j][1]))
    cams = list(zip(sc["R"], sc["t"]))
    return rng, sc["K"][0], cams, sc["X"], obs


def perturb(rng, cams, pts, rot=0.02, trans=0.05, point=0.05):
    out = [cams[0]]
    for R, t in cams[1:]:
        w = [rng.gauss(0, rot) for _ in range(3)]
        out.append((mul(axis_angle_to_R(w), R), [v + rng.gauss(0, trans) for v in t]))
    return out, [[v + rng.gauss(0, point) for v in x] for x in pts]


def explicit_s(U, V, W, mu, free):
    """S = U* - W V*^-1 W^T as a dense matrix."""
    pos = {i: 6 * k for k, i in enumerate(free)}
    n = 6 * len(free)
    s = [[0.0] * n for _ in range(n)]
    for i in free:
        for p in range(6):
            for q in range(6):
                s[pos[i] + p][pos[i] + q] = U[i][p][q] + (mu if p == q else 0.0)
    for j in range(len(V)):
        vinv = inv([[V[j][p][q] + (mu if p == q else 0.0) for q in range(3)] for p in range(3)])
        for i in free:
            for k in free:
                if (i, j) in W and (k, j) in W:
                    blk = mul(mul(W[(i, j)], vinv), transpose(W[(k, j)]))
                    for p in range(6):
                        for q in range(6):
                            s[pos[i] + p][pos[k] + q] -= blk[p][q]
    return s


def setup(seed=2, n_cams=4, n_pts=12, mu=2.5):
    rng, K, cams, pts, obs = make_problem(seed, n_cams=n_cams, n_pts=n_pts)
    cams, pts = perturb(rng, cams, pts)
    free = list(range(1, n_cams))
    U, V, W, ga, gb = build_blocks(K, cams, pts, obs, free)
    return K, cams, pts, obs, free, U, V, W, ga, gb, mu


def test_implicit_product_equals_explicit_schur_complement():
    _, _, _, _, free, U, V, W, ga, gb, mu = setup()
    system = ReducedSystem(U, V, W, ga, gb, mu, free)
    s = explicit_s(U, V, W, mu, free)
    rng = random.Random(1)
    for _ in range(3):
        x = [rng.uniform(-1, 1) for _ in range(system.size)]
        y = system.apply(x)
        ref = [sum(a * b for a, b in zip(row, x)) for row in s]
        scale_ = max(abs(v) for v in ref)
        assert max(abs(a - b) for a, b in zip(y, ref)) <= 1e-9 * scale_
    blocks = system.block_jacobi()
    for k, i in enumerate(free):
        d = [row[6 * k:6 * k + 6] for row in s[6 * k:6 * k + 6]]
        prod = mul(blocks[i], d)
        assert max(abs(prod[p][q] - (1.0 if p == q else 0.0)) for p in range(6) for q in range(6)) < 1e-8


def test_pcg_with_small_tolerance_matches_the_direct_solve():
    _, _, _, _, free, U, V, W, ga, gb, mu = setup()
    system = ReducedSystem(U, V, W, ga, gb, mu, free)
    e = system.rhs()
    direct = solve(explicit_s(U, V, W, mu, free), e)
    blocks = system.block_jacobi()
    x, its = pcg(system.apply, lambda r: system.precondition(blocks, r), e, 1e-12, 10 * system.size)
    assert its <= 10 * system.size
    size = max(abs(v) for v in direct)
    assert max(abs(a - b) for a, b in zip(x, direct)) <= 1e-7 * size


def test_truncated_steps_have_the_stated_predicted_reduction():
    K, cams, pts, obs, free, U, V, W, ga, gb, _ = setup(seed=3, n_pts=15)
    f0 = cost(K, cams, pts, obs)
    g = [x for i in free for x in ga[i]] + [x for d in gb for x in d]
    for mu in (1e-2, 1.0, 1e3, 1e6):
        for max_cg in (1, 2, 5):
            da, db, its = inexact_newton_step(U, V, W, ga, gb, mu, free, eta=1e-14, max_cg=max_cg)
            assert its == max_cg
            delta = [x for i in free for x in da[i]] + [x for d in db for x in d]
            # the linear model L(delta) = 1/2 ||r + J delta||^2, from the observation blocks
            model = 0.0
            for i, j, u, v in obs:
                R, t = cams[i]
                p = project_point(K, R, t, pts[j])
                a, b = observation_blocks(K, R, t, pts[j])
                for k in range(2):
                    lin = p[k] - (u, v)[k] + sum(b[k][c] * db[j][c] for c in range(3))
                    if i in da:
                        lin += sum(a[k][c] * da[i][c] for c in range(6))
                    model += 0.5 * lin * lin
            pred = f0 - model
            assert pred > 0
            # the code computes pred = -g^T delta - 1/2 ||J delta||^2 from the blocks
            jd = quadratic_form(U, V, W, free, da, db)
            assert abs(pred - (-sum(x * y for x, y in zip(g, delta)) - 0.5 * jd)) <= 1e-8 * f0


def test_exact_data_is_recovered_up_to_the_gauge():
    rng, K, cams_true, pts_true, obs = make_problem(3)
    cams0, pts0 = perturb(rng, cams_true, pts_true)
    assert reprojection_rms(K, cams0, pts0, obs) > 1.0
    cams, pts, info = inexact_newton_bundle_adjustment(K, cams0, pts0, obs, eta=0.1)
    assert reprojection_rms(K, cams, pts, obs) < 1e-8
    s = math.sqrt(sum(v * v for v in cams[1][1])) / math.sqrt(sum(v * v for v in cams_true[1][1]))
    assert abs(s - 1.0) < 0.2
    for (R, t), (Rt, tt) in zip(cams, cams_true):
        assert max(abs(R[a][b] - Rt[a][b]) for a in range(3) for b in range(3)) < 1e-6
        assert max(abs(x - s * y) for x, y in zip(t, tt)) < 1e-6 * max(1.0, s * max(abs(y) for y in tt))
    for x, y in zip(pts, pts_true):
        assert max(abs(a - s * b) for a, b in zip(x, y)) < 1e-6 * max(1.0, max(abs(b) for b in y))


def test_costs_decrease_strictly_with_few_cg_iterations():
    rng, K, cams_true, pts_true, obs = make_problem(4, noise=0.5)
    cams0, pts0 = perturb(rng, cams_true, pts_true, rot=0.05, trans=0.2, point=0.1)
    _, _, info = inexact_newton_bundle_adjustment(K, cams0, pts0, obs, eta=0.5, max_cg=3)
    costs = info["costs"]
    assert len(costs) > 3
    assert all(c1 < c0 for c0, c1 in zip(costs, costs[1:]))
    assert all(1 <= c <= 3 for c in info["cg"])


def test_noisy_data_reaches_at_most_the_cost_of_the_truth():
    rng, K, cams_true, pts_true, obs = make_problem(5, noise=1.0)
    cams0, pts0 = perturb(rng, cams_true, pts_true)
    cams, pts, _ = inexact_newton_bundle_adjustment(K, cams0, pts0, obs, eta=0.1)
    assert cost(K, cams, pts, obs) <= cost(K, cams_true, pts_true, obs)
    free = [1, 2, 3]
    _, _, _, ga, gb = build_blocks(K, cams, pts, obs, free)
    g = [x for i in free for x in ga[i]] + [x for d in gb for x in d]
    assert max(abs(x) for x in g) < 1e-6

History

Triggs, McLauchlan, Hartley and Fitzgibbon (2000) described the reduced bundle system and the sparse direct methods to solve it. Inexact Newton methods with a forcing sequence were analyzed by Dembo, Eisenstat and Steihaug in 1982. Agarwal, Snavely, Seitz and Szeliski (2010) combined the two for reconstructions from community photo collections with thousands of cameras and millions of points: inexact Levenberg-Marquardt steps, CG on the reduced camera system with the Schur complement applied implicitly, and block preconditioners. In the same year Byröd and Åström studied preconditioned conjugate gradients for bundle adjustment. The iterative Schur approach became a standard solver in open source bundle adjustment software.

References

  1. Sameer Agarwal, Noah Snavely, Steven M. Seitz and Richard Szeliski, Bundle adjustment in the large, Computer Vision ECCV 2010, Lecture Notes in Computer Science 6312, Springer, 2010, 29-42, the whole paper (inexact step Levenberg-Marquardt, the implicit and explicit Schur complement, the block Jacobi and Schur-Jacobi preconditioners and the experiments)
  2. Ron S. Dembo, Stanley C. Eisenstat and Trond Steihaug, Inexact Newton methods, SIAM Journal on Numerical Analysis 19(2), 1982, 400-408, the whole paper (the forcing sequence and the local convergence theorems)
  3. Martin Byröd and Kalle Åström, Conjugate gradient bundle adjustment, Computer Vision ECCV 2010, Lecture Notes in Computer Science 6312, Springer, 2010, the whole paper (preconditioned conjugate gradients on the bundle adjustment least squares problem)
  4. Jorge Nocedal and Stephen J. Wright, Numerical Optimization, second edition, Springer, 2006, Chapter 5 (the conjugate gradient method, Theorems 5.1 and 5.2, preconditioning) and Section 7.1 (inexact Newton methods)
  5. Bill Triggs, Philip F. McLauchlan, Richard I. Hartley and Andrew W. Fitzgibbon, Bundle adjustment, a modern synthesis, in Vision Algorithms, Theory and Practice, Lecture Notes in Computer Science 1883, Springer, 2000, 298-372, Section 6, Network structure and implementation (Section 6.1, the Schur complement and the reduced bundle system)

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_iteration
  • a full proof of 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