Algorithm Search⌘K

Algorithmcore

Monte Carlo criticality calculation

Also called Monte Carlo power iteration.

Finds k_eff by tracking generations of fission neutrons, using the fission sites of each generation as the source of the next.

Time
O(G N K) average
Space
O(N K) extra
Where
G = the number of cycles; K = the mean number of collisions per neutron; N = the number of neutrons per cycle
Properties
randomizednot exactiterativerandomized
Origin
J. Lieberoth, 1968

A Monte Carlo criticality calculation estimates the effective multiplication factor keffk_{\mathrm{eff}} of a reactor or of any system with fissile material, the largest eigenvalue of the k-eigenvalue problem. It is power iteration done with particles. A cycle follows NN neutrons from their birth to their absorption or leakage, by the same analog rules as in a fixed-source run, and stores the sites where they cause fission. The number of new neutrons per starting neutron is the estimate of kk for the cycle. The next cycle starts NN neutrons from the stored sites. After the first cycles, the inactive ones, the distribution of the sites is close to the fundamental mode, and the mean of kk over the remaining active cycles is the result. Each cycle is cheap, but the cycles are correlated, the result has a small bias of order 1/N1/N, and the source can take many cycles to converge in a large system.

In plain words

In a reactor, each neutron can cause a fission, and a fission makes new neutrons. One batch of neutrons is one generation. If the next generation is larger, the system grows; if it is smaller, the system dies out. The factor kk is the ratio of the two sizes.

A computer cannot follow all neutrons, so it follows a sample of, say, a thousand. It counts how many new neutrons they make, and it notes where they were made. Then it takes a thousand of these new places at random and starts again. After some generations the places settle into a fixed pattern, and from then on the counts give kk.

The problem

The model is one-speed transport in a bare slab 0≤x≤L0 \le x \le L with vacuum faces: total cross section Σt\Sigma_t, scattering cross section Σs\Sigma_s, production cross section νΣf\nu\Sigma_f (fission neutrons made per unit path), isotropic scattering and isotropic fission emission. Let F\mathcal{F} be the operator that maps a density ss of fission neutrons to the density of the fission neutrons of the next generation that they cause. The task is the largest eigenvalue of

Fs=k s,s≥0,\mathcal{F} s = k\, s, \quad s \ge 0,

which is keffk_{\mathrm{eff}}, with its eigenfunction, the fundamental fission source. The k-eigenvalue problem page gives the existence of a positive, simple largest eigenvalue for this kind of operator.

The algorithm

  1. MC-CRITICALITY(N, I, A)
  2. 1source ← N sites drawn uniformly in the fissile region; k ← 1
  3. 2for g ← 1 to I + A do
  4. 3bank ← empty; total ← 0
  5. 4for each site x in source do start a neutron at x with a direction uniform on [-1, 1]
  6. 5repeat: fly the distance s = -ln(ξ) / Σt; if the neutron leaves the slab, stop
  7. 6total ← total + νΣf / Σt ▷ the collision estimate of k
  8. 7put ⌊νΣf / (Σt k) + ξ⌋ copies of the collision site in the bank
  9. 8with probability Σs / Σt scatter into a new direction, else stop
  10. 9k ← k_g ← total / N
  11. 10source ← N sites drawn from the bank with replacement
  12. 11keep the values k_g of the active cycles g = I + 1, ..., I + A
  13. 12return their mean and its standard error

Line L6 scores the expected number of fission neutrons of a collision, νΣf/Σt\nu\Sigma_f/\Sigma_t, which is the collision estimator of the production. Line L7 divides by the kk of the previous cycle so that the bank stays near NN sites, and the random rounding ⌊a+ξ⌋\lfloor a + \xi \rfloor has the mean aa. Line L10 keeps the number of neutrons per cycle fixed at NN. Lines L11 and L12 drop the inactive cycles, in which the source is still far from the fundamental mode.

Example

