Algorithm Search⌘K

Algorithmadvanced

Stochastic collocation method

Also called sparse grid stochastic collocation, sparse grid collocation.

Solves the deterministic model at nodes of a sparse grid in parameter space and interpolates, a non-intrusive and spectrally accurate surrogate.

Time
O(N C + d T) worst
Space
O(N) extra
Where
C = the cost of one model run; L = the Smolyak level; N = the number of distinct sparse grid nodes, O(2^L L^(d-1)); T = the number of tensor grid points summed over all combination terms; d = the number of inputs
Properties
deterministicnot exactnot intrusive
Origin
Dongbin Xiu, Jan S. Hesthaven, Ivo Babuska, Fabio Nobile, Raul Tempone, Clayton G. Webster, 2005

The stochastic collocation method builds a polynomial surrogate of a model with random inputs by running the model at the nodes of a sparse grid in the input space and interpolating. Each run is an ordinary deterministic solve, so the method is non-intrusive, like spectral projection, but its output is an interpolant rather than a set of chaos coefficients. The grid is the Smolyak sparse grid built from nested Clenshaw-Curtis nodes, so the number of runs grows like 2LLd−12^L L^{d-1} with the level LL instead of (2L+1)d(2^L + 1)^d for a full tensor grid. The same grid gives a sparse quadrature for the mean and the variance. For outputs that are analytic in the inputs, the error falls faster than any power of the number of runs in low dimension, and still fast in moderate dimension.

In plain words

You have a slow model with a few uncertain inputs, and you want a fast formula that copies it. Pick a set of input points, run the model at each, and draw the smooth polynomial that passes exactly through all the results. A full grid of points along every input axis gets too large fast: 17 points per axis in 5 inputs is 1.4 million runs. A sparse grid keeps mainly the points near the axes and few of the points that change all inputs at the same time, because smooth models seldom need those. In 3 inputs, 177 points do the work of 4913. Averages come for free: each grid point has a weight, and the average of the model is the weighted sum of the runs.

The problem

The inputs ξ1,…,ξd\xi_1, \ldots, \xi_d are independent and uniform on [−1,1][-1, 1] (other laws follow by a change of variables). The model output is Q=q(ξ)Q = q(\xi), where qq is continuous and can only be evaluated. Find a surrogate ALqA_L q, a polynomial in ξ\xi that is cheap to evaluate, that equals qq at the nodes of a given grid, and that converges to qq uniformly as the level LL grows. Also find approximations of E[Q]\mathbb{E}[Q] and Var[Q]\mathrm{Var}[Q] from the same runs.

The algorithm

The one dimensional rule of level ll has m(0)=1m(0) = 1 node, the midpoint, and m(l)=2l+1m(l) = 2^l + 1 nodes xj=−cos⁡(πj/2l)x_j = -\cos(\pi j / 2^l) for l≥1l \ge 1. These levels are nested: every node of level l−1l - 1 is a node of level ll. Let UlU_l be Lagrange interpolation on the level ll nodes and QlQ_l the Clenshaw-Curtis rule on them.

  1. STOCHASTIC-COLLOCATION(q, d, L)
  2. 1T ← {(κ_l, l) : l ∈ ℕ^d, L-d+1 ≤ |l| ≤ L}, κ_l = (-1)^(L-|l|) · C(d-1, L-|l|)
  3. 2H ← union over (κ_l, l) ∈ T of the tensor grids X_{l_1} × ... × X_{l_d}
  4. 3for each node x ∈ H: y_x ← q(x) ▷ one run per distinct node
  5. 4A_L q(ξ) = Σ_{(κ_l, l) ∈ T} κ_l (U_{l_1} ⊗ ... ⊗ U_{l_d}) y (ξ)
  6. 5w_x ← Σ_{(κ_l, l) ∈ T, x in grid l} κ_l · Π_k (Clenshaw-Curtis weight of x_k at level l_k)
  7. 6return A_L q, mean Σ_x w_x y_x, variance Σ_x w_x y_x^2 - mean^2

