Algorithm Search⌘K

Algorithmresearch

Sparse polynomial chaos by compressive sampling

Also called compressive sensing polynomial chaos, l1-minimization polynomial chaos.

Recovers a polynomial chaos expansion with few large coefficients from fewer runs than terms by l1 minimization.

Time
O(N C + (K + d) N P + N^3) worst
Space
O(N P) extra
Where
C = the cost of one model run; K = the number of ISTA iterations; N = the number of model runs (N can be less than P); P = the number of chaos terms; d = the number of inputs
Properties
randomizednot exactnot intrusive
Origin
Alireza Doostan, Houman Owhadi, Geraud Blatman, Bruno Sudret, Holger Rauhut, Rachel Ward, 2011

Sparse polynomial chaos finds a polynomial chaos expansion from fewer model runs than the expansion has terms. It uses the fact that the expansion of many outputs has only a few large coefficients. Ordinary least squares needs at least as many runs NN as terms PP, but when N<PN < P the linear system Ac=yA c = y has many solutions. The method picks the one with the smallest ℓ1\ell_1 norm, as in compressed sensing, because the ℓ1\ell_1 norm favors vectors with few nonzero entries. This page solves the penalized form, the LASSO, by the iterative shrinkage-thresholding algorithm (ISTA), and then refits the coefficients it keeps by least squares. In the example below, 25 random runs recover exactly a five term polynomial in five inputs, out of 56 candidate terms.

In plain words

You want a polynomial formula for a slow model, but the formula has more unknown weights than you can afford runs. Usually that is hopeless: too few equations for the unknowns. But if most of the weights are really zero, there is hope, because you only have to find the few that are not. The trick is to ask for the solution that fits the runs and has the smallest sum of absolute weights. That choice tends to set most weights exactly to zero. A simple loop finds it: take a small step that improves the fit, then pull every weight toward zero by a fixed amount, and set it to zero if it crosses. At the end, fit the surviving weights again by plain least squares to undo the pull.

The problem

The input ξ=(ξ1,…,ξd)\xi = (\xi_1, \ldots, \xi_d) has independent components with laws ρk\rho_k, the output is Q=q(ξ)Q = q(\xi), and Ψα\Psi_\alpha, α∈Λ\alpha \in \Lambda, is the orthonormal chaos basis of total degree pp, with P=∣Λ∣P = |\Lambda| terms. Given NN runs yi=q(xi)y_i = q(x_i) at points drawn from the input law, possibly with N<PN < P, find coefficients cc with few nonzero entries such that ∑αcαΨα\sum_\alpha c_\alpha \Psi_\alpha fits the runs. With the scaled design matrix A[i,α]=Ψα(xi)/NA[i, \alpha] = \Psi_\alpha(x_i) / \sqrt{N} and the scaled outputs yi/Ny_i / \sqrt{N}, the convex problem is

min⁡c∈RPF(c)=12∥Ac−y∥2+λ∥c∥1,λ>0.\min_{c \in \mathbb{R}^P} F(c) = \tfrac{1}{2} \|A c - y\|^2 + \lambda \|c\|_1, \qquad \lambda > 0.

The scaling makes E[ATA]=I\mathbb{E}[A^{\mathsf T} A] = I, so λ\lambda has the same meaning for every NN.

The algorithm

  1. SPARSE-PCE(q, ρ, p, N, λ, K)
  2. 1Λ ← all α ∈ ℕ^d with |α| ≤ p; draw x_1, ..., x_N from ρ ▷ N may be smaller than P
  3. 2y_i ← q(x_i) / √N; A[i, α] ← Ψ_α(x_i) / √N ▷ N model runs
  4. 3L ← ‖A‖_2^2 by power iteration; c ← 0
  5. 4repeat K times: c ← S_{λ/L}(c - (1/L) A^T (A c - y)) ▷ ISTA step
  6. 5S ← {α : c_α ≠ 0}
  7. 6if |S| < N: c ← least-squares fit of y on the columns S of A ▷ debias
  8. 7return c

Lines L1 and L2 draw the points and run the model, as in regression. Line L3 bounds the Lipschitz constant LL of the gradient AT(Ac−y)A^{\mathsf T} (A c - y) by the largest eigenvalue of ATAA^{\mathsf T} A; the reference code runs 200 steps of power iteration and adds 1 percent, so the step 1/L1/L is safe. Line L4 is the proximal gradient step of ISTA: a gradient step on the smooth part, then the soft threshold Sτ(t)=sign⁡(t)max⁡(∣t∣−τ,0)S_\tau(t) = \operatorname{sign}(t) \max(|t| - \tau, 0) in each entry, which is the proximal map of τ∣t∣\tau |t|. Entries that the gradient step leaves smaller than λ/L\lambda / L become exactly zero. The reference code takes λ\lambda as a fraction of ∥ATy∥∞\|A^{\mathsf T} y\|_\infty, because for λ≥∥ATy∥∞\lambda \ge \|A^{\mathsf T} y\|_\infty the solution is c=0c = 0. Line L5 reads the support. Line L6 refits on the support without the penalty, which removes the shrinkage of every kept coefficient by about λ\lambda.

Example

