Module contents
Lesson 16 of 27Advanced 115 min

Parametric uncertainty propagation: polynomial chaos and stochastic collocation

Propagate uncertain inputs using Karhunen-Loève fields, polynomial chaos, stochastic Galerkin and Smolyak sparse-grid collocation.

After this lesson you can

  • Represent a Gaussian random field with a truncated Karhunen-Loève expansion and choose the number of modes.
  • Construct polynomial chaos using the orthogonal family appropriate to each input distribution.
  • Calculate coefficients by quadrature projection, regression and stochastic Galerkin and compare cost and intrusiveness.
  • Construct Smolyak sparse grids and explain how they mitigate dimensionality.
  • Obtain output mean, variance and distribution from the expansion and validate against Monte Carlo.

Before you start

Propagating uncertainty

Unknown material conductivity makes a chip’s predicted temperature uncertain. Uncertainty propagation starts from an input law and model to estimate an output distribution: mean, spread, quantiles or probability of exceeding a threshold. The result depends on the chosen law and model; it does not itself validate the physics. Monte Carlo requires no solver modification, but each sample may require a PDE solve.

Fields via Karhunen-Loève

For a centered field with symmetric positive integrable covariance, the Karhunen-Loève expansion uses orthonormal eigenfunctions of its integral operator:

∫DK(x,y)ϕj(y) dy=λjϕj(x),a(x,ω)=aˉ(x)+∑j≥1λj ξj(ω)ϕj(x).\int_D K(x,y)\phi_j(y)\,\mathrm dy=\lambda_j\phi_j(x),\qquad a(x,\omega)=\bar a(x)+\sum_{j\ge1}\sqrt{\lambda_j}\,\xi_j(\omega)\phi_j(x).

Coefficients have zero mean and identity covariance; for a Gaussian field they are independent normals. Retaining mm modes preserves fraction ∑j≤mλj/∑jλj\sum_{j\le m}\lambda_j/\sum_j\lambda_j of integrated variance, not necessarily output variance. Mercer provides a pointwise representation under additional assumptions, such as kernel continuity on a compact domain. For a lognormal field expand the Gaussian logarithm and then exponentiate.

Nyström with positive weights wiw_i diagonalizes symmetric matrix wiK(xi,xj)wj\sqrt{w_i}K(x_i,x_j)\sqrt{w_j}. If vjv_j is a normalized Euclidean eigenvector, ϕj(xi)=vij/wi\phi_j(x_i)=v_{ij}/\sqrt{w_i} is orthonormal under that quadrature. The figure uses the trapezoidal rule: short correlation usually spreads variance across more modes.

Integrated squared truncation error is ∑j>mλj\sum_{j>m}\lambda_j. To choose mm one may set an integrated variance fraction, but should then recompute the quantity of interest with more modes: an output sensitive to local detail can change even when retained fraction is high. Eigenfunction signs are arbitrary; simultaneously changing the sign of a mode and its coefficient leaves the represented field unchanged.

InteractiveBuild a field mode by mode
  • Truncated Gaussian field

The fraction is the sum of retained eigenvalues divided by the kernel integrated trace, equal to one. Changing length also changes modes; the same normals fix a reproducible realization.

Kernel
Length
4
Integrated variance captured78.7 %
Weighted modes and one fixed realization calculated from the stated kernel.

Polynomial bases

A polynomial chaos expansion approximates a square-integrable output by P(ξ)≈∑ν∈Acνψν(ξ)P(\xi)\approx\sum_{\nu\in\mathcal A} c_\nu\psi_\nu(\xi), with ψν\psi_\nu orthonormal for the input law and ψ0=1\psi_0=1. Then EPPCE=c0\mathbb EP_{\rm PCE}=c_0 and Var⁡(PPCE)=∑ν≠0cν2\operatorname{Var}(P_{\rm PCE})=\sum_{\nu\ne0}c_\nu^2. These are surrogate moments and exclude truncation or fitting error.