Line L1 lists the terms of the Smolyak combination formula. Only the levels with ∣l∣|l| in the top dd layers appear, with integer coefficients that sum to 1. Line L2 collects the distinct nodes; because the levels are nested, the grids of different terms share many nodes, and the reference code stores each node once, keyed by its exact angle j/2lj / 2^l as a fraction. Line L3 is the only place that runs the model, and the runs are independent. Line L4 is the surrogate: each term is a tensor Lagrange interpolant that reads its values from the shared table. Line L5 gives each node its sparse quadrature weight; some of these weights are negative. Line L6 returns the moments of the quadrature. The variance uses the quadrature of q2q^2, which is less accurate than the surrogate itself, because q2q^2 is rougher than qq.

Example

For d=2d = 2 the grids have 1, 5, 13, 29 and 65 nodes at levels 0 to 4, and for d=3d = 3 they have 1, 7, 25, 69 and 177. 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 has mean 3.5 and variance 13.844588. The surrogate error is the root mean square error at 300 random points divided by the standard deviation. The numbers are deterministic, except the surrogate error, which is a measurement with seed 5.

LL runs full tensor grid error of mean variance error of variance surrogate error
2 25 125 1.14 5.22626 8.62 0.91
3 69 729 1.1×10−31.1 \times 10^{-3} 20.06157 6.22 0.24
4 177 4913 1.1×10−91.1 \times 10^{-9} 17.32732 3.48 5.4×10−25.4 \times 10^{-2}
5 441 35937 4×10−164 \times 10^{-16} 13.67727 0.167 1.2×10−41.2 \times 10^{-4}
6 1073 274625 4×10−164 \times 10^{-16} 13.84443 1.6×10−41.6 \times 10^{-4} 5.2×10−125.2 \times 10^{-12}
7 2561 2146689 0 13.84459 1.7×10−101.7 \times 10^{-10} 5.2×10−155.2 \times 10^{-15}

The mean is exact to rounding from level 5. The variance lags by about one level, because it integrates q2q^2. At level 6 the surrogate matches the function to 12 digits with 1073 runs, where the full tensor grid of the same one dimensional level has 274625 nodes. At low levels the variance can be far too large, since negative weights make ∑wxyx2−mean2\sum w_x y_x^2 - \text{mean}^2 an unreliable estimate.

Correctness

Write Δl=Ul−Ul−1\Delta_l = U_l - U_{l-1} with U−1=0U_{-1} = 0. Expanding the differences shows that the combination formula equals AL=∑∣l∣≤LΔl1⊗⋯⊗ΔldA_L = \sum_{|l| \le L} \Delta_{l_1} \otimes \cdots \otimes \Delta_{l_d}. Two theorems follow, both proved in the proof file. First, with nested nodes, ALqA_L q interpolates qq at every node of the sparse grid. Second, ALA_L reproduces every polynomial in ∑∣l∣≤LPm(l1)−1⊗⋯⊗Pm(ld)−1\sum_{|l| \le L} \mathbb{P}_{m(l_1) - 1} \otimes \cdots \otimes \mathbb{P}_{m(l_d) - 1}, which contains all polynomials of total degree at most LL, and many of higher degree. The same argument with the one dimensional rules, which are exact for degree 2l+12l + 1 at least, shows that the sparse quadrature of level LL is exact for all polynomials of total degree at most 2L+12L + 1; the tests check this and that a monomial of degree 2L+22L + 2 fails. Barthelmann, Novak and Ritter proved the exactness and interpolation statements and gave error bounds for Clenshaw-Curtis sparse grids. For outputs analytic in the inputs, Nobile, Tempone and Webster proved convergence rates in terms of the number of nodes.

Proof: The Smolyak collocation surrogate on nested nodes interpolates the runs, reproduces total degree L, and its quadrature is exact for total degree 2L + 1full