Exact recovery. Take d=5d = 5 uniform inputs, total degree p=3p = 3, so P=56P = 56, and a true expansion with the constant 1 and four other nonzero coefficients of size between 0.5 and 1.5 at random positions. The run uses λ=0.01∥ATy∥∞\lambda = 0.01 \|A^{\mathsf T} y\|_\infty and K=2000K = 2000. A trial counts as recovered if every coefficient is within 10−810^{-8} of the truth. This is a measurement over 20 seeds.

runs NN N/PN/P recovered
10 0.18 0 of 20
12 0.21 1 of 20
14 0.25 2 of 20
16 0.29 2 of 20
18 0.32 12 of 20
20 0.36 18 of 20
25 0.45 20 of 20

Least squares cannot even start below 56 runs. The sharp change from failure to success is typical of compressed sensing.

The Ishigami function. Q=sin⁡x1+7sin⁡2x2+0.1 x34sin⁡x1Q = \sin x_1 + 7 \sin^2 x_2 + 0.1\, x_3^4 \sin x_1 with xk=πξkx_k = \pi \xi_k, ξk\xi_k uniform on [−1,1][-1, 1], has mean 3.5 and variance 13.84459. The basis is Legendre of total degree 8, so P=165P = 165, with λ=0.01∥ATy∥∞\lambda = 0.01 \|A^{\mathsf T} y\|_\infty and K=1500K = 1500. The validation error is the mean squared error on 1000 fresh points divided by the variance. This is a measurement over seeds 0 to 4.

NN kept terms mean, range median validation error
50 33 to 49 3.476 to 3.632 6.3×10−26.3 \times 10^{-2}
75 18 to 44 3.471 to 3.510 1.1×10−31.1 \times 10^{-3}
100 15 to 27 3.489 to 3.510 5.2×10−45.2 \times 10^{-4}
150 13 to 21 3.489 to 3.507 4.5×10−44.5 \times 10^{-4}

With 100 runs the error is below that of least squares on the same basis with 495 runs (median 1.5×10−31.5 \times 10^{-3}), because the fit keeps only about 20 terms. The error stops falling near 4×10−44 \times 10^{-4}, the error of a sparse expansion of degree 8.

Correctness

The objective FF is convex, and a minimizer exists because F(c)≥λ∥c∥1→∞F(c) \ge \lambda \|c\|_1 \to \infty. ISTA is the proximal gradient method for FF. With the step 1/L1/L and L≥∥A∥22L \ge \|A\|_2^2, each step does not increase FF, and Beck and Teboulle proved (their Theorem 3.1) that F(ck)−F(c∗)≤L∥c0−c∗∥2/(2k)F(c_k) - F(c^*) \le L \|c_0 - c^*\|^2 / (2k) for every minimizer c∗c^*. A fixed point of the step is exactly a point that satisfies the optimality conditions: (AT(y−Ac))α=λsign⁡(cα)(A^{\mathsf T}(y - A c))_\alpha = \lambda \operatorname{sign}(c_\alpha) where cα≠0c_\alpha \ne 0 and ∣(AT(y−Ac))α∣≤λ|(A^{\mathsf T}(y - A c))_\alpha| \le \lambda elsewhere. The proof file proves the descent property, the rate and the fixed point characterization. The debias step is exact on the support: if SS contains the true support of a polynomial qq in the span and the columns SS of AA are independent, the refit returns the true coefficients.

That the ℓ1\ell_1 solution finds the true support is a separate, probabilistic claim. It holds when the matrix AA satisfies a restricted isometry property or a null space property of order ss. For bounded orthonormal systems, random samples from the orthogonality law give such a matrix with high probability when NN is of order ss times a power of log⁡P\log P. Rauhut and Ward proved this for Legendre polynomials with samples from the Chebyshev law and a preconditioned system; the constants are large, and the run counts in the example are measurements, not consequences of the theorem.

Proof: ISTA decreases the LASSO objective at the rate L R^2 / (2k), its fixed points are the minimizers, and the refit is exact on a correct supportfull

We assume exact arithmetic. Let AA be the real N×PN \times P matrix and y∈RNy \in \mathbb{R}^N of lines L1 and L2, f(c)=12∥Ac−y∥2f(c) = \frac{1}{2} \|A c - y\|^2, g(c)=λ∥c∥1g(c) = \lambda \|c\|_1 with λ>0\lambda > 0, and F=f+gF = f + g. The gradient is ∇f(c)=AT(Ac−y)\nabla f(c) = A^{\mathsf T}(A c - y). We assume L≥∥A∥22L \ge \|A\|_2^2, the largest eigenvalue of ATAA^{\mathsf T} A. Write T(c)=Sλ/L(c−∇f(c)/L)T(c) = S_{\lambda/L}(c - \nabla f(c) / L) for the step of line L4, with SτS_\tau applied entrywise.

Lemma 1 (a minimizer exists). FF is convex and has at least one minimizer c∗c^*.

Proof. ff is convex as a convex quadratic, and gg is a norm times λ\lambda. FF is continuous and F(c)≥λ∥c∥1F(c) \ge \lambda \|c\|_1, so the set {c:F(c)≤F(0)}\{c : F(c) \le F(0)\} is closed and bounded, and FF attains its minimum on it. □\square

