Algorithm Search⌘K

Algorithmcore

Non-intrusive spectral projection

Also called pseudospectral projection, NISP, discrete spectral projection, quadrature-based polynomial chaos.

Computes polynomial chaos coefficients as projections evaluated by quadrature over model runs at the quadrature nodes.

Time
O(m^d (C + d P)) worst
Space
O(P + d m) extra
Where
C = the cost of one model run; P = the number of chaos terms (d+p choose p); d = the number of inputs; m = the number of Gauss points per input; p = the total degree
Properties
deterministicnot exactnot intrusive
Origin
Matthew T. Reagan, Habib N. Najm, Roger G. Ghanem, Omar M. Knio, 2003

Non-intrusive spectral projection (NISP) computes the coefficients of a polynomial chaos expansion of a model output by numerical integration. For an orthonormal basis, the coefficient of Ψα\Psi_\alpha is the projection cα=E[q(ξ)Ψα(ξ)]c_\alpha = \mathbb{E}[q(\xi) \Psi_\alpha(\xi)]. NISP replaces each expectation by a Gauss quadrature rule for the input law, so it needs the model only at the quadrature nodes, as a black box. One set of runs gives all coefficients, and from them the mean, the variance and the Sobol indices. With a tensor rule of mm points per input, the coefficients of degree up to pp are exact for every polynomial output of total degree pp when m≥p+1m \ge p + 1. For a smooth output they converge exponentially. The price is the mdm^d runs of the tensor grid, so the plain method serves only a few inputs.

In plain words

You want to write a model output as a sum of special polynomials of the random inputs, and you need the weight of each polynomial. Each weight is an average: the average of the output times that polynomial. You cannot compute the average exactly, but you can estimate it well from a few carefully chosen input values and weights, a Gauss rule. So you run the model at those input values, and you compute every weight from the same set of runs. The model itself does not change, which is why the method is called non-intrusive. For one input, ten runs are often enough. For several inputs, the rule uses every combination of the points, so the number of runs multiplies with each new input.

The problem

The input ξ=(ξ1,…,ξd)\xi = (\xi_1, \ldots, \xi_d) has independent components with laws ρ1,…,ρd\rho_1, \ldots, \rho_d, on a probability space (Ω,F,P)(\Omega, \mathcal{F}, \mathbb{P}). The model output is Q=q(ξ)Q = q(\xi), square integrable, and qq can only be evaluated. The basis is Ψα(ξ)=∏kψαk(k)(ξk)\Psi_\alpha(\xi) = \prod_k \psi^{(k)}_{\alpha_k}(\xi_k), where ψ0(k),ψ1(k),…\psi^{(k)}_0, \psi^{(k)}_1, \ldots are the orthonormal polynomials of ρk\rho_k: the normalized probabilists' Hermite polynomials Hen/n!\mathrm{He}_n / \sqrt{n!} for a standard normal input, and 2n+1 Pn\sqrt{2n+1}\, P_n with the Legendre polynomials PnP_n for a uniform input on [−1,1][-1, 1]. The index set is the total degree set Λ={α:∣α∣≤p}\Lambda = \{\alpha : |\alpha| \le p\}, with P=(d+pp)P = \binom{d+p}{p} terms. The output is the vector of coefficients cαc_\alpha, α∈Λ\alpha \in \Lambda, and the moments and Sobol indices of the expansion qp=∑αcαΨαq_p = \sum_\alpha c_\alpha \Psi_\alpha.

The algorithm

  1. NISP(q, ρ_1..ρ_d, p, m)
  2. 1for k ← 1 to d: (x^k_j, w^k_j), j = 1..m ← Gauss rule of ρ_k ▷ Golub-Welsch
  3. 2Λ ← all α ∈ ℕ^d with |α| ≤ p; c_α ← 0 for α ∈ Λ
  4. 3for each node x = (x^1_{j_1}, ..., x^d_{j_d}) with weight w = w^1_{j_1} ⋯ w^d_{j_d} do
  5. 4y ← q(x) ▷ one model run
  6. 5for each α ∈ Λ: c_α ← c_α + w y Ψ_α(x)
  7. 6return c, mean c_0, variance Σ_{α ≠ 0} c_α^2

