Algorithm Search⌘K

Algorithmadvanced

Consistent adjoint driven importance sampling

Also called CADIS.

Uses a deterministic adjoint solution to build a consistent biased source and weight windows for one Monte Carlo tally.

Time
O(J A M + N K) average
Space
O(A + M) extra
Where
A = the number of discrete directions; J = the number of source iterations of the adjoint solve; K = the mean number of flights per history; M = the number of mesh cells; N = the number of Monte Carlo histories
Properties
randomizedexactiterativerandomized
Origin
John C. Wagner, Alireza Haghighat, 1998

CADIS computes an approximate importance with a deterministic adjoint solve and uses it twice in a Monte Carlo run for one tally: to bias the source toward important places, and to set the weight windows. The word "consistent" means that source particles are born with exactly the weight that the window of their cell asks for, so the run does not split or kill them at birth. The Monte Carlo estimate stays unbiased whatever the quality of the adjoint; a good adjoint only makes the variance small, and an exact one would make it zero. John Wagner and Alireza Haghighat published the method in 1998 for shielding problems, with the adjoint from a discrete ordinates code.

In plain words

To make a Monte Carlo run for one detector fast, you need to know which particles matter. The importance map gives the answer: for each place, direction and energy, how much a particle there is expected to add to the detector.

CADIS gets a rough importance map from a cheap deterministic calculation that runs backward from the detector. Then it starts more particles where the map says they matter, with smaller weights so the average stays right. During the run, it gives every place a normal weight that is the inverse of the importance there. Heavy particles in important places are split, and light particles in unimportant places play roulette. In the ideal case every particle carries the same expected count, and the result has no noise at all.

The problem

The model problem is one-speed transport in a slab 0≤x≤L0 \le x \le L with vacuum faces, cut into MM cells of width h=L/Mh = L/M. The medium has the total cross section Σt\Sigma_t and the scattering cross section Σs\Sigma_s, with c=Σs/Σtc = \Sigma_s/\Sigma_t, and scattering is isotropic. The source has the density qiq_i in cell ii, isotropic, with ∑iqih=1\sum_i q_i h = 1 (one source particle). The detector has the response function σd,i\sigma_{d,i}, and the quantity to estimate is the response

R=∑iσd,i∫cell iϕ(x) dx,R = \sum_i \sigma_{d,i} \int_{\text{cell } i} \phi(x)\, dx,

where ϕ\phi is the scalar flux. With σd=1\sigma_d = 1 in the detector cells, RR is the expected track length of all particles of one history in the detector. A general code has a three-dimensional mesh, energy groups and a mesh of windows in space and energy, but the steps are the same.

The algorithm

  1. CADIS-PARAMETERS(q, σ_d, c_u)
  2. 1φ⁺ ← the scalar adjoint flux of the S_N solve with the source σ_d
  3. 2R̂ ← Σ_i q_i φ⁺_i h ▷ the deterministic estimate of R
  4. 3p_i ← q_i φ⁺_i h / R̂ for every cell i ▷ the biased source
  5. 4w̄_i ← R̂ / φ⁺_i ▷ the birth weight and the window target
  6. 5w_L,i ← 2 w̄_i / (c_u + 1), w_U,i ← c_u w_L,i
  7. CADIS-RUN(N)
  8. 6for n ← 1 to N do
  9. 7draw cell i with probability p_i, x uniform in cell i, μ uniform on [-1, 1], put (x, μ, w̄_i) in the bank, S ← 0
  10. 8while the bank is not empty do take a particle (x, μ, w) in cell i from the bank, and repeat until it ends:
  11. 9s ← -ln(ξ) / Σ_t, d ← the distance to the edge of cell i along μ
  12. 10S ← S + w σ_d,i min(s, d); if s ≥ d, move to the next cell (end on leakage), else collide: w ← c w, μ ← 2ξ' - 1
  13. 11if w > w_U,i then k ← min(⌈w / w_U,i⌉, k_max), w ← w / k, put k - 1 copies in the bank
  14. 12else if w < w_L,i then w ← w̄_i with probability w / w̄_i, else the particle ends
  15. 13add S and S² to the sums
  16. return the mean of S and its standard error

Lines L1 to L5 are the deterministic part. Line L1 solves L+ϕ+=σdL^+\phi^+ = \sigma_d. In a one-speed slab with isotropic scattering, the scalar adjoint flux is the forward scalar flux with the source σd\sigma_d (see the importance page), so the same discrete ordinates solver does both. Line L3 biases the source in proportion to the importance, and line L4 gives the birth weight qih/pi=R^/ϕi+q_i h/p_i = \hat R/\phi^+_i, which is also the center of the window. The ratio cu=wU/wLc_u = w_U/w_L is usually 5.