We assume exact arithmetic. For a level l≥0l \ge 0, let XlX_l be the one dimensional nodes (X0={0}X_0 = \{0\} and Xl={−cos⁡(πj/2l):0≤j≤2l}X_l = \{-\cos(\pi j / 2^l) : 0 \le j \le 2^l\}), m(l)=∣Xl∣m(l) = |X_l|, UlU_l the Lagrange interpolation operator on XlX_l, and QlQ_l the interpolatory quadrature on XlX_l for the uniform law on [−1,1][-1, 1], Qlf=E[Ulf]Q_l f = \mathbb{E}[U_l f]. Let Vl=Pm(l)−1V_l = \mathbb{P}_{m(l) - 1}, the polynomials of degree less than m(l)m(l). Put U−1=0U_{-1} = 0, Δl=Ul−Ul−1\Delta_l = U_l - U_{l-1}, and for a multi-index l∈Ndl \in \mathbb{N}^d write Ul=Ul1⊗⋯⊗UldU_l = U_{l_1} \otimes \cdots \otimes U_{l_d} and Δl=Δl1⊗⋯⊗Δld\Delta_l = \Delta_{l_1} \otimes \cdots \otimes \Delta_{l_d}, acting on functions of dd variables.

Lemma 1 (one dimensional facts). The sets XlX_l are nested, Xl−1⊆XlX_{l-1} \subseteq X_l, and so are the spaces, Vl−1⊆VlV_{l-1} \subseteq V_l. Ulf=fU_l f = f for f∈Vlf \in V_l. Qlf=E[f]Q_l f = \mathbb{E}[f] for every polynomial ff of degree at most e(l)e(l), where e(0)=1e(0) = 1 and e(l)=2l+1e(l) = 2^l + 1 for l≥1l \ge 1; in particular e(l)≥2l+1e(l) \ge 2l + 1 and ee is increasing.

Proof. The node −cos⁡(πj/2l−1)-\cos(\pi j / 2^{l-1}) equals −cos⁡(π(2j)/2l)-\cos(\pi (2j) / 2^l), and 0=−cos⁡(π⋅2l−1/2l)0 = -\cos(\pi \cdot 2^{l-1} / 2^l), so Xl−1⊆XlX_{l-1} \subseteq X_l; since mm increases, so do the VlV_l. Interpolation on m(l)m(l) distinct nodes reproduces polynomials of degree less than m(l)m(l), by uniqueness of the interpolant. So QlQ_l is exact for degree m(l)−1m(l) - 1. The node set is symmetric about 0, so the weights are symmetric, and the rule gives 0 for every odd monomial, which is the exact mean; hence QlQ_l is exact for degree m(l)m(l) when m(l)−1m(l) - 1 is even, which holds for all ll. That is e(0)=1e(0) = 1 and e(l)=2l+1e(l) = 2^l + 1. Finally 2l≥2l2^l \ge 2l for all l≥1l \ge 1, by induction. □\square

Lemma 2 (the combination formula is the difference form). For L≥0L \ge 0,

∑∣l∣≤LΔl=∑L−d+1≤∣j∣≤L(−1)L−∣j∣(d−1L−∣j∣) Uj,\sum_{|l| \le L} \Delta_l = \sum_{L - d + 1 \le |j| \le L} (-1)^{L - |j|} \binom{d-1}{L - |j|}\, U_j,

where the sums run over l,j∈Ndl, j \in \mathbb{N}^d. The same holds with QQ in place of UU.

Proof. Expand each Δlk=Ulk−Ulk−1\Delta_{l_k} = U_{l_k} - U_{l_k - 1}. The product Δl\Delta_l is ∑e∈{0,1}d(−1)∣e∣Ul−e\sum_{e \in \{0,1\}^d} (-1)^{|e|} U_{l - e}, where a term with some lk−ek=−1l_k - e_k = -1 vanishes. So the coefficient of UjU_j on the left is ∑(−1)∣e∣\sum (-1)^{|e|} over the e∈{0,1}de \in \{0, 1\}^d with ∣j+e∣≤L|j + e| \le L, that is ∑t=0min⁡(d,s)(−1)t(dt)\sum_{t=0}^{\min(d, s)} (-1)^t \binom{d}{t} with s=L−∣j∣≥0s = L - |j| \ge 0. If s≥ds \ge d this is (1−1)d=0(1 - 1)^d = 0. If 0≤s≤d−10 \le s \le d - 1, the partial alternating sum is ∑t=0s(−1)t(dt)=(−1)s(d−1s)\sum_{t=0}^{s} (-1)^t \binom{d}{t} = (-1)^s \binom{d-1}{s}, by induction on ss with Pascal's rule (dt)=(d−1t)+(d−1t−1)\binom{d}{t} = \binom{d-1}{t} + \binom{d-1}{t-1}, because the sum telescopes. For ∣j∣>L|j| > L the coefficient is 0. The quadrature case is the same algebra. □\square