Line L1 builds an mm point rule for each input law. The Golub-Welsch algorithm gets it from the three term recurrence xψn−1=bnψn+bn−1ψn−2x \psi_{n-1} = b_n \psi_n + b_{n-1} \psi_{n-2}: the nodes are the eigenvalues of the symmetric tridiagonal Jacobi matrix with off-diagonal b1,…,bm−1b_1, \ldots, b_{m-1}, and the weights are the squared first components of its unit eigenvectors. For the orthonormal Hermite family bn=nb_n = \sqrt{n}, and for the orthonormal Legendre family bn=n/4n2−1b_n = n / \sqrt{4n^2 - 1}. The weights sum to 1, because ρk\rho_k is a probability law. The Gauss-Hermite quadrature page uses the physicists' weight e−x2e^{-x^2}; its nodes are those here divided by 2\sqrt{2}, and its weights are those here times π\sqrt{\pi}. Line L3 visits the mdm^d nodes of the tensor rule. Line L4 is the only call to the model, and the runs are independent, so they can run in parallel. Line L5 accumulates every coefficient from the same run. Line L6 reads the moments off the coefficients by orthonormality; the Sobol index of a set of inputs is the sum of cα2c_\alpha^2 over the α\alpha whose nonzero entries are exactly those inputs, divided by the variance.

Example

One Gaussian input. Let Q=eξQ = e^{\xi} with ξ∼N(0,1)\xi \sim N(0, 1). The exact mean is e1/2=1.6487213e^{1/2} = 1.6487213, the exact variance is e2−e=4.6707743e^2 - e = 4.6707743, and the exact coefficients are cn=e1/2/n!c_n = e^{1/2} / \sqrt{n!}. The run takes p=m−1p = m - 1. The values are deterministic.

mm (runs) mean error of mean variance error of variance cm−1c_{m-1} exact cm−1c_{m-1}
2 1.5430806 1.06×10−11.06 \times 10^{-1} 1.381098 3.29 1.1752 1.6487
3 1.6381925 1.05×10−21.05 \times 10^{-2} 3.312833 1.36 0.9025 1.1658
4 1.6479690 7.52×10−47.52 \times 10^{-4} 4.279512 3.91×10−13.91 \times 10^{-1} 0.5480 0.6731
5 1.6486794 4.18×10−54.18 \times 10^{-5} 4.583510 8.73×10−28.73 \times 10^{-2} 0.2835 0.3365
6 1.6487194 1.90×10−61.90 \times 10^{-6} 4.654858 1.59×10−21.59 \times 10^{-2} 0.1299 0.1505
8 1.6487213 2.45×10−92.45 \times 10^{-9} 4.670446 3.29×10−43.29 \times 10^{-4} 0.02072 0.02322

With m=2m = 2 the nodes are ±1\pm 1 with weights 1/21/2, so the mean is cosh⁡1\cosh 1. The mean converges much faster than the top coefficient. The rule integrates eξΨne^{\xi} \Psi_n well for small nn, but for n=m−1n = m - 1 the integrand has a high degree part that the rule cannot see. This error is called aliasing.

The Ishigami function. Let 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], with the Legendre basis and m=p+1m = p + 1:

pp runs PP mean variance S1S_1 S2S_2 ST3S_{T3}
4 125 35 3.441659 17.16952 0.2489 0.6415 0.1096
6 343 84 3.499702 14.80586 0.2935 0.4878 0.2187
8 729 165 3.500000 13.88491 0.3130 0.4442 0.2428
10 1331 286 3.500000 13.84513 0.3139 0.4424 0.2437
12 2197 455 3.500000 13.84459 0.3139 0.4424 0.2437
exact 3.5 13.84459 0.3139 0.4424 0.2437

At p=4p = 4 the variance is too large, not too small, which can only come from aliasing: a truncated exact expansion always has a smaller variance than the function. S3S_3 is zero to rounding at every degree, because x3x_3 enters only together with x1x_1.

Correctness

The claim is that the coefficients are exact projections whenever the tensor rule integrates qΨαq \Psi_\alpha exactly. An mm point Gauss rule is exact for polynomials of degree at most 2m−12m - 1, and the tensor rule is exact for polynomials whose degree in each variable is at most 2m−12m - 1. So if qq is a polynomial of total degree at most pp and m≥p+1m \ge p + 1, then qΨαq \Psi_\alpha has degree at most 2p≤2m−22p \le 2m - 2 in each variable, and NISP returns the exact expansion. For a general q=∑βcβΨβq = \sum_\beta c_\beta \Psi_\beta, the computed coefficient is c~α=cα+∑β∉Λcβ Qm[ΨαΨβ]\tilde c_\alpha = c_\alpha + \sum_{\beta \notin \Lambda} c_\beta\, Q_m[\Psi_\alpha \Psi_\beta], where QmQ_m is the rule. The second term is the aliasing error. For uniform inputs and a continuous qq, it tends to zero as mm grows, because Gauss rules on a bounded interval converge for every continuous integrand. The proof file proves the Golub-Welsch formulas, the exactness and the aliasing formula.

