Algorithm Search⌘K

Algorithmadvanced

CoSaMP

Also called compressive sampling matching pursuit.

A greedy sparse recovery method that adds 2s candidate columns by correlation with the residual, solves least squares on the merged support and prunes back to s entries.

Time
O(K (m n + m s^2)) worst
Space
O(m s + n) extra
Where
K = the number of iterations; m = the number of measurements; n = the length of the signal; s = the sparsity level
Properties
deterministicgreedyiterativeneeds sparsity level
Origin
Deanna Needell, Joel A. Tropp, 2008

CoSaMP (compressive sampling matching pursuit) recovers a vector x∈Rnx \in \mathbb{R}^n with at most ss nonzero entries from y=Ax+ey = Ax + e with m<nm < n measurements. Each iteration correlates the residual with the columns of AA, adds the 2s2s best matching columns to the current support, solves a least squares problem on the merged set of at most 3s3s columns and keeps the ss largest entries of the solution. Like orthogonal matching pursuit, it uses correlations and least squares, but OMP adds one column per step and never removes one, while CoSaMP adds many columns at once and can remove wrong ones. Like iterative hard thresholding, it keeps an ss-sparse iterate and has a uniform guarantee under the restricted isometry property, but it replaces the gradient step by an exact least squares fit, so it often needs only a few iterations. Unlike iterative shrinkage-thresholding and basis pursuit, it needs the sparsity level ss and no weight λ\lambda. Needell and Tropp proved that under δ4s≤0.1\delta_{4s} \le 0.1 each iteration halves the error up to a fixed multiple of the noise.

The problem

Given a real m×nm \times n matrix AA, a vector y∈Rmy \in \mathbb{R}^m and a sparsity level ss with 3s≤m3s \le m, find an ss-sparse x^\hat x with small error ∥x^−x∥\|\hat x - x\|, where y=Ax+ey = Ax + e and xx is ss-sparse or close to an ss-sparse vector. This is a form of sparse signal recovery. The output is an ss-sparse vector.

The algorithm

Hs(v)H_s(v) keeps the ss entries of vv of largest magnitude. ATA_T holds the columns of AA in the set TT.

  1. CoSaMP(A, y, s, K)
  2. 1a ← 0
  3. 2for k = 1 to K
  4. 3p ← Aᵀ (y - A a) ▷ proxy: correlations with the residual
  5. 4Ω ← indices of the 2s largest |pᵢ| ▷ identify
  6. 5T ← Ω ∪ supp(a) ▷ merge, |T| ≤ 3s
  7. 6b_T ← argmin ‖y - A_T z‖, b ← 0 off T ▷ least squares on T
  8. 7a ← H_s(b) ▷ prune to s entries
  9. 8stop if the residual ‖y - A a‖ is small or stops changing
  10. 9return a

Line L4 takes 2s2s columns, not ss, because the error x−ax - a has up to 2s2s nonzero entries: ss from xx and ss from the current aa. Line L5 keeps the old support, so a correct entry found earlier is not lost before the least squares step can weigh it. Line L6 is the only expensive step. Needell and Tropp solve it approximately with a few steps of conjugate gradients or LSQR, and the analysis allows this. The implementation here uses the pseudoinverse from a thin SVD of ATA_T, which also handles the case of dependent columns.

Example

Take m=4m = 4, n=8n = 8 and A=[I∣H/2]A = [I \mid H/2], where HH is the 4×44 \times 4 Sylvester Hadamard matrix with rows (1,1,1,1)(1,1,1,1), (1,−1,1,−1)(1,-1,1,-1), (1,1,−1,−1)(1,1,-1,-1), (1,−1,−1,1)(1,-1,-1,1). Let x1=1x_1 = 1, x6=2x_6 = 2 and all other entries zero, so s=2s = 2 and y=(2,−1,1,−1)y = (2, -1, 1, -1), with ∥y∥=7≈2.6458\|y\| = \sqrt 7 \approx 2.6458. This is the first example of the iterative hard thresholding page.

Iteration 1 starts from a=0a = 0. The proxy is p=ATy=(2,−1,1,−1,0.5,2.5,0.5,0.5)p = A^Ty = (2, -1, 1, -1, 0.5, 2.5, 0.5, 0.5). The 2s=42s = 4 largest entries are entry 6 (2.5), entry 1 (2) and two of the entries 2, 3, 4 (all of magnitude 1); the implementation takes 2 and 3 by the lower index rule. So T={1,2,3,6}T = \{1, 2, 3, 6\}. These four columns are independent and contain the true support, so the least squares fit is exact: b1=1b_1 = 1, b6=2b_6 = 2, and b2=b3=0b_2 = b_3 = 0. Pruning keeps entries 1 and 6, and a=xa = x with residual 0. Any choice among the tied entries gives the same result.

