Algorithm Search⌘K

Algorithmcore

Track-length estimator

Also called track-length tally.

Estimates the scalar flux in a region by summing weight times the path length of every track segment inside it, divided by the number of histories and the volume.

Time
O(N K B) average
Space
O(B) extra
Where
B = the number of bins that a flight crosses; K = the mean number of flights per history; N = the number of histories
Properties
randomizedexactiterativerandomized
Origin
Jerome Spanier, Ely M. Gelbard, 1969

The track-length estimator turns the histories of a Monte Carlo transport run into an estimate of the scalar flux in a region. Every straight flight of a particle of weight ww scores ww times the length of the part of the flight that lies inside the region; the sum divided by the number of histories NN and the volume VV is an unbiased estimate of the average flux. The reason is that the scalar flux is the total path length travelled per unit volume per source particle. The collision estimator estimates the same quantity from collisions only. The track-length estimator scores from every particle that crosses the region, so it has a much lower variance in thin regions, and it is the only one of the two that works in a void; the collision estimator needs no path geometry and can be better in dense regions. Next-event estimation and path tracing score expected contributions at points instead.

In plain words

The flux in a box tells how much travel happens in it. If ten particles each fly one centimetre in a box of one cubic centimetre, the flux is ten. So, to measure the flux, add up the length of every piece of path inside the box, and divide by the size of the box and the number of particles.

A particle that crosses the box without any collision still adds its path. That is why this method works well in a box of thin gas or even an empty box, where almost nobody hits an atom. The cost is geometry: the code must find where each flight enters and leaves each box.

The problem

The problem is the same as for the collision estimator: estimate the average scalar flux per source particle

ϕˉj=1Vj∫Bjϕ(r) dr\bar\phi_j = \frac{1}{V_j} \int_{B_j} \phi(r)\, dr

over tally regions BjB_j, from NN histories of analog Monte Carlo transport or of a fair weighted game. A history is a chain of straight flights. A flight starts at rr in direction Ω\Omega and has path length ss; its track length in BjB_j is the length of {r+tΩ:0≤t≤s}∩Bj\{r + t\Omega : 0 \le t \le s\} \cap B_j. The code below uses a slab 0≤x≤L0 \le x \le L cut into bins of width Δx\Delta x. A flight from x0x_0 to x1x_1 with direction cosine μ\mu has the track length ∣x1−x0∣/∣μ∣|x_1 - x_0|/|\mu|, and it splits among the bins it crosses by the part of [x0,x1][x_0, x_1] in each bin.

The algorithm

  1. TRACK-LENGTH-ESTIMATOR(N, SOURCE, bins)
  2. 1for n ← 1 to N do
  3. 2(x, μ) ← SOURCE(), w ← 1, h ← 0 ▷ h holds the scores of this history
  4. 3loop
  5. 4s ← -ln(ξ) / Σ_t ▷ free flight
  6. 5for each bin j that the flight crosses do h_j ← h_j + w · (path length of the flight in bin j)
  7. 6if the particle left the system then break
  8. 7with probability Σ_a / Σ_t break ▷ absorbed
  9. 8μ ← a new direction from the scattering law
  10. 9S_j ← S_j + h_j, Q_j ← Q_j + h_j² for every bin j
  11. 10return φ_j = S_j / (N V_j), with s_j = sqrt((Q_j / N - (S_j / N)²) / (N - 1)) / V_j

Line L5 is the difference with the collision estimator. A flight that leaves the system scores only up to the face. With reflecting faces, the flight scores each straight piece between reflections. In a heterogeneous medium, the flight crosses region faces during free-flight sampling, and the code scores each piece as it crosses; with delta tracking there are no face crossings, and the code must find the bin crossings in a separate step. For a reaction rate, line L5 scores wΣrℓw \Sigma_r \ell instead of wℓw \ell.

Example