One neutron by hand. Take L=2L = 2 cm, Σt=1 cm−1\Sigma_t = 1\ \mathrm{cm}^{-1}, Σs=0.5\Sigma_s = 0.5, νΣf=0.6\nu\Sigma_f = 0.6, k=1k = 1 and one site at x=1x = 1, with the random numbers 0.75,0.5,0.3,0.2,0.0,0.6,0.7,0.90.75, 0.5, 0.3, 0.2, 0.0, 0.6, 0.7, 0.9.

  • Line L4: μ=2⋅0.75−1=0.5\mu = 2 \cdot 0.75 - 1 = 0.5.
  • Line L5: s=−ln⁡(1−0.5)=0.693147s = -\ln(1 - 0.5) = 0.693147, so x=1+0.5⋅0.693147=1.346574x = 1 + 0.5 \cdot 0.693147 = 1.346574. Line L6 adds 0.60.6.
  • Line L7: ⌊0.6+0.3⌋=0\lfloor 0.6 + 0.3 \rfloor = 0 sites. Line L8: 0.2<0.50.2 < 0.5, so the neutron scatters, and μ=2⋅0.0−1=−1\mu = 2 \cdot 0.0 - 1 = -1.
  • Line L5: s=−ln⁡(1−0.6)=0.916291s = -\ln(1 - 0.6) = 0.916291, so x=0.430283x = 0.430283. Line L6 adds 0.60.6, so the total is 1.21.2.
  • Line L7: ⌊0.6+0.7⌋=1\lfloor 0.6 + 0.7 \rfloor = 1 site at x=0.430283x = 0.430283. Line L8: 0.9≥0.50.9 \ge 0.5, so the neutron is absorbed.

The cycle gives kg=1.2k_g = 1.2 and a bank with one site. This is the first test of the implementation.

An infinite medium. With Σt=1\Sigma_t = 1, Σs=0.9\Sigma_s = 0.9 and νΣf=0.12\nu\Sigma_f = 0.12, the exact value is k∞=νΣf/(Σt−Σs)=1.2k_\infty = \nu\Sigma_f/(\Sigma_t - \Sigma_s) = 1.2. A run with N=500N = 500, 2 inactive and 20 active cycles (random.Random(1)) gives 1.1888±0.00771.1888 \pm 0.0077.

A bare slab. The same material in a slab of L=20L = 20 cm has keff=1.12006k_{\mathrm{eff}} = 1.12006 from a discrete ordinates solve (S16S_{16}, 320 cells). A run with N=500N = 500, 10 inactive and 30 active cycles (random.Random(2)) gives 1.1171±0.00861.1171 \pm 0.0086.

A bad first source. Start all N=2000N = 2000 neutrons at x=1x = 1, near the left face (random.Random(3)). Many of them leak, so the first cycles give small values of kk:

cycle 1 2 3 4 5 6 7 8 9 10
kgk_g 0.734 0.835 0.956 0.994 1.078 1.093 1.141 1.102 1.134 1.142

From cycle 7 on, the values scatter about the right answer, but the source shape needs more cycles: its Shannon entropy rises from 2.51 to about 4.15 by cycle 18, near the value 4.1854.185 of the fundamental mode. With 20 inactive and 40 active cycles, the run gives 1.1175±0.00401.1175 \pm 0.0040. The values in the first cycles would bias the mean low, so they must be inactive.

The error estimate is too small. Over 25 independent runs (seeds 100 to 124, N=500N = 500, 20 inactive and 50 active cycles), the spread of the 25 values of kk is 0.007120.00712 and the mean naive standard error of line L12 is 0.006960.00696, a ratio of 1.021.02. For the fraction of sites in x<2x < 2, a local tally, the spread is 0.004040.00404 and the naive error is 0.001930.00193, a ratio of 2.102.10. The global kk is almost not affected by the correlation between cycles, but a local tally is. These are measurements on this problem.

Correctness

The proofs are below. Three statements, with different status:

  • One cycle is correct in expectation. This is a theorem: given the source, the expected bank is the next-generation fission density divided by the old kk, and the expected kgk_g is the number of fission neutrons per source neutron.
  • For large NN, the cycles are power iteration. This is a theorem in the limit N→∞N \to \infty with a fixed number of cycles: the source follows s↦Fs/∥Fs∥s \mapsto \mathcal{F}s/\|\mathcal{F}s\| and kg→∥Fs∥k_g \to \|\mathcal{F}s\|, so the source tends to the fundamental mode and kgk_g to keffk_{\mathrm{eff}}, with the error in the shape reduced by about the dominance ratio per cycle.
  • For finite NN, there are two biases. The mean of kk has a bias of order 1/N1/N, because each cycle is normalized to NN neutrons (Brissenden and Garlick 1986, cited, not proved here). The naive standard error of line L12 treats correlated cycles as independent; the proof shows the exact formula, and positive correlations make the naive error too small.