So line L4 computes ALq=∑∣l∣≤LΔlqA_L q = \sum_{|l| \le L} \Delta_l q, and line L6 computes the mean ∑∣l∣≤LΔlQq\sum_{|l| \le L} \Delta^Q_l q with ΔlQ=⨂k(Qlk−Qlk−1)\Delta^Q_l = \bigotimes_k (Q_{l_k} - Q_{l_k - 1}), because ∑xwxyx\sum_x w_x y_x regroups the same sum by node.

Lemma 3 (polynomial exactness). If f=f1⊗⋯⊗fdf = f_1 \otimes \cdots \otimes f_d with fk∈Vβkf_k \in V_{\beta_k} and ∣β∣≤L|\beta| \le L, then ALf=fA_L f = f. By linearity, ALA_L reproduces every function in ∑∣β∣≤LVβ1⊗⋯⊗Vβd\sum_{|\beta| \le L} V_{\beta_1} \otimes \cdots \otimes V_{\beta_d}, which contains all polynomials of total degree at most LL.

Proof. By Lemma 1, Ulfk=fkU_l f_k = f_k for l≥βkl \ge \beta_k, so Δlfk=0\Delta_l f_k = 0 for l>βkl > \beta_k. Hence Δlf=∏kΔlkfk\Delta_l f = \prod_k \Delta_{l_k} f_k is 0 unless l≤βl \le \beta in every entry, and all such ll satisfy ∣l∣≤∣β∣≤L|l| \le |\beta| \le L. Then ALf=∑l≤β⨂kΔlkfk=⨂k∑lk=0βkΔlkfk=⨂kUβkfk=fA_L f = \sum_{l \le \beta} \bigotimes_k \Delta_{l_k} f_k = \bigotimes_k \sum_{l_k = 0}^{\beta_k} \Delta_{l_k} f_k = \bigotimes_k U_{\beta_k} f_k = f, by the telescoping sum. A monomial ξβ\xi^\beta of total degree ∣β∣≤L|\beta| \le L has ξkβk∈Vβk\xi_k^{\beta_k} \in V_{\beta_k}, because m(l)−1≥lm(l) - 1 \ge l for every ll. □\square

Lemma 4 (interpolation at the nodes). For every node xx of the sparse grid HH, ALq(x)=q(x)A_L q(x) = q(x).

Proof. The node xx lies in the tensor grid of some l∘l^\circ with ∣l∘∣≤L|l^\circ| \le L; put βk\beta_k as the smallest level with xk∈Xβkx_k \in X_{\beta_k}, so β≤l∘\beta \le l^\circ and ∣β∣≤L|\beta| \le L. By nestedness, xk∈Xlx_k \in X_l for all l≥βkl \ge \beta_k, so (Ulg)(xk)=g(xk)(U_l g)(x_k) = g(x_k) for l≥βkl \ge \beta_k, and (Δlg)(xk)=0(\Delta_l g)(x_k) = 0 for l>βkl > \beta_k. A tensor product operator applied to qq and evaluated at xx depends only on the one dimensional values, so (Δlq)(x)=0(\Delta_l q)(x) = 0 unless l≤βl \le \beta. As in Lemma 3, ALq(x)=∑l≤β(Δlq)(x)=(Uβq)(x)=q(x)A_L q(x) = \sum_{l \le \beta} (\Delta_l q)(x) = (U_\beta q)(x) = q(x), the last step because xx is a node of the tensor grid of β\beta. □\square

Lemma 5 (quadrature exactness). The mean of line L6 is exact for every polynomial of total degree at most 2L+12L + 1.