Proof: The Golub-Welsch rule is exact to degree 2m - 1, so NISP recovers every polynomial of low enough degree and its error is pure aliasingfull

We assume exact arithmetic, including an exact symmetric eigendecomposition in line L1. Each input ξk\xi_k has a law ρk\rho_k that is symmetric about 0 with all moments finite and with infinitely many points in its support, the inputs are independent, and ψ0=1,ψ1,ψ2,…\psi_0 = 1, \psi_1, \psi_2, \ldots are the orthonormal polynomials of one law, with deg⁡ψn=n\deg \psi_n = n. For the two laws of the reference code they satisfy the three term recurrence

x ψn−1(x)=bnψn(x)+bn−1ψn−2(x),n≥1,x\, \psi_{n-1}(x) = b_n \psi_n(x) + b_{n-1} \psi_{n-2}(x), \qquad n \ge 1,

with ψ−1=0\psi_{-1} = 0 and bn>0b_n > 0: bn=nb_n = \sqrt{n} for the standard normal law, from xHen−1=Hen+(n−1)Hen−2x \mathrm{He}_{n-1} = \mathrm{He}_n + (n - 1) \mathrm{He}_{n-2} and ψn=Hen/n!\psi_n = \mathrm{He}_n / \sqrt{n!}, and bn=n/(2n−1)(2n+1)b_n = n / \sqrt{(2n-1)(2n+1)} for the uniform law on [−1,1][-1, 1], from nPn=(2n−1)xPn−1−(n−1)Pn−2n P_n = (2n - 1) x P_{n-1} - (n - 1) P_{n-2} and ψn=2n+1 Pn\psi_n = \sqrt{2n+1}\, P_n. Both follow by direct substitution.

Lemma 1 (Golub-Welsch). Let JJ be the symmetric tridiagonal m×mm \times m matrix with zero diagonal and off-diagonal b1,…,bm−1b_1, \ldots, b_{m-1}, and let (xj,vj)(x_j, v_j), j=1,…,mj = 1, \ldots, m, be its eigenpairs with ∥vj∥=1\|v_j\| = 1. Then each xjx_j is a zero of ψm\psi_m, the xjx_j are distinct, and wj=(vj)12=1/∑n=0m−1ψn(xj)2w_j = (v_j)_1^2 = 1 / \sum_{n=0}^{m-1} \psi_n(x_j)^2.

Proof. Write Ψ(x)=(ψ0(x),…,ψm−1(x))T\Psi(x) = (\psi_0(x), \ldots, \psi_{m-1}(x))^{\mathsf T}. The recurrence for n=1,…,mn = 1, \ldots, m reads xΨ(x)=JΨ(x)+bmψm(x) emx \Psi(x) = J \Psi(x) + b_m \psi_m(x)\, e_m. Take an eigenpair (λ,v)(\lambda, v). Row i<mi < m of Jv=λvJ v = \lambda v is bi−1vi−1+bivi+1=λvib_{i-1} v_{i-1} + b_i v_{i+1} = \lambda v_i; since bi>0b_i > 0, it determines vi+1v_{i+1} from v1,…,viv_1, \ldots, v_i, by the same rule as the recurrence determines ψi(λ)\psi_i(\lambda). So v=v1Ψ(λ)v = v_1 \Psi(\lambda), and v1≠0v_1 \ne 0 because v≠0v \ne 0. Then row mm gives bmψm(λ)v1=0b_m \psi_m(\lambda) v_1 = 0, so ψm(λ)=0\psi_m(\lambda) = 0. The eigenspace of λ\lambda is spanned by Ψ(λ)\Psi(\lambda), so it has dimension 1; as JJ is symmetric, its mm eigenvalues are then distinct. Finally 1=∥v∥2=v12 ∥Ψ(λ)∥21 = \|v\|^2 = v_1^2\, \|\Psi(\lambda)\|^2. □\square

Lemma 2 (discrete orthonormality). For 0≤a,b≤m−10 \le a, b \le m - 1, ∑jwj ψa(xj) ψb(xj)=δab\sum_{j} w_j\, \psi_a(x_j)\, \psi_b(x_j) = \delta_{ab}.