The number of inactive cycles is a rule of thumb, checked with a diagnostic such as the fission source entropy. No such diagnostic proves that the source has converged.

Proof: One cycle is correct in expectation, the large-N limit is power iteration, and the naive error ignores correlationfull

We assume exact arithmetic and exact independent uniform random numbers. The slab, the cross sections and the lines L1 to L12 are those of the page. We assume Σs<Σt\Sigma_s < \Sigma_t, so that a neutron has on average at most Σt/(Σt−Σs)\Sigma_t/(\Sigma_t - \Sigma_s) collisions, and νΣf>0\nu\Sigma_f > 0.

The next-generation kernel. For a neutron born at xx with an isotropic direction, let C(x,⋅)C(x, \cdot) be its analog collision density: for a set DD of points, ∫DC(x,y) dy\int_D C(x, y)\, dy is the expected number of its collisions in DD. The expected number of fission neutrons it makes in DD is

∫Df(x,y) dy,f(x,y)=νΣfΣt C(x,y),\int_D f(x, y)\, dy, \qquad f(x, y) = \frac{\nu\Sigma_f}{\Sigma_t}\, C(x, y),

and the operator of the page is (Fs)(y)=∫s(x)f(x,y) dx(\mathcal{F}s)(y) = \int s(x) f(x, y)\, dx.

Lemma 1 (one cycle in expectation). Let the source of a cycle be the sites x1,…,xNx_1, \ldots, x_N, and let kk be the value used in line L7. Then for every set DD,

E[number of banked sites in D]=1k∑n=1N∫Df(xn,y) dy,E[kg]=1N∑n=1N∫0Lf(xn,y) dy.E[\text{number of banked sites in } D] = \frac{1}{k} \sum_{n = 1}^{N} \int_D f(x_n, y)\, dy, \qquad E[k_g] = \frac{1}{N} \sum_{n = 1}^{N} \int_0^L f(x_n, y)\, dy.

Proof. Lines L4, L5 and L8 are the analog game, so the collisions of the neutron from xnx_n have the density C(xn,⋅)C(x_n, \cdot). At a collision at yy, line L7 banks ⌊a+ξ⌋\lfloor a + \xi \rfloor sites with a=νΣf/(Σtk)a = \nu\Sigma_f/(\Sigma_t k). If a=m+ra = m + r with an integer mm and 0≤r<10 \le r < 1, this is m+1m + 1 with probability rr and mm otherwise, so its mean is aa. The random number ξ\xi is independent of the past, so the expected number of banked sites in DD is a∫DC(xn,y) dy=(1/k)∫Df(xn,y) dya \int_D C(x_n, y)\, dy = (1/k) \int_D f(x_n, y)\, dy. The sum over the NN neutrons gives the first formula. Line L6 adds νΣf/Σt\nu\Sigma_f/\Sigma_t at each collision in the slab, so the expected total for neutron nn is ∫0Lf(xn,y) dy\int_0^L f(x_n, y)\, dy, and line L9 divides by NN. □\square

So, given the source, the bank is an unbiased estimate of F\mathcal{F} applied to the empirical source, divided by kk, and kgk_g is an unbiased estimate of the number of fission neutrons per source neutron. The value of kk in line L7 changes only the size of the bank, not its shape.

Theorem 1 (the limit of many neutrons is power iteration). Let the first source be NN independent sites with a density s0s_0, and fix a number of cycles GG. Write ∥s∥=∫0Ls(x) dx\|s\| = \int_0^L s(x)\, dx and sg+1=Fsg/∥Fsg∥s_{g+1} = \mathcal{F}s_g/\|\mathcal{F}s_g\|. Then for every g≤Gg \le G, as N→∞N \to \infty, kg→∥Fsg−1∥k_g \to \|\mathcal{F}s_{g-1}\| in probability, and the empirical distribution of the source of cycle g+1g + 1 converges weakly in probability to the density sgs_g.

Proof. We use induction on gg. Let Π\Pi be the empirical distribution of the current source, and assume that Π\Pi converges weakly in probability to a density ss (for g=1g = 1 this is the law of large numbers for the NN independent first sites). Let φ\varphi be a bounded continuous function on [0,L][0, L], and let YnY_n be the sum of φ\varphi over the sites that neutron nn banks.