Lemma 2 (the step is a proximal step). T(c)T(c) is the unique minimizer of z↦L2∥z−(c−∇f(c)/L)∥2+λ∥z∥1z \mapsto \frac{L}{2} \|z - (c - \nabla f(c)/L)\|^2 + \lambda \|z\|_1.

Proof. The function is a sum over entries of hj(zj)=L2(zj−vj)2+λ∣zj∣h_j(z_j) = \frac{L}{2}(z_j - v_j)^2 + \lambda |z_j|, with v=c−∇f(c)/Lv = c - \nabla f(c)/L, and each hjh_j is strictly convex. For zj>0z_j > 0, hj′=L(zj−vj)+λh_j' = L(z_j - v_j) + \lambda vanishes at zj=vj−λ/Lz_j = v_j - \lambda/L, which is positive exactly when vj>λ/Lv_j > \lambda / L; the case zj<0z_j < 0 is symmetric. If ∣vj∣≤λ/L|v_j| \le \lambda/L, then the one-sided derivatives at 0 are −Lvj+λ≥0-L v_j + \lambda \ge 0 on the right and −Lvj−λ≤0-L v_j - \lambda \le 0 on the left, so zj=0z_j = 0 is the minimizer. In all cases the minimizer is Sλ/L(vj)S_{\lambda/L}(v_j). □\square

Lemma 3 (the key inequality). For every cc and zz, with c+=T(c)c^+ = T(c),

F(z)−F(c+)≥L2(∥c+−z∥2−∥c−z∥2).F(z) - F(c^+) \ge \tfrac{L}{2} \big(\|c^+ - z\|^2 - \|c - z\|^2\big).

Proof. The optimality condition of Lemma 2 says that γ=−∇f(c)−L(c+−c)\gamma = -\nabla f(c) - L (c^+ - c) is a subgradient of gg at c+c^+, so g(z)≥g(c+)+γT(z−c+)g(z) \ge g(c^+) + \gamma^{\mathsf T}(z - c^+). Convexity of ff gives f(z)≥f(c)+∇f(c)T(z−c)f(z) \ge f(c) + \nabla f(c)^{\mathsf T}(z - c). Since ∇f\nabla f is ∥A∥22\|A\|_2^2-Lipschitz and L≥∥A∥22L \ge \|A\|_2^2, the descent lemma gives f(c+)≤f(c)+∇f(c)T(c+−c)+L2∥c+−c∥2f(c^+) \le f(c) + \nabla f(c)^{\mathsf T}(c^+ - c) + \frac{L}{2}\|c^+ - c\|^2; for this quadratic ff it is the identity f(c+)=f(c)+∇f(c)T(c+−c)+12∥A(c+−c)∥2f(c^+) = f(c) + \nabla f(c)^{\mathsf T}(c^+ - c) + \frac{1}{2}\|A (c^+ - c)\|^2 together with ∥Aw∥2≤∥A∥22∥w∥2\|A w\|^2 \le \|A\|_2^2 \|w\|^2. Add the three inequalities:

F(z)−F(c+)≥(∇f(c)+γ)T(z−c+)−L2∥c+−c∥2=−L(c+−c)T(z−c+)−L2∥c+−c∥2.F(z) - F(c^+) \ge (\nabla f(c) + \gamma)^{\mathsf T}(z - c^+) - \tfrac{L}{2}\|c^+ - c\|^2 = -L (c^+ - c)^{\mathsf T}(z - c^+) - \tfrac{L}{2}\|c^+ - c\|^2.

Expand ∥c−z∥2=∥c+−c∥2+2(c−c+)T(c+−z)+∥c+−z∥2\|c - z\|^2 = \|c^+ - c\|^2 + 2 (c - c^+)^{\mathsf T}(c^+ - z) + \|c^+ - z\|^2; the right side above is exactly L2(∥c+−z∥2−∥c−z∥2)\frac{L}{2}(\|c^+ - z\|^2 - \|c - z\|^2). □\square

Lemma 4 (descent). F(T(c))≤F(c)−L2∥T(c)−c∥2F(T(c)) \le F(c) - \frac{L}{2} \|T(c) - c\|^2. So the objective never increases along the ISTA iterates.

Proof. Take z=cz = c in Lemma 3. □\square

Lemma 5 (the rate, Beck and Teboulle, Theorem 3.1). Let c0c_0 be any start, ck+1=T(ck)c_{k+1} = T(c_k), and c∗c^* any minimizer. Then for k≥1k \ge 1, F(ck)−F(c∗)≤L∥c0−c∗∥2/(2k)F(c_k) - F(c^*) \le L \|c_0 - c^*\|^2 / (2k).

Proof. Take c=cjc = c_j and z=c∗z = c^* in Lemma 3: F(c∗)−F(cj+1)≥L2(∥cj+1−c∗∥2−∥cj−c∗∥2)F(c^*) - F(c_{j+1}) \ge \frac{L}{2}(\|c_{j+1} - c^*\|^2 - \|c_j - c^*\|^2). Sum over j=0,…,k−1j = 0, \ldots, k-1; the right side telescopes:

kF(c∗)−∑j=1kF(cj)≥L2(∥ck−c∗∥2−∥c0−c∗∥2)≥−L2∥c0−c∗∥2.k F(c^*) - \sum_{j=1}^{k} F(c_j) \ge \tfrac{L}{2}\big(\|c_k - c^*\|^2 - \|c_0 - c^*\|^2\big) \ge -\tfrac{L}{2}\|c_0 - c^*\|^2.

