Algorithmadvanced
Stochastic Galerkin method
Also called spectral stochastic finite element method, intrusive polynomial chaos, stochastic Galerkin projection.
Projects the governing equations onto the polynomial chaos basis, giving one large coupled deterministic system for all coefficients.
- Time
- O((P n)^3) worst
- Space
- Θ((P n)^2) extra
- Where
- P = the number of chaos terms (d+p choose p); d = the number of random inputs; n = the number of deterministic unknowns; p = the total degree
- Model
- Real RAM
- Properties
- deterministicnot exactintrusive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Roger G. Ghanem, Pol D. Spanos, 1991
The stochastic Galerkin method computes a polynomial chaos expansion of the solution of an equation with random inputs. It writes the unknown as , a sum of chaos polynomials with unknown coefficient vectors, puts this sum into the equation, and asks that the residual be orthogonal to every polynomial of the basis. This is the Galerkin method applied in the random variables. The result is one deterministic system for all coefficients at once, times as large as the original problem, where is the number of chaos terms. The method is intrusive: the solver of the model must be rewritten to assemble and solve the coupled system. In return, for smooth dependence on the input the error decays exponentially in the degree , and the error is within a constant of the best possible polynomial approximation.
In plain words
Suppose a structure has a stiffness that is not known exactly, only its range. You want to know how the deflection depends on the unknown stiffness. You guess that the deflection is a polynomial in the unknown value, with unknown coefficients. Put the guess into the equation. The equation will not hold exactly, but you can ask that the error is, on average, unrelated to each polynomial in the guess. That gives one equation for each coefficient. All of these equations are coupled, so you solve them together as one big linear system. After that, the mean of the deflection is the first coefficient, and the variance is the sum of the squares of the others. You run the solver once, but on a larger problem, instead of running it many times.
The problem
The model is a linear system with unknowns, for example a finite element method discretization of a diffusion equation. The input has independent components, each uniform on , and the matrix depends on it in the affine way
which is the form a truncated Karhunen-Loeve expansion of a random field coefficient gives. The matrices are symmetric, and is positive definite for every in the box. The output is the mean , the variance of each component, and a polynomial surrogate of total degree at most .
The basis is the set of products , with the orthonormal Legendre polynomials, for the multi-indices . Then . For other input laws, the generalized polynomial chaos picks the matching family, and the algorithm does not change.
The algorithm
The Galerkin conditions for all are, after the substitution ,
With the matrices this is with , a sum of Kronecker products.
STOCHASTIC-GALERKIN(A_0, ..., A_d, f, p)- 1
Λ ← all α ∈ ℕ^d with |α| ≤ p, the zero index first; P ← |Λ| - 2
G_0 ← I_P; G_k[β, α] ← E[ξ_k Ψ_β Ψ_α] for k = 1..d ▷ exact formulas, no quadrature - 3
K ← Σ_{k=0..d} G_k ⊗ A_k ▷ P × P blocks of size n × n - 4
F ← e_0 ⊗ f ▷ E[Ψ_β] = 1 for β = 0, else 0 - 5
solve K c = F for c = (c_α), α ∈ Λ - 6
mean ← c_0; variance_i ← Σ_{α ≠ 0} (c_α)_i^2 - 7
return c, mean, variance
Line L1 builds the total degree set, sorted by degree. Line L2 needs only one dimensional facts, because the inputs are independent: is zero unless and agree in every coordinate except , and there they differ by one. The three term recurrence with gives the nonzero entries. So each has at most two nonzero entries per row, and has at most nonzero blocks per block row. Line L5 is the single solve of the method; the reference code uses dense Gaussian elimination, and large problems use the conjugate gradient method with the preconditioner . Line L6 uses orthonormality: the mean is the coefficient of and the variance is the sum of the other squares.
Example
Take the scalar model with uniform on . The exact moments are and , so . Here , , and is a tridiagonal matrix of size . The values below come from the reference code; they are deterministic.
| mean | error of mean | variance | error of variance | error | best error | |
|---|---|---|---|---|---|---|
| 0 | 0.5000000000 | 0 | ||||
| 1 | 0.5454545455 | 0.0247933884 | ||||
| 2 | 0.5490196078 | 0.0307574010 | ||||
| 3 | 0.5492851768 | 0.0315104224 | ||||
| 4 | 0.5493046209 | 0.0315881058 | ||||
| 6 | 0.5493061364 | 0.0315960330 |
The errors fall by a factor of about 13 per degree, which is exponential convergence. The last two columns compare with the error of the best degree approximation, the truncated exact expansion: the Galerkin error is at most 4 percent larger. The mean at is ; it equals the two point Gauss-Legendre rule applied to , an instance of the theorem in the Properties section.
The reference code also solves the diffusion problem on with zero boundary values and linear elements on 8 cells, where on the left half and on the right half. At the system has blocks and 105 unknowns. The mean of is against from a Gauss rule on the exact solution, and the variance is against .
Correctness
The coefficients from line L5 satisfy the Galerkin conditions, because block row of is the condition for written out with the definition of . The system has a unique solution: for a coefficient vector with surrogate , orthonormality gives , which is positive unless . So is symmetric positive definite. The same identity says that the Galerkin solution is the best approximation of in the energy norm among all vector polynomials of total degree , which is Cea's lemma in the random variables. The proof file proves these facts and the theorem on Gauss rules below.
Proof: The stochastic Galerkin system is the Galerkin projection, has a unique solution, and gives the best approximation in the energy normfull
We assume exact arithmetic. The inputs are independent and uniform on , with . The matrices are real, symmetric and of size , and is positive definite for every . The basis , , is orthonormal: , with . Let be the set of functions with , and identify with the stacked vector . Then with , and .
Lemma 1 (the block system is the Galerkin projection). A vector solves if and only if satisfies for every .
Proof. By linearity of expectation, , the block row of . Also , which is for and otherwise, so it is the block .
Lemma 2 (the energy identity). For every , , and . In particular is symmetric positive definite, so has exactly one solution and line L5 terminates with it.
Proof. Expand: . The second identity is the case where only appears, together with . is symmetric because each and each is symmetric. If , then is a nonzero polynomial, so it is nonzero on a set of positive probability, and there ; hence . A positive definite matrix is nonsingular, and Gaussian elimination with partial pivoting on a nonsingular matrix finds a nonzero pivot in each of its finitely many steps.
Lemma 3 (spectral equivalence). If for every in the box, with , then .
Proof. For every , . Take the expectation and use both identities of Lemma 2.
So the eigenvalues of lie in , for every and .
Lemma 4 (best approximation in the energy norm). Let be the exact solution and . Then .
Proof. The form is an inner product on square integrable vector functions, because is symmetric positive definite and bounded on the box. The exact solution satisfies for every , so for every . By Lemma 1, as well. Subtract: for all , so is the -orthogonal projection of onto . For any , by the Pythagorean identity.
Under the hypothesis of Lemma 3, lies between and times , so in that norm the error is at most times the best error.
Lemma 5 (one input is Gauss projection). Let , and let and be the nodes and weights of the point Gauss-Legendre rule for the uniform law on , so that . Then for .
Proof. Let , the matrix with . Let . The Gauss rule is exact for polynomials of degree , so , that is ; as is square, is orthogonal. The three term recurrence gives for , and . The nodes are the zeros of , so at every node for all , which is with . Hence and
The middle factor is block diagonal with blocks . So . The vector has entries . Therefore , which is the claim.
Theorem. Under the assumptions above, the algorithm terminates, returns the unique coefficients of the Galerkin projection of onto , and these give the best approximation of in in the energy norm. The returned mean is and the returned variances are those of the components of .
Proof. Lines L1 to L4 are finite loops. Termination and uniqueness are Lemma 2, the projection property is Lemma 1, and the optimality is Lemma 4. For the moments, , and by orthonormality, so the variance of is , which is line L6.
Complexity
In the real RAM model, line L2 costs with the simple test of the reference code, or with a hash of the indices. Line L3 forms entries, of which only are nonzero. A dense direct solve costs time and space. With sparse storage, one product costs , and preconditioned CG needs a number of iterations that does not grow with or (the theorem below). grows like for fixed , so the method is practical only for moderate .
Properties
- Theorem (spectral equivalence). If for all in the box, with , then . So the condition number of preconditioned by is at most , for every and . In the example and the bound is 3.
- Theorem (one input). If , the Galerkin coefficients are , where are the point Gauss-Legendre nodes and weights for the uniform law. So for one input and affine dependence, stochastic Galerkin gives the same coefficients as non-intrusive spectral projection and the same surrogate as stochastic collocation at the Gauss nodes. This does not hold for or for a nonlinear dependence on .
- Quasi-optimal. The error is the best possible in the energy norm (a theorem); in the norm , which is the norm up to a factor when , it is at most times the best error.
- Intrusive. The deterministic solver must be changed to form . One run of a large solve replaces many runs of the original solver.
- Deterministic. There is no sampling error; the only errors are the truncation at degree and the solver tolerance.
Variants and improvements
- Other input laws. Hermite, Laguerre or Jacobi chaos for Gaussian, gamma or beta inputs, by the Wiener-Askey scheme of generalized polynomial chaos. Only the recurrence constants in line L2 change.
- Non-affine and nonlinear models. For a lognormal coefficient or a nonlinear equation, the Galerkin projection needs triple products or a pseudospectral evaluation of the nonlinear terms, and loses its sparsity.
- Solvers. Mean-based block diagonal preconditioning, Kronecker product preconditioners, and low-rank tensor solvers that never store all unknowns.
- Adaptive and anisotropic bases. Different degrees for different inputs, or index sets grown by error indicators, reduce when the inputs are of unequal importance.
- Space-random discretization. Babuska, Tempone and Zouraris analyzed the joint finite element discretization in the physical and the random variables, with and versions in both.
When to use it
Use stochastic Galerkin when you own the solver, the model is linear or mildly nonlinear in the unknown, the coefficients are affine or polynomial in a moderate number of inputs, and you need the whole law of the output, not only a mean. Use non-intrusive spectral projection, regression-based polynomial chaos or stochastic collocation when the model is a black box or when the dependence on is strongly nonlinear; these run the existing solver at many inputs. Use Monte Carlo integration or multilevel Monte Carlo when is large or the output is not smooth in .
Pitfalls
- A coefficient that is not positive. If is indefinite for some in the support, for example , the exact solution has a pole and can be singular. A truncated expansion of a positive field can also lose positivity; check the bound on .
- Gaussian inputs in an affine coefficient. with Gaussian is negative with positive probability, and the problem has no finite variance solution. Use a lognormal or a bounded law.
- Large . With and , and the system is 1001 times the size of one solve. The block structure must be kept sparse.
- Wrong normalization. With unnormalized polynomials, ; the mean is still but the variance is .
- Long time integration. For time dependent problems with a random frequency, a fixed degree loses accuracy as time grows, because the solution oscillates faster and faster in .
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.
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra and error norms for the scientific-computing pages.
A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.
API (fixed; other pages copy this file byte for byte):
zeros(m, n=None) m by n zero matrix (n = m if not given)
eye(n) n by n identity
add(A, B), sub(A, B) entrywise sum and difference (vectors or matrices)
scale(c, A) c times A (vector or matrix)
matmul(A, B) matrix product
matvec(A, x) matrix times vector
transpose(A) transpose
dot(x, y) inner product of two vectors
norm2(x) Euclidean norm of a vector, as a float
outer(x, y) outer product x y^T
solve(A, b) Gaussian elimination with partial pivoting;
b is a vector or a matrix of right sides
inv(A) inverse of A
det(A) determinant of A
cholesky(A) lower triangular L with A = L L^T (floats)
cholesky_solve(L, b) solve L L^T x = b for a vector b
err_l1(e, dx=1) sum |e_j| dx
err_l2(e, dx=1) sqrt(sum e_j^2 dx), as a float
err_linf(e, dx=1) max |e_j| (dx is not used)
observed_order(errors) [log2(E_i / E_(i+1)) for successive errors]
"""
import math
def zeros(m, n=None):
"""Return an m by n matrix of zeros (n = m if n is None)."""
if n is None:
n = m
return [[0] * n for _ in range(m)]
def eye(n):
"""Return the n by n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1
return out
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c, a):
"""Return c times a, for a vector or a matrix a."""
if _is_matrix(a):
return [[c * x for x in row] for row in a]
return [c * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def matmul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]
def dot(x, y):
"""Return the inner product of the vectors x and y."""
return sum(a * b for a, b in zip(x, y))
def norm2(x):
"""Return the Euclidean norm of the vector x, as a float."""
return math.sqrt(float(dot(x, x)))
def outer(x, y):
"""Return the outer product x y^T as a matrix."""
return [[a * b for b in y] for a in x]
def _eliminate(a, rhs):
"""Reduce a to upper triangular form with partial pivoting.
a is a copy of the square matrix, rhs a list of right side rows (one
row per row of a) that receives the same row operations. Return the
number of row swaps. Raise ValueError if a pivot is zero.
"""
n = len(a)
swaps = 0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("matrix is singular")
if p != k:
a[k], a[p] = a[p], a[k]
rhs[k], rhs[p] = rhs[p], rhs[k]
swaps += 1
for i in range(k + 1, n):
f = a[i][k] / a[k][k]
if f == 0:
continue
for j in range(k, n):
a[i][j] -= f * a[k][j]
for j in range(len(rhs[i])):
rhs[i][j] -= f * rhs[k][j]
return swaps
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (the result is a vector) or a matrix with one column per
right side (the result is a matrix). Fraction entries stay exact.
Raise ValueError if a is singular.
"""
n = len(a)
work = [list(row) for row in a]
vector = not _is_matrix(b)
rhs = [[v] for v in b] if vector else [list(row) for row in b]
_eliminate(work, rhs)
m = len(rhs[0]) if n else 0
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(m):
s = rhs[i][j]
for k in range(i + 1, n):
s -= work[i][k] * x[k][j]
x[i][j] = s / work[i][i]
if vector:
return [row[0] for row in x]
return x
def inv(a):
"""Return the inverse of the square matrix a."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a (0 if singular)."""
work = [list(row) for row in a]
rhs = [[] for _ in a]
try:
swaps = _eliminate(work, rhs)
except ValueError:
return 0
d = -1 if swaps % 2 else 1
for i in range(len(a)):
d *= work[i][i]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T, in floats.
Raise ValueError if a is not symmetric positive definite.
"""
n = len(a)
low = [[0.0] * n for _ in range(n)]
for j in range(n):
s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[j][j] = math.sqrt(s)
for i in range(j + 1, n):
t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
low[i][j] = t / low[j][j]
return low
def cholesky_solve(low, b):
"""Solve L L^T x = b, with L from cholesky, for a vector b."""
n = len(low)
y = [0.0] * n
for i in range(n):
y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def err_l1(e, dx=1):
"""Return the discrete L1 norm sum |e_j| dx."""
return sum(abs(v) for v in e) * dx
def err_l2(e, dx=1):
"""Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
return math.sqrt(float(sum(v * v for v in e) * dx))
def err_linf(e, dx=1):
"""Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
return max(abs(v) for v in e)
def observed_order(errors):
"""Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
stochastic_galerkin_method.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stochastic-galerkin-method/. The authors are listed in prov/850TYY.jsonl.
"""Stochastic Galerkin method for a linear system with an affine random matrix.
The model is A(xi) u(xi) = f, with
A(xi) = A_0 + xi_1 A_1 + ... + xi_d A_d,
where xi_1..xi_d are independent and uniform on [-1, 1] and f is a fixed
vector. The solution is sought as u(xi) = sum_a c_a Psi_a(xi), where Psi_a
are the orthonormal Legendre chaos polynomials of total degree at most p.
The Galerkin conditions E[(A(xi) u(xi) - f) Psi_b(xi)] = 0 for every b in
the basis give one block system K c = F with
K = sum_k G_k (x) A_k, G_k[a][b] = E[xi_k Psi_a Psi_b] (xi_0 = 1),
and F = e_0 (x) f. The block system is solved with scimat.solve.
"""
import math
from scimat import solve
Vector = list[float]
Matrix = list[list[float]]
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: list[tuple[int, ...]] = []
def rec(prefix: list[int], left: int) -> None:
if len(prefix) == d:
out.append(tuple(prefix))
return
for v in range(left, -1, -1):
rec(prefix + [v], left - v)
rec([], p)
out.sort(key=lambda a: (sum(a), [-v for v in a]))
return out
def legendre_xi_product(m: int, n: int) -> float:
"""E[xi psi_m(xi) psi_n(xi)] for orthonormal Legendre psi_n = sqrt(2n+1) P_n, xi uniform on [-1, 1]."""
if n == m + 1:
return (m + 1) / math.sqrt((2 * m + 1) * (2 * m + 3))
if m == n + 1:
return (n + 1) / math.sqrt((2 * n + 1) * (2 * n + 3))
return 0.0
def galerkin_matrices(index: list[tuple[int, ...]], d: int) -> list[Matrix]:
"""G_0 = identity and G_k[a][b] = E[xi_k Psi_a Psi_b] for k = 1..d."""
size = len(index)
g = [[[0.0] * size for _ in range(size)] for _ in range(d + 1)]
for i in range(size):
g[0][i][i] = 1.0
for k in range(d):
for i, a in enumerate(index):
for j, b in enumerate(index):
if all(a[t] == b[t] for t in range(d) if t != k):
g[k + 1][i][j] = legendre_xi_product(a[k], b[k])
return g
def stochastic_galerkin(a_mats: list[Matrix], f: Vector, p: int) -> tuple[list[tuple[int, ...]], list[Vector]]:
"""Solve the Galerkin system; return the index set and one coefficient vector per index."""
d = len(a_mats) - 1
n = len(f)
index = total_degree_set(d, p) # @line L1
size = len(index)
g = galerkin_matrices(index, d) # @line L2
big = [[0.0] * (size * n) for _ in range(size * n)]
for k in range(d + 1): # @line L3
for i in range(size):
for j in range(size):
gij = g[k][i][j]
if gij == 0.0:
continue
for r in range(n):
row = big[i * n + r]
ak = a_mats[k][r]
for s in range(n):
row[j * n + s] += gij * ak[s]
rhs = [0.0] * (size * n) # @line L4
rhs[:n] = [float(v) for v in f]
sol = solve(big, rhs) # @line L5
coeffs = [sol[i * n:(i + 1) * n] for i in range(size)]
return index, coeffs # @line L7
def mean_and_variance(coeffs: list[Vector]) -> tuple[Vector, Vector]:
"""Mean c_0 and variance sum_{a != 0} c_a^2, component by component."""
mean = list(coeffs[0]) # @line L6
var = [sum(c[r] ** 2 for c in coeffs[1:]) for r in range(len(mean))]
return mean, var
def legendre_basis(x: float, p: int) -> list[float]:
"""Orthonormal Legendre values psi_0(x)..psi_p(x)."""
vals = [1.0, x]
for k in range(2, p + 1):
vals.append(((2 * k - 1) * x * vals[-1] - (k - 1) * vals[-2]) / k)
return [vals[k] * math.sqrt(2 * k + 1) for k in range(p + 1)]
def evaluate(index: list[tuple[int, ...]], coeffs: list[Vector], xi: list[float]) -> Vector:
"""The surrogate u_p(xi) = sum_a c_a Psi_a(xi)."""
p = max(sum(a) for a in index)
tables = [legendre_basis(x, p) for x in xi]
out = [0.0] * len(coeffs[0])
for a, c in zip(index, coeffs):
w = 1.0
for t, at in enumerate(a):
w *= tables[t][at]
for r in range(len(out)):
out[r] += w * c[r]
return out
def diffusion_matrices(n_el: int, amp: float) -> list[Matrix]:
"""Linear finite elements for -(a u')' = 1 on (0, 1), u(0) = u(1) = 0.
The coefficient is a = 1 + amp xi_1 on (0, 1/2) and 1 + amp xi_2 on (1/2, 1);
n_el is even. Return [A_0, A_1, A_2] for the n_el - 1 interior nodes.
"""
h = 1.0 / n_el
n = n_el - 1
left = [[0.0] * n for _ in range(n)]
right = [[0.0] * n for _ in range(n)]
for e in range(n_el):
target = left if e < n_el // 2 else right
nodes = [e - 1, e]
for a_i, i in enumerate(nodes):
for a_j, j in enumerate(nodes):
if 0 <= i < n and 0 <= j < n:
target[i][j] += (1.0 if a_i == a_j else -1.0) / h
a0 = [[left[i][j] + right[i][j] for j in range(n)] for i in range(n)]
a1 = [[amp * v for v in row] for row in left]
a2 = [[amp * v for v in row] for row in right]
return [a0, a1, a2]
def load_vector(n_el: int) -> Vector:
"""The load F_i = integral of the hat function i, which is h for f = 1."""
return [1.0 / n_el] * (n_el - 1)
test_stochastic_galerkin_method.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stochastic-galerkin-method/. The authors are listed in prov/850TYY.jsonl.
import math
import random
from scimat import cholesky, matvec, solve
from stochastic_galerkin_method import (
diffusion_matrices,
evaluate,
galerkin_matrices,
legendre_basis,
load_vector,
mean_and_variance,
stochastic_galerkin,
total_degree_set,
)
def gauss_legendre(n):
"""Gauss-Legendre nodes and weights on [-1, 1] by Newton's method."""
xs, ws = [], []
for i in range(1, n + 1):
x = math.cos(math.pi * (i - 0.25) / (n + 0.5))
for _ in range(100):
p0, p1 = 1.0, x
for k in range(2, n + 1):
p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
dp = n * (x * p1 - p0) / (x * x - 1)
step = p1 / dp
x -= step
if abs(step) < 1e-15:
break
p0, p1 = 1.0, x
for k in range(2, n + 1):
p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
dp = n * (x * p1 - p0) / (x * x - 1)
xs.append(x)
ws.append(2 / ((1 - x * x) * dp * dp))
return xs, ws
def test_index_set_size_is_binomial():
for d in range(1, 4):
for p in range(0, 5):
idx = total_degree_set(d, p)
assert len(idx) == math.comb(d + p, p)
assert idx[0] == (0,) * d
assert len(set(idx)) == len(idx)
def test_triple_products_match_quadrature():
xs, ws = gauss_legendre(12)
for m in range(6):
for n in range(6):
q = sum(0.5 * w * x * legendre_basis(x, 6)[m] * legendre_basis(x, 6)[n] for x, w in zip(xs, ws))
g = galerkin_matrices([(k,) for k in range(6)], 1)[1][m][n]
assert abs(q - g) < 1e-13
def test_scalar_problem_converges_to_exact_moments():
# (2 + xi) u = 1, xi uniform on [-1, 1]: E[u] = ln(3) / 2, E[u^2] = 1/3
exact_mean = math.log(3.0) / 2.0
exact_var = 1.0 / 3.0 - exact_mean**2
errors = []
for p in range(0, 9):
_, c = stochastic_galerkin([[[2.0]], [[1.0]]], [1.0], p)
m, v = mean_and_variance(c)
errors.append(abs(m[0] - exact_mean))
assert errors[0] > 4e-2
assert errors[-1] < 1e-10
assert all(errors[i + 1] < errors[i] / 5 for i in range(len(errors) - 1))
assert abs(v[0] - exact_var) < 1e-9
def test_deterministic_matrix_gives_deterministic_solution():
a0 = [[4.0, 1.0], [1.0, 3.0]]
zero = [[0.0, 0.0], [0.0, 0.0]]
f = [1.0, 2.0]
_, c = stochastic_galerkin([a0, zero, zero], f, 3)
u = solve(a0, f)
assert all(abs(c[0][r] - u[r]) < 1e-14 for r in range(2))
assert all(abs(x) < 1e-14 for cv in c[1:] for x in cv)
def test_galerkin_residual_is_orthogonal_to_the_basis():
mats = diffusion_matrices(4, 0.6)
f = load_vector(4)
idx, c = stochastic_galerkin(mats, f, 3)
xs, ws = gauss_legendre(6)
n = len(f)
worst = 0.0
for b in idx:
acc = [0.0] * n
for x1, w1 in zip(xs, ws):
for x2, w2 in zip(xs, ws):
u = evaluate(idx, c, [x1, x2])
a = [[mats[0][i][j] + x1 * mats[1][i][j] + x2 * mats[2][i][j] for j in range(n)] for i in range(n)]
res = [ra - fa for ra, fa in zip(matvec(a, u), f)]
psi = legendre_basis(x1, 3)[b[0]] * legendre_basis(x2, 3)[b[1]]
for r in range(n):
acc[r] += w1 * w2 / 4.0 * res[r] * psi
worst = max(worst, max(abs(v) for v in acc))
assert worst < 1e-13
def test_block_matrix_is_positive_definite():
mats = diffusion_matrices(4, 0.9)
idx = total_degree_set(2, 3)
g = galerkin_matrices(idx, 2)
n = 3
size = len(idx)
big = [[sum(g[k][i // n][j // n] * mats[k][i % n][j % n] for k in range(3)) for j in range(size * n)] for i in range(size * n)]
assert all(big[i][j] == big[j][i] for i in range(size * n) for j in range(size * n))
cholesky(big)
def test_diffusion_moments_match_tensor_quadrature():
def u_half(x1, x2, amp):
a1, a2 = 1 + amp * x1, 1 + amp * x2
cc = (a2 + 3 * a1) / (4 * (a1 + a2))
return (cc / 2 - 1 / 8) / a1
xs, ws = gauss_legendre(30)
m = s2 = 0.0
for x1, w1 in zip(xs, ws):
for x2, w2 in zip(xs, ws):
u = u_half(x1, x2, 0.5)
m += w1 * w2 / 4 * u
s2 += w1 * w2 / 4 * u * u
_, c = stochastic_galerkin(diffusion_matrices(4, 0.5), load_vector(4), 5)
mean, var = mean_and_variance(c)
assert abs(mean[1] - m) < 1e-7
assert abs(var[1] - (s2 - m * m)) < 1e-7
def test_one_input_equals_gauss_projection():
a0 = [[3.0, -1.0, 0.0], [-1.0, 3.0, -1.0], [0.0, -1.0, 3.0]]
a1 = [[1.0, 0.5, 0.0], [0.5, -1.0, 0.0], [0.0, 0.0, 0.5]]
f = [1.0, 0.0, 2.0]
for p in range(0, 6):
_, c = stochastic_galerkin([a0, a1], f, p)
xs, ws = gauss_legendre(p + 1)
sols = [solve([[a0[i][j] + x * a1[i][j] for j in range(3)] for i in range(3)], f) for x in xs]
for a in range(p + 1):
proj = [sum(0.5 * w * legendre_basis(x, p)[a] * u[r] for x, w, u in zip(xs, ws, sols)) for r in range(3)]
assert all(abs(proj[r] - c[a][r]) < 1e-12 for r in range(3))
def test_surrogate_is_close_at_random_points():
rng = random.Random(7)
_, c = stochastic_galerkin([[[2.0]], [[1.0]]], [1.0], 10)
idx = total_degree_set(1, 10)
for _ in range(20):
x = rng.uniform(-1.0, 1.0)
assert abs(evaluate(idx, c, [x])[0] - 1.0 / (2.0 + x)) < 1e-5
History
Ghanem and Spanos introduced the spectral stochastic finite element method in their 1991 book. They expanded the random coefficient by the Karhunen-Loeve theorem, the solution in the Wiener-Hermite chaos of Wiener and of Cameron and Martin, and applied a Galerkin projection to both. Xiu and Karniadakis replaced the Hermite basis by the Askey families in 2002, which made the method practical for uniform and other non-Gaussian inputs. Babuska, Tempone and Zouraris gave the first error analysis of the joint discretization for elliptic problems in 2004. Later work went into solvers and preconditioners for the large coupled system and into adaptive index sets.
References
- Roger G. Ghanem and Pol D. Spanos, Stochastic Finite Elements, A Spectral Approach, revised edition, Dover, 2003 (first edition Springer, 1991), the spectral stochastic finite element method, with the Karhunen-Loeve expansion of the coefficient, the polynomial chaos expansion of the solution and the Galerkin projection onto the chaos basis
- Dongbin Xiu and George Em Karniadakis, The Wiener-Askey polynomial chaos for stochastic differential equations, SIAM Journal on Scientific Computing 24(2), 2002, 619-644, the Galerkin projection with Askey chaos bases and its convergence in numerical examples
- Dongbin Xiu, Numerical Methods for Stochastic Computations, A Spectral Method Approach, Princeton University Press, 2010, Chapter 6 (the stochastic Galerkin method)
- Olivier P. Le Maitre and Omar M. Knio, Spectral Methods for Uncertainty Quantification, Springer, 2010, Chapter 4 (Galerkin methods) and the later chapter on solvers for stochastic Galerkin problems
- Ivo Babuska, Raul Tempone and Georgios E. Zouraris, Galerkin finite element approximations of stochastic elliptic partial differential equations, SIAM Journal on Numerical Analysis 42(2), 2004, 800-825, the Galerkin approximation in the random and the physical variables together, with a priori error estimates
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 850TYY Edit this page History Report an error Markdown