Proof. Take a monomial ξβ\xi^\beta with ∣β∣≤2L+1|\beta| \le 2L + 1, and let γk\gamma_k be the smallest level with e(γk)≥βke(\gamma_k) \ge \beta_k. Since e(l)≥2l+1e(l) \ge 2l + 1, γk≤⌈(βk−1)/2⌉≤βk/2\gamma_k \le \lceil (\beta_k - 1)/2 \rceil \le \beta_k / 2 for βk≥1\beta_k \ge 1, and γk=0\gamma_k = 0 for βk=0\beta_k = 0. So ∣γ∣≤∣β∣/2≤L+1/2|\gamma| \le |\beta| / 2 \le L + 1/2, and as ∣γ∣|\gamma| is an integer, ∣γ∣≤L|\gamma| \le L. Since ee is increasing, Qlξkβk=E[ξkβk]Q_l \xi_k^{\beta_k} = \mathbb{E}[\xi_k^{\beta_k}] for l≥γkl \ge \gamma_k, and the differences vanish for l>γkl > \gamma_k. The argument of Lemma 3 with QQ in place of UU gives the value ∏kQγkξkβk=∏kE[ξkβk]=E[ξβ]\prod_k Q_{\gamma_k} \xi_k^{\beta_k} = \prod_k \mathbb{E}[\xi_k^{\beta_k}] = \mathbb{E}[\xi^\beta], by independence. □\square

Theorem. STOCHASTIC-COLLOCATION stops after exactly ∣H∣|H| model runs. Its surrogate ALqA_L q equals qq at every node of HH and equals qq everywhere when qq is a polynomial of total degree at most LL. Its mean is exact when qq is a polynomial of total degree at most 2L+12L + 1, and its variance is exact when qq has total degree at most LL.

Proof. Termination: line L1 lists finitely many multi-indices, each tensor grid is finite, and line L3 runs the model once per distinct node of the finite set HH. The surrogate statements are Lemmas 2, 3 and 4. The mean is Lemma 5. If qq has total degree at most LL, then q2q^2 has total degree at most 2L≤2L+12L \le 2L + 1, so both QL[q]Q_L[q] and QL[q2]Q_L[q^2] are exact by Lemma 5, and so is their combination. ■\blacksquare

The theorem says nothing about the rate for a general smooth qq. The bounds of Barthelmann, Novak and Ritter and of Nobile, Tempone and Webster, which the page quotes, need regularity of qq and the growth of the Lebesgue constants of the Clenshaw-Curtis nodes, and are not proved here.

Complexity

In the real RAM model, the number of distinct nodes is N=O(2LLd−1)N = O(2^L L^{d-1}) for fixed dd, and line L3 costs NCN C. Lines L4 to L6 work term by term; let TT be the number of tensor grid points summed over all terms, counted with repetition. The weights of line L5 cost O(dT)O(d T), and the moments O(N)O(N). One evaluation of the surrogate costs O(dT)O(d T) plus the one dimensional Lagrange values. The total for building and moments is O(NC+dT)O(N C + d T), and the table of runs takes O(N)O(N) space. For d=3d = 3 and L=6L = 6 the reference code needs about a second in Python, mostly to evaluate the surrogate at the test points.

Properties

  • Non-intrusive. One deterministic run per node.
  • Interpolatory (theorem, nested nodes). The surrogate equals the model at every node.
  • Polynomial exactness (theorem). Total degree LL for interpolation and 2L+12L + 1 for the quadrature.
  • Hierarchical. With nested nodes, raising the level reuses all previous runs.
  • Deterministic. No sampling error; the error is interpolation error.
  • Negative weights. The sparse quadrature has negative weights: for d=2d = 2 and d=3d = 3 at levels 2 to 4, between 5 and 69 nodes have a negative weight (measured with the reference code). So the variance estimate can be inaccurate or even negative.
  • Moderate dimension. The node count still grows with dd; sparse grids push the practical limit to roughly ten to twenty inputs for smooth outputs.