By Lemma 4, F(cj)≥F(ck)F(c_j) \ge F(c_k) for j≤kj \le k, so ∑j=1kF(cj)≥kF(ck)\sum_{j=1}^k F(c_j) \ge k F(c_k). Then k(F(ck)−F(c∗))≤L2∥c0−c∗∥2k (F(c_k) - F(c^*)) \le \frac{L}{2} \|c_0 - c^*\|^2. □\square

Lemma 6 (fixed points are minimizers). T(c)=cT(c) = c if and only if cc minimizes FF, if and only if, with r=AT(y−Ac)r = A^{\mathsf T}(y - A c), rj=λsign⁡(cj)r_j = \lambda \operatorname{sign}(c_j) for cj≠0c_j \ne 0 and ∣rj∣≤λ|r_j| \le \lambda for cj=0c_j = 0.

Proof. Since FF is convex, cc is a minimizer if and only if 0∈∇f(c)+λ ∂∥c∥10 \in \nabla f(c) + \lambda\, \partial \|c\|_1, which in entries is the stated condition, because ∇f(c)=−r\nabla f(c) = -r and the subdifferential of ∣t∣|t| is {sign⁡t}\{\operatorname{sign} t\} for t≠0t \ne 0 and [−1,1][-1, 1] for t=0t = 0. On the other hand, T(c)=cT(c) = c means Sλ/L(cj+rj/L)=cjS_{\lambda/L}(c_j + r_j/L) = c_j for every jj. If cj≠0c_j \ne 0, Lemma 2 shows that this holds if and only if cj=cj+rj/L−(λ/L)sign⁡(cj)c_j = c_j + r_j/L - (\lambda/L) \operatorname{sign}(c_j), that is rj=λsign⁡(cj)r_j = \lambda \operatorname{sign}(c_j). If cj=0c_j = 0, it holds if and only if ∣rj/L∣≤λ/L|r_j / L| \le \lambda / L. □\square

Lemma 7 (the refit is exact on a correct support). Let y=Ac∘y = A c^\circ for a vector c∘c^\circ whose nonzero entries lie in SS, and let the columns SS of AA be linearly independent. Then the refit of line L6 returns c∘c^\circ.

Proof. The columns SS form a matrix ASA_S of full column rank, so the least-squares problem min⁡u∥ASu−y∥\min_u \|A_S u - y\| has a unique solution (the normal equations have a positive definite matrix). The restriction of c∘c^\circ to SS gives a zero residual, so it is that solution, and the other entries are set to 0. □\square

Theorem. SPARSE-PCE stops after NN model runs and a fixed number of arithmetic operations. After KK steps from c0=0c_0 = 0, the ISTA iterate satisfies F(cK)≤F(cK−1)≤…≤F(0)F(c_K) \le F(c_{K-1}) \le \ldots \le F(0) and F(cK)−min⁡F≤L∥c∗∥2/(2K)F(c_K) - \min F \le L \|c^*\|^2 / (2K). Every limit point of the iterates is a minimizer. If the support found in line L5 contains the support of the true coefficient vector of a polynomial qq in the span, and the columns on it are independent, the returned coefficients are the true ones.

Proof. Termination: power iteration runs a fixed number of steps, ISTA runs KK steps, and the refit is one Cholesky solve on at most N−1N - 1 columns. Monotonicity and the rate are Lemmas 4 and 5 with c0=0c_0 = 0. The iterates stay in the bounded set {F≤F(0)}\{F \le F(0)\}; if cki→cˉc_{k_i} \to \bar c, then ∥T(cki)−cki∥2≤2L(F(cki)−F(cki+1))→0\|T(c_{k_i}) - c_{k_i}\|^2 \le \frac{2}{L}(F(c_{k_i}) - F(c_{k_i + 1})) \to 0 by Lemma 4, because F(ck)F(c_k) is decreasing and bounded below. TT is continuous, so T(cˉ)=cˉT(\bar c) = \bar c, and Lemma 6 makes cˉ\bar c a minimizer. The last claim is Lemma 7. ■\blacksquare

Two parts of the method are not covered by the theorem. First, the reference code estimates LL by 200 power iteration steps times 1.01. Power iteration approaches ∥A∥22\|A\|_2^2 from below, so the margin is a heuristic; the tests check that the estimate bounds ∥ATAv∥/∥v∥\|A^{\mathsf T} A v\| / \|v\| on random vectors. Second, the theorem does not say that the support of the LASSO minimizer is the true support. That needs a property of AA such as the restricted isometry property, which random samples give only with high probability.

Complexity

In the real RAM model, line L2 costs NCN C for the runs plus O(dNP)O(d N P) for the design matrix. Each power iteration step and each ISTA step costs O(NP)O(N P), for two products with AA; with 200 power steps and K≥200K \ge 200, lines L3 and L4 cost O(KNP)O(K N P). The refit on ∣S∣<N|S| < N columns costs O(N∣S∣2+∣S∣3)=O(N3)O(N |S|^2 + |S|^3) = O(N^3). The total is O(NC+(K+d)NP+N3)O(N C + (K + d) N P + N^3) time and O(NP)O(N P) space. ISTA may need many iterations: its rate is only O(1/k)O(1/k), and FISTA, its accelerated form, reaches O(1/k2)O(1/k^2) at the same cost per step.

