Algorithm Search⌘K

Modelintro

Diffusion approximation of transport

Also called P1 approximation, neutron diffusion equation.

Approximates transport by a diffusion equation for the scalar flux, valid when scattering dominates and the flux is nearly isotropic.

The diffusion approximation replaces the transport equation for the angular flux ψ(x,Ω)\psi(x, \Omega) by a diffusion equation for the scalar flux ϕ(x)\phi(x) alone. Particles are assumed to move nearly the same amount in all directions, so the net current is proportional to the gradient of the flux (Fick's law), with the diffusion coefficient D=1/(3Σtr)D = 1/(3\Sigma_{tr}). The result is the steady heat equation with absorption, −∇⋅D∇ϕ+Σaϕ=q-\nabla\cdot D\nabla\phi + \Sigma_a\phi = q. It is exact in an infinite homogeneous medium, accurate in large media where scattering dominates, and wrong within a few mean free paths of a boundary, a source or a strong absorber. Reactor core design in two energy groups, the low-order operator of diffusion synthetic acceleration and radiative heat transfer in optically thick matter all use it. It is the lowest order of the spherical harmonics method.

The machine

Unknowns. The scalar flux ϕ(x)=∫ψ(x,Ω) dΩ\phi(x) = \int \psi(x, \Omega)\, d\Omega and the current J(x)=∫Ω ψ(x,Ω) dΩJ(x) = \int \Omega\, \psi(x, \Omega)\, d\Omega. In a slab with μ\mu the cosine of the direction, ϕ=∫−11ψ dμ\phi = \int_{-1}^{1}\psi\, d\mu and J=∫−11μ ψ dμJ = \int_{-1}^{1}\mu\,\psi\, d\mu.

Equations. The balance and Fick's law,

∇⋅J+Σa ϕ=q,J=−D ∇ϕ,D=13Σtr,Σtr=Σt−μˉ0 Σs,\nabla\cdot J + \Sigma_a\,\phi = q, \qquad J = -D\,\nabla\phi, \qquad D = \frac{1}{3\Sigma_{tr}}, \quad \Sigma_{tr} = \Sigma_t - \bar\mu_0\,\Sigma_s,

so −∇⋅(D∇ϕ)+Σaϕ=q-\nabla\cdot(D\nabla\phi) + \Sigma_a\phi = q. Here Σa=Σt−Σs\Sigma_a = \Sigma_t - \Sigma_s is the absorption cross section, μˉ0\bar\mu_0 is the mean cosine of the scattering angle, and qq is the isotropic source. For a k-eigenvalue problem, q=νΣfϕ/kq = \nu\Sigma_f\phi/k.

Derivation from transport. Take the slab equation μ ∂xψ+Σtψ=(Σsϕ+3μˉ0ΣsμJ+q)/2\mu\,\partial_x\psi + \Sigma_t\psi = (\Sigma_s\phi + 3\bar\mu_0\Sigma_s\mu J + q)/2, with scattering that is linearly anisotropic. Integrate it over μ\mu to get the balance J′+Σaϕ=qJ' + \Sigma_a\phi = q. Multiply it by μ\mu and integrate to get ddx∫μ2ψ dμ+ΣtJ=μˉ0ΣsJ\frac{d}{dx}\int\mu^2\psi\, d\mu + \Sigma_t J = \bar\mu_0\Sigma_s J. The P1P_1 closure takes ψ\psi linear in μ\mu, ψ=(ϕ+3μJ)/2\psi = (\phi + 3\mu J)/2, which gives ∫μ2ψ dμ=ϕ/3\int\mu^2\psi\, d\mu = \phi/3 and so J=−ϕ′/(3Σtr)J = -\phi'/(3\Sigma_{tr}). This is a theorem about the P1P_1 equations; the approximation is the closure itself.

Boundary conditions. A vacuum face has no incoming particles, but diffusion has only one condition per face, so it must approximate this:

  • Zero flux at the face: simple, too low, since the true flux does not vanish there.
  • Marshak: the incoming partial current J−=ϕ/4−J/2J^- = \phi/4 - J/2 is zero, that is Jout=ϕ/2J_{\mathrm{out}} = \phi/2 (with the convention ϕ=∫ψ dμ\phi = \int\psi\, d\mu). In the linear form this is the zero flux at the extrapolated distance 2D2D outside the face.
  • Milne extrapolation: zero flux at the distance 0.7104/Σt0.7104/\Sigma_t outside the face, the value from the exact solution of the half-space (Milne) problem with c=1c = 1 and isotropic scattering. Codes often use 0.7104/Σtr0.7104/\Sigma_{tr} for anisotropic scattering, which is a rule of thumb.
  • Reflection: J=0J = 0.

At an interface between materials, ϕ\phi and the normal current D ∂nϕD\,\partial_n\phi are continuous.

Discretization. The implementation uses cell-centered finite volumes (finite volume method) in a slab. The current through the face between cells jj and j+1j + 1 is (ϕj−ϕj+1)/R(\phi_j - \phi_{j+1})/R with R=Δxj/(2Dj)+Δxj+1/(2Dj+1)R = \Delta x_j/(2D_j) + \Delta x_{j+1}/(2D_{j+1}), a boundary face adds the resistance of its condition, and the tridiagonal system is solved by the Thomas algorithm. The kk value comes from power iteration on the fission source.

What it counts

The model predicts the scalar flux, the reaction rates Σxϕ\Sigma_x\phi and the currents, but not the angular distribution. It cannot represent a beam, a void, or the flux near a face. Its errors are measured against transport solutions or experiments.

The cost model is the real RAM, counting operations per cell. A diffusion solve has one unknown per cell, where a discrete ordinates solve has NN unknowns per cell and needs many sweeps. In a slab of MM cells the system is tridiagonal and costs O(M)O(M) operations; in two and three dimensions it is a sparse symmetric positive definite system, solved by conjugate gradients or by the multigrid method in close to O(M)O(M) operations. A kk-eigenvalue problem costs one solve per power iteration.

Relation to other models

  • Transport. The linear Boltzmann transport equation is the exact one-particle model; diffusion is its P1P_1 truncation. In an infinite homogeneous medium with a uniform source, both give ϕ=q/Σa\phi = q/\Sigma_a.
  • The diffusion limit. If Σt\Sigma_t is scaled by 1/ε1/\varepsilon, and Σa\Sigma_a and qq by ε\varepsilon, the transport solution tends to the solution of the diffusion equation as ε→0\varepsilon \to 0, away from boundary layers of a few mean free paths (Larsen and Keller 1974; a theorem of asymptotic analysis). Spatial schemes that keep this limit on cells many mean free paths thick, such as linear discontinuous finite elements, are said to have the thick diffusion limit; Adams and Larsen (2002) review which schemes have it.
  • PNP_N and SPNSP_N. The spherical harmonics method keeps more moments. P1P_1 in steady state is diffusion; time dependent P1P_1 is a telegraph equation with a finite signal speed, while time dependent diffusion has an infinite one. The simplified SPNSP_N equations replace the one-dimensional derivatives of slab PNP_N by gradients, which gives coupled diffusion equations.
  • Discrete ordinates. In a thick diffusive medium the slow modes of source iteration are the smooth solutions of the diffusion equation, which is why diffusion synthetic acceleration removes them.
  • Energy. With the multigroup approximation, each group has its own DgD_g and Σa,g\Sigma_{a,g}, and the groups are coupled by scattering and fission. Two-group diffusion is the classical model of a thermal reactor.

Known results in the model

Fick's law from P1P_1 (theorem). If ψ\psi is linear in μ\mu and the scattering is at most linearly anisotropic, the first moment equation is exactly J=−Dϕ′J = -D\phi' with D=1/(3Σtr)D = 1/(3\Sigma_{tr}) (the derivation above).

The infinite medium (theorem). With reflecting faces, Σa=0.1\Sigma_a = 0.1, D=1/3D = 1/3 and q=1q = 1, the discrete solution is ϕ=10\phi = 10 in every cell, the value q/Σaq/\Sigma_a of transport.

The bare slab (theorem and measurement). A homogeneous slab with Σt=1\Sigma_t = 1, Σa=0.1\Sigma_a = 0.1, νΣf=0.12\nu\Sigma_f = 0.12 and width L=20L = 20 cm has k∞=1.2k_\infty = 1.2 and, with ϕ=0\phi = 0 at the faces, k=νΣf/(Σa+D(π/L)2)=1.108804k = \nu\Sigma_f/(\Sigma_a + D(\pi/L)^2) = 1.108804. The finite volume kk is 1.10897761.1089776, 1.10884781.1088478, 1.10881531.1088153 and 1.10880721.1088072 with 20, 40, 80 and 160 cells, so the error falls by 4 per halving of the cells, which is second order. The boundary condition matters more than the mesh:

face condition width used for the buckling kk
zero flux at the face 20 1.108804
Marshak, 2D2D outside 21.3333 1.119103
Milne, 0.71040.7104 outside 21.4208 1.119719
transport, S16S_{16} with 320 cells 1.120062

The transport value is the measurement of the k-eigenvalue problem page. The Milne distance gives kk within 3.5×10−43.5 \times 10^{-4} of transport, and the zero flux condition is 1% low.

A slab with a source (measurement). Take Σt=1\Sigma_t = 1, c=0.9c = 0.9 (Σa=0.1\Sigma_a = 0.1), q=1q = 1 and vacuum faces. Diffusion with Marshak faces has an exact solution, and the transport values come from S16S_{16} with diamond difference on 200 cells:

width (mean free paths) leakage per face, diffusion leakage per face, transport center flux, diffusion center flux, transport
2 0.770383 0.743626 2.668293 3.009311
10 1.329219 1.296145 9.054542 9.038785
40 1.337394 1.305766 9.999744 9.999639

In the thick slabs the center agrees to 2×10−32 \times 10^{-3} and better, and the leakage is about 2.5% high. In the thin slab of 2 mean free paths the center flux is 11% low, because most of the slab is boundary layer.

The decay length (theorem). In a source-free medium the flux far from sources decays like e−κΣtxe^{-\kappa\Sigma_t x}. Diffusion gives κ2=3(1−c)\kappa^2 = 3(1 - c), and exact one-speed transport gives the root of c artanh(κ)/κ=1c\,\mathrm{artanh}(\kappa)/\kappa = 1. Both agree to first order in 1−c1 - c:

cc diffusion κ\kappa transport κ\kappa ratio
0.5 1.224745 0.957504 1.2791
0.9 0.547723 0.525430 1.0424
0.99 0.173205 0.172511 1.0040
0.999 0.054772 0.054750 1.0004

So diffusion describes the flux well only when cc is near 1, that is when particles scatter many times before they are absorbed.

The diffusion limit (measurement). In a slab of width 1 with Σt=1/ε\Sigma_t = 1/\varepsilon, Σa=ε\Sigma_a = \varepsilon, q=εq = \varepsilon and vacuum faces, the center flux of S8S_8 with 300 cells and of diffusion with Marshak faces is 0.3442420.344242 and 0.3386270.338627 for ε=0.1\varepsilon = 0.1, 0.3033710.303371 and 0.3021260.302126 for ε=0.03\varepsilon = 0.03, and 0.2913120.291312 and 0.2909450.290945 for ε=0.01\varepsilon = 0.01. The gap shrinks as ε→0\varepsilon \to 0, as the theorem of Larsen and Keller predicts.

Rules of thumb. Diffusion is accurate more than about two or three mean free paths from boundaries, sources and strong absorbers, and when the absorption is small compared with the scattering. These are rules of thumb from reactor physics, not theorems; the tables above show their size in one-speed slabs.

Code

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.

diffusion_approximation_of_transport.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diffusion-approximation-of-transport/. The authors are listed in prov/P2WTRA.jsonl.
"""The one-speed diffusion approximation in a slab, solved by cell-centered finite volumes.

    -d/dx (D dphi/dx) + sigma_a phi = q,   J = -D dphi/dx (Fick's law),
    D = 1 / (3 sigma_tr),  sigma_tr = sigma_t - mu_bar sigma_s.

Cells j = 0 .. M - 1 of widths dx[j] carry constant data. The current through
the face between cells j and j + 1 is (phi_j - phi_(j+1)) / R with the
resistance R = dx_j / (2 D_j) + dx_(j+1) / (2 D_(j+1)), so the scheme is
exact for a flux that is linear in each cell and keeps the particle balance
of every cell.

Face conditions, for the current that leaves the slab:
    "zero"     phi = 0 on the face:              J_out = phi_cell / (dx / (2 D))
    "marshak"  vacuum, Marshak condition J_out = phi_face / 2, which is phi = 0 at the extrapolated distance 2 D
    a number d phi = 0 at the distance d outside the face: J_out = phi_cell / (dx / (2 D) + d / D)
    "reflect"  J_out = 0

The tridiagonal system is solved by the Thomas algorithm of the shared helper scisparse.
"""

import math

from scisparse import thomas

MILNE = 0.7104461  # the extrapolation distance of the Milne problem in mean free paths, c = 1


def diffusion_coefficient(sigma_t, sigma_s=0.0, mu_bar=0.0):
    """D = 1 / (3 sigma_tr) with the transport cross section sigma_tr = sigma_t - mu_bar sigma_s."""
    return 1.0 / (3.0 * (sigma_t - mu_bar * sigma_s))


def _face_resistance(bc, d, h):
    """Resistance from the cell center to the point where phi = 0, or None for no leakage."""
    if bc == "reflect":
        return None
    if bc == "zero":
        return h / (2.0 * d)
    if bc == "marshak":
        return h / (2.0 * d) + 2.0
    return h / (2.0 * d) + float(bc) / d


def solve_fixed_source(D, sigma_a, q, dx, left="marshak", right="marshak"):
    """Solve the diffusion equation with the cell data D, sigma_a and q.

    Returns (phi, leak_left, leak_right), the leakages being the currents that leave each face."""
    m = len(dx)
    a, b, c, rhs = [0.0] * m, [0.0] * m, [0.0] * m, [0.0] * m
    for j in range(m):
        b[j] = sigma_a[j] * dx[j]
        rhs[j] = q[j] * dx[j]
    for j in range(m - 1):
        g = 1.0 / (dx[j] / (2.0 * D[j]) + dx[j + 1] / (2.0 * D[j + 1]))
        b[j] += g
        b[j + 1] += g
        c[j] -= g
        a[j + 1] -= g
    rl = _face_resistance(left, D[0], dx[0])
    rr = _face_resistance(right, D[-1], dx[-1])
    if rl is not None:
        b[0] += 1.0 / rl
    if rr is not None:
        b[-1] += 1.0 / rr
    phi = thomas(a, b, c, rhs)
    leak_left = phi[0] / rl if rl is not None else 0.0
    leak_right = phi[-1] / rr if rr is not None else 0.0
    return phi, leak_left, leak_right


def k_eigenvalue(D, sigma_a, nu_sigma_f, dx, left="zero", right="zero", tol=1e-12, max_iter=10000):
    """Power iteration on the fission source. Returns (k, phi normalized to max 1, iterations)."""
    m = len(dx)
    phi = [1.0] * m
    k = 1.0
    for it in range(1, max_iter + 1):
        src = [nu_sigma_f[j] * phi[j] / k for j in range(m)]
        new, _, _ = solve_fixed_source(D, sigma_a, src, dx, left, right)
        prod_old = sum(nu_sigma_f[j] * phi[j] * dx[j] for j in range(m))
        prod_new = sum(nu_sigma_f[j] * new[j] * dx[j] for j in range(m))
        k_new = k * prod_new / prod_old
        top = max(new)
        phi = [v / top for v in new]
        if abs(k_new - k) <= tol * k_new:
            return k_new, phi, it
        k = k_new
    return k, phi, max_iter


def bare_slab_k(nu_sigma_f, sigma_a, D, width):
    """k of a bare homogeneous slab with phi = 0 at the faces of the given width: buckling (pi / width)^2."""
    return nu_sigma_f / (sigma_a + D * (math.pi / width) ** 2)


def slab_leakage_marshak(q, sigma_a, D, width):
    """Exact diffusion leakage through each face of a homogeneous slab with a uniform source and Marshak faces.

    phi = (q / sigma_a) (1 - A cosh(kappa (x - width / 2))), kappa = sqrt(sigma_a / D),
    A = 1 / (cosh(kappa width / 2) + 2 D kappa sinh(kappa width / 2))."""
    kappa = math.sqrt(sigma_a / D)
    h = kappa * width / 2.0
    amp = 1.0 / (math.cosh(h) + 2.0 * D * kappa * math.sinh(h))
    return q / sigma_a * D * amp * kappa * math.sinh(h)


def diffusion_decay_constant(c):
    """kappa in units of sigma_t for phi ~ exp(-kappa sigma_t x) in a source-free medium: kappa^2 = 3 (1 - c)."""
    return math.sqrt(3.0 * (1.0 - c))


def transport_decay_constant(c):
    """The exact one-speed transport value: the root kappa in (0, 1) of c atanh(kappa) / kappa = 1, for 0 < c < 1."""
    lo, hi = 1e-15, 1.0 - 1e-16
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if c * math.atanh(mid) / mid < 1.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)
scisparse.py 189 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Tridiagonal solvers, sparse matrices and simple iterative solvers.