Given the source, the YnY_n are independent. Each ∣Yn∣|Y_n| is at most max⁡∣φ∣\max|\varphi| times the number of collisions of neutron nn times ⌈a⌉\lceil a \rceil, and the number of collisions is geometric, so E[Yn2∣source]≤M2E[Y_n^2 \mid \text{source}] \le M_2, a constant that does not depend on the source. By Lemma 1, E[Yn∣xn]=(1/k)∫φ(y)f(xn,y) dyE[Y_n \mid x_n] = (1/k) \int \varphi(y) f(x_n, y)\, dy, and this is a bounded continuous function of xnx_n, because the collision density of a neutron in a slab depends continuously on its birth point. By Chebyshev's inequality with the bound M2M_2, 1N∑nYn−1N∑nE[Yn∣xn]→0\frac{1}{N}\sum_n Y_n - \frac{1}{N}\sum_n E[Y_n \mid x_n] \to 0 in probability, and by the weak convergence of Π\Pi, 1N∑nE[Yn∣xn]→(1/k)∫φ Fs\frac{1}{N}\sum_n E[Y_n \mid x_n] \to (1/k)\int \varphi\, \mathcal{F}s in probability. The same argument with φ=1\varphi = 1 and with the score of line L6 gives ∣bank∣/N→∥Fs∥/k|\text{bank}|/N \to \|\mathcal{F}s\|/k and kg→∥Fs∥k_g \to \|\mathcal{F}s\|. Here kk is the value of the previous cycle, which converges in probability by the induction (or is the fixed k0k_0 in the first cycle), and it is positive.

So the empirical distribution of the bank converges weakly in probability to Fs/∥Fs∥\mathcal{F}s/\|\mathcal{F}s\|, and ∥Fs∥>0\|\mathcal{F}s\| > 0 because νΣf>0\nu\Sigma_f > 0. Line L10 draws NN sites independently from the bank. Given the bank, the mean of φ\varphi over these sites has the conditional mean equal to the mean over the bank and a conditional variance at most max⁡φ2/N\max\varphi^2/N, so it converges in probability to the same limit. This is the induction step. □\square

So in the limit the sources are the iterates of power iteration on F\mathcal{F} with the normalization ∥s∥=1\|s\| = 1, and kgk_g is the norm of F\mathcal{F} applied to the normalized source. If F\mathcal{F} has a simple positive eigenvalue keffk_{\mathrm{eff}} that is larger in modulus than all others, with a positive eigenfunction s⋆s^\star (the k-eigenvalue problem page gives this for the slab), and s0s_0 has a positive component along s⋆s^\star, then sg→s⋆s_g \to s^\star and ∥Fsg∥→keff\|\mathcal{F}s_g\| \to k_{\mathrm{eff}}, and the error in the shape falls by about the dominance ratio ∣k2∣/keff|k_2|/k_{\mathrm{eff}} per cycle. This is the convergence theorem of power iteration. The theorem above holds for a fixed number of cycles; it does not say that a run with a finite NN and very many cycles has a mean equal to keffk_{\mathrm{eff}}.

The bias for finite NN (cited). With a finite NN, the source is random, and E[FΠ/∥FΠ∥]E[\mathcal{F}\Pi/\|\mathcal{F}\Pi\|] is not FE[Π]/∥FE[Π]∥\mathcal{F}E[\Pi]/\|\mathcal{F}E[\Pi]\|, because the normalization is a nonlinear map. So the stationary mean of the source is not exactly the fundamental mode, and the mean of kgk_g differs from keffk_{\mathrm{eff}}. Brissenden and Garlick (1986) show that this bias is of order 1/N1/N. We do not prove this here. In the 25 runs of the page, the mean of kk is 1.119311.11931 with a standard error of 0.00712/25=0.00140.00712/\sqrt{25} = 0.0014, about half a standard error from the SNS_N value 1.120061.12006, so the bias is not visible at this accuracy (a measurement).

Theorem 2 (the variance of the mean of correlated cycles). Let kI+1,…,kI+Ak_{I+1}, \ldots, k_{I+A} be a stationary sequence with the variance σ2\sigma^2 and the correlations ρj=Corr⁡(kg,kg+j)\rho_j = \operatorname{Corr}(k_g, k_{g+j}). Then the mean kˉ\bar k of line L12 has

Var⁡(kˉ)=σ2A(1+2∑j=1A−1(1−jA)ρj).\operatorname{Var}(\bar k) = \frac{\sigma^2}{A}\Big(1 + 2\sum_{j = 1}^{A - 1}\Big(1 - \frac{j}{A}\Big)\rho_j\Big).