Lines L6 to L13 are a Monte Carlo run with implicit capture (line L10 multiplies the weight by cc instead of killing the particle) and the window check of lines L11 and L12 after every cell crossing and every collision. At a collision the new direction is sampled before the window check, so each copy that line L11 puts in the bank has the new direction. Line L13 adds the total score of the history, with all its copies.

Example

The parameters. Take L=10L = 10 cm, M=40M = 40, Σt=1 cm−1\Sigma_t = 1\ \mathrm{cm}^{-1}, c=0.5c = 0.5, the source uniform on [0,1][0, 1] (cells 0 to 3, qi=1q_i = 1) and the detector on [9,10][9, 10] (cells 36 to 39, σd=1\sigma_d = 1). An S16S_{16} solve with diamond differences gives:

cell ϕi+\phi^+_i target wˉi\bar w_i wL,iw_{L,i} wU,iw_{U,i}
0 4.492×10−54.492 \times 10^{-5} 1.642 0.5474 2.737
3 1.062×10−41.062 \times 10^{-4} 0.6943 0.2314 1.157
4 1.370×10−41.370 \times 10^{-4} 0.5384 0.1795 0.8973
5 1.761×10−41.761 \times 10^{-4} 0.4189 0.1396 0.6982
8 3.707×10−43.707 \times 10^{-4} 0.1990 0.06634 0.3317
20 7.428×10−37.428 \times 10^{-3} 9.932×10−39.932 \times 10^{-3} 3.311×10−33.311 \times 10^{-3} 1.655×10−21.655 \times 10^{-2}
36 0.8660 8.519×10−58.519 \times 10^{-5} 2.840×10−52.840 \times 10^{-5} 1.420×10−41.420 \times 10^{-4}

The estimate is R^=7.377×10−5\hat R = 7.377 \times 10^{-5}. The biased source probabilities of cells 0 to 3 are 0.1522,0.2106,0.2771,0.36010.1522, 0.2106, 0.2771, 0.3601, so the source moves toward the detector. Check by hand: p0wˉ0=0.1522⋅1.642=0.2500=q0hp_0 \bar w_0 = 0.1522 \cdot 1.642 = 0.2500 = q_0 h, the true probability of cell 0. The target falls by a factor of about 2.7 per cm, so there is one split of about 2.7 for each centimeter a particle moves toward the detector.

One particle. A particle born in cell 3 has the weight 0.6943. It flies to the right into cell 4, whose window is [0.1795,0.8973][0.1795, 0.8973], so nothing happens. It collides in cell 5: implicit capture gives 0.5⋅0.6943=0.34720.5 \cdot 0.6943 = 0.3472, inside [0.1396,0.6982][0.1396, 0.6982]. If it then reaches cell 8 with this weight, it is above wU=0.3317w_U = 0.3317, and line L11 splits it into ⌈0.3472/0.3317⌉=2\lceil 0.3472/0.3317 \rceil = 2 copies of weight 0.1736, inside the window of cell 8. If instead it flies back into cell 2 (window [0.3007,1.503][0.3007, 1.503]), it is still inside; a second collision there gives 0.1736<0.30070.1736 < 0.3007, and line L12 lets it survive with probability 0.1736/0.9021=0.1920.1736/0.9021 = 0.192 with the weight 0.9021.

Measured gain. Runs with random.Random(7) and the flight count as the cost, FOM=1/(relative error2⋅flights)\mathrm{FOM} = 1/(\text{relative error}^2 \cdot \text{flights}):

cc method histories mean relative error flights FOM
0.5 analog 10510^5 1.129×10−41.129 \times 10^{-4} 0.345 418 950 2.0×10−52.0 \times 10^{-5}
0.5 source biasing only 10510^5 1.431×10−41.431 \times 10^{-4} 0.323 438 629 2.2×10−52.2 \times 10^{-5}
0.5 CADIS 10410^4 7.677×10−57.677 \times 10^{-5} 0.0565 274 045 1.14×10−31.14 \times 10^{-3}
0.9 analog 10510^5 9.938×10−39.938 \times 10^{-3} 0.0561 1 328 399 2.39×10−42.39 \times 10^{-4}
0.9 source biasing only 10510^5 1.022×10−21.022 \times 10^{-2} 0.0566 1 400 767 2.23×10−42.23 \times 10^{-4}
0.9 CADIS 10410^4 1.137×10−21.137 \times 10^{-2} 0.0280 848 244 1.51×10−31.51 \times 10^{-3}