Proof. By Lemma 1, (vj)a+1=wj ψa(xj)(v_j)_{a+1} = \sqrt{w_j}\, \psi_a(x_j) up to the common sign of vjv_j. The matrix V=[v1,…,vm]V = [v_1, \ldots, v_m] is orthogonal, so its rows are orthonormal as well: ∑j(vj)a+1(vj)b+1=δab\sum_j (v_j)_{a+1} (v_j)_{b+1} = \delta_{ab}. □\square

Lemma 3 (Gauss exactness). For every polynomial ff of degree at most 2m−12m - 1, ∑jwjf(xj)=E[f(ξ)]\sum_j w_j f(x_j) = \mathbb{E}[f(\xi)].

Proof. Divide: f=ψms+rf = \psi_m s + r with deg⁡s≤m−1\deg s \le m - 1 and deg⁡r≤m−1\deg r \le m - 1. Since ss is a combination of ψ0,…,ψm−1\psi_0, \ldots, \psi_{m-1}, orthogonality gives E[ψms]=0\mathbb{E}[\psi_m s] = 0, so E[f]=E[r]\mathbb{E}[f] = \mathbb{E}[r]. Write r=∑a<mraψar = \sum_{a < m} r_a \psi_a; then E[r]=r0\mathbb{E}[r] = r_0. On the quadrature side, ψm(xj)=0\psi_m(x_j) = 0 by Lemma 1, so ∑jwjf(xj)=∑ara∑jwjψa(xj)ψ0(xj)=r0\sum_j w_j f(x_j) = \sum_a r_a \sum_j w_j \psi_a(x_j) \psi_0(x_j) = r_0 by Lemma 2 with b=0b = 0. □\square

With f=1f = 1, the weights sum to 1.

Lemma 4 (tensor exactness). Let Qm[g]=∑j1,…,jdwj11⋯wjdd g(xj11,…,xjdd)Q_m[g] = \sum_{j_1, \ldots, j_d} w^1_{j_1} \cdots w^d_{j_d}\, g(x^1_{j_1}, \ldots, x^d_{j_d}) be the tensor rule of lines L3 to L5. If gg is a polynomial whose degree in each variable is at most 2m−12m - 1, then Qm[g]=E[g(ξ)]Q_m[g] = \mathbb{E}[g(\xi)].

Proof. QmQ_m and E\mathbb{E} are both linear, so it suffices to take g=∏kgk(ξk)g = \prod_k g_k(\xi_k) with deg⁡gk≤2m−1\deg g_k \le 2m - 1. Then Qm[g]=∏k∑jwjkgk(xjk)=∏kE[gk(ξk)]Q_m[g] = \prod_k \sum_j w^k_j g_k(x^k_j) = \prod_k \mathbb{E}[g_k(\xi_k)] by Lemma 3, and this equals E[g]\mathbb{E}[g] by independence. □\square

Lemma 5 (what line L5 computes). After the loop, c~α=Qm[q Ψα]\tilde c_\alpha = Q_m[q\, \Psi_\alpha] for every α∈Λ\alpha \in \Lambda.

Proof. Each node of the tensor grid is visited exactly once in line L3, with its product weight, and line L5 adds w q(x) Ψα(x)w\, q(x)\, \Psi_\alpha(x) to c~α\tilde c_\alpha. The sum over all nodes is the definition of Qm[qΨα]Q_m[q \Psi_\alpha]. □\square

Lemma 6 (aliasing). Let m≥p+1m \ge p + 1, and let q=∑β∈BcβΨβq = \sum_{\beta \in B} c_\beta \Psi_\beta be a polynomial, with BB finite and cβ=E[qΨβ]c_\beta = \mathbb{E}[q \Psi_\beta]. Then for α∈Λ\alpha \in \Lambda,

c~α=cα+∑β∈B, βk≥2m−αk for some kcβ Qm[ΨαΨβ].\tilde c_\alpha = c_\alpha + \sum_{\beta \in B,\ \beta_k \ge 2m - \alpha_k \text{ for some } k} c_\beta\, Q_m[\Psi_\alpha \Psi_\beta].

