Algorithmresearch
Forward-weighted CADIS
Also called FW-CADIS.
Weights the adjoint source by the inverse forward flux, so variance reduction gives a uniform relative error over a mesh tally.
- Time
- O(J A M + N (K + B)) average
- Space
- O(A + M + B) extra
- Where
- A = the number of discrete directions; B = the number of tally bins; J = the number of source iterations of one deterministic solve; K = the mean number of flights per history; M = the number of mesh cells; N = the number of Monte Carlo histories
- Model
- Real RAM
- Properties
- randomizedexactiterativerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John C. Wagner, Douglas E. Peplow, Scott W. Mosher, 2014
FW-CADIS is CADIS for many tallies at once: a mesh tally over a large region, or a set of detectors with very different responses. CADIS makes one tally good and can leave the others with no score at all. FW-CADIS first runs a deterministic forward solve to estimate every tally, then sets the adjoint source of each tally to the inverse of its estimate, so that every tally counts with the same relative weight in the importance. The rest is CADIS: a biased source and weight windows from the adjoint flux. The goal is about the same relative error in every bin. John Wagner, Douglas Peplow and Scott Mosher described the method in 2014.
In plain words
Suppose you want a map of the radiation in a whole building, not one number at one detector. Near the source the map is easy, because many particles go there. Far away, almost no particles arrive, and the map there is pure noise.
CADIS can make one far spot good, but it does so by sending particles toward that spot only. FW-CADIS first makes a cheap rough map. Then it tells the importance calculation: a place where the rough map is small needs more help, so give it a large weight. Particles are then pushed toward the weak places as much as toward the strong ones, and every part of the map gets about the same accuracy.
The problem
The model problem is the slab of the CADIS page: one-speed transport in with vacuum faces, cells of width , total cross section , scattering ratio , isotropic scattering, and a source with . The tally is a mesh of equal bins, each made of cells, and the quantity in bin is
the expected track length per source particle in the bin. The goal is to estimate all with relative errors that are about equal, or equivalently to make the largest small for a given amount of work. The can differ by many orders of magnitude.
The algorithm
FW-CADIS-PARAMETERS(q, B, c_u)- 1
φ ← the scalar flux of the forward S_N solve with the source q - 2
q⁺_i ← 1 / T̂_j(i), where T̂_j = Σ_{i in bin j} φ_i h and j(i) is the bin of cell i - 3
φ⁺ ← the scalar adjoint flux of the S_N solve with the source q⁺ - 4
R̂ ← Σ_i q_i φ⁺_i h, and p_i ← q_i φ⁺_i h / R̂ - 5
w̄_i ← R̂ / φ⁺_i, w_L,i ← 2 w̄_i / (c_u + 1), w_U,i ← c_u w_L,i FW-CADIS-RUN(N)- 6
for n ← 1 to N do run one history of CADIS-RUN, lines L7 to L12 of the CADIS page, with these parameters - 7
during the history, add w times the track length in each cell to the score S_j of its bin j - 8
add each S_j and S_j² to the sums of bin j return the mean of S_j and its standard error for every bin j
Line L1 is the only new solve. Line L2 is the forward weighting: the adjoint source of bin is the inverse of its deterministic estimate, so the adjoint problem asks for the importance of a particle for the sum of relative tallies. Lines L3 to L5 are lines L1 to L5 of CADIS with this source. Lines L6 to L8 are the CADIS Monte Carlo run with a score for each bin. In a slab with isotropic scattering both solves are forward solves of the same code, as in CADIS.
Example
Take cm, , bins of 1 cm, , , and a source uniform on , in the middle of the slab. An forward solve gives the bin estimates
and the bins 9 to 16 are the mirror image. The center bins have more than 2000 times the flux of the end bins.
The response by hand. The adjoint source is in bin . By reciprocity, . The solver gives . So in FW-CADIS the estimated response is always the number of bins, and each bin adds exactly 1 to it.
The parameters. The scalar adjoint flux is in the end cells and to in the source cells, so the importance is 160 times larger at the faces than at the source. The birth weights in the four source cells are , with biased probabilities : the source changes little, and the windows do the work of pushing particles outward. The target weight in the end cells is .
Measured errors. Runs with random.Random(5) give the relative errors of six bins, the ratio of the largest to the smallest relative error over all 16 bins, and the figure of merit of the worst bin, :
| method | histories | flights | worst-bin FOM | |||||||
|---|---|---|---|---|---|---|---|---|---|---|
| analog | 604 242 | 0.251 | 0.048 | 0.004 | 0.004 | 0.048 | 0.206 | 60.5 | ||
| CADIS for bin 16 | 260 217 | no score | 0.786 | 0.016 | 0.011 | 0.038 | 0.050 | none | none | |
| FW-CADIS | 171 415 | 0.084 | 0.051 | 0.011 | 0.011 | 0.053 | 0.082 | 7.4 |
CADIS for the last bin makes that bin good and the bins on the other side bad; three of the left bins get no score at all in this run. FW-CADIS gives both end bins about the same error, the ratio of the largest to the smallest error falls from 60.5 to 7.4, and the worst bin has a figure of merit 32 times the analog one. These are measurements on one toy problem. The errors are not fully uniform: the product integrated over a bin, which is the expected density of Monte Carlo tracks in the ideal case, runs from in the end bins to in the center bins, because the adjoint of a slab with leakage cannot follow exactly.
Correctness
Unbiasedness. This is a theorem: the Monte Carlo part is CADIS with another positive adjoint, so the proof of CADIS applies to the score of every bin. The mean of each is the exact , whatever the errors of the forward and adjoint solves. The proof is below.
The response is . This is a theorem about the deterministic part: with on bin , the discrete reciprocity of the solver gives .
Why the errors become uniform. This is a heuristic, the one of Wagner, Peplow and Mosher. If each particle at a point carried exactly the target weight , the expected density of Monte Carlo tracks at would be the physical flux divided by the weight, . A relative error that is the same in every bin needs about the same number of tracks in every bin, so should be about constant over the tally region. The forward weighting of the adjoint source is a cheap way to come close to this: where is small, the adjoint source is large. The example shows that the result is closer to uniform than analog play or CADIS, but not uniform.
Proof: FW-CADIS is unbiased in every bin, and its estimated response is the number of binsfull
We assume exact arithmetic and exact independent uniform random numbers. The slab, the cells, the bins and the lines L1 to L8 are those of the page, and the lines of CADIS-RUN are those of the CADIS page.
Theorem 1 (unbiased bins). Assume that the forward estimates of line L2 are positive, that the adjoint flux of line L3 is positive in every cell with , and that the expected number of flights of one history is finite. Then for every bin , the mean of the score of one history is the exact , whatever the errors of the two deterministic solves.
Proof. Fix a bin , and let for the cells of bin and for all other cells. With this response function, the CADIS score of line L10 is the sum of times the track length in the cells of bin , which is the score that line L7 adds. The exact CADIS response is then the expected analog track length in bin per source particle, which is .
Lines L4 and L5 of FW-CADIS are lines L4 and L5 of CADIS with the adjoint of line L3, and the run of line L6 is CADIS-RUN with these parameters. Theorem 1 of the CADIS proof holds for any positive values of the adjoint in the source cells: the proof uses only that where , that the birth weight is , that the window targets are finite, and that the flights and collisions keep their analog laws. The adjoint that CADIS takes from a solve with the source can therefore be replaced by the adjoint of line L3, whose source is , without a change in the proof. The theorem gives .
All bins use the same run, so the theorem holds for every at the same time. Line L8 adds the scores of one history, so the bin means are means of independent and identically distributed scores, and the standard error of each bin is the usual one.
Theorem 2 (the estimated response). Let the forward and the adjoint solves of lines L1 and L3 be the same discrete operator and its adjoint, so that the discrete reciprocity holds. Then .
Proof. By line L2, . So
In a slab with isotropic scattering, the discrete adjoint of the sweep with the symmetric quadrature is the forward sweep with the directions reversed, and the scalar fluxes agree, which is why the code of the page uses one solver for both. The value for in the example is a check of this.
The track density (a heuristic). Suppose that each particle at a point has exactly the target weight . A tally of the physical flux is the sum of the weights times the track lengths, so the expected track length of the Monte Carlo particles per unit volume at is the flux divided by the weight, . If is constant over the tally region, every bin of the same size gets the same expected number of tracks, each with a weight that follows the flux, and the relative errors of the bins are then about equal. The window of finite width, the correlation between the copies of one history, and an adjoint that does not make constant make this an approximation. It is not a theorem, and the example of the page measures how far a real run is from it.
Complexity
In the real RAM model, the two deterministic solves cost each, with source iterations, directions and cells. The Monte Carlo run costs for the flights and for the sums of line L8, so in all. A code that keeps a list of the bins a history touched pays only for those. The memory is for the windows and the fluxes, for the sums, and for the angular sweep. As for CADIS, the time to a given worst-bin error is a measurement.
Properties
- Unbiased in every bin, for any positive forward and adjoint estimates.
- One run for many tallies. All bins come from one run with one set of windows.
- Balanced, not optimal. The method aims at a uniform relative error. It does not minimize a stated error measure, and it can give a worse error than CADIS for the one bin that CADIS was made for.
- Two deterministic solves. The forward solve is extra work, usually small next to the Monte Carlo run.
Variants and improvements
- Response-weighted tallies. For a dose or a reaction rate with the response function , the adjoint source is , the response function divided by the forward estimate of the response.
- A few detectors. For a set of point or region tallies, the adjoint source is the sum of their response functions, each divided by its forward estimate.
- A tally over the whole problem. For a global flux map, in every cell.
- Iterative forward methods. Other methods set the windows from the flux map of a previous Monte Carlo run instead of a deterministic adjoint, and repeat; they reach a similar goal without a deterministic code.
When to use it
Use FW-CADIS when a single run must give a map of the flux or the dose over a large region, or several tallies with very different values, for example a dose map in a building around a reactor or an accelerator. Use plain CADIS when one tally matters, and analog or lightly biased play when all tallies are close to the source.
Pitfalls
- A zero or tiny forward estimate (line L2). A bin that the forward solve gives as almost zero gets an enormous adjoint source, and the windows then send the run into that bin. Put a floor on , or leave bins outside the region of interest out of the adjoint source.
- The adjoint source cell by cell (line L2). Using in each cell instead of for the bin weights the cells of a bin in a different way from the tally; for a bin with a steep flux inside it, the importance then favors the low-flux edge of the bin.
- An inaccurate forward solve (line L1). Ray effects or a coarse mesh in the forward solve put the wrong weights on bins. The mean stays right, but the errors are no longer balanced.
- Errors per copy (line L8). The variance of each bin must use the total score of the history in that bin, with all its copies.
- Sums for every bin of every history (line L8). With a large mesh, adding numbers per history costs more than the flights. Keep the list of bins that the history touched.
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/fw-cadis/. The authors are listed in prov/GNWTPH.jsonl.
"""FW-CADIS: forward-weighted CADIS for a mesh tally in a one-speed slab.
The slab 0 <= x <= L has M cells of width h = L / M, a total cross section
sigma_t and a scattering cross section sigma_s (cm^-1), isotropic scattering
and vacuum faces. The source q_i is isotropic and normalized to one source
particle. The tally is the flux integral T_j over each of B equal bins (a
bin holds M / B cells). The goal is about the same relative error in every
bin, so the method weights each bin by the inverse of its expected value:
1. Solve the forward problem by discrete ordinates: phi_i.
2. Set the adjoint source q+_i = 1 / T_j(i), the inverse of the
deterministic estimate of the bin that holds cell i, and solve the adjoint
problem (with isotropic scattering in a slab, a forward solve with the
source q+ gives the scalar adjoint flux).
3. Do CADIS with this adjoint: bias the source to q_i phi+_i / R, give birth
weights R / phi+_i, and set the weight window targets to R / phi+_i.
4. Run Monte Carlo with implicit capture and weight windows, and score the
track length of each particle in each bin.
run_monte_carlo with params=None is the analog game.
"""
import math
def gauss_legendre(order):
"""Nodes and weights of the Gauss-Legendre rule on [-1, 1]; the weights sum to 2."""
nodes, weights = [], []
for i in range(order):
x = math.cos(math.pi * (i + 0.75) / (order + 0.5))
for _ in range(100):
p0, p1 = 1.0, x
for m in range(2, order + 1):
p0, p1 = p1, ((2 * m - 1) * x * p1 - (m - 1) * p0) / m
dp = order * (x * p1 - p0) / (x * x - 1.0)
dx = p1 / dp
x -= dx
if abs(dx) < 1e-15:
break
nodes.append(x)
weights.append(2.0 / ((1.0 - x * x) * dp * dp))
return nodes, weights
def sn_solve(q, length, sigma_t, sigma_s, order=16, tol=1e-12, max_iter=10000):
"""Scalar flux (cell averages) of the fixed source problem by S_N with diamond
differences and source iteration. q_i is the isotropic source density in cell i."""
m = len(q)
h = length / m
nodes, weights = gauss_legendre(order)
phi = [0.0] * m
for _ in range(max_iter):
src = [sigma_s * p + s for p, s in zip(phi, q)]
new = [0.0] * m
for mu, wt in zip(nodes, weights):
a = abs(mu) / h
cells = range(m) if mu > 0 else range(m - 1, -1, -1)
psi_in = 0.0
for i in cells:
psi_out = ((a - 0.5 * sigma_t) * psi_in + 0.5 * src[i]) / (a + 0.5 * sigma_t)
new[i] += wt * 0.5 * (psi_in + psi_out)
psi_in = psi_out
change = max(abs(u - v) for u, v in zip(new, phi))
phi = new
if change <= tol * max(phi):
break
return phi
def bin_totals(phi, h, bins):
per = len(phi) // bins
return [sum(phi[j * per:(j + 1) * per]) * h for j in range(bins)]
def fw_cadis_parameters(q, length, sigma_t, sigma_s, bins, c_u=5.0, order=16):
"""The deterministic part of FW-CADIS. Returns the forward flux, the bin
estimates, the adjoint flux and the CADIS source and window parameters."""
m = len(q)
h = length / m
per = m // bins
total = sum(q) * h
q = [v / total for v in q]
phi = sn_solve(q, length, sigma_t, sigma_s, order) # @line L1
t = bin_totals(phi, h, bins)
q_adj = [1.0 / t[i // per] for i in range(m)] # @line L2
adj = sn_solve(q_adj, length, sigma_t, sigma_s, order) # @line L3
r = sum(qi * a * h for qi, a in zip(q, adj)) # @line L4
pdf = [qi * a * h / r for qi, a in zip(q, adj)]
target = [r / a for a in adj] # @line L5
lower = [2.0 * w / (c_u + 1.0) for w in target]
upper = [c_u * w for w in lower]
return {"forward": phi, "bin_estimate": t, "adjoint": adj, "response": r, "source_pdf": pdf, "birth_weight": target, "target": target, "lower": lower, "upper": upper, "q": q}
def apply_window(x, mu, w, cell, lower, upper, target, rng, stack, max_split=10):
"""Split above the window into ceil(w / w_U) copies, roulette below it with
survival weight equal to the target. Returns the weight to continue with, or 0.0."""
if w > upper[cell]:
n = min(max_split, math.ceil(w / upper[cell]))
w /= n
for _ in range(n - 1):
stack.append((x, mu, w, cell))
return w
if w < lower[cell]:
if rng.random() < w / target[cell]:
return target[cell]
return 0.0
return w
def run_monte_carlo(n, length, sigma_t, sigma_s, bins, rng, params=None, q=None):
"""Track-length estimates of the flux integral in each bin per source particle.
With params from fw_cadis_parameters (or any CADIS parameters): biased source,
implicit capture and weight windows. With params=None: the analog game with
the source q. Returns (means, standard errors, number of flights)."""
m = len(q) if params is None else len(params["target"])
h = length / m
per = m // bins
if params is not None:
pdf, wbirth = params["source_pdf"], params["birth_weight"]
lower, upper, target = params["lower"], params["upper"], params["target"]
else:
total = sum(q) * h
pdf, wbirth = [v * h / total for v in q], [1.0] * m
cdf, acc = [], 0.0
for v in pdf:
acc += v
cdf.append(acc)
biased = params is not None
c = sigma_s / sigma_t
s1, s2 = [0.0] * bins, [0.0] * bins
flights = 0
for _ in range(n): # @line L6
u = rng.random() * acc
cell = next((i for i, v in enumerate(cdf) if u < v), m - 1)
stack = [((cell + rng.random()) * h, 2.0 * rng.random() - 1.0, wbirth[cell], cell)]
score = [0.0] * bins
while stack:
x, mu, w, cell = stack.pop()
while w > 0.0:
flights += 1
s = -math.log(1.0 - rng.random()) / sigma_t
edge = (cell + 1) * h if mu > 0 else cell * h
d = (edge - x) / mu if mu != 0.0 else math.inf
if s >= d:
score[cell // per] += w * d # @line L7
cell += 1 if mu > 0 else -1
x = edge
if cell < 0 or cell >= m:
break
if biased:
w = apply_window(x, mu, w, cell, lower, upper, target, rng, stack)
continue
score[cell // per] += w * s
x += mu * s
if biased:
w *= c
mu = 2.0 * rng.random() - 1.0
w = apply_window(x, mu, w, cell, lower, upper, target, rng, stack)
elif rng.random() >= c:
break
else:
mu = 2.0 * rng.random() - 1.0
for j in range(bins): # @line L8
s1[j] += score[j]
s2[j] += score[j] * score[j]
means = [v / n for v in s1]
errors = [math.sqrt(max(b / n - a * a, 0.0) / (n - 1)) for a, b in zip(means, s2)]
return means, errors, flights
def relative_errors(means, errors):
return [e / mval if mval > 0 else math.inf for mval, e in zip(means, errors)]
test_fw_cadis.py 65 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fw-cadis/. The authors are listed in prov/GNWTPH.jsonl.
import random
import pytest
from fw_cadis import bin_totals, fw_cadis_parameters, relative_errors, run_monte_carlo, sn_solve
L, M, B, C = 16.0, 64, 16, 0.5
H = L / M
Q = [1.0 if 30 <= i < 34 else 0.0 for i in range(M)] # source in [7.5, 8.5]
def reference_bins():
"""Bin totals on a mesh 4 times finer with S_32, per source particle."""
m = 4 * M
q = [1.0 if 120 <= i < 136 else 0.0 for i in range(m)] # density 1 on [7.5, 8.5]
return bin_totals(sn_solve(q, L, 1.0, C, order=32), L / m, B)
def test_adjoint_source_is_the_inverse_forward_estimate():
p = fw_cadis_parameters(Q, L, 1.0, C, B)
t = p["bin_estimate"]
assert t == pytest.approx(bin_totals(p["forward"], H, B))
assert t[0] == pytest.approx(t[-1], rel=1e-9) and t[7] == pytest.approx(t[8], rel=1e-9) # symmetric
# the adjoint solve with q+ = 1 / T_j reproduces R = <q, phi+> = <q+, phi> = number of bins
q_adj = [1.0 / t[i // (M // B)] for i in range(M)]
forward = sum(a * f * H for a, f in zip(q_adj, p["forward"]))
assert p["response"] == pytest.approx(forward, rel=1e-9)
assert forward == pytest.approx(B, rel=1e-12)
def test_consistent_birth_weights():
p = fw_cadis_parameters(Q, L, 1.0, C, B)
assert sum(p["source_pdf"]) == pytest.approx(1.0, abs=1e-12)
for i in range(M):
assert p["birth_weight"][i] * p["source_pdf"][i] == pytest.approx(p["q"][i] * H, abs=1e-15)
assert p["lower"][i] < p["target"][i] < p["upper"][i]
def test_deterministic_estimate_close_to_fine_reference():
p = fw_cadis_parameters(Q, L, 1.0, C, B)
for a, b in zip(p["bin_estimate"], reference_bins()):
assert a == pytest.approx(b, rel=0.06)
def test_means_agree_with_reference():
ref = reference_bins()
p = fw_cadis_parameters(Q, L, 1.0, C, B)
m, e, _ = run_monte_carlo(3000, L, 1.0, C, B, random.Random(21), params=p)
for j in range(B):
assert abs(m[j] - ref[j]) < 4.0 * e[j] + 0.01 * ref[j]
m, e, _ = run_monte_carlo(20000, L, 1.0, C, B, random.Random(22), q=Q)
for j in range(B):
assert abs(m[j] - ref[j]) < 4.0 * e[j] + 0.01 * ref[j]
def test_more_uniform_errors_than_analog():
# Measured with fixed seeds: the worst bin has a far better figure of merit with FW-CADIS.
p = fw_cadis_parameters(Q, L, 1.0, C, B)
m_f, e_f, fl_f = run_monte_carlo(3000, L, 1.0, C, B, random.Random(5), params=p)
m_a, e_a, fl_a = run_monte_carlo(20000, L, 1.0, C, B, random.Random(5), q=Q)
r_f, r_a = relative_errors(m_f, e_f), relative_errors(m_a, e_a)
assert max(r_f) / min(r_f) < max(r_a) / min(r_a) / 3.0
assert 1.0 / (max(r_f) ** 2 * fl_f) > 5.0 / (max(r_a) ** 2 * fl_a)
History
Wagner, Peplow and Mosher described FW-CADIS in Nuclear Science and Engineering in 2014, for "global" problems (a flux map over the whole geometry) and "regional" problems (several tallies), as an extension of the CADIS method of Wagner and Haghighat (1998). The paper gives the argument that a uniform density of Monte Carlo particles over the tally region gives uniform relative errors, and the forward weighting of the adjoint source as a way to reach it.
References
- John C. Wagner, Douglas E. Peplow and Scott W. Mosher, FW-CADIS method for global and regional variance reduction of Monte Carlo radiation transport calculations, Nuclear Science and Engineering 176(1), 2014, 37-57, the adjoint source weighted by the inverse forward response, the argument for a uniform density of Monte Carlo particles, and the test problems
- John C. Wagner and Alireza Haghighat, Automated variance reduction of Monte Carlo shielding calculations using the discrete ordinates adjoint function, Nuclear Science and Engineering 128(2), 1998, 186-208, CADIS, the biased source and the weight windows that FW-CADIS reuses
- Alireza Haghighat and John C. Wagner, Monte Carlo variance reduction with deterministic importance functions, Progress in Nuclear Energy 42(1), 2003, the review of importance functions and of the contributon density
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 GNWTPH Edit this page History Report an error Markdown