A finer reference (M=160M = 160 and S32S_{32}) gives R=7.613×10−5R = 7.613 \times 10^{-5} for c=0.5c = 0.5 and 0.0111720.011172 for c=0.9c = 0.9. The runs differ from it by 0.15 to 2.2 standard errors (the largest is the analog run for c=0.9c = 0.9), which is a normal spread for six runs. The gain of CADIS over analog is a factor of 57 in the figure of merit for c=0.5c = 0.5 and 6.3 for c=0.9c = 0.9, where more particles reach the detector without help. Source biasing alone gains almost nothing here; the windows do the work. Note also that the CADIS mean agrees with the fine reference, not with the coarse estimate R^=7.377×10−5\hat R = 7.377 \times 10^{-5}: an error in the adjoint changes the variance, never the mean.

Correctness

There are two claims, both theorems; the proofs are below.

Unbiasedness. If ϕi+>0\phi^+_i > 0 in every cell where qi>0q_i > 0, and the expected number of flights per history is finite, then the expected value of SS is the exact response RR of the transport problem, for any positive ϕ+\phi^+ at all. The biased source with the weights qih/piq_i h/p_i has the same expected weight in each cell as the true source; implicit capture keeps the expected weight of each collision; the split and the roulette keep the expected weight in each cell. A martingale argument over the events of a history turns these local facts into the global one.

Zero variance in the limit. In a discrete model, where a particle moves between states with the probabilities PijP_{ij} and scores at its end, the biased game with the exact importance vv, the source qivi/Rq_i v_i/R, the transitions Pijvj/viP_{ij} v_j / v_i and the weight R/viR/v_i in state ii scores exactly RR in every history. CADIS imitates this game: its weights are R^/ϕi+\hat R/\phi^+_i, and the windows push each particle back toward that weight. With an approximate adjoint and windows of finite width, the variance is not zero, and the gain is a measurement, as in the table above.

Proof: CADIS is unbiased, and its exact-importance limit has zero variancefull

We assume exact arithmetic and exact independent uniform random numbers. The slab, the cells, the cross sections and the lines L1 to L13 are those of the page. We write σmax⁡=max⁡iσd,i\sigma_{\max} = \max_i \sigma_{d,i} and assume c<1c < 1; the case c=1c = 1 in a finite slab is the same, with the bound on the track length of Lemma 1 replaced by the one for a finite slab.

The analog value function. For a particle of unit weight that is about to start a flight at the point xx with the direction μ\mu, let V(x,μ)V(x, \mu) be the expected track-length score ∑iσd,i⋅\sum_i \sigma_{d,i} \cdot (track length in cell ii) of the analog game, summed over the whole future of the particle. The importance page shows that VV is the adjoint flux; here we only need its definition as an expectation. In the analog game the expected number of collisions is at most 1/(1−c)1/(1 - c) and each flight has the mean length 1/Σt1/\Sigma_t, so

0≤V(x,μ)≤Vmax⁡=σmax⁡Σt(1−c).0 \le V(x, \mu) \le V_{\max} = \frac{\sigma_{\max}}{\Sigma_t (1 - c)}.

By the analog page, the analog game is unbiased, so the exact response per source particle is

R=∑iqih⋅1h∫cell i12∫−11V(x,μ) dμ dx.(1)R = \sum_i q_i h \cdot \frac{1}{h} \int_{\text{cell } i} \frac{1}{2} \int_{-1}^{1} V(x, \mu)\, d\mu\, dx. \qquad (1)

Lemma 1 (first event). Let a particle of unit weight start a flight at (x,μ)(x, \mu) in cell ii, and let ss and dd be as in line L9. Then