Properties

  • Fewer runs than terms. It can work with N<PN < P, if the expansion is sparse or nearly sparse.
  • Convex. The LASSO problem has no spurious local minima, and ISTA converges from any start.
  • Randomized. The points are random, and recovery holds with high probability, not always.
  • Non-intrusive. The model is a black box.
  • Biased without refit. The ℓ1\ell_1 penalty shrinks every kept coefficient; the refit of line L6 removes this.
  • Parameter dependent. The result depends on λ\lambda, which has to be chosen, for example by cross-validation.

Variants and improvements

  • Basis pursuit. Solve min⁡∥c∥1\min \|c\|_1 subject to Ac=yA c = y exactly, by linear programming, or with ∥Ac−y∥≤δ\|A c - y\| \le \delta for noisy data.
  • FISTA. Add a momentum step to ISTA; the rate becomes O(1/k2)O(1/k^2) (Beck and Teboulle, Theorem 4.4).
  • Greedy methods. Orthogonal matching pursuit adds one basis function at a time, and least angle regression follows the whole LASSO path; Blatman and Sudret choose the stopping point by the leave-one-out error.
  • Weighted ℓ1\ell_1 and preconditioning. Weights that grow with the degree, or sampling from the Chebyshev law with a preconditioner, improve recovery for Legendre bases.
  • Adaptive bases. Grow the candidate set Λ\Lambda around the terms already found, instead of fixing a total degree.

When to use it

Use sparse polynomial chaos when runs are expensive, the number of inputs is moderate to large, and you expect only a few inputs and low order interactions to matter, so that most coefficients are small. Choose λ\lambda by cross-validation, and check the result on runs that were not used. Use least squares when you can afford two or three times PP runs, and spectral projection for few inputs on a grid.

Pitfalls

  • Dense expansions. If many coefficients have similar size, no sparse solution fits, and the ℓ1\ell_1 fit is a poor approximation. The validation error shows this.
  • A step larger than 1/L1/L. ISTA then can diverge. Estimate LL from above, not from below; power iteration approaches ∥A∥22\|A\|_2^2 from below, so add a margin.
  • Unscaled λ\lambda. A fixed λ\lambda means different things for different NN and output scales. Scale it by ∥ATy∥∞\|A^{\mathsf T} y\|_\infty or by the noise level.
  • Refit on a large support. If the support has NN or more entries, the least-squares refit is not unique; the reference code then keeps the ISTA result.
  • Slow convergence. ISTA can need thousands of steps for a small λ\lambda. Stop on the change in FF, or use FISTA.

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.

scimat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and error norms for the scientific-computing pages.

A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.

API (fixed; other pages copy this file byte for byte):
    zeros(m, n=None)        m by n zero matrix (n = m if not given)
    eye(n)                  n by n identity
    add(A, B), sub(A, B)    entrywise sum and difference (vectors or matrices)
    scale(c, A)             c times A (vector or matrix)
    matmul(A, B)            matrix product
    matvec(A, x)            matrix times vector
    transpose(A)            transpose
    dot(x, y)               inner product of two vectors
    norm2(x)                Euclidean norm of a vector, as a float
    outer(x, y)             outer product x y^T
    solve(A, b)             Gaussian elimination with partial pivoting;
                            b is a vector or a matrix of right sides
    inv(A)                  inverse of A
    det(A)                  determinant of A
    cholesky(A)             lower triangular L with A = L L^T (floats)
    cholesky_solve(L, b)    solve L L^T x = b for a vector b
    err_l1(e, dx=1)         sum |e_j| dx
    err_l2(e, dx=1)         sqrt(sum e_j^2 dx), as a float
    err_linf(e, dx=1)       max |e_j| (dx is not used)
    observed_order(errors)  [log2(E_i / E_(i+1)) for successive errors]
"""

import math


def zeros(m, n=None):
    """Return an m by n matrix of zeros (n = m if n is None)."""
    if n is None:
        n = m
    return [[0] * n for _ in range(m)]


def eye(n):
    """Return the n by n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1
    return out


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return 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):
    """Return 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(c, a):
    """Return c times a, for a vector or a matrix a."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def matmul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]


def dot(x, y):
    """Return the inner product of the vectors x and y."""
    return sum(a * b for a, b in zip(x, y))


def norm2(x):
    """Return the Euclidean norm of the vector x, as a float."""
    return math.sqrt(float(dot(x, x)))


def outer(x, y):
    """Return the outer product x y^T as a matrix."""
    return [[a * b for b in y] for a in x]