In Wiener-Askey, a uniform law uses Legendre, normal uses probabilists’ Hermite, gamma uses Laguerre and beta uses Jacobi, with suitable parameters and normalization. For independent variables, multiply univariate bases. Dependence requires an adapted basis or valid joint transformation; its effect on smoothness matters. A basis of total degree at most pp in dd variables has (d+pp)\binom{d+p}{p} terms. Xiu and Karniadakis develop this correspondence.

Nonintrusive construction uses the solver as a black box. Projection approximates cν=E[Pψν]c_\nu=\mathbb E[P\psi_\nu] by quadrature; regression minimizes ∑i∣P(ξi)−∑νcνψν(ξi)∣2\sum_i|P(\xi_i)-\sum_\nu c_\nu\psi_\nu(\xi_i)|^2. At least as many data as coefficients are needed for full rank. Twofold oversampling is a practical rule, not a guarantee of good conditioning. Evaluate error on independent data.

For example, if XX is uniform on [−1,1][-1,1], the first two orthonormal functions are 11 and 3X\sqrt3X. Response P=2+3XP=2+3X has coefficients c0=2c_0=2 and c1=3c_1=\sqrt3: its mean is 2 and variance 3. This identification depends on normalization; with unnormalized Legendre polynomials each squared coefficient must be multiplied by its corresponding norm.

InteractivePolynomial chaos learns
  • Response
  • PCE

Below: histogram densities over [0,5] for the same independent sample. Omitted tails are not renormalized.

Distribution
Fit
2
Independent validation RMSE0.00163
Outside histogram, true / PCE0.00 % / 0.00 %
Projection or regression of a known response, with independent validation and empirical densities.

Stochastic Galerkin inserts the expansion into the equations and projects residual onto each mode. If A(ξ)u(ξ)=f(ξ)A(\xi)u(\xi)=f(\xi), blocks are Aμν=E[ψμA(ξ)ψν]A_{\mu\nu}=\mathbb E[\psi_\mu A(\xi)\psi_\nu] and fμ=E[ψμf]f_\mu=\mathbb E[\psi_\mu f]. It solves coupled coefficients and requires operator access; nonlinearity and high dimension can increase cost. Collocation or regression can use a black box.

Collocation and Smolyak

Stochastic collocation solves the model at nodes and combines results by interpolation or quadrature. A product of nn nodes per dimension has ndn^d points. A Smolyak sparse grid combines increments Δi=Qi−Qi−1\Delta_i=Q_i-Q_{i-1}, with Q0=0Q_0=0:

Ad,q=∑ij≥1∑j(ij−1)≤qΔi1⊗⋯⊗Δid.A_{d,q}=\sum_{\substack{i_j\ge1\\\sum_j(i_j-1)\le q}} \Delta_{i_1}\otimes\cdots\otimes\Delta_{i_d}.

Nested Clenshaw-Curtis reuses repeated nodes. At fixed level the count can grow much less than the product; increasing dimension and level remains difficult. Dimension adaptivity prioritizes relevant increments but requires an error criterion and does not guarantee detection of omitted interactions.

For example, in two dimensions and level q=1q=1 the combination is Q2⊗Q1+Q1⊗Q2−Q1⊗Q1Q_2\otimes Q_1+Q_1\otimes Q_2-Q_1\otimes Q_1. With one central node in Q1Q_1 and three nodes in Q2Q_2, five distinct points are evaluated instead of the nine in product Q2⊗Q2Q_2\otimes Q_2. The negative sign avoids double-counting the central contribution: retaining nodes without their weights does not define correct quadrature.

InteractiveFrom tensor grid to sparse grid
  • Smolyak

A fixed oblique projection is used in 3D, so some points may overlap. The count covers the full set; fixed level does not remove the difficulty of increasing level and dimension together.

View
Grid
2
10
Nodes drawn13
Sparse at d=10221
Tensor at d=109,765,625
Nested Clenshaw-Curtis nodes; the 3D view is an oblique projection.