Two histories by hand. A beam enters a pure absorber of 2 cm with Σt=1 cm−1\Sigma_t = 1\ \mathrm{cm}^{-1}, with two bins of 1 cm. The first history draws a flight −ln⁡0.75=0.287682-\ln 0.75 = 0.287682 cm and is absorbed in bin 0, which scores 0.2876820.287682. The second history draws a flight ln⁡10=2.302585\ln 10 = 2.302585 cm and leaves at x=2x = 2, which scores 1 cm in each bin. So ϕ0=1.287682/2=0.643841\phi_0 = 1.287682/2 = 0.643841 and ϕ1=1.0/2=0.5\phi_1 = 1.0/2 = 0.5 per source particle.

A slanted flight. A flight from x=0.25x = 0.25 with μ=0.5\mu = 0.5 and a path length of 1 cm ends at x=0.75x = 0.75. With bins of 0.5 cm, it lies for 0.250.25 cm in xx in each of the first two bins, so each bin scores 0.25/0.5=0.50.25/0.5 = 0.5 cm of path.

Against the collision estimator. The two estimators were run on the same problems with N=20000N = 20000 (random.Random(1) to random.Random(3)). For a beam on a pure absorber of 2 cm with Σt=1 cm−1\Sigma_t = 1\ \mathrm{cm}^{-1} and four bins:

bin exact collision track length
[0, 0.5] 0.786939 0.7869 ± 0.0069 0.7836 ± 0.0023
[0.5, 1] 0.477302 0.4776 ± 0.0060 0.4774 ± 0.0032
[1, 1.5] 0.289499 0.2798 ± 0.0049 0.2927 ± 0.0030
[1.5, 2] 0.175590 0.1795 ± 0.0040 0.1805 ± 0.0026

In a slab of 1 cm with c=0.5c = 0.5 and four bins, the first bin gives these values as Σt\Sigma_t goes down:

Σt\Sigma_t (cm−1\mathrm{cm}^{-1}) beam, collision beam, track length isotropic source, collision isotropic source, track length
1 1.149 ± 0.016 1.177 ± 0.006 0.795 ± 0.014 0.804 ± 0.010
0.1 1.136 ± 0.048 1.071 ± 0.007 1.638 ± 0.058 1.658 ± 0.028
0.01 1.160 ± 0.152 1.011 ± 0.004 2.780 ± 0.238 2.737 ± 0.103

The collision estimator gets worse as the slab gets thinner, because fewer particles collide and each score 1/Σt1/\Sigma_t is larger. For a beam the track-length error even goes down, because an uncollided particle scores exactly Δx\Delta x. For an isotropic source the track-length error also grows, but more slowly: a particle that flies almost parallel to the faces has a long path in one bin. These numbers are measurements, not bounds.

Correctness

The claim is a theorem: for an analog game or a fair weighted game, E[ϕj]=ϕˉjE[\phi_j] = \bar\phi_j for every NN, with no condition on Σt\Sigma_t; it holds in a void too. The proof uses the track-length density: the expected total weighted path length that histories travel in a small volume drdr around rr, with directions in dΩd\Omega, is ψ(r,Ω) dr dΩ\psi(r, \Omega)\, dr\, d\Omega, where ψ\psi is the angular flux. This holds because a flight from a collision or source point carries its weight along the path with survival probability e−τe^{-\tau}, which is the uncollided part of the transport solution, and the sum over flights is the Neumann series again. Integration over the bin and all directions gives ∫Bjϕ\int_{B_j} \phi. The full proof is below.

The score of one flight is at most the flight length, so the variance is finite when the flights have finite second moments, which holds when Σt\Sigma_t is bounded below by a positive constant or the region is bounded. In an unbounded void a flight can be infinite, but then the particle leaves and the score is the bounded chord of the bin.

Proof: The track-length estimator is unbiased for the average fluxfull