On the same data, iterative hard thresholding finds the right support in its first step but then only halves the error per step, because it takes a gradient step instead of the least squares fit. In a run on 20 random 32×6432 \times 64 Gaussian matrices with entries of variance 1/m1/m, CoSaMP recovered every ss-sparse test vector for s=2,3,4,5s = 2, 3, 4, 5, in 1 to 3 iterations. This is a measurement.

Correctness

The full proof is in proofs/correctness.md. With δ=δ4s<1\delta = \delta_{4s} < 1, d=x−ad = x - a and c=δ/(1−δ)c = \delta/(1 - \delta), one iteration satisfies four bounds:

  1. Identification: the part of dd missed by Ω\Omega is small, ∥dΩc∥≤2δ1−δ∥d∥+21+δ1−δ∥e∥\|d_{\Omega^c}\| \le \frac{2\delta}{1 - \delta}\|d\| + \frac{2\sqrt{1 + \delta}}{1 - \delta}\|e\|. The proof compares pp on the support of dd and on Ω\Omega, and uses that AUTAVA_U^TA_V has norm at most δ\delta for disjoint sets UU, VV.
  2. Merge: ∥xTc∥≤∥dΩc∥\|x_{T^c}\| \le \|d_{\Omega^c}\|, because aa vanishes off TT.
  3. Least squares: ∥x−b∥≤1+c2 ∥xTc∥+∥e∥/1−δ\|x - b\| \le \sqrt{1 + c^2}\,\|x_{T^c}\| + \|e\|/\sqrt{1 - \delta}.
  4. Prune: ∥x−Hs(b)∥≤2∥x−b∥\|x - H_s(b)\| \le 2\|x - b\|, because Hs(b)H_s(b) is the best ss-sparse approximation of bb.

Together, ∥x−a′∥≤ρ∥x−a∥+τ∥e∥\|x - a'\| \le \rho\|x - a\| + \tau\|e\| with ρ=4δ1+c2/(1−δ)\rho = 4\delta\sqrt{1 + c^2}/(1 - \delta). At δ=0.1\delta = 0.1 this is ρ≈0.447\rho \approx 0.447 and τ≈6.80\tau \approx 6.80, so the error falls geometrically to about 12.3∥e∥12.3\|e\|. The factor is below 1 for δ\delta up to about 0.195. Needell and Tropp state the invariant ∥x−ak+1∥≤0.5∥x−ak∥+10ν\|x - a^{k+1}\| \le 0.5\|x - a^k\| + 10\nu under δ4s≤0.1\delta_{4s} \le 0.1, with the unrecoverable energy ν\nu, which also covers signals that are only close to sparse.

Proof: One CoSaMP iteration contracts the error by a factor below 1/2 when delta_4s <= 0.1, up to a fixed multiple of the noisefull

Setting. AA is a real m×nm \times n matrix, x∈Rnx \in \mathbb{R}^n has at most ss nonzero entries, and y=Ax+ey = Ax + e. For a set TT of indices, ATA_T holds the columns in TT, vTv_T is the restriction of vv to TT and TcT^c is the complement. Hs(v)H_s(v) keeps the ss entries of largest magnitude. The restricted isometry constant δk\delta_k is the smallest δ\delta with (1−δ)∥z∥2≤∥Az∥2≤(1+δ)∥z∥2(1 - \delta)\|z\|^2 \le \|Az\|^2 \le (1 + \delta)\|z\|^2 for all zz with at most kk nonzero entries; it does not decrease with kk. We write δ=δ4s\delta = \delta_{4s} and assume δ<1\delta < 1.

One iteration starts from an ss-sparse vector aa and computes:

  1. the proxy p=AT(y−Aa)p = A^T(y - Aa) and the set Ω\Omega of the indices of its 2s2s largest entries;
  2. the merged set T=Ω∪supp⁡(a)T = \Omega \cup \operatorname{supp}(a), with ∣T∣≤3s|T| \le 3s;
  3. the least squares solution bb with bT=arg⁡min⁡z∥y−ATz∥b_T = \arg\min_z \|y - A_Tz\| and bTc=0b_{T^c} = 0;
  4. the pruned vector a′=Hs(b)a' = H_s(b).

Theorem. With c=δ/(1−δ)c = \delta/(1 - \delta),

∥x−a′∥≤ρ ∥x−a∥+τ ∥e∥,ρ=4δ1+c21−δ,τ=41+c21+δ1−δ+21−δ.\|x - a'\| \le \rho\,\|x - a\| + \tau\,\|e\|,\qquad \rho = \frac{4\delta\sqrt{1 + c^2}}{1 - \delta},\qquad \tau = \frac{4\sqrt{1 + c^2}\sqrt{1 + \delta}}{1 - \delta} + \frac{2}{\sqrt{1 - \delta}}.

