Algorithm Search⌘K

Algorithmcore

Regression-based polynomial chaos

Also called least-squares polynomial chaos, point collocation polynomial chaos, polynomial chaos regression.

Fits polynomial chaos coefficients by least squares to model runs at random or designed inputs, with more runs than coefficients.

Time
O(N (C + P^2)) worst
Space
O(N P) extra
Where
C = the cost of one model run; N = the number of model runs (N >= P); P = the number of chaos terms (d+p choose p); d = the number of inputs; p = the total degree
Properties
randomizednot exactnot intrusive
Origin
Albert Cohen, Mark A. Davenport, Dany Leviatan, Geraud Blatman, Bruno Sudret, 2013

Regression-based polynomial chaos fits the coefficients of a polynomial chaos expansion to a set of model runs by least squares. It draws NN input points, runs the model at each, and chooses the coefficients that minimize the sum of squared differences between the expansion and the outputs. Unlike spectral projection by quadrature, it accepts any set of points, so the runs can come from random sampling, a Latin hypercube or an existing database. The number of runs must exceed the number of coefficients PP; a common rule of thumb (a heuristic, not a theorem) is N=2PN = 2P to 3P3P. The leave-one-out error, computed from one fit by the hat matrix identity, measures how well the expansion predicts new runs.

In plain words

You want a polynomial formula that copies a slow model, so that you can compute averages and sensitivities from the formula instead of the model. Run the model at a few hundred random inputs. Then pick the polynomial that passes as close as possible to all the outputs, in the sense of the smallest total squared miss. This is ordinary curve fitting with special polynomials, and one linear solve gives all the coefficients. To check the fit, leave out one run, fit again, and see how badly the new fit predicts the run you left out; average this over all runs. A simple formula gives this average from the single fit, so you do not need to refit. Take about two or three times as many runs as there are coefficients.

The problem

The input ξ=(ξ1,…,ξd)\xi = (\xi_1, \ldots, \xi_d) has independent components with laws ρ1,…,ρd\rho_1, \ldots, \rho_d. The output Q=q(ξ)Q = q(\xi) is square integrable, and qq can only be evaluated. The basis Ψα(ξ)=∏kψαk(k)(ξk)\Psi_\alpha(\xi) = \prod_k \psi^{(k)}_{\alpha_k}(\xi_k) is orthonormal for the law of ξ\xi, and the index set is Λ={α:∣α∣≤p}\Lambda = \{\alpha : |\alpha| \le p\} with P=(d+pp)P = \binom{d+p}{p} terms. Given N≥PN \ge P points x1,…,xNx_1, \ldots, x_N and the outputs yi=q(xi)y_i = q(x_i), find

c=arg⁡min⁡c∈RP∑i=1N(yi−∑α∈ΛcαΨα(xi))2,c = \arg\min_{c \in \mathbb{R}^P} \sum_{i=1}^{N} \Big(y_i - \sum_{\alpha \in \Lambda} c_\alpha \Psi_\alpha(x_i)\Big)^2,

together with an estimate of the error of qp=∑αcαΨαq_p = \sum_\alpha c_\alpha \Psi_\alpha on new inputs. The moments and the Sobol indices then follow from cc as for any orthonormal expansion.

The algorithm

  1. REGRESSION-PCE(q, ρ, p, N)
  2. 1Λ ← all α ∈ ℕ^d with |α| ≤ p; P ← |Λ|; require N ≥ P
  3. 2draw x_1, ..., x_N independently from ρ
  4. 3y_i ← q(x_i) for i = 1..N ▷ N model runs
  5. 4A[i, α] ← Ψ_α(x_i) ▷ N × P design matrix
  6. 5solve (A^T A) c = A^T y by Cholesky
  7. 6h_i ← A_i (A^T A)^{-1} A_i^T; ε_LOO ← (1/N) Σ_i ((y_i - A_i c) / (1 - h_i))^2 / Var(y)
  8. 7return c, ε_LOO