Variants and improvements

  • Tensor Gauss collocation. Babuska, Nobile and Tempone used full tensor grids of Gauss points, which interpolate on mdm^d nodes and give the moments by Gauss quadrature; good for very few inputs.
  • Anisotropic grids. Weight the levels by input, ∑kgklk≤L\sum_k g_k l_k \le L, to spend more nodes on the important inputs.
  • Adaptive sparse grids. Add the difference terms Δl\Delta_l with the largest hierarchical surpluses one at a time, as in dimension adaptive quadrature.
  • Local bases. Piecewise linear hierarchical bases on sparse grids handle outputs with kinks or jumps, where global polynomials oscillate.
  • Conversion to chaos. The surrogate can be expanded in a chaos basis to get the Sobol indices, as the sparse pseudospectral method does with the same runs.
  • Leja and Gauss-Patterson nodes. Other nested families with slower growth per level, for a finer choice of grid size.

When to use it

Use stochastic collocation when the model is a black box, the inputs are few to moderate in number, and the output is smooth in the inputs, and you want a surrogate that you can evaluate anywhere. It shares the grid with sparse grid quadrature, so it gives the mean at no extra cost. Prefer spectral projection or regression when you need chaos coefficients and Sobol indices directly, the stochastic Galerkin method when you can change the solver and want one coupled solve, and Monte Carlo integration when the output is not smooth or the dimension is high.

Pitfalls

  • Non-smooth outputs. A jump or a kink in qq causes Gibbs oscillations of the global interpolant and slow convergence. Use a local basis or an adaptive grid.
  • Variance from low levels. QL[q2]−QL[q]2Q_L[q^2] - Q_L[q]^2 can be badly wrong, as at L=2L = 2 to 4 in the example. Check the variance at two consecutive levels, or integrate the square of the surrogate on a finer rule.
  • Non-nested nodes. With non-nested nodes, such as Gauss points, the combination formula is not interpolatory and the grids of different terms share few nodes, so the run count rises.
  • Equally spaced nodes. Equally spaced nodes give a fast growing Lebesgue constant and the Runge phenomenon. Use Clenshaw-Curtis or Leja points.
  • Wrong input map. For non-uniform inputs, map them to [−1,1][-1, 1] first, or use nodes and weights for their own law; mixing the two gives wrong moments.

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.

stochastic_collocation_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stochastic-collocation-method/. The authors are listed in prov/S37CZP.jsonl.
"""Stochastic collocation on a Smolyak sparse grid of nested Clenshaw-Curtis nodes.

The inputs xi_1..xi_d are independent and uniform on [-1, 1]. The 1D rule of
level l has m(0) = 1 node (the midpoint) and m(l) = 2^l + 1 nodes
x_j = -cos(pi j / 2^l) for l >= 1; the levels are nested. The Smolyak
surrogate of level L is the combination

    A_L = sum over l in N^d with L - d + 1 <= |l| <= L of
          (-1)^(L - |l|) binom(d - 1, L - |l|) U_(l_1) x ... x U_(l_d),

where U_l is Lagrange interpolation on the level l nodes. The model runs
once at each distinct node of the union of the tensor grids. The mean and
variance come from the matching sparse quadrature: E[q] ~ Q_L[q] and
Var[q] ~ Q_L[q^2] - Q_L[q]^2.
"""

import itertools
import math
from fractions import Fraction
from typing import Callable

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


def level_keys(level: int) -> list[Fraction]:
    """Nodes of a level as exact fractions t of pi, with node -cos(pi t); nested across levels."""
    if level == 0:
        return [Fraction(1, 2)]
    n = 2**level
    return [Fraction(j, n) for j in range(n + 1)]


def node(key: Fraction) -> float:
    """The node -cos(pi t) for the key t, with exact 0 and +-1."""
    if key == Fraction(1, 2):
        return 0.0
    if key == 0:
        return -1.0
    if key == 1:
        return 1.0
    return -math.cos(math.pi * key)