The naive estimate of line L12, the sample variance divided by AA, estimates σ2/A\sigma^2/A (up to a term of order 1/A1/A), so it is too small when the ρj\rho_j are positive.

Proof. Var⁡(kˉ)=A−2∑g,hCov⁡(kg,kh)\operatorname{Var}(\bar k) = A^{-2}\sum_{g, h}\operatorname{Cov}(k_g, k_h). There are AA terms with g=hg = h, each σ2\sigma^2, and for each j≥1j \ge 1 there are 2(A−j)2(A - j) terms with ∣g−h∣=j|g - h| = j, each σ2ρj\sigma^2\rho_j. Adding them gives the formula. □\square

The correlations come from the bank: a cycle with more sites in a region starts more neutrons there in the next cycle. The cited paper of Ueki, Brown, Parsons and Kornreich relates the decay of the ρj\rho_j for tallies of the source shape to the dominance ratio. The 25 independent runs of the page are a measurement of this effect: the ratio of the true spread to the naive error is 1.021.02 for kk and 2.102.10 for a local tally.

Complexity

In the real RAM model, one neutron costs O(K)O(K) steps of lines L5 to L8, where KK is the mean number of collisions; in an infinite medium K=Σt/(Σt−Σs)K = \Sigma_t/(\Sigma_t - \Sigma_s), which is 10 in the example. A cycle costs O(NK)O(NK), and G=I+AG = I + A cycles cost O(GNK)O(GNK). The bank holds at most one site per collision for νΣf/(Σtk)<1\nu\Sigma_f/(\Sigma_t k) < 1, so the memory is O(NK)O(NK) in the worst case and about NN sites in a normal cycle. The statistical error of kk falls like 1/AN1/\sqrt{AN} when the cycles are about independent, and more slowly when the dominance ratio is close to 1.

Properties

  • Not exact. The result has a statistical error and a bias of order 1/N1/N.
  • Analog transport inside a cycle. Lines L4 to L8 use the same flight and collision rules as a fixed-source run, so the method works with any geometry and any cross section data.
  • Correlated cycles. Each source comes from the previous bank, so the kgk_g and every tally are serially correlated, and the more so as the dominance ratio approaches 1.
  • Slow source convergence in large systems. The error in the shape falls by about the dominance ratio per cycle, which is 0.990.99 for a 100 cm slab of the example material in diffusion theory.

Variants and improvements

  • Other estimators of kk. The absorption estimator scores νΣf/Σa\nu\Sigma_f/\Sigma_a at each absorption, and the track-length estimator scores νΣf\nu\Sigma_f times each flight length. Production codes combine the three with weights from their covariances.
  • Implicit capture. Neutrons survive collisions with a reduced weight, and the bank uses the weight in line L7.
  • Other source normalizations. Line L10 can take every banked site and change the weights instead of resampling, or keep a variable number of neutrons per cycle.
  • Faster convergence. Wielandt shifts, the fission matrix method and coarse mesh finite difference acceleration reduce the effective dominance ratio, at the cost of extra work per cycle.
  • Better error bars. Batching cycles, or estimating the correlations between cycles and correcting the variance, gives honest error bars for local tallies.

When to use it

Use a Monte Carlo criticality calculation when keffk_{\mathrm{eff}} or the power distribution of a system must be known with exact geometry and continuous energy data, for example for the safety of fuel storage and transport, for reactor design checks, and as a reference for deterministic codes. A deterministic eigenvalue solve is cheaper when the geometry and the cross sections can be simplified, and it gives the whole flux shape without noise.

Pitfalls

  • Too few inactive cycles (line L11). The first cycles have the wrong source and a biased kk. Check the fission source entropy and the local tallies, not only kk.
  • A first source far from the fissile material (line L1). If the first sites are in a region with no fuel, line L7 banks few or no sites; spread the first source over all fissile regions.
  • Too few neutrons per cycle (line L10). The bias is of order 1/N1/N, and with small NN some fuel regions can lose all their sites. Use at least some thousands of neutrons per cycle in a real problem.
  • The naive error bar (line L12). It assumes independent cycles. For local tallies in large systems it can be several times too small.
  • No division by the old kk (line L7). Without it, the bank grows or shrinks by a factor kk per cycle. Resampling then still gives NN sites, but the bank cost and the variance of the resampling change from cycle to cycle.
  • An empty bank (line L10). In a strongly subcritical system with few neutrons, a cycle can bank no sites. The implementation stops with an error.

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.