Proof. By Lemma 5 and linearity, c~α=∑β∈BcβQm[ΨαΨβ]\tilde c_\alpha = \sum_{\beta \in B} c_\beta Q_m[\Psi_\alpha \Psi_\beta]. If αk+βk≤2m−1\alpha_k + \beta_k \le 2m - 1 for every kk, then Lemma 4 and orthonormality give Qm[ΨαΨβ]=E[ΨαΨβ]=δαβQ_m[\Psi_\alpha \Psi_\beta] = \mathbb{E}[\Psi_\alpha \Psi_\beta] = \delta_{\alpha\beta}. The term β=α\beta = \alpha is of this kind, because 2αk≤2p≤2m−22 \alpha_k \le 2p \le 2m - 2. The other terms of this kind are 0, and the terms left are the ones in the sum. □\square

Lemma 7 (moments and Sobol indices of the result). Let q~=∑α∈Λc~αΨα\tilde q = \sum_{\alpha \in \Lambda} \tilde c_\alpha \Psi_\alpha. Then E[q~]=c~0\mathbb{E}[\tilde q] = \tilde c_0 and Var[q~]=∑α≠0c~α2\mathrm{Var}[\tilde q] = \sum_{\alpha \ne 0} \tilde c_\alpha^2. For a nonempty set uu of inputs, the Sobol variance of q~\tilde q for uu is ∑α:{k:αk>0}=uc~α2\sum_{\alpha : \{k : \alpha_k > 0\} = u} \tilde c_\alpha^2.

Proof. E[Ψα]=E[ΨαΨ0]=δα0\mathbb{E}[\Psi_\alpha] = \mathbb{E}[\Psi_\alpha \Psi_0] = \delta_{\alpha 0} and E[q~2]=∑αc~α2\mathbb{E}[\tilde q^2] = \sum_\alpha \tilde c_\alpha^2 by orthonormality. For the Sobol part, group the terms by their set of active inputs: q~=∑ufu\tilde q = \sum_u f_u with fu=∑{k:αk>0}=uc~αΨαf_u = \sum_{\{k : \alpha_k > 0\} = u} \tilde c_\alpha \Psi_\alpha. Each fuf_u depends only on ξu\xi_u, and the integral of fuf_u over any one ξk\xi_k with k∈uk \in u is 0, because E[ψn]=0\mathbb{E}[\psi_n] = 0 for n≥1n \ge 1. By uniqueness of the Hoeffding-Sobol decomposition, these fuf_u are its terms, and Var[fu]=∑c~α2\mathrm{Var}[f_u] = \sum \tilde c_\alpha^2 over its indices by orthonormality. □\square

Theorem. NISP stops after exactly mdm^d model runs. It returns c~α=Qm[qΨα]\tilde c_\alpha = Q_m[q \Psi_\alpha], and the mean and variance of the line L6 are those of q~\tilde q. If qq is a polynomial whose degree in each variable is at most 2m−1−p2m - 1 - p, then c~α=cα\tilde c_\alpha = c_\alpha for every α∈Λ\alpha \in \Lambda. In particular, if m≥p+1m \ge p + 1 and qq has total degree at most pp, then q~=q\tilde q = q.

Proof. Termination: line L1 runs dd eigendecompositions of m×mm \times m matrices, line L2 lists the finite set Λ\Lambda, and the loop of line L3 has mdm^d passes, each with one model run and ∣Λ∣|\Lambda| updates. The value of c~α\tilde c_\alpha is Lemma 5, and the moments are Lemma 7. If qq has degree at most 2m−1−p2m - 1 - p in each variable, then qΨαq \Psi_\alpha has degree at most 2m−12m - 1 in each variable, since αk≤p\alpha_k \le p; Lemma 4 gives c~α=E[qΨα]=cα\tilde c_\alpha = \mathbb{E}[q \Psi_\alpha] = c_\alpha. If m≥p+1m \ge p + 1 and qq has total degree at most pp, then its degree in each variable is at most p≤2m−1−pp \le 2m - 1 - p, and q=∑α∈ΛcαΨαq = \sum_{\alpha \in \Lambda} c_\alpha \Psi_\alpha, so q~=q\tilde q = q. ■\blacksquare

The reference code computes the eigendecomposition by cyclic Jacobi rotations, which converge but do not stop in finitely many steps in exact arithmetic. The code stops at a relative off-diagonal tolerance of 10−1510^{-15} or after 100 sweeps, whichever comes first, so it terminates; the nodes and weights are then correct to rounding, and the test checks exactness to degree 2m−12m - 1 to a relative 10−1210^{-12}.

Complexity