Line L1 builds the total degree set. Line L2 draws the points from the input law, which makes 1NATA\frac{1}{N} A^{\mathsf T} A an unbiased estimate of the identity, because E[ΨαΨβ]=δαβ\mathbb{E}[\Psi_\alpha \Psi_\beta] = \delta_{\alpha\beta}. Line L3 is the only place that runs the model, and the runs are independent. Line L4 evaluates the one dimensional polynomials by their recurrence and multiplies them. Line L5 solves the normal equations with the Cholesky decomposition of the P×PP \times P Gram matrix; when AA is ill conditioned, a QR decomposition of AA is the safer choice. Line L6 computes the leverages hih_i, the diagonal of the hat matrix H=A(ATA)−1ATH = A (A^{\mathsf T} A)^{-1} A^{\mathsf T}, from the same Cholesky factor: hi=∥L−1AiT∥2h_i = \|L^{-1} A_i^{\mathsf T}\|^2. The ratio (yi−Aic)/(1−hi)(y_i - A_i c)/(1 - h_i) is exactly the error at xix_i of the fit without run ii, so εLOO\varepsilon_{\mathrm{LOO}} is the leave-one-out mean squared error, divided by the sample variance of the outputs.

Example

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 and ξk\xi_k uniform on [−1,1][-1, 1] has mean 3.5, variance 13.84459, S1=0.3139S_1 = 0.3139 and total index ST3=0.2437S_{T3} = 0.2437. The fit uses the Legendre basis of total degree p=8p = 8, so P=165P = 165, and random uniform points. Each row of the table is a measurement over the five seeds 0 to 4. The validation error is the mean squared error on 2000 fresh random points divided by the variance.

NN N/PN/P mean, range over seeds S1S_1, range median εLOO\varepsilon_{\mathrm{LOO}} median validation error
167 1.01 -0.34 to 4.37 0.023 to 0.272 5.5 2.3
247 1.5 3.482 to 3.564 0.304 to 0.316 8.5×10−38.5 \times 10^{-3} 1.2×10−21.2 \times 10^{-2}
330 2 3.457 to 3.504 0.309 to 0.314 3.2×10−33.2 \times 10^{-3} 3.3×10−33.3 \times 10^{-3}
495 3 3.486 to 3.503 0.311 to 0.314 1.2×10−31.2 \times 10^{-3} 1.5×10−31.5 \times 10^{-3}

With almost as many runs as coefficients, the fit is useless: a relative error above 1 means that the expansion is worse than the constant mean. From N=1.5PN = 1.5 P on, the error falls fast, and the leave-one-out error tracks the validation error within a factor of about 2 without any extra runs. For comparison, the tensor Gauss rule of spectral projection needs 729 runs at p=8p = 8.

Correctness