monte_carlo_criticality.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/monte-carlo-criticality/. The authors are listed in prov/1ER0M9.jsonl.
"""Monte Carlo criticality calculation: power iteration over fission generations.

The model is one-speed transport in a bare slab 0 <= x <= L with vacuum on
both faces (L = math.inf gives an infinite medium). The medium has a total
cross section sigma_t, a scattering cross section sigma_s and a production
cross section nu_sigma_f, all in cm^-1. Scattering and fission emission are
isotropic. A cycle follows N source neutrons with weight 1 by analog play:

- the flight s = -ln(xi) / sigma_t;
- at a collision, the collision estimate of k gains nu_sigma_f / sigma_t,
  and floor(nu_sigma_f / (sigma_t k) + xi) fission sites are banked, where
  k is the estimate of the previous cycle;
- the neutron scatters with probability sigma_s / sigma_t, else it is absorbed.

The next cycle starts from N sites drawn with replacement from the bank.
The first cycles are inactive: they only let the source converge. The
result is the mean of the cycle estimates of k over the active cycles.

sn_k_eigenvalue is an independent deterministic reference: discrete
ordinates with diamond differences and power iteration on the fission source.
"""

import math


def shannon_entropy(sites, length, bins):
    """H = -sum p_j log2 p_j of the sites over `bins` equal bins of [0, length]."""
    counts = [0] * bins
    for x in sites:
        j = min(bins - 1, max(0, int(x / length * bins)))
        counts[j] += 1
    n = len(sites)
    return -sum(c / n * math.log2(c / n) for c in counts if c > 0)


def run_cycle(source, length, sigma_t, sigma_s, nu_sigma_f, k_prev, rng):
    """Follow every source site once. Returns (bank of fission sites, collision estimate of k)."""
    has_faces = not math.isinf(length)
    p_scatter = sigma_s / sigma_t
    k_score = nu_sigma_f / sigma_t
    bank = []  # @line L3
    total = 0.0
    for x in source:  # @line L4
        mu = 2.0 * rng.random() - 1.0
        while True:  # @line L5
            x += mu * (-math.log(1.0 - rng.random()) / sigma_t)
            if has_faces and (x < 0.0 or x > length):
                break  # the neutron leaks
            total += k_score  # @line L6
            n_sites = int(k_score / k_prev + rng.random())  # @line L7
            bank.extend([x] * n_sites)
            if rng.random() >= p_scatter:  # @line L8
                break  # absorbed
            mu = 2.0 * rng.random() - 1.0
    return bank, total / len(source)


def monte_carlo_criticality(length, sigma_t, sigma_s, nu_sigma_f, n, inactive, active, rng, bins=20, k0=1.0, start=None):
    """Power iteration with n neutrons per cycle.

    The first source is uniform in the slab, or n sites at the point `start`.
    Returns a dict with the mean k over the active cycles, its naive standard
    error (which treats the cycles as independent), the k of every cycle and
    the Shannon entropy of the fission bank of every cycle."""
    if math.isinf(length):
        source = [0.0] * n  # every point of an infinite medium is the same
    elif start is not None:
        source = [start] * n
    else:
        source = [length * rng.random() for _ in range(n)]  # @line L1
    k = k0
    k_cycles, entropies = [], []
    for cycle in range(inactive + active):  # @line L2
        bank, k_c = run_cycle(source, length, sigma_t, sigma_s, nu_sigma_f, k, rng)
        if not bank:
            raise RuntimeError("the fission bank is empty; the system is far below critical or n is too small")
        k = k_c  # @line L9
        k_cycles.append(k_c)
        if not math.isinf(length):
            entropies.append(shannon_entropy(bank, length, bins))
        source = [bank[int(rng.random() * len(bank))] for _ in range(n)]  # @line L10
    act = k_cycles[inactive:]  # @line L11
    mean = sum(act) / len(act)  # @line L12
    var = sum((v - mean) ** 2 for v in act) / (len(act) - 1) if len(act) > 1 else 0.0
    return {"k": mean, "std_error": math.sqrt(var / len(act)), "k_cycles": k_cycles, "entropy": entropies}


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_sweep(q, h, sigma_t, nodes, weights):
    """Scalar flux of one transport sweep with isotropic source density q per cell and vacuum faces."""
    m = len(q)
    phi = [0.0] * m
    for mu, wt in zip(nodes, weights):
        a = abs(mu) / h
        order = range(m) if mu > 0 else range(m - 1, -1, -1)
        psi_in = 0.0
        for i in order:
            psi_out = ((a - 0.5 * sigma_t) * psi_in + 0.5 * q[i]) / (a + 0.5 * sigma_t)
            phi[i] += wt * 0.5 * (psi_in + psi_out)
            psi_in = psi_out
    return phi