A vector is a list. A sparse matrix is a list of rows, and each row is a
dict that maps a column index to a value. Entries may be int, float or
fractions.Fraction. thomas, thomas_periodic, spmatvec, from_dense and
to_dense keep Fraction entries exact. cg takes square roots and works in
float.

API (fixed; other pages copy this file byte for byte):
    thomas(a, b, c, d)             solve a tridiagonal system. Row i reads
                                   a[i] x[i-1] + b[i] x[i] + c[i] x[i+1] = d[i];
                                   a[0] and c[n-1] are not used.
    thomas_periodic(a, b, c, d)    solve a cyclic tridiagonal system: as
                                   thomas, but a[0] multiplies x[n-1] and
                                   c[n-1] multiplies x[0]. Uses the
                                   Sherman-Morrison formula. n >= 3.
    from_dense(A)                  sparse copy of a dense matrix (drops zeros)
    to_dense(A, ncols=None)        dense copy of a sparse matrix
    spmatvec(A, x)                 A times x
    poisson2d(nx, ny, dx, dy, bc="dirichlet")
                                   the matrix of MINUS the 5-point Laplacian
                                   on nx by ny unknowns, numbered
                                   k = i + nx * j (i along x, j along y).
                                   bc = "dirichlet": unknowns at the interior
                                   nodes ((i + 1) dx, (j + 1) dy) with zero
                                   values outside; the matrix is symmetric
                                   positive definite.
                                   bc = "periodic": the grid wraps around in
                                   both directions; the matrix is symmetric
                                   positive semidefinite, and its null space
                                   is the constant vectors.
                                   bc = "neumann": unknowns at cell centers,
                                   zero normal derivative at the walls (a
                                   missing neighbor drops out of the
                                   stencil); null space as for "periodic".
    cg(A, b, tol=1e-10, maxit=None, x0=None)
                                   conjugate gradient for a symmetric
                                   positive (semi)definite A. Stops when
                                   ||b - A x||_2 <= tol * ||b||_2. Returns
                                   (x, iterations). For a singular A, b must
                                   be in the range of A (for the Poisson
                                   matrices above: sum(b) = 0).
    gauss_seidel(A, b, iters, x0=None)
                                   iters forward Gauss-Seidel sweeps; every
                                   row needs a nonzero diagonal entry.