If the design matrix AA has full column rank, then ATAA^{\mathsf T} A is symmetric positive definite, the Cholesky factor exists, and the solution of line L5 is the unique minimizer: for any c′c', ∥Ac′−y∥2=∥Ac−y∥2+∥A(c′−c)∥2\|A c' - y\|^2 = \|A c - y\|^2 + \|A (c' - c)\|^2 because the residual is orthogonal to the columns of AA. If qq lies in the span of Ψα\Psi_\alpha, α∈Λ\alpha \in \Lambda, then y=Ac∗y = A c^*, and the minimizer is c∗c^* itself, with a zero residual. With random points, full rank holds with probability 1 for polynomial bases and N≥PN \ge P (the zero set of a nonzero polynomial has measure zero). The leave-one-out identity follows from the Sherman-Morrison formula applied to ATA−AiTAiA^{\mathsf T} A - A_i^{\mathsf T} A_i. The proof file gives these steps in full.

Stability is a theorem only for enough runs. Let K(Λ)=sup⁡ξ∑α∈ΛΨα(ξ)2K(\Lambda) = \sup_\xi \sum_{\alpha \in \Lambda} \Psi_\alpha(\xi)^2. Cohen, Davenport and Leviatan proved that if K(Λ)≤κN/log⁡NK(\Lambda) \le \kappa N / \log N with an explicit constant κ\kappa depending on a chosen r>0r > 0, then with probability at least 1−2N−r1 - 2 N^{-r} the empirical Gram matrix 1NATA\frac{1}{N} A^{\mathsf T} A has all eigenvalues in [1/2,3/2][1/2, 3/2], and for a bounded qq the expected error of the fit, truncated at the bound, is close to the best approximation error in Λ\Lambda, plus a term of order N−rN^{-r}. For the Legendre basis K=P2K = P^2 in one dimension, so the theorem asks for NN of order P2log⁡PP^2 \log P uniform samples; the 2P2P to 3P3P rule is a heuristic that works for smooth outputs, as the example shows, but has no such guarantee.

Proof: The normal equations give the unique least-squares fit, the fit is exact on the span, and the hat matrix gives the leave-one-out residualsfull

We assume exact arithmetic. Let AA be the N×PN \times P design matrix of line L4, with rows Ai=(Ψα(xi))α∈ΛA_i = (\Psi_\alpha(x_i))_{\alpha \in \Lambda}, and let y=(y1,…,yN)Ty = (y_1, \ldots, y_N)^{\mathsf T}. Write G=ATAG = A^{\mathsf T} A and r(c)=y−Acr(c) = y - A c.

Lemma 1 (Cholesky succeeds exactly when AA has full column rank). GG is symmetric positive semidefinite, and it is positive definite if and only if the columns of AA are linearly independent.

Proof. GT=GG^{\mathsf T} = G, and vTGv=∥Av∥2≥0v^{\mathsf T} G v = \|A v\|^2 \ge 0, with equality if and only if Av=0A v = 0. So GG is positive definite if and only if Av=0A v = 0 only for v=0v = 0. The Cholesky algorithm on a symmetric matrix finds a positive pivot at every step if and only if the matrix is positive definite, so line L5 succeeds exactly in this case. □\square

Lemma 2 (the normal equations give the unique minimizer). If AA has full column rank, the solution cc of Gc=ATyG c = A^{\mathsf T} y satisfies ∥r(c′)∥2=∥r(c)∥2+∥A(c′−c)∥2\|r(c')\|^2 = \|r(c)\|^2 + \|A (c' - c)\|^2 for every c′c', so cc is the unique minimizer of ∥y−Ac′∥\|y - A c'\|.

Proof. ATr(c)=ATy−Gc=0A^{\mathsf T} r(c) = A^{\mathsf T} y - G c = 0, so the residual is orthogonal to every column of AA. Then r(c′)=r(c)−A(c′−c)r(c') = r(c) - A (c' - c), and the cross term 2(c′−c)TATr(c)2 (c' - c)^{\mathsf T} A^{\mathsf T} r(c) vanishes. The last term is positive for c′≠cc' \ne c by full rank. □\square

Lemma 3 (exact on the span). If q=∑α∈Λcα∗Ψαq = \sum_{\alpha \in \Lambda} c^*_\alpha \Psi_\alpha and AA has full column rank, then line L5 returns c=c∗c = c^*.

Proof. Then y=Ac∗y = A c^*, so ∥r(c∗)∥=0\|r(c^*)\| = 0, which is the smallest possible value, and Lemma 2 says the minimizer is unique. □\square

Lemma 4 (the leverages). Let LL be the Cholesky factor, G=LLTG = L L^{\mathsf T}, and hi=AiG−1AiTh_i = A_i G^{-1} A_i^{\mathsf T}. Then hi=∥L−1AiT∥2h_i = \|L^{-1} A_i^{\mathsf T}\|^2, 0≤hi≤10 \le h_i \le 1, and ∑ihi=P\sum_i h_i = P.

Proof. G−1=L−TL−1G^{-1} = L^{-\mathsf T} L^{-1}, so hi=(L−1AiT)T(L−1AiT)h_i = (L^{-1} A_i^{\mathsf T})^{\mathsf T} (L^{-1} A_i^{\mathsf T}). The hat matrix H=AG−1ATH = A G^{-1} A^{\mathsf T} satisfies HT=HH^{\mathsf T} = H and H2=AG−1GG−1AT=HH^2 = A G^{-1} G G^{-1} A^{\mathsf T} = H, so it is an orthogonal projection, and hi=eiTHei=∥Hei∥2≤∥ei∥2=1h_i = e_i^{\mathsf T} H e_i = \|H e_i\|^2 \le \|e_i\|^2 = 1. Finally ∑ihi=tr⁡H=tr⁡(G−1ATA)=tr⁡IP=P\sum_i h_i = \operatorname{tr} H = \operatorname{tr}(G^{-1} A^{\mathsf T} A) = \operatorname{tr} I_P = P. □\square

Lemma 5 (leave-one-out residuals). Suppose AA with row ii removed, A(i)A_{(i)}, still has full column rank, and let c(i)c_{(i)} be its least-squares fit to yy with entry ii removed. Then hi<1h_i < 1 and

yi−Aic(i)=yi−Aic1−hi.y_i - A_i c_{(i)} = \frac{y_i - A_i c}{1 - h_i}.

Proof. G(i)=A(i)TA(i)=G−AiTAiG_{(i)} = A_{(i)}^{\mathsf T} A_{(i)} = G - A_i^{\mathsf T} A_i is positive definite by Lemma 1. By the matrix determinant lemma, det⁡G(i)=(1−AiG−1AiT)det⁡G=(1−hi)det⁡G\det G_{(i)} = (1 - A_i G^{-1} A_i^{\mathsf T}) \det G = (1 - h_i) \det G, so hi<1h_i < 1. The Sherman-Morrison formula gives

G(i)−1=G−1+G−1AiTAiG−11−hi.G_{(i)}^{-1} = G^{-1} + \frac{G^{-1} A_i^{\mathsf T} A_i G^{-1}}{1 - h_i}.

Also A(i)Ty(i)=ATy−AiTyiA_{(i)}^{\mathsf T} y_{(i)} = A^{\mathsf T} y - A_i^{\mathsf T} y_i. Multiply: c(i)=G(i)−1(ATy−AiTyi)c_{(i)} = G_{(i)}^{-1} (A^{\mathsf T} y - A_i^{\mathsf T} y_i). Apply AiA_i on the left and use AiG−1ATy=AicA_i G^{-1} A^{\mathsf T} y = A_i c and AiG−1AiT=hiA_i G^{-1} A_i^{\mathsf T} = h_i:

Aic(i)=Aic−hiyi+hi(Aic−hiyi)1−hi=Aic−hiyi1−hi.A_i c_{(i)} = A_i c - h_i y_i + \frac{h_i (A_i c - h_i y_i)}{1 - h_i} = \frac{A_i c - h_i y_i}{1 - h_i}.

Then yi−Aic(i)=(1−hi)yi−Aic+hiyi1−hi=yi−Aic1−hiy_i - A_i c_{(i)} = \frac{(1 - h_i) y_i - A_i c + h_i y_i}{1 - h_i} = \frac{y_i - A_i c}{1 - h_i}. □\square

Lemma 6 (unbiased Gram matrix). If the points are drawn independently from the input law, then E[1NG]=IP\mathbb{E}[\frac{1}{N} G] = I_P.

Proof. 1NGαβ=1N∑iΨα(xi)Ψβ(xi)\frac{1}{N} G_{\alpha\beta} = \frac{1}{N} \sum_i \Psi_\alpha(x_i) \Psi_\beta(x_i), and each term has expectation E[ΨαΨβ]=δαβ\mathbb{E}[\Psi_\alpha \Psi_\beta] = \delta_{\alpha\beta} by orthonormality. □\square

Theorem. REGRESSION-PCE stops after NN model runs. If AA has full column rank, it returns the unique least-squares coefficients; they equal the true coefficients when qq lies in the span of the basis. If also every A(i)A_{(i)} has full column rank, the value εLOO\varepsilon_{\mathrm{LOO}} of line L6 equals 1N∑i(yi−Aic(i))2\frac{1}{N} \sum_i (y_i - A_i c_{(i)})^2 divided by the sample variance of yy, the leave-one-out mean squared error of NN separate refits.

Proof. Termination: lines L2 to L4 are loops of length NN and NPN P, line L5 is a Cholesky factorization of a P×PP \times P matrix and two triangular solves, and line L6 is NN triangular solves; all are finite. The coefficients are Lemmas 1 to 3, and the leave-one-out value is Lemmas 4 and 5. ■\blacksquare

The theorem makes no claim about the accuracy of the fit on new inputs for a qq outside the span. That claim needs the probabilistic stability theorem of Cohen, Davenport and Leviatan, which holds when N/log⁡NN / \log N is large compared with sup⁡ξ∑αΨα(ξ)2\sup_\xi \sum_\alpha \Psi_\alpha(\xi)^2, and which is quoted on the page but not proved here.

Complexity

In the real RAM model, line L3 costs NCN C. Line L4 costs O(N(dp+dP))O(N (d p + d P)). The Gram matrix costs O(NP2)O(N P^2), the Cholesky factor O(P3)O(P^3), and the leverages O(NP2)O(N P^2) by NN triangular solves. Since N≥PN \ge P, the total is O(N(C+P2))O(N (C + P^2)) time, and the design matrix takes O(NP)O(N P) space. For p=8p = 8, d=3d = 3 and N=495N = 495 the reference code takes well under a second in Python; for an expensive model, NCN C dominates.

Properties

  • Non-intrusive and design free. Any point set works, including runs that exist already.
  • Exact for polynomials (theorem). If qq is in the span of the basis and AA has full column rank, the fit is exact.
  • Randomized. With random points, the coefficients are random; repeated fits with new seeds show the spread, as in the example.
  • Free error estimate. The leave-one-out error comes from one fit, by the hat matrix identity.
  • Needs more runs than terms. N≥PN \ge P is necessary; NN close to PP gives a badly conditioned fit.
  • Curse of dimensionality. PP grows like dp/p!d^p / p! for fixed pp, and NN grows with it.

Variants and improvements

  • Weighted least squares. Draw the points from a sampling law adapted to the basis, such as the Chebyshev law for Legendre polynomials, and weight the rows by the density ratio. With the sampling law proportional to ∑αΨα2 ρ\sum_\alpha \Psi_\alpha^2\, \rho, the quantity KK of the stability theorem becomes PP, so the run count it needs falls to order Plog⁡PP \log P.
  • Designed points. Latin hypercube, quasi-Monte Carlo points or D-optimal subsets of a candidate set give better conditioned fits than plain random points for the same NN.
  • Sparse fits. When N<PN < P, or when most coefficients are small, use sparse polynomial chaos by l1 minimization, least angle regression or orthogonal matching pursuit, and choose the basis by the leave-one-out error.
  • Regularized fits. Ridge regression adds a penalty λ∥c∥2\lambda \|c\|^2 and keeps the solve stable when NN is close to PP.
  • Gradient-enhanced regression. If the model also returns derivatives, add rows for ∂q/∂ξk\partial q / \partial \xi_k; each run then gives d+1d + 1 equations.

When to use it

Use regression when the model is a black box, when the runs come from a given design or a database, or when a tensor quadrature grid would be too large. It is the usual choice for moderate dimension (up to about ten inputs) with a smooth output. Use spectral projection when the dimension is small and you can choose the points freely, sparse polynomial chaos when runs are fewer than coefficients, and Monte Carlo integration when the output is not smooth.

Pitfalls

  • Too few runs. At N≈PN \approx P the Gram matrix is nearly singular, and the coefficients are dominated by noise in the fit, as the first row of the example shows.
  • Unbounded bases. With Gaussian inputs, Hermite polynomials grow fast, and a few points in the tails get large leverage. Check that the leverages hih_i are not close to 1, and consider weighted sampling.
  • Normal equations square the condition number. The condition number of ATAA^{\mathsf T} A is the square of that of AA. For high degrees, use QR on AA.
  • Trusting the training residual. The residual of the fit always falls as pp grows; the leave-one-out error does not, and it is the one to use to pick pp.
  • Leverage equal to 1. If hi=1h_i = 1, removing run ii makes AA rank deficient and the leave-one-out formula divides by zero. Such a run is the only one that fixes some coefficient.

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.

regression_polynomial_chaos.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/regression-polynomial-chaos/. The authors are listed in prov/MZG7P5.jsonl.
"""Regression-based (least-squares) polynomial chaos with the leave-one-out error.

The input xi = (xi_1..xi_d) has independent components, each "uniform" on
[-1, 1] (orthonormal Legendre basis sqrt(2n+1) P_n) or "normal" (standard
normal, orthonormal Hermite basis He_n / sqrt(n!)). The code draws N random
inputs from the input law, runs the model, and solves the normal equations
(A^T A) c = A^T y by Cholesky, with A[i][a] = Psi_a(x_i). The leave-one-out
error uses the identity e_(-i) = e_i / (1 - h_i), where h_i is the diagonal
of the hat matrix A (A^T A)^(-1) A^T.
"""

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 gram(rows: list[list[float]]) -> list[list[float]]:
    """A^T A for the matrix with the given rows, using symmetry."""
    n = len(rows[0])
    g = [[0.0] * n for _ in range(n)]
    for r in rows:
        for i in range(n):
            ri = r[i]
            gi = g[i]
            for j in range(i, n):
                gi[j] += ri * r[j]
    for i in range(n):
        for j in range(i):
            g[i][j] = g[j][i]
    return g


def forward(low: list[list[float]], b: list[float]) -> list[float]:
    """Solve L z = b for lower triangular L."""
    z = [0.0] * len(b)
    for i in range(len(b)):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    return z


def least_squares(rows: list[list[float]], y: list[float]) -> tuple[list[float], list[list[float]]]:
    """Coefficients of min ||A c - y|| by the normal equations; also returns the Cholesky factor of A^T A."""
    n = len(rows[0])
    rhs = [sum(r[j] * yi for r, yi in zip(rows, y)) for j in range(n)]
    low = cholesky(gram(rows))
    return cholesky_solve(low, rhs), low


def loo_error(rows: list[list[float]], y: list[float], coeffs: list[float], low: list[list[float]]) -> float:
    """Relative leave-one-out error mean((e_i / (1 - h_i))^2) / var(y)."""
    n = len(y)
    total = 0.0
    for r, yi in zip(rows, y):
        e = yi - sum(a * c for a, c in zip(r, coeffs))
        z = forward(low, r)
        h = sum(v * v for v in z)
        total += (e / (1.0 - h)) ** 2
    mean = sum(y) / n
    var = sum((v - mean) ** 2 for v in y) / (n - 1)
    return (total / n) / var


def regression_pce(q: Model, families: list[str], p: int, n: int, rng: random.Random):
    """Least-squares PCE of total degree p from n random runs; returns (index, coeffs, loo)."""
    index = total_degree_set(len(families), p)  # @line L1
    if n < len(index):
        raise ValueError("need at least as many runs as coefficients")
    xs = [sample(families, rng) for _ in range(n)]  # @line L2
    y = [q(x) for x in xs]  # @line L3
    rows = [design_row(index, families, x) for x in xs]  # @line L4
    coeffs, low = least_squares(rows, y)  # @line L5
    loo = loo_error(rows, y, coeffs, low)  # @line L6
    return index, coeffs, loo  # @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 sobol_from_coefficients(index: list[tuple[int, ...]], coeffs: list[float]) -> tuple[list[float], list[float]]:
    """First order and total Sobol indices of an orthonormal expansion (Sudret 2008)."""
    d = len(index[0])
    _, var = mean_variance(coeffs)
    first = [0.0] * d
    total = [0.0] * d
    for a, c in zip(index, coeffs):
        active = [k for k in range(d) if a[k] > 0]
        if len(active) == 1:
            first[active[0]] += c * c
        for k in active:
            total[k] += c * c
    return [s / var for s in first], [s / var for s in total]


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)
scimat.py 227 lines
# 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)]
test_regression_polynomial_chaos.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/regression-polynomial-chaos/. The authors are listed in prov/MZG7P5.jsonl.
import math
import random

import pytest

from regression_polynomial_chaos import (
    cholesky,
    design_row,
    forward,
    gram,
    ishigami,
    least_squares,
    loo_error,
    mean_variance,
    regression_pce,
    sample,
    sobol_from_coefficients,
    total_degree_set,
)


def small_problem(seed):
    rng = random.Random(seed)
    fams = ["uniform", "normal"]
    index = total_degree_set(2, 2)
    xs = [sample(fams, rng) for _ in range(15)]
    rows = [design_row(index, fams, x) for x in xs]
    y = [math.sin(x[0]) + 0.3 * x[1] ** 3 + 0.1 * rng.gauss(0, 1) for x in xs]
    return rows, y


def test_polynomial_in_the_span_is_recovered_exactly():
    rng = random.Random(5)
    fams = ["uniform", "normal"]
    index = total_degree_set(2, 3)
    true = [rng.uniform(-1, 1) for _ in index]

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

    got_index, c, loo = regression_pce(q, fams, 3, 2 * len(index), random.Random(9))
    assert got_index == index
    assert max(abs(a - b) for a, b in zip(c, true)) < 1e-9
    assert loo < 1e-18


def test_loo_identity_matches_brute_force_refits():
    for seed in range(3):
        rows, y = small_problem(seed)
        c, low = least_squares(rows, y)
        fast = loo_error(rows, y, c, low)
        total = 0.0
        for i in range(len(y)):
            ci, _ = least_squares(rows[:i] + rows[i + 1 :], y[:i] + y[i + 1 :])
            total += (y[i] - sum(a * b for a, b in zip(rows[i], ci))) ** 2
        mean = sum(y) / len(y)
        var = sum((v - mean) ** 2 for v in y) / (len(y) - 1)
        assert abs(fast - total / len(y) / var) < 1e-9 * max(1.0, fast)


def test_hat_diagonal_sums_to_the_number_of_terms():
    rows, _ = small_problem(4)
    low = cholesky(gram(rows))
    h = [sum(v * v for v in forward(low, r)) for r in rows]
    assert abs(sum(h) - len(rows[0])) < 1e-10
    assert all(0.0 <= v <= 1.0 + 1e-12 for v in h)


def test_residual_is_orthogonal_to_every_basis_column():
    rows, y = small_problem(7)
    c, _ = least_squares(rows, y)
    res = [yi - sum(a * b for a, b in zip(r, c)) for r, yi in zip(rows, y)]
    for j in range(len(rows[0])):
        assert abs(sum(r[j] * e for r, e in zip(rows, res))) < 1e-10


def test_empirical_gram_matrix_tends_to_identity():
    rng = random.Random(2)
    index = total_degree_set(1, 3)
    rows = [design_row(index, ["uniform"], sample(["uniform"], rng)) for _ in range(4000)]
    g = gram(rows)
    n = len(rows)
    assert max(abs(g[i][j] / n - (1.0 if i == j else 0.0)) for i in range(4) for j in range(4)) < 0.15


def test_exponential_of_gaussian():
    _, c, loo = regression_pce(lambda x: math.exp(x[0]), ["normal"], 6, 200, random.Random(1))
    exact = [math.exp(0.5) / math.sqrt(math.factorial(n)) for n in range(7)]
    assert max(abs(a - b) for a, b in zip(c, exact)) < 0.05
    assert loo < 1e-3


def test_ishigami_sobol_indices():
    index, c, loo = regression_pce(ishigami, ["uniform"] * 3, 6, 252, random.Random(0))
    mean, _ = mean_variance(c)
    s, st = sobol_from_coefficients(index, c)
    assert abs(mean - 3.5) < 0.1
    assert abs(s[0] - 0.3139) < 0.02
    assert abs(s[1] - 0.4424) < 0.04
    assert abs(st[2] - 0.2437) < 0.03
    assert loo < 0.1


def test_too_few_runs_is_rejected():
    with pytest.raises(ValueError):
        regression_pce(ishigami, ["uniform"] * 3, 2, 9, random.Random(0))

History

The method of least squares goes back to Legendre in 1805 and to Gauss. Regression fits of polynomial chaos coefficients to random model runs came into use in the early 2000s as a non-intrusive alternative to the stochastic Galerkin method and to quadrature. Blatman and Sudret made the leave-one-out error from the hat matrix the standard check, and used it in 2011 to build sparse expansions by least angle regression. Cohen, Davenport and Leviatan gave in 2013 the first sharp theorem on how many random runs a stable least-squares fit needs, which started the work on optimal weighted sampling.

References

  1. Albert Cohen, Mark A. Davenport and Dany Leviatan, On the stability and accuracy of least squares approximations, Foundations of Computational Mathematics 13(5), 2013, 819-834, the stability condition on the number of random samples, K(P) at most a constant times N / log N, for the empirical Gram matrix to be close to the identity
  2. 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 leave-one-out error of a least-squares chaos expansion computed from the hat matrix diagonal
  3. Bruno Sudret, Global sensitivity analysis using polynomial chaos expansions, Reliability Engineering and System Safety 93(7), 2008, 964-979, the Sobol indices as sums of squared chaos coefficients, with the regression estimate of the coefficients
  4. Olivier P. Le Maitre and Omar M. Knio, Spectral Methods for Uncertainty Quantification, Springer, 2010, Chapter 3 (non-intrusive methods)

Where this leads

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