def _eliminate(a, rhs):
    """Reduce a to upper triangular form with partial pivoting.

    a is a copy of the square matrix, rhs a list of right side rows (one
    row per row of a) that receives the same row operations. Return the
    number of row swaps. Raise ValueError if a pivot is zero.
    """
    n = len(a)
    swaps = 0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("matrix is singular")
        if p != k:
            a[k], a[p] = a[p], a[k]
            rhs[k], rhs[p] = rhs[p], rhs[k]
            swaps += 1
        for i in range(k + 1, n):
            f = a[i][k] / a[k][k]
            if f == 0:
                continue
            for j in range(k, n):
                a[i][j] -= f * a[k][j]
            for j in range(len(rhs[i])):
                rhs[i][j] -= f * rhs[k][j]
    return swaps


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

    b is a vector (the result is a vector) or a matrix with one column per
    right side (the result is a matrix). Fraction entries stay exact.
    Raise ValueError if a is singular.
    """
    n = len(a)
    work = [list(row) for row in a]
    vector = not _is_matrix(b)
    rhs = [[v] for v in b] if vector else [list(row) for row in b]
    _eliminate(work, rhs)
    m = len(rhs[0]) if n else 0
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = rhs[i][j]
            for k in range(i + 1, n):
                s -= work[i][k] * x[k][j]
            x[i][j] = s / work[i][i]
    if vector:
        return [row[0] for row in x]
    return x


def inv(a):
    """Return the inverse of the square matrix a."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a (0 if singular)."""
    work = [list(row) for row in a]
    rhs = [[] for _ in a]
    try:
        swaps = _eliminate(work, rhs)
    except ValueError:
        return 0
    d = -1 if swaps % 2 else 1
    for i in range(len(a)):
        d *= work[i][i]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T, in floats.

    Raise ValueError if a is not symmetric positive definite.
    """
    n = len(a)
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
        if s <= 0.0:
            raise ValueError("matrix is not positive definite")
        low[j][j] = math.sqrt(s)
        for i in range(j + 1, n):
            t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
            low[i][j] = t / low[j][j]
    return low


def cholesky_solve(low, b):
    """Solve L L^T x = b, with L from cholesky, for a vector b."""
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def err_l1(e, dx=1):
    """Return the discrete L1 norm sum |e_j| dx."""
    return sum(abs(v) for v in e) * dx


def err_l2(e, dx=1):
    """Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
    return math.sqrt(float(sum(v * v for v in e) * dx))


def err_linf(e, dx=1):
    """Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
    return max(abs(v) for v in e)


def observed_order(errors):
    """Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
    return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
sparse_polynomial_chaos.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-polynomial-chaos/. The authors are listed in prov/NEQJ8H.jsonl.
"""Sparse polynomial chaos by l1 minimization (compressive sampling).

The input xi = (xi_1..xi_d) has independent components, each "uniform" on
[-1, 1] (orthonormal Legendre basis) or "normal" (orthonormal Hermite basis).
The code draws N random inputs, possibly fewer than the number of terms P,
and solves the LASSO form of basis pursuit denoising

    min_c  (1/2) ||A c - y||^2 + lam ||c||_1,   A[i][a] = Psi_a(x_i) / sqrt(N),
    y_i = q(x_i) / sqrt(N),

by ISTA (proximal gradient with the constant step 1/L, L = ||A||_2^2).
It then refits the coefficients on the support that ISTA found by least
squares, which removes the shrinkage bias of the l1 penalty.
"""

import itertools
import math
import random
from typing import Callable

from scimat import cholesky, cholesky_solve

Model = Callable[[list[float]], float]


def recurrence_offdiag(family: str, k: int) -> float:
    """b_k in x psi_(k-1) = b_k psi_k + b_(k-1) psi_(k-2) for the orthonormal family."""
    if family == "uniform":
        return k / math.sqrt((2 * k - 1) * (2 * k + 1))
    if family == "normal":
        return math.sqrt(k)
    raise ValueError("family must be 'uniform' or 'normal'")


def basis_1d(family: str, x: float, p: int) -> list[float]:
    """psi_0(x)..psi_p(x), orthonormal for the law of the family."""
    vals = [1.0]
    if p >= 1:
        vals.append(x / recurrence_offdiag(family, 1))
    for k in range(2, p + 1):
        bk, bk1 = recurrence_offdiag(family, k), recurrence_offdiag(family, k - 1)
        vals.append((x * vals[k - 1] - bk1 * vals[k - 2]) / bk)
    return vals


def total_degree_set(d: int, p: int) -> list[tuple[int, ...]]:
    """All a in N^d with |a| <= p, sorted by total degree; the zero index is first."""
    out = [a for a in itertools.product(range(p + 1), repeat=d) if sum(a) <= p]
    out.sort(key=lambda a: (sum(a), [-v for v in a]))
    return out


def sample(families: list[str], rng: random.Random) -> list[float]:
    """One draw of the input vector from its law."""
    return [rng.uniform(-1.0, 1.0) if f == "uniform" else rng.gauss(0.0, 1.0) for f in families]


def design_row(index: list[tuple[int, ...]], families: list[str], x: list[float]) -> list[float]:
    """The row Psi_a(x), a in index."""
    p = max(sum(a) for a in index)
    tables = [basis_1d(families[k], x[k], p) for k in range(len(x))]
    return [math.prod(tables[k][a[k]] for k in range(len(x))) for a in index]


def apply(rows: list[list[float]], c: list[float]) -> list[float]:
    """A c."""
    return [sum(a * b for a, b in zip(r, c)) for r in rows]


def apply_t(rows: list[list[float]], v: list[float]) -> list[float]:
    """A^T v."""
    out = [0.0] * len(rows[0])
    for r, vi in zip(rows, v):
        if vi != 0.0:
            for j, a in enumerate(r):
                out[j] += a * vi
    return out