"""

import math


def thomas(a, b, c, d):
    n = len(d)
    if n == 0:
        return []
    cp = [0] * n
    dp = [0] * n
    cp[0] = c[0] / b[0] if n > 1 else 0
    dp[0] = d[0] / b[0]
    for i in range(1, n):
        m = b[i] - a[i] * cp[i - 1]
        if i < n - 1:
            cp[i] = c[i] / m
        dp[i] = (d[i] - a[i] * dp[i - 1]) / m
    x = [0] * n
    x[n - 1] = dp[n - 1]
    for i in range(n - 2, -1, -1):
        x[i] = dp[i] - cp[i] * x[i + 1]
    return x


def thomas_periodic(a, b, c, d):
    """Cyclic tridiagonal solve. A = T + u v^T with u = (gamma, 0, .., 0, c[n-1])
    and v = (1, 0, .., 0, a[0] / gamma), so T is tridiagonal."""
    n = len(d)
    if n < 3:
        raise ValueError("thomas_periodic needs n >= 3")
    gamma = -b[0]
    bb = list(b)
    bb[0] = b[0] - gamma
    bb[n - 1] = b[n - 1] - c[n - 1] * a[0] / gamma
    y = thomas(a, bb, c, d)
    u = [0] * n
    u[0] = gamma
    u[n - 1] = c[n - 1]
    z = thomas(a, bb, c, u)
    vy = y[0] + a[0] * y[n - 1] / gamma
    vz = z[0] + a[0] * z[n - 1] / gamma
    f = vy / (1 + vz)
    return [y[i] - f * z[i] for i in range(n)]


def from_dense(A):
    return [{j: v for j, v in enumerate(row) if v != 0} for row in A]


def to_dense(A, ncols=None):
    if ncols is None:
        ncols = len(A)
    out = []
    for row in A:
        r = [0] * ncols
        for j, v in row.items():
            r[j] = v
        out.append(r)
    return out


def spmatvec(A, x):
    return [sum(v * x[j] for j, v in row.items()) for row in A]


def poisson2d(nx, ny, dx, dy, bc="dirichlet"):
    if bc not in ("dirichlet", "periodic", "neumann"):
        raise ValueError("bc must be dirichlet, periodic or neumann")
    cx = 1 / (dx * dx)
    cy = 1 / (dy * dy)
    A = []
    for j in range(ny):
        for i in range(nx):
            row = {}
            k = i + nx * j
            for (ii, jj, w) in ((i - 1, j, cx), (i + 1, j, cx), (i, j - 1, cy), (i, j + 1, cy)):
                inside = 0 <= ii < nx and 0 <= jj < ny
                if bc == "periodic":
                    ii %= nx
                    jj %= ny
                    inside = True
                if bc == "neumann" and not inside:
                    continue
                row[k] = row.get(k, 0) + w
                if inside:
                    m = ii + nx * jj
                    row[m] = row.get(m, 0) - w
            A.append({m: v for m, v in row.items() if v != 0})
    return A


def cg(A, b, tol=1e-10, maxit=None, x0=None):
    n = len(b)
    if maxit is None:
        maxit = 10 * n
    x = [0.0] * n if x0 is None else [float(v) for v in x0]
    if x0 is None:
        r = [float(v) for v in b]
    else:
        ax = spmatvec(A, x)
        r = [b[i] - ax[i] for i in range(n)]
    bnorm = math.sqrt(sum(float(v) * float(v) for v in b))
    stop = tol * bnorm
    rr = sum(v * v for v in r)
    if math.sqrt(rr) <= stop:
        return x, 0
    p = list(r)
    for it in range(1, maxit + 1):
        ap = spmatvec(A, p)
        pap = sum(p[i] * ap[i] for i in range(n))
        if pap <= 0:
            return x, it
        alpha = rr / pap
        for i in range(n):
            x[i] += alpha * p[i]
            r[i] -= alpha * ap[i]
        rr_new = sum(v * v for v in r)
        if math.sqrt(rr_new) <= stop:
            return x, it
        beta = rr_new / rr
        rr = rr_new
        p = [r[i] + beta * p[i] for i in range(n)]
    return x, maxit


def gauss_seidel(A, b, iters, x0=None):
    n = len(b)
    x = [0] * n if x0 is None else list(x0)
    for _ in range(iters):
        for i in range(n):
            row = A[i]
            s = b[i]
            diag = 0
            for j, v in row.items():
                if j == i:
                    diag = v
                else:
                    s -= v * x[j]
            x[i] = s / diag
    return x
test_diffusion_approximation_of_transport.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diffusion-approximation-of-transport/. The authors are listed in prov/P2WTRA.jsonl.
import math
import random
import unittest

from diffusion_approximation_of_transport import (MILNE, bare_slab_k, diffusion_coefficient,
                                                  diffusion_decay_constant, k_eigenvalue,
                                                  slab_leakage_marshak, solve_fixed_source,
                                                  transport_decay_constant)

D = 1.0 / 3.0


class TestModel(unittest.TestCase):
    def test_diffusion_coefficient(self):
        self.assertAlmostEqual(diffusion_coefficient(1.0), 1.0 / 3.0, places=15)
        # linearly anisotropic scattering lowers the transport cross section
        self.assertAlmostEqual(diffusion_coefficient(1.0, 0.9, 0.5), 1.0 / (3.0 * 0.55), places=15)

    def test_bare_slab_check_value(self):
        self.assertAlmostEqual(bare_slab_k(0.12, 0.1, D, 20.0), 1.108804, places=6)
        self.assertAlmostEqual(bare_slab_k(0.12, 0.1, D, 20.0 + 2.0 * MILNE), 1.119719, places=6)
        self.assertAlmostEqual(bare_slab_k(0.12, 0.1, D, 1e9), 1.2, places=9)

    def test_decay_constants(self):
        for c in (0.5, 0.9, 0.99, 0.999):
            kt = transport_decay_constant(c)
            self.assertAlmostEqual(c * math.atanh(kt) / kt, 1.0, places=12)
            kd = diffusion_decay_constant(c)
            self.assertGreater(kd, kt)
        self.assertAlmostEqual(transport_decay_constant(0.5), 0.957504, places=6)
        self.assertAlmostEqual(diffusion_decay_constant(0.9) / transport_decay_constant(0.9), 1.042428, places=6)
        self.assertLess(diffusion_decay_constant(0.999) / transport_decay_constant(0.999), 1.0005)


class TestSolver(unittest.TestCase):
    def test_infinite_medium(self):
        phi, ll, lr = solve_fixed_source([D] * 10, [0.1] * 10, [1.0] * 10, [1.0] * 10, "reflect", "reflect")
        for p in phi:
            self.assertAlmostEqual(p, 10.0, places=12)
        self.assertEqual((ll, lr), (0.0, 0.0))

    def test_balance_on_a_random_slab(self):
        rng = random.Random(2)
        m = 60
        d = [rng.uniform(0.1, 2.0) for _ in range(m)]
        sa = [rng.uniform(0.01, 1.0) for _ in range(m)]
        q = [rng.uniform(0.0, 3.0) for _ in range(m)]
        dx = [rng.uniform(0.05, 1.0) for _ in range(m)]
        for left, right in (("marshak", "zero"), ("reflect", 0.71), ("zero", "reflect")):
            phi, ll, lr = solve_fixed_source(d, sa, q, dx, left, right)
            absorbed = sum(s * p * h for s, p, h in zip(sa, phi, dx))
            source = sum(s * h for s, h in zip(q, dx))
            self.assertAlmostEqual(absorbed + ll + lr, source, delta=1e-11 * source)
            self.assertGreater(min(phi), 0.0)

    def test_fixed_source_leakage_is_second_order(self):
        exact = slab_leakage_marshak(1.0, 0.1, D, 10.0)
        errs = []
        for m in (25, 50, 100, 200):
            _, ll, lr = solve_fixed_source([D] * m, [0.1] * m, [1.0] * m, [10.0 / m] * m)
            self.assertAlmostEqual(ll, lr, places=12)
            errs.append(abs(lr - exact))
        for a, b in zip(errs, errs[1:]):
            self.assertAlmostEqual(a / b, 4.0, delta=0.1)
        self.assertAlmostEqual(exact, 1.329219, places=6)

    def test_bare_slab_k_is_second_order(self):
        exact = bare_slab_k(0.12, 0.1, D, 20.0)
        errs = []
        for m in (20, 40, 80):
            k, phi, _ = k_eigenvalue([D] * m, [0.1] * m, [0.12] * m, [20.0 / m] * m)
            errs.append(k - exact)
            self.assertAlmostEqual(phi[m // 2 - 1], phi[m // 2], places=9)
        self.assertAlmostEqual(errs[0], 1.731e-4, delta=1e-7)
        for a, b in zip(errs, errs[1:]):
            self.assertAlmostEqual(a / b, 4.0, delta=0.05)

    def test_extrapolated_faces(self):
        m = 80
        km, _, _ = k_eigenvalue([D] * m, [0.1] * m, [0.12] * m, [20.0 / m] * m, "marshak", "marshak")
        self.assertAlmostEqual(km, bare_slab_k(0.12, 0.1, D, 20.0 + 4.0 * D), delta=5e-5)
        kl, _, _ = k_eigenvalue([D] * m, [0.1] * m, [0.12] * m, [20.0 / m] * m, MILNE, MILNE)
        self.assertAlmostEqual(kl, bare_slab_k(0.12, 0.1, D, 20.0 + 2.0 * MILNE), delta=5e-5)
        self.assertLess(km, kl)


if __name__ == "__main__":
    unittest.main()

References

  1. E. E. Lewis and W. F. Miller, Jr., Computational Methods of Neutron Transport, Wiley, 1984, the sections on the P1 equations, the diffusion approximation and its boundary conditions
  2. J. J. Duderstadt and L. J. Hamilton, Nuclear Reactor Analysis, Wiley, 1976, the chapters on one-speed diffusion theory, the extrapolated boundary and the criticality of bare reactors
  3. E. W. Larsen and J. B. Keller, Asymptotic solution of neutron transport problems for small mean free paths, Journal of Mathematical Physics 15(1), 1974, 75-81, the asymptotic limit in which the transport solution tends to the solution of a diffusion equation, with boundary layers
  4. 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 for the spherical harmonics equations
  5. Marvin L. Adams and Edward W. Larsen, Fast iterative methods for discrete-ordinates particle transport calculations, Progress in Nuclear Energy 40(1), 2002, 3-159, the role of the diffusion limit in the analysis of source iteration and of diffusion synthetic acceleration

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/P2WTRA/text.yaml