The lab’s Gaussian rules are not nested, although some nodes coincide; the combination can have negative weights. A failure indicator is discontinuous: quadrature of its probability can be unstable and even lie outside [0,1][0,1]. Compare with sampling and refinement.

Lab: diffusion with uncertain conductivity

Solve −(ku′)′=1-(ku')'=1 on [0,1][0,1], u(0)=u(1)=0u(0)=u(1)=0, and observe u(1/2)u(1/2). The logarithm of kk is 0.5 times an exponential field of length 0.25 truncated to two KL modes. This is a synthetic PDE, not a calibrated chip; the conservative solver extends lesson 15’s. Modes are fixed on 65 points and interpolated to faces of each grid, sharing the truncated field.

The two calculated eigenvalues sum to approximately 0.6043 of unit integrated variance. About 39.6% of Gaussian-field variance is therefore omitted: the following statistics describe this truncated model, not complete uncertainty of an infinitely many-mode field. Increasing mm is part of convergence study and makes parameter exploration more expensive.

Run the library and then the cells in order. Degree-three Hermite PCE has ten terms and uses 100 solutions for regression and 1000 independent validation points. Projection uses 25 product Gaussian nodes and Smolyak combines non-nested Gaussian rules at level four. Physical nodes are counted, excluding time and fitting cost. MC, projection, PCE and Smolyak use physical level four.

[ ]KL, PCE and Smolyak from scratchBrowser
"""Propagación de incertidumbre para difusión 1D."""
import numpy as np
from math import factorial,comb
from scipy.special import roots_hermitenorm

def kl_expansion(kernel,x_grid,n_modes):
    x=np.asarray(x_grid,dtype=float)
    if x.ndim!=1 or len(x)<2 or np.any(np.diff(x)<=0) or not 1<=n_modes<=len(x):raise ValueError('malla o número de modos inválidos')
    w=np.empty_like(x);w[0]=(x[1]-x[0])/2;w[-1]=(x[-1]-x[-2])/2
    w[1:-1]=(x[2:]-x[:-2])/2
    K=np.asarray(kernel(x[:,None],x[None,:]),dtype=float)
    if K.shape!=(len(x),len(x)) or not np.allclose(K,K.T):raise ValueError('núcleo no simétrico')
    sw=np.sqrt(w);vals,vec=np.linalg.eigh(sw[:,None]*K*sw[None,:]);idx=np.argsort(vals)[::-1][:n_modes]
    if np.any(vals[idx]<-1e-10):raise ValueError('núcleo no positivo')
    return np.maximum(vals[idx],0),vec[:,idx]/sw[:,None]

def diffusion(z,level,grid,lam,phi):
    """Campo KL truncado fijo entre mallas; salida u(1/2), diferencias conservativas."""
    z=np.asarray(z,dtype=float);n=2**(level+2);h=1/n;x=(np.arange(n)+.5)*h
    modes=np.stack([np.interp(x,grid,phi[:,j]) for j in range(len(lam))],axis=1)
    k=np.exp(.5*(z@(modes*np.sqrt(lam)[None,:]).T))
    diag=(k[:,:-1]+k[:,1:])/h**2;off=-k[:,1:-1]/h**2;rhs=np.ones_like(diag)
    for j in range(1,n-1):
        a=off[:,j-1]/diag[:,j-1];diag[:,j]-=a*off[:,j-1];rhs[:,j]-=a*rhs[:,j-1]
    u=np.zeros_like(rhs);u[:,-1]=rhs[:,-1]/diag[:,-1]
    for j in range(n-3,-1,-1):u[:,j]=(rhs[:,j]-off[:,j]*u[:,j+1])/diag[:,j]
    return u[:,n//2-1]

def multi_indices(d,p):
    import itertools
    return [a for a in itertools.product(range(p+1),repeat=d) if sum(a)<=p]

def hermite_basis(z,p):
    """Hermite probabilista ortonormal para normales estándar independientes."""
    z=np.asarray(z,dtype=float);d=z.shape[1];one=[np.ones_like(z)]
    if p>=1:one.append(z)
    for n in range(1,p):one.append((z*one[n]-np.sqrt(n)*one[n-1])/np.sqrt(n+1))
    indices=multi_indices(d,p)
    return np.column_stack([np.prod([one[a[j]][:,j] for j in range(d)],axis=0) for a in indices]),indices

def gauss_normal(n):
    x,w=roots_hermitenorm(n)
    return x,w/np.sqrt(2*np.pi)

def smolyak_normal_2d(level):
    """ΔQ_i⊗ΔQ_j, i+j≤level+2; reglas Gaussianas non-anidadas."""
    def delta(i):
        x,w=gauss_normal(i)
        if i==1:return x,w
        a,b=gauss_normal(i-1)
        return np.r_[x,a],np.r_[w,-b]
    nodes=[];weights=[]
    for i in range(1,level+2):
        for j in range(1,level+3-i):
            a,wa=delta(i);b,wb=delta(j)
            for x,wx in zip(a,wa):
                for y,wy in zip(b,wb):
                    nodes.append((round(float(x),14),round(float(y),14)));weights.append(wx*wy)
    unique={}
    for node,w in zip(nodes,weights):unique[node]=unique.get(node,0.)+w
    unique={k:v for k,v in unique.items() if abs(v)>1e-13}
    return np.array(list(unique)),np.array(list(unique.values()))

def setup():
    grid=np.linspace(0,1,65)
    lam,phi=kl_expansion(lambda x,y:np.exp(-np.abs(x-y)/.25),grid,2)
    return grid,lam,phi

def uq_experiment():
    grid,lam,phi=setup();solve=lambda z:diffusion(z,4,grid,lam,phi)
    rng=np.random.default_rng(42);train=rng.normal(size=(100,2));y=solve(train)
    X,idx=hermite_basis(train,3);coef=np.linalg.lstsq(X,y,rcond=None)[0]
    valid=rng.normal(size=(1000,2));truth=solve(valid);pred=hermite_basis(valid,3)[0]@coef
    x,w=gauss_normal(5);z=np.array([(a,b) for a in x for b in x]);ww=np.outer(w,w).ravel()
    projected=hermite_basis(z,3)[0].T@(ww*solve(z))
    nodes,weights=smolyak_normal_2d(4);ys=solve(nodes);threshold=.14
    return {'lam':lam,'modes':len(idx),'condition':np.linalg.cond(X),'coef':coef,'projection':projected,
      'relative_rmse':np.linalg.norm(pred-truth)/np.linalg.norm(truth),
      'mc_mean':truth.mean(),'mc_var':truth.var(ddof=1),'mc_exceed':(truth>threshold).mean(),
      'pce_mean':coef[0],'pce_var':sum(coef[1:]**2),'pce_exceed':(pred>threshold).mean(),
      'sparse_nodes':len(nodes),'sparse_weight_sum':weights.sum(),
      'sparse_mean':weights@ys,'sparse_var':weights@(ys**2)-(weights@ys)**2,
      'sparse_exceed':weights@(ys>threshold)}
print('biblioteca UQ lista')
[ ]Compare PCE, quadrature and MCBrowser
r=uq_experiment()
print('autovalores KL',r['lam'],'términos',r['modes'],'condición regresión',r['condition'])
print('RMSE relativo validación',r['relative_rmse'])
print('MC media, varianza, P(u>0.14)',r['mc_mean'],r['mc_var'],r['mc_exceed'])
print('PCE media, varianza, P(u>0.14)',r['pce_mean'],r['pce_var'],r['pce_exceed'])
print('coeficientes proyección',r['projection'])
print('Smolyak nodos, suma pesos, media, varianza, excedencia',
      r['sparse_nodes'],r['sparse_weight_sum'],r['sparse_mean'],r['sparse_var'],r['sparse_exceed'])
print('soluciones nivel 4: regresión 100, proyección 25, Smolyak',r['sparse_nodes'],'MC 1000')

PCE exceedance is obtained by evaluating the surrogate on the same 1000 independent inputs as MC. In this realization both give 0.281 and direct indicator quadrature gives 0.2333: agreeing on smooth moments does not guarantee tail accuracy. Approximate binomial standard error of 0.281 with 1000 samples is 0.0142, excluding physical discretization and KL truncation.

The next check varies mode count using the same 5000 normal realizations in every case. Differences are paired but still have sampling and spatial-discretization error; even 16 modes do not exactly represent the continuous field.

[ ]Convergence as KL modes are addedBrowser
grid=np.linspace(0,1,65)
lam,phi=kl_expansion(lambda x,y:np.exp(-abs(x-y)/.25),grid,16)
z=np.random.default_rng(98).normal(size=(5000,16))
for m in (2,4,8,16):
    y=diffusion(z[:,:m],4,grid,lam[:m],phi[:,:m])
    print('modos',m,'varianza del campo retenida',sum(lam[:m]),
          'media',y.mean(),'varianza',y.var(ddof=1),'excedencia',np.mean(y>.14))

In the run with seed 98, mean changes from 0.1274 with two modes to 0.1332 with sixteen; a practical sign that truncation matters in this example. Retained percentage is a property of the field, while the mean change also depends on the PDE’s nonlinear response.

The next cell reuses lesson 15’s adaptive allocator and the same fine and coarse KL field. Its bias indicator is heuristic; it estimates the mean, not exceedance probability. Pilot work is included in cost. MLMC and MC levels and tolerances are not identical, so the table illustrates the tradeoff without proving universal superiority.

[ ]MLMC for the same fieldBrowser
def estimate_rates(means,variances,costs):
    """Pendientes estimadas por regresión en niveles positivos; sesgo ruidoso."""
    ell=np.arange(1,len(means));mask=(np.abs(np.asarray(means)[1:])>1e-15)&(np.asarray(variances)[1:]>1e-15)
    if mask.sum()<2:return np.nan,np.nan,np.nan
    a=-np.polyfit(ell[mask],np.log2(np.abs(np.asarray(means)[1:][mask])),1)[0]
    b=-np.polyfit(ell[mask],np.log2(np.asarray(variances)[1:][mask]),1)[0]
    g=np.polyfit(ell[mask],np.log2(np.asarray(costs)[1:][mask]),1)[0]
    return float(a),float(b),float(g)

def adaptive_mlmc(level_sampler,cost_fn,eps,seed=42,pilot=1000,min_level=3,max_level=7):
    """Piloto por nivel, selección heurística de L y muestra final independiente."""
    if eps<=0 or pilot<30 or min_level<1 or max_level<min_level:raise ValueError('parámetros inválidos')
    rng=np.random.default_rng(seed);means=[];variances=[];costs=[]
    selected=max_level;bias_est=np.inf;rates=(np.nan,np.nan,np.nan)
    for level in range(max_level+1):
        y=level_sampler(level,pilot,rng);means.append(float(y.mean()));variances.append(float(y.var(ddof=1)));costs.append(float(cost_fn(level)))
        if level>=min_level:
            rates=estimate_rates(means,variances,costs)
            alpha=np.clip(rates[0] if np.isfinite(rates[0]) else 1.,.5,2.)
            # Añadimos dos errores estándar para no tratar una media ruidosa como cero.
            bias_est=(abs(means[-1])+2*np.sqrt(variances[-1]/pilot))/(2**alpha-1)
            if bias_est<eps/np.sqrt(2):selected=level;break
    V=np.maximum(variances,1e-30);C=np.asarray(costs)
    counts=np.maximum(2,np.ceil(2*eps**-2*np.sqrt(V/C)*np.sum(np.sqrt(V*C))).astype(int))
    # La estimación final es independiente del piloto que seleccionó tamaños y L.
    final_rng=np.random.default_rng(seed+100000);values=[];estimated_var=0.
    for l,n in enumerate(counts):
        y=level_sampler(l,int(n),final_rng);values.append(float(y.mean()));estimated_var+=float(y.var(ddof=1)/n)
    final_work=int(np.dot(counts,C));pilot_work=int(pilot*np.sum(C))
    return {'estimate':sum(values),'se':np.sqrt(estimated_var),'counts':counts,'means':means,'variances':variances,'costs':costs,'rates':rates,'bias_proxy':bias_est,'level':selected,'budget_met':bias_est<eps/np.sqrt(2),'final_work':final_work,'pilot_work':pilot_work,'total_work':final_work+pilot_work}
grid,lam,phi=setup()
def level(l,n,rng):
    z=rng.normal(size=(n,2))
    fine=diffusion(z,l,grid,lam,phi)
    return fine if l==0 else fine-diffusion(z,l-1,grid,lam,phi)
cost=lambda l:2**(l+2)+(2**(l+1) if l else 0)
r=adaptive_mlmc(level,cost,.001,pilot=300,max_level=6)
print('MLMC media',r['estimate'],'SE',r['se'],'nivel',r['level'],
      'criterio heurístico',r['budget_met'],'trabajo final/piloto/total',
      r['final_work'],r['pilot_work'],r['total_work'])
print('MC anterior: trabajo físico aproximado',1000*2**6)

The mean can be stable even when quantiles or failure are not. Adjust modes, degree and grid, inspect conditioning and validate with independent points. Chaospy provides projection and sparse quadrature; Dakota and UQLab are other platforms. Match laws, normalizations and orders before comparing.

The next cell repeats projection and sparse quadrature for the same PDE with Chaospy. Mean and variance of the truncated PCE are not exactly the direct quadrature variance of the response. Chaospy retains 55 nodes in the sparse combination; our implementation groups numerically coincident nodes and uses 53. Both calculate the same integral up to rounding in this case.

[ ]Comparison with ChaospyBrowser
import chaospy as cp
dist=cp.J(cp.Normal(),cp.Normal())
basis=cp.generate_expansion(3,dist,normed=True)
grid,lam,phi=setup()
for sparse in (False,True):
    nodes,weights=cp.generate_quadrature(4,dist,rule='gaussian',sparse=sparse)
    y=diffusion(nodes.T,4,grid,lam,phi)
    model=cp.fit_quadrature(basis,nodes,weights,y)
    print('dispersa',sparse,'nodos',len(weights),
          'media cuadratura',weights@y,
          'varianza cuadratura',weights@(y*y)-(weights@y)**2,
          'media PCE',cp.E(model,dist),'varianza PCE',cp.Var(model,dist))

Exercises

ProofPCE moments
Prove: Prove the mean and variance formulas for an orthonormal basis.
0
ψ₀=1 and E[ψμψν]=δμν.

Step 1 of 3. What is E[ψν] for nonzero ν?

NumericBasis size
How many terms are in the total-degree p=4 basis for d=10 variables?
NumericOversampled regression
With that basis and an oversampling ratio of 2, how many evaluations are used at minimum?
QuizOrthogonal families
For independent uniform, gamma and beta inputs, which families correspond in that order?
QuizChoose a method
When can stochastic Galerkin be appropriate?
CodeKL with Nyström
Implement kl_expansion(kernel,x_grid,n_modes) for an increasing grid: trapezoidal rule, symmetric weighted matrix, descending eigenvalues and eigenfunctions evaluated at nodes. Return (values, functions) with functions orthonormal under the weights.
import numpy as np
def kl_expansion(kernel,x_grid,n_modes):
  pass
Shift+Enter to run
Key idea
KL reduces input dimension; PCE and collocation exploit parameter regularity, with errors that must be checked for each quantity of interest.