For δ=0.1\delta = 0.1 this gives ρ≈0.4472\rho \approx 0.4472 and τ≈6.798\tau \approx 6.798, and ρ<1\rho < 1 holds for δ\delta up to about 0.19540.1954. When ρ<1\rho < 1, the iterates from a0=0a^0 = 0 satisfy ∥x−ak∥≤ρk∥x∥+τ∥e∥/(1−ρ)\|x - a^k\| \le \rho^k\|x\| + \tau\|e\|/(1 - \rho), which is about 12.3∥e∥12.3\|e\| in the limit at δ=0.1\delta = 0.1.

Two facts about restricted isometries

Lemma 1. If ∣U∣≤k|U| \le k, every eigenvalue of AUTAUA_U^TA_U lies in [1−δk,1+δk][1 - \delta_k, 1 + \delta_k]. Hence ∥AUTw∥≤1+δk ∥w∥\|A_U^Tw\| \le \sqrt{1 + \delta_k}\,\|w\| for all ww, ∥AUTAUz∥≥(1−δk)∥z∥\|A_U^TA_Uz\| \ge (1 - \delta_k)\|z\|, and the pseudoinverse satisfies ∥AU+∥≤1/1−δk\|A_U^+\| \le 1/\sqrt{1 - \delta_k} and ∥(AUTAU)−1∥≤1/(1−δk)\|(A_U^TA_U)^{-1}\| \le 1/(1 - \delta_k).

Proof. The Rayleigh quotient of AUTAUA_U^TA_U is ∥AUz∥2/∥z∥2∈[1−δk,1+δk]\|A_Uz\|^2/\|z\|^2 \in [1 - \delta_k, 1 + \delta_k]. The singular values of AUA_U are the square roots of these eigenvalues, and ∥AU+∥\|A_U^+\| is the inverse of the smallest one. □\square

Lemma 2. If UU and VV are disjoint and ∣U∣+∣V∣≤k|U| + |V| \le k, then ∥AUTAV∥≤δk\|A_U^TA_V\| \le \delta_k.

Proof. Let W=U∪VW = U \cup V. The matrix AWTAW−IA_W^TA_W - I has norm at most δk\delta_k by Lemma 1, and AUTAVA_U^TA_V is its off-diagonal block (the identity has no entries there). The norm of a block is at most the norm of the whole matrix. □\square

Proof of the theorem

Let d=x−ad = x - a and R=supp⁡(d)R = \operatorname{supp}(d), so ∣R∣≤2s|R| \le 2s. The residual is y−Aa=ARdR+ey - Aa = A_Rd_R + e.

Step 1 (identification). We show ∥dΩc∥≤2δ1−δ∥d∥+21+δ1−δ∥e∥\|d_{\Omega^c}\| \le \frac{2\delta}{1 - \delta}\|d\| + \frac{2\sqrt{1 + \delta}}{1 - \delta}\|e\|.

Since Ω\Omega holds the 2s2s largest entries of pp and ∣R∣≤2s|R| \le 2s, we have ∥pR∥2≤∥pΩ∥2\|p_R\|^2 \le \|p_\Omega\|^2. Remove the common part R∩ΩR \cap \Omega: ∥pR∖Ω∥≤∥pΩ∖R∥\|p_{R \setminus \Omega}\| \le \|p_{\Omega \setminus R}\|.

Upper bound: pΩ∖R=AΩ∖RTARdR+AΩ∖RTep_{\Omega \setminus R} = A_{\Omega \setminus R}^TA_Rd_R + A_{\Omega \setminus R}^Te. The sets Ω∖R\Omega \setminus R and RR are disjoint with at most 4s4s elements together, so Lemma 2 and Lemma 1 give ∥pΩ∖R∥≤δ∥d∥+1+δ ∥e∥\|p_{\Omega \setminus R}\| \le \delta\|d\| + \sqrt{1 + \delta}\,\|e\|.

Lower bound: split ARdR=AR∖ΩdR∖Ω+AR∩ΩdR∩ΩA_Rd_R = A_{R \setminus \Omega}d_{R \setminus \Omega} + A_{R \cap \Omega}d_{R \cap \Omega}. Then

pR∖Ω=AR∖ΩTAR∖ΩdR∖Ω+AR∖ΩTAR∩ΩdR∩Ω+AR∖ΩTe,p_{R \setminus \Omega} = A_{R \setminus \Omega}^TA_{R \setminus \Omega}d_{R \setminus \Omega} + A_{R \setminus \Omega}^TA_{R \cap \Omega}d_{R \cap \Omega} + A_{R \setminus \Omega}^Te,

and by the two lemmas ∥pR∖Ω∥≥(1−δ)∥dR∖Ω∥−δ∥d∥−1+δ ∥e∥\|p_{R \setminus \Omega}\| \ge (1 - \delta)\|d_{R \setminus \Omega}\| - \delta\|d\| - \sqrt{1 + \delta}\,\|e\|.