def sn_k_eigenvalue(length, sigma_t, sigma_s, nu_sigma_f, cells=80, order=8, tol=1e-9, parity=1, max_iter=5000):
    """k of the slab by S_N with diamond differences.

    One iteration is one sweep with the source sigma_s phi + nu_sigma_f phi / k,
    which converges to the same fixed point as nested power and source iteration.
    parity=1 starts from a symmetric flux (the fundamental mode); parity=-1 starts
    from an antisymmetric one, which the iteration keeps, and gives the first
    odd mode, so that k_odd / k_even is the dominance ratio.
    Returns (k, phi)."""
    h = length / cells
    nodes, weights = gauss_legendre(order)
    xs = [(i + 0.5) * h for i in range(cells)]
    phi = [1.0 if parity == 1 else math.cos(math.pi * x / length) for x in xs]
    k = 1.0
    for _ in range(max_iter):
        fission = sum(phi) * nu_sigma_f
        q = [sigma_s * p + nu_sigma_f * p / k for p in phi]
        new = sn_sweep(q, h, sigma_t, nodes, weights)
        k_new = k * sum(new) * nu_sigma_f / fission if parity == 1 else k * sum(abs(v) for v in new) / sum(abs(v) for v in phi)
        if abs(k_new - k) < tol and max(abs(a - b) for a, b in zip(new, phi)) < tol * max(abs(v) for v in new):
            return k_new, new
        scale = max(abs(v) for v in new)
        phi = [v / scale for v in new]
        k = k_new
    return k, phi
test_monte_carlo_criticality.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/monte-carlo-criticality/. The authors are listed in prov/1ER0M9.jsonl.
import math
import random

import pytest

from monte_carlo_criticality import (
    gauss_legendre,
    monte_carlo_criticality,
    run_cycle,
    shannon_entropy,
    sn_k_eigenvalue,
)


class FixedRng:
    """Returns the given numbers in order, so that a cycle can be checked by hand."""

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

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


def test_hand_trace_of_one_neutron():
    # L = 2, sigma_t = 1, sigma_s = 0.5, nu_sigma_f = 0.6, k_prev = 1, one site at x = 1.
    # r = 0.75: mu = 0.5. r = 0.5: s = ln 2, x = 1.346574. Score 0.6.
    # r = 0.3: floor(0.6 + 0.3) = 0 sites. r = 0.2 < 0.5: scatter. r = 0.0: mu = -1.
    # r = 0.6: s = -ln 0.4 = 0.916291, x = 0.430283. Score 0.6, total 1.2.
    # r = 0.7: floor(0.6 + 0.7) = 1 site. r = 0.9 >= 0.5: absorbed.
    rng = FixedRng([0.75, 0.5, 0.3, 0.2, 0.0, 0.6, 0.7, 0.9])
    bank, k = run_cycle([1.0], 2.0, 1.0, 0.5, 0.6, 1.0, rng)
    assert k == pytest.approx(1.2)
    assert len(bank) == 1
    assert bank[0] == pytest.approx(1.0 + 0.5 * math.log(2.0) - math.log(2.5), abs=1e-12)
    assert bank[0] == pytest.approx(0.430283, abs=1e-6)


def test_leak_on_first_flight():
    rng = FixedRng([1.0 - 1e-12, 0.99])  # mu close to 1, flight -ln(0.01) = 4.6 > L - x
    bank, k = run_cycle([1.0], 2.0, 1.0, 0.5, 0.6, 1.0, rng)
    assert bank == [] and k == 0.0


def test_entropy_values():
    assert shannon_entropy([0.3] * 50, 1.0, 8) == 0.0
    assert shannon_entropy([(j + 0.5) / 8 for j in range(8)], 1.0, 8) == pytest.approx(3.0)
    assert shannon_entropy([0.1, 0.1, 0.9, 0.9], 1.0, 2) == pytest.approx(1.0)


