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
- 29Taxonomy of simulation uncertainty sourcesEffective dimension and ANOVA decompositionGalerkin methodSpectral convergenceMultifidelity Monte Carlo
- 09Orthogonal polynomialsGaussian quadratureGauss-Hermite quadrature for Gaussian expectationsCurse of dimensionality in quadrature
- 14Gaussian processKernel design for Gaussian processes
- 02Spectral theorem
- 11Linear regression model and least-squares fitting
- 05Gaussian linear model
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:
Coefficients have zero mean and identity covariance; for a Gaussian field they are independent normals. Retaining modes preserves fraction 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 diagonalizes symmetric matrix . If is a normalized Euclidean eigenvector, is orthonormal under that quadrature. The figure uses the trapezoidal rule: short correlation usually spreads variance across more modes.
Integrated squared truncation error is . To choose 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.
Polynomial bases
A polynomial chaos expansion approximates a square-integrable output by , with orthonormal for the input law and . Then and . 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 in variables has terms. Xiu and Karniadakis develop this correspondence.
Nonintrusive construction uses the solver as a black box. Projection approximates by quadrature; regression minimizes . 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 is uniform on , the first two orthonormal functions are and . Response has coefficients and : 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.
Stochastic Galerkin inserts the expansion into the equations and projects residual onto each mode. If , blocks are and . 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 nodes per dimension has points. A Smolyak sparse grid combines increments , with :
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 the combination is . With one central node in and three nodes in , five distinct points are evaluated instead of the nine in product . The negative sign avoids double-counting the central contribution: retaining nodes without their weights does not define correct quadrature.
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 . Compare with sampling and refinement.
Lab: diffusion with uncertain conductivity
Solve on , , and observe . The logarithm of 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 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.
"""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')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.
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.
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.
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
Step 1 of 3. What is E[ψν] for nonzero ν?
import numpy as np
def kl_expansion(kernel,x_grid,n_modes):
pass