def cc_weights(level: int) -> list[float]:
    """Clenshaw-Curtis weights of a level for the uniform probability law on [-1, 1] (they sum to 1)."""
    if level == 0:
        return [1.0]
    n = 2**level
    w = []
    for j in range(n + 1):
        theta = math.pi * j / n
        s = 0.0
        for k in range(1, n // 2 + 1):
            b = 1.0 if 2 * k == n else 2.0
            s += b * math.cos(2 * k * theta) / (4 * k * k - 1)
        c = 1.0 if j in (0, n) else 2.0
        w.append(0.5 * c / n * (1.0 - s))
    return w


def lagrange(xs: list[float], x: float) -> list[float]:
    """Values at x of the Lagrange basis polynomials on the nodes xs."""
    out = []
    for i, xi in enumerate(xs):
        v = 1.0
        for j, xj in enumerate(xs):
            if j != i:
                v *= (x - xj) / (xi - xj)
        out.append(v)
    return out


def smolyak_terms(d: int, level: int) -> list[tuple[int, tuple[int, ...]]]:
    """The pairs (coefficient, level multi-index) of the combination formula."""
    terms = []
    for lv in itertools.product(range(level + 1), repeat=d):
        s = sum(lv)
        if level - d + 1 <= s <= level:
            coef = (-1) ** (level - s) * math.comb(d - 1, level - s)
            terms.append((coef, lv))
    return terms


def collocate(q: Model, d: int, level: int) -> dict:
    """Run the model on the sparse grid and return the surrogate data."""
    terms = smolyak_terms(d, level)  # @line L1
    grid = {}
    for _, lv in terms:  # @line L2
        for keys in itertools.product(*(level_keys(v) for v in lv)):
            grid.setdefault(keys, None)
    for keys in grid:  # @line L3
        grid[keys] = q([node(k) for k in keys])
    return {"d": d, "level": level, "terms": terms, "values": grid}


def evaluate(sc: dict, x: list[float]) -> float:
    """The Smolyak surrogate A_L at the point x."""
    total = 0.0
    for coef, lv in sc["terms"]:  # @line L4
        keys = [level_keys(v) for v in lv]
        basis = [lagrange([node(k) for k in ks], xk) for ks, xk in zip(keys, x)]
        for pick in itertools.product(*(range(len(ks)) for ks in keys)):
            y = sc["values"][tuple(keys[k][j] for k, j in enumerate(pick))]
            total += coef * y * math.prod(basis[k][j] for k, j in enumerate(pick))
    return total


def quadrature_weights(sc: dict) -> dict:
    """The sparse quadrature weight of each distinct node; the surrogate's mean is sum w y."""
    weights = {}
    for coef, lv in sc["terms"]:
        keys = [level_keys(v) for v in lv]
        ws = [cc_weights(v) for v in lv]
        for pick in itertools.product(*(range(len(ks)) for ks in keys)):
            key = tuple(keys[k][j] for k, j in enumerate(pick))
            weights[key] = weights.get(key, 0.0) + coef * math.prod(ws[k][j] for k, j in enumerate(pick))
    return weights


def moments(sc: dict) -> tuple[float, float]:
    """Mean Q_L[q] and variance Q_L[q^2] - Q_L[q]^2 from the sparse quadrature."""
    w = quadrature_weights(sc)  # @line L5
    mean = sum(w[k] * y for k, y in sc["values"].items())
    second = sum(w[k] * y * y for k, y in sc["values"].items())
    return mean, second - mean * mean  # @line L6


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_stochastic_collocation_method.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stochastic-collocation-method/. The authors are listed in prov/S37CZP.jsonl.
import itertools
import math
import random

from stochastic_collocation_method import (
    cc_weights,
    collocate,
    evaluate,
    ishigami,
    level_keys,
    moments,
    node,
    quadrature_weights,
    smolyak_terms,
)


def mono_mean(beta):
    return math.prod(0.0 if b % 2 else 1.0 / (b + 1) for b in beta)


def test_node_counts():
    assert [len(collocate(lambda x: 0.0, 2, L)["values"]) for L in range(5)] == [1, 5, 13, 29, 65]
    assert [len(collocate(lambda x: 0.0, 3, L)["values"]) for L in range(5)] == [1, 7, 25, 69, 177]


def test_levels_are_nested():
    for lv in range(1, 6):
        assert set(level_keys(lv - 1)) <= set(level_keys(lv))


def test_clenshaw_curtis_weights():
    for lv in range(6):
        xs = [node(k) for k in level_keys(lv)]
        w = cc_weights(lv)
        assert abs(sum(w) - 1.0) < 1e-14
        assert all(v > 0 for v in w)
        exact_degree = 1 if lv == 0 else 2**lv + 1
        for k in range(exact_degree + 1):
            got = sum(wi * xi**k for wi, xi in zip(w, xs))
            assert abs(got - mono_mean([k])) < 1e-13


def test_combination_coefficients_sum_to_one():
    for d in (1, 2, 3, 4):
        for L in range(5):
            assert sum(c for c, _ in smolyak_terms(d, L)) == 1


def test_surrogate_interpolates_at_the_nodes():
    sc = collocate(lambda x: math.exp(x[0] - 0.5 * x[1] + 0.3 * x[2]), 3, 3)
    for keys, y in sc["values"].items():
        assert abs(evaluate(sc, [node(k) for k in keys]) - y) < 1e-12


def test_reproduces_polynomials_of_total_degree_at_most_level():
    rng = random.Random(4)
    d, L = 3, 3
    monos = [b for b in itertools.product(range(L + 1), repeat=d) if sum(b) <= L]
    coef = {b: rng.uniform(-1, 1) for b in monos}

    def poly(x):
        return sum(c * math.prod(xk**bk for xk, bk in zip(x, b)) for b, c in coef.items())

    sc = collocate(poly, d, L)
    for _ in range(20):
        x = [rng.uniform(-1, 1) for _ in range(d)]
        assert abs(evaluate(sc, x) - poly(x)) < 1e-11


def test_quadrature_is_exact_through_total_degree_2l_plus_1():
    d, L = 2, 3
    w = quadrature_weights(collocate(lambda x: 0.0, d, L))
    for beta in itertools.product(range(2 * L + 2), repeat=d):
        if sum(beta) <= 2 * L + 1:
            got = sum(wk * math.prod(node(k) ** b for k, b in zip(key, beta)) for key, wk in w.items())
            assert abs(got - mono_mean(beta)) < 1e-12
    beta = (2, 2 * L)
    got = sum(wk * math.prod(node(k) ** b for k, b in zip(key, beta)) for key, wk in w.items())
    assert abs(got - mono_mean(beta)) > 1e-6


def test_ishigami_moments():
    sc = collocate(ishigami, 3, 6)
    assert len(sc["values"]) == 1073
    mean, var = moments(sc)
    assert abs(mean - 3.5) < 1e-12
    assert abs(var - 13.844588) < 1e-3

History

Smolyak introduced the combination of tensor products of one dimensional rules in 1963, and sparse grids were developed for quadrature and interpolation in the 1990s, with the analysis of Clenshaw-Curtis sparse grid interpolation by Barthelmann, Novak and Ritter in 2000. Xiu and Hesthaven proposed collocation at the nodes of tensor and sparse grids as a high order non-intrusive alternative to the stochastic Galerkin method in 2005. Babuska, Nobile and Tempone analyzed tensor Gauss collocation for elliptic problems with random coefficients in 2007, and Nobile, Tempone and Webster gave the error analysis of the sparse grid form in 2008, followed by anisotropic and adaptive versions.

References

  1. Dongbin Xiu and Jan S. Hesthaven, High-order collocation methods for differential equations with random inputs, SIAM Journal on Scientific Computing 27(3), 2005, 1118-1139, the collocation of a model with random inputs at the nodes of tensor and Smolyak sparse grids, with the moments from the matching quadrature
  2. Ivo Babuska, Fabio Nobile and Raul Tempone, A stochastic collocation method for elliptic partial differential equations with random input data, SIAM Journal on Numerical Analysis 45(3), 2007, 1005-1034, the tensor Gauss collocation method and its exponential convergence for solutions analytic in the parameters
  3. Fabio Nobile, Raul Tempone and Clayton G. Webster, A sparse grid stochastic collocation method for partial differential equations with random input data, SIAM Journal on Numerical Analysis 46(5), 2008, 2309-2345, the error analysis of Smolyak collocation on Clenshaw-Curtis and Gauss nodes, with the rate in terms of the number of nodes
  4. Volker Barthelmann, Erich Novak and Klaus Ritter, High dimensional polynomial interpolation on sparse grids, Advances in Computational Mathematics 12(4), 2000, 273-288, the exactness of the Smolyak operator on sums of tensor polynomial spaces, its interpolation property for nested nodes, and the error bounds for Clenshaw-Curtis sparse grids

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