Algorithmadvanced
Diffusion synthetic acceleration
Speeds up source iteration by correcting each iterate with a diffusion solve for the error, which captures the slowly converging smooth modes.
- Time
- O(I N M) worst
- Space
- O(M) extra
- Where
- I = the number of iterations; M = the number of cells; N = the number of directions
- Model
- Real RAM
- Properties
- deterministicnot exactiterativenot randomized
- Evidence
- Proof sketchCode in 1 languages
Diffusion synthetic acceleration (DSA) makes source iteration fast in thick scattering media. Source iteration removes the error modes that vary fast in space in a few sweeps, but it damps the smooth modes only by the factor , the scattering ratio, per sweep. These smooth modes are the ones that the diffusion approximation describes well. So after each sweep DSA solves a diffusion equation for the error, with the change of the scattering source as its source, and adds the result to the flux. One diffusion solve costs much less than a sweep. In an infinite medium the error then falls by at most about per iteration instead of . This holds on the discrete level only if the diffusion equation is discretized consistently with the transport scheme; a diffusion equation that is discretized on its own can make the iteration diverge in thick cells.
In plain words
Source iteration follows the particles one bounce at a time. In a thick material where almost every collision is a bounce, you need hundreds of sweeps.
The slow part of the error is smooth: it changes slowly from cell to cell. A diffusion equation gets smooth errors right, and it is cheap to solve. So after each sweep you solve a diffusion equation for the error and add that guess to the flux.
The sweep removes the rough part of the error and the diffusion solve removes the smooth part. Together they cut the error by about five times in each step, however thick the material is. The catch: the diffusion equation must be built from the same cell equations as the sweep. If it is built in another way, the two parts disagree in thick cells, and the iteration can blow up.
The problem
The model is the one-speed slab problem of the source iteration page. The slab has cells with the widths , the total and scattering cross sections and in , the absorption and an isotropic source . The directions and weights are the -point Gauss-Legendre rule with even, the weights sum to 2, and the equations are
with diamond difference in space. Each face is vacuum or reflecting. Write for these equations, as on the source iteration page. The problem is to find the same solution as source iteration, in far fewer sweeps, when is near 1 and the slab is many mean free paths thick.
The algorithm
DSA(N, Σt, Σs, q, h, faces, tol, φ0)- 1
φ_j ← φ0_j (or 0) for every cell j - 2
repeat - 3
S_j ← (Σs_j φ_j + q_j) / 2 for every cell j ▷ the scattering source of the last iterate - 4
φ½ ← SWEEP(S) ▷ one transport sweep of all directions - 5
R_j ← Σs_j (φ½_j - φ_j) for every cell j ▷ the source of the remaining error - 6
f ← the solution of -d/dx (D df/dx) + Σa f = R, discretized consistently with diamond difference; D = 1/(3Σt) - 7
φ_new ← φ½ + f; d ← max_j |φ_new_j - φ_j|; φ ← φ_new - 8
until d ≤ tol · max_j |φ_j| (or d is not finite)
Line L4 is the transport sweep of the source iteration page, with the reflected values solved exactly. Line L5 is the change of the scattering source in this sweep. The error that is left, , solves the transport equation with this source, and line L6 replaces that transport problem by a diffusion problem.
Line L6 is the part that makes DSA work. Its unknowns are the values at the cell edges. Write and . The row of the inner edge between the cells and is
A face row keeps the terms of its one cell, and a vacuum face adds 1 to its diagonal entry (the Marshak condition: no particles enter). The correction in cell is . These rows are the diamond difference P1 equations with the current eliminated (Theorem 2 of the proof), which is the method of Alcouffe (1977). The system is tridiagonal, symmetric and positive definite, and the Thomas algorithm solves it in operations.
The implementation also has the usual cell-centered diffusion equation as the option "inconsistent", with the face coefficient . It is a correct discretization of diffusion, but it does not match diamond difference.
Example
An infinite medium by hand. Take , , , both faces reflecting and . Line L3 gives , and the sweep gives in every direction, so . Line L5 gives . The source is flat, so the diffusion solution has no gradient: , . Line L7 gives , the exact solution, after one iteration. Source iteration needs 154 iterations to reach a change of in the same problem.
The Fourier factors. In an infinite homogeneous medium the error mode is multiplied by in each source iteration and by in each DSA iteration (Theorem 5 of the proof). For :
| source iteration, continuous | DSA, continuous | source iteration, | DSA, | |
|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 0 |
| 0.5 | 0.927295 | 0.054838 | 0.927295 | 0.054838 |
| 1 | 0.785398 | 0.141593 | 0.785397 | 0.141589 |
| 2.525 | 0.472756 | 0.224665 | 0.471030 | 0.222127 |
| 5 | 0.274680 | 0.187642 | 0.254061 | 0.164548 |
| 20 | 0.076042 | 0.069112 | 0.029043 | 0.021761 |
Source iteration is slow for small , the smooth modes. DSA is worst at , where neither the sweep nor diffusion is good, and the largest factor is . The largest factor over all is .
Thick cells. Take , , 100 equal cells, vacuum faces and . The Fourier columns are the largest factor over all modes on a reflecting slab of equal cells (Theorems 5 and 7 of the proof). The measured columns are the ratio of the last two changes after 40 iterations from a rough start (300 for source iteration).
| consistent, Fourier | consistent, measured | inconsistent, Fourier | inconsistent, measured | source iteration, measured | |
|---|---|---|---|---|---|
| 0.1 | 0.2190 | 0.2118 | 0.2152 | 0.2082 | 0.9659 |
| 1 | 0.2190 | 0.2137 | 0.7370 | 0.7161 | 0.9900 |
| 10 | 0.2190 | 0.2141 | 42.42 | 40.37 | 0.9899 |
The consistent scheme has the same rate for every cell size. The inconsistent one is as good for thin cells, slow for cells of one mean free path, and diverges for thick cells. Its rate for thick cells is near , which exceeds 1 once .
Iterations to convergence. With , , , vacuum faces and :
| slab | cells | source iteration | consistent DSA | inconsistent DSA | leakage at |
|---|---|---|---|---|---|
| 10 mean free paths | 40 | 437 | 11 | 10 | 3.70841381 |
| 100 mean free paths | 400 | 1356 | 10 | 10 | 5.13942747 |
The cells here are 0.25 mean free paths, so both DSA schemes work. In a heterogeneous slab of 60 cells with random in , in , widths in cm, one reflecting and one vacuum face, consistent DSA reaches in 17 iterations, source iteration needs 2188, and inconsistent DSA overflows after 266 iterations.
Correctness
The proofs are in the proof file. If is the diamond difference solution, the DSA error satisfies , where is the diffusion solve of line L6. So the exact solution is a fixed point, and DSA converges to the same answer as source iteration whenever the spectral radius of this map is below 1 (Theorem 3). The edge system of line L6 is exactly the diamond difference P1 system with the current eliminated, and it is symmetric positive definite if some cell absorbs or some face is vacuum (Theorems 1 and 2). For with reflecting faces, P1 and are the same equations, so one DSA iteration gives the exact solution in any heterogeneous slab (Theorem 4). On equal cells with reflecting faces, the cosine modes are eigenvectors, the flat mode is removed in one step, and the eigenvalue is the factor of the equations exact in space at (Theorem 5). From this, for every cell size, with (Theorem 6). The inconsistent scheme has a different factor, which exceeds 1 for thick cells (Theorem 7).
Proof: Consistent DSA keeps the transport solution, its diffusion equation is the diamond difference P1 system, it is exact for S2 with reflection, and its Fourier factor is below the scattering ratio for every cell sizefull
We assume exact arithmetic. The slab, the cross sections and the lines L1 to L8 are those of the page. Cell has , , the absorption and the width , and it lies between the edges and . The directions and weights are the -point Gauss-Legendre rule with even, so the weights are positive, they sum to 2, and the rule is exact for : .
As in the source iteration proof, line L4 with the source of line L3 is the affine map . Here sweeps the source with zero incoming data and the same reflection, and sweeps with the given data. That proof shows that the sweep with exact reflection has exactly one solution (its Lemma 1) and that, if in every cell, the diamond difference equations have exactly one solution (its Theorem 3).
The diffusion equation for the correction
Write and . The consistent correction of line L6 solves the edge system with the rows
at the inner edge between the cells and . The face rows keep only the terms of the one cell next to the face, and a vacuum face adds 1 to its diagonal entry. The cell correction is .
Theorem 1 (the edge system is symmetric positive definite). If some cell has or some face is vacuum, then is symmetric positive definite. So line L6 has exactly one solution, and the tridiagonal elimination without pivoting computes it.
Proof. Each cell adds the matrix to the rows and columns of its two edges. This gives the entries of (1). So
If the form is 0, then for every because , so is a constant . Then a cell with or a vacuum face gives . So is positive definite. The pivots of the elimination are ratios of leading principal minors, which are positive for such a matrix.
Theorem 2 (the edge system is the diamond difference P1 system). Consider the P1 equations for a flux and a current with one value at each edge, the source in cell , and diamond difference in space:
with at a reflecting face and the Marshak condition or at a vacuum face. Then solves these equations if and only if solves the edge system, with given by (3) below.
Proof. In cell , the two equations (2) give the sum and the difference of the currents at its edges: and . So the cell fixes the currents at its edges:
At an inner edge , the value from cell must equal the value from cell . Multiply this equation by 2 and move all terms to the left: this is (1). At a reflecting face , in (3) gives , the face row. At a vacuum face, gives the same row with added to the coefficient of . The face is the mirror case. Each step can be reversed, so the two systems have the same solutions.
The Marshak condition is the P1 form of "no particles enter": with , the incoming current at is , and it is zero when .
The same fixed point
Theorem 3 (DSA keeps the transport solution). Let be the diamond difference solution, , and let be the linear map from the residual to the correction of line L6. The error of DSA satisfies
So is a fixed point of lines L3 to L7, and the iteration converges to from every start if and only if the spectral radius of is less than 1.
Proof. Line L4 gives , so . Line L5 gives . Line L7 adds and subtracts nothing else. So . The last claim is the standard fact for a linear iteration with a fixed matrix.
Theorem 4 (S2 with reflection is exact in one iteration). Let , let both faces reflect, let every cell have , and let the cross sections and widths vary from cell to cell. Then from any , one DSA iteration gives the diamond difference solution .
Proof. Let . Since and , we have . Here is the sweep of the source . So is the scalar flux of the diamond difference problem with scattering , the source in place of and reflection at both faces. By the source iteration proof, this problem has exactly one solution.
The rule has and the weights 1 and 1. Write and at each edge. The diamond difference equations of the two directions in cell are , with the cell values equal to the mean of the edge values. Their sum, times , is the first equation (2). Their difference, times and with , is the second equation (2). Reflection is . The change of variables is invertible, . So the problem and the P1 problem (2) are the same system. By Theorem 2 its solves the edge system, and its cell flux is the mean of the edge values, which is the correction of line L6. Since , Theorem 1 says that this correction is unique. So , and line L7 gives .
With vacuum faces the claim fails: with no incoming particles gives , while line L6 uses the Marshak value . The tests measure a relative error of about 2 percent after one step in that case.
Fourier analysis
Theorem 5 (the factor of consistent DSA). Let the slab have equal cells of width with the same and , let , and let both faces reflect. For let , and . Then is an eigenvector of the DSA error map of Theorem 3 with the eigenvalue
Proof. By Theorem 5 of the source iteration proof, . So with . Try the edge values for . All cells have the same and . Since , the left side of (1) is
and since , the right side is . At the face both sides are half of these values with , and at they are half of them with . So every row holds if
Since , and the bracket is positive, so this fixes . By Theorem 1 (here ) it is the solution. The cell correction is . Divide the equation for by and use :
Line L7 adds this to .
The vectors are orthogonal, so they are all the eigenvectors in this case, and the spectral radius is the largest over the values of .
Corollary (the flat mode). For , and , so . The mode that source iteration damps the least, by the factor , is removed in one step. In particular, in a homogeneous slab with both faces reflecting and a flat source, one DSA iteration from a flat start gives the exact solution.
Write , so . A short computation gives the second form
The factor of the diamond difference scheme is the factor of the equations exact in space, evaluated at . As runs over , runs over for every cell size. As , , which gives the factor of the continuous problem.
Theorem 6 (a bound for every cell size). Let . Then , and for every and (with if ),
So consistent DSA on equal cells with reflecting faces converges for every cell thickness , with a rate that does not depend on it.
Proof. Since ,
The terms with are positive and at most , so . The terms with are negative and at least . Since the rule is exact for , , so the sum of the numbers over is , and . With (4) and , . For and , . Finally, , and equality would need all the weight at ; for even no node is 0, so .
For , , so and , which agrees with Theorem 4. The values of are 0.4260 for , 0.3799 for and 0.3862 for , and for the continuous rule. The true maximum of is smaller. For the continuous factor with , the maximum over a fine grid of is near ; this value is a computation, not part of the theorem.
Theorem 7 (the inconsistent scheme). With the same slab and modes, the cell-centered correction of the page (face coefficient between equal cells, no current at a reflecting face) has the eigenvalue
If and , then for close enough to , so the iteration diverges on fine enough meshes of thick cells.
Proof. The cell row is with . At a reflecting face the missing neighbor has the same value as the cell, which holds for because and for . With every row becomes , so , and as before. As , and because no node is 0, so . This has absolute value greater than 1 exactly when . By continuity, for near , and these values of occur once is large.
Since , the two schemes agree for smooth modes, . They differ for the modes that change sign from cell to cell. In thick cells these modes have near 0, and the consistent scheme gives them almost no correction while the inconsistent one gives them a correction of nearly times their size. For the threshold is .
Complexity
In the real RAM model, one iteration is one sweep, operations, plus one tridiagonal solve, operations. So iterations cost , and the diffusion solve adds only a fraction of about to the work of source iteration. The gain is in . On equal cells with reflecting faces, Theorem 6 bounds the rate by for , so is at most about , which is 19 for , independent of , and the cell size. The measured counts are 10 to 11, against 437 to 1356 for source iteration. The extra memory is for the residual, the tridiagonal system and the correction.
Properties
- The same answer. DSA changes the iteration, not the equations. Its fixed point is the diamond difference solution of source iteration (Theorem 3).
- A rate that does not depend on the scattering ratio. On equal cells with reflecting faces, the error falls by at most per iteration for (Theorem 6). The measured rate is about , which matches the Fourier maximum of the continuous problem.
- Unconditional stability. With the consistent diffusion equation, the bound holds for every cell thickness (Theorem 6). The inconsistent equation diverges once on fine meshes (Theorem 7).
- Exact for S2 with reflection. P1 and are the same equations, so the correction is the exact error (Theorem 4).
- Cheap. One tridiagonal solve per sweep in a slab. In several dimensions, the diffusion solve is a sparse elliptic problem, which multigrid or conjugate gradients solve at a cost small next to a sweep, as a rule of thumb.
Variants and improvements
- Inconsistent DSA. A diffusion equation discretized on its own, such as the cell-centered scheme of the implementation, is simpler and works for cells thinner than about one mean free path (Theorem 7).
- Larsen's four-step method. Larsen (1982) derived consistent diffusion equations for other transport discretizations by taking the P1 moments of the discrete transport equations, as Theorem 2 does for diamond difference. For linear discontinuous and multidimensional schemes the fully consistent equation is large, and partially consistent schemes are used, as described in the review of Adams and Larsen (2002).
- DSA as a preconditioner. Write the transport problem as and use the diffusion solve as a preconditioner for GMRES. Warsa, Wareing and Morel (2004) found that this keeps the speed in multidimensional problems with strong material discontinuities, where plain DSA loses much of its effectiveness.
- Other low-order operators. Transport synthetic acceleration uses a cheap low-order transport problem, such as , in place of diffusion. Nonlinear schemes such as coarse mesh finite difference use a diffusion problem whose coefficients are updated from the transport solution. Both appear in the review of Adams and Larsen (2002).
- Energy groups and eigenvalues. In the multigroup approximation DSA accelerates the inner iteration of each group. For the k-eigenvalue problem a similar diffusion correction accelerates the outer power iteration.
When to use it
Use DSA when source iteration is slow: near 1 and a slab many mean free paths thick, as in reactor cores with water, or in radiative transfer in optically thick matter. Derive the diffusion equation from the transport discretization, as in line L6, or at least check its Fourier factor for thick cells. In multidimensional problems with strong material discontinuities, use DSA as a preconditioner for a Krylov method. When the problem is thin or strongly absorbing, plain source iteration is already fast and DSA brings little.
Pitfalls
- An inconsistent diffusion equation (line L6). A diffusion scheme that is correct for diffusion can still make DSA diverge. In the example the cell-centered scheme has the rate 40 for cells of 10 mean free paths. Test the scheme with thick cells.
- The wrong face condition (line L6). Vacuum faces need the Marshak row. With a zero flux face condition the correction is wrong near the face, and the edge system does not match the P1 equations.
- A singular system. With in every cell and both faces reflecting, the edge system is singular (Theorem 1), and so is the transport problem. Fix the flux level by another condition.
- Negative flux fixups. A fixup in the sweep makes the transport scheme nonlinear and no longer consistent with line L6. As a rule of thumb, the rate then becomes worse in thick cells.
- The sign of the residual (line L5). The source of the diffusion problem is , the change of the scattering source, not the change of the flux.
- The weight convention. With weights that sum to 2, the scattering source is and the diffusion equation is written for . Other conventions need matching factors in lines L3 and L6.
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/diffusion-synthetic-acceleration/. The authors are listed in prov/XAVARJ.jsonl.
"""Diffusion synthetic acceleration (DSA) of source iteration for the slab S_N equations with diamond differences.
The slab has M cells with sigma_t[j], sigma_s[j], an isotropic source q[j]
and widths dx[j]. The scalar flux is phi = integral of psi over mu in
[-1, 1], so the emission per unit mu is (sigma_s phi + q) / 2 and the
Gauss-Legendre weights sum to 2. Faces are "vacuum" or "reflect".
One DSA iteration:
1. sweep with the source of the last iterate: phi_half
2. the residual R_j = sigma_s,j (phi_half_j - phi_j)
3. solve a diffusion equation for the correction f with the source R
4. phi_new = phi_half + f
accel = "consistent": the diffusion equation for the edge values f_i is the
one obtained from the diamond difference P1 equations by eliminating the
current (the method of Alcouffe 1977). With g = 2 / (3 sigma_t dx) and the
absorption sigma_a = sigma_t - sigma_s, the row of edge i between the cells
L (left) and R (right) is
(-g_L + sa_L dx_L / 2) f_(i-1) + (g_L + g_R + sa_L dx_L / 2 + sa_R dx_R / 2) f_i
+ (-g_R + sa_R dx_R / 2) f_(i+1) = R_L dx_L + R_R dx_R.
A vacuum face adds 1 to its diagonal entry (the Marshak condition
J_out = f / 2), and a reflecting face adds nothing. The cell correction is
the mean of the two edge values.
accel = "inconsistent": the usual cell-centered diffusion equation with the
face coefficient 1 / (dx_L / (2 D_L) + dx_R / (2 D_R)), D = 1 / (3 sigma_t).
This is a correct discretization of diffusion, but not the one consistent with
diamond difference, and it diverges for thick cells.
accel = "none": plain source iteration.
"""
import math
from scisparse import thomas
def legendre(n: int, x: float):
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 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 _dd(mu, psi, sigma_t, src, dx):
m = len(dx)
cells = [0.0] * m
for j in (range(m) if mu > 0 else range(m - 1, -1, -1)):
a = 2.0 * abs(mu) / dx[j]
cells[j] = (src[j] + a * psi) / (sigma_t[j] + a)
psi = 2.0 * cells[j] - psi
return cells, psi
def sweep(mus, ws, sigma_t, src, dx, left="vacuum", right="vacuum"):
"""Scalar flux of one diamond difference sweep of all directions; reflection is exact. Returns (phi, leak_left, leak_right)."""
n, m = len(mus), len(dx)
phi = [0.0] * m
leak_l = leak_r = 0.0
for k in range(n // 2, n):
mu, w = mus[k], ws[k]
if left == "reflect" and right == "reflect":
_, s1 = _dd(mu, 0.0, sigma_t, src, dx)
_, t2 = _dd(-mu, 0.0, sigma_t, src, dx)
r = 1.0
for st, h in zip(sigma_t, dx):
tau = st * h / mu
r *= (2.0 - tau) / (2.0 + tau)
fwd, out_r = _dd(mu, (r * s1 + t2) / (1.0 - r * r), sigma_t, src, dx)
bwd, out_l = _dd(-mu, out_r, sigma_t, src, dx)
elif left == "reflect":
bwd, out_l = _dd(-mu, 0.0, sigma_t, src, dx)
fwd, out_r = _dd(mu, out_l, sigma_t, src, dx)
else:
fwd, out_r = _dd(mu, 0.0, sigma_t, src, dx)
bwd, out_l = _dd(-mu, out_r if right == "reflect" else 0.0, sigma_t, src, dx)
for j in range(m):
phi[j] += w * (fwd[j] + bwd[j])
if right != "reflect":
leak_r += w * mu * out_r
if left != "reflect":
leak_l += w * mu * out_l
return phi, leak_l, leak_r
def consistent_correction(sigma_t, sigma_s, dx, res, left="vacuum", right="vacuum"):
"""Cell corrections from the edge diffusion equation with the source res (the residual sigma_s (phi_half - phi))."""
m = len(dx)
n = m + 1
a, b, c, d = [0.0] * n, [0.0] * n, [0.0] * n, [0.0] * n
for j in range(m):
g = 2.0 / (3.0 * sigma_t[j] * dx[j])
sa = (sigma_t[j] - sigma_s[j]) * dx[j] / 2.0
# cell j couples its left edge j and its right edge j + 1
b[j] += g + sa
c[j] += -g + sa
a[j + 1] += -g + sa
b[j + 1] += g + sa
d[j] += res[j] * dx[j]
d[j + 1] += res[j] * dx[j]
if left == "vacuum":
b[0] += 1.0
if right == "vacuum":
b[m] += 1.0
f = thomas(a, b, c, d)
return [(f[j] + f[j + 1]) / 2.0 for j in range(m)]
def inconsistent_correction(sigma_t, sigma_s, dx, res, left="vacuum", right="vacuum"):
"""Cell corrections from the cell-centered diffusion equation with Marshak or reflecting faces."""
m = len(dx)
D = [1.0 / (3.0 * s) for s in sigma_t]
a, b, c, d = [0.0] * m, [0.0] * m, [0.0] * m, [0.0] * m
for j in range(m):
b[j] = (sigma_t[j] - sigma_s[j]) * dx[j]
d[j] = res[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
if left == "vacuum":
b[0] += 1.0 / (dx[0] / (2.0 * D[0]) + 2.0)
if right == "vacuum":
b[-1] += 1.0 / (dx[-1] / (2.0 * D[-1]) + 2.0)
return thomas(a, b, c, d)
def dsa(n, sigma_t, sigma_s, q, dx, left="vacuum", right="vacuum", accel="consistent",
tol=1e-10, max_iter=10000, phi0=None):
"""Source iteration with diffusion synthetic acceleration.
Returns a dict with phi, the leakages, the number of iterations and the list of the largest changes."""
mus, ws = gauss_legendre(n)
m = len(dx)
phi = list(phi0) if phi0 is not None else [0.0] * m # @line L1
changes = []
leak_l = leak_r = 0.0
it = 0
for it in range(1, max_iter + 1): # @line L2
src = [(sigma_s[j] * phi[j] + q[j]) / 2.0 for j in range(m)] # @line L3
half, leak_l, leak_r = sweep(mus, ws, sigma_t, src, dx, left, right) # @line L4
res = [sigma_s[j] * (half[j] - phi[j]) for j in range(m)] # @line L5
if accel == "consistent":
corr = consistent_correction(sigma_t, sigma_s, dx, res, left, right) # @line L6
elif accel == "inconsistent":
corr = inconsistent_correction(sigma_t, sigma_s, dx, res, left, right)
else:
corr = [0.0] * m
new = [half[j] + corr[j] for j in range(m)] # @line L7
change = max(abs(new[j] - phi[j]) for j in range(m))
phi = new
changes.append(change)
if not math.isfinite(change) or change <= tol * (max(abs(v) for v in phi) or 1.0): # @line L8
break
return {"phi": phi, "leak_left": leak_l, "leak_right": leak_r, "iterations": it, "changes": changes}
def fourier_si(lam, c, mus=None, ws=None):
"""Source iteration factor (c / 2) sum w / (1 + lam^2 mu^2); with mus = None the exact angular integral c atan(lam) / lam."""
if mus is None:
return c if lam == 0.0 else c * math.atan(lam) / lam
return 0.5 * c * sum(w / (1.0 + (lam * mu) ** 2) for mu, w in zip(mus, ws))
def fourier_dsa(lam, c, mus=None, ws=None):
"""DSA factor omega_SI - c (1 - omega_SI) / (1 - c + lam^2 / 3) for the mode with the wave number lam sigma_t."""
if lam == 0.0:
return 0.0 # the flat mode is removed exactly; this is also the limit for c = 1
w = fourier_si(lam, c, mus, ws)
return w - c * (1.0 - w) / (1.0 - c + lam * lam / 3.0)
def fourier_dsa_dd(theta, c, tau, mus, ws):
"""Consistent DSA with diamond difference on equal cells of optical thickness tau, for the mode cos(theta (j + 1/2))."""
return fourier_dsa(2.0 * math.tan(theta / 2.0) / tau, c, mus, ws)
def fourier_dsa_inconsistent(theta, c, tau, mus, ws):
"""Inconsistent cell-centered DSA with diamond difference, for the same mode."""
w = fourier_si(2.0 * math.tan(theta / 2.0) / tau, c, mus, ws)
return w - c * (1.0 - w) / (1.0 - c + 4.0 * math.sin(theta / 2.0) ** 2 / (3.0 * tau * tau))
def spectral_radius_dsa(c, mus=None, ws=None, samples=4000, lam_max=50.0):
"""The largest |fourier_dsa| on a grid of lam in [0, lam_max]. Returns (radius, lam at the maximum)."""
best, at = 0.0, 0.0
for i in range(samples + 1):
lam = lam_max * i / samples
v = abs(fourier_dsa(lam, c, mus, ws))
if v > best:
best, at = v, lam
return best, at
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_synthetic_acceleration.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diffusion-synthetic-acceleration/. The authors are listed in prov/XAVARJ.jsonl.
import math
import random
import unittest
from diffusion_synthetic_acceleration import (dsa, fourier_dsa, fourier_dsa_dd, fourier_dsa_inconsistent,
gauss_legendre, spectral_radius_dsa)
def slab_rate(accel, h, c=0.99, m=100, iters=40):
phi0 = [1.0 + 0.5 * math.sin(3.7 * j) for j in range(m)]
r = dsa(8, [1.0] * m, [c] * m, [0.0] * m, [h] * m, accel=accel, tol=0.0, max_iter=iters, phi0=phi0)
ch = r["changes"]
return ch[-1] / ch[-2]
class TestFourier(unittest.TestCase):
def test_continuous_spectral_radius(self):
rho, lam = spectral_radius_dsa(1.0)
self.assertAlmostEqual(rho, 0.2247, delta=1e-4)
self.assertAlmostEqual(lam, 2.53, delta=0.02)
rho, _ = spectral_radius_dsa(0.99)
self.assertAlmostEqual(rho, 0.2214, delta=1e-4)
self.assertEqual(fourier_dsa(0.0, 0.9), 0.0)
def test_s2_dsa_is_exact(self):
mus, ws = gauss_legendre(2)
for lam in (0.1, 1.0, 3.0, 30.0):
for c in (0.5, 0.99, 1.0):
self.assertAlmostEqual(fourier_dsa(lam, c, mus, ws), 0.0, delta=1e-11)
def test_cosine_modes_are_eigenvectors(self):
mus, ws = gauss_legendre(8)
m, h, c = 30, 0.7, 0.95
for accel, factor in (("consistent", fourier_dsa_dd), ("inconsistent", fourier_dsa_inconsistent)):
for k in (0, 1, 4, 15, 29):
theta = math.pi * k / m
e = [math.cos(theta * (j + 0.5)) for j in range(m)]
r = dsa(8, [1.0] * m, [c] * m, [0.0] * m, [h] * m, "reflect", "reflect", accel,
tol=0.0, max_iter=1, phi0=e)
omega = factor(theta, c, h, mus, ws)
for j in range(m):
self.assertAlmostEqual(r["phi"][j], omega * e[j], places=12)
def test_consistent_factor_is_bounded_for_all_cell_sizes(self):
mus, ws = gauss_legendre(8)
for tau in (0.01, 0.1, 1.0, 10.0, 100.0):
worst = max(abs(fourier_dsa_dd(math.pi * k / 500, 0.999, tau, mus, ws)) for k in range(500))
self.assertLess(worst, 0.2247)
bad = max(abs(fourier_dsa_inconsistent(math.pi * k / 500, 0.99, 10.0, mus, ws)) for k in range(500))
self.assertGreater(bad, 40.0)
class TestIteration(unittest.TestCase):
def test_infinite_medium_in_one_step(self):
r = dsa(8, [1.0] * 10, [0.9] * 10, [1.0] * 10, [1.0] * 10, "reflect", "reflect", tol=0.0, max_iter=1)
for p in r["phi"]:
self.assertAlmostEqual(p, 10.0, places=12)
def test_s2_reflecting_slab_in_one_step(self):
rng = random.Random(4)
m = 25
st = [rng.uniform(0.5, 5.0) for _ in range(m)]
ss = [s * rng.uniform(0.8, 0.999) for s in st]
q = [rng.uniform(0.0, 1.0) for _ in range(m)]
dx = [rng.uniform(0.1, 2.0) for _ in range(m)]
phi0 = [rng.uniform(0.0, 5.0) for _ in range(m)]
exact = dsa(2, st, ss, q, dx, "reflect", "reflect", "none", tol=1e-15)["phi"]
one = dsa(2, st, ss, q, dx, "reflect", "reflect", tol=0.0, max_iter=1, phi0=phi0)["phi"]
for a, b in zip(one, exact):
self.assertAlmostEqual(a, b, delta=1e-11 * b)
# with S4, or with vacuum faces, one step is not exact
four = dsa(4, st, ss, q, dx, "reflect", "reflect", tol=0.0, max_iter=1, phi0=phi0)["phi"]
self.assertGreater(max(abs(a - b) / b for a, b in zip(four, exact)), 0.1)
def test_measured_rates(self):
for h in (0.1, 1.0, 10.0):
self.assertLess(slab_rate("consistent", h), 0.22)
self.assertLess(slab_rate("inconsistent", 0.1), 0.22)
self.assertGreater(slab_rate("inconsistent", 1.0), 0.7)
self.assertGreater(slab_rate("inconsistent", 10.0), 30.0)
self.assertGreater(slab_rate("none", 10.0, iters=200), 0.985)
def test_same_solution_far_fewer_iterations(self):
m, length = 40, 10.0
args = (8, [1.0] * m, [0.99] * m, [1.0] * m, [length / m] * m)
si = dsa(*args, accel="none", tol=1e-8)
ac = dsa(*args, accel="consistent", tol=1e-8)
self.assertEqual(si["iterations"], 437)
self.assertLessEqual(ac["iterations"], 12)
ref = dsa(*args, accel="consistent", tol=1e-14)
self.assertAlmostEqual(ac["leak_right"], ref["leak_right"], delta=1e-8)
# source iteration stops much farther from the solution than its tolerance suggests
self.assertGreater(abs(si["leak_right"] - ref["leak_right"]), 1e-7)
absorbed = sum(0.01 * p * length / m for p in ref["phi"])
self.assertAlmostEqual(absorbed + ref["leak_left"] + ref["leak_right"], length, places=9)
def test_heterogeneous_slab(self):
rng = random.Random(9)
m = 60
st = [rng.uniform(0.5, 20.0) for _ in range(m)]
ss = [s * rng.uniform(0.9, 0.999) for s in st]
q = [rng.uniform(0.0, 1.0) for _ in range(m)]
dx = [rng.uniform(0.05, 2.0) for _ in range(m)]
ac = dsa(8, st, ss, q, dx, "reflect", "vacuum", tol=1e-12)
self.assertLess(ac["iterations"], 20)
ic = dsa(8, st, ss, q, dx, "reflect", "vacuum", "inconsistent", tol=1e-12, max_iter=300)
self.assertFalse(math.isfinite(ic["changes"][-1]))
si = dsa(8, st, ss, q, dx, "reflect", "vacuum", "none", tol=1e-12, phi0=ac["phi"])
self.assertLessEqual(si["iterations"], 3)
absorbed = sum((a - b) * p * h for a, b, p, h in zip(st, ss, ac["phi"], dx))
self.assertAlmostEqual(absorbed + ac["leak_right"], sum(x * h for x, h in zip(q, dx)), delta=1e-8)
if __name__ == "__main__":
unittest.main()
History
Kopp proposed the synthetic method in 1963: a low-order problem corrects each transport iterate. Reed (1971) analyzed the diffusion correction by Fourier analysis for the continuous problem and found the factor , but discretized forms of the method could be unstable for thick cells. Alcouffe (1977) showed that the diffusion equation must be derived from the diamond difference transport equations, and the result was stable for every cell thickness. Larsen (1982) turned this into a general procedure and proved unconditional stability in slab geometry. Adams and Larsen (2002) review the theory. Warsa, Wareing and Morel (2004) showed that DSA loses effectiveness in multidimensional problems with material discontinuities and that Krylov methods with a DSA preconditioner restore it.
References
- R. E. Alcouffe, Diffusion synthetic acceleration methods for the diamond-differenced discrete-ordinates equations, Nuclear Science and Engineering 64(2), 1977, 344-355, the derivation of a diffusion equation consistent with diamond difference and its stability for thick cells
- W. H. Reed, The effectiveness of acceleration techniques for iterative methods in transport theory, Nuclear Science and Engineering 45(3), 1971, 245-254, the Fourier analysis of the diffusion correction for the continuous problem
- E. W. Larsen, Unconditionally stable diffusion-synthetic acceleration methods for the slab geometry discrete ordinates equations. Part I: Theory, Nuclear Science and Engineering 82(1), 1982, 47-63, the four-step procedure that derives a consistent diffusion equation from a given transport discretization
- 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 sections on diffusion synthetic acceleration, its Fourier analysis and the consistency requirement
- J. S. Warsa, T. A. Wareing and J. E. Morel, Krylov iterative methods and the degraded effectiveness of diffusion synthetic acceleration for multidimensional SN calculations in problems with material discontinuities, Nuclear Science and Engineering 147(3), 2004, 218-248, DSA as a preconditioner for Krylov methods and its loss of effectiveness in multidimensional problems with material discontinuities
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 XAVARJ Edit this page History Report an error Markdown