We assume exact arithmetic and exact independent uniform random numbers, and the analog game of analog Monte Carlo transport, in which every history ends with probability 1 and the number of flights has a finite second moment. The argument for a fair weighted game is the same with weights. Write a phase space point as p=(r,Ω)p = (r, \Omega) (energy can be added as one more coordinate), Σt(r)≥0\Sigma_t(r) \ge 0 for the total cross section, and τ(r,Ω,t)=∫0tΣt(r+t′Ω) dt′\tau(r, \Omega, t) = \int_0^t \Sigma_t(r + t'\Omega)\, dt' for the optical depth along a ray.

The flight starts. Let χ(p)\chi(p) be the density of the starting points of flights: the source points, plus the points just after a scattering. By the same summation over generations as for the collision density, E[number of flights starting in A]=∫AχE[\text{number of flights starting in } A] = \int_A \chi, and in the analog game χ=q+∫KsF\chi = q + \int K_s F, where qq is the source density and the second term is the density of scattered particles leaving collisions. The integral form of the linear Boltzmann transport equation states that the angular flux is the uncollided transport of χ\chi:

ψ(r,Ω)=∫0∞χ(r−tΩ,Ω) e−τ(r−tΩ,Ω,t) dt.(1)\psi(r, \Omega) = \int_0^\infty \chi(r - t\Omega, \Omega)\, e^{-\tau(r - t\Omega, \Omega, t)}\, dt. \qquad (1)

This is the definition of the emission density χ\chi in the integral equation, and (1) is the integral form of the streaming and absorption part, Ω⋅∇ψ+Σtψ=χ\Omega \cdot \nabla \psi + \Sigma_t \psi = \chi, solved along each characteristic.

Lemma 1 (one flight). For a flight that starts at p0=(r0,Ω)p_0 = (r_0, \Omega), the expected track length in a set BB of positions is ∫0∞1[r0+tΩ∈B] e−τ(r0,Ω,t) dt\int_0^\infty \mathbf{1}[r_0 + t\Omega \in B]\, e^{-\tau(r_0, \Omega, t)}\, dt.

Proof. The flight covers the ray up to its path length SS, which satisfies P(S>t)=e−τ(r0,Ω,t)P(S > t) = e^{-\tau(r_0, \Omega, t)} by free-flight sampling (if the ray leaves the system, the flight stops at the face, and for later tt the indicator of BB is 0 because BB is inside the system). The track length in BB is ∫0S1[r0+tΩ∈B] dt=∫0∞1[t<S] 1[r0+tΩ∈B] dt\int_0^S \mathbf{1}[r_0 + t\Omega \in B]\, dt = \int_0^\infty \mathbf{1}[t < S]\, \mathbf{1}[r_0 + t\Omega \in B]\, dt. Taking expectations and exchanging the expectation and the integral (the integrand is non-negative) gives the claim. □\square

Lemma 2 (one history). The total track length hh of one history in BB satisfies E[h]=∫B∫ψ(r,Ω) dΩ dr=∫Bϕ(r) drE[h] = \int_B \int \psi(r, \Omega)\, d\Omega\, dr = \int_B \phi(r)\, dr.

Proof. Sum Lemma 1 over the flights of the history. Given its starting point, each flight has the law of Lemma 1, so by the tower rule and the definition of χ\chi,

E[h]=∫χ(r0,Ω)∫0∞1[r0+tΩ∈B] e−τ(r0,Ω,t) dt dr0 dΩ.E[h] = \int \chi(r_0, \Omega) \int_0^\infty \mathbf{1}[r_0 + t\Omega \in B]\, e^{-\tau(r_0, \Omega, t)}\, dt\, dr_0\, d\Omega.

Change variables to the end point r=r0+tΩr = r_0 + t\Omega for fixed Ω\Omega and tt; the map r0↦rr_0 \mapsto r is a translation with Jacobian 1. Then

E[h]=∫∫B∫0∞χ(r−tΩ,Ω) e−τ(r−tΩ,Ω,t) dt dr dΩ=∫B∫ψ(r,Ω) dΩ drE[h] = \int \int_B \int_0^\infty \chi(r - t\Omega, \Omega)\, e^{-\tau(r - t\Omega, \Omega, t)}\, dt\, dr\, d\Omega = \int_B \int \psi(r, \Omega)\, d\Omega\, dr

by (1). The exchanges of integrals are valid because everything is non-negative. □\square

Theorem (unbiased). The estimate ϕB=SB/(NV)\phi_B = S_B/(N V) of line L10 satisfies E[ϕB]=1V∫Bϕ drE[\phi_B] = \frac{1}{V}\int_B \phi\, dr for every N≥1N \ge 1, also where Σt=0\Sigma_t = 0, and Var[ϕB]=Var[h]/(NV2)\mathrm{Var}[\phi_B] = \mathrm{Var}[h]/(N V^2).

Proof. SBS_B is the sum of NN independent copies of hh, one per history, so E[SB]=NE[h]E[S_B] = N E[h] and Var[SB]=NVar[h]\mathrm{Var}[S_B] = N \mathrm{Var}[h]. Lemma 2 gives the mean. Nothing in Lemmas 1 and 2 needs Σt>0\Sigma_t > 0 in BB. ■\blacksquare

Finite variance. If BB is bounded with diameter DD, each flight contributes at most DD, so h≤D⋅nfh \le D \cdot n_f with nfn_f the number of flights, and Var[h]≤D2E[nf2]<∞\mathrm{Var}[h] \le D^2 E[n_f^2] < \infty. The central limit theorem then gives the asymptotic error bar of line L10.

The slab. In a slab, positions are x∈[0,L]x \in [0, L], the bins are intervals and Ω\Omega reduces to μ\mu. A flight from x0x_0 with path length SS ends at x0+μSx_0 + \mu S, and the path length in a bin [a,b][a, b] is the length of [min⁡(x0,x0+μS),max⁡(x0,x0+μS)]∩[a,b][\min(x_0, x_0 + \mu S), \max(x_0, x_0 + \mu S)] \cap [a, b] divided by ∣μ∣|\mu|, which is what line L5 adds. For a beam on a pure absorber with μ=1\mu = 1, the history is one flight, and Lemma 1 gives E[h]=∫abe−Σtx dxE[h] = \int_a^b e^{-\Sigma_t x}\, dx for the bin [a,b][a, b], the same exact value as for the collision estimator.

Complexity

Each flight costs O(1)O(1) plus the work to find its crossings with the bins. With uniform bins in a slab this is O(1)O(1) per crossed bin, so a run costs O(NKB)O(N K B) with KK flights per history and BB bins crossed per flight; with a mesh tally that is not aligned with the geometry, a ray walk through the mesh does the same work. The space is O(B)O(B) for the sums. In a code where the tally regions are the cells of the geometry, the crossings are found anyway by free-flight sampling, and the tally is almost free.

Properties

  • Unbiased everywhere. Including voids and thin regions, where the collision estimator fails or is noisy.
  • Scores without collisions. Every particle that crosses the region scores, so the number of scores per history is high in thin regions.
  • Bounded scores. The score of one flight is at most its length, or the longest chord of the region. A long chord near a grazing direction is the main source of variance for an isotropic source in a thin region.
  • Path geometry. It needs the intersection of each flight with the tally regions, which costs more than the collision estimator when the tally mesh is not the geometry.

Variants and improvements

  • Reaction rates. Score wΣr(E)ℓw \Sigma_r(E) \ell for the rate of reaction rr; this is the usual estimator of the fission source and of heating in production codes.
  • Expected track length. Score at each flight the expected track length in the region along the ray, the integral of e−τ(t)e^{-\tau(t)} over the path lengths tt at which the ray is inside the region, instead of the sampled one. It has a lower variance, at the cost of an integral per flight.
  • Surface current and surface flux. On a surface, count crossings with weight ww for the current, and with weight w/∣μ∣w/|\mu| for the surface flux, the limit of the track-length estimator for a thin bin. The surface flux estimator has an infinite variance for grazing crossings, so codes cut off small ∣μ∣|\mu|.
  • Combined estimators. A weighted combination of the track-length, collision and absorption estimates with weights from the sample covariance has a lower variance than each one; it is used for keffk_{\mathrm{eff}} in criticality codes.

When to use it

Use the track-length estimator for fluxes and reaction rates in cells of the geometry, in thin regions, in gases, in voids and on fine mesh tallies in optically thin parts of the problem. Use the collision estimator in dense regions with many short flights and when path lengths in the tally regions are expensive to find. For a flux at a point, use next-event estimation.

Pitfalls

  • The factor 1/∣μ∣1/|\mu|. In slab geometry the path length in a bin is the depth in xx divided by ∣μ∣|\mu|. A code that scores the depth in xx underestimates the flux.
  • Truncated flights. A flight that leaves the system or reaches a reflecting face must score only to the face, and then the rest after the reflection.
  • Delta tracking. With delta tracking the tentative flights do not stop at region faces, so the tally must clip each flight to the bins itself. Scoring at the tentative collisions instead gives a collision estimator with the majorant cross section.
  • Grazing flights. For an isotropic source in a thin bin, rare flights almost parallel to the faces give large scores. The estimate stays unbiased, but its error falls slowly and the error bar converges slowly.
  • Per-flight variance. As for every tally, the variance must come from the history totals.

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.

track_length_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/track-length-estimator/. The authors are listed in prov/QW4YNY.jsonl.
"""Track-length estimator of the scalar flux in a one-speed slab.

The slab is 0 <= x <= L with total and scattering cross sections sigma_t
and sigma_s (cm^-1) and isotropic scattering, cut into equal bins of
width dx. Each history follows one particle of weight 1 with analog Monte
Carlo. Every flight is a straight segment; the part of the segment that
lies in bin j has path length |overlap in x| / |mu|, and the history
scores w times that length into bin j. The estimate is

    phi_j = (sum of scores in bin j) / (N * dx),

the average flux over the bin per source particle. In one dimension the
bin "volume" is its width dx. The standard error comes from the variance
of the per-history scores.

The faces are "vacuum" or "reflect" (specular reflection). A flight that
reaches a vacuum face scores up to the face and ends the history.
"""

import math


def uniform_open(rng) -> float:
    return 1.0 - rng.random()


def beam_source(length, rng):
    """A normally incident beam on the left face."""
    return 0.0, 1.0


def uniform_isotropic_source(length, rng):
    """A source uniform in x on [0, L] and isotropic in direction."""
    return length * rng.random(), 2.0 * rng.random() - 1.0


def score_segment(a, b, mu, w, dx, nbins, hist):
    """Add w * (path length in bin j) for the x interval between a and b."""
    lo, hi = min(a, b), max(a, b)
    j = min(int(lo / dx), nbins - 1)
    while j < nbins and j * dx < hi:
        overlap = min(hi, (j + 1) * dx) - max(lo, j * dx)
        if overlap > 0.0:
            hist[j] = hist.get(j, 0.0) + w * overlap / abs(mu)
        j += 1


def fly(x, mu, s, length, faces, w, dx, nbins, hist):
    """Move a distance s and score every piece of the path. Returns (x, mu, inside)."""
    if mu == 0.0:  # a flight parallel to the faces stays in its bin
        j = min(int(x / dx), nbins - 1)
        hist[j] = hist.get(j, 0.0) + w * s
        return x, mu, True
    while True:
        face = length if mu > 0.0 else 0.0
        d = (face - x) / mu  # path length to the face
        if s <= d:
            x_new = x + s * mu
            score_segment(x, x_new, mu, w, dx, nbins, hist)
            return x_new, mu, True
        score_segment(x, face, mu, w, dx, nbins, hist)
        if faces == "vacuum":
            return face, mu, False
        s -= d
        x, mu = face, -mu


def track_length_estimator(n, length, sigma_t, sigma_s, nbins, rng, source=beam_source, faces="vacuum"):
    """Returns (phi, se): flux per source particle in each bin, and its standard error."""
    dx = length / nbins
    p_abs = (sigma_t - sigma_s) / sigma_t
    total = [0.0] * nbins
    total_sq = [0.0] * nbins
    for _ in range(n):  # @line L1
        x, mu = source(length, rng)  # @line L2
        w = 1.0
        hist = {}
        while True:  # @line L3
            s = -math.log(uniform_open(rng)) / sigma_t  # @line L4
            x, mu, inside = fly(x, mu, s, length, faces, w, dx, nbins, hist)  # @line L5
            if not inside:  # @line L6
                break
            if rng.random() < p_abs:  # @line L7
                break
            mu = 2.0 * rng.random() - 1.0  # @line L8
        for j, v in hist.items():  # @line L9
            total[j] += v
            total_sq[j] += v * v
    phi, se = [], []
    for j in range(nbins):  # @line L10
        mean = total[j] / n
        var = (total_sq[j] / n - mean * mean) * n / (n - 1)
        phi.append(mean / dx)
        se.append(math.sqrt(max(var, 0.0) / n) / dx)
    return phi, se
test_track_length_estimator.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/track-length-estimator/. The authors are listed in prov/QW4YNY.jsonl.
import math
import random

import pytest

from track_length_estimator import fly, track_length_estimator, uniform_isotropic_source


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

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


def expint(order, z, steps=2000):
    """E_n(z) = integral over u in (0, 1] of exp(-z/u) u^(n-2) du, by Simpson's rule (n >= 2)."""
    if z == 0.0:
        return 1.0 / (order - 1)
    h = 1.0 / steps
    total = 0.0
    for k in range(steps + 1):
        u = k * h
        f = 0.0 if u == 0.0 else math.exp(-z / u) * u ** (order - 2)
        total += f * (1 if k in (0, steps) else (4 if k % 2 else 2))
    return total * h / 3.0


def test_one_history_by_hand():
    # Beam on a slab of 2 cm, sigma_t = 1, pure absorber, two bins of 1 cm.
    # r = 0.25: xi = 0.75, flight -ln 0.75 = 0.287682, all in bin 0. r = 0.5: absorbed.
    phi, _ = track_length_estimator(1 + 1, 2.0, 1.0, 0.0, 2, FixedRng([0.25, 0.5, 0.9, 0.5]))
    # The second history: r = 0.9 gives a flight ln 10 = 2.302585, which leaves the slab.
    # It scores 1 cm in each bin. Totals: bin 0 = 1.287682, bin 1 = 1.0; N = 2.
    assert phi == pytest.approx([1.287682 / 2, 1.0 / 2], abs=1e-6)


def test_slanted_segment_and_reflection():
    hist = {}
    fly(0.25, 0.5, 1.0, 2.0, "vacuum", 1.0, 0.5, 4, hist)  # x goes from 0.25 to 0.75
    assert hist == pytest.approx({0: 0.5, 1: 0.5})
    hist = {}
    x, mu, inside = fly(1.5, 1.0, 1.0, 2.0, "reflect", 1.0, 1.0, 2, hist)
    assert inside and x == pytest.approx(1.5) and mu == -1.0
    assert hist == pytest.approx({1: 1.0})


def test_pure_absorber_beam_exact():
    sig, length, nb, n = 1.0, 2.0, 4, 20000
    phi, se = track_length_estimator(n, length, sig, 0.0, nb, random.Random(1))
    dx = length / nb
    for j in range(nb):
        exact = (math.exp(-sig * j * dx) - math.exp(-sig * (j + 1) * dx)) / (sig * dx)
        assert abs(phi[j] - exact) < 4.0 * se[j]


def test_reflecting_slab_is_infinite_medium():
    length, sig_t, sig_s, n = 2.0, 1.0, 0.5, 6000
    phi, se = track_length_estimator(n, length, sig_t, sig_s, 4, random.Random(2), uniform_isotropic_source, "reflect")
    exact = (1.0 / length) / (sig_t - sig_s)
    for p, e in zip(phi, se):
        assert abs(p - exact) < 4.0 * e


def test_pure_absorber_volume_source_against_e3():
    length, sig, nb, n = 2.0, 1.0, 4, 20000
    phi, se = track_length_estimator(n, length, sig, 0.0, nb, random.Random(3), uniform_isotropic_source)
    q, dx = 1.0 / length, length / nb
    for j in range(nb):
        a, b = j * dx, (j + 1) * dx
        left = (expint(3, sig * a) - expint(3, sig * b)) / sig
        right = (expint(3, sig * (length - b)) - expint(3, sig * (length - a))) / sig
        exact = q / (2.0 * sig * dx) * (2.0 * dx - left - right)
        assert abs(phi[j] - exact) < 4.0 * se[j]


def collision_tally(n, length, sig_t, sig_s, nbins, rng):
    """A plain collision estimator on the same problem, for comparison."""
    dx, p_abs = length / nbins, (sig_t - sig_s) / sig_t
    tot, tot_sq = [0.0] * nbins, [0.0] * nbins
    for _ in range(n):
        x, mu = 0.0, 1.0  # a normal beam on the left face
        hist = [0.0] * nbins
        while True:
            x += mu * -math.log(1.0 - rng.random()) / sig_t
            if not 0.0 <= x <= length:
                break
            hist[min(int(x / dx), nbins - 1)] += 1.0 / sig_t
            if rng.random() < p_abs:
                break
            mu = 2.0 * rng.random() - 1.0
        for j in range(nbins):
            tot[j] += hist[j]
            tot_sq[j] += hist[j] ** 2
    mean = [t / n for t in tot]
    se = [math.sqrt((s / n - m * m) / (n - 1)) / dx for s, m in zip(tot_sq, mean)]
    return [m / dx for m in mean], se


def test_thin_slab_track_length_beats_collision():
    # In an optically thin slab few histories collide, so the collision tally is noisy.
    # With a normal beam, every uncollided particle scores exactly dx in each bin.
    length, sig_t, sig_s, nb, n = 1.0, 0.1, 0.05, 4, 8000
    phi_t, se_t = track_length_estimator(n, length, sig_t, sig_s, nb, random.Random(4))
    phi_c, se_c = collision_tally(n, length, sig_t, sig_s, nb, random.Random(5))
    for j in range(nb):
        assert abs(phi_t[j] - phi_c[j]) < 4.0 * math.hypot(se_t[j], se_c[j])
        assert se_t[j] < 0.5 * se_c[j]

History

The interpretation of the scalar flux as the track length per unit volume is old in reactor physics, and early Monte Carlo codes scored track lengths in their cells. Spanier and Gelbard gave the track-length and collision estimators side by side, with their variances, in their 1969 book. Lux and Koblinger gave a general theory of transport estimators, including expected-value variants, in 1991. The track-length estimator is the standard flux tally of production codes today.

References

  1. Jerome Spanier and Ely M. Gelbard, Monte Carlo Principles and Neutron Transport Problems, Addison-Wesley, 1969, Dover reprint 2008, the estimators of linear functionals of the flux, with the track-length estimator
  2. Ivan Lux and Laszlo Koblinger, Monte Carlo Particle Transport Methods, Neutron and Photon Calculations, CRC Press, 1991, the chapter on estimators, with the track-length estimator and its comparison with the collision estimator
  3. E. E. Lewis and W. F. Miller, Jr., Computational Methods of Neutron Transport, Wiley, 1984, the chapter on the Monte Carlo method, with the flux tallies

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