def lipschitz(rows: list[list[float]], iters: int = 200) -> float:
    """An upper bound on ||A||_2^2: power iteration on A^T A, enlarged by 1 percent."""
    v = [1.0] * len(rows[0])
    lam = 0.0
    for _ in range(iters):
        w = apply_t(rows, apply(rows, v))
        lam = math.sqrt(sum(t * t for t in w))
        if lam == 0.0:
            return 1.0
        v = [t / lam for t in w]
    return 1.01 * lam


def soft(t: float, tau: float) -> float:
    """The soft thresholding S_tau(t) = sign(t) max(|t| - tau, 0), the prox of tau |.|."""
    if t > tau:
        return t - tau
    if t < -tau:
        return t + tau
    return 0.0


def objective(rows: list[list[float]], y: list[float], c: list[float], lam: float) -> float:
    """(1/2) ||A c - y||^2 + lam ||c||_1."""
    r = [a - b for a, b in zip(apply(rows, c), y)]
    return 0.5 * sum(t * t for t in r) + lam * sum(abs(t) for t in c)


def ista(rows: list[list[float]], y: list[float], lam: float, iters: int, lip: float | None = None) -> list[float]:
    """ISTA with the constant step 1/L from c = 0."""
    lip = lipschitz(rows) if lip is None else lip  # @line L3
    c = [0.0] * len(rows[0])
    for _ in range(iters):  # @line L4
        g = apply_t(rows, [a - b for a, b in zip(apply(rows, c), y)])
        c = [soft(cj - gj / lip, lam / lip) for cj, gj in zip(c, g)]
    return c


def debias(rows: list[list[float]], y: list[float], support: list[int]) -> list[float]:
    """Least-squares refit on the given support; the other coefficients are 0."""
    c = [0.0] * len(rows[0])
    if not support:
        return c
    sub = [[r[j] for j in support] for r in rows]
    g = [[sum(r[i] * r[j] for r in sub) for j in range(len(support))] for i in range(len(support))]
    rhs = [sum(r[i] * yi for r, yi in zip(sub, y)) for i in range(len(support))]
    for j, v in zip(support, cholesky_solve(cholesky(g), rhs)):
        c[j] = v
    return c


def sparse_pce(q: Model, families: list[str], p: int, n: int, lam_ratio: float, iters: int, rng: random.Random):
    """Sparse PCE of total degree p from n runs; lam = lam_ratio * ||A^T y||_inf. Returns (index, coeffs, support)."""
    index = total_degree_set(len(families), p)  # @line L1
    xs = [sample(families, rng) for _ in range(n)]
    s = 1.0 / math.sqrt(n)
    y = [s * q(x) for x in xs]  # @line L2
    rows = [[s * v for v in design_row(index, families, x)] for x in xs]
    lam = lam_ratio * max(abs(t) for t in apply_t(rows, y))
    c = ista(rows, y, lam, iters)
    support = [j for j, v in enumerate(c) if v != 0.0]  # @line L5
    if len(support) < n:
        c = debias(rows, y, support)  # @line L6
    return index, c, support  # @line L7


def mean_variance(coeffs: list[float]) -> tuple[float, float]:
    """Mean c_0 and variance sum_{a != 0} c_a^2 of an orthonormal expansion."""
    return coeffs[0], sum(c * c for c in coeffs[1:])


def ishigami(x: list[float], a: float = 7.0, b: float = 0.1) -> float:
    """The Ishigami function with inputs xi_k uniform on [-1, 1], mapped to pi xi_k."""
    x1, x2, x3 = (math.pi * v for v in x)
    return math.sin(x1) + a * math.sin(x2) ** 2 + b * x3**4 * math.sin(x1)
test_sparse_polynomial_chaos.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-polynomial-chaos/. The authors are listed in prov/NEQJ8H.jsonl.
import itertools
import math
import random

from sparse_polynomial_chaos import (
    apply,
    apply_t,
    debias,
    design_row,
    ista,
    lipschitz,
    objective,
    sample,
    soft,
    sparse_pce,
    total_degree_set,
)


def random_problem(seed, n=8, d=2, p=3):
    rng = random.Random(seed)
    fams = ["uniform"] * d
    index = total_degree_set(d, p)
    rows = [[v / math.sqrt(n) for v in design_row(index, fams, sample(fams, rng))] for _ in range(n)]
    y = [rng.gauss(0, 1) for _ in range(n)]
    return rows, y


def test_soft_thresholding():
    assert soft(3.0, 1.0) == 2.0
    assert soft(-3.0, 1.0) == -2.0
    assert soft(0.5, 1.0) == 0.0
    assert soft(-1.0, 1.0) == 0.0


def test_lipschitz_bounds_the_gradient():
    rows, _ = random_problem(1)
    lip = lipschitz(rows)
    rng = random.Random(2)
    for _ in range(20):
        v = [rng.gauss(0, 1) for _ in rows[0]]
        w = apply_t(rows, apply(rows, v))
        assert math.sqrt(sum(t * t for t in w)) <= lip * math.sqrt(sum(t * t for t in v)) + 1e-12