V(x,μ)=E[σd,imin⁡(s,d)]+P(s≥d) V(e,μ)+E[1[s<d]  c⋅12∫−11V(x+μs,μ′) dμ′],V(x, \mu) = E\big[\sigma_{d,i} \min(s, d)\big] + P(s \ge d)\, V(e, \mu) + E\Big[\mathbf{1}[s < d]\; c \cdot \frac{1}{2} \int_{-1}^{1} V(x + \mu s, \mu')\, d\mu'\Big],

where ee is the edge of the cell and V(e,μ)=0V(e, \mu) = 0 if the particle leaves the slab there.

Proof. Condition on the first flight. The track length in cell ii during the flight is min⁡(s,d)\min(s, d). If s≥ds \ge d, the particle is at the edge with the direction μ\mu, and because the exponential law has no memory, the rest of its path has the law of a new flight from (e,μ)(e, \mu). If s<ds < d, the particle collides at x+μsx + \mu s, survives with probability cc, and starts a new flight with a direction uniform on [−1,1][-1, 1]. Taking expectations gives the three terms. □\square

Lemma 2 (one event of CADIS keeps the value). Let a particle of weight ww start a flight at (x,μ)(x, \mu) in cell ii in CADIS-RUN. Let Δ\Delta be the score that line L10 adds during this flight, and let B′B' be the set of particles (none, one, or several copies) that exist after lines L10 to L12. Then

E[Δ+∑(x′,μ′,w′)∈B′w′V(x′,μ′)]=wV(x,μ).E\Big[\Delta + \sum_{(x', \mu', w') \in B'} w' V(x', \mu')\Big] = w V(x, \mu).

Proof. The flight of line L9 has the analog law, so E[Δ]=wE[σd,imin⁡(s,d)]E[\Delta] = w E[\sigma_{d,i} \min(s, d)], the first term of Lemma 1 times ww. Consider the window check of lines L11 and L12 for a particle of weight uu at a point yy with direction ν\nu in a cell jj. If line L11 acts, it leaves k≥1k \ge 1 particles of weight u/ku/k at (y,ν)(y, \nu), so ∑w′V=uV(y,ν)\sum w' V = u V(y, \nu). If line L12 acts, it leaves one particle of weight wˉj\bar w_j with probability u/wˉju/\bar w_j and none otherwise, so E[∑w′V]=(u/wˉj) wˉj V(y,ν)=uV(y,ν)E[\sum w' V] = (u/\bar w_j)\, \bar w_j\, V(y, \nu) = u V(y, \nu). Otherwise the particle is unchanged. So the window check keeps E[∑w′V]E[\sum w' V] in every case.

If s≥ds \ge d and the particle stays in the slab, it reaches (e,μ)(e, \mu) with weight ww, and after the check the expected value is wV(e,μ)w V(e, \mu). If it leaves, nothing remains and V(e,μ)=0V(e, \mu) = 0. If s<ds < d, implicit capture gives the weight cwcw and line L10 samples μ′\mu' uniform on [−1,1][-1, 1] before the check, so the expected value after the check is cw⋅12∫V(x+μs,μ′) dμ′cw \cdot \frac{1}{2}\int V(x + \mu s, \mu')\, d\mu'. Adding the three cases gives ww times the right side of Lemma 1, which is wV(x,μ)w V(x, \mu). □\square

The order matters here: the new direction is drawn before the check, so every copy has an independent future with the law of a scattered particle. If the copies kept the old direction, the expected value after the collision would be cw V(x+μs,μ)cw\, V(x + \mu s, \mu), and Lemma 2 would fail.

Theorem 1 (unbiasedness). Assume ϕi+>0\phi^+_i > 0 in every cell with qi>0q_i > 0, 1<cu1 < c_u, kmax⁡≥1k_{\max} \ge 1, and that the expected number of flights TT of one history (with all its copies) is finite. Then E[S]=RE[S] = R, the exact response of (1), whatever the values of ϕ+\phi^+ are.

Proof. Number the flights of one history in the order in which CADIS-RUN does them, t=1,2,…,Tt = 1, 2, \ldots, T. After step tt, let StS_t be the score so far and BtB_t the set of particles that wait, including the one in flight, each with its weight and its state at the start of its next flight. Let

Φt=St+∑(x,μ,w)∈BtwV(x,μ).\Phi_t = S_t + \sum_{(x, \mu, w) \in B_t} w V(x, \mu).

Step t+1t + 1 does one flight of one particle of BtB_t and leaves the others alone, so Lemma 2 gives E[Φt+1∣Ft]=ΦtE[\Phi_{t+1} \mid \mathcal{F}_t] = \Phi_t, where Ft\mathcal{F}_t is the history up to step tt. So Φt\Phi_t is a martingale up to the stopping time TT, at which the bank is empty and ΦT=S\Phi_T = S.

The increments are bounded in conditional mean. A weight grows only at line L12, to a target wˉj\bar w_j, and at birth it is a target as well, so every weight is at most W=max⁡jwˉjW = \max_j \bar w_j, which is finite because ϕ+>0\phi^+ > 0 where it is used. One step adds at most Wσmax⁡min⁡(s,d)W \sigma_{\max} \min(s, d) to the score, with conditional mean at most Wσmax⁡/ΣtW\sigma_{\max}/\Sigma_t, and changes the bank by at most kmax⁡+1k_{\max} + 1 particles, each with wV≤WVmax⁡w V \le W V_{\max}. So E[∣Φt+1−Φt∣∣Ft]≤Wσmax⁡/Σt+(kmax⁡+2)WVmax⁡E[|\Phi_{t+1} - \Phi_t| \mid \mathcal{F}_t] \le W\sigma_{\max}/\Sigma_t + (k_{\max} + 2) W V_{\max}. With E[T]<∞E[T] < \infty, the optional stopping theorem in its form for bounded conditional increments gives E[S]=E[ΦT]=E[Φ0]E[S] = E[\Phi_T] = E[\Phi_0].

At the start, line L7 picks cell ii with probability pi=qiϕi+h/R^p_i = q_i \phi^+_i h/\hat R, which is positive where qi>0q_i > 0, gives the weight wˉi=R^/ϕi+=qih/pi\bar w_i = \hat R/\phi^+_i = q_i h/p_i, and draws (x,μ)(x, \mu) uniform in the cell and in direction. So

E[Φ0]=∑i:qi>0pi⋅qihpi⋅1h∫cell i12∫−11V(x,μ) dμ dx=RE[\Phi_0] = \sum_{i : q_i > 0} p_i \cdot \frac{q_i h}{p_i} \cdot \frac{1}{h}\int_{\text{cell } i} \frac{1}{2}\int_{-1}^{1} V(x, \mu)\, d\mu\, dx = R

by (1). The values ϕi+\phi^+_i cancel, which is why the quality of the adjoint does not enter the mean. □\square

Theorem 2 (zero variance with the exact importance, discrete form). Consider a particle that moves on the states 1,…,m1, \ldots, m. From state ii it moves to state jj with probability Pij≥0P_{ij} \ge 0, or it ends with probability ei=1−∑jPij≥0e_i = 1 - \sum_j P_{ij} \ge 0 and then scores gi≥0g_i \ge 0. Assume the walk ends with probability 1 from every state. Let viv_i be the expected score from state ii, so that

vi=eigi+∑jPijvj,(2)v_i = e_i g_i + \sum_j P_{ij} v_j, \qquad (2)

let qq be the start distribution and R=∑iqivi>0R = \sum_i q_i v_i > 0. Define the biased game on the states with vi>0v_i > 0: start in ii with probability q^i=qivi/R\hat q_i = q_i v_i/R and weight R/viR/v_i; from ii move to jj with probability P^ij=Pijvj/vi\hat P_{ij} = P_{ij} v_j/v_i and multiply the weight by Pij/P^ijP_{ij}/\hat P_{ij}; end with probability e^i=eigi/vi\hat e_i = e_i g_i/v_i and score the weight times eigi/e^ie_i g_i/\hat e_i. Then every history of the biased game scores exactly RR.

Proof. The biased probabilities are a distribution: ∑iq^i=1\sum_i \hat q_i = 1 by the definition of RR, and ∑jP^ij+e^i=(∑jPijvj+eigi)/vi=1\sum_j \hat P_{ij} + \hat e_i = (\sum_j P_{ij} v_j + e_i g_i)/v_i = 1 by (2). A state with vj=0v_j = 0 has P^ij=0\hat P_{ij} = 0, so the biased walk never enters it. The weight starts at w0=qi/q^i=R/vi0w_0 = q_i/\hat q_i = R/v_{i_0}. If wk=R/vikw_k = R/v_{i_k}, a move to jj gives wk+1=wkPij/P^ij=wkvik/vj=R/vjw_{k+1} = w_k P_{ij}/\hat P_{ij} = w_k v_{i_k}/v_j = R/v_j. So by induction the weight in state ii is always R/viR/v_i, and the score at the end in state ii is (R/vi)⋅eigi/e^i=(R/vi)⋅vi=R(R/v_i) \cdot e_i g_i/\hat e_i = (R/v_i) \cdot v_i = R.

The biased walk ends with probability 1. The probability that it is still running after nn steps from state ii is ∑j(Pn)ijvj/vi\sum_j (P^n)_{ij} v_j / v_i, and ∑j(Pn)ijvj\sum_j (P^n)_{ij} v_j is the expected score of the analog walks from ii that last more than nn steps. Since the analog walk ends with probability 1 and vv is bounded, this tends to 0 by dominated convergence. □\square

How CADIS relates to Theorem 2. The weight of the zero variance game in state ii is R/viR/v_i, the importance in the denominator. CADIS uses the same value R^/ϕi+\hat R/\phi^+_i for the birth weight and the window target, and lines L3 and L4 are exactly the biased start of Theorem 2 with vv replaced by ϕ+\phi^+. CADIS does not change the flight and scattering laws; it uses splitting and roulette to keep each weight near the target, which makes the expected number of particles in a cell follow the importance, as the biased transitions P^\hat P do. This link is a heuristic. Theorem 1 holds in all cases, and the variance reduction of a real run is a measurement.

Complexity

In the real RAM model, one source iteration of the adjoint solve costs O(AM)O(AM) for AA directions and MM cells, and the solve takes JJ iterations, about ln⁡(tolerance)/ln⁡c\ln(\text{tolerance})/\ln c without acceleration. The Monte Carlo part costs O(NK)O(NK) for NN histories with KK flights each, including the copies made by line L11. The windows and the source need O(M)O(M) memory, and the solve needs O(A+M)O(A + M) beyond the flux arrays. In three dimensions with GG energy groups the adjoint costs O(JAMG)O(J A M G) per solve, which is usually small next to the Monte Carlo time.

The cost that matters is the time to reach a given relative error. CADIS makes the variance per history smaller and the work per history different (more copies near the detector, fewer flights far from it). The product is the figure of merit, a measurement for each problem.

Properties

  • Unbiased for any positive adjoint, any cu>1c_u > 1 and any cap kmax⁡≥1k_{\max} \ge 1.
  • Consistent. The source particles are born at the center of their windows, so the window check at birth does nothing.
  • One tally. The importance is for one response. Other tallies of the same run get no help and may get worse.
  • Automatic. The user gives the source and the detector, not importances by hand.
  • Depends on the adjoint. A coarse mesh, few directions or ray effects in the discrete ordinates adjoint lower the gain, but never bias the result.

Variants and improvements

  • FW-CADIS weights the adjoint source by the inverse of a forward estimate, so that many tallies or a mesh tally get about the same relative error.
  • Space-energy CADIS. With a multigroup adjoint, the windows and the biased source depend on the energy group as well, which is the form used for shielding.
  • Angle-dependent importance. Variants use the angular adjoint flux, or the product of the forward and adjoint angular fluxes, to set windows that depend on the direction, for streaming paths and ducts.
  • Other adjoint solvers. A diffusion or a coarse Monte Carlo adjoint is cheaper and can replace the discrete ordinates solve when the gain still pays.
  • Source biasing only, or windows only. Each part alone is a valid unbiased game. The example shows that the windows give most of the gain in a slab.

When to use it

Use CADIS for one detector response that analog Monte Carlo reaches with too few particles: shielding, dose behind a wall, a detector far from a source, a response in a small region. It needs a deterministic adjoint code on a mesh that covers the problem. Do not use it for many tallies at once or for a map of the flux over a large region; use FW-CADIS there. For a k-eigenvalue problem it does not apply directly, because there is no fixed source and no single detector.

Pitfalls

  • Birth weight not equal to the target (line L4 or L7). If source particles start with weight 1 instead of wˉi\bar w_i, the first window check splits or kills them at once. The mean stays right, but the time goes into the source cells. This is the inconsistency that CADIS removes.
  • Window check before the new direction (line L10 before L11). If a collision puts copies in the bank before it samples the new direction, the copies keep the direction from before the collision, which is a scattering that did not happen. This biases the tally.
  • Zero adjoint in a cell (line L4). Where ϕi+=0\phi^+_i = 0, for example in a region that cannot reach the detector, the target is infinite. Use a floor on ϕ+\phi^+, or a window that only plays roulette there.
  • Errors per copy (line L13). The variance must use the total score of each history, with all its copies, not each copy alone.
  • Wrong adjoint source (line L1). The adjoint source must be the response function σd\sigma_d of the tally. A forward flux, or the adjoint of another detector, gives valid but poor windows.
  • Ray effects (line L1). In two and three dimensions a discrete ordinates adjoint with few directions has streaks of high and low importance. The windows then split and kill particles along the streaks, which wastes time.

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.

cadis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cadis/. The authors are listed in prov/VERVKH.jsonl.
"""CADIS: consistent adjoint driven importance sampling 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, the same in all
cells), isotropic scattering and vacuum faces. The source q_i (one value per
cell, isotropic, normalized to one source particle) and the detector
response sigma_d,i (one value per cell) define the response
R = integral of sigma_d phi dx.

CADIS has a deterministic step and a Monte Carlo step:

1. Solve the adjoint problem with the source sigma_d by discrete ordinates.
   With isotropic scattering in a slab, the adjoint angular flux is the
   forward angular flux of the same source with mu reversed, so the scalar
   adjoint flux phi+ comes from a forward solve with the source sigma_d.
2. Estimate R = sum_i q_i phi+_i h, bias the source to q_i phi+_i h / R, give
   a source particle born in cell i the weight R / phi+_i, and set the weight
   window target of cell i to the same value R / phi+_i, with the bounds
   w_L = 2 w / (c_u + 1) and w_U = c_u w_L.
3. Run Monte Carlo with implicit capture and the windows, checked at every
   collision and every cell boundary, and score sigma_d times the track length.

run_monte_carlo with windows=None is the analog game (analog absorption,
unit weights), the reference for the variance comparison.
"""

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 phi_i (cell averages) of the fixed source problem by S_N, 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 cadis_parameters(q, sigma_d, length, sigma_t, sigma_s, c_u=5.0, order=16):
    """The deterministic part of CADIS.

    Returns a dict with the adjoint flux phi+, the estimate R of the response per
    source particle, the biased source probabilities, the birth weights, and the
    window targets and bounds of every cell."""
    m = len(q)
    h = length / m
    total = sum(q) * h
    q = [v / total for v in q]  # one source particle
    adj = sn_solve(sigma_d, length, sigma_t, sigma_s, order)  # @line L1
    r = sum(qi * a * h for qi, a in zip(q, adj))  # @line L2
    p_biased = [qi * a * h / r for qi, a in zip(q, adj)]  # @line L3
    target = [r / a for a in adj]  # @line L4
    lower = [2.0 * w / (c_u + 1.0) for w in target]  # @line L5
    upper = [c_u * w for w in lower]
    return {"adjoint": adj, "response": r, "source_pdf": p_biased, "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):
    """The weight window game in one cell. Returns the weight to continue with, or 0.0.

    Above the window the particle splits into n = ceil(w / w_U) copies of weight
    w / n (at most max_split); the extra copies go on the stack. Below the
    window it plays Russian roulette with survival weight equal to the target."""
    if w > upper[cell]:  # @line L11
        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]:  # @line L12
        if rng.random() < w / target[cell]:
            return target[cell]
        return 0.0
    return w


def run_monte_carlo(n, length, sigma_t, sigma_s, sigma_d, rng, params=None, q=None, windows=True):
    """Monte Carlo estimate of R per source particle with its standard error.

    With params (from cadis_parameters) and windows=True: CADIS (biased source,
    implicit capture, weight windows). With params=None: the analog game with the
    source q. Returns (mean, standard error, number of flights)."""
    m = len(sigma_d)
    h = length / m
    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 and windows
    c = sigma_s / sigma_t
    s1 = s2 = 0.0
    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)  # @line L7
        stack = [((cell + rng.random()) * h, 2.0 * rng.random() - 1.0, wbirth[cell], cell)]
        score = 0.0
        while stack:  # @line L8
            x, mu, w, cell = stack.pop()
            while w > 0.0:
                flights += 1
                s = -math.log(1.0 - rng.random()) / sigma_t  # @line L9
                edge = (cell + 1) * h if mu > 0 else cell * h
                d = (edge - x) / mu if mu != 0.0 else math.inf
                if s >= d:  # the particle reaches the cell boundary first
                    score += w * sigma_d[cell] * d  # @line L10
                    cell += 1 if mu > 0 else -1
                    x = edge
                    if cell < 0 or cell >= m:
                        break  # leakage
                    if biased:
                        w = apply_window(x, mu, w, cell, lower, upper, target, rng, stack)
                    continue  # a new flight; the exponential law has no memory
                score += w * sigma_d[cell] * s
                x += mu * s
                if biased:
                    w *= c  # implicit capture
                    mu = 2.0 * rng.random() - 1.0  # every split copy gets this new direction
                    w = apply_window(x, mu, w, cell, lower, upper, target, rng, stack)
                elif rng.random() >= c:
                    break  # analog absorption
                else:
                    mu = 2.0 * rng.random() - 1.0
        s1 += score  # @line L13
        s2 += score * score
    mean = s1 / n
    var = max(s2 / n - mean * mean, 0.0) * n / (n - 1)
    return mean, math.sqrt(var / n), flights
test_cadis.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cadis/. The authors are listed in prov/VERVKH.jsonl.
import math
import random

import pytest

from cadis import apply_window, cadis_parameters, gauss_legendre, run_monte_carlo, sn_solve

L, M = 10.0, 40
H = L / M
Q = [1.0 if i < 4 else 0.0 for i in range(M)]  # source in [0, 1]
SD = [1.0 if i >= 36 else 0.0 for i in range(M)]  # detector in [9, 10]


class FixedRng:
    def __init__(self, values):
        self.values = list(values)

    def random(self):
        return self.values.pop(0)


def reference_response(c):
    """R on a mesh 4 times finer with S_32, per source particle."""
    m = 4 * M
    h = L / m
    q = [1.0 if i < 16 else 0.0 for i in range(m)]  # density 1 on [0, 1]: one source particle
    phi = sn_solve(q, L, 1.0, c, order=32)
    return sum(p * h for i, p in enumerate(phi) if i >= 144)


def test_gauss_legendre():
    nodes, weights = gauss_legendre(16)
    assert sum(weights) == pytest.approx(2.0, abs=1e-13)
    assert sum(w * x**2 for x, w in zip(nodes, weights)) == pytest.approx(2.0 / 3.0, abs=1e-13)


def test_sn_infinite_medium_limit():
    # A thick slab with a uniform source: the center flux tends to q / sigma_a = 1 / 0.5 = 2.
    phi = sn_solve([1.0] * 100, 100.0, 1.0, 0.5, order=8)
    assert phi[50] == pytest.approx(2.0, rel=1e-6)


def test_sn_pure_absorber_beam_like():
    # A source in the first cell only and no scattering: the flux far away falls at least like e^(-x).
    phi = sn_solve([1.0] + [0.0] * 39, 10.0, 1.0, 0.0, order=16)
    assert all(phi[i + 1] < phi[i] * math.exp(-H) * 1.0001 for i in range(1, 39))


@pytest.mark.parametrize("c", [0.5, 0.9])
def test_adjoint_reciprocity(c):
    # <q, phi+> from the adjoint solve equals <sigma_d, phi> from the forward solve.
    p = cadis_parameters(Q, SD, L, 1.0, c)
    phi = sn_solve(p["q"], L, 1.0, c)
    forward = sum(s * f * H for s, f in zip(SD, phi))
    assert p["response"] == pytest.approx(forward, rel=1e-9)


def test_consistent_source_and_windows():
    p = cadis_parameters(Q, SD, L, 1.0, 0.5, c_u=5.0)
    assert sum(p["source_pdf"]) == pytest.approx(1.0, abs=1e-12)
    for i in range(M):
        # the weight times the biased probability is the true probability: the source is unbiased
        assert p["birth_weight"][i] * p["source_pdf"][i] == pytest.approx(p["q"][i] * H, abs=1e-15)
        # particles are born at the target weight, inside their window
        assert p["lower"][i] < p["birth_weight"][i] < p["upper"][i]
        assert p["upper"][i] / p["lower"][i] == pytest.approx(5.0)
        assert (p["lower"][i] + p["upper"][i]) / 2 == pytest.approx(p["target"][i])
    # the importance grows toward the detector, so the targets fall
    assert all(p["target"][i] > p["target"][i + 1] for i in range(30))


def test_window_game_keeps_the_weight():
    lower, upper, target = [1.0], [5.0], [3.0]
    stack = []
    w = apply_window(0.0, 1.0, 12.0, 0, lower, upper, target, FixedRng([]), stack)
    assert w == pytest.approx(4.0) and len(stack) == 2  # ceil(12 / 5) = 3 copies of 4
    assert w + sum(s[2] for s in stack) == pytest.approx(12.0)
    assert apply_window(0.0, 1.0, 0.6, 0, lower, upper, target, FixedRng([0.19]), []) == 3.0  # 0.19 < 0.2
    assert apply_window(0.0, 1.0, 0.6, 0, lower, upper, target, FixedRng([0.21]), []) == 0.0
    assert apply_window(0.0, 1.0, 2.0, 0, lower, upper, target, FixedRng([]), []) == 2.0
    # the roulette keeps the mean: 0.6 = P(survive) * 3 = 0.2 * 3


@pytest.mark.parametrize("c", [0.5, 0.9])
def test_cadis_and_analog_agree_with_reference(c):
    ref = reference_response(c)
    p = cadis_parameters(Q, SD, L, 1.0, c)
    m, se, _ = run_monte_carlo(4000, L, 1.0, c, SD, random.Random(11), params=p)
    assert abs(m - ref) < 4.0 * se + 0.01 * ref
    m, se, _ = run_monte_carlo(20000, L, 1.0, c, SD, random.Random(12), q=Q)
    assert abs(m - ref) < 4.0 * se + 0.01 * ref


def test_cadis_beats_analog():
    # Measured with fixed seeds: the figure of merit per flight is far larger with CADIS.
    p = cadis_parameters(Q, SD, L, 1.0, 0.5)
    m_c, se_c, f_c = run_monte_carlo(4000, L, 1.0, 0.5, SD, random.Random(7), params=p)
    m_a, se_a, f_a = run_monte_carlo(40000, L, 1.0, 0.5, SD, random.Random(7), q=Q)
    fom_c = 1.0 / ((se_c / m_c) ** 2 * f_c)
    fom_a = 1.0 / ((se_a / m_a) ** 2 * f_a)
    assert fom_c > 10.0 * fom_a

History

John Wagner and Alireza Haghighat published CADIS in Nuclear Science and Engineering in 1998, with the importance from a discrete ordinates adjoint solve and the consistent biased source and windows. The use of the adjoint as an importance function was much older; the new step was to compute it automatically and to make the source and the windows agree. Haghighat and Wagner reviewed adjoint-based variance reduction in 2003, and Wagner, Peplow and Mosher extended the method in 2014 to many tallies as FW-CADIS.

References

  1. 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, the biased source q phi+ / R, the birth weights and window targets R / phi+, the window bounds from the target, and the shielding results
  2. 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, the consistency of the source and the windows, and the zero variance argument
  3. 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 summary of CADIS for one tally before its extension to many tallies
  4. Ivan Lux and Laszlo Koblinger, Monte Carlo Particle Transport Methods, Neutron and Photon Calculations, CRC Press, 1991, the chapters on non-analog games and on zero variance schemes built from the importance

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 proofH1 sketch
  • a full proof of time.average
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example