Algorithmcore
Spherical harmonics method
Also called PN method, PN approximation.
Expands the angular flux in spherical harmonics up to degree N, giving a hyperbolic system of moment equations.
- Time
- O(M N^3) worst
- Space
- O(M N^2) extra
- Where
- M = the number of cells; N = the degree of the expansion
- Model
- Real RAM
- Properties
- deterministicnot exactnot iterativenot randomized
- Evidence
- Proof sketchCode in 1 languages
The spherical harmonics method, or method, approximates the angular dependence of the transport equation by a finite expansion. The angular flux is written as a sum of spherical harmonics up to degree , and taking moments of the transport equation gives a coupled system of first-order equations for the coefficients. In a slab the harmonics are the Legendre polynomials, and the system has unknowns. It is hyperbolic, and its wave speeds are the roots of , which are the Gauss nodes. For this reason with the Mark boundary conditions is the same discrete scheme as in a slab. is the diffusion approximation. Unlike discrete ordinates, the expansion treats all directions alike, so it has no ray effects in several dimensions, but a truncated expansion can be negative.
In plain words
At each point, particles move in all directions, and some directions carry more particles than others. The method describes this spread by a few numbers: the total, the net flow in one direction, how lopsided the spread is, and so on, each one a finer detail than the last. You keep the first few of these numbers and drop the rest.
The transport equation then becomes a small set of equations for these numbers. With only the total and the net flow you get diffusion. With more numbers you get closer to the true transport answer.
In a slab this is the same as following particles along a few special directions, so the two methods give the same numbers. The difference is how you solve: here all the unknowns are solved together in one linear system, with no repeated sweeps.
The problem
The slab has cells with the widths , the total and scattering cross sections and in , the absorption and an isotropic source . The angular flux solves
with a vacuum or a reflecting condition at each face. The method, for odd, writes
So is the scalar flux and is the current. Multiplying the transport equation by and integrating, with the recurrence , gives the equations
with and for . In matrix form, for . Each face needs conditions:
- Marshak: the half-range moments of the incoming flux are zero for .
- Mark: the incoming flux is zero at the positive roots of .
- Reflection: all odd moments are zero.
The algorithm
PN-SLAB(N, Σt, Σs, q, h, faces, bc)- 1
A ← the (N+1) × (N+1) streaming matrix: A[l][l+1] = (l+1)/(2l+1), A[l][l-1] = l/(2l+1) - 2
add (N+1)/2 rows for the face x = 0: Marshak, Mark or reflection conditions on the moments u_0 - 3
for each cell j and l = 0..N: add the row [A (u_{j+1} - u_j)/h_j + S_j (u_j + u_{j+1})/2]_l = q_j δ_{l0} - 4
add (N+1)/2 rows for the face x = L - 5
solve the banded linear system for the edge moments u_0, ..., u_M - 6
φ_j ← (u_{j,0} + u_{j+1,0})/2; leakages ← -u_{0,1} at x = 0 and u_{M,1} at x = L
The unknowns are the moments at each of the cell edges, in all. Line L3 is diamond difference: the cell value is the mean of the edge values. Lines L2 and L4 give rows each, so the system is square. The rows are ordered from left to right, so the matrix is banded with about diagonals on each side of the main one, and Gaussian elimination with partial pivoting keeps the fill inside the band. The Marshak rows use the half-range integrals , which a Gauss rule with points computes exactly.
Scattering couples only to itself, through . So line L5 includes it, and no source iteration is needed.
Example
The speeds by hand. For , , with the eigenvalues , the nodes of the two-point Gauss rule. For the eigenvalues are and , the roots of . For the equations are and , which is diffusion with .
Convergence in N. Take , , , vacuum faces and 200 cells. The table gives the leakage through one face and the flux at the center. with Mark conditions gives the same numbers as with diamond difference on the same mesh, to in the measurements; the reference is .
| width | leakage, Marshak | leakage, Mark | center, Marshak | center, Mark | |
|---|---|---|---|---|---|
| 2 | 1 | 0.770384 | 0.786622 | 2.668245 | 2.513710 |
| 2 | 3 | 0.747011 | 0.752284 | 2.989767 | 2.952453 |
| 2 | 5 | 0.744451 | 0.746609 | 3.014498 | 3.003413 |
| 2 | 7 | 0.743879 | 0.745022 | 3.012406 | 3.007473 |
| 2 | 0.743626 | 3.009311 | |||
| 10 | 1 | 1.329221 | 1.378312 | 9.054526 | 9.019608 |
| 10 | 3 | 1.300960 | 1.310459 | 9.036516 | 9.032432 |
| 10 | 5 | 1.297676 | 1.301576 | 9.038102 | 9.036307 |
| 10 | 7 | 1.296625 | 1.298734 | 9.038601 | 9.037620 |
| 10 | 1.296145 | 9.038785 |
with Marshak conditions gives the leakage , against for the exact diffusion solution. In these runs the Marshak leakage is more accurate than the Mark leakage at every , and the error of the Marshak leakage falls by a factor of about 3 to 8 per step of 2 in .
Decay constants. In an infinite medium with , the slowest mode decays like (Theorem 7 of the proof):
| 1 | 3 | 5 | 7 | 15 | transport | |
|---|---|---|---|---|---|---|
| 1.224745 | 0.988751 | 0.964672 | 0.959481 | 0.957521 | 0.957504 | |
| 0.547723 | 0.525560 | 0.525430 | 0.525430 | 0.525430 | 0.525430 |
The transport values are those of the diffusion approximation page. When scattering dominates, the flux is nearly isotropic and low orders are already accurate.
The flux at a vacuum face. For the slab of width 2, the incoming flux , , should be 0. The expansion gives:
| 0.1 | 0.3 | 0.5 | 0.7 | 0.9 | 1.0 | |
|---|---|---|---|---|---|---|
| 0.6548 | 0.4237 | 0.1926 | -0.0385 | -0.2696 | -0.3852 | |
| 0.5944 | 0.1800 | -0.1093 | -0.1822 | 0.0524 | 0.3136 | |
| 0.3600 | -0.1149 | -0.0476 | 0.0901 | -0.0924 | 0.2042 |
A polynomial in cannot jump from 0 to the outgoing flux at , so it oscillates and goes negative. The boundary conditions make only some moments of the incoming flux zero.
Correctness
The proofs are in the proof file. The equations are the exact moment equations with (Lemma 1). The matrix has the eigenvectors with the eigenvalues , the roots of , so the system is hyperbolic with incoming characteristics at each face (Theorem 2). The map from the values at the Gauss nodes to the moments is invertible, and it turns the diamond difference rows with Mark or reflecting conditions into the diamond difference equations; so these have the same solution, and it is unique when every cell absorbs (Theorem 4). The row gives exact particle balance for any face conditions (Theorem 5). is diffusion, and its Marshak form is the edge system of diffusion synthetic acceleration (Theorem 6). The decay constants are the roots of the dispersion function (Theorem 7). The method is a model error: as grows, the answers approach transport, which the tables measure.
Proof: The slab P_N equations are hyperbolic with the Gauss nodes as speeds, their diamond difference form with Mark conditions is the S_(N+1) scheme, they conserve particles, P1 is diffusion, and their decay constants are those of S_(N+1)full
We assume exact arithmetic. The slab, the cross sections and the lines L1 to L6 are those of the page, is odd, is the Legendre polynomial of degree , and . Scattering and the source are isotropic, and . The vector has the streaming matrix with and , and the collision matrix . Let be the roots of and the Gauss-Legendre weights.
The moment equations
Lemma 1 (the moment equations). If solves , then for every
The equations are these equations for with set to 0.
Proof. Multiply by and integrate over . The recurrence turns into the first two terms. On the right, .
The only approximation is : the flux is assumed to be a polynomial of degree in .
Theorem 2 (the speeds are the Gauss nodes). for . So has the distinct real eigenvalues , it is diagonalizable, and the equations are a hyperbolic system. Half of the speeds are positive and half are negative.
Proof. Row of is for . For the term with is missing from , so the row is , which is at a root of . The vectors are not zero (). The roots of are real, distinct and symmetric about 0, and 0 is not a root because is even.
So each face has incoming characteristics, and it needs conditions, as lines L2 and L4 give.
The link to discrete ordinates
Let be the matrix with the entries and the matrix with . So takes the values at the nodes to the moments, by the Gauss rule, and evaluates the expansion at the nodes.
Lemma 3. , with , and .
Proof. . The degree of is at most , so the Gauss rule is exact, and the orthogonality gives . The columns of are , so Theorem 2 gives . Finally .
Theorem 4 (P_N with Mark conditions is S_(N+1)). Let the cell rows of line L3 be the diamond difference form
on the edge vectors , and let each face be reflecting ( for odd ) or vacuum with the Mark conditions ( at the face for the incoming nodes). Then solves these equations if and only if solves the diamond difference equations with the Gauss rule, zero incoming flux at vacuum faces and reflection, and then and the current are the scalar flux and the current of . With in every cell, the system of line L5 has exactly one solution.
Proof. By Lemma 3, , , and . Multiply the cell rows by :
where is the mean of the edge values of . This is the diamond difference scheme, with the cell value equal to the mean of the edge values. The Mark rows are for the incoming nodes, which is zero incoming flux. At a reflecting face, since , . If all odd vanish, the face reflects. Conversely, if this is 0 for all , the odd polynomial of degree at most has the roots and , so it is zero, and every odd is 0. Since is invertible, the two systems have the same solutions, and is the current. The source iteration proof shows that the diamond difference equations with vacuum or reflecting faces have exactly one solution when in every cell.
So in a slab, adds nothing that does not have. The difference is in the solver: line L5 solves the coupled system directly, with no source iteration, so its cost does not depend on .
Conservation and the low orders
Theorem 5 (balance). For any face conditions, the solution of lines L1 to L5 satisfies
with at and at .
Proof. Row of cell is , since and . Multiply by and sum over the cells; the sum of the differences telescopes to .
Theorem 6 (P1 is diffusion). For the equations are and , which is the balance with Fick's law , . The Marshak condition at is , and the Mark condition is . The diamond difference P1 system with Marshak faces is the edge system of consistent diffusion synthetic acceleration.
Proof. The equations are rows 0 and 1 of Lemma 1. With , the Marshak condition gives , and the Mark condition gives . The cell rows are the equations (2) of the proof of diffusion synthetic acceleration with the source , and Theorem 2 of that proof eliminates the current.
So the two conditions place the zero of the linear extrapolation of at the distances (Marshak) and (Mark) outside the face; the exact Milne value is .
Decay constants
Theorem 7 (the infinite medium modes). Let and . The equations have a solution with if and only if , and
which is, up to the factor in front, the dispersion function of . On it has exactly one root, the decay constant of the slowest mode, and bisection on the determinant finds it. For the root is .
Proof. Substituting gives . By Lemma 3, , where is the vector of weights (row 0 of ). The matrix determinant lemma gives , and . Pair the nodes : , so the bracket is the one shown. For the product is positive, and the bracket decreases strictly from to , so it has exactly one zero, where the determinant changes sign. For , and , so the bracket is , which is 0 at .
The implementation evaluates by the three-term recurrence of a tridiagonal determinant, . As , the Gauss sum tends to , whose zero of is the decay constant of exact transport, because the integrand is analytic on for .
Complexity
In the real RAM model the system has unknowns and a lower bandwidth of about . Banded elimination with partial pivoting costs operations and stores numbers. This does not depend on the scattering ratio. with source iteration costs for iterations, which is cheaper for small and more expensive when is large. In three dimensions there are moments, and in two dimensions with symmetry ; the equations are then solved by iterative methods.
Properties
- Hyperbolic. The speeds are the Gauss nodes, all inside , so information moves at most at the particle speed (Theorem 2).
- Equal to S_(N+1) in a slab. With Mark conditions, also on the discrete level with diamond difference (Theorem 4).
- Rotationally invariant. In several dimensions the spherical harmonics up to degree span a space that rotations map to itself, so no direction is preferred. This is why has no ray effects, which discrete ordinates has.
- Not positive. A truncated expansion can be negative, near faces, voids and beams (the example).
- Conservative. The row is the exact balance of each cell (Theorem 5).
- Direct. Scattering enters the system, so no source iteration is needed and the cost does not grow as .
Variants and improvements
- Anisotropic scattering. With the Legendre moments of the scattering kernel, the diagonal entries become . The method takes scattering of degree up to at no extra cost.
- Simplified P_N. The equations replace the one-dimensional derivatives by three-dimensional gradients and divergences. They give a set of coupled diffusion equations, which is much cheaper than full and is used in reactor core codes, as a rule of thumb more accurate than diffusion near interfaces.
- Filtered P_N. McClarren and Hauck (2010) damp the highest moments after each step or in the equations. This reduces the oscillations and negative values of the example.
- Even-parity and odd-parity forms. Eliminating the odd moments gives a second-order, self-adjoint system for the even ones, which suits finite elements.
- Other boundary conditions. Marshak and Mark conditions are the common choices; variational conditions also exist. The example shows that the choice matters for low .
When to use it
Use when the angular flux is smooth: media where scattering dominates, with no voids and no strong beams, and in several dimensions when ray effects of discrete ordinates would be a problem. Its moment form also suits radiative transfer and coupling to other moment models. Low orders, to or , are a step above diffusion at a modest cost. In a slab, and are equivalent, and the choice is between a direct banded solve and a sweep with acceleration. Avoid it near vacuum faces, in voids and for streaming particles, where the expansion oscillates.
Pitfalls
- Even N (line L1). With even, 0 is a root of , so one speed is 0 and the faces need or conditions that do not split evenly. Use odd .
- Negative flux. The reconstructed angular flux, and in hard problems even the scalar flux, can be negative. Use more moments, a filter, or a positive method.
- Boundary conditions (lines L2 and L4). Vacuum cannot be imposed exactly; Marshak and Mark give different answers at low . A mismatch between the conditions and the expansion order is a common error.
- The normalization. With , the expansion has the factor . Another convention changes the entries of and of the boundary rows.
- The cost in several dimensions. The number of moments grows like , and the equations couple all of them. Large in three dimensions is expensive, which is why and discrete ordinates are often used.
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
# Part of https://algorithm.tamnd.com/spherical-harmonics-method/. The authors are listed in prov/HXR9T4.jsonl.
"""The P_N (spherical harmonics) equations in slab geometry.
The angular flux is expanded in Legendre polynomials up to degree N (N odd):
psi(x, mu) = sum_l (2l + 1) / 2 * phi_l(x) P_l(mu), phi_l = integral of P_l psi over [-1, 1].
So phi_0 is the scalar flux and phi_1 is the current. Multiplying the
transport equation by P_l and integrating gives, for l = 0, ..., N and
isotropic scattering and source,
(l + 1) / (2l + 1) phi_(l+1)' + l / (2l + 1) phi_(l-1)' + sigma_l phi_l = q delta_(l0),
with phi_(N+1) = 0, sigma_0 = sigma_t - sigma_s and sigma_l = sigma_t for
l >= 1. In matrix form A u' + S u = q e_0.
pn_slab discretizes this with diamond differences on the cell edges and
solves the whole linear system at once with a banded Gaussian
elimination, so scattering needs no iteration. Each face is "vacuum" or
"reflect"; a vacuum face uses the Marshak conditions (half-range odd
moments of the incoming flux are zero) or the Mark conditions (the
incoming flux is zero at the positive roots of P_(N+1)).
"""
import math
def legendre(n: int, x: float):
"""P_n(x) and P_n'(x)."""
if n == 0:
return 1.0, 0.0
p0, p1 = 1.0, x
for k in range(2, n + 1):
p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
return p1, n * (x * p1 - p0) / (x * x - 1.0)
def legendre_all(n: int, x: float):
"""[P_0(x), ..., P_n(x)]."""
p = [1.0, x][: n + 1]
for k in range(2, n + 1):
p.append(((2 * k - 1) * x * p[k - 1] - (k - 1) * p[k - 2]) / k)
return p
def gauss_legendre(n: int):
"""Nodes in increasing order and weights of the n-point Gauss-Legendre rule on [-1, 1]."""
nodes, weights = [0.0] * n, [0.0] * n
for i in range((n + 1) // 2):
x = math.cos(math.pi * (i + 0.75) / (n + 0.5))
for _ in range(100):
p, dp = legendre(n, x)
step = p / dp
x -= step
if abs(step) < 1e-16:
break
p, dp = legendre(n, x)
w = 2.0 / ((1.0 - x * x) * dp * dp)
nodes[n - 1 - i], weights[n - 1 - i] = x, w
nodes[i], weights[i] = -x, w
return nodes, weights
def moment_matrix(n: int):
"""The (n + 1) x (n + 1) streaming matrix A of the P_n equations."""
a = [[0.0] * (n + 1) for _ in range(n + 1)]
for l in range(n + 1):
if l + 1 <= n:
a[l][l + 1] = (l + 1) / (2 * l + 1)
if l >= 1:
a[l][l - 1] = l / (2 * l + 1)
return a
def half_range_moments(n: int):
"""H[m][l] = integral of P_m(mu) P_l(mu) over [0, 1], for m, l <= n (exact by Gauss quadrature)."""
xs, ws = gauss_legendre(n + 1)
h = [[0.0] * (n + 1) for _ in range(n + 1)]
for x, w in zip(xs, ws):
p = legendre_all(n, (x + 1.0) / 2.0)
for m in range(n + 1):
for l in range(n + 1):
h[m][l] += 0.5 * w * p[m] * p[l]
return h
def solve_sparse(rows, rhs):
"""Gaussian elimination with partial pivoting; rows is a list of dicts (column -> value).
With the lower bandwidth kl (row i has no entry left of column i - kl), the
pivot is searched in the rows k to k + kl, and the work is O(n kl^2)."""
n = len(rows)
rows = [dict(r) for r in rows]
rhs = list(rhs)
kl = max(i - min(r) for i, r in enumerate(rows))
for k in range(n):
top = min(n, k + kl + 1)
p = max(range(k, top), key=lambda i: abs(rows[i].get(k, 0.0)))
if rows[p].get(k, 0.0) == 0.0:
raise ValueError("singular system")
rows[k], rows[p] = rows[p], rows[k]
rhs[k], rhs[p] = rhs[p], rhs[k]
piv = rows[k][k]
for i in range(k + 1, top):
v = rows[i].get(k, 0.0)
if v != 0.0:
f = v / piv
ri = rows[i]
for j, a in rows[k].items():
ri[j] = ri.get(j, 0.0) - f * a
del ri[k]
rhs[i] -= f * rhs[k]
x = [0.0] * n
for k in range(n - 1, -1, -1):
s = rhs[k] - sum(a * x[j] for j, a in rows[k].items() if j > k)
x[k] = s / rows[k][k]
return x
def _face_rows(n, face, bc, sign):
"""Rows (lists of coefficients of the n + 1 moments) of the conditions at one face.
sign = +1 for the left face (incoming mu > 0), -1 for the right face (incoming mu < 0)."""
out = []
if face == "reflect":
for l in range(1, n + 1, 2):
out.append([1.0 if m == l else 0.0 for m in range(n + 1)])
elif bc == "mark":
mus, _ = gauss_legendre(n + 1)
for mu in mus[(n + 1) // 2:]:
p = legendre_all(n, sign * mu)
out.append([(2 * l + 1) / 2.0 * p[l] for l in range(n + 1)])
else:
h = half_range_moments(n)
for m in range(1, n + 1, 2):
out.append([(2 * l + 1) / 2.0 * h[m][l] * (sign ** l) for l in range(n + 1)])
return out
def pn_slab(n, sigma_t, sigma_s, q, dx, left="vacuum", right="vacuum", bc="marshak"):
"""Solve the slab P_n equations (n odd) with diamond differences.
Returns a dict with phi (cell averages of the scalar flux), moments (the
n + 1 moments at each of the M + 1 edges) and the leakages."""
if n % 2 == 0:
raise ValueError("n must be odd")
m = len(dx)
k = n + 1
a = moment_matrix(n) # @line L1
rows, rhs = [], []
for coeffs in _face_rows(n, left, bc, 1): # @line L2
rows.append({l: c for l, c in enumerate(coeffs) if c != 0.0})
rhs.append(0.0)
for j in range(m):
for l in range(k): # @line L3
sig = sigma_t[j] - (sigma_s[j] if l == 0 else 0.0)
row = {}
for c in range(k):
if a[l][c] != 0.0:
row[j * k + c] = row.get(j * k + c, 0.0) - a[l][c] / dx[j]
row[(j + 1) * k + c] = row.get((j + 1) * k + c, 0.0) + a[l][c] / dx[j]
row[j * k + l] = row.get(j * k + l, 0.0) + sig / 2.0
row[(j + 1) * k + l] = row.get((j + 1) * k + l, 0.0) + sig / 2.0
rows.append(row)
rhs.append(q[j] if l == 0 else 0.0)
for coeffs in _face_rows(n, right, bc, -1): # @line L4
rows.append({m * k + l: c for l, c in enumerate(coeffs) if c != 0.0})
rhs.append(0.0)
u = solve_sparse(rows, rhs) # @line L5
moments = [u[i * k:(i + 1) * k] for i in range(m + 1)]
phi = [(moments[j][0] + moments[j + 1][0]) / 2.0 for j in range(m)] # @line L6
return {"phi": phi, "moments": moments, "leak_left": -moments[0][1], "leak_right": moments[m][1]}
def angular_flux(moments, mu):
"""psi(mu) = sum (2l + 1) / 2 phi_l P_l(mu) from the moments at one point."""
p = legendre_all(len(moments) - 1, mu)
return sum((2 * l + 1) / 2.0 * v * p[l] for l, v in enumerate(moments))
def pn_determinant(n, c, kappa):
"""det(S - kappa A) for sigma_t = 1 and the scattering ratio c, by the three-term recurrence."""
d_prev, d = 1.0, 1.0 - c
for l in range(1, n + 1):
d_prev, d = d, d - kappa * kappa * l * l / ((2 * l + 1) * (2 * l - 1)) * d_prev
return d
def pn_decay_constant(n, c):
"""The smallest kappa > 0 with det(S - kappa A) = 0 (sigma_t = 1): solutions exp(-kappa x) of the infinite medium P_n equations."""
mus, _ = gauss_legendre(n + 1)
lo, hi = 0.0, 1.0 / mus[-1]
for _ in range(200):
mid = (lo + hi) / 2.0
if pn_determinant(n, c, mid) > 0.0:
lo = mid
else:
hi = mid
return (lo + hi) / 2.0
def sn_slab(n, sigma_t, sigma_s, q, dx, left="vacuum", right="vacuum", tol=1e-13, max_iter=10000):
"""Reference S_n solution with diamond differences by source iteration.
The reflected values are lagged by one iteration. Returns (phi, leak_left, leak_right)."""
mus, ws = gauss_legendre(n)
m = len(dx)
phi = [0.0] * m
back_l = {mu: 0.0 for mu in mus if mu > 0}
back_r = dict(back_l)
leak_l = leak_r = 0.0
for _ in range(max_iter):
src = [(sigma_s[j] * phi[j] + q[j]) / 2.0 for j in range(m)]
new = [0.0] * m
leak_l = leak_r = 0.0
for mu, w in zip(mus, ws):
psi = 0.0
if mu < 0 and right == "reflect":
psi = back_r[-mu]
if mu > 0 and left == "reflect":
psi = back_l[mu]
cells = range(m) if mu > 0 else range(m - 1, -1, -1)
for j in cells:
a = 2.0 * abs(mu) / dx[j]
c = (src[j] + a * psi) / (sigma_t[j] + a)
psi = 2.0 * c - psi
new[j] += w * c
if mu > 0:
leak_r += w * mu * psi
if right == "reflect":
back_r[mu] = psi
else:
leak_l += w * abs(mu) * psi
if left == "reflect":
back_l[-mu] = psi
change = max(abs(a - b) for a, b in zip(new, phi))
phi = new
if change <= tol * max(phi):
break
return phi, (0.0 if left == "reflect" else leak_l), (0.0 if right == "reflect" else leak_r)
test_spherical_harmonics_method.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spherical-harmonics-method/. The authors are listed in prov/HXR9T4.jsonl.
import math
import random
import unittest
from spherical_harmonics_method import (gauss_legendre, legendre_all, moment_matrix, pn_decay_constant,
pn_slab, sn_slab)
def uniform(m, length, c=0.9):
return [1.0] * m, [c] * m, [1.0] * m, [length / m] * m
class TestMoments(unittest.TestCase):
def test_eigenvalues_are_gauss_nodes(self):
for n in (1, 3, 5, 7, 9):
a = moment_matrix(n)
mus, _ = gauss_legendre(n + 1)
for mu in mus:
v = legendre_all(n, mu)
av = [sum(a[l][c] * v[c] for c in range(n + 1)) for l in range(n + 1)]
for l in range(n + 1):
self.assertAlmostEqual(av[l], mu * v[l], places=12)
def test_decay_constants(self):
for c in (0.5, 0.9, 0.99):
self.assertAlmostEqual(pn_decay_constant(1, c), math.sqrt(3.0 * (1.0 - c)), places=12)
values = [pn_decay_constant(n, 0.5) for n in (1, 3, 5, 7, 15)]
for a, b in zip(values, values[1:]):
self.assertGreater(a, b)
self.assertAlmostEqual(values[-1], 0.957504, delta=3e-5)
for n in (3, 7):
k = pn_decay_constant(n, 0.5)
mus, ws = gauss_legendre(n + 1)
self.assertAlmostEqual(0.25 * sum(w / (1.0 - (k * mu) ** 2) for mu, w in zip(mus, ws)), 1.0, places=10)
class TestSlab(unittest.TestCase):
def test_mark_equals_s_n_plus_1(self):
for n in (1, 3, 5):
st, ss, q, dx = uniform(40, 4.0)
p = pn_slab(n, st, ss, q, dx, bc="mark")
phi, _, leak = sn_slab(n + 1, st, ss, q, dx)
for a, b in zip(p["phi"], phi):
self.assertAlmostEqual(a, b, delta=1e-9)
self.assertAlmostEqual(p["leak_right"], leak, delta=1e-9)
p = pn_slab(3, st, ss, q, dx, "reflect", "vacuum", bc="mark")
phi, _, leak = sn_slab(4, st, ss, q, dx, "reflect", "vacuum")
for a, b in zip(p["phi"], phi):
self.assertAlmostEqual(a, b, delta=1e-9)
def test_mark_equals_s_n_plus_1_heterogeneous(self):
rng = random.Random(3)
m = 30
st = [rng.uniform(0.5, 4.0) for _ in range(m)]
ss = [s * rng.uniform(0.0, 0.9) for s in st]
q = [rng.uniform(0.0, 2.0) for _ in range(m)]
dx = [rng.uniform(0.05, 0.5) for _ in range(m)]
p = pn_slab(5, st, ss, q, dx, bc="mark")
phi, ll, lr = sn_slab(6, st, ss, q, dx)
for a, b in zip(p["phi"], phi):
self.assertAlmostEqual(a, b, delta=1e-9 * max(phi))
self.assertAlmostEqual(p["leak_left"], ll, delta=1e-9)
def test_p1_marshak_is_diffusion(self):
st, ss, q, dx = uniform(200, 10.0)
p = pn_slab(1, st, ss, q, dx)
kappa, d, half = math.sqrt(0.3), 1.0 / 3.0, 5.0
b = 1.0 / (2.0 * d * kappa * math.sinh(kappa * half) + math.cosh(kappa * half))
self.assertAlmostEqual(p["leak_right"], 10.0 * (1.0 - b * math.cosh(kappa * half)) / 2.0, delta=1e-5)
self.assertAlmostEqual(p["leak_right"], 1.329219, delta=1e-5)
def test_balance(self):
rng = random.Random(8)
m = 50
st = [rng.uniform(0.5, 4.0) for _ in range(m)]
ss = [s * rng.uniform(0.5, 0.99) for s in st]
q = [rng.uniform(0.0, 2.0) for _ in range(m)]
dx = [rng.uniform(0.05, 0.5) for _ in range(m)]
for bc in ("marshak", "mark"):
p = pn_slab(7, st, ss, q, dx, "vacuum", "vacuum", bc)
absorbed = sum((a - b) * f * h for a, b, f, h in zip(st, ss, p["phi"], dx))
source = sum(a * h for a, h in zip(q, dx))
self.assertAlmostEqual(absorbed + p["leak_left"] + p["leak_right"], source, delta=1e-10)
def test_infinite_medium(self):
p = pn_slab(5, [1.0] * 10, [0.9] * 10, [1.0] * 10, [1.0] * 10, "reflect", "reflect")
for v in p["phi"]:
self.assertAlmostEqual(v, 10.0, places=10)
for mom in p["moments"]:
for v in mom[1:]:
self.assertAlmostEqual(v, 0.0, places=10)
def test_convergence_in_n(self):
st, ss, q, dx = uniform(200, 2.0)
ref = 0.743626 # S16 with the same mesh
errors = [abs(pn_slab(n, st, ss, q, dx)["leak_right"] - ref) for n in (1, 3, 5, 7)]
for a, b in zip(errors, errors[1:]):
self.assertGreater(a, b)
self.assertLess(errors[-1], 5e-4)
self.assertGreater(errors[0], 0.02)
def test_even_n_rejected(self):
with self.assertRaises(ValueError):
pn_slab(2, [1.0], [0.5], [1.0], [1.0])
if __name__ == "__main__":
unittest.main()
History
Jeans introduced the spherical harmonics expansion for radiative transfer in stars in 1917. In neutron transport, Mark proposed the boundary condition at the roots of in reports of the 1940s, and Marshak (1947) proposed the conditions on half-range moments. The equivalence of and in slab geometry made the two methods two views of one approximation. The simplified equations were proposed by Gelbard around 1960. Lewis and Miller (1984) give the method and its boundary conditions in textbook form, and McClarren and Hauck (2010) are an example of the more recent work on filters that control the oscillations.
References
- E. E. Lewis and W. F. Miller, Jr., Computational Methods of Neutron Transport, Wiley, 1984, the chapter on the spherical harmonics method, its boundary conditions and its relation to discrete ordinates in slab geometry
- R. E. Marshak, Note on the spherical harmonic method as applied to the Milne problem for a sphere, Physical Review 71, 1947, 443-446, the boundary conditions on half-range moments of the incoming flux
- R. G. McClarren and C. D. Hauck, Robust and accurate filtered spherical harmonics expansions for radiative transfer, Journal of Computational Physics 229(16), 2010, 5597-5614, the oscillations and negative values of truncated expansions and the filters that damp them
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 HXR9T4 Edit this page History Report an error Markdown