Combine the two bounds: (1−δ)∥dR∖Ω∥≤2δ∥d∥+21+δ ∥e∥(1 - \delta)\|d_{R \setminus \Omega}\| \le 2\delta\|d\| + 2\sqrt{1 + \delta}\,\|e\|. Since dd vanishes off RR, dΩc=dR∖Ωd_{\Omega^c} = d_{R \setminus \Omega}, which proves the claim.

Step 2 (merge). aa vanishes off TT, so xTc=dTcx_{T^c} = d_{T^c}. Since Tc⊆ΩcT^c \subseteq \Omega^c, ∥xTc∥≤∥dΩc∥\|x_{T^c}\| \le \|d_{\Omega^c}\|.

Step 3 (least squares). We show ∥x−b∥≤1+c2 ∥xTc∥+∥e∥/1−δ\|x - b\| \le \sqrt{1 + c^2}\,\|x_{T^c}\| + \|e\|/\sqrt{1 - \delta}.

Write y=ATxT+ATcxTc+ey = A_Tx_T + A_{T^c}x_{T^c} + e. The least squares solution is bT=AT+yb_T = A_T^+y, and AT+AT=IA_T^+A_T = I because ATA_T has full column rank (∣T∣≤3s|T| \le 3s and δ3s≤δ<1\delta_{3s} \le \delta < 1). So

xT−bT=−AT+(ATcxTc+e)=−(ATTAT)−1ATTATcxTc−AT+e.x_T - b_T = -A_T^+(A_{T^c}x_{T^c} + e) = -(A_T^TA_T)^{-1}A_T^TA_{T^c}x_{T^c} - A_T^+e.

The vector xTcx_{T^c} has at most ss nonzero entries, on a set disjoint from TT, so Lemma 2 (with at most 4s4s indices) and Lemma 1 give ∥xT−bT∥≤c∥xTc∥+∥e∥/1−δ\|x_T - b_T\| \le c\|x_{T^c}\| + \|e\|/\sqrt{1 - \delta}. Now ∥x−b∥2=∥xTc∥2+∥xT−bT∥2\|x - b\|^2 = \|x_{T^c}\|^2 + \|x_T - b_T\|^2, and the triangle inequality in R2\mathbb{R}^2 for the vectors (∥xTc∥,c∥xTc∥)(\|x_{T^c}\|, c\|x_{T^c}\|) and (0,∥e∥/1−δ)(0, \|e\|/\sqrt{1 - \delta}) gives the claim.

Step 4 (prune). a′=Hs(b)a' = H_s(b) is the best ss-sparse approximation of bb (keeping the largest entries minimizes the discarded energy), and xx is ss-sparse, so ∥b−a′∥≤∥b−x∥\|b - a'\| \le \|b - x\|. Hence ∥x−a′∥≤∥x−b∥+∥b−a′∥≤2∥x−b∥\|x - a'\| \le \|x - b\| + \|b - a'\| \le 2\|x - b\|.

Conclusion. Chain the four steps:

∥x−a′∥≤21+c2(2δ1−δ∥d∥+21+δ1−δ∥e∥)+21−δ∥e∥=ρ∥x−a∥+τ∥e∥.\|x - a'\| \le 2\sqrt{1 + c^2}\left(\frac{2\delta}{1 - \delta}\|d\| + \frac{2\sqrt{1 + \delta}}{1 - \delta}\|e\|\right) + \frac{2}{\sqrt{1 - \delta}}\|e\| = \rho\|x - a\| + \tau\|e\|.

If ρ<1\rho < 1, induction from a0=0a^0 = 0 gives ∥x−ak∥≤ρk∥x∥+τ∥e∥(1+ρ+⋯+ρk−1)≤ρk∥x∥+τ∥e∥/(1−ρ)\|x - a^k\| \le \rho^k\|x\| + \tau\|e\|(1 + \rho + \dots + \rho^{k-1}) \le \rho^k\|x\| + \tau\|e\|/(1 - \rho). □\square

Remarks

The proof uses the restricted isometry property only on the set U=supp⁡(x)∪supp⁡(a)∪ΩU = \operatorname{supp}(x) \cup \operatorname{supp}(a) \cup \Omega, which has at most 4s4s elements. So the one-step bound holds for every matrix with δ\delta replaced by ∥I−AUTAU∥\|I - A_U^TA_U\|, whenever that number is below 1. The test file checks this local form on a Gaussian matrix.

Needell and Tropp (2009) prove the invariant ∥x−ak+1∥≤0.5∥x−ak∥+10ν\|x - a^{k+1}\| \le 0.5\|x - a^k\| + 10\nu under δ4s≤0.1\delta_{4s} \le 0.1, where ν\nu is the unrecoverable energy: the noise norm plus terms from the tail of xx, which vanish when xx is exactly ss-sparse. The argument above has the same four steps with simpler constants and treats only exactly sparse xx. For a general xx, apply it to the best ss-term approximation xsx_s and put A(x−xs)A(x - x_s) into the noise.

Complexity