def test_infinite_medium_k_inf():
    # k_inf = nu_sigma_f / sigma_a = 0.12 / 0.1 = 1.2; each neutron has 1 / (1 - c) = 10 collisions.
    r = monte_carlo_criticality(math.inf, 1.0, 0.9, 0.12, 500, 2, 20, random.Random(1))
    assert abs(r["k"] - 1.2) < 4.0 * r["std_error"]
    assert 0.004 < r["std_error"] < 0.02


def test_gauss_legendre():
    nodes, weights = gauss_legendre(8)
    assert sum(weights) == pytest.approx(2.0, abs=1e-13)
    for p in range(0, 16):  # exact for polynomials of degree 2n - 1 = 15
        exact = 2.0 / (p + 1) if p % 2 == 0 else 0.0
        assert sum(w * x**p for x, w in zip(nodes, weights)) == pytest.approx(exact, abs=1e-13)


def test_sn_reference_limits():
    # A very thick slab tends to k_inf; a thin one leaks and has k below the diffusion value.
    k_thick, _ = sn_k_eigenvalue(400.0, 1.0, 0.9, 0.12, cells=200, order=8)
    assert k_thick == pytest.approx(1.2, abs=2e-3)
    k_slab, phi = sn_k_eigenvalue(20.0, 1.0, 0.9, 0.12, cells=80, order=8)
    assert 1.1088 < k_slab < 1.2  # above the diffusion value without extrapolation, 1.108804
    assert min(phi) > 0.0 and phi[0] == pytest.approx(phi[-1], rel=1e-9)  # positive and symmetric
    k_odd, _ = sn_k_eigenvalue(20.0, 1.0, 0.9, 0.12, cells=80, order=8, parity=-1)
    assert 0.80 < k_odd / k_slab < 0.87  # the dominance ratio


def test_bare_slab_against_sn():
    k_ref, _ = sn_k_eigenvalue(20.0, 1.0, 0.9, 0.12, cells=80, order=8)
    r = monte_carlo_criticality(20.0, 1.0, 0.9, 0.12, 500, 10, 30, random.Random(2))
    assert abs(r["k"] - k_ref) < 4.0 * r["std_error"] + 0.003
    assert len(r["k_cycles"]) == 40 and len(r["entropy"]) == 40


def test_entropy_rises_from_a_point_source():
    r = monte_carlo_criticality(20.0, 1.0, 0.9, 0.12, 1000, 0, 30, random.Random(3), start=1.0)
    h = r["entropy"]
    assert h[0] < 3.0  # the first bank is near x = 1
    late = sum(h[20:]) / 10
    assert 4.05 < late < 4.32  # near the entropy of the fundamental mode, 4.185, and below log2(20)
    assert sum(r["k_cycles"][:2]) / 2 < sum(r["k_cycles"][20:]) / 10  # early cycles leak more

History

The method of successive generations was among the first uses of Monte Carlo for reactors. Lieberoth (1968) described the method with a fixed number of neutrons per cycle and studied the convergence of the source. Brissenden and Garlick (1986) analyzed the bias of kk that comes from the normalization of each generation and the bias of its error estimate. Ueki, Brown, Parsons and Kornreich (2003) related the correlation between cycles to the dominance ratio, and Ueki and Brown introduced the Shannon entropy of the source as a convergence diagnostic.

References

  1. J. Lieberoth, A Monte Carlo technique to solve the static eigenvalue problem of the Boltzmann transport equation, Nukleonik 11, 1968, 213, the generation method with a fixed number of source neutrons and the convergence of the fission source
  2. R. J. Brissenden and A. R. Garlick, Biases in the estimation of Keff and its error by Monte Carlo methods, Annals of Nuclear Energy 13(2), 1986, 63-83, the bias of k of order 1/N from the normalization of each generation, and the bias of the error estimate from the correlation between generations
  3. Taro Ueki, Forrest B. Brown, D. Kent Parsons and Drew E. Kornreich, Autocorrelation and dominance ratio in Monte Carlo criticality calculations, Nuclear Science and Engineering 145, 2003, 279, the correlation between cycles and its relation to the dominance ratio
  4. Ivan Lux and Laszlo Koblinger, Monte Carlo Particle Transport Methods, Neutron and Photon Calculations, CRC Press, 1991, the chapter on the Monte Carlo solution of eigenvalue problems
  5. Jerome Spanier and Ely M. Gelbard, Monte Carlo Principles and Neutron Transport Problems, Addison-Wesley, 1969, Dover reprint 2008, the chapter on the Monte Carlo solution of the criticality problem

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