In the real RAM model, line L1 costs O(dm3)O(d m^3) with the Jacobi eigenvalue method of the reference code. The loop of lines L3 to L5 runs mdm^d times, and each pass costs one model run CC, O(dp)O(d p) for the one dimensional basis values, and O(dP)O(d P) for the products and sums. The total is O(md(C+dP))O(m^d (C + d P)) time and O(P+dm)O(P + d m) extra space; the runs are not stored. In practice CC dominates everything else. With m=p+1m = p + 1 and d=5d = 5, p=4p = 4, the tensor grid has 3125 nodes for 126 coefficients. Sparse grid quadrature reduces the node count to a number that grows only polynomially in dd for fixed accuracy level.

Properties

  • Non-intrusive. The model is a black box. Its existing solver runs unchanged at each node.
  • Exact for polynomials (theorem). With m≥p+1m \ge p + 1, every polynomial in the span of Ψα\Psi_\alpha, α∈Λ\alpha \in \Lambda, is recovered exactly, and NISP is then a projection onto that span.
  • Embarrassingly parallel. The mdm^d runs are independent.
  • Deterministic. No sampling error; the error is truncation plus aliasing.
  • Exponential convergence (theorem for analytic outputs). For uniform inputs, if qq is analytic in a neighborhood of [−1,1]d[-1, 1]^d, the quadrature error and the truncation error both decay exponentially in mm and pp. For Gaussian inputs, the decay also needs growth conditions on qq; the example above shows it for eξe^{\xi}.
  • Curse of dimensionality. The tensor grid has mdm^d nodes.

Variants and improvements

  • Sparse grid projection. Replace the tensor rule by a Smolyak sparse grid. The direct use of a sparse quadrature in line L5 aliases even some coefficients inside the index set; Constantine, Eldred and Phipps showed that a combination of tensor projections, the sparse pseudospectral approximation method, avoids this.
  • Other input laws. Gauss-Laguerre for gamma and Gauss-Jacobi for beta inputs, or rules built from the recurrence of an arbitrary law; see generalized polynomial chaos.
  • Nested rules. Gauss-Kronrod-Patterson or Clenshaw-Curtis points reuse the runs of a coarse rule when the level rises.
  • Least squares instead of quadrature. Regression-based polynomial chaos fits the coefficients to runs at random points and does not need a structured grid.
  • Anisotropic grids. Different mm for inputs of different importance, chosen from a first coarse run.

When to use it

Use NISP when the model is a black box, the number of inputs is small (up to about four with tensor grids, more with sparse grids), and the output is smooth in the inputs. It is the simplest way to get a polynomial chaos expansion from an existing code. Use regression-based polynomial chaos when the runs come from a given design or when the grid would be too large, sparse polynomial chaos when only a few coefficients matter, and stochastic collocation when you need an interpolating surrogate on a sparse grid. Use Monte Carlo integration when the output is not smooth, for example an indicator of failure.

Pitfalls

  • Too few points for the degree. With m<p+1m < p + 1, the high coefficients are mostly aliasing. Keep m≥p+1m \ge p + 1, and check the size of the last coefficients.
  • A variance that is too large. The variance from aliased coefficients can be larger than the true variance, as at p=4p = 4 in the Ishigami example. A variance that falls as mm grows is a sign of aliasing.
  • Wrong weight convention. To use a Gauss-Hermite table for the weight e−x2e^{-x^2} with the standard normal law, multiply its nodes by 2\sqrt{2} and its weights by 1/π1/\sqrt{\pi}. Without the change, the moments are wrong.
  • Non-smooth outputs. A jump or a kink in qq makes the coefficients decay slowly, and the expansion shows Gibbs oscillations. Split the input domain or use a sampling method.
  • Dependent inputs. The tensor rule and the product basis need independent inputs. Map dependent inputs to independent ones first, for example by a Rosenblatt or Nataf transform.

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.

non_intrusive_spectral_projection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/non-intrusive-spectral-projection/. The authors are listed in prov/K2M34Y.jsonl.
"""Non-intrusive spectral projection (pseudospectral projection) of a model output.

The input xi = (xi_1..xi_d) has independent components. Each component is
"uniform" (on [-1, 1], with the orthonormal Legendre basis sqrt(2n+1) P_n)
or "normal" (standard normal, with the orthonormal probabilists' Hermite basis
He_n / sqrt(n!)). The coefficient of Psi_a in the expansion of q(xi) is the
projection c_a = E[q Psi_a], and this code evaluates it with a tensor Gauss
rule of m points per input. The Gauss rules come from the Golub-Welsch
method: the nodes are the eigenvalues of the Jacobi matrix of the
recurrence, and the weights are the squared first components of its unit
eigenvectors. The eigenvalues are computed by the cyclic Jacobi method.
"""