One iteration costs a product with AA and one with ATA^T, which is O(mn)O(mn) for a dense matrix, a selection of the 2s2s largest entries in O(n)O(n), and a least squares problem with mm rows and at most 3s3s columns. A direct solve by QR decomposition or an SVD costs O(ms2)O(ms^2). So KK iterations cost O(K(mn+ms2))O(K(mn + ms^2)), and the extra memory is O(ms+n)O(ms + n) for ATA_T and the vectors. With a fast operator and an iterative least squares solver, an iteration costs a fixed number of products with AA and ATA^T. Under δ4s≤0.1\delta_{4s} \le 0.1, reaching error ε∥x∥\varepsilon\|x\| plus the noise term takes O(log⁡(1/ε))O(\log(1/\varepsilon)) iterations by the contraction factor.

Properties

  • The guarantee is uniform: one matrix with small δ4s\delta_{4s} works for every ss-sparse xx, and the error is linear in the noise and in the tail of xx.
  • In the noiseless case, once the true support lies inside TT, the least squares step gives xx exactly. So on easy instances CoSaMP stops after a finite number of iterations, unlike iterative hard thresholding and ISTA.
  • The iterate is always ss-sparse. Entries can enter and leave the support in every iteration.
  • It is not scale sensitive in the way IHT is: if AA is multiplied by a constant c≠0c \ne 0, every iterate is divided by cc and the residuals stay the same, because the selections in lines L4 and L7 depend only on the order of magnitudes and line L6 is an exact fit.
  • The condition δ4s≤0.1\delta_{4s} \le 0.1 is stronger than the conditions known for ℓ1\ell_1 minimization, such as δ2s<1/2\delta_{2s} < 1/\sqrt 2 for basis pursuit.

Variants and improvements

  • Subspace pursuit (Dai and Milenkovic 2009) adds only ss candidates, solves least squares on the 2s2s columns, prunes to ss and then solves least squares again on the final support. It has a guarantee of the same kind.
  • Hard thresholding pursuit (Foucart 2011) takes the support of a gradient step, as in IHT, and then solves least squares on it. It sits between IHT and CoSaMP.
  • A final debiasing step, a least squares solve on the returned support, improves the result when the loop stops early.
  • The same steps work for other structured sparsity models (block sparsity, tree sparsity in wavelets) if lines L4 and L7 are replaced by the best approximation in the model.
  • Foucart reports better restricted isometry conditions for CoSaMP than δ4s≤0.1\delta_{4s} \le 0.1 with a refined analysis; see the book of Foucart and Rauhut.

When to use it

Use CoSaMP when the sparsity level is known, the matrix satisfies a restricted isometry property with room to spare (random Gaussian, Bernoulli or partial Fourier matrices with enough rows), and a solution with the exact sparsity is wanted. It usually needs fewer iterations than iterative hard thresholding, at the cost of a least squares problem per iteration. When ss is not known, ℓ1\ell_1 methods such as basis pursuit are easier to set up. When ss is very small, orthogonal matching pursuit is simpler and needs exactly ss steps.

Pitfalls

  • The merged set has up to 3s3s columns, and the least squares problem needs 3s≤m3s \le m and independent columns. With a coherent matrix or too large an ss, ATA_T can be rank deficient. Use a pseudoinverse or a QR solver with column pivoting, not the normal equations.
  • The sparsity level is an input. If the true signal has more than ss large entries, the result is the best fit with ss entries, not the signal.
  • The iteration is not monotone in the residual in general. Keep the best iterate seen, or stop when the residual stops decreasing.
  • On a coherent matrix the identification step can miss a true column again and again. The theorem needs a small δ4s\delta_{4s}; a small coherence alone is not enough for large ss.
  • Ties in the selection of lines L4 and L7 make runs depend on the tie rule. Fix it.

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.

cosamp.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cosamp/. The authors are listed in prov/E7NF54.jsonl.
"""CoSaMP (compressive sampling matching pursuit) of Needell and Tropp.

A is a list of m rows of length n, y has length m and s is the sparsity
level. Each iteration picks the 2s largest entries of the proxy A^T v,
merges them with the current support, solves least squares on the merged
set and keeps the s largest entries of the solution.
"""

from imgla import matvec, norm2, rmatvec, svd


def largest(v, k):
    """Indices of the k entries of largest magnitude (ties: lower index first)."""
    return sorted(range(len(v)), key=lambda i: (-abs(v[i]), i))[:k]


def least_squares_on(a, y, cols, rcond=1e-12):
    """argmin_z ||y - A_T z|| for the columns T = cols.

    The pseudoinverse is applied through a thin SVD of A_T, so the result is
    the least squares solution of minimum norm when A_T has dependent
    columns (for example when |T| > m).
    """
    at = [[row[i] for i in cols] for row in a]
    u, sig, v = svd(at)
    cut = rcond * sig[0] if sig else 0.0
    z = [0.0] * len(cols)
    for k, sk in enumerate(sig):
        if sk <= cut:
            continue
        c = sum(u[r][k] * y[r] for r in range(len(y))) / sk
        for j in range(len(cols)):
            z[j] += c * v[j][k]
    return z