def test_ista_objective_never_increases():
    rows, y = random_problem(3)
    lam = 0.05 * max(abs(t) for t in apply_t(rows, y))
    lip = lipschitz(rows)
    prev = objective(rows, y, [0.0] * len(rows[0]), lam)
    for k in range(1, 60):
        f = objective(rows, y, ista(rows, y, lam, k, lip), lam)
        assert f <= prev + 1e-12
        prev = f


def test_beck_teboulle_sublinear_bound():
    rows, y = random_problem(4)
    lam = 0.05 * max(abs(t) for t in apply_t(rows, y))
    lip = lipschitz(rows)
    c_star = ista(rows, y, lam, 20000, lip)
    f_star = objective(rows, y, c_star, lam)
    r2 = sum(t * t for t in c_star)
    for k in range(1, 80):
        gap = objective(rows, y, ista(rows, y, lam, k, lip), lam) - f_star
        assert gap <= lip * r2 / (2 * k) + 1e-9


def test_limit_satisfies_the_optimality_conditions():
    rows, y = random_problem(5)
    lam = 0.05 * max(abs(t) for t in apply_t(rows, y))
    c = ista(rows, y, lam, 20000)
    g = apply_t(rows, [b - a for a, b in zip(apply(rows, c), y)])
    for cj, gj in zip(c, g):
        if cj != 0.0:
            assert abs(gj - math.copysign(lam, cj)) < 1e-6
        else:
            assert abs(gj) <= lam + 1e-6


def test_large_penalty_gives_zero():
    rows, y = random_problem(6)
    lam = 1.0001 * max(abs(t) for t in apply_t(rows, y))
    assert all(v == 0.0 for v in ista(rows, y, lam, 50))


def test_matches_brute_force_l0_oracle_with_fewer_runs_than_terms():
    fams = ["uniform", "uniform"]
    index = total_degree_set(2, 3)
    true = [0.0] * len(index)
    true[index.index((1, 0))] = 1.5
    true[index.index((0, 2))] = -0.8

    def q(x):
        return sum(a * b for a, b in zip(design_row(index, fams, x), true))

    n = 7
    rng = random.Random(8)
    xs = [sample(fams, rng) for _ in range(n)]
    rows = [design_row(index, fams, x) for x in xs]
    y = [q(x) for x in xs]
    best = None
    for supp in itertools.combinations(range(len(index)), 2):
        c = debias(rows, y, list(supp))
        res = sum((a - b) ** 2 for a, b in zip(apply(rows, c), y))
        if best is None or res < best[0]:
            best = (res, supp)
    assert best[1] == (index.index((1, 0)), index.index((0, 2)))
    _, c, _ = sparse_pce(q, fams, 3, n, 0.01, 3000, random.Random(8))
    assert max(abs(a - b) for a, b in zip(c, true)) < 1e-8


def test_sparse_polynomial_in_five_inputs_from_25_runs():
    fams = ["uniform"] * 5
    index = total_degree_set(5, 3)
    rng = random.Random(0)
    true = [0.0] * len(index)
    for j in rng.sample(range(1, len(index)), 4):
        true[j] = rng.choice([-1, 1]) * rng.uniform(0.5, 1.5)
    true[0] = 1.0

    def q(x):
        return sum(a * b for a, b in zip(design_row(index, fams, x), true))

    _, c, support = sparse_pce(q, fams, 3, 25, 0.01, 2000, random.Random(100))
    assert len(index) == 56
    assert max(abs(a - b) for a, b in zip(c, true)) < 1e-8
    assert len(support) < 25

History

The ℓ1\ell_1 norm as a proxy for sparsity goes back to work in geophysics and statistics, and became the basis of compressed sensing in the mid 2000s. Iterative soft thresholding for ℓ1\ell_1 penalized least squares was analyzed in the same years, and Beck and Teboulle proved its O(1/k)O(1/k) rate and gave the accelerated FISTA in 2009. Doostan and Owhadi applied compressive sampling to the chaos coefficients of PDEs with random inputs in 2011. In the same year Blatman and Sudret built sparse expansions by least angle regression with a leave-one-out stopping rule. Rauhut and Ward proved in 2012 that sparse Legendre expansions are recovered from a number of samples that grows only with the sparsity and logarithmically with the number of terms.

References

  1. Alireza Doostan and Houman Owhadi, A non-adapted sparse approximation of PDEs with stochastic inputs, Journal of Computational Physics 230(8), 2011, 3015-3034, the recovery of sparse chaos coefficients of PDE solutions by l1 minimization from fewer random samples than basis functions
  2. Holger Rauhut and Rachel Ward, Sparse Legendre expansions via l1-minimization, Journal of Approximation Theory 164(5), 2012, 517-533, the recovery guarantee for sparse Legendre expansions from random samples of the Chebyshev law with a preconditioned system
  3. Amir Beck and Marc Teboulle, A fast iterative shrinkage-thresholding algorithm for linear inverse problems, SIAM Journal on Imaging Sciences 2(1), 2009, 183-202, Theorem 3.1 (the O(1/k) rate of ISTA with a constant step) and Theorem 4.4 (the O(1/k^2) rate of FISTA)
  4. Geraud Blatman and Bruno Sudret, Adaptive sparse polynomial chaos expansion based on least angle regression, Journal of Computational Physics 230(6), 2011, 2345-2367, the sparse chaos expansion by least angle regression with the basis chosen by the leave-one-out error

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)
WritingW2 basic
  • a scene preset for the example