import itertools
import math
from typing import Callable

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


def jacobi_eigen(a: list[list[float]], tol: float = 1e-15, max_sweeps: int = 100) -> tuple[list[float], list[list[float]]]:
    """Eigenvalues and unit eigenvectors (columns of V) of a symmetric matrix, by cyclic Jacobi rotations."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(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)
        if off <= tol * tol * max(1.0, sum(m[i][i] ** 2 for i in range(n))):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if m[p][q] == 0.0:
                    continue
                theta = (m[q][q] - m[p][p]) / (2.0 * m[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                s = t * c
                for k in range(n):
                    mkp, mkq = m[k][p], m[k][q]
                    m[k][p] = c * mkp - s * mkq
                    m[k][q] = s * mkp + c * mkq
                for k in range(n):
                    mpk, mqk = m[p][k], m[q][k]
                    m[p][k] = c * mpk - s * mqk
                    m[q][k] = s * mpk + c * mqk
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - s * vkq
                    v[k][q] = s * vkp + c * vkq
    return [m[i][i] for i in range(n)], v


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 gauss_rule(family: str, m: int) -> tuple[list[float], list[float]]:
    """The m point Gauss rule for the probability law of the family (weights sum to 1), sorted by node."""
    jac = [[0.0] * m for _ in range(m)]
    for k in range(1, m):
        jac[k - 1][k] = jac[k][k - 1] = recurrence_offdiag(family, k)
    vals, vecs = jacobi_eigen(jac)
    pairs = sorted((vals[j], vecs[0][j] ** 2) for j in range(m))
    return [x for x, _ in pairs], [w for _, w in pairs]


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 nisp(q: Model, families: list[str], p: int, m: int) -> tuple[list[tuple[int, ...]], list[float], int]:
    """Coefficients c_a = sum_j w_j q(x_j) Psi_a(x_j) on the tensor Gauss grid; returns (index, coeffs, runs)."""
    d = len(families)
    rules = [gauss_rule(fam, m) for fam in families]  # @line L1
    index = total_degree_set(d, p)  # @line L2
    coeffs = [0.0] * len(index)
    runs = 0
    for pick in itertools.product(range(m), repeat=d):  # @line L3
        x = [rules[k][0][j] for k, j in enumerate(pick)]
        w = math.prod(rules[k][1][j] for k, j in enumerate(pick))
        y = q(x)  # @line L4
        runs += 1
        tables = [basis_1d(families[k], x[k], p) for k in range(d)]
        for i, a in enumerate(index):  # @line L5
            coeffs[i] += w * y * math.prod(tables[k][a[k]] for k in range(d))
    return index, coeffs, runs  # @line L6


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 evaluate(index: list[tuple[int, ...]], coeffs: list[float], families: list[str], x: list[float]) -> float:
    """The expansion sum_a c_a Psi_a(x)."""
    p = max(sum(a) for a in index)
    tables = [basis_1d(families[k], x[k], p) for k in range(len(x))]
    return sum(c * math.prod(tables[k][a[k]] for k in range(len(x))) for a, c in zip(index, coeffs))


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_non_intrusive_spectral_projection.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/non-intrusive-spectral-projection/. The authors are listed in prov/K2M34Y.jsonl.
import math
import random

from non_intrusive_spectral_projection import (
    basis_1d,
    evaluate,
    gauss_rule,
    ishigami,
    jacobi_eigen,
    mean_variance,
    nisp,
    sobol_from_coefficients,
    total_degree_set,
)


def moment(family, k):
    if k % 2:
        return 0.0
    if family == "uniform":
        return 1.0 / (k + 1)
    return float(math.prod(range(k - 1, 0, -2)))


def test_jacobi_eigen_diagonalizes():
    rng = random.Random(3)
    n = 6
    a = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(i, n):
            a[i][j] = a[j][i] = rng.uniform(-1, 1)
    vals, v = jacobi_eigen(a)
    for k in range(n):
        av = [sum(a[i][j] * v[j][k] for j in range(n)) for i in range(n)]
        assert all(abs(av[i] - vals[k] * v[i][k]) < 1e-12 for i in range(n))


def test_gauss_rules_are_exact_to_degree_2m_minus_1():
    for family in ("uniform", "normal"):
        for m in range(1, 9):
            xs, ws = gauss_rule(family, m)
            assert abs(sum(ws) - 1.0) < 1e-13
            for k in range(2 * m):
                q = sum(w * x**k for x, w in zip(xs, ws))
                size = sum(w * abs(x) ** k for x, w in zip(xs, ws))
                assert abs(q - moment(family, k)) < 1e-12 * max(1.0, size)


def test_basis_is_orthonormal():
    for family in ("uniform", "normal"):
        xs, ws = gauss_rule(family, 10)
        for a in range(8):
            for b in range(8):
                g = sum(w * basis_1d(family, x, 8)[a] * basis_1d(family, x, 8)[b] for x, w in zip(xs, ws))
                assert abs(g - (1.0 if a == b else 0.0)) < 1e-11


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

    def q(x):
        return evaluate(index, true, fams, x)

    got_index, got, runs = nisp(q, fams, 4, 5)
    assert got_index == index
    assert runs == 25
    assert max(abs(a - b) for a, b in zip(got, true)) < 1e-12


def test_exponential_of_gaussian():
    _, c, _ = nisp(lambda x: math.exp(x[0]), ["normal"], 5, 12)
    exact = [math.exp(0.5) / math.sqrt(math.factorial(n)) for n in range(6)]
    assert max(abs(a - b) for a, b in zip(c, exact)) < 1e-6
    mean, var = mean_variance(c)
    assert abs(mean - math.exp(0.5)) < 1e-10
    captured = sum(math.e / math.factorial(n) for n in range(1, 6))
    assert abs(var - captured) < 1e-5


def test_ishigami_moments_and_sobol_indices():
    index, c, runs = nisp(ishigami, ["uniform"] * 3, 8, 9)
    assert runs == 729
    mean, var = mean_variance(c)
    assert abs(mean - 3.5) < 1e-6
    assert abs(var - 13.844588) < 0.06
    s, st = sobol_from_coefficients(index, c)
    assert abs(s[0] - 0.3139) < 0.002
    assert abs(s[1] - 0.4424) < 0.002
    assert abs(s[2]) < 1e-12
    assert abs(st[2] - 0.2437) < 0.002


def test_aliasing_with_too_few_points():
    # degree 4 expansion of x^6 with a 3 point rule: the projection is wrong
    _, c_bad, _ = nisp(lambda x: x[0] ** 6, ["uniform"], 4, 3)
    _, c_good, _ = nisp(lambda x: x[0] ** 6, ["uniform"], 4, 6)
    assert abs(c_good[0] - 1.0 / 7.0) < 1e-13
    assert max(abs(a - b) for a, b in zip(c_bad, c_good)) > 1e-2

History

Projection onto orthogonal polynomials by Gauss quadrature is classical numerical analysis; Golub and Welsch showed in 1969 how to compute the rules from the recurrence by an eigenvalue problem. In uncertainty quantification, the intrusive stochastic Galerkin method of Ghanem and Spanos came first. Reagan, Najm, Ghanem and Knio used the quadrature form in 2003 to propagate uncertain rate constants through reacting flow codes that could not be rewritten, and named it non-intrusive spectral projection. Sparse grid forms followed, and Constantine, Eldred and Phipps gave the sparse pseudospectral approximation method in 2012 to remove the aliasing of direct sparse quadrature.

References

  1. Matthew T. Reagan, Habib N. Najm, Roger G. Ghanem and Omar M. Knio, Uncertainty quantification in reacting-flow simulations through non-intrusive spectral projection, Combustion and Flame 132(3), 2003, 545-555, the non-intrusive spectral projection of a legacy code by quadrature over runs at the nodes
  2. Olivier P. Le Maitre and Omar M. Knio, Spectral Methods for Uncertainty Quantification, Springer, 2010, Chapter 3 (non-intrusive methods, including the projection by quadrature and its sparse grid forms)
  3. Gene H. Golub and John H. Welsch, Calculation of Gauss quadrature rules, Mathematics of Computation 23(106), 1969, 221-230, the Gauss nodes as eigenvalues of the Jacobi matrix and the weights from the first eigenvector components
  4. 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
  5. Paul G. Constantine, Michael S. Eldred and Eric T. Phipps, Sparse pseudospectral approximation method, Computer Methods in Applied Mechanics and Engineering 229-232, 2012, 1-12, the aliasing error of projection with Smolyak quadrature and the sparse pseudospectral method that avoids it

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