def cosamp(a, y, s, iters=50, tol=1e-12, x0=None):
    """Run CoSaMP. Returns (x, residual_norms) with residual_norms[k] = ||y - A x^k||.

    x0 is an optional s-sparse start (default 0). The loop stops after iters
    steps, when the residual is at most tol * ||y||, or when the support and
    the residual stop changing.
    """
    n = len(a[0])
    x = list(x0) if x0 is not None else [0.0] * n  # @line L1
    v = [yi - ai for yi, ai in zip(y, matvec(a, x))]
    res = [norm2(v)]
    if res[0] == 0.0:
        return x, res
    for _ in range(iters):  # @line L2
        if res[-1] <= tol * norm2(y):
            break
        p = rmatvec(a, v)  # @line L3
        omega = largest(p, 2 * s)  # @line L4
        t = sorted(set(omega) | {i for i in range(n) if x[i] != 0.0})  # @line L5
        bt = least_squares_on(a, y, t)  # @line L6
        b = [0.0] * n
        for i, val in zip(t, bt):
            b[i] = val
        keep = largest(b, s)  # @line L7
        x_new = [0.0] * n
        for i in keep:
            x_new[i] = b[i]
        v = [yi - ai for yi, ai in zip(y, matvec(a, x_new))]  # @line L8
        res.append(norm2(v))
        same = all((x_new[i] != 0.0) == (x[i] != 0.0) for i in range(n))
        x = x_new
        if same and res[-1] >= res[-2] * (1.0 - 1e-12):
            break
    return x, res  # @line L9
imgla.py 259 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).

A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""

import math


def _flat(x):
    """Flatten a list of rows (an image) into one list; a vector is returned as is."""
    if x and isinstance(x[0], (list, tuple)):
        return [v for row in x for v in row]
    return x


def zeros(m, n):
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n):
    """The n x n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1.0
    return out


def transpose(a):
    """A^T."""
    return [list(col) for col in zip(*a)]


def conj_transpose(a):
    """A^H, the conjugate transpose."""
    return [[v.conjugate() for v in col] for col in zip(*a)]


def matmul(a, b):
    """The product A B."""
    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, x):
    """The product A x."""
    return [sum(v * w for v, w in zip(row, x)) for row in a]


def rmatvec(a, y):
    """The product A^H y."""
    n = len(a[0]) if a else 0
    out = [0.0] * n
    for row, yi in zip(a, y):
        if yi == 0:
            continue
        for j, v in enumerate(row):
            out[j] += v.conjugate() * yi
    return out


def dot(u, v):
    """<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
    return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))


def norm2(x):
    """The Euclidean norm. Images (lists of rows) are flattened."""
    return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))


def solve(a, b):
    """Solve A x = b by Gaussian elimination with partial pivoting.

    b is a vector or a matrix (a list of rows). A must be square and
    nonsingular; a zero pivot raises ValueError. Fractions stay exact.
    """
    n = len(a)
    vec = not (b and isinstance(b[0], (list, tuple)))
    rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
    m = [list(row) + rhs[i] for i, row in enumerate(a)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / piv
            if f != 0:
                mr, mc = m[r], m[c]
                for j in range(c, w):
                    mr[j] -= f * mc[j]
    x = [[0.0] * (w - n) for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(w - n):
            s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def cholesky(a):
    """Lower triangular L with A = L L^H for a Hermitian positive definite A."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
        d = d.real if isinstance(d, complex) else d
        if not d > 0:
            raise ValueError("matrix is not positive definite")
        ljj = math.sqrt(d)
        low[j][j] = ljj
        for i in range(j + 1, n):
            s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
            low[i][j] = s / ljj
    return low


def cho_solve(low, b):
    """Solve (L L^H) x = b, with L from cholesky."""
    n = len(low)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
        x[i] = s / low[i][i].conjugate()
    return x


def _rot_params(app, aqq, apq):
    """c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
    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(1.0 + t * t)
    return c, c * t


def sym_eig(a, tol=1e-15, max_sweeps=100):
    """Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.

    Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
    """
    n = len(a)
    m = [[float(v) for v in row] for row in a]
    q = eye(n)
    for _ in range(max_sweeps):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(m[i][i] ** 2 for i in range(n)) + off
        if off <= (tol * tol) * scale or off == 0.0:
            break
        for p in range(n - 1):
            for r in range(p + 1, n):
                apq = m[p][r]
                if apq == 0.0:
                    continue
                c, s = _rot_params(m[p][p], m[r][r], apq)
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - s * mkr
                    m[k][r] = s * mkp + c * mkr
                mp, mr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = mp[k], mr[k]
                    mp[k] = c * mpk - s * mrk
                    mr[k] = s * mpk + c * mrk
                m[p][r] = m[r][p] = 0.0
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - s * qkr
                    q[k][r] = s * qkp + c * qkr
    order = sorted(range(n), key=lambda i: m[i][i])
    w = [m[i][i] for i in order]
    qs = [[q[k][i] for i in order] for k in range(n)]
    return w, qs


def _complete(cols, m):
    """Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
    for idx, col in enumerate(cols):
        if any(v != 0.0 for v in col):
            continue
        for e in range(m):
            cand = [0.0] * m
            cand[e] = 1.0
            for _ in range(2):
                for jdx, other in enumerate(cols):
                    if jdx == idx or not any(v != 0.0 for v in other):
                        continue
                    h = sum(a * b for a, b in zip(other, cand))
                    cand = [a - h * b for a, b in zip(cand, other)]
            nrm = math.sqrt(sum(v * v for v in cand))
            if nrm > 0.5:
                cols[idx] = [v / nrm for v in cand]
                break
    return cols


def svd(a, tol=1e-15, max_sweeps=100):
    """Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).

    Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
    descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
    """
    m, n = len(a), len(a[0])
    if m < n:
        v, s, u = svd(transpose(a), tol, max_sweeps)
        return u, s, v
    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 r in range(p + 1, n):
                cp, cr = cols[p], cols[r]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cr)
                gamma = sum(x * y for x, y in zip(cp, cr))
                if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                c, s = _rot_params(alpha, beta, gamma)
                cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
                cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
                vp, vr = vcols[p], vcols[r]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
                vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
        if not rotated:
            break
    sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
    # A column below 1e-150 times the largest one is zero to working precision;
    # its squares underflow, so its direction carries no information.
    floor = max(sig) * 1e-150 if sig else 0.0
    sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
    order = sorted(range(n), key=lambda j: -sig[j])
    s_out = [sig[j] for j in order]
    ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
    ucols = _complete(ucols, m)
    u = [[ucols[j][i] for j in range(n)] for i in range(m)]
    v = [[vcols[j][i] for j in order] for i in range(n)]
    return u, s_out, v


def adjoint_gap(apply_a, apply_ah, x, y):
    """|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.

    x and y may be vectors or images (lists of rows). If the denominator is
    zero, the absolute gap is returned.
    """
    ax = apply_a(x)
    gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
    den = norm2(ax) * norm2(y)
    return gap / den if den > 0.0 else gap
test_cosamp.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cosamp/. The authors are listed in prov/E7NF54.jsonl.

import itertools
import math
import random

from cosamp import cosamp, largest, least_squares_on
from imgla import matvec, norm2, solve, sym_eig


def gauss_matrix(rng, m, n):
    return [[rng.gauss(0.0, 1.0) / math.sqrt(m) for _ in range(n)] for _ in range(m)]


def sparse_vector(rng, n, s):
    x = [0.0] * n
    for i in rng.sample(range(n), s):
        x[i] = rng.choice([-1.0, 1.0]) * (1.0 + rng.random())
    return x


def dist(u, v):
    return norm2([p - q for p, q in zip(u, v)])


def rho(d):
    """Contraction factor of the proof: 4 d sqrt(1 + (d/(1-d))^2) / (1 - d)."""
    c = d / (1.0 - d)
    return 4.0 * d * math.sqrt(1.0 + c * c) / (1.0 - d)


def tau(d):
    """Noise factor of the proof."""
    c = d / (1.0 - d)
    return 4.0 * math.sqrt(1.0 + c * c) * math.sqrt(1.0 + d) / (1.0 - d) + 2.0 / math.sqrt(1.0 - d)


def local_delta(a, cols):
    """||I - A_U^T A_U|| for the column set U."""
    g = [[(1.0 if i == j else 0.0) - sum(row[i] * row[j] for row in a) for j in cols] for i in cols]
    w, _ = sym_eig(g)
    return max(abs(w[0]), abs(w[-1]))


def test_proof_constants_at_delta_one_tenth():
    assert abs(rho(0.1) - 0.44718) < 1e-5
    assert abs(tau(0.1) - 6.79824) < 1e-5
    assert rho(0.1954) < 1.0 < rho(0.1955)


def test_largest_picks_top_magnitudes():
    assert largest([0.5, -3.0, 2.0, -2.0, 1.0], 3) == [1, 2, 3]


def test_least_squares_matches_normal_equations_and_min_norm():
    rng = random.Random(1)
    a = gauss_matrix(rng, 10, 6)
    y = [rng.gauss(0.0, 1.0) for _ in range(10)]
    cols = [0, 2, 3, 5]
    g = [[sum(row[i] * row[j] for row in a) for j in cols] for i in cols]
    rhs = [sum(row[i] * yi for row, yi in zip(a, y)) for i in cols]
    assert dist(least_squares_on(a, y, cols), solve(g, rhs)) <= 1e-10
    # Dependent columns: the same column twice. The minimum norm solution
    # splits the coefficient equally, and the residual is orthogonal to A_T.
    b = [[row[0], row[0], row[1]] for row in a]
    z = least_squares_on(b, y, [0, 1, 2])
    assert abs(z[0] - z[1]) <= 1e-10
    r = [yi - sum(bi * zi for bi, zi in zip(row, z)) for row, yi in zip(b, y)]
    for j in range(3):
        assert abs(sum(row[j] * ri for row, ri in zip(b, r))) <= 1e-10


def test_exact_recovery_of_sparse_vectors_from_gaussian_measurements():
    for seed in range(10):
        rng = random.Random(100 + seed)
        a = gauss_matrix(rng, 32, 64)
        x = sparse_vector(rng, 64, 4)
        xh, res = cosamp(a, matvec(a, x), 4)
        assert dist(xh, x) <= 1e-9
        assert len(res) - 1 <= 5


def test_one_step_bound_of_the_proof_holds_with_the_local_constant():
    # For an s-sparse start a, let U = supp(x) + supp(a) + Omega (|U| <= 4s).
    # The proof only uses ||I - A_U^T A_U|| = d, so whenever d < 1:
    # ||x - a_new|| <= rho(d) ||x - a|| + tau(d) ||e||.
    rng = random.Random(2)
    m, n, s = 40, 60, 3
    a = gauss_matrix(rng, m, n)
    checked = 0
    for _ in range(40):
        x = sparse_vector(rng, n, s)
        e = [rng.gauss(0.0, 0.02) for _ in range(m)]
        y = [u + v for u, v in zip(matvec(a, x), e)]
        start = sparse_vector(rng, n, s)
        a_new, _ = cosamp(a, y, s, iters=1, x0=start)
        v = [yi - ai for yi, ai in zip(y, matvec(a, start))]
        omega = largest([sum(row[j] * vi for row, vi in zip(a, v)) for j in range(n)], 2 * s)
        u = sorted({i for i in range(n) if x[i] != 0.0 or start[i] != 0.0} | set(omega))
        d = local_delta(a, u)
        if d >= 1.0:
            continue
        checked += 1
        assert dist(a_new, x) <= rho(d) * dist(start, x) + tau(d) * norm2(e) + 1e-10
    assert checked >= 10


def test_noiseless_result_equals_exhaustive_l0_search():
    for seed in range(6):
        rng = random.Random(300 + seed)
        m, n, s = 7, 12, 2
        a = gauss_matrix(rng, m, n)
        x = sparse_vector(rng, n, s)
        y = matvec(a, x)
        best = None
        for sup in itertools.combinations(range(n), s):
            z = least_squares_on(a, y, list(sup))
            r = norm2([yi - sum(a[i][j] * zj for j, zj in zip(sup, z)) for i, yi in enumerate(y)])
            if best is None or r < best[0]:
                best = (r, sup, z)
        brute = [0.0] * n
        for j, zj in zip(best[1], best[2]):
            brute[j] = zj
        assert dist(brute, x) <= 1e-9
        xh, _ = cosamp(a, y, s)
        assert dist(xh, brute) <= 1e-9


def test_noisy_error_is_a_small_multiple_of_the_noise():
    rng = random.Random(4)
    a = gauss_matrix(rng, 48, 64)
    x = sparse_vector(rng, 64, 3)
    e = [rng.gauss(0.0, 0.01) for _ in range(48)]
    y = [u + v for u, v in zip(matvec(a, x), e)]
    xh, _ = cosamp(a, y, 3)
    assert sum(1 for t in xh if t != 0.0) <= 3
    assert dist(xh, x) <= 3.0 * norm2(e)

History

Greedy pursuits with one column per step go back to matching pursuit (Mallat and Zhang 1993) and orthogonal matching pursuit. Needell and Tropp posted CoSaMP in 2008 and published it in 2009. It was one of the first greedy methods with a uniform guarantee as strong as that of ℓ1\ell_1 minimization up to constants: optimal error bounds for noisy and approximately sparse signals under a restricted isometry condition, and a cost bound. Dai and Milenkovic proposed subspace pursuit independently at the same time. Later work by Foucart and others improved the restricted isometry constants for CoSaMP, IHT and related methods.

References

  1. Deanna Needell and Joel A. Tropp, CoSaMP, iterative signal recovery from incomplete and inaccurate samples, Applied and Computational Harmonic Analysis 26(3), 2009, pages 301 to 321 (the algorithm, the iteration invariant under delta_4s <= 0.1 and the cost analysis)
  2. Wei Dai and Olgica Milenkovic, Subspace pursuit for compressive sensing signal reconstruction, IEEE Transactions on Information Theory 55(5), 2009, pages 2230 to 2249
  3. Simon Foucart and Holger Rauhut, A Mathematical Introduction to Compressive Sensing, Birkhauser, 2013, chapter 3 (the algorithm) and chapter 6 (its analysis under the restricted isometry property)

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.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)
WritingW1 outline
  • In plain words