# Honghu.jl documentation, all pages

Every page of the documentation site in one file, generated from [the repository](https://github.com/chongchonghe/Honghu.jl) at commit `e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a`. Each page below is also published on its own, as HTML and as Markdown.


---

<!-- page: index.md -->

# Honghu.jl

[![](https://zenodo.org/badge/DOI/10.5281/zenodo.23569081.svg)](https://doi.org/10.5281/zenodo.23569081)

<p align="center"><img src="figures/honghu-logo.png" alt="Honghu.jl logo" width="300"></p>

Honghu is named after 鸿鹄 (hóng hú), an ancient Chinese term for the large, high-flying swan.

**Three-dimensional radiation magnetohydrodynamics in pure Julia, written for teaching, laptop runs, and method development.**

Honghu ([He 2026](https://doi.org/10.5281/zenodo.23569082)) solves the Euler equations, or the equations of ideal MHD, coupled to the two-moment (M1) radiation transport equations (grey or multigroup) in one, two, or three dimensions on a uniform Cartesian grid. It implements the algorithms of [Quokka](https://github.com/quokka-astro/quokka), a GPU code for astrophysical radiation hydrodynamics ([Wibking & Krumholz 2022](https://scixplorer.org/abs/2022MNRAS.512.1430W/abstract); [He, Wibking & Krumholz 2024a](https://scixplorer.org/abs/2024MNRAS.531.1228H/abstract), [2024b](https://scixplorer.org/abs/2024MNRAS.535.3059H/abstract); [He et al. 2026](https://scixplorer.org/abs/2026OJAp....959235H/abstract)), in compact, readable Julia so that students can study them and developers can test changes quickly.

Documentation: <https://chongchonghe.github.io/Honghu.jl/> holds this README, a reference built from every docstring, a guide to the physics, numerics and code design of each physics module (so far photochemistry and MHD), and the technical notes in `docs/`. Each page is also published as Markdown, and `honghu-docs.md` holds all of them in one file.

## Speed against Athena++

Athena++ ([Stone et al. 2020](https://scixplorer.org/abs/2020ApJS..249....4S/abstract)) is a production MHD code in C++, tuned for Intel CPUs and compilers. On one core of an AMD Threadripper PRO 7975WX (Zen 4), Honghu runs Athena++'s own MHD blast at **91% of Athena++'s speed**. The problem is `inputs/mhd/athinput.blast` (PLM, HLLD, CFL 0.3, periodic) at $128^3$ as one block, 40 steps, no output:

| Code | Build | Mcell-updates/s |
|:---|:---|---:|
| Athena++ | Intel icpx, `-O3 -ipo -qopenmp-simd -march=native -fp-model=precise` | 2.91 |
| **Honghu** | Julia 1.13 | **2.64** |

Honghu does no reassociation and no approximate division, so Athena++ is built with IEEE-precise floating point too: both codes then do the arithmetic the source says. The schemes are close but not the same: Athena++'s VL2 predictor is a first-order half step, cheaper than the first of Honghu's two PLM stages of SSP-RK2, Honghu's HLLD carries the Minoshima & Miyoshi (2021) low-Mach and carbuncle terms, and its constrained transport is Q26 with LD04 averaging rather than Gardiner & Stone's. The builds and the flags tried are in [`notes/performance-findings.md`](https://github.com/chongchonghe/Honghu.jl/blob/main/notes/performance-findings.md). Honghu's side of the table:

```bash
julia --project=. -t 1 notes/performance-experiments/athena_blast.jl 128 40
```

## Why Honghu

For over a decade, [pyro](https://github.com/python-hydro/pyro2) ([Zingale 2014](https://scixplorer.org/abs/2014A%26C.....6...52Z/abstract); [Harpole et al. 2019](https://scixplorer.org/abs/2019JOSS....4.1265H/abstract)) has been a standard way to learn computational hydrodynamics through readable 2D finite-volume solvers in Python. Honghu brings that style (short kernels, built-in test problems, and single-call execution and plotting) to three dimensions, ideal MHD with constrained transport, and grey or multigroup M1 radiation.

- On one core of an Apple M5 Max laptop, a $128^3$ blast wave runs at 8.3 million cell updates per second with hydrodynamics, 3.3 million with radiation, and 3.4 million with MHD; on four cores, hydrodynamics reaches 23 million. Every hot kernel is multithreaded and allocation-free, guarded by allocation tests in the suite (see [Performance](#performance)). On one core of a Linux server, Honghu runs Athena++'s MHD blast at 91% of the speed of Athena++ compiled with `icpx` (see [the comparison](#speed-against-athena) above).
- The solvers match Quokka's: HLLC with Batten wave speeds, Rider's correction, and the Minoshima & Miyoshi carbuncle cure; PPM; SSP Runge-Kutta; HLLD and constrained transport for MHD; the M1 system with an HLL solver; and the IMEX PD-ARS integrator for stiff matter-radiation coupling. Kernels are structured to transliterate directly to Quokka's C++ and back.
- Honghu is the reference implementation of the adaptive reduced speed of light approximation ([He, Krumholz & Wibking 2026](https://scixplorer.org/abs/2026arXiv261121353H/abstract)), using an exact von Neumann stability bound for the scheme, and `examples/irsla_paper.jl` reproduces every number and data file in Section 5 of that paper. Its matter-radiation coupling reduces each cell's implicit step to a single scalar equation and converges on all 240 cells of a stress test spanning optical depths from $10^{-4}$ to $10^{12}$, where Quokka's $(1+N_g)$ Newton formulation fails on 75. Dust-gas thermal coupling reduces to a single scalar equation in the same way. Algorithms proven here port directly to Quokka, and a Brent's method fix found during coupling tests was upstreamed to SciML's BracketingNonlinearSolve.
- Over 2400 tests check exact Riemann solutions, analytic diffusion and Marshak waves, the Sedov blast, the Lowrie & Edwards radiative shocks (including the Zel'dovich spike), measured convergence orders, and exact conservation, directional isotropy, and positivity. Every figure on this page is generated by scripts in `docs/`; see [Verification](#verification).
- Adding an equation of state, opacity law, Riemann solver, reconstruction scheme, coupling solver, or speed-of-light limiter only requires defining a type and a few methods. Julia's multiple dispatch compiles user types into the core kernels without overhead; see [Extending](#extending).
- Honghu depends on three standard libraries and four SciML packages; plotting is a package extension that loads only when you load Plots. It is tested on Julia 1.10 (LTS) and newer in CI, and every page of the [documentation site](https://chongchonghe.github.io/Honghu.jl/) is published as both HTML and Markdown (bundled in `honghu-docs.md` and indexed by `llms.txt`).

| Kelvin-Helmholtz instability | Sedov blast |
|:---:|:---:|
| ![Kelvin-Helmholtz](figures/kh.gif) | ![Sedov blast](figures/sedov.gif) |
| $512^2$, PPM + SSPRK3 | density in the mid-plane slice, $64^3$, PPM + SSPRK3 |
| **M1 radiation shadow** | **Orszag-Tang MHD vortex** |
| ![shadow](figures/shadow.gif) | ![Orszag-Tang](figures/orszag_tang.gif) |
| $500\times200$, a beam striking an opaque clump; colour is $\log_{10}E_r$ over ten decades | density, $256^2$, HLLD + constrained transport, PPM + SSPRK2 |

## What it solves

**Hydrodynamics.** The compressible Euler equations,

$$\partial_t \rho + \nabla\cdot(\rho\mathbf{v}) = 0, \qquad \partial_t (\rho\mathbf{v}) + \nabla\cdot(\rho\mathbf{v}\mathbf{v} + P\mathbb{I}) = \mathbf{f}_\mathrm{rad}, \qquad \partial_t E + \nabla\cdot[(E+P)\mathbf{v}] = \dot{e}_\mathrm{rad},$$

with an ideal-gas equation of state.

**Magnetohydrodynamics.** With `Simulation(mhd = true)`, the equations of ideal MHD, with the field face-centred and advanced by constrained transport, so that $\nabla\cdot\mathbf{b}$ stays at round-off. The scheme is Quokka's: the HLLD Riemann solver, the Q26 EMF and [Londrillo & Del Zanna (2004)](https://scixplorer.org/abs/2004JCoPh.195...17L/abstract) averaging; with piecewise-constant reconstruction it reproduces Quokka's shock tubes to round-off. Radiation and photochemistry run on a magnetised gas.

**Radiation.** The first two angular moments of the radiative transfer equation, closed with the [Levermore (1984)](https://scixplorer.org/abs/1984JQSRT..31..149L/abstract) M1 closure,

$$\partial_t E_r + \frac{\hat{c}}{c}\nabla\cdot\mathbf{F}_r = S, \qquad \partial_t \mathbf{F}_r + \hat{c}\,c\,\nabla\cdot(\mathbb{T}E_r) = \mathbf{S}_F,$$

where $\mathbb{T}(\mathbf{f})$ is the Eddington tensor built from the reduced flux $\mathbf{f} = \mathbf{F}_r/(cE_r)$. Unlike flux-limited diffusion, M1 interpolates between the free-streaming limit ($\mathbb{T}\to\hat{n}\hat{n}$, where radiation travels in straight lines and casts shadows) and the diffusion limit ($\mathbb{T}\to\mathbb{I}/3$).

Each frequency group carries its own pair of moment equations. The default is a single grey group; see [Multigroup radiation](#multigroup-radiation).

## Numerical method

Space and time are separated by the method of lines: a spatial operator $L(U) = -(F_{i+1/2}-F_{i-1/2})/\Delta x$ is assembled once per stage, and the stages are pure ODE updates.

| Component | Choice |
|:---|:---|
| Reconstruction | piecewise constant (`PCM`), piecewise linear (`PLM`, four limiters), piecewise parabolic (`PPM`) |
| Hydro Riemann solver | `HLLC` (default) with Batten wave speeds, Rider's nonlinear correction, and the [Minoshima & Miyoshi (2021)](https://scixplorer.org/abs/2021JCoPh.44610639M/abstract) carbuncle cure and low-dissipation pressure; or `LLF` |
| MHD | `HLLD` (default; [Miyoshi & Kusano 2005](https://scixplorer.org/abs/2005JCoPh.208..315M/abstract) with the [Minoshima & Miyoshi 2021](https://scixplorer.org/abs/2021JCoPh.44610639M/abstract) corrections), `LLFMHD` or `HLLMHD`; constrained transport with the Q26 EMF and LD04 averaging |
| Radiation Riemann solver | `HLL` on the M1 system with frozen-Eddington-tensor wave speeds ([Skinner & Ostriker 2013](https://scixplorer.org/abs/2013ApJS..206...21S/abstract); [Balsara 1999](https://scixplorer.org/abs/1999JQSRT..61..617B/abstract)) |
| Hydro time integration | SSP Runge-Kutta, first to third order (`ForwardEuler`, `SSPRK2` (default), `SSPRK3`) |
| Radiation time integration | IMEX PD-ARS: transport explicit, stiff matter coupling implicit; second order and asymptotic-preserving |
| Matter-radiation coupling, grey | 2×2 Newton-Raphson per cell in $(E_\mathrm{int}, R)$, with an analytic flux/momentum update and a lagged outer iteration for the $\mathbf{v}\cdot\mathbf{F}$ work term |
| Matter-radiation coupling, $N_g$ groups | a $(1+N_g)$-dimensional implicit solve per cell, by one of three interchangeable [coupling solvers](#matter-radiation-coupling-solvers) |

Radiation subcycles inside each hydro step at the reduced speed of light $\hat{c}$. A degenerate direction (`n[d] == 1`) carries no ghost cells and is skipped entirely, so 1D and 2D problems cost what they should.

## Install and run

Honghu requires Julia 1.10 (the LTS release) or newer. There are two ways to install it.

**1. As a package.** In the Julia REPL, in the environment of your own project:

```julia
using Pkg; Pkg.develop(url = "https://github.com/chongchonghe/Honghu.jl")
using Honghu

# optionally, install Plots package for plotting
Pkg.add("Plots")
```

`Pkg.develop` clones the repository into `~/.julia/dev/Honghu`, so you can read and edit the source there.

**2. From a clone.** Clone the repository and start Julia in it, with the repository as the active project:

```bash
# optionally, install Plots for plotting in the global environment
julia -e 'using Pkg; Pkg.add("Plots")'

git clone https://github.com/chongchonghe/Honghu.jl
cd Honghu.jl
julia --project=. -e 'using Pkg; Pkg.instantiate()'   # once, to install the dependencies
julia --project=. -t auto                             # start Julia with threads
```

Then, in the Julia REPL:

```julia
using Honghu
```

A shock tube in five lines:

```julia
sim = Simulation(n = (256, 1, 1), eos = IdealGas(gamma = 1.4), boundaries = Boundaries(Outflow()))
set_initial_conditions!(sim) do x, y, z
    x < 0.5 ? (rho = 1.0, p = 1.0) : (rho = 0.125, p = 0.1)
end
run!(sim, tmax = 0.2)
```

Optionally, plot the result with `plotstate` (it needs `using Plots`, see [Plotting](#plotting)):

```julia
using Plots
p = plotstate(sim)
display(p)      # density against x
plotpanels(sim) # density, speed, pressure, temperature
```

If no window opens, see [Plotting](#plotting).

A 3D radiation-hydrodynamics run, writing snapshots for ParaView:

```julia
rad = RadiationPhysics(c = 2.998e10, chat = 2.998e8, a_rad = 7.5657e-15,
                       opacity = ConstantOpacity(0.4))
sim = Simulation(n = (128, 128, 128), xhi = (1e15, 1e15, 1e15),
                 eos = IdealGas(gamma = 5/3, cv = cv_from_mu(0.6, 5/3)),
                 radiation = rad, boundaries = Boundaries(Outflow()))
set_initial_conditions!(sim) do x, y, z
    (rho = 1e-20, T = 10.0, Erad = 7.5657e-15 * 10.0^4)
end
run!(sim, tmax = 1e5, outdir = "out", dtout = 1e4)
```

Honghu has defined a set of standard test problems that are ready to run in `Honghu.Problems`, listed in [Built-in problems](#built-in-problems). Each returns `(sim, tmax)`, a simulation with its initial conditions set and the end time of the test, ready to `run!`. Here the 3D Sedov blast at $128^3$ runs to $t = 0.001$ (short of its `tmax`):

```julia
sim, tmax = Honghu.Problems.sedov_blast(n = 128)
run!(sim; tmax = 0.001)
display(plotstate(sim, var = :speed))
plotpanels(sim) # density, speed, pressure, temperature
```

`run!` ends by printing its performance. On 4 threads of an Apple M5 Max it reads

```
done: 88 steps, t = 0.001, 16.29 s (1.13e+07 cell-updates/s) on 4 threads
```

`animate_run` takes the place of `run!` when you want an animation: it advances the simulation to `tmax`, draws a frame of `var` at `nframes` evenly spaced times, and writes a GIF. Here the 2D Kelvin-Helmholtz instability at $128^2$ first runs to $t = 1$ with `run!`, writing a VTK snapshot every 0.1 into `kh/` (`data_00000.vti`, ..., for ParaView), and is then animated from $t = 1$ to $t = 3$ into `kh.gif`. On 4 threads the two take about 4 s and 10 s:

```julia
sim, tmax = Honghu.Problems.kelvin_helmholtz(n = 128)
run!(sim; tmax=1, outdir = "kh", dtout = 0.1)
animate_run(sim; tmax=3, nframes = 100, var = :density, fps = 20, filename = "kh.gif", c = :plasma)
```

To run a script with threads (see [Threads](#threads)), for example one of the examples:

```bash
julia --project=. -t auto examples/sod_1d.jl   # from a clone
julia -t auto script.jl                        # with the package installed
```

## Built-in problems

Each returns `(sim, tmax)`, ready to `run!`:

```julia
sim, tmax = Honghu.Problems.kelvin_helmholtz(n = 512)
run!(sim; tmax, outdir = "kh", dtout = 0.02)
```

| Problem | Tests |
|:---|:---|
| `sod_shock_tube` | shocks, contacts, rarefactions against `sod_exact` |
| `smooth_advection` | order of accuracy of the reconstruction |
| `kelvin_helmholtz` | 2D shear instability, exact conservation |
| `sedov_blast` | 3D strong explosion, spherical symmetry on a Cartesian grid |
| `radiation_streaming` | free-streaming limit: the front must move at exactly $\hat{c}$ |
| `radiation_diffusion` | static diffusion limit against an analytic Gaussian |
| `matter_coupling` | stiff energy exchange, equilibrium and exact energy conservation |
| `marshak_wave` | non-equilibrium radiation-driven heat wave |
| `marshak_vaytet` | the same wave with a $\nu^{-2}$ opacity and $N_g$ groups, which a grey run cannot reproduce |
| `radhydro_shock` | Mach 3 radiative shock against the Lowrie & Edwards semi-analytic solution |
| `radiation_shadow` | M1 casting a sharp shadow behind an opaque clump |
| `brio_wu`, `ryu_jones_2a` | MHD shock tubes, against Quokka |
| `alfven_wave` | oblique circularly polarised Alfven wave: second-order convergence of MHD |
| `orszag_tang` | 2D MHD vortex with interacting shocks, $\nabla\cdot\mathbf{b}$ at round-off |

The scripts in `examples/` run and post-process these problems. When Plots is installed, every example writes a figure by default alongside its VTK or text output:

```bash
julia --project=. -t auto examples/sod_1d.jl              # -> sod.png, sod.txt, sod_exact.txt
julia --project=. -t auto examples/sod_1d.jl 1024         # positional arguments still work
julia --project=. -t auto examples/sod_1d.jl --no-plot    # data only, for batch jobs
julia --project=. -t auto examples/sod_1d.jl --outdir=run # send everything somewhere else
```

Without Plots, the examples still write their data files and print a one-line note on how to enable plotting.

## Comparing schemes

`compare` runs a problem across schemes and grid resolutions, scores each run with the problem's metrics, prints a summary table, and writes it to disk.

```julia
using Honghu
const P = Honghu.Problems

compare(P.sod_shock_tube, :riemann, (HLLC(), LLF()); sizes = (64, 128, 256, 512))
```

```
  variant        size       cells       steps      wall_s  l1_density
  HLLC             64          64          69    0.002033     0.01004
  HLLC            128         128         139    0.001882    0.004942
  ...
  (zero for every run: floors, newton_mean, newton_max, newton_failures)
  convergence rate, -dlog(metric)/dlog(size):
  variant  l1_density
  HLLC           0.95
  LLF            0.97
```

You can sweep any keyword that the problem forwards to `Simulation` (such as `:reconstruction`, `:integrator`, `:closure`, or `:cfl`), and each value labels its own rows. When a variant needs more than one keyword, pass a NamedTuple of keyword sets:

```julia
compare(P.radhydro_shock, (P1 = (closure = EddingtonClosure(),),
                           M1 = (closure = LevermoreClosure(),)); sizes = (64, 128, 256))
```

Under the hood, a variant is a builder function mapping resolution to `(sim, tmax)`, the same signature used by the built-in problem factories. Passing builders directly lets variants differ in initial conditions, geometry, or global settings:

```julia
compare(["flat"  => nx -> setup(nx, amplitude = 0.1),
         "steep" => nx -> setup(nx, amplitude = 0.9)];
        sizes = (64, 128, 256), metrics = default_metrics(P.smooth_advection))
```

Every built-in problem takes `n` for resolution (with `nx` accepted as an alias).

You can also pass simulations you have already constructed:

```julia
a, _ = P.sod_shock_tube(n = 256, riemann = HLLC())
b, _ = P.sod_shock_tube(n = 256, riemann = LLF())
compare("HLLC" => a, "LLF" => b; tmax = 0.2, metrics = default_metrics(P.sod_shock_tube))
```

Because a `Simulation` instance has a fixed grid, passing pre-built simulations runs a single resolution without a convergence rate, and `plotcompare` renders the result as a bar chart. You must supply `tmax` because `Simulation` does not store a stopping time; `compare` runs the simulations in place so you can plot them afterward.

Each row also records `steps`, `wall_s`, `floors`, and the Newton iteration counts, showing whether a lower error came from taking smaller steps or hitting the positivity floors. The first run of each variant is a warm-up that is discarded before timing.

`compare` writes the table to a text file stamped with the git commit hash, and `plotcompare` reads that file directly:

```julia
using Plots
plotcompare("sod_shock_tube_riemann_compare.txt",
            "smooth_advection_riemann_compare.txt")   # the same schemes, two problems
```

Problems with an exact or reference solution define `default_metrics` in `src/problems/metrics.jl`; for other problems, pass `metrics = (; name = sim -> ...)` explicitly.

`examples/compare_schemes.jl` compares HLLC and LLF on both a shock tube and a smooth advection wave.

## Verification

Every figure below is regenerated by `julia --project=. -t auto docs/make_figures.jl`, or by running the test suite with `--figures`. Each compares the code against something independent: an exact Riemann solution, an analytic diffusion solution, a measured convergence slope, or a similarity solution.

```bash
julia --project=. -t 4 test/runtests.jl             # 2430 tests, ~2.5 min
julia --project=. -t auto test/runtests.jl --figures # ... and redraw the figures below
```

| | |
|:---:|:---:|
| ![Sod shock tube](figures/sod.png) | ![convergence](figures/convergence.png) |
| **Sod shock tube** against the exact Riemann solution at $t = 0.2$, 256 cells. | **Order of accuracy** on smooth advection. PCM, PLM and PPM sit on their expected slopes. |
| ![radiation diffusion](figures/diffusion.png) | ![Marshak wave](figures/marshak.png) |
| **Static diffusion limit** against the analytic Gaussian $\sigma^2 = \sigma_0^2 + 2Dt$. The answer is independent of how many mean free paths a cell spans, which is the asymptotic-preserving property. | **Marshak wave**: radiation runs ahead of the matter, so $T_{\rm rad}$ and $T_{\rm gas}$ separate at the front and merge behind it. |
| ![Sedov blast](figures/sedov.png) | ![shadow](figures/shadow.png) |
| **Sedov blast**, $96^3$. Every cell in the box collapses onto one radial profile, and the shock sits on the Sedov-Taylor radius. | **M1 shadow**. The clump removes the beam over ten decades; a diffusion-based scheme would let radiation leak around it. |

![radiative shock](figures/radshock.png)

**Mach 3 radiative shock** ([Lowrie & Edwards 2008](https://scixplorer.org/abs/2008ShWav..18..129L/abstract)), against the semi-analytic solution. This optically thick, strongly coupled shock has a radiative precursor ahead of the front and a Zel'dovich spike just behind it, where the matter temperature overshoots its downstream equilibrium value ($4.26$ against $3.66$). Capturing the spike requires the velocity-dependent coupling terms, the implicit solve, and the shock-capturing reconstruction to work together. Relative $L_1$ error in $T_\mathrm{rad}$ is $0.19\%$ at 256 cells, compared with Quokka's $1\%$ tolerance.

The test suite (`julia --project=. -t 4 test/runtests.jl`, 2430 tests, ~2.5 min) checks:

- Smooth-advection convergence rates of 1 for PCM, 2 for PLM, and 2.3 for PPM (PPM stops below 3 because the Colella-Woodward monotonicity constraint flattens the parabola at the two extrema of the sine wave, as in Athena++ and Quokka).
- Toro's five shock tubes, including the "123" near-vacuum problem and both strong blasts, without triggering positivity floors.
- Conservation of mass, momentum, and total energy to $10^{-14}$ relative on periodic boundaries, and bitwise-comparable profiles when the same 1D problem is run along $x$, $y$, or $z$.
- Radiation free streaming with the front arriving at $\hat{c}t$ to 2% and $|\mathbf{F}| \le cE$ everywhere, and static diffusion with relative $L_1$ errors of 0.6%, 0.13%, and 0.06% at 64, 128, and 256 cells against the analytic Gaussian regardless of cell optical depth.
- Stiff matter-radiation coupling: a single step $10^{5}$ times longer than the coupling time lands on radiative equilibrium while conserving $E_\mathrm{int} + (c/\hat{c})E_r$ to $10^{-13}$, and radiation momentum transfer matches $\Delta p = (\rho\kappa/c)F_0(1-e^{-\hat{c}\rho\kappa t})/(\hat{c}\rho\kappa)$ to 1% with second-order convergence.
- The Mach 3 radiative shock to $0.19\%$ relative $L_1$ error in $T_\mathrm{rad}$ at 256 cells against the semi-analytic solution, with the Zel'dovich spike at $4.21$ (exact $4.26$) and zero positivity floor repairs.
- Multigroup consistency: at $N_g = 1$ the multigroup source step matches the grey 2×2 driver to round-off across $\kappa \in [0, 10^9]$, an optically thick multigroup cell relaxes onto $a_rT^4f_g(T)$ in every group, and at intermediate optical depths the two single-step coupling solvers converge toward the error-controlled ODE reference at second order in $\Delta t$.

## Performance

The cost of one step, per cell and per CPU core, for the same 3D blast wave at $128^3$ in three forms: the Sedov blast of `Honghu.Problems.sedov_blast`; the same blast with grey M1 radiation coupled to the gas ($\kappa = 100$, about one optical depth per cell, one radiation substep per step); and the same blast in a uniform magnetic field ($\beta = 1$ in the ambient gas). All three use PLM and SSP-RK2, with HLLC for the hydrodynamics and HLLD with constrained transport for MHD. One thread on a laptop (Apple M5 Max), Julia 1.13, `Float64`, measured 2026-11-28:

| | Hydrodynamics (blast wave) | Radiation hydrodynamics (blast wave + grey M1) | Magnetohydrodynamics (magnetised blast wave) |
|:---|---:|---:|---:|
| **Mcell-updates per CPU-second** | **8.32** | **3.34** | **3.38** |
| **CPU-ns per cell-update** | **120** | **299** | **296** |
| reconstruction (PLM) | 16 | 17 | 28 |
| Riemann solver (HLLC, HLLD) | 84 | 84 | 170 |
| flux divergence and stage update | 10 | 10 | 11 |
| EMF and induction (constrained transport) | — | — | 49 |
| radiation transport (HLL) | — | 112 | — |
| matter-radiation coupling (implicit) | — | 53 | — |
| conversions and floors | 6 | 11 | 13 |
| ghost cells | 0.4 | 0.4 | 11 |
| time step | 1 | 1 | 3 |
| other (copies, combines) | 4 | 11 | 10 |

The rows below the totals are CPU-ns per cell-update and add up to the total: a profile of whole steps assigns each sample to the kernel it was in, and the radiation rows hold everything under the transport operator and the coupling solve, ghost cells and floors included. A radiation run with more substeps per step pays the two radiation rows once per substep. With radiation, reconstruction and the Riemann solver cost what they cost without it, and MHD costs 2.5 times hydrodynamics, mostly in the HLLD solver and the edge-centred EMFs. To measure it on your machine:

```bash
julia --project=. -t 1 test/benchmarks.jl        # prints this table; an argument sets n
```

Allocation per step is flat in the grid size (152 KiB for hydrodynamics, 284 KiB with radiation, all of it threading overhead), and `test/test_performance.jl` asserts that every hot kernel stays below 8 bytes per cell to guard against closure-boxing regressions.

### Threads

Honghu runs as one process and spreads its grid loops over Julia's threads, one row of cells, `(j, k)`, per task. The number of threads is set when Julia starts and cannot change in a running session:

```bash
julia --project=. -t 6 script.jl                  # 6 threads
julia --project=. -t auto script.jl               # as many threads as Julia counts CPUs
JULIA_NUM_THREADS=6 julia --project=. script.jl   # the same as -t 6
```

In the REPL, `Threads.nthreads()` gives the number, and the line `run!` prints at the end says how many threads the run used. A 1D run has a single row, so it runs on one thread whatever `-t` asks for; 2D and 3D runs use all of them. On the Apple M5 Max below, which has 6 performance and 12 efficiency cores, `-t auto` gives 6 threads.

The 3D Sedov blast at $128^3$, `Honghu.Problems.sedov_blast(n = 128, reconstruction = PLM())` with SSP-RK2, the default, 20 steps after one warm-up step, Apple M5 Max, Julia 1.13, measured 2026-11-28:

| Threads | 20 steps | per step | throughput |
|:---|---:|---:|---:|
| 1 | 5.11 s | 0.256 s | 8.21 Mcell-updates/s |
| 4 | 1.83 s | 0.091 s | 22.9 Mcell-updates/s |

Four threads are 2.8 times faster than one. To measure it on your machine, save this as `sedov_timing.jl` and run it with `-t 1` and with `-t 4`:

```julia
using Honghu
sim, _ = Honghu.Problems.sedov_blast(n = 128, reconstruction = PLM())
step!(sim)                                         # warm-up: compiles the step
t = @elapsed for _ in 1:20; step!(sim); end
println(Threads.nthreads(), " threads: ", t / 20, " s per step")
```

```bash
julia --project=. -t 1 sedov_timing.jl
julia --project=. -t 4 sedov_timing.jl
```

#### On a compute node

On a 32-core workstation node (AMD Threadripper PRO 7975WX, one NUMA domain), the Sedov blast with PPM and SSP-RK3, the defaults before 2026-11-27, measured with `test/benchmarks_parallel.jl`:

| threads | $128^3$ per step | $256^3$ per step |
|---:|---:|---:|
| 1 | 1.20 s | 9.5 s |
| 8 | 0.20 s | 1.63 s |
| 16 | 0.115 s | 0.88 s |
| 32, pinned | 0.082 s | 0.67 s |
| 64, pinned | 0.078 s | 0.64 s |

From 8 threads on, the hydrodynamic sweeps run on cache-sized boxes of cells rather than whole-grid passes (`Simulation(tile = :auto)`, the default), which lets them keep scaling after the memory bus saturates (on Apple Silicon tiling was slower at every thread count, so `:auto` leaves it off there). When a job has the whole node, pinning threads with `JULIA_EXCLUSIVE=1 julia -t 32` (one thread per physical core, where CPUs `0` to `31` are the physical cores as shown by `lscpu -e`) improves 32-thread speed by about 10%. Avoid pinning a job that uses only part of the node: pinned to CPUs `0` to `15`, a 16-thread run gets only two of the four L3 caches and runs 20% slower than unpinned. Hyperthreads (`-t 64`) add about 5%. `docs/parallel-findings.md` records the full measurements.

**Memory.** Buffers scale as roughly `72 * ncells * 8` bytes when grey radiation is enabled and `35 * ncells * 8` without, where `ncells` includes ghost cells. A $128^3$ radiation-hydrodynamics run uses about 1.4 GB; pure hydrodynamics at $128^3$ uses about 0.7 GB. Every radiation buffer has `4 * ngroups` components per cell, so the radiation half of that footprint scales linearly with the number of frequency groups.

## Output

- `write_vtk(sim, path)` writes a self-contained `.vti` image-data file with raw appended binary and no external library dependencies. ParaView, VisIt, and yt open it directly, and a numbered series (`data_00000.vti`, `data_00001.vti`, ...) loads as a time series.
- `write_line(sim, path; dir, at)` writes a plain-text table along one axis for plotting 1D profiles such as shock tubes and Marshak waves.
- `save_checkpoint` / `load_checkpoint!` read and write raw binary restart files.

`run!(sim; tmax, outdir, dtout)` writes VTK snapshots on a fixed cadence and trims the step so that it lands exactly on the output times.

## Plotting

`field(sim, name)` extracts any named quantity as a plain `(nx, ny, nz)` array and needs no packages:

```julia
rho, label = field(sim, :density)
available_fields(sim)   # :density, :vx, :speed, :pressure, :temperature, :mach, :Erad, :Trad, ...
```

Loading Plots activates a package extension that adds the plotting methods. They pick the representation from the dimensionality: a line in 1D, a heat map in 2D, a mid-plane slice in 3D.

```julia
using Plots, Honghu

sim, tmax = Honghu.Problems.kelvin_helmholtz(n = 128)
run!(sim; tmax)

plot(sim)                                  # a recipe, so plot/plot! work directly
plotstate(sim, var = :Erad, logscale = true)
plotpanels(sim)                            # density, speed, pressure, temperature (+ radiation)
```

`animate_run` makes an animation on the fly: it takes the place of `run!`, advancing the simulation to `tmax` and drawing a frame at `nframes` evenly spaced times, then writes a GIF. It needs no snapshots on disk:

```julia
sim, tmax = Honghu.Problems.kelvin_helmholtz(n = 256)
animate_run(sim; tmax, nframes = 100, var = :density, fps = 20,
            filename = "kh.gif", c = :magma)   # further keywords go to plotstate
```

Calling any of them before loading Plots prints instructions on loading it.

In the REPL or VS Code, `display` opens the figure in a GR window. When running a script from the command line (`julia script.jl`), the process exits as soon as the script finishes, closing the window; call `readline()` after `display` to keep the window open, or save directly to disk with `savefig(plotstate(sim), "sod.png")`. Note that the scripts in `examples/` include `examples/common.jl`, which sets `ENV["GKSwstype"] = "100"` so GR renders off-screen without opening a window; unset that variable or set it to `"gksqt"` if you want interactive windows from an example script.

`docs/make_figures.jl` and `docs/make_animations.jl` regenerate everything shown above.

## Layout

```
Honghu.jl/
  Project.toml   deps: Printf, Dates, LinearAlgebra (stdlibs), OrdinaryDiffEq
                 and SciMLBase; Plots is a weak dependency
  README.md      this file
  CLAUDE.md      invariants, performance traps, and a per-file guide to src/
  logs.md        development log: what was asked for, what was built, why
  future.md      work not done, with enough detail to start; known bugs
  src/           the package -- 33 files, one concern each
    planck.jl    the incomplete Planck integral and RadiationGroups
    newton.jl    the linear solve of one Newton step on a bordered system
    coupling*.jl the coupling interface and the three solvers behind it
    riemann/     one Riemann solver per file, mirroring Quokka's headers
    problems/    built-in problems, exact solutions, per-problem metrics
  ext/           plotting methods, loaded only when Plots is present
  test/          the test suite, plus benchmarks.jl
  docs/          make.jl (the documentation site), make_figures.jl,
                 make_animations.jl, the generated figures/, technical notes
  examples/      sod_1d, kelvin_helmholtz_2d, sedov_3d, compare_schemes,
                 marshak_wave, radiation_shadow, radiating_blast_3d
```

The include order in `src/Honghu.jl` is significant, because later files use types defined earlier. `CLAUDE.md` has the file-by-file table and the invariants each layer relies on.

## Extending

The code is built around small, dispatch-based interfaces. To add your own piece of physics, define a type and a few methods:

```julia
struct KramersOpacity <: Honghu.AbstractOpacity end
Honghu.planck_opacity(::KramersOpacity, rho, T) = 4e25 * rho * T^-3.5
Honghu.flux_mean_opacity(op::KramersOpacity, rho, T) = Honghu.planck_opacity(op, rho, T)
Honghu.energy_mean_opacity(op::KramersOpacity, rho, T) = Honghu.planck_opacity(op, rho, T)
```

The same pattern works for `AbstractEOS`, `AbstractOpacity`, `AbstractLimiter`, `AbstractReconstruction`, `AbstractIntegrator`, `AbstractRiemannSolver`, `AbstractClosure` and `BoundaryCondition`. `test/test_extensions.jl` defines a toy subtype of every one of them and runs a simulation with it, so it doubles as copy-paste documentation of exactly which methods each interface needs.

## Multigroup radiation

The radiation field can be resolved into $N_g$ frequency groups. Each group carries its own energy density and flux through the same M1 solver, and exchanges energy with the gas through its own opacity:

$$\partial_t E_g + \frac{\hat{c}}{c}\nabla\cdot\mathbf{F}_g = \hat{c}\rho\left(\kappa_{P,g}\,a_rT^4f_g(T) - \kappa_{E,g}E_g\right), \qquad g = 1,\dots,N_g,$$

where $f_g(T)$ is the fraction of a Planck spectrum at $T$ that falls in group $g$, computed as the difference of the normalised incomplete Planck integral $P(x) = (15/\pi^4)\int_0^x t^3/(e^t-1)\,\mathrm{d}t$ at the group edges ($x = h\nu/k_BT$). Quokka tabulates $P$ and interpolates; Honghu evaluates it directly with the Bernoulli expansion below $x = 1$ and the exponential tail above, avoiding table generation. The last group takes $1 - \sum(\mathrm{rest})$, so the fractions sum to one and the total emitted energy equals $a_rT^4$ to round-off.

**One group is grey and is the default.** Because `ngroups` is a type parameter, every kernel specialises on it and a single-group run dispatches to the 2×2 grey source driver, matching the grey code path to round-off.

**Groups.** `RadiationGroups` takes $N_g + 1$ increasing edges, or a range and a count. `energy_unit * edge` must have units of energy so that $x = \mathrm{energy}/k_BT$ is dimensionless. Pass `CGS.h_planck` when giving edges in Hz, or leave `energy_unit = 1` to specify edges directly in units of $k_BT$ (as the unit-free test problems do).

```julia
RadiationGroups([0.1, 1.0, 5.0, 20.0])                                # three groups, edges in units of k_B T
RadiationGroups(6e10, 6e14, 4; energy_unit = Honghu.CGS.h_planck)     # four log-spaced groups, edges in Hz
RadiationGroups(6e10, 6e14, 4; spacing = :linear)                     # :log is the default, since a Planck spectrum spans decades
```

The outermost edges act as integration limits: the first group integrates down to `edges[1]` and the last up to `edges[end]`. Both `0.0` and `Inf` are valid, and the grey default is `RadiationGroups([0.0, Inf])`.

**Opacity.** Group opacities are piecewise constant across each group and evaluated at the geometric mean $\sqrt{\nu_g\nu_{g+1}}$ of the group edges (matching Quokka's `piecewise_constant_opacity`). Because a constant opacity cancels out of any spectral average within the group, the Planck, energy, and flux means are equal inside each group. `FrequencyOpacity(f)` takes a function `f(nu, rho, T)` and throws an error if used in a single-group run, since a frequency-dependent law has no well-defined grey evaluation point; passing a grey `AbstractOpacity` subtype to a multigroup run assigns that same $\kappa$ to every group (as in Vaytet's constant-opacity model).

**A run.** Pass `groups`, and `k_B` in whatever units the rest of the problem uses:

```julia
using Honghu
const CGS = Honghu.CGS

groups = RadiationGroups(6e10, 6e14, 4; energy_unit = CGS.h_planck)
rad = RadiationPhysics(c = CGS.c_light, a_rad = CGS.a_rad, k_B = CGS.k_B,
                       groups = groups, beta_order = 0,
                       opacity = FrequencyOpacity((nu, rho, T) -> 2000.0 * (nu / 4e13)^-2))

sim = Simulation(n = (64, 1, 1), xhi = (20.0, 1.0, 1.0), radiation = rad, hydro = false,
                 eos = IdealGas(gamma = 5/3, cv = 1.0),
                 boundaries = Boundaries(Outflow()))
set_initial_conditions!(sim) do x, y, z
    (rho = 1e-3, T = 300.0, Erad = CGS.a_rad * 300.0^4)
end
run!(sim, tmax = 1e-8)
```

Passing a scalar `Erad` in the initial conditions specifies the total radiation energy density, which is distributed across groups according to a Planck spectrum at $T_\mathrm{rad} = (E_\mathrm{rad}/a_r)^{1/4}$. A `Fixed` radiation boundary condition is the only place where you must supply all `4 * ngroups` components explicitly; see `Honghu.Problems.marshak_vaytet` for an example using `planck_fractions`.

Diagnostics default to frequency-integrated totals: `field(sim, :Erad)`, `:Fx`, `:reduced_flux`, and `radiation_temperature` sum over all groups, while a trailing index selects an individual group (such as `field(sim, :Erad_2)`). `available_fields` lists per-group field names whenever `ngroups > 1`.

## Matter-radiation coupling solvers

With $N_g \geq 2$ groups, the implicit energy exchange solves a $(1+N_g)$-dimensional stiff system per cell, selected via the `coupling` keyword of `RadiationPhysics`:

```julia
rad = RadiationPhysics(c = 1.0, a_rad = 1.0, opacity = ConstantOpacity(1e3),
                       groups = groups, coupling = QuokkaCoupling())
```

All coupling solvers read the per-group emission rate and absorption coefficient from `coupling_coefficients`, and the opacity law is carried on the cell state so temperature derivatives ($\mathrm{d}\kappa/\mathrm{d}T$ included) are evaluated directly from the opacity model. `BracketedCoupling` and `AdaptiveCoupling` are built on `coupling_coefficients`, whereas `QuokkaCoupling` is a separate hand-derived formulation in Quokka's variables that shares only its initial guess with them.

| Solver | Description and use case |
|:---|:---|
| `BracketedCoupling()` | **Default production solver.** Backward Euler in $(E_\mathrm{gas}, E_g)$, reduced algebraically to a single scalar equation. Because the group equations are linear in $E_g$ at fixed gas temperature, they can be eliminated in closed form, leaving the cell's energy balance as a scalar function of $E_\mathrm{gas}$ on an interval that brackets the root. By default it uses `Brent()` from BracketingNonlinearSolve (averaging 7.7 evaluations per cell), requires no Jacobian or linear solve, allocates zero bytes, and is the only solver that supports dust-gas coupling. Across a 240-cell stress test covering three opacity laws and $\tau_\mathrm{cell}$ from $10^{-4}$ to $10^{12}$, it converges on all 240 cells. See `docs/coupling-new-method.md` for details. |
| `QuokkaCoupling()` | The $(1+N_g)$ Newton-Raphson solver in Quokka's variables $(E_\mathrm{gas}, R_g)$, where $R_g$ is the energy transferred from gas to group $g$ over the step. Solving for $R_g$ removes $\tau = \hat{c}\rho\kappa\Delta t$ from the residual and keeps the Jacobian well-conditioned at high optical depth. Included for structural parity with Quokka and cross-checking against `BracketedCoupling`. On steeply temperature-dependent opacities its unreduced Newton step can point in the wrong direction, failing on 75 of the 240 stress-test cells. |
| `AdaptiveCoupling()` | An error-controlled stiff ODE integrator (`Rosenbrock23` by default) over the coupling step. Intended as a reference solver to verify single-step solvers against a tight ODE tolerance: it takes tens of internal steps per cell, runs 12 to several hundred times slower than the single-step solvers, and allocates 8 to 21 kB per cell. |

`QuokkaCoupling` also accepts a `linsolve` keyword specifying how each $(1+N_g)\times(1+N_g)$ Newton step is solved. The default, `ArrowheadSolve()`, eliminates the diagonal group block into the gas row in $O(N_g)$ time without forming a matrix; `DenseSolve()` runs a dense LU factorisation on the full matrix. Both `ArrowheadSolve` and `BracketedCoupling`'s closed-form elimination rely on groups coupling only through the gas; adding direct group-to-group exchange (such as Compton redistribution or line overlap) would require `DenseSolve`.

Cells that reach `max_iterations` without converging increment `newton_failures` in the run summary rather than throwing an exception. See [`future.md`](https://github.com/chongchonghe/Honghu.jl/blob/main/future.md) for a reproduction of `QuokkaCoupling` failing to converge when a hot gas cools through a steeply falling opacity.

Single-group runs without dust bypass `coupling` and use the inline 2×2 Newton driver in `src/source_terms.jl` (controlled by `tolerance` and `max_iterations` on `RadiationPhysics`). Setting a dust model routes single-group runs through the multigroup driver and `BracketedCoupling`.

## Source terms

`source = f(x, y, z, t)` specifies a volumetric radiation energy source and is folded into the implicit matter-radiation coupling step, which keeps stiff emission terms stable.

`strang_sources = f(sim, t, dt, order)` is a general operator-split hook called for $\Delta t/2$ before the time step and $\Delta t/2$ after it, mutating `sim.U` and `sim.R` in place. It matches Quokka's `addStrangSplitSources` and is where external forces such as gravity, driving, or optically thin cooling can be attached. Applying two half-steps gives second-order accuracy in time (the trapezoid rule, which integrates linear-in-time sources exactly).

```julia
function gravity!(sim, t, dt, order)
    g = sim.grid
    for k in g.lo[3]:g.hi[3], j in g.lo[2]:g.hi[2], i in g.lo[1]:g.hi[1]
        rho = sim.U[Honghu.IRHO, i, j, k]
        dp = -9.8 * rho * dt
        sim.U[Honghu.IEGAS, i, j, k] += dp * (sim.U[Honghu.IMY, i, j, k] + dp / 2) / rho
        sim.U[Honghu.IMY, i, j, k] += dp
    end
end

Simulation(n = (64, 64, 1), strang_sources = gravity!)
```

Honghu does not ship built-in gravity, cooling, or driving modules; `strang_sources` provides the hook to add them without modifying `step!`. The `order` argument (`SourceForward` or `SourceReverse`) lets you reverse the sequence of multiple non-commuting operators between the two half-steps.

## Units

Honghu is unit-agnostic: `c`, `a_rad`, `cv` and the opacities are all supplied by you. Use `Honghu.CGS` for CGS constants, or set `c = a_rad = cv = 1` and work in code units, as the built-in radiation problems do.

## Choosing radiation parameters

Two dimensionless ratios determine whether a radiation-hydrodynamics setup is in the regime these equations model:

**Radiation-to-gas energy, $a_r T^4 / (\rho c_v T)$.** These equations are non-relativistic and keep only $O(v/c)$ terms in the coupling. A radiation energy density that dominates the gas by many orders of magnitude will accelerate the matter towards $c$, outside the validity of the $O(v/c)$ expansion. Because the ratio scales as $T^3/\rho$, a hot, tenuous medium becomes radiation-dominated quickly: at $10^5$ K, gas domination requires $\rho \gtrsim 4\times10^{-8}\ \mathrm{g\,cm^{-3}}$. Keep the ratio of order unity or below unless the gas remains non-relativistic.

**Reduced speed of light, $\hat{c} / \max(|v| + c_s)$.** The reduced speed of light must still outrun every fluid signal; a factor of about 20 is typical. Lowering $\hat{c}$ increases the radiation timestep (`max_radiation_substeps` caps how many radiation substeps one hydro step may take, shrinking the hydro step if needed), at the cost of rescaling the radiation diffusion coefficient by $\hat{c}/c$. Set $\hat{c} = c$ whenever the static diffusion limit matters quantitatively.

See `examples/radiating_blast_3d.jl` for an example that checks both ratios at startup.

## Limitations

- Uniform Cartesian grids on a single shared-memory node (no adaptive mesh refinement or MPI).
- No self-gravity.
- Multigroup opacity is piecewise constant within each group. Power-law in-group profiles (which separate the Planck, energy, and flux group means in Quokka) and direct group-to-group coupling terms such as Compton redistribution are not implemented.
- Lowering $\hat{c}$ below $c$ rescales the static radiation diffusion coefficient by $\hat{c}/c$.
- **The hydrodynamics-radiation split is first order in time.** Each subsystem is second order on its own (SSP-RK2 by default for hydrodynamics and IMEX PD-ARS for radiation), while `step!` advances hydrodynamics and then radiation via first-order Lie splitting, as in Quokka. In typical runs where radiation subcycles many times per hydro step, the splitting error stays well below the spatial discretisation error. User source terms passed via [`strang_sources`](#source-terms) are Strang-split to second order.

## References

Quokka:

- B. D. Wibking & M. R. Krumholz, 2022, "QUOKKA: a code for two-moment AMR radiation hydrodynamics on GPUs", *MNRAS* 512, 1430. [SciX/ADS](https://scixplorer.org/abs/2022MNRAS.512.1430W/abstract)
- C.-C. He, B. D. Wibking & M. R. Krumholz, 2024a, "An asymptotically correct implicit-explicit time integration scheme for finite volume radiation-hydrodynamics", *MNRAS* 531, 1228. [SciX/ADS](https://scixplorer.org/abs/2024MNRAS.531.1228H/abstract)
- C.-C. He, B. D. Wibking & M. R. Krumholz, 2024b, "A novel numerical method for mixed-frame multigroup radiation-hydrodynamics with GPU acceleration implemented in the QUOKKA code", *MNRAS* 535, 3059. [SciX/ADS](https://scixplorer.org/abs/2024MNRAS.535.3059H/abstract)
- C.-C. He, B. D. Wibking, A. Vijayan, M. R. Krumholz & P. S. Li, 2026, "A novel algorithm for GPU-accelerated particle-mesh interactions implemented in the QUOKKA code", *The Open Journal of Astrophysics* 9, 159235. [SciX/ADS](https://scixplorer.org/abs/2026OJAp....959235H/abstract)

Methods and test problems:

- C.-C. He, 2026, Honghu.jl v0.1.0, Zenodo, [doi:10.5281/zenodo.23569082](https://doi.org/10.5281/zenodo.23569082): this code
- [Stone et al. (2020)](https://scixplorer.org/abs/2020ApJS..249....4S/abstract), *ApJS* 249, 4: Athena++, in the speed comparison
- [He, Krumholz & Wibking (2026)](https://scixplorer.org/abs/2026arXiv261121353H/abstract), arXiv:2611.21353: the adaptive reduced speed of light approximation (`StabilityBound`)
- [Colella & Woodward (1984)](https://scixplorer.org/abs/1984JCoPh..54..174C/abstract), *JCP* 54, 174: PPM
- [Toro (2009)](https://doi.org/10.1007/b79761), *Riemann Solvers and Numerical Methods for Fluid Dynamics*: HLLC, exact Riemann solver
- [Miyoshi & Kusano (2005)](https://scixplorer.org/abs/2005JCoPh.208..315M/abstract), *JCP* 208, 315: HLLD
- [Minoshima & Miyoshi (2021)](https://scixplorer.org/abs/2021JCoPh.44610639M/abstract), *JCP* 446, 110639: low-dissipation HLLD, and its HLLC limit
- [Londrillo & Del Zanna (2004)](https://scixplorer.org/abs/2004JCoPh.195...17L/abstract), *JCP* 195, 17: EMF averaging for constrained transport
- [Levermore (1984)](https://scixplorer.org/abs/1984JQSRT..31..149L/abstract), *JQSRT* 31, 149: M1 closure
- [Balsara (1999)](https://scixplorer.org/abs/1999JQSRT..61..617B/abstract), *JQSRT* 61, 617: frozen-Eddington-tensor wave speeds
- [Skinner & Ostriker (2013)](https://scixplorer.org/abs/2013ApJS..206...21S/abstract), *ApJS* 206, 21: M1 wave speeds, reduced speed of light
- [Chu et al. (2019)](https://scixplorer.org/abs/2019JCoPh.389...62C/abstract), *JCP* 389, 62: IMEX PD-ARS
- [Vaytet et al. (2011)](https://scixplorer.org/abs/2011JQSRT.112.1323V/abstract), *JQSRT* 112, 1323: multigroup M1, and the frequency-dependent Marshak wave
- [Lowrie & Edwards (2008)](https://scixplorer.org/abs/2008ShWav..18..129L/abstract), *Shock Waves* 18, 129: radiative shock solutions
- [Zingale (2014)](https://scixplorer.org/abs/2014A%26C.....6...52Z/abstract), *Astronomy and Computing* 6, 52; [Harpole et al. (2019)](https://scixplorer.org/abs/2019JOSS....4.1265H/abstract), *JOSS* 4, 1265: pyro

## Contributing, support and citing

Questions, bug reports and feature requests are welcome on the [issue tracker](https://github.com/chongchonghe/Honghu.jl/issues). [CONTRIBUTING.md](https://github.com/chongchonghe/Honghu.jl/blob/main/CONTRIBUTING.md) explains how to report a problem, how to propose a change, and how to run the tests and the documentation build. Everyone taking part is expected to follow the [code of conduct](https://github.com/chongchonghe/Honghu.jl/blob/main/CODE_OF_CONDUCT.md). Honghu is maintained by its author, who reads every issue and decides what is merged.

If you use Honghu in your research, please cite the Zenodo record of the version you used; for v0.1.0 that is [10.5281/zenodo.23569082](https://doi.org/10.5281/zenodo.23569082). Every release is archived on Zenodo, and the DOI [10.5281/zenodo.23569081](https://doi.org/10.5281/zenodo.23569081) always resolves to the latest version; each version also has its own DOI, listed on that page. [CITATION.cff](https://github.com/chongchonghe/Honghu.jl/blob/main/CITATION.cff) holds the metadata, and GitHub's "Cite this repository" button formats it.

## License

MIT; see [LICENSE](https://github.com/chongchonghe/Honghu.jl/blob/main/LICENSE).

## Author

[Chong-Chong He](https://chongchonghe.github.io/) (chongchong.he@anu.edu.au).


---

<!-- page: reference/index.md -->

# Reference

```julia
Honghu
```

A three-dimensional radiation-magnetohydrodynamics code in pure Julia.

The Euler equations are solved with an unsplit finite-volume method-of-lines
scheme: piecewise-constant, -linear or -parabolic reconstruction of the
primitive variables, a choice of Riemann solver (HLLC or LLF), and a
strong-stability-preserving Runge-Kutta integrator. With `mhd = true` it
solves ideal MHD instead, with the field face-centred and advanced by
constrained transport (HLLD or LLF, the Q26 EMF and LD04 averaging).

Radiation is treated with the two-moment (M1) approximation, grey or resolved
into `NG` frequency groups (see `RadiationGroups`). Transport uses
an HLL solver built on the M1 closure, and the stiff matter-radiation coupling
is solved implicitly, the two being combined by the second-order,
asymptotic-preserving IMEX PD-ARS scheme. Radiation subcycles inside each hydro
step at the reduced speed of light.

The algorithms follow Quokka (Wibking & Krumholz 2022; He, Wibking & Krumholz
2024).

## Getting started

```julia
using Honghu

sim = Simulation(n = (256, 1, 1), boundaries = Boundaries(Outflow()),
                 eos = IdealGas(gamma = 1.4))
set_initial_conditions!(sim) do x, y, z
    x < 0.5 ? (rho = 1.0, p = 1.0) : (rho = 0.125, p = 0.1)
end
run!(sim, tmax = 0.2)
```

or start from one of the built-in problems:

```julia
sim = Honghu.Problems.kelvin_helmholtz(n = 256)
run!(sim, tmax = 2.0, outdir = "kh", dtout = 0.02)
```

## Pages

- [Simulation and grid](reference/simulation.md): [`Diagnostics`](#Diagnostics), [`reset_diagnostics!`](#reset_diagnostics-bang), [`SourceOrder`](#SourceOrder), [`Simulation`](#Simulation), [`set_initial_conditions!`](#set_initial_conditions-bang), [`timestep`](#timestep), [`step!`](#step-bang), [`nrepaired`](#nrepaired), [`run!`](#run-bang), [`conserved_totals`](#conserved_totals), [`primitives`](#primitives), [`gas_temperature`](#gas_temperature), [`radiation_temperature`](#radiation_temperature), [`CartesianGrid`](#CartesianGrid), [`Periodic`](#Periodic), [`Outflow`](#Outflow), [`Reflecting`](#Reflecting), [`Fixed`](#Fixed), [`FunctionBC`](#FunctionBC), [`Boundaries`](#Boundaries), [`ForwardEuler`](#ForwardEuler), [`SSPRK2`](#SSPRK2), [`SSPRK3`](#SSPRK3)
- [Hydrodynamics](reference/hydro.md): [`IdealGas`](#IdealGas), [`cv_from_mu`](#cv_from_mu), [`Floors`](#Floors), [`MinMod`](#MinMod), [`MonotonizedCentral`](#MonotonizedCentral), [`VanLeer`](#VanLeer), [`Sweby`](#Sweby), [`PCM`](#PCM), [`PLM`](#PLM), [`PPM`](#PPM), [`HLLMHD`](#HLLMHD), [`LLF`](#LLF), [`LLFMHD`](#LLFMHD), [`HydroState`](#HydroState), [`HLLD`](#HLLD), [`HLLC`](#HLLC), [`AbstractRiemannSolver`](#AbstractRiemannSolver), [`AbstractMHDRiemannSolver`](#AbstractMHDRiemannSolver), [`riemann_flux`](#riemann_flux)
- [Magnetohydrodynamics](reference/mhd.md): [`MagneticField`](#MagneticField)
- [Radiation transport](reference/radiation.md): [`RadiationPhysics`](#RadiationPhysics), [`ngroups`](#ngroups), [`LevermoreClosure`](#LevermoreClosure), [`EddingtonClosure`](#EddingtonClosure), [`planck_integral`](#planck_integral), [`RadiationGroups`](#RadiationGroups), [`planck_fractions`](#planck_fractions), [`ConstantOpacity`](#ConstantOpacity), [`PowerLawOpacity`](#PowerLawOpacity), [`UserOpacity`](#UserOpacity), [`FrequencyOpacity`](#FrequencyOpacity)
- [Reduced speed of light](reference/rsla.md): [`AbstractChatLimiter`](#AbstractChatLimiter), [`ConstantChat`](#ConstantChat), [`StabilityBound`](#StabilityBound), [`OpticalDepthFit`](#OpticalDepthFit), [`per_group`](#per_group), [`flux_form`](#flux_form)
- [Matter-radiation coupling](reference/coupling.md): [`AbstractCoupling`](#AbstractCoupling), [`QuokkaCoupling`](#QuokkaCoupling), [`BracketedCoupling`](#BracketedCoupling), [`AdaptiveCoupling`](#AdaptiveCoupling), [`AbstractDustModel`](#AbstractDustModel), [`NoDust`](#NoDust), [`BateKetoDust`](#BateKetoDust), [`AbstractJacobianSolve`](#AbstractJacobianSolve), [`DenseSolve`](#DenseSolve), [`ArrowheadSolve`](#ArrowheadSolve)
- [Photoionization chemistry](reference/chemistry.md): [`AbstractNetwork`](#AbstractNetwork), [`NetworkOptions`](#NetworkOptions), [`nspecies`](#nspecies), [`nbands`](#nbands), [`species_names`](#species_names), [`species_masses`](#species_masses), [`network_reactions`](#network_reactions), [`band_edges`](#band_edges), [`AbstractChemSolver`](#AbstractChemSolver), [`RosenbrockChem`](#RosenbrockChem), [`BackwardEulerChem`](#BackwardEulerChem), [`Photochemistry`](#Photochemistry), [`HydrogenIliev1`](#HydrogenIliev1), [`HydrogenIliev2`](#HydrogenIliev2)
- [Output, plotting and comparison](reference/output.md): [`write_vtk`](#write_vtk), [`write_line`](#write_line), [`save_checkpoint`](#save_checkpoint), [`load_checkpoint!`](#load_checkpoint-bang), [`coordinates`](#coordinates), [`available_fields`](#available_fields), [`field`](#field), [`plotstate`](#plotstate), [`plotpanels`](#plotpanels), [`animate_run`](#animate_run), [`plotcompare`](#plotcompare), [`relative_l1`](#relative_l1), [`relative_l2`](#relative_l2), [`default_metrics`](#default_metrics), [`ComparisonTable`](#ComparisonTable), [`compare`](#compare), [`write_comparison`](#write_comparison), [`read_comparison`](#read_comparison), [`convergence_rate`](#convergence_rate)
- [Test problems](reference/problems.md): [`sod_shock_tube`](#sod_shock_tube), [`radiation_streaming`](#radiation_streaming), [`radhydro_shock_exact`](#radhydro_shock_exact), [`brio_wu`](#brio_wu), [`smooth_advection`](#smooth_advection), [`stromgren_iliev`](#stromgren_iliev), [`ryu_jones_2a`](#ryu_jones_2a), [`kelvin_helmholtz`](#kelvin_helmholtz), [`radiation_diffusion`](#radiation_diffusion), [`orszag_tang`](#orszag_tang), [`interpolate_to`](#interpolate_to), [`sedov_blast`](#sedov_blast), [`alfven_wave`](#alfven_wave), [`diffusion_exact`](#diffusion_exact), [`sod_exact`](#sod_exact), [`matter_coupling`](#matter_coupling), [`rad_dust`](#rad_dust), [`ionized_radius`](#ionized_radius), [`rad_dust_reference`](#rad_dust_reference), [`stromgren_radius_analytic`](#stromgren_radius_analytic), [`stromgren_radius_finite_c`](#stromgren_radius_finite_c), [`marshak_wave`](#marshak_wave), [`radhydro_shock`](#radhydro_shock), [`radhydro_shock_super`](#radhydro_shock_super), [`radiation_shadow`](#radiation_shadow), [`marshak_vaytet`](#marshak_vaytet), [`total_erad`](#total_erad), [`radhydro_pulse_dyn`](#radhydro_pulse_dyn)
- [Utilities and constants](reference/utilities.md): [`CGS.c_light`](#CGS-c_light), [`CGS.k_B`](#CGS-k_B), [`CGS.m_u`](#CGS-m_u), [`CGS.m_H`](#CGS-m_H), [`CGS.h_planck`](#CGS-h_planck), [`CGS.sigma_SB`](#CGS-sigma_SB), [`CGS.a_rad`](#CGS-a_rad), [`CGS.G_grav`](#CGS-G_grav), [`CGS.M_sun`](#CGS-M_sun), [`CGS.parsec`](#CGS-parsec), [`CGS.au`](#CGS-au), [`CGS.year`](#CGS-year), [`CGS.eV`](#CGS-eV)


---

<!-- page: reference/simulation.md -->

# Simulation and grid

Docstrings from `src/simulation.jl`, `src/grid.jl`, `src/launch.jl`, `src/variables.jl`, `src/boundary.jl`, `src/integrators.jl`.

## Exported

### `Diagnostics` {#Diagnostics}

Source: [`src/simulation.jl:15`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L15)

```julia
Diagnostics
```

Running counters describing how hard the solver had to work, accumulated from
construction and reported by [`run!`](#run-bang). Read them off `sim.diag`, or reset
them with [`reset_diagnostics!`](#reset_diagnostics-bang).

| field | meaning |
|:---|:---|
| `steps` | steps taken |
| `rad_substeps` | IMEX radiation substeps taken |
| `floors_hydro` | cell updates that hit a gas density or pressure floor |
| `floors_rad` | cell updates projected back onto the M1 admissible set |
| `floors_scalar` | cells where a negative mass-scalar density was clipped to zero |
| `floors_presolve` | cells whose radiation energy was floored before a coupling solve, because the energy the solve conserves was not positive |
| `repairs_postsolve` | cells whose radiation state was repaired after a coupling solve |
| `newton_cells` | cells passed through the implicit coupling solve |
| `newton_iterations` | Newton iterations summed over those cells |
| `newton_max` | worst-case Newton iterations in any one cell |
| `newton_failures` | cells that hit `max_iterations` without converging |
| `chem_cells` | cells passed through the chemistry solve ([`chemistry_step!`](#chemistry_step-bang)) |
| `chem_steps` | chemistry solver steps summed over those cells (Newton iterations for [`BackwardEulerChem`](#BackwardEulerChem)) |
| `chem_max` | worst-case chemistry steps in any one cell |
| `chem_failures` | cells whose chemistry solve did not converge |

A handful of floor hits is normal wherever the solution genuinely reaches
vacuum. `newton_failures > 0` is not: it means the implicit solve gave up, and
the run should not be trusted, and neither should `chem_failures > 0`, which
says the same of the chemistry solve.

### `reset_diagnostics!` {#reset_diagnostics-bang}

Source: [`src/simulation.jl:65`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L65)

```julia
reset_diagnostics!(sim) -> Diagnostics
```

Zero the counters in `sim.diag`. Useful when timing or scoring a phase of a run
separately from the transient that preceded it.

### `SourceOrder` {#SourceOrder}

Source: [`src/simulation.jl:113`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L113)

```julia
SourceOrder
```

Which half of the Strang-split source step is running: `SourceForward` before
the advance, `SourceReverse` after it.

The order matters only when several source terms are applied in sequence and do
not commute -- reversing the sequence on the second half-step is what keeps the
pair second order. A single source term can ignore it.

Quokka's `enum class SourceOrder { forward, reverse }`.

### `Simulation` {#Simulation}

Source: [`src/simulation.jl:192`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L192)

```julia
Simulation(; n, xlo = (0,0,0), xhi = (1,1,1), kwargs...)
```

A three-dimensional (radiation-)hydrodynamics simulation.

#### Grid

  - `n`   : interior cell counts, `(nx, ny, nz)` or a single integer. A
    direction with `n[d] == 1` is degenerate and is skipped entirely, so a 1D
    problem is `n = (256, 1, 1)`.
  - `xlo`, `xhi` : domain corners.

#### Physics

  - `eos = IdealGas()`  : equation of state.
  - `radiation = nothing` : a [`RadiationPhysics`](#RadiationPhysics) to enable the
    two-moment radiation module.
  - `hydro = true` : evolve the Euler equations. Set to `false` for static
    radiation tests; this also freezes the gas momentum in the coupling.
  - `source = nothing` : callable `source(x, y, z, t)` returning a *radiation*
    energy source density (energy per volume per time), applied inside the
    implicit coupling. For anything else -- gravity, driving, cooling -- use
    `strang_sources`.
  - `strang_sources = nothing` : callable `f(sim, t, dt, order)` applied at
    `dt/2` before the advance and `dt/2` after it, mutating `sim.U` and `sim.R`
    in place. See [`SourceOrder`](#SourceOrder).
  - `floors = Floors()` : positivity floors.
  - `nscalars = 0` : number of passive mass scalars, stored as the conserved
    `rho * X_s` in rows `NHYDRO + 1 : NHYDRO + nscalars` of `sim.U` (see
    [`scalar_index`](#scalar_index)) and set from the key `X` of
    [`set_initial_conditions!`](#set_initial_conditions-bang). With the default, the state is exactly
    the five hydro variables.
  - `mhd = false` : evolve the magnetic field, with constrained transport. The
    field is `sim.B`, a [`MagneticField`](#MagneticField) of face-centred components, set
    by the keys `bx`, `by`, `bz` or the `vector_potential` of
    [`set_initial_conditions!`](#set_initial_conditions-bang), and its energy is part of the total
    energy in `sim.U`. Only [`Periodic`](#Periodic) and [`Outflow`](#Outflow) boundaries
    are supported with it; any other is an `ArgumentError`.
  - `chemistry = nothing` : a [`Photochemistry`](#Photochemistry) to evolve a chemical
    network, with its ionizing photons, inside every radiation substep. It sets
    `nscalars` to the number of species (an explicit `nscalars` must equal it)
    and needs radiation with the default [`ConstantChat`](#ConstantChat) limiter,
    `beta_order = 0` and zero thermal opacity in every group (the coupling would
    take the gas temperature from the constant-mu equation of state, which
    ignores the species), and an `eos` with
    `adiabatic_index(eos) == 5/3`, or the constructor throws an `ArgumentError`.
    One chemistry workspace is built per row of cells, `n[2] * n[3]` of them.
    The species scalars are renormalised to add up to `rho` at the start of
    every radiation advance, in every hydrodynamic right-hand side and at the end
    of every step (see [`enforce_scalar_floors!`](#enforce_scalar_floors-bang)).

#### Numerics

  - `reconstruction = PPM()` : [`PCM`](#PCM), [`PLM`](#PLM) or [`PPM`](#PPM).
  - `radiation_reconstruction = reconstruction` : reconstruction for the
    radiation moments. "PPM hydro with PLM radiation" is a standard pairing:
    the M1 system is stiffer and the extra order buys less there. The
    ghost-cell width is taken from whichever needs more.
  - `riemann = HLLC()` : interface flux solver, [`HLLC`](#HLLC) or [`LLF`](#LLF);
    with `mhd = true` an MHD solver, [`HLLD`](#HLLD) (the default), [`HLLMHD`](#HLLMHD) or [`LLFMHD`](#LLFMHD).
  - `integrator = SSPRK2()`  : explicit integrator for the hydro subsystem.
  - `boundaries = Boundaries(Outflow())`, `radiation_boundaries = boundaries`.
  - `cfl = 0.4`, `cfl_radiation = 0.3`.
  - `max_radiation_substeps = 10` : if the hydro step would need more radiation
    substeps than this, the hydro step is shortened instead.

#### Parallel performance

  - `tile = :auto` : a tuple `(b1, b2, b3)` makes the hydrodynamic sweeps run
    one box of cells at a time, with the interface states and fluxes of a box in
    a per-task scratch array that stays in cache, instead of three passes over
    whole-grid arrays. A sweep along `d` takes the whole interior along `d` and
    blocks of `b_e` cells along each other direction `e`. `nothing` gives the
    untiled sweep, which is also what a reconstruction other than `PCM`, `PLM`
    or `PPM` always gets. `:auto` is [`DEFAULT_TILE`](#DEFAULT_TILE) with
    [`TILE_MIN_THREADS`](#TILE_MIN_THREADS) threads or more, if the sweep along every active
    direction has at least one box per thread, and `nothing` otherwise; on Apple
    Silicon, where tiling was measured slower at every thread count, it is
    always `nothing`. The answer
    is the same to the bit whatever `tile` is: it changes speed only. On a
    machine with different caches another tile may be faster, and
    `test/benchmarks_parallel.jl --tile=a,b,c` measures one;
    `docs/parallel-findings.md` says how the defaults were chosen.
  - `flush_subnormals = true` : [`step!`](#step-bang) runs with subnormal numbers
    flushed to zero, on the calling thread and on every task it spawns, and
    restores the caller's mode on return. A blast or a shock spreads values
    such as `1e-200` ahead of itself, physically zero, and their products in
    the Riemann solvers underflow into the subnormal range, which x86 CPUs
    handle in microcode: a 64^3 MHD blast ran 1.4 times slower without the
    flush. The answer changes only where a result would have been subnormal.

#### Example

```julia
sim = Simulation(n = (128, 128, 1), xhi = (1.0, 1.0, 1.0),
                 eos = IdealGas(gamma = 1.4),
                 boundaries = Boundaries(Periodic()))
set_initial_conditions!(sim) do x, y, z
    (rho = 1.0, vx = 0.0, p = 1.0)
end
run!(sim, tmax = 0.5)
```

### `set_initial_conditions!` {#set_initial_conditions-bang}

Source: [`src/simulation.jl:515`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L515)

```julia
set_initial_conditions!(f, sim; vector_potential = nothing)
```

Fill the interior state from a callable `f(x, y, z)` that returns a `NamedTuple`
of primitive variables at the cell centre.

Recognised keys:

| key                | meaning                                | default |
|:-------------------|:---------------------------------------|:--------|
| `rho`              | mass density                           | required |
| `p` or `T`         | pressure, or gas temperature           | required (one of) |
| `vx`, `vy`, `vz`   | velocity                               | `0` |
| `Erad` or `Trad`   | radiation energy density, or radiation temperature | gas temperature |
| `Fx`, `Fy`, `Fz`   | radiation flux                         | `0` |
| `X`                | mass fractions of the passive scalars: a tuple or vector of `sim.nscalars` numbers | all `0`; with `chemistry`, [`initial_mass_fractions`](#initial_mass_fractions) of the network |
| `bx`, `by`, `bz`   | magnetic field (`mhd = true` only)     | `0` |

With `mhd = true` the field is face-centred ([`MagneticField`](#MagneticField)), and is set
before the cells: `f` is called at the centre of every face as well, and the face
normal to `d` takes `f`'s component `d` there. Its discrete divergence is then
exactly zero for any field whose component `b_d` does not vary along `d`, a
uniform field among them. Any other field should come from
`vector_potential = (x, y, z) -> (Ax, Ay, Az)`, whose discrete curl, from `A`
evaluated at the edge centres, is added to the faces: its divergence is zero to
round-off. The total energy of each cell then includes the magnetic energy of
the cell-centred field ([`magnetic_energy`](#magnetic_energy)), so `p` is the gas pressure. A
field key or a `vector_potential` given to a simulation without MHD is an
`ArgumentError`.

Ghost cells are filled from the boundary conditions afterwards, so `f` is only
called on interior cells.

The radiation keys are *totals*, whatever the group structure: `Erad` and the
fluxes are split over the frequency groups by the Planck spectrum at the
radiation temperature `Erad` implies, so a multigroup run starts in equilibrium
rather than with everything piled into group 1. A multigroup problem therefore
needs no group-aware initial condition of its own; a [`Fixed`](#Fixed) radiation
boundary still does, since nothing splits a boundary state.

`X` holds mass *fractions*, as the problem is posed; the state stores the
conserved density `rho * X_s`. Its length must be `sim.nscalars`, and a
different length is an `ArgumentError` rather than a scalar quietly left at
zero. Leaving `X` out sets every fraction to zero, which is also what a
`Simulation` without scalars wants.

With `chemistry`, `X` gives one mass fraction per species of the network, electrons
included, in the order of [`species_names`](#species_names); leaving it out is an error
([`initial_mass_fractions`](#initial_mass_fractions)). A `T` key then goes through the network's equation of
state, [`network_eint`](#network_eint) of the species the cell starts with, and not the
constant-`mu` one of `eos`, so the same `T` means the same energy that
[`gas_temperature`](#gas_temperature) reports back.

`Erad` defaults to `a_r T^4`, the radiation in equilibrium with the gas, which is
wrong for a photoionization problem: it puts a blackbody's energy in the band of
ionizing photons, where there should be none. A chemistry run must pass `Erad`
(usually a tiny value, or the radiation field it starts with) instead.

```julia
set_initial_conditions!(sim) do x, y, z
    x < 0.5 ? (rho = 1.0, p = 1.0) : (rho = 0.125, p = 0.1)
end
```

### `timestep` {#timestep}

Source: [`src/simulation.jl:961`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L961)

```julia
timestep(sim)
```

The step size allowed by the CFL conditions of the enabled physics.

With radiation enabled the hydro step is additionally capped so that it needs no
more than `sim.max_radiation_substeps` radiation substeps.

### `step!` {#step-bang}

Source: [`src/simulation.jl:989`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L989)

```julia
step!(sim, dt = timestep(sim))
```

Advance the simulation by one step. Returns the step size taken.

The hydrodynamic and radiation subsystems are advanced in sequence, which is
Lie (first-order) operator splitting -- see the note on splitting error in the
README. The step ends by projecting the state back onto the admissible set, so
that between steps `sim.U` and `sim.R` are always physical and every diagnostic
can read them without repairing anything.

### `nrepaired` {#nrepaired}

Source: [`src/simulation.jl:1070`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L1070)

```julia
nrepaired(sim) -> Int
```

Total cell updates that hit a positivity floor: gas, radiation and mass scalars
together.
Zero is the invariant worth asserting in a test: a scheme that needs no help
from the floors is one whose positivity you have actually verified.

### `run!` {#run-bang}

Source: [`src/simulation.jl:1112`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L1112)

```julia
run!(sim; tmax, dtout = nothing, maxsteps = typemax(Int),
     outdir = nothing, basename = "data", verbose = true, callback = nothing)
```

Integrate to `tmax`.

  - `dtout`    : if given (together with `outdir`), write a snapshot every
    `dtout` of simulation time; the step size is trimmed to land exactly on the
    output times.
  - `outdir`   : directory for VTK output; created if needed.
  - `callback` : called as `callback(sim)` after each step. Return `false` to
    stop early.

Returns `sim`.

### `conserved_totals` {#conserved_totals}

Source: [`src/simulation.jl:1222`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L1222)

```julia
conserved_totals(sim)
```

Volume integrals of the conserved quantities over the interior, returned as a
`NamedTuple` `(mass, momentum, energy_gas, energy_rad, energy_total, scalars)`.
`scalars` is a vector with the mass of each passive scalar, `sum(rho X_s) dV`,
and is empty without scalars. With MHD, `energy_gas` is the cells' total energy,
which then includes the magnetic energy. Useful as a conservation check; note that the
total energy is only conserved exactly when every boundary is periodic or
reflecting and there are no sources.

### `primitives` {#primitives}

Source: [`src/simulation.jl:1263`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L1263)

```julia
primitives(sim)
```

A fresh `(nhydrovars(sim), nx, ny, nz)` array of interior primitive variables
`(rho, vx, vy, vz, p)`, followed by one row per mass scalar. Those rows hold the
conserved density `rho X_s`, not the mass fraction `X_s`, exactly as the
reconstruction sees them. Convenience for analysis and plotting.

Does not modify `sim`. This is load-bearing, not incidental: it used to apply
the positivity floors to `sim.U` as a side effect, so a run that was plotted
every ten steps and one that was not could quietly disagree.

### `gas_temperature` {#gas_temperature}

Source: [`src/simulation.jl:1281`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L1281)

```julia
gas_temperature(sim)
```

A fresh `(nx, ny, nz)` array of gas temperatures over the interior. With
`chemistry` it is the network's temperature, [`network_temperature`](#network_temperature) of the
cell's species and internal energy, because the constant-`mu` equation of state
is wrong in partially ionized gas; otherwise it is the equation of state's.

### `radiation_temperature` {#radiation_temperature}

Source: [`src/simulation.jl:1316`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L1316)

```julia
radiation_temperature(sim)
```

A fresh `(nx, ny, nz)` array of radiation temperatures `(E_rad / a_rad)^(1/4)`.

### `CartesianGrid` {#CartesianGrid}

Source: [`src/grid.jl:8`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L8)

```julia
CartesianGrid(; n, xlo = (0,0,0), xhi = (1,1,1), nghost = 3, T = Float64)
```

Uniform Cartesian grid of `n = (nx, ny, nz)` interior cells covering
`[xlo[d], xhi[d]]` in each direction, padded with `nghost` ghost cells in every
*active* direction (a direction with `n[d] == 1` gets none).

`n` may also be given as a single integer (cubic grid).

#### Fields

  - `n`      : interior cell counts
  - `ng`     : ghost cells per direction (0 where inactive)
  - `lo`,`hi`: first/last interior index of the padded arrays
  - `dims`   : full padded array size, `n .+ 2 .* ng`
  - `dx`     : cell size per direction
  - `active` : `n[d] > 1`

#### Example

```julia
g = CartesianGrid(n = (128, 128, 1), xhi = (1.0, 1.0, 1.0), nghost = 3)
```

### `Periodic` {#Periodic}

Source: [`src/boundary.jl:26`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/boundary.jl#L26)

```julia
Periodic()
```

Wrap around to the opposite side of the domain.

### `Outflow` {#Outflow}

Source: [`src/boundary.jl:33`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/boundary.jl#L33)

```julia
Outflow()
```

Zero-gradient (transmissive) condition: copy the adjacent interior cell.

### `Reflecting` {#Reflecting}

Source: [`src/boundary.jl:40`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/boundary.jl#L40)

```julia
Reflecting()
```

Mirror the interior state and flip the sign of the normal momentum (hydro) or
the normal radiation flux of every frequency group (radiation).

### `Fixed` {#Fixed}

Source: [`src/boundary.jl:48`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/boundary.jl#L48)

```julia
Fixed(state)
```

Hold the ghost cells at a constant *conserved* state. `state` is a tuple or
`SVec` covering the whole state vector: `NHYDRO + nscalars` values on a hydro
boundary (the conserved `rho * X_s` of each mass scalar after the five gas
variables), and on a radiation boundary `NRAD * ngroups`, the groups contiguous
and four components each, so a two-group state is

    (E₁, Fx₁, Fy₁, Fz₁, E₂, Fx₂, Fy₂, Fz₂)

This is the one place a multigroup problem has to write its group structure out
by hand -- nothing splits a boundary state the way `set_initial_conditions!`
splits a scalar `Erad` -- and a state of the wrong length is a
`DimensionMismatch` at the first ghost fill, not a silent grey boundary.
`Honghu.Problems.marshak_vaytet` builds one from [`planck_fractions`](#planck_fractions) and
is the worked example.

Used e.g. to drive a Marshak wave by imposing an incident radiation energy
density and flux at the low-x face.

### `FunctionBC` {#FunctionBC}

Source: [`src/boundary.jl:76`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/boundary.jl#L76)

```julia
FunctionBC(f)
```

Hold the ghost cells at a *conserved* state computed from position and time,
`f(x, y, z, t) -> NTuple` or `SVec` of length `NHYDRO + nscalars` on a hydro
boundary and `NRAD * ngroups` on a radiation one, with the same
group-contiguous layout [`Fixed`](#Fixed) documents.

The time-dependent counterpart of [`Fixed`](#Fixed), which ignores the `t` it is
handed. Covers a driven inflow, a source that switches on, or a boundary profile
that varies across the face:

```julia
# a beam whose intensity ramps up over one light-crossing time (one group)
FunctionBC((x, y, z, t) -> (min(t, 1.0), 0.999 * min(t, 1.0), 0.0, 0.0))
```

`f` is called once per ghost cell per fill, so it should be cheap, but it is not
in the cell loop and need not be allocation-free.

### `Boundaries` {#Boundaries}

Source: [`src/boundary.jl:100`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/boundary.jl#L100)

```julia
Boundaries(x, y, z)
Boundaries(bc)
```

Boundary conditions for the three directions. Each of `x`, `y`, `z` is a
`(low, high)` tuple of [`BoundaryCondition`](#BoundaryCondition)s; the single-argument form
applies `bc` to all six faces.

```julia
Boundaries(Periodic())
Boundaries((Outflow(), Outflow()), (Periodic(), Periodic()), (Periodic(), Periodic()))
```

### `ForwardEuler` {#ForwardEuler}

Source: [`src/integrators.jl:21`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L21)

```julia
ForwardEuler()
```

First-order explicit Euler. Only first-order accurate in time, so it is useful
mainly with [`PCM`](#PCM) or for debugging.

### `SSPRK2` {#SSPRK2}

Source: [`src/integrators.jl:29`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L29)

```julia
SSPRK2()
```

Two-stage, second-order strong-stability-preserving Runge-Kutta (Heun). The
default, as in Quokka: the operator split between hydrodynamics and radiation,
and between the hydrodynamics and the source terms, is first or second order in
time, so a third-order hydro integrator buys accuracy that the step as a whole
cannot keep, at 1.5 times the cost.

### `SSPRK3` {#SSPRK3}

Source: [`src/integrators.jl:40`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L40)

```julia
SSPRK3()
```

Three-stage, third-order strong-stability-preserving Runge-Kutta of Shu & Osher
(1988). The natural partner of [`PPM`](#PPM) for pure hydrodynamics, where no
operator split limits the order in time.

## Internals

### `HydroWorkspace` {#HydroWorkspace}

Source: [`src/simulation.jl:127`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L127)

```julia
HydroWorkspace{T}
```

Scratch arrays for the hydrodynamic sweeps. Allocated once per simulation.

`backend` is the [`AbstractBackend`](#AbstractBackend) the sweeps launch their cell kernels
on, [`CPUThreads`](#CPUThreads) unless the constructor's `backend` keyword says
otherwise; it is the one field that may be changed after construction, which is
how the tests run a whole simulation's sweeps through [`KABackend`](#KABackend). Any
backend but `CPUThreads` runs the sweep as one whole-grid box, never tiled.

### `RadiationWorkspace` {#RadiationWorkspace}

Source: [`src/simulation.jl:161`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L161)

```julia
RadiationWorkspace{T}
```

Scratch arrays for the radiation sweeps and the IMEX stages.

`chat` is the odd one out: it is `(ngroups, i, j, k)` rather than
`(nradvars, i, j, k)`, and it holds the local reduced speed of light rather than
a state (see [`update_chat!`](#update_chat-bang)). It is filled with the constant
`phys.chat` when the simulation is built, so a run with the default
[`ConstantChat`](#ConstantChat) limiter reads exactly the number it always did and never
writes to it again.

### `has_radiation` {#has_radiation}

Source: [`src/simulation.jl:438`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L438)

```julia
has_radiation(sim)
```

Whether the radiation module is enabled (a compile-time property of the type).

### `has_mhd` {#has_mhd}

Source: [`src/simulation.jl:445`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L445)

```julia
has_mhd(sim)
```

Whether the simulation evolves a magnetic field (a compile-time property of the
type): `sim.B` is then a [`MagneticField`](#MagneticField), and `nothing` otherwise.

### `nhydrovars` {#nhydrovars}

Source: [`src/simulation.jl:453`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L453)

```julia
nhydrovars(sim) -> Int
```

Length of the gas state vector, `NHYDRO + sim.nscalars`: the five hydro
variables followed by one conserved density `rho * X_s` per mass scalar. It is
the first dimension of `sim.U` and of the hydro scratch arrays.

### `hydro_rhs!` {#hydro_rhs-bang}

Source: [`src/simulation.jl:685`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L685)

```julia
hydro_rhs!(dU, U, sim; update = nothing)
```

Method-of-lines right-hand side of the Euler equations: fill ghost cells,
convert to primitives (applying floors), then accumulate `-div F` from a
directional sweep per active dimension.

With `update = (a, U0, b, c)` it takes the Runge-Kutta stage as well,
`U = a U0 + b U + c dU` over the interior, in the last sweep (see
[`flux_divergence!`](#flux_divergence-bang)), and leaves `dU` incomplete: what `combine!` would
then do, without the pass over four whole arrays.

With MHD the stage also fills the ghost faces of `sim.B`, takes the EMFs after the
sweeps, and, with `update`, the same stage of the field from `sim.mw.B0`
([`constrained_transport!`](#constrained_transport-bang)).

### `rad_rhs!` {#rad_rhs-bang}

Source: [`src/simulation.jl:739`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L739)

```julia
rad_rhs!(dR, R, sim, t)
```

Method-of-lines right-hand side of the M1 transport operator (the explicit part
of the IMEX scheme). Repairs `R` in place first, so the state handed to the HLL
solver always satisfies `E > 0` and `|F| < cE`.

### `advance_hydro!` {#advance_hydro-bang}

Source: [`src/simulation.jl:769`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L769)

```julia
advance_hydro!(sim, dt)
```

One explicit SSP-RK step of the Euler equations.

### `imex_substep!` {#imex_substep-bang}

Source: [`src/simulation.jl:835`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L835)

```julia
imex_substep!(sim, dt, t)
```

One IMEX PD-ARS substep of the radiation subsystem.

Stage 1 is the identity and is skipped. Stage 2 takes a forward-Euler transport
step into scratch storage and applies the implicit coupling there; stage 3
forms the Shu-Osher combination of the two stages, adds the transport of the
stage-2 state, and applies the implicit coupling again.

The local reduced speed of light is computed once, from the state at the start
of the substep, and both stages use it. That is the scheme the stability bound
is derived for -- one `phi` per cell held fixed through the whole PD-ARS step --
and it keeps `e + sum_g E_g/phi_g` exactly conserved over the substep: each stage
conserves it for its own `phi`, so a `phi` that changed between the stages would
leave a residual `(E(2) - E^n)(1/phi_b - 1/phi_a)`. With the default
[`ConstantChat`](#ConstantChat) limiter the [`update_chat!`](#update_chat-bang) call is a no-op. The
flux absorption coefficient of the optional wave-speed correction, which only
the standard RSLA may use, is a property of the flux and is refreshed for each
stage.

### `advance_radiation!` {#advance_radiation-bang}

Source: [`src/simulation.jl:896`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L896)

```julia
advance_radiation!(sim, dt)
```

Subcycle the radiation subsystem over one hydro step, using as many IMEX
substeps as the radiation CFL condition requires.

With chemistry and hydrodynamics both on, the species scalars are clipped and
renormalised to add up to `rho` once before the first substep, and the clip is
counted in `Diagnostics.floors_scalar`. The last Runge-Kutta combine of the hydro
step is neither floored nor renormalised, so without this the chemistry would read
species whose masses add up to `rho` only to about a percent, or are negative, and
its write-back (which clamps a negative species to zero) would create mass. The
substeps leave `rho` and the scalars alone and the burn conserves the species
total, so one call covers all of them.

### `apply_strang_sources!` {#apply_strang_sources-bang}

Source: [`src/simulation.jl:1025`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L1025)

```julia
apply_strang_sources!(sim, t, dt, order) -> sim
```

Apply the user's operator-split source terms over `dt`, which is *half* the
step: [`step!`](#step-bang) calls this once before the advance with `SourceForward`
and once after with `SourceReverse`, which is what makes the pair second order.

The Julia counterpart of Quokka's `addStrangSplitSources`, called from the same
two places in the driver and with the same halved step.

The hook mutates `sim.U` and `sim.R` directly, so it has the grid, the equation
of state and the radiation parameters to hand. It is called once per half-step,
not once per cell, so it need not be allocation-free -- but a loop *inside* it
is in the hot path, and the boxing trap described in CLAUDE.md applies there.

```julia
# constant gravity along -y, as a momentum and energy kick
function gravity!(sim, t, dt, order)
    g = sim.grid
    for k in g.lo[3]:g.hi[3], j in g.lo[2]:g.hi[2], i in g.lo[1]:g.hi[1]
        rho = sim.U[Honghu.IRHO, i, j, k]
        dp = -0.1 * rho * dt
        sim.U[Honghu.IEGAS, i, j, k] +=
            dp * (sim.U[Honghu.IMY, i, j, k] + dp / 2) / rho
        sim.U[Honghu.IMY, i, j, k] += dp
    end
end
Simulation(n = (64, 64, 1), strang_sources = gravity!)
```

Nothing is implemented on top of this hook: no gravity, no cooling, no driving.
It exists so that adding one does not mean editing `step!`.

### `enforce_state!` {#enforce_state-bang}

Source: [`src/simulation.jl:1080`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/simulation.jl#L1080)

```julia
enforce_state!(sim) -> Int
```

Project both subsystems, and the mass scalars if there are any, onto their
admissible sets and accumulate the repair count. Called at the end of every step and after the initial conditions, which
is what lets the conversion kernels and every diagnostic path stay read-only.

The analogue of Quokka's `EnforceLimits`, called from the same place in the
driver.

### `ndim` {#ndim}

Source: [`src/grid.jl:69`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L69)

```julia
ndim(grid)
```

Number of active (non-degenerate) directions, 1, 2, or 3.

### `cellcenter` {#cellcenter}

Source: [`src/grid.jl:76`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L76)

```julia
cellcenter(grid, i, j, k)
```

Coordinates of the centre of the cell with *padded* indices `(i, j, k)`.

### `cellvolume` {#cellvolume}

Source: [`src/grid.jl:86`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L86)

```julia
cellvolume(grid)
```

Volume of one cell (inactive directions contribute their full box extent).

### `interior` {#interior}

Source: [`src/grid.jl:93`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L93)

```julia
interior(grid)
```

`CartesianIndices` spanning the interior (non-ghost) cells.

### `interior_box` {#interior_box}

Source: [`src/grid.jl:102`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L102)

```julia
interior_box(grid)
```

The interior cells as a box `(irange, jrange, krange)`, the form
[`launch!`](#launch-bang) takes.

### `boxsize` {#boxsize}

Source: [`src/grid.jl:110`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L110)

```julia
boxsize(grid)
```

Physical extent `(Lx, Ly, Lz)` of the domain.

### `allocate` {#allocate}

Source: [`src/grid.jl:117`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L117)

```julia
allocate(grid, nvar, T = eltype(grid))
```

Zero-initialised `(nvar, dims...)` array sized for `grid`, ghost cells included.

The variable index comes first so that the `nvar` components of a cell are
contiguous in Julia's column-major layout, which is what the Riemann solvers
want.

### `_shift` {#_shift}

Source: [`src/grid.jl:134`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L134)

Unit offset tuple for direction `D`, known at compile time.

### `cell_ranges` {#cell_ranges}

Source: [`src/grid.jl:139`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L139)

```julia
cell_ranges(grid, Val(D))
```

Index ranges of the cells whose interface states must be reconstructed for a
sweep along direction `D`: the interior extended by one cell in `D`.

### `face_ranges` {#face_ranges}

Source: [`src/grid.jl:152`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L152)

```julia
face_ranges(grid, Val(D))
```

Index ranges of the interfaces at which fluxes are needed for a sweep along
direction `D`. Face `f` is the low-side face of cell `f`, so the interior cells
`lo:hi` are bounded by faces `lo:hi+1`.

### `threaded_jk` {#threaded_jk}

Source: [`src/grid.jl:165`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L165)

```julia
threaded_jk(f, jrange, krange)
```

Call `f(j, k)` for every pair in `jrange × krange`, spreading the work over
`Threads.nthreads()` threads. Flattening the two outer loops keeps 2D runs
(where `krange` has length one) parallel.

### `reduce_max_jk` {#reduce_max_jk}

Source: [`src/grid.jl:191`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L191)

```julia
reduce_max_jk(f, jrange, krange, T)
```

Threaded `maximum` of `f(j, k)::T` over `jrange × krange`. Partial results are
written to distinct slots rather than accumulated per thread, so the result does
not depend on the scheduler.

### `threaded_chunks` {#threaded_chunks}

Source: [`src/grid.jl:210`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L210)

```julia
threaded_chunks(f, ntot; minchunk = 1)
```

Call `f(r)` once for each of up to `Threads.nthreads()` contiguous ranges `r`
that partition `1:ntot`, each range on its own task. The ranges are fixed by
`ntot` and the thread count alone, so which task does which work is not left to a
scheduler. That keeps neighbouring indices, which share cache lines and stencil
data, on one core. Fewer chunks are used when a chunk would be shorter than
`minchunk`, and with one chunk `f` runs on the calling task.

Tasks are spawned rather than handed to `Threads.@threads :static`, which throws
when it is called from inside another threaded region.

### `threaded_copyto!` {#threaded_copyto-bang}

Source: [`src/grid.jl:259`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L259)

```julia
threaded_copyto!(dst, src)
```

`copyto!(dst, src)` for two arrays of the same length, spread over the threads.
A whole-array copy streams memory, and one core cannot saturate the memory bus.

### `threaded_fill!` {#threaded_fill-bang}

Source: [`src/grid.jl:275`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/grid.jl#L275)

```julia
threaded_fill!(A, x)
```

`fill!(A, x)` spread over the threads.

### `AbstractBackend` {#AbstractBackend}

Source: [`src/launch.jl:15`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/launch.jl#L15)

```julia
AbstractBackend
```

Where [`launch!`](#launch-bang) runs a cell kernel. [`CPUThreads`](#CPUThreads) and
[`CPUSerial`](#CPUSerial) are built in; [`KABackend`](#KABackend) runs on any device
KernelAbstractions supports, a GPU included, once that package is loaded.

### `CPUThreads` {#CPUThreads}

Source: [`src/launch.jl:24`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/launch.jl#L24)

```julia
CPUThreads()
```

The default backend: the rows `(j, k)` of a box are spread over
`Threads.nthreads()` threads, and each row is one inner loop over `i`. The inner
loop is what the compiler vectorises, so a row is the CPU's unit of work while
the cell stays the kernel's.

### `CPUSerial` {#CPUSerial}

Source: [`src/launch.jl:34`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/launch.jl#L34)

```julia
CPUSerial()
```

The whole box on the calling task, `k` outermost and `i` innermost. For work
that is already one task of a parallel loop, such as one tile of the tiled hydro
sweep.

### `KABackend` {#KABackend}

Source: [`src/launch.jl:43`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/launch.jl#L43)

```julia
KABackend(backend)
```

Runs a cell kernel as a KernelAbstractions kernel on `backend`, one work-item
per cell: `KABackend(CUDABackend())` on an NVIDIA GPU, with the arrays given as
`CuArray`s, or `KABackend(KernelAbstractions.CPU())` on the CPU, which is how
the test suite checks the device path without a device. Its `launch!` lives in
the extension `HonghuKernelAbstractionsExt`, loaded with KernelAbstractions.

### `launch!` {#launch-bang}

Source: [`src/launch.jl:56`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/launch.jl#L56)

```julia
launch!(backend, box, f, args...)
```

Call `f(i, j, k, args...)` once for every cell `(i, j, k)` of
`box = (irange, jrange, krange)`, on `backend`. The calls may run in any order
and concurrently, so `f` must write only to cell `(i, j, k)`'s own entries (or
to entries no other cell of the box writes).

### `StaticRows` {#StaticRows}

Source: [`src/launch.jl:108`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/launch.jl#L108)

```julia
StaticRows{R}(data, dims, offset)
```

A four-index array `(n, i, j, k)` whose row count `R = dims[1]` is part of its
type: what [`launch!`](#launch-bang) hands a cell kernel on the CPU in place of an
`Array{T,4}` or a [`TileArray`](#TileArray), at the same memory. An `Array`'s stride
along `i` is `size(A, 1)`, a run-time number, so a vectorised loop over `i` has
to gather every element it reads from a separate address; with the stride a
constant, LLVM loads a face array (`R = 1`) contiguously and a state array
(`R = 5`) with wide loads and shuffles. The kernels index it as they index the
array, and the addresses are the same, so the answer is the same to the bit.

### `NHYDRO` {#NHYDRO}

Source: [`src/variables.jl:20`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/variables.jl#L20)

Number of hydrodynamic variables.

### `NRAD` {#NRAD}

Source: [`src/variables.jl:22`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/variables.jl#L22)

Number of M1 radiation variables *per frequency group*: energy density and three
flux components. A grey run has one group, so the state vector is `NRAD` long;
with `NG` groups it is `NRAD * NG`.

### `scalar_index` {#scalar_index}

Source: [`src/variables.jl:42`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/variables.jl#L42)

```julia
scalar_index(s) -> Int
```

Row of `sim.U` holding the conserved density `rho * X_s` of mass scalar `s`
(`s = 1, ..., sim.nscalars`): the scalars follow the `NHYDRO` hydro rows, as in
Quokka's `scalar0_index`. Use it instead of writing `NHYDRO + s` so that the
layout lives in one place.

### `cons2prim` {#cons2prim}

Source: [`src/variables.jl:52`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/variables.jl#L52)

```julia
cons2prim(eos, u::SVec{5}) -> SVec{5}
```

Convert a conserved hydro state to primitives `(rho, vx, vy, vz, p)`.

### `prim2cons` {#prim2cons}

Source: [`src/variables.jl:68`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/variables.jl#L68)

```julia
prim2cons(eos, w::SVec{5}) -> SVec{5}
```

Convert primitives `(rho, vx, vy, vz, p)` to the conserved hydro state.

### `kinetic_energy` {#kinetic_energy}

Source: [`src/variables.jl:81`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/variables.jl#L81)

```julia
kinetic_energy(u::SVec{5})
```

Kinetic energy density `|m|^2 / (2 rho)` of a conserved hydro state.

### `internal_energy` {#internal_energy}

Source: [`src/variables.jl:90`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/variables.jl#L90)

```julia
internal_energy(u::SVec{5})
```

Internal energy density `Etot - Ekin` of a conserved hydro state.

Source: [`src/eos.jl:71`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/eos.jl#L71)

```julia
internal_energy(eos, rho, p)
```

Internal energy *density* from mass density and pressure.

### `rad_cons2prim` {#rad_cons2prim}

Source: [`src/variables.jl:97`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/variables.jl#L97)

```julia
rad_cons2prim(c, r::SVec{4}) -> SVec{4}
```

Convert `(Erad, Fx, Fy, Fz)` to `(Erad, fx, fy, fz)` with reduced flux
`f = F / (c Erad)`.

### `rad_prim2cons` {#rad_prim2cons}

Source: [`src/variables.jl:109`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/variables.jl#L109)

```julia
rad_prim2cons(c, v::SVec{4}) -> SVec{4}
```

Inverse of [`rad_cons2prim`](#rad_cons2prim).

### `BoundaryCondition` {#BoundaryCondition}

Source: [`src/boundary.jl:8`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/boundary.jl#L8)

```julia
BoundaryCondition
```

Supertype for boundary conditions. Built-in conditions are [`Periodic`](#Periodic),
[`Outflow`](#Outflow), [`Reflecting`](#Reflecting), [`Fixed`](#Fixed) and [`FunctionBC`](#FunctionBC).

To add your own, define

```julia
struct MyBC <: Honghu.BoundaryCondition end
Honghu.fill_face!(A, ::MyBC, grid, dir::Int, side::Int, t) = ...
```

where `side` is `1` for the low face and `2` for the high face, and `A` is the
`(nvar, i, j, k)` state array whose ghost cells must be written.

### `fill_ghosts!` {#fill_ghosts-bang}

Source: [`src/boundary.jl:136`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/boundary.jl#L136)

```julia
fill_ghosts!(A, boundaries, grid, t = 0; momentum_blocks = size(A, 1) ÷ NRAD)
```

Fill every ghost cell of the state array `A` according to `boundaries`.
Inactive directions are skipped.

`momentum_blocks` is how many `NRAD`-long blocks of `A` have the normal momentum
or flux that [`Reflecting`](#Reflecting) flips at row `dir + 1` of the block. The
default, one block per group, is right for a radiation array and for a bare
five-variable hydro array. A hydro array that carries mass scalars after its
five rows is `NHYDRO + nscalars` long, and the default would count a scalar row
as part of a second block and flip it; the simulation passes
`momentum_blocks = 1` for `sim.U`, and so should any caller that fills the
ghosts of such an array.

Source: [`src/magnetic_field.jl:119`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/magnetic_field.jl#L119)

```julia
fill_ghosts!(B::MagneticField, boundaries, grid)
```

Fill the ghost faces of all three field components, one boundary at a time. Across
a component's own direction its faces are laid out like cells, and
[`fill_face!`](#fill_face-bang) fills them as it fills cells. Along it there is one more face
than cells:

  - [`Periodic`](#Periodic): face `hi + 1` is face `lo`, so ghost face `lo - m` is
    face `hi + 1 - m` and ghost face `hi + 1 + m` is face `lo + m`. Faces `lo` and
    `hi + 1` are both evolved, and stay equal because their updates read the same
    numbers.
  - [`Outflow`](#Outflow): the transverse components are copied from the boundary
    row, and the normal component is integrated outward from the boundary face so
    that `div b = 0` in every ghost cell, as Quokka's MHD diode condition
    (`applyMHDDiodeBC`) does for an outflowing boundary. A copied normal face would
    leave a ghost cell a divergence wherever the transverse field varies along the
    boundary, and the field of a static equilibrium out of balance there.

Only these two are defined; [`check_mhd_boundaries`](#check_mhd_boundaries) refuses the others
when the simulation is built. The ghost cells of the gas state then need
[`mhd_ghost_energy!`](#mhd_ghost_energy-bang).

### `fill_face!` {#fill_face-bang}

Source: [`src/boundary.jl:169`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/boundary.jl#L169)

```julia
fill_face!(A, bc, grid, dir, side, t)
```

Fill the `grid.ng[dir]` ghost cells on one face. `side == 1` is the low face,
`side == 2` the high face.

### `AbstractIntegrator` {#AbstractIntegrator}

Source: [`src/integrators.jl:13`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L13)

```julia
AbstractIntegrator
```

Supertype of the explicit time integrators: [`ForwardEuler`](#ForwardEuler),
[`SSPRK2`](#SSPRK2), [`SSPRK3`](#SSPRK3).

### `tableau` {#tableau}

Source: [`src/integrators.jl:49`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L49)

```julia
tableau(integrator)
```

Shu-Osher coefficients `(a, b, c)` per stage, each stage performing

    U <- a U^n + b U + c dt L(U)

### `nstages` {#nstages}

Source: [`src/integrators.jl:60`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L60)

```julia
nstages(integrator)
```

Number of right-hand-side evaluations per step.

### `combine!` {#combine-bang}

Source: [`src/integrators.jl:67`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L67)

```julia
combine!(dst, a, A, b, B, c, C, grid, nvar)
```

Interior-cell kernel `dst = a A + b B + c C`. `dst` may alias `A` or `B`.

### `IMEX_AEX_21` {#IMEX_AEX_21}

Source: [`src/integrators.jl:92`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L92)

Explicit tableau entries of the IMEX PD-ARS scheme.

### `IMEX_AIM_22` {#IMEX_AIM_22}

Source: [`src/integrators.jl:96`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L96)

Implicit tableau entries of the IMEX PD-ARS scheme.

### `IMEX_ALPHA` {#IMEX_ALPHA}

Source: [`src/integrators.jl:100`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L100)

Shu-Osher weight of stage 3, `AIM_32 / AIM_22`.

### `combine_gas!` {#combine_gas-bang}

Source: [`src/integrators.jl:103`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/integrators.jl#L103)

```julia
combine_gas!(U, alpha, Utmp, grid; bfield = nothing)
```

`U <- (1 - alpha) U + alpha Utmp` for the gas state, combining density, momentum
and *internal* energy and then rebuilding the total energy. With MHD, `bfield`
is the simulation's [`MagneticField`](#MagneticField), the same for both states because a
radiation substep does not change it, and its energy is taken out of both and
added back.

Combining the total energy directly would leave a spurious kinetic residual
`alpha (1-alpha) |Δm|² / (2 rho)` in the internal energy extracted by the next
implicit solve, which can drive the temperature negative in cells straddling a
radiation front.



---

<!-- page: reference/hydro.md -->

# Hydrodynamics

Docstrings from `src/eos.jl`, `src/hydro_system.jl`, `src/tiling.jl`, `src/limiters.jl`, `src/reconstruction.jl`, `src/riemann/`.

## Exported

### `IdealGas` {#IdealGas}

Source: [`src/eos.jl:36`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/eos.jl#L36)

```julia
IdealGas(; gamma = 5/3, cv = 1.0)
```

Ideal gas with constant adiabatic index `gamma` and constant specific heat at
constant volume `cv` (per unit mass).

`gamma` and `cv` are independent inputs so that the code stays unit-agnostic:
in code units the usual choice is `cv = 1`, while in CGS you want
`cv = `[`cv_from_mu`](#cv_from_mu)`(mu, gamma)`.

`cv` only enters through the gas temperature, i.e. only when radiation is
enabled; pure hydrodynamics is unaffected by it.

### `cv_from_mu` {#cv_from_mu}

Source: [`src/eos.jl:56`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/eos.jl#L56)

```julia
cv_from_mu(mu, gamma; k_B = CGS.k_B, m_u = CGS.m_u)
```

Specific heat at constant volume of an ideal gas of mean molecular weight `mu`,
`cv = k_B / (mu m_u (gamma - 1))`. Defaults give CGS units (erg g⁻¹ K⁻¹).

### `Floors` {#Floors}

Source: [`src/hydro_system.jl:4`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/hydro_system.jl#L4)

```julia
Floors(; rho = 1e-30, pressure = 1e-30, erad = 1e-30)
```

Lower bounds enforced on the state after every stage. Cells that fall below
`rho` are reset to `(rho, v = 0, p = pressure)`; cells whose internal energy
falls below `pressure/(gamma-1)` keep their momentum and have only the thermal
part reset.

### `MinMod` {#MinMod}

Source: [`src/limiters.jl:14`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/limiters.jl#L14)

```julia
MinMod()
```

`minmod(dL, dR)`. The most diffusive of the TVD limiters, and the most robust.

### `MonotonizedCentral` {#MonotonizedCentral}

Source: [`src/limiters.jl:21`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/limiters.jl#L21)

```julia
MonotonizedCentral()
```

The MC limiter of van Leer (1977), `minmod(2dL, (dL+dR)/2, 2dR)`. The default:
sharper than minmod while remaining TVD.

### `VanLeer` {#VanLeer}

Source: [`src/limiters.jl:29`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/limiters.jl#L29)

```julia
VanLeer()
```

The harmonic-mean limiter `2 dL dR / (dL + dR)` for `dL dR > 0`, else zero.
Smooth, which helps steady-state convergence.

### `Sweby` {#Sweby}

Source: [`src/limiters.jl:37`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/limiters.jl#L37)

```julia
Sweby(beta = 1.5)
```

Generalised minmod limiter `minmod(beta dL, (dL+dR)/2, beta dR)`. TVD for
`1 <= beta <= 2`; `beta = 1` is minmod and `beta = 2` is MC.

### `PCM` {#PCM}

Source: [`src/reconstruction.jl:21`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/reconstruction.jl#L21)

```julia
PCM()
```

Piecewise-constant (Godunov) reconstruction. First-order accurate; useful as a
robustness fallback and for verifying that higher-order schemes actually help.

### `PLM` {#PLM}

Source: [`src/reconstruction.jl:29`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/reconstruction.jl#L29)

```julia
PLM(limiter = MonotonizedCentral())
```

Piecewise-linear reconstruction with a TVD slope limiter. Second-order accurate
in smooth regions.

### `PPM` {#PPM}

Source: [`src/reconstruction.jl:40`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/reconstruction.jl#L40)

```julia
PPM()
```

Piecewise-parabolic method of Colella & Woodward (1984), with the interface
constraint and monotonicity correction used by Athena++ / Quokka (Mignone 2014):
edge values are clamped to the range of the three neighbouring cell averages,
and at a local extremum the parabola collapses to an MC-limited line.

Third-order accurate on smooth data away from extrema; this is the recommended
default.

### `HLLMHD` {#HLLMHD}

Source: [`src/riemann/hll_mhd.jl:7`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/hll_mhd.jl#L7)

```julia
HLLMHD()
```

Two-wave HLL solver for ideal MHD: one intermediate state between the two fast
waves, with HLLD's bounding speeds (Miyoshi & Kusano 2005, eq. 67),
`S_L = min(u_L, u_R) - max(c_fL, c_fR)` and `S_R = max(u_L, u_R) + max(c_fL, c_fR)`,
returned as `am = -min(0, S_L)` and `ap = max(0, S_R)`.

For benchmarking [`HLLD`](#HLLD): the two share their speeds, so constrained
transport gets the same `alpha^±` from either, and they differ only inside the fan,
where HLL smears the contact and the rotational discontinuities that HLLD resolves.
It is the flux HLLD blends toward with the weight of Minoshima & Miyoshi (2021),
and with LD04 averaging, itself the HLL flux of the transverse field along one
direction, it makes a scheme whose gas and field see the same two-wave model.
Quokka has no MHD HLL solver. Rebuilds the energy of each side from the pressure,
`P / (gamma - 1)`, as HLLD does, and uses neither the carbuncle input nor `sL.E`.

### `LLF` {#LLF}

Source: [`src/riemann/llf.jl:7`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/llf.jl#L7)

```julia
LLF()
```

Local Lax-Friedrichs, also called Rusanov: a single wave at the fastest signal
speed `max(|u| + c_s)`, with the whole Riemann fan replaced by that one
estimate.

The most diffusive and most robust of the solvers, and the useful control in a
comparison: whatever [`HLLC`](#HLLC) buys is the difference between them. It
smears contact discontinuities badly, because it has no contact wave to resolve
them with, while shocks -- which are self-steepening -- survive comparatively
well. Uses neither `gamma` nor the carbuncle correction.

```julia
compare(Honghu.Problems.sod_shock_tube,
        (HLLC = (riemann = HLLC(),), LLF = (riemann = LLF(),)); sizes = (64, 128, 256))
```

### `LLFMHD` {#LLFMHD}

Source: [`src/riemann/llf_mhd.jl:7`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/llf_mhd.jl#L7)

```julia
LLFMHD()
```

Local Lax-Friedrichs (Rusanov) solver for ideal MHD: one wave at the fastest
signal speed `max(|u| + c_f)` over the two sides, with `c_f` the fast
magnetosonic speed along the face normal. Quokka's `LLF_MHD`.

The control in a comparison, as [`LLF`](#LLF) is for [`HLLC`](#HLLC): it smears
contacts and rotational discontinuities, which [`HLLD`](#HLLD) resolves. Quokka
uses it for its first-order fallback fluxes. The bounding speeds it returns,
`am = -min(0, uL - c_fL, uR - c_fR)` and `ap = max(0, uL + c_fL, uR + c_fR)`,
are Davis's estimates rather than HLLD's, as in Quokka. Uses neither the carbuncle
input nor `sL.E`: the energy is rebuilt from the pressure, `P/(gamma - 1)`, as
Quokka does.

### `HydroState` {#HydroState}

Source: [`src/riemann/state.jl:10`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/state.jl#L10)

```julia
HydroState(rho, u, v, w, P, cs, E, by = 0, bz = 0)
```

One side of an interface, in *canonical* form: `u` is the velocity normal to the
interface and `v`, `w` the two transverse components, and likewise `by`, `bz`
for the magnetic field. The caller permutes the components; the solvers never
think about direction.

Field names match `quokka::HydroState`, the transverse field included: one state
type serves both the hydrodynamic and the MHD solvers, as in Quokka, so a solver
transliterates field for field. The hydrodynamic solvers ignore `by` and `bz`, and
the seven-argument constructor sets them to zero. It is an immutable struct of
concrete floats, so it lives on the stack and costs exactly what passing the
numbers separately costs -- `test_performance.jl` holds that claim to account.
The normal field is not a field of the state: it is single-valued at the face and
is passed to [`mhd_flux`](#mhd_flux) on its own, as Quokka passes `bx`.

| field | meaning |
|:---|:---|
| `rho` | mass density |
| `u` | normal velocity |
| `v`, `w` | transverse velocities |
| `P` | pressure |
| `cs` | adiabatic sound speed |
| `E` | total energy density, the magnetic energy included |
| `by`, `bz` | transverse magnetic field |

### `HLLD` {#HLLD}

Source: [`src/riemann/hlld.jl:12`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/hlld.jl#L12)

```julia
HLLD()
```

Five-wave HLLD solver of Miyoshi & Kusano (2005): the two fast waves, the two
rotational (Alfven) waves and the contact, with the low-Mach pressure and the
carbuncle blending of Minoshima & Miyoshi (2021). Quokka's `HLLD`, and the
default solver of a simulation with `mhd = true`.

  - The bounding speeds are MK5's eq. 67, `S_L = min(u_L, u_R) - max(c_fL, c_fR)`
    and `S_R = max(u_L, u_R) + max(c_fL, c_fR)`, returned as
    `am = -min(0, S_L)` and `ap = max(0, S_R)`.
  - The total pressure of the star states carries MM21's eq. 15 correction, a
    factor `phi = chi (2 - chi)` on the velocity-jump term with
    `chi = min(1, c_u / c_f)`, so that pressure perturbations scale as `M^2` at
    low Mach number.
  - Inside the fan the flux is blended toward HLL by MM21's eq. 10 sensor,
    `theta = min(1, (c_f - min(du, 0)) / (c_f - min(dw, 0)))^4`, with `du` the jump
    of the reconstructed normal velocity and `dw` the transverse velocity jump
    the sweep passes in, so that a shock aligned with the grid does not grow a
    carbuncle.

Like Quokka's, it rebuilds the energy of each side from the pressure,
`P / (gamma - 1)`, and does not read `sL.E`.

### `HLLC` {#HLLC}

Source: [`src/riemann/hllc.jl:14`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/hllc.jl#L14)

```julia
HLLC()
```

Three-wave HLLC solver: left- and right-going acoustic waves plus the contact
discontinuity. Resolving the contact is what keeps a material interface sharp,
which is why this is the default.

Structurally a gamma-law solver -- `gamma` enters the Roe-averaged sound speed
and Rider's correction as a scalar -- so it is not appropriate for a genuinely
non-ideal equation of state. See [`AbstractEOS`](#AbstractEOS).

### `AbstractRiemannSolver` {#AbstractRiemannSolver}

Source: [`src/riemann/state.jl:57`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/state.jl#L57)

```julia
AbstractRiemannSolver
```

Supertype for the interface flux solvers: [`HLLC`](#HLLC) and [`LLF`](#LLF).
Pass one to [`Simulation`](#Simulation) as `riemann = HLLC()`.

A concrete subtype implements

    riemann_flux(solver, sL::HydroState, sR::HydroState, gamma, du, dw) -> SVec{5}

returning the conservative flux `(mass, normal momentum, transverse momentum 1,
transverse momentum 2, energy)` in canonical form.

Every solver takes the same arguments and ignores what it does not need --
`LLF` uses neither `gamma` nor the carbuncle inputs. That is a small departure
from Quokka, whose per-solver argument lists differ, and it is deliberate: the
sweep computes `du` and `dw` unconditionally in both codes, so a uniform
signature costs nothing and keeps one call site instead of one per solver.

`test/test_extensions.jl` pins this contract with a toy solver.

### `AbstractMHDRiemannSolver` {#AbstractMHDRiemannSolver}

Source: [`src/riemann/state.jl:80`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/state.jl#L80)

```julia
AbstractMHDRiemannSolver <: AbstractRiemannSolver
```

Supertype of the MHD interface solvers, [`LLFMHD`](#LLFMHD) and [`HLLD`](#HLLD),
which a simulation with `mhd = true` takes as `riemann`. A concrete subtype
implements

    mhd_flux(solver, sL::HydroState, sR::HydroState, gamma, bx, dw) -> (SVec{5}, am, ap)

the counterpart of Quokka's `HLLD(sL, sR, gamma, bx, perp_v_jump)`. It returns the
flux of `(mass, normal momentum, transverse momentum 1, transverse momentum 2,
energy)` in canonical form, and the two non-negative bounding speeds of the
Riemann fan, `am` to the left and `ap` to the right, which constrained transport
needs at every face: for the face velocity and the averaging of the EMFs. `bx`
is the normal field at the face and `dw` the carbuncle input of
[`riemann_flux`](#riemann_flux). The flux of the transverse field is not returned: the
field is advanced by the EMFs, never by a flux.

### `riemann_flux` {#riemann_flux}

Source: [`src/riemann/state.jl:108`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/state.jl#L108)

```julia
riemann_flux(solver, sL, sR, gamma, du, dw) -> SVec{5}
```

The conservative flux across one interface in canonical form.

`du` is the jump in normal velocity across the interface and `dw` the smallest
transverse velocity difference in the two adjoining cells. Both feed the
carbuncle correction and may be passed as zero to disable it; solvers without
one ignore them.

## Internals

### `AbstractEOS` {#AbstractEOS}

Source: [`src/eos.jl:6`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/eos.jl#L6)

```julia
AbstractEOS
```

Supertype for equations of state.

A concrete subtype `E` must implement

  - [`pressure`](#pressure)`(eos, rho, eint)`
  - [`internal_energy`](#internal_energy)`(eos, rho, p)`
  - [`soundspeed`](#soundspeed)`(eos, rho, p)`
  - [`adiabatic_index`](#adiabatic_index)`(eos)`
  - [`temperature`](#temperature)`(eos, rho, eint)`
  - [`eint_from_temperature`](#eint_from_temperature)`(eos, rho, T)`
  - [`heat_capacity`](#heat_capacity)`(eos, rho, T)`

Only the first four are needed for pure hydrodynamics; the rest are used by the
radiation-matter coupling. `test/test_extensions.jl` pins this list: it defines
an EOS implementing exactly these methods and runs a simulation with it.

::: {.callout-warning title="The built-in HLLC solver assumes a gamma-law gas"}
[`HLLC`](#HLLC) uses `adiabatic_index(eos)` as a scalar in the Roe-averaged
sound speed and in Rider's wave-speed correction, so it is *structurally* a
gamma-law solver. Defining `adiabatic_index` on a genuinely non-ideal EOS
silences the `MethodError` and then silently uses an effective constant
gamma, which is worse than failing. Such an EOS needs its own
[`AbstractRiemannSolver`](#AbstractRiemannSolver); [`LLF`](#LLF) is a good starting point,
since it needs only the sound speed.
:::

### `pressure` {#pressure}

Source: [`src/eos.jl:64`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/eos.jl#L64)

```julia
pressure(eos, rho, eint)
```

Thermal pressure from mass density `rho` and internal energy *density* `eint`.

### `soundspeed` {#soundspeed}

Source: [`src/eos.jl:78`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/eos.jl#L78)

```julia
soundspeed(eos, rho, p)
```

Adiabatic sound speed.

### `temperature` {#temperature}

Source: [`src/eos.jl:85`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/eos.jl#L85)

```julia
temperature(eos, rho, eint)
```

Gas temperature from mass density and internal energy density.

### `eint_from_temperature` {#eint_from_temperature}

Source: [`src/eos.jl:92`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/eos.jl#L92)

```julia
eint_from_temperature(eos, rho, T)
```

Internal energy density from mass density and temperature.

### `heat_capacity` {#heat_capacity}

Source: [`src/eos.jl:99`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/eos.jl#L99)

```julia
heat_capacity(eos, rho, T)
```

Volumetric heat capacity `∂(eint)/∂T` at fixed density.

### `adiabatic_index` {#adiabatic_index}

Source: [`src/eos.jl:106`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/eos.jl#L106)

```julia
adiabatic_index(eos)
```

Adiabatic index `gamma`.

### `enforce_floors!` {#enforce_floors-bang}

Source: [`src/hydro_system.jl:22`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/hydro_system.jl#L22)

```julia
enforce_floors!(U, eos, grid, floors, nscalars = 0; bfield = nothing) -> Int
```

Project the conserved gas state onto the admissible set, over the whole array,
ghost cells included. Cells below `floors.rho` are reset to a quiescent floor
state; cells whose internal energy is below `floors.pressure/(gamma-1)` keep
their momentum and have only the thermal part reset.

With MHD, `bfield` is the simulation's [`MagneticField`](#MagneticField): the total energy
then holds the magnetic energy as well, which a floor keeps, and only the internal
energy is reset, to a value that [`cons2prim!`](#cons2prim-bang) is guaranteed to read as
above the floor. Where the magnetic energy is large the internal energy is then
known only to its round-off, which is what a dual-energy formalism would cure.

Returns the number of cells repaired, which the driver accumulates so that a
silently unphysical run is visible. Only the hydro repairs are counted: a
density reset also rescales the `nscalars` mass-scalar rows, but that is not a
repair of its own.

The density reset keeps each mass fraction `X_s = rho X_s / rho` of the cell and
writes `floors.rho * X_s`, so a scalar is not erased by the floor. Quokka scales
`rho X_s` by `rho / rho_new` and renormalises; this departs from it on purpose,
because a floored cell is a state the scheme has already lost and the one thing
worth keeping is what was in it. A cell whose density was not positive and
finite has no mass fraction to keep and gets `X_s = 0`.

This is deliberately a *separate* operation from [`cons2prim!`](#cons2prim-bang), matching
Quokka's split between `EnforceLimits` and its `const`-qualified
`ComputePrimVars`. The two used to be fused, which meant that reading a
diagnostic field silently mutated the state being diagnosed: results depended on
how often you looked, and the repairs went uncounted. Keep them apart.

### `enforce_scalar_floors!` {#enforce_scalar_floors-bang}

Source: [`src/hydro_system.jl:113`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/hydro_system.jl#L113)

```julia
enforce_scalar_floors!(U, grid, nscalars, renormalise = false) -> Int
```

Set every negative or NaN mass-scalar density `rho X_s` to zero, over the whole
array, ghost cells included, and return the number of cells changed. A scalar is
a mass fraction and cannot be negative; a small negative value is what
reconstruction leaves behind at a sharp front. The count goes to
`Diagnostics.floors_scalar`, kept apart from the gas floors because a scalar
clip says nothing about the gas.

With `renormalise = false`, the default, there is nothing more: the scalars are
passive and independent, and `sum_s X_s` is not forced to one.

With `renormalise = true` the scalars of a cell are then multiplied by
`rho / sum_s rho X_s`, wherever that sum and `rho` are positive, so that the mass
fractions add up to one. A simulation with a chemistry network passes `true`,
because its scalars are the species of one gas and must add up to `rho`. Each
`rho X_s` is reconstructed and limited on its own, so the species fluxes do not
add up to the mass flux, and the sum drifts from `rho` by a few percent in ten
steps of a run with PLM or PPM (3.7% for PPM on a density wave; PCM keeps it). This
is Quokka's cure, the renormalisation in the mass-scalar part of `EnforceLimits`
(`hydro_system.hpp`, after the density floor). The conservative alternative, a
consistent multi-fluid advection (CMA, Plewa & Mueller 1999), makes the species
fluxes add up to the mass flux by construction; it is not implemented. The
renormalisation is not a repair and is not counted.

Separate from [`enforce_floors!`](#enforce_floors-bang) so that a run without scalars never
reaches it.

### `cons2prim!` {#cons2prim-bang}

Source: [`src/hydro_system.jl:178`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/hydro_system.jl#L178)

```julia
cons2prim!(prim, U, eos, grid, nscalars = 0; bfield = nothing)
```

Fill `prim = (rho, vx, vy, vz, p)` from the conserved state `U` over the whole
array, ghost cells included. With MHD, `bfield` is the simulation's
[`MagneticField`](#MagneticField), and the pressure is that of `E - E_kin - E_mag`. The `nscalars` mass-scalar rows are copied
unchanged, so they hold `rho X_s` and not `X_s`: that is what is reconstructed,
as in Quokka.

`U` is **only read**. Every caller — the right-hand side, `timestep`, and every
diagnostic and plotting path — gets the same guarantee, so looking at a
simulation cannot change it. Admissibility is the caller's job, via
[`enforce_floors!`](#enforce_floors-bang); on a state that has not been floored this returns
whatever the arithmetic gives, including negative pressures.

### `prim2cons!` {#prim2cons-bang}

Source: [`src/hydro_system.jl:219`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/hydro_system.jl#L219)

```julia
prim2cons!(U, prim, eos, grid)
```

Fill the conserved state from primitives over the whole array.

### `hydro_fluxes!` {#hydro_fluxes-bang}

Source: [`src/hydro_system.jl:236`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/hydro_system.jl#L236)

```julia
hydro_fluxes!(flux, qL, qR, prim, eos, solver, Val(D), grid, nscalars = 0)
```

Solve the Riemann problem at every interface normal to direction `D` with
`solver` (an [`AbstractRiemannSolver`](#AbstractRiemannSolver)) and store the resulting
conservative flux.

If the reconstruction produced an inadmissible state (non-positive density or
pressure, or a NaN) the interface falls back to the piecewise-constant state of
the adjoining cell, which is guaranteed admissible because the floors have
already been applied.

The `nscalars` mass scalars are carried by the Riemann mass flux `F_rho`: the
flux of `rho X_s` is `F_rho` times the mass fraction of the upwind side, taken
from the reconstructed `rho X_s / rho` on that side (or from the cell-centred
state if that side fell back). So a uniform `X_s` is advected exactly, to
round-off, whatever the solver does, because the flux of `rho X_s` and `F_rho`
move together. The face fraction is a ratio of two separately limited
reconstructions, so `X_s` can overshoot where `rho` and `X_s` jump together;
[`enforce_scalar_floors!`](#enforce_scalar_floors-bang) repairs a negative result.

The solvers themselves do not know about scalars. Quokka's HLLC and LLF instead
carry them as extra conserved components inside the solver (`HLLC.hpp:123-129`,
`LLF.hpp:26-33`). For HLLC that is the same thing as the mass flux times the
upwind `X_s`. For LLF it is a deliberate departure: it keeps the
[`riemann_flux`](#riemann_flux) contract of five components, and it is less diffusive
for the scalar than LLF's own dissipation term would be.

The carbuncle inputs `du` and `dw` are computed for every solver, not gated on
whether the chosen one consumes them. Quokka does the same
(`hydro_system.hpp:1484-1498`), and reuses the intermediates for its velocity
divergence; the reads are 18 per face in 3D and 2 in 1D, against a reconstruction
and a Riemann solve.

### `flux_divergence!` {#flux_divergence-bang}

Source: [`src/hydro_system.jl:393`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/hydro_system.jl#L393)

```julia
flux_divergence!(dU, flux, Val(D), grid, nvar, overwrite = false, update = nothing)
```

Subtract `(F_{i+1/2} - F_{i-1/2}) / dx` from `dU` over the interior cells, or,
with `overwrite = true`, store its negative there and ignore what `dU` held.

With `update = (a, U0, b, U, c)` the result is not stored in `dU` at all: it is
the last term of the Runge-Kutta stage `U = a U0 + b U + c dU`, which is formed
on the spot, with the same arithmetic as [`combine!`](#combine-bang). That saves the
stage a pass over four whole arrays, and is how Quokka forms its stages too,
from the fluxes and not from a stored right-hand side. Only the last direction
of a right-hand side may do it, and only because the sweeps read `prim`, never
`U`.

The right-hand sides pass `overwrite = true` for the first active direction, in
place of zeroing `dU` first: one fewer pass over a whole array per right-hand
side. The result is the same to the bit, except that `0 - x` and `-x` differ in
the sign of an exact zero, which no comparison sees.

### `hydro_timestep` {#hydro_timestep}

Source: [`src/hydro_system.jl:456`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/hydro_system.jl#L456)

```julia
hydro_timestep(prim, eos, grid, cfl; bfield = nothing)
```

Largest stable step of the unsplit method-of-lines scheme,

    dt = cfl / max_cells Σ_d (|v_d| + c_s) / dx_d

summed over the active directions. Reduces to `cfl dx / (|v| + c_s)` in 1D.
With MHD (`bfield` a [`MagneticField`](#MagneticField)) the sound speed is replaced by the
fast magnetosonic speed for propagation along each direction `d`, Quokka's
`FastMagnetoSonicSpeed` of the cell-centred field.

### `DEFAULT_TILE` {#DEFAULT_TILE}

Source: [`src/tiling.jl:23`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/tiling.jl#L23)

```julia
DEFAULT_TILE
```

The transverse block sizes `(b1, b2, b3)` of the tiled hydrodynamic sweep. A
sweep along `D` ignores `b_D` and takes the whole interior along `D`, so with
`(32, 1, 1)` the `x` sweep runs one row of cells at a time and the `y` and `z`
sweeps one 32-cell-wide strip of a plane. The scratch of a box, interface states
and fluxes, is `3 nvar (n_D + 3) b_d1 b_d2` numbers: 0.5 MB at 128^3 and 1 MB at
256^3, about a core's L2. Chosen by measurement on a 32-core node; see
`docs/parallel-findings.md`.

### `TILE_MIN_THREADS` {#TILE_MIN_THREADS}

Source: [`src/tiling.jl:36`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/tiling.jl#L36)

```julia
TILE_MIN_THREADS
```

Below this many threads, `Simulation(tile = :auto)` (the default) does not tile,
nor on a grid where a sweep would have fewer boxes than threads (a 2D run below
about 1024^2 at 32 threads).
Tiling pays by relieving the memory bus that many cores share, and costs 4-7% on
one core, so on this node it loses at 2 and 4 threads and wins from 8 on (5% at
8, 8% at 16, 30% at 32). The answer is the same either way. On Apple Silicon
`:auto` never tiles: on an M5 Max tiling was slower at every thread count, all
18 cores included.

### `TileArray` {#TileArray}

Source: [`src/tiling.jl:78`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/tiling.jl#L78)

```julia
TileArray(buf, dims, offset)
```

A box-local array indexed with *global* cell indices: `A[n, i, j, k]` is element
`(n, i - offset[1], j - offset[2], k - offset[3])` of the column-major array of
size `dims` stored at the start of `buf`. It is the counterpart of AMReX's
`Array4`, and lets the cell kernels write the interface states
and fluxes of one tile without a change. One buffer serves the sweeps in every
direction, each with its own `dims`.

Deliberately not an `AbstractArray`, like [`SVec`](#SVec), because its axes
would not be `1:size`. Only scalar `getindex` and `setindex!` are defined, so
nothing else can be done with it by accident.

### `has_tiled_method` {#has_tiled_method}

Source: [`src/tiling.jl:114`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/tiling.jl#L114)

```julia
has_tiled_method(reconstruction) -> Bool
```

Whether the tiled sweep can run `reconstruction`. True for `PCM`, `PLM` and
`PPM`, which have cell kernels. A reconstruction defined outside the package
owns its whole sweep through `reconstruct!`, so it runs untiled.

### `tile_boxes` {#tile_boxes}

Source: [`src/tiling.jl:124`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/tiling.jl#L124)

```julia
tile_boxes(grid, D, tile) -> Vector{NTuple{3,UnitRange{Int}}}
```

The boxes of interior cells that the tiled sweep along `D` visits: the whole
interior along `D`, blocks of `tile[d]` cells along each other direction (the
last block may be shorter), together exactly the interior. They are ordered with
the first index fastest, so consecutive boxes, which run on the same task, are
neighbours in memory.

### `HydroTiles` {#HydroTiles}

Source: [`src/tiling.jl:147`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/tiling.jl#L147)

```julia
HydroTiles{T}
```

What the tiled sweep needs, built once with the simulation: the boxes and the
scratch shape of each direction, and one `(qL, qR, flux)` set of buffers per
task. A task's scratch is indexed by its chunk number, never by `threadid()`, so
no two tasks share one.

### `hydro_sweep!` {#hydro_sweep-bang}

Source: [`src/tiling.jl:171`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/tiling.jl#L171)

```julia
hydro_sweep!(dU, prim, scratch, reconstruction, eos, solver, Val(D), grid, nvar,
             nscalars, overwrite, update, backend, tiles)
```

The hydrodynamic sweep along `D`: reconstruct the interface states, solve the
Riemann problems and take the flux divergence into `dU` (overwriting it if
`overwrite`, or forming the Runge-Kutta stage `update`, as
[`flux_divergence!`](#flux_divergence-bang) does). It is the same three launches whatever runs
them, box by box ([`_sweep_box!`](#_sweep_box-bang)):

  - **tiled**, when `tiles` is a [`HydroTiles`](#HydroTiles), the reconstruction has
    cell kernels and the backend is [`CPUThreads`](#CPUThreads): each task takes a run
    of [`tile_boxes`](#tile_boxes) and launches them serially into its own
    cache-sized scratch, a [`TileArray`](#TileArray);
  - otherwise as **one box**, the whole interior, with `scratch = (qL, qR, flux)`
    three whole-grid arrays and the launches spread over `backend`. This is
    how a GPU runs it, a CPU below `TILE_MIN_THREADS` threads, and Apple
    Silicon.

A reconstruction defined outside the package has no cell kernel, so it runs as
one box with its own `reconstruct!`.

### `_sweep_box!` {#_sweep_box-bang}

Source: [`src/tiling.jl:265`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/tiling.jl#L265)

```julia
_sweep_box!(backend, box, qL, qR, flux, dU, prim, reconstruction, eos, solver,
            Val(D), grid, gam, act1, act2, invdx, nvar, nscalars, Val(overwrite),
            update)
```

The sweep along `D` over the interior cells `box`, as three launches on
`backend`: reconstruction over the cells of `box` extended by one along `D` (as
[`cell_ranges`](#cell_ranges) does for the whole grid), the Riemann solves over its
faces `lo:hi+1` along `D` (as [`face_ranges`](#face_ranges)), and the divergence over
`box`. `qL`, `qR` and `flux` need only cover those cells and faces: a tile's
[`TileArray`](#TileArray), or three whole-grid arrays.

### `AbstractLimiter` {#AbstractLimiter}

Source: [`src/limiters.jl:6`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/limiters.jl#L6)

```julia
AbstractLimiter
```

Supertype for slope limiters. Implement `limit(lim, dL, dR)`, returning the
limited undivided slope across the cell.

### `limit` {#limit}

Source: [`src/limiters.jl:48`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/limiters.jl#L48)

```julia
limit(limiter, dL, dR)
```

Limited slope of a cell whose backward and forward differences are `dL`, `dR`.

### `AbstractReconstruction` {#AbstractReconstruction}

Source: [`src/reconstruction.jl:13`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/reconstruction.jl#L13)

```julia
AbstractReconstruction
```

Supertype for spatial reconstruction schemes: [`PCM`](#PCM), [`PLM`](#PLM),
[`PPM`](#PPM).

### `required_ghosts` {#required_ghosts}

Source: [`src/reconstruction.jl:53`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/reconstruction.jl#L53)

```julia
required_ghosts(method)
```

Minimum number of ghost cells needed by a reconstruction method. At least two
are always used so that the reconstruction sweep can write the interface states
of the first ghost cell without leaving the array.

### `reconstruct!` {#reconstruct-bang}

Source: [`src/reconstruction.jl:64`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/reconstruction.jl#L64)

```julia
reconstruct!(qL, qR, q, method, Val(D), grid, nvar)
```

Fill the interface states `qL`, `qR` along direction `D` from the cell-centred
primitive variables `q`. All three arrays are `(nvar, i, j, k)` and share the
grid layout; only the components `1:nvar` are touched.

### `ppm_edges` {#ppm_edges}

Source: [`src/reconstruction.jl:135`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/reconstruction.jl#L135)

```julia
ppm_edges(qmm, qm, qc, qp, qpp) -> (a_minus, a_plus)
```

PPM interface values on the low and high edge of the central cell, given the
five-point stencil of cell averages.

### `HLLD_DELTA` {#HLLD_DELTA}

Source: [`src/riemann/hlld.jl:9`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/hlld.jl#L9)

Quokka's `DELTA`: the relative size of `rho (S - u)(S - S_M) - bx^2` below which MK5's star state is degenerate.

### `mhd_flux` {#mhd_flux}

Source: [`src/riemann/state.jl:100`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann/state.jl#L100)

```julia
mhd_flux(solver, sL, sR, gamma, bx, dw) -> (F::SVec{5}, am, ap)
```

The conservative flux across one interface in canonical form, for an
[`AbstractMHDRiemannSolver`](#AbstractMHDRiemannSolver), and the bounding speeds of the fan.



---

<!-- page: reference/mhd.md -->

# Magnetohydrodynamics

Docstrings from `src/magnetic_field.jl`, `src/mhd_system.jl`.

## Exported

### `MagneticField` {#MagneticField}

Source: [`src/magnetic_field.jl:19`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/magnetic_field.jl#L19)

```julia
MagneticField{T}
```

The face-centred magnetic field `b` of a simulation with `mhd = true`, as
`sim.B`: `sim.B[d]` is the `(1, i, j, k)` array of the component normal to the
faces along direction `d`, with one more face than cells along `d` when `d` is
active, and `sim.B[d][1, i, j, k]` is the field on the *low* face of cell
`(i, j, k)` (the convention of Quokka and of [`reconstruct!`](#reconstruct-bang)). Ghost faces
are filled by the boundary conditions, like ghost cells.

The field is in units in which the magnetic pressure is `|b|^2 / 2`, as in Quokka
(Heaviside-Lorentz, `b = B / sqrt(4 pi)` in Gaussian units). The cell-centred
total energy `sim.U[IEGAS]` includes the magnetic energy `|b_cc|^2 / 2`, with
`b_cc` the average of a cell's two faces along each direction
([`magnetic_energy`](#magnetic_energy)).

## Internals

### `cell_centred_field` {#cell_centred_field}

Source: [`src/magnetic_field.jl:51`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/magnetic_field.jl#L51)

```julia
cell_centred_field(B, d, i, j, k)
```

Component `d` of the cell-centred field of cell `(i, j, k)`: the average of its
low and high face along `d`. Along an inactive direction the two are the same face.

### `magnetic_energy` {#magnetic_energy}

Source: [`src/magnetic_field.jl:63`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/magnetic_field.jl#L63)

```julia
magnetic_energy(B, i, j, k)
```

The magnetic energy density `|b_cc|^2 / 2` of cell `(i, j, k)`, from the
cell-centred field ([`cell_centred_field`](#cell_centred_field)), as Quokka takes it. It is the
part of the cell's total energy that is neither kinetic nor internal, so every
place that takes the internal energy as `E - E_kin` subtracts it as well, and
every place that writes `E = E_int + E_kin` adds it back.

`B === nothing`, a simulation without MHD, gives `false`, a zero of every float
type: `x - false` is `x`, so the hydrodynamic paths keep their numbers.

### `fast_magnetosonic_speed` {#fast_magnetosonic_speed}

Source: [`src/magnetic_field.jl:84`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/magnetic_field.jl#L84)

```julia
fast_magnetosonic_speed(gamma, rho, P, bn, bt1, bt2)
```

The fast magnetosonic speed for propagation along the direction of `bn`, with
`bt1`, `bt2` the two transverse components: Quokka's `FastMagnetoSonicSpeed`
(`HydroState.hpp`), with `gamma P` for the square of the sound speed times `rho`.

### `check_mhd_boundaries` {#check_mhd_boundaries}

Source: [`src/magnetic_field.jl:103`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/magnetic_field.jl#L103)

```julia
check_mhd_boundaries(boundaries)
```

Throw an `ArgumentError` unless every face of `boundaries` is [`Periodic`](#Periodic)
or [`Outflow`](#Outflow), the two conditions the face-centred field has.

### `mhd_ghost_energy!` {#mhd_ghost_energy-bang}

Source: [`src/magnetic_field.jl:200`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/magnetic_field.jl#L200)

```julia
mhd_ghost_energy!(U, B, boundaries, grid)
```

Give every ghost cell beyond an [`Outflow`](#Outflow) boundary the internal energy of
the interior cell it was copied from, by replacing that cell's magnetic energy in
the copied total energy with the ghost cell's own: Quokka's step 3 of
`applyMHDDiodeBC`. Its ghost faces differ from the source cell's (the normal one
is integrated, see [`fill_ghosts!`](#fill_ghosts-bang)), so a plain copy of the total energy
would give the ghost cell another pressure. Call it after the ghost cells of `U`
and the ghost faces of `B` are filled. Without an outflow boundary it does nothing:
a periodic ghost cell's faces are images of its source's, and so is its energy.

### `divergence_b` {#divergence_b}

Source: [`src/magnetic_field.jl:300`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/magnetic_field.jl#L300)

```julia
divergence_b(sim) -> Array{T,3}
```

The discrete divergence `sum_d (b_d[high face] - b_d[low face]) / dx_d` of every
interior cell, the quantity constrained transport keeps at round-off. Directions
that are inactive contribute nothing.

### `mhd_riemann_ghosts` {#mhd_riemann_ghosts}

Source: [`src/mhd_system.jl:30`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/mhd_system.jl#L30)

```julia
mhd_riemann_ghosts(reconstruction) -> Int
```

How many rows of faces beyond the interior, across the sweep direction, the MHD
sweep solves Riemann problems on: the Q26 EMF reconstructs the face velocity
`u*` along each transverse direction to the edges, and a reconstruction of the
edges of the interior reads that many faces past them (paper Sec. 2.3.1: 1 for
PCM, 2 for PLM, 3 for PPM). It is Quokka's `MinimumHydroRiemannGhost`, which
takes 3 for Q26 whatever the order. The simulation's ghost width is one more,
for the carbuncle input of the outermost of those faces.

### `MHDWorkspace` {#MHDWorkspace}

Source: [`src/mhd_system.jl:45`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/mhd_system.jl#L45)

```julia
MHDWorkspace{T}
```

Scratch arrays of the MHD step, built with the simulation:

  - `bcc`: the cell-centred field, `(3, i, j, k)`, every cell, ghosts included;
  - `bL`, `bR`: its interface states along the current sweep;
  - `fspd[d]`: `(2, faces of d)`, the bounding speeds `alpha^-`, `alpha^+` the
    Riemann solver returned on each face normal to `d` (Quokka's
    `fast_mhd_wavespeeds`);
  - `ustar[d]`: `(1, faces of d)`, the Q26 face velocity of each face,
    `(alpha^+ u_L + alpha^- u_R) / (alpha^+ + alpha^-)` (Quokka's `facevel`);
  - `emf[w]`: `(1, edges along w)`, the EMF on each edge along `w`, with one more
    edge than cells along each active direction across `w`;
  - `B0[d]`: the field at the start of the step, for the Runge-Kutta stages.

The face arrays are whole-grid and kept between the sweeps, because the EMF of an
edge reads the faces of two directions. Along an inactive direction `d`,
`fspd[d]` holds ones and is never written: LD04 weights the corner EMFs by these
speeds, and when the two sides of every face along `d` are equal the corners pair
up and the speeds along `d` cancel, exactly for one.

### `constrained_transport!` {#constrained_transport-bang}

Source: [`src/mhd_system.jl:304`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/mhd_system.jl#L304)

```julia
constrained_transport!(sim, update)
```

The EMF on every edge that bounds an interior face ([`MHDWorkspace`](#MHDWorkspace)), from
the face arrays the sweeps left, and then, with `update = (a, B0, b, c dt)`, the
Runge-Kutta stage of the face-centred field, `B = a B0 + b B + c dt curl(eps)` on
every interior face. Any linear combination of divergence-free fields is
divergence-free and `curl` is a discrete curl, so every stage of every tableau
keeps `div b` where it was.

### `mhd_prepare!` {#mhd_prepare-bang}

Source: [`src/mhd_system.jl:337`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/mhd_system.jl#L337)

```julia
mhd_prepare!(sim)
```

What the MHD stage needs before its sweeps, after `cons2prim!`: the cell-centred
field of every cell, and the face velocity of every face normal to an inactive
direction, the cell's own velocity.



---

<!-- page: reference/radiation.md -->

# Radiation transport

Docstrings from `src/radiation_system.jl`, `src/riemann_radiation.jl`, `src/planck.jl`, `src/opacity.jl`.

## Exported

### `RadiationPhysics` {#RadiationPhysics}

Source: [`src/radiation_system.jl:4`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L4)

```julia
RadiationPhysics(; c, chat = c, a_rad, opacity,
                 groups = GREY, k_B = 1,
                 closure = LevermoreClosure(),
                 coupling = BracketedCoupling(),
                 dust = NoDust(),
                 beta_order = 1,
                 tolerance = 1e-9,
                 max_iterations = 100,
                 max_outer_iterations = 5)
```

Parameters of the two-moment (M1) radiation module, grey or multigroup.

  - `c`       : speed of light, in the same units as the rest of the problem.
  - `chat`    : reduced speed of light. Using `chat < c` relaxes the radiation
    CFL condition and leaves the *static* diffusion and free-streaming limits
    intact; it does change dynamic-diffusion problems, so only reduce it when
    the radiation transport is much faster than every other signal in the
    problem. With a `chat_limiter` other than the default this is the *nominal*
    reduction `phi0 c`: a floor on the local `chat` and the speed the time step
    is still set from, not the speed every cell runs at.
  - `chat_limiter` : an [`AbstractChatLimiter`](#AbstractChatLimiter) making the reduced speed of
    light local. The default, [`ConstantChat`](#ConstantChat), is the standard RSLA and a
    bit-for-bit no-op; [`StabilityBound`](#StabilityBound) is the improved RSLA, which
    raises `chat` towards `c` in cells optically thick on the grid scale, where
    the RSLA equilibrates matter and radiation at the wrong temperature and
    where the implicit coupling supplies the damping that makes the full speed
    of light stable anyway.
  - `a_rad`   : radiation constant `4σ/c`, so that the equilibrium radiation
    energy density is `a_rad T⁴`.
  - `opacity` : an [`AbstractOpacity`](#AbstractOpacity).
  - `groups`  : a [`RadiationGroups`](#RadiationGroups). The default, [`GREY`](#GREY), is the
    single group spanning every frequency, and reproduces grey radiation exactly;
    `ngroups > 1` puts the whole radiation module on the multigroup path, from
    the state-vector length down to the coupling solver.
  - `k_B`     : Boltzmann constant. It is read *only* to turn a group edge into
    `x = energy_unit * edge / (k_B T)` for the Planck fractions, so it matters
    only when the group edges are in physical units -- pass `CGS.k_B` alongside
    `energy_unit = CGS.h_planck` for edges in Hz. A grey run computes no
    fractions and never reads it, and unit-free edges given directly in units of
    `k_B T` want the default `1`; wrong in either of those cases it costs
    nothing, wrong in the physical-units case it moves energy between groups.
  - `coupling` : the implicit matter-radiation solver used when `ngroups > 1`, an
    `AbstractCoupling` -- [`BracketedCoupling`](#BracketedCoupling) (the default,
    allocation-free), [`QuokkaCoupling`](#QuokkaCoupling) or [`AdaptiveCoupling`](#AdaptiveCoupling). A
    grey run ignores it and uses [`radiation_source_step!`](#radiation_source_step-bang)'s own 2×2
    Newton driver.
  - `dust`     : an [`AbstractDustModel`](#AbstractDustModel). [`NoDust`](#NoDust), the default,
    couples the radiation to the gas. [`BateKetoDust`](#BateKetoDust) couples it to dust
    at its own temperature instead, and the dust to the gas by collisions; the
    `opacity` is then the dust's, the gas has none, and `coupling` must be
    [`BracketedCoupling`](#BracketedCoupling). A grey run with dust goes through the
    multigroup driver, which handles one group unchanged.
  - `closure`  : [`LevermoreClosure`](#LevermoreClosure) (the M1 default) or
    [`EddingtonClosure`](#EddingtonClosure), which fixes `chi = 1/3`. Use the latter only to
    reproduce reference solutions derived under the P1 approximation; it cannot
    free-stream.
  - `beta_order` : `1` keeps the `O(v/c)` terms in the matter-radiation coupling
    (radiation force, work, and the comoving-frame corrections); `0` drops them,
    which is appropriate only for a static medium.
  - `tolerance`, `max_iterations`, `max_outer_iterations` : controls of the
    implicit coupling solve (see [`radiation_source_step!`](#radiation_source_step-bang)).
  - `wavespeed_correction = false` : scale the HLL dissipation of the radiation
    *energy* at each face by `epsilon = min(1, 1/tau)`, with `tau` the harmonic
    mean of the two cells' flux-mean optical depths across the face (Skinner et
    al. 2019; optional in Quokka). In optically thick cells the HLL
    dissipation `sigma chat (E_R - E_L)/2` is a numerical diffusion far faster
    than the physical one, `c/(3 tau)`; the correction removes it. Allowed
    with the standard RSLA only: with a local `chat_limiter` the stability bound
    no longer holds. A face's correction is set by both cells beside it, so a
    thick cell bounded with its own correction can run at `phi = 1` behind an
    almost undamped face beside a thin one, and in a uniform medium the lowered
    dissipation lets modes near a quarter of the grid frequency grow wherever
    the radiation's inertia matters, which the checkerboard bound does not see
    (paper Sec. 3.2; `analysis/v2/check_wavespeed.py`).

### `ngroups` {#ngroups}

Source: [`src/radiation_system.jl:143`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L143)

```julia
ngroups(phys) -> Int
```

The number of frequency groups, a compile-time constant so every radiation
kernel specialises on it. One group is grey radiation and is the default.

Source: [`src/planck.jl:122`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/planck.jl#L122)

```julia
ngroups(groups) -> Int
```

How many frequency groups. A compile-time constant, so kernels specialise on it.

### `LevermoreClosure` {#LevermoreClosure}

Source: [`src/riemann_radiation.jl:25`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann_radiation.jl#L25)

```julia
LevermoreClosure()
```

The M1 closure of Levermore (1984),
`chi(f) = (3 + 4f²) / (5 + 2√(4 - 3f²))`. Interpolates between `1/3` in the
diffusion limit and `1` in the free-streaming limit, so radiation travels in
straight lines and casts shadows. The default.

### `EddingtonClosure` {#EddingtonClosure}

Source: [`src/riemann_radiation.jl:35`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann_radiation.jl#L35)

```julia
EddingtonClosure()
```

The Eddington (P1) approximation, `chi = 1/3` for every `f`, which makes the
radiation pressure isotropic everywhere.

This is *not* a two-moment closure in the usual sense: it cannot free-stream and
will not cast a shadow. It is here because several semi-analytic reference
solutions are derived under it -- notably the Lowrie & Edwards (2008) radiative
shock -- so reproducing them requires matching the assumption.

### `planck_integral` {#planck_integral}

Source: [`src/planck.jl:16`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/planck.jl#L16)

```julia
planck_integral(x) -> Real
```

The normalised incomplete Planck integral `P(x) = (15/pi^4) int_0^x t^3/(e^t-1) dt`,
so `P(0) = 0` and `P(Inf) = 1`. `x = h nu / (k_B T)` is frequency in units of the
thermal frequency.

This is the fraction of a blackbody's energy radiated below `nu`.

### `RadiationGroups` {#RadiationGroups}

Source: [`src/planck.jl:57`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/planck.jl#L57)

```julia
RadiationGroups{NG}(edges; energy_unit = 1)
```

`NG` frequency groups defined by `NG + 1` monotonically increasing `edges`.

`energy_unit` converts an edge to an energy, so that `x = energy_unit * edge /
(k_B T)`: pass `CGS.h_planck` to give the edges in Hz, as
`Honghu.Problems.marshak_vaytet` does, or leave it at `1` to give them as
energies in whatever units `k_B` is in -- which for the unit-free test problems,
where `k_B = 1`, means directly in units of `T`.

The outermost edges are the integration limits, so the first group collects
everything below `edges[1]` and the last everything above `edges[end]` -- the
fractions always sum to exactly one, whatever the edges are. This matches
Quokka's `radBoundaries`, including that convention.

Source: [`src/planck.jl:99`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/planck.jl#L99)

```julia
RadiationGroups(lo, hi, ngroups; energy_unit = 1, spacing = :log)
```

`ngroups` groups between `lo` and `hi`, spaced logarithmically (the usual choice,
since a Planck spectrum spans decades) or linearly.

### `planck_fractions` {#planck_fractions}

Source: [`src/planck.jl:147`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/planck.jl#L147)

```julia
planck_fractions(groups, T_rad, k_B) -> SVec{NG}
```

The fraction of a blackbody at temperature `T_rad` falling in each group, summing
to exactly one.

The last group takes `1 - sum(rest)` rather than its own integral, so the sum is
one by construction no matter where the edges sit -- the same guarantee Quokka's
`ComputePlanckEnergyFractions` makes, and the reason total emitted energy is
conserved to round-off regardless of the group structure.

### `ConstantOpacity` {#ConstantOpacity}

Source: [`src/opacity.jl:80`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L80)

```julia
ConstantOpacity(kappa)
ConstantOpacity(; planck, energy = planck, flux = planck)
```

Opacity independent of density and temperature.

### `PowerLawOpacity` {#PowerLawOpacity}

Source: [`src/opacity.jl:103`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L103)

```julia
PowerLawOpacity(; kappa0, rho0 = 1.0, T0 = 1.0, m = 0.0, n = 0.0)
```

Opacity of the form `kappa = kappa0 (rho/rho0)^m (T/T0)^n`, applied to all three
means. Kramers-like laws are `m = 1, n = -3.5`; the classic Marshak-wave test
uses `n = -3`.

### `UserOpacity` {#UserOpacity}

Source: [`src/opacity.jl:139`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L139)

```julia
UserOpacity(f)
UserOpacity(; planck, energy = planck, flux = planck,
              dplanck_dT = nothing, denergy_dT = dplanck_dT)
```

Opacity defined by user callables `f(rho, T) -> kappa`.

`dplanck_dT` and `denergy_dT` are optional callables of the same signature
giving `dkappa/dT`. Supplying them makes the coupling's Newton Jacobian exact;
leaving them out substitutes zero, which costs iterations but not the root (see
[`dkappa_dT`](#dkappa_dT)).

### `FrequencyOpacity` {#FrequencyOpacity}

Source: [`src/opacity.jl:206`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L206)

```julia
FrequencyOpacity(f; grey = nothing, dkappa_dT = nothing, dgrey_dT = nothing)
```

Opacity from a callable `f(nu, rho, T) -> kappa`, evaluated at each group centre.

```julia
# Vaytet's nu^-2 law: kappa = 2000 (nu / 4e13)^-2 cm^2/g
FrequencyOpacity((nu, rho, T) -> 2000.0 * (nu / 4.0e13)^-2)
```

A frequency-dependent law has no single grey value, so the grey entry points
throw unless `grey` gives one explicitly. That is deliberate: silently
collapsing `kappa(nu)` to some arbitrary frequency is how a multigroup opacity
ends up quietly driving a single-group run.

`dkappa_dT(nu, rho, T)` and `dgrey_dT(rho, T)` are the optional temperature
derivatives, per group and grey respectively. They default to zero, which leaves
the coupling's Jacobian inexact -- costing Newton convergence rate, not the root
it converges to (see [`dkappa_dT`](#dkappa_dT)).

## Internals

### `nradvars` {#nradvars}

Source: [`src/radiation_system.jl:151`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L151)

```julia
nradvars(phys) -> Int
```

Length of the radiation state vector, `4 * ngroups`: an energy density and three
flux components per group.

### `gbase` {#gbase}

Source: [`src/radiation_system.jl:159`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L159)

```julia
gbase(g) -> Int
```

Index offset of group `g` in the radiation state vector, so that group `g`'s
energy density is at `gbase(g) + IERAD` and its `d` momentum at `gbase(g) + d + 1`.

Groups are stored contiguously, four components at a time, which is Quokka's
`radEnergy_index + numRadVarsPerGroup * g` layout. Keeping a group's components
adjacent means one group's Riemann problem reads one cache line, and it keeps
the momentum-index convention (`d + 1` within a group) that `fill_ghosts!`
relies on to serve hydro and radiation with one implementation.

### `amend_rad` {#amend_rad}

Source: [`src/radiation_system.jl:173`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L173)

```julia
amend_rad(er, Fx, Fy, Fz, c, erad_floor)
    -> (er, Fx, Fy, Fz, fx, fy, fz, repaired)
```

Project one radiation state onto the admissible set of the M1 closure: energy
density at or above the floor, and reduced flux `|F|/(cE)` strictly below one
(the flux is rescaled, preserving its direction). Also returns the reduced flux
components, which the caller usually wants anyway.

`repaired` is true when the state was inadmissible: an energy density below the
floor or NaN, or a flux that had to be rescaled. An energy density exactly at the
floor is admissible and is not counted, where it would otherwise be a "repair" in
every call for the dark cells of a photoionization run. The returned values are
the projection either way, and a caller that writes them back for a cell at the
floor, as [`enforce_rad_floors!`](#enforce_rad_floors-bang) does, leaves the energy as it was and
passes the flux through `(F / cE) cE`.

### `enforce_rad_floors!` {#enforce_rad_floors-bang}

Source: [`src/radiation_system.jl:219`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L219)

```julia
enforce_rad_floors!(R, phys, grid, floors) -> Int
```

Project the radiation state onto the admissible set of the M1 closure over the
whole array, ghost cells included (see [`amend_rad`](#amend_rad)). Returns the number
of cells repaired.

The radiation counterpart of [`enforce_floors!`](#enforce_floors-bang), and separate from
[`rad_cons2prim!`](#rad_cons2prim-bang) for the same reason.

### `amend_rad_state!` {#amend_rad_state-bang}

Source: [`src/radiation_system.jl:235`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L235)

```julia
amend_rad_state!(R, phys, grid, floors) -> Int
```

Repair the radiation state of the *interior* cells in place. Used after each
implicit coupling solve of the IMEX scheme, so that every stage hands the next
transport step an admissible state -- not between the transport stage and the
solve, where the flux must be left alone (see [`floor_rad_energy!`](#floor_rad_energy-bang)). The
ghost cells are refilled from the boundary conditions before they are next read,
so there is no point touching them here.

### `floor_rad_energy!` {#floor_rad_energy-bang}

Source: [`src/radiation_system.jl:250`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L250)

```julia
floor_rad_energy!(R, U, chat, phys, grid, floors; bfield = nothing) -> Int
```

Hand the transport stage's radiation state to the implicit coupling solve
unchanged where the solve can absorb it, and floor the radiation energy only
where it cannot. Used after the explicit transport stages of the IMEX scheme,
before the solve; returns the number of cells floored.

Neither the flux nor the energy is limited where the solve can take the state.
In an optically thick cell run at a local CFL number far above one -- which is
what a local reduced speed of light does at `phi = 1` -- the transport stage
leaves `|F| >> cE`, and the solve, which divides the flux by
`1 + chat rho kappa_F dt >> 1`, is exactly what turns it into the diffusion flux
`-c grad E / (3 rho kappa_F)`. Clipping `|F|` to `cE` first threw that flux away:
on the thick hot spot of the paper's test it raised the IRSLA error from 0.0003%
to 0.80%, twice that of the standard RSLA. The same stage can also leave `E < 0`
where a thick cell at large `phi` borders cells at small `phi` across a steep
jump; raising `E` to the floor there adds energy every substep, and on an Ensman
shock resolved by 64 cells it made the IRSLA error 17 times that of the RSLA.

The solve conserves `e_int + sum_g E_g/phi_g` (with `phi_g = chat_g/c`) and
returns a positive temperature whenever that is positive, so a negative `E` is
left for it to absorb. Only a cell whose budget is not positive is floored, as
before; the full repair, [`amend_rad_state!`](#amend_rad_state-bang), runs after the solve.

### `rad_cons2prim!` {#rad_cons2prim-bang}

Source: [`src/radiation_system.jl:342`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L342)

```julia
rad_cons2prim!(rprim, R, phys, grid)
```

Fill the radiation primitives `(Erad, fx, fy, fz)` from the conserved state over
the whole array, ghost cells included.

`R` is **only read**; see [`cons2prim!`](#cons2prim-bang) for why. Run
[`enforce_rad_floors!`](#enforce_rad_floors-bang) first if the state may be inadmissible — on an
admissible state the reduced flux this computes automatically satisfies
`|f| < 1`.

### `rad_fluxes!` {#rad_fluxes-bang}

Source: [`src/radiation_system.jl:375`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L375)

```julia
rad_fluxes!(flux, qL, qR, R, chat, phys, Val(D), grid)
```

Solve the HLL Riemann problem of the M1 system at every interface normal to
direction `D`.

`chat` is the per-cell, per-group reduced speed of light (see
[`update_chat!`](#update_chat-bang)), or `nothing`. An array is passed under the standard RSLA
and in the flux form of a local limiter (see [`flux_form`](#flux_form)), and the
interface then uses the **minimum** of the two adjacent cells. In the flux form
that is the stable choice wherever `chat` varies: an optically thick cell may
locally run at the full speed of light, but letting it set the signal speed of a
flux into a transparent neighbour would impose a CFL-violating speed there,
where no source damping is available to control the resulting amplification.
`nothing` is passed in the default, time-derivative form of a local limiter: the
flux is then the unreduced one, at the true speed of light, and
[`scale_by_phi!`](#scale_by_phi-bang) multiplies each cell's update by its own `phi`
afterwards, so no interface value is needed.

As in the hydro sweep, an inadmissible reconstructed state (non-positive energy
density, or a reduced flux at or beyond the causal limit) falls back to the
piecewise-constant state of the adjoining cells.

### `scale_by_phi!` {#scale_by_phi-bang}

Source: [`src/radiation_system.jl:478`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L478)

```julia
scale_by_phi!(dR, chat, phys, grid)
```

Multiply each interior cell's radiation right-hand side by its own reduction
`chat_g/c`, group by group: the time-derivative form of a local reduced speed of
light (see [`flux_form`](#flux_form)).

### `radiation_timestep` {#radiation_timestep}

Source: [`src/radiation_system.jl:503`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L503)

```julia
radiation_timestep(phys, grid, cfl)
```

Radiation CFL condition, `dt = cfl / (chat Σ_d 1/dx_d)` over the active
directions. Independent of the state because the M1 signal speed is bounded by
`chat`.

### `_grid_scales` {#_grid_scales}

Source: [`src/radiation_system.jl:525`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L525)

```julia
_grid_scales(grid) -> (dx_min, sum_d 1/dx_d, (1/dx_1, 1/dx_2, 1/dx_3))
```

The grid numbers the limiter needs, over the *active* directions only: the
smallest cell width (read by the fitting form), the reciprocal-width sum the CFL
number is built from (the same one `radiation_timestep` forms), and the
per-direction reciprocal widths, zero in an inactive direction.

A free function because both callers capture the result in a threaded closure,
and a variable assigned inside a loop in the enclosing scope would be boxed --
every cell would then allocate. That is not hypothetical: written inline it cost
54 bytes a cell.

### `_signal_sum` {#_signal_sum}

Source: [`src/radiation_system.jl:551`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L551)

```julia
_signal_sum(closure, R, i, j, k, g, c, inv3) -> sum_d sigma_d / dx_d
```

The HLL signal speed of group `g` in this cell along each active direction, as a
fraction of `chat`, divided by the cell width and summed: the rate at which one
explicit stage amplifies a grid-scale checkerboard, per unit `chat dt`.

`sigma_d = max(0.1, sqrt(T_dd))` is exactly the speed `m1_flux` hands the Riemann
solver along `d`: `1/sqrt(3)` in every direction where the radiation is
isotropic, and -- where it free-streams -- one along the beam and the `0.1` floor
across it. Using the closure's own speeds rather than the P1 value is what keeps
[`StabilityBound`](#StabilityBound) honest in a free-streaming cell, which is exactly the
cell with no source damping to spare; using them *per direction* rather than
the largest of them keeps a beamed cell in two or three dimensions from being
bounded as if it beamed along every axis at once.

### `update_chiF!` {#update_chiF-bang}

Source: [`src/radiation_system.jl:590`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L590)

```julia
update_chiF!(chiF, U, eos, phys, grid, floors; bfield = nothing)
```

Fill the per-cell, per-group flux absorption coefficient `rho kappa_F` over the
whole array including ghost cells, for the wave-speed correction of
[`RadiationPhysics`](#RadiationPhysics).

### `update_chat!` {#update_chat-bang}

Source: [`src/radiation_system.jl:618`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L618)

```julia
update_chat!(chat, U, R, eos, phys, grid, floors, dt; update_momentum = true,
             bfield = nothing)
```

Fill the per-cell, per-group reduced speed of light `chat[g, i, j, k]` from the
current state, over the *whole* array including ghost cells.

Ghost cells are included because the transport step needs the limiter on both
sides of every interface, including the ones bounding the domain; the limiter is
purely local, so filling them costs one extra loop and no communication. `U` and
`R` must already have had their own ghost cells filled.

`update_momentum = false`, as for a run without hydrodynamics, means that the
coupling freezes the gas momentum: the gas then has no inertia to share with the
radiation, and the momentum block of [`StabilityBound`](#StabilityBound) loses its cap `K_F`.

A [`ConstantChat`](#ConstantChat) limiter -- the default -- dispatches to a no-op: the
array was filled with `phys.chat` when the simulation was built and cannot
change.

### `_radiation_inertia` {#_radiation_inertia}

Source: [`src/radiation_system.jl:672`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L672)

```julia
_radiation_inertia(cl, R, i, j, k, c, rho, ng) -> (1 + T_max) E / (rho c^2)
```

The ratio of the radiation to the gas inertia that caps the damping of the
momentum block in [`StabilityBound`](#StabilityBound): `E` and the flux summed over the
`ng` groups, as for the heat capacity, and `T_max` the largest diagonal element
of the Eddington tensor of that total, the most restrictive momentum channel.

### `energy_exchange_dt` {#energy_exchange_dt}

Source: [`src/radiation_system.jl:761`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/radiation_system.jl#L761)

```julia
energy_exchange_dt(U, R, eos, phys, grid, xi, floors; bfield = nothing) -> dt
```

The longest substep at which every optically thick cell may run at `phi = 1`,
`dt = xi / (c max_i [4 a_rad T^3 / (rho c_v) * sum_d sigma_d/dx_d])` minimised
over interior cells. Requested by `StabilityBound(energy_step = true)`.

**Not a stability condition.** The standard RSLA and the stability-bound limiter
are both stable without it, at any radiation-to-gas pressure ratio. What it buys
is accuracy where radiation carries a large share of the heat capacity: there
the limiter's energy channel caps `phi` near `phi0/(sigma C_r)` at the RSLA step,
because with `K = hrat c dt chi_E` the damping `chi_E/(2 + K)` saturates at
`1/(hrat c dt)` and cannot overcome the transport amplification. Below this
step it can, by a margin `1 - xi`, and cells thick enough -- `chi_E / sum_d(1/dx_d)`
beyond about `2 sigma/(1 - xi)` -- reach `phi = 1` and the exact equations.

With hydrodynamics disabled the gas still exchanges heat with the radiation, so
unlike a radiation-*force* constraint this one does not switch off when the gas
cannot move.

### `AbstractClosure` {#AbstractClosure}

Source: [`src/riemann_radiation.jl:17`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann_radiation.jl#L17)

```julia
AbstractClosure
```

Supertype for the closure that supplies the Eddington factor `chi(f)`:
[`LevermoreClosure`](#LevermoreClosure) or [`EddingtonClosure`](#EddingtonClosure).

### `eddington_factor` {#eddington_factor}

Source: [`src/riemann_radiation.jl:48`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann_radiation.jl#L48)

```julia
eddington_factor([closure = LevermoreClosure()], f)
```

Eddington factor for the reduced flux `f = |F| / (c E)`.

### `EddingtonTensor` {#EddingtonTensor}

Source: [`src/riemann_radiation.jl:63`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann_radiation.jl#L63)

```julia
EddingtonTensor(diag, aniso, n)
```

The Eddington tensor `T_ij = diag δ_ij + aniso n_i n_j` in factored form, where
`n` is the unit vector along the radiation flux. Index it as `T[i, j]`.

### `eddington_tensor` {#eddington_tensor}

Source: [`src/riemann_radiation.jl:75`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann_radiation.jl#L75)

```julia
eddington_tensor([closure = LevermoreClosure()], fx, fy, fz) -> EddingtonTensor
```

Build the Eddington tensor from the reduced flux vector.

### `m1_flux` {#m1_flux}

Source: [`src/riemann_radiation.jl:95`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann_radiation.jl#L95)

```julia
m1_flux(er, Fx, Fy, Fz, tedd, D) -> (SVec{4}, S)
```

Physical M1 flux normal to a face with normal direction `D` (before the reduced
speed-of-light rescaling), together with the normalised signal speed
`S = max(0.1, sqrt(T_DD))`.

The `0.1` floor mirrors Quokka: it keeps `S_L = S_R = 0` (and hence a `0/0`
flux) from occurring in cells where the Eddington tensor becomes degenerate.

### `hll_radiation` {#hll_radiation}

Source: [`src/riemann_radiation.jl:112`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/riemann_radiation.jl#L112)

```julia
hll_radiation(erL, FxL, FyL, FzL, erR, FxR, FyR, FzR, c, chat, Val(D),
              closure = LevermoreClosure()) -> SVec{4}
```

HLL flux of the grey M1 system across one interface with normal along direction
`D`. Components are `(energy, x-momentum, y-momentum, z-momentum)`.

### `GREY` {#GREY}

Source: [`src/planck.jl:119`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/planck.jl#L119)

The single group spanning all frequencies, which reproduces grey radiation.

### `group_centers` {#group_centers}

Source: [`src/planck.jl:129`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/planck.jl#L129)

```julia
group_centers(groups) -> SVec
```

The geometric mean of each group's edges, which is the frequency a
piecewise-constant opacity is evaluated at. Quokka's `ComputeBinCenterOpacity`
uses the same `sqrt(nu_g nu_{g+1})`.

An unbounded outer group has no geometric mean, so it falls back to its finite
edge -- the alternative is an opacity of zero or infinity in the group that
usually carries the least energy.

### `planck_fractions_dT` {#planck_fractions_dT}

Source: [`src/planck.jl:173`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/planck.jl#L173)

```julia
planck_fractions_dT(groups, T_rad, k_B) -> SVec{NG}
```

`d(fraction)/dT` for each group, by centred differences on a relative step.

The Jacobian of the coupling needs `d(a T^4 f_g)/dT = 4 a T^3 f_g + a T^4 f_g'`.
The second piece is what moves energy between groups as the gas heats, and
dropping it -- as an implementation that assumed fixed fractions would -- slows
the Newton iteration without changing where it converges.

### `AbstractOpacity` {#AbstractOpacity}

Source: [`src/opacity.jl:9`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L9)

```julia
AbstractOpacity
```

Supertype for opacity laws. A concrete subtype must implement

  - [`planck_opacity`](#planck_opacity)`(op, rho, T)`
  - [`energy_mean_opacity`](#energy_mean_opacity)`(op, rho, T)`
  - [`flux_mean_opacity`](#flux_mean_opacity)`(op, rho, T)`

each returning a *specific* opacity (cm² g⁻¹ in CGS), so that the absorption
coefficient is `rho * kappa`.

Optionally it may also implement [`dkappa_dT`](#dkappa_dT)`(op, rho, T)`, which makes
the matter-radiation coupling's Newton Jacobian exact. The default is zero,
which is exact for an opacity that does not depend on temperature and merely
slower for one that does.

### `planck_opacity` {#planck_opacity}

Source: [`src/opacity.jl:28`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L28)

```julia
planck_opacity(op, rho, T) -> kappa_P
```

The Planck-mean specific opacity of `op` at density `rho` and gas temperature
`T`. It weights thermal emission, the `rho kappa_P a_rad T^4` term of the
matter-radiation coupling. Part of the [`AbstractOpacity`](#AbstractOpacity) interface.

### `energy_mean_opacity` {#energy_mean_opacity}

Source: [`src/opacity.jl:37`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L37)

```julia
energy_mean_opacity(op, rho, T) -> kappa_E
```

The energy-mean specific opacity of `op` at density `rho` and gas temperature
`T`. It weights the absorption of the radiation energy, the `rho kappa_E E_rad`
term of the coupling. Part of the [`AbstractOpacity`](#AbstractOpacity) interface.

### `flux_mean_opacity` {#flux_mean_opacity}

Source: [`src/opacity.jl:46`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L46)

```julia
flux_mean_opacity(op, rho, T) -> kappa_F
```

The flux-mean specific opacity of `op` at density `rho` and gas temperature
`T`. It weights the damping of the radiation flux, `rho kappa_F F`, and so the
radiation force on the gas. Part of the [`AbstractOpacity`](#AbstractOpacity) interface.

### `dkappa_dT` {#dkappa_dT}

Source: [`src/opacity.jl:55`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L55)

```julia
dkappa_dT(op, rho, T) -> (dkappaP_dT, dkappaE_dT)
```

Temperature derivatives of the Planck- and energy-mean opacities.

The coupling solves `d E_g/dt = chat rho (kappa_P,g B_g(T) - kappa_E,g E_g)` by
Newton's method, so the exact Jacobian carries `dkappa_P/dT * B_g` and
`-dkappa_E/dT * E_g` alongside `kappa_P dB_g/dT`. Supplying these derivatives is
what makes it exact.

**The default is zero.** A zero derivative does not change where the iteration
converges -- the residual it is driven to zero is still the residual of the true
equations -- only how fast it gets there. So it is safe everywhere, and exact
wherever `kappa` is independent of `T`.

### `group_opacity` {#group_opacity}

Source: [`src/opacity.jl:182`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L182)

```julia
group_opacity(op, nu, rho, T) -> Real
```

The opacity of a frequency group centred on `nu`.

Defaults to the grey Planck mean, so any existing opacity law used with several
groups gives the same `kappa` in every group -- a genuine configuration, and the
one Vaytet et al. (2011) call the constant-opacity model. Override it for a law
that actually varies with frequency, or use [`FrequencyOpacity`](#FrequencyOpacity).

### `group_opacity_dT` {#group_opacity_dT}

Source: [`src/opacity.jl:194`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L194)

```julia
group_opacity_dT(op, nu, rho, T) -> Real
```

`dkappa/dT` of the group centred on `nu`: the companion of
[`group_opacity`](#group_opacity), and what the coupling's exact Jacobian needs.

Defaults to the grey Planck-mean derivative, which for the constant-opacity
model is the right answer in every group. Zero unless the law supplies one.

### `group_opacities` {#group_opacities}

Source: [`src/opacity.jl:260`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L260)

```julia
group_opacities(op, groups, rho, T) -> SVec{NG}
```

The opacity in each group, evaluated at the group centres.

With one group this is the grey Planck mean, so a single-group run goes down
exactly the path it did before multigroup existed.

### `group_opacities_dT` {#group_opacities_dT}

Source: [`src/opacity.jl:275`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/opacity.jl#L275)

```julia
group_opacities_dT(op, groups, rho, T) -> SVec{NG}
```

`dkappa/dT` in each group: [`group_opacities`](#group_opacities) differentiated with respect
to temperature, and the piece [`coupling_jacobian`](#coupling_jacobian) needs to be exact.

Zero unless the opacity law supplies a derivative, which is exact for every
temperature-independent law and an approximation for the rest.



---

<!-- page: reference/rsla.md -->

# Reduced speed of light

Docstrings from `src/rsla.jl`.

## Exported

### `AbstractChatLimiter` {#AbstractChatLimiter}

Source: [`src/rsla.jl:28`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/rsla.jl#L28)

```julia
AbstractChatLimiter
```

The rule that sets the local reduced speed of light `chat_i = phi_i * c`.

A limiter is a pure function of *local* cell quantities, collected in a
[`LocalCell`](#LocalCell), so it needs no communication and can be evaluated in ghost
cells like any other pointwise quantity. Implement one by adding a method to
[`chat_factor`](#chat_factor).

Three are provided:

  - [`ConstantChat`](#ConstantChat)     -- `phi = phi0` everywhere: the standard RSLA, and
    the default;
  - [`StabilityBound`](#StabilityBound)   -- the largest `phi` that is stable at the current
    step, in closed form and with no tunable physics parameters;
  - [`OpticalDepthFit`](#OpticalDepthFit)  -- the two-parameter fitting form, for
    experimentation.

### `ConstantChat` {#ConstantChat}

Source: [`src/rsla.jl:82`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/rsla.jl#L82)

```julia
ConstantChat()
```

The standard RSLA: `phi = phi0` in every cell, i.e. `chat` is the global constant
given to [`RadiationPhysics`](#RadiationPhysics).

The default, and a genuine no-op -- the `chat` array is filled once at
construction and never touched again, and every kernel reads the same number it
read before variable `chat` existed, bit for bit.

### `StabilityBound` {#StabilityBound}

Source: [`src/rsla.jl:94`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/rsla.jl#L94)

```julia
StabilityBound(; beta = 0.9, energy_step = false, xi = 0.5,
               flux_form = false)
```

The IRSLA in its parameter-free form: in each cell take the *largest* `phi` that
the step is still stable at.

Accuracy increases monotonically with `phi` up to the stability limit, so the
optimal local choice is the limit itself -- and for the IMEX PD-ARS update used
here, with the HLL transport flux, that limit is known exactly. A von Neumann
analysis of one substep ([He, Krumholz & Wibking 2026](https://scixplorer.org/abs/2026arXiv261121353H/abstract), Sec. 3) finds the worst mode is
always the grid-scale checkerboard, for which the transport symbol is a pure
dissipation and the coupling splits into an energy block `(T, E)` and a momentum
block `(v, F)`. Each block is a 2×2 problem with a closed-form boundary:

    phi c dt [ sum_d sigma_d/dx_d - chi_E / (2 + K) ] <= 1,
    phi c dt [ sum_d sigma_d/dx_d - chi_F / (2 + K_F) ] <= 1,

with `K = hrat * c dt * chi_E = 4 a_rad T^3 kappa_P c dt / c_v`, which is the
substep divided by the gas cooling time at the *true* speed of light, and
`K_F = rinert * c dt * chi_F` its analogue for the momentum.

  - The first term is the transport amplification: the checkerboard is amplified
    by `2 phi c dt sum_d sigma_d/dx_d - 1` in each explicit stage.
  - `chi_E/(2 + K)` is the damping the implicit coupling supplies. While the gas
    heat capacity dominates (`K << 2`) it is half the absorption per step, and the
    first line reduces to `nu (2 sigma - tau) <= 2` in one dimension. Once the gas
    exchanges its heat with the radiation within a step (`K >> 2`) the damping
    saturates at `1/(hrat c dt)`: the radiation cannot be damped faster than the
    gas can absorb what it deposits.
  - The momentum block has the same form with `K` replaced by `K_F`, set by the
    ratio of radiation to gas *inertia*. It is smaller than `K` by about
    `(a/c)^2`, but it is kept: the bound is a difference of two large terms
    when the cell is thick, and dropping even a small `K_F` can then select an
    unstable `phi` (He, Krumholz & Wibking 2026, Sec. 3.2).

Both are *exact* for this scheme, not estimates: they agree with the full
five-variable amplification matrix to the precision of a bisection, for any
Mach number, and a checkerboard run in this code flips from decaying to growing
between 0.9 and 1.1 of the bound in one, two and three dimensions.

Three things follow, and each corrects an earlier form of the limiter.

  - The optical depth enters as `chi / sum_d(1/dx_d)`, i.e. `rho kappa dx/D` for a
    cube in `D` dimensions -- not `rho kappa dx_min`, which is `D` times too
    generous and is unstable in two and three dimensions.
  - The channel that bites when radiation matters energetically is the
    *heat-capacity* one above. It depends on `(gamma - 1) P_rad/P_gas`, not on
    the radiation force, and it never makes the standard RSLA itself unstable:
    at `phi = phi0` the left sides are at most the CFL number times `sigma`. So
    no step restriction is needed for stability, only a cap on `phi`.
  - `sigma_d` is the closure's own signal speed. Under M1 it reaches one where
    the radiation free-streams, and a bound written with the P1 value
    `1/sqrt(3)` is then `sqrt(3)` too generous in exactly the cell with no
    damping to spare.

`beta <= 1` is a safety factor on the bound; `phi` is then clamped into
`[phi0, 1]`, so the limiter can never ask for *less* than the RSLA the user
requested. Where both brackets are `<= 0` there is no bound at all and `phi = 1`
exactly, so optically thick interiors run the unmodified, conservative scheme.

**The cap in radiation-rich cells.** Where `sigma hrat c dt / dx >~ 1` -- which at
the RSLA step means `4 (gamma - 1) P_rad/P_gas >~ phi0/(sigma C_r)` -- the
bound cannot reach one however thick the cell, and `phi` saturates near
`phi0/(sigma C_r)`. That is a limit of the step, not of the limiter: removing it
takes a shorter step. `energy_step = true` asks for one, capping the substep at
`xi / (hrat c sum_d sigma_d/dx_d)` so that thick cells can run at `phi = 1`
(see [`energy_exchange_dt`](#energy_exchange_dt)), but never below the CFL step of the unreduced
scheme, at which `phi = 1` is stable everywhere anyway. It is off by default
because it costs steps, by a factor of about
`4 (gamma - 1) P_rad/P_gas * sigma C_r / (xi phi0)` wherever it binds, and at
most `1/phi0`.

Each frequency group always gets its own `phi`; see [`per_group`](#per_group) for why
one `phi` per cell has nothing to recommend it.

### `OpticalDepthFit` {#OpticalDepthFit}

Source: [`src/rsla.jl:182`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/rsla.jl#L182)

```julia
OpticalDepthFit(; s, p, per_group = false)
```

The IRSLA in its original fitting form,

    phi = (phi0 + (s tau_cell)^p) / (1 + (s tau_cell)^p),   tau_cell = chi_E dx_min,

which rises from `phi0` in transparent cells to one in cells of optical depth
`>> 1/s`, with `p` setting how sharply.

**This form carries no stability bound.** Values of `(s, p)` that raise `phi`
well above what [`StabilityBound`](#StabilityBound) permits do not necessarily crash -- they
can run to completion and be badly wrong, which is the failure mode
`StabilityBound` exists to exclude. Provided for experimentation and for
reproducing published results; prefer `StabilityBound` for anything else.

### `per_group` {#per_group}

Source: [`src/rsla.jl:208`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/rsla.jl#L208)

```julia
per_group(limiter) -> Bool
```

Whether each frequency group is allowed its own `phi`, or the cell takes one
value for all of them, from its most restrictive group.

[`StabilityBound`](#StabilityBound) always uses one `phi` per group; only the fitting form
[`OpticalDepthFit`](#OpticalDepthFit) keeps the switch, to reproduce earlier results. The groups are
independent in transport; in the coupling they are not, and summing the source
terms gives

    d/dt [e + sum_g E_g] = c rho sum_g (phi_g - 1) (kappa_P B_g - kappa_E E_g),

so with `phi` uniform over groups *and cells* the RSLA obeys the identity
`Delta [e + sum_g E_g] = (1 - phi) Delta e`, and with a per-group `phi` it does
not (measured in one cell, no transport, 400 coupling steps: a drift of -44.5
per cent of the cell's energy at `phi = (1, 0.1)` where the identity predicts
none). That identity, however, is a property of a *global* reduction and is lost
by any local limiter, per-cell or per-group. What a local `phi` keeps, in the
time-derivative form of [`flux_form`](#flux_form), is exact conservation of
`e + sum_g E_g/phi_g`: the coupling conserves it cell by cell, and the flux
differences telescope in `E_g/phi_g`. That holds with a per-group `phi` exactly
as with a per-cell one. The von Neumann analysis finds both stable for the
coupled multigroup system, and a per-group `phi` is the more accurate of the
two, since a transparent group no longer holds the thick ones back (on the Vaytet
Marshak wave, 21.2, 7.8 and 2.7 per cent against 26.0, 11.5 and 4.3 per cent at
`phi0 = 0.003, 0.01, 0.03`), at the same cost. One `phi` per cell therefore has
no advantage, and the stability bound does not offer it.

### `flux_form` {#flux_form}

Source: [`src/rsla.jl:241`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/rsla.jl#L241)

```julia
flux_form(limiter) -> Bool
```

Where a local `phi` enters the transport step. `false`, the default, puts it
where the RSLA puts `chat`: on the time derivative,

    (1/phi_i) dU_i/dt = -(G_{i+1/2} - G_{i-1/2})/dx + S_i,

so each cell's update is `phi_i` times the flux difference of the *unreduced*
HLL flux (wave speeds `+/- sigma c`). `true` puts it inside the divergence,
`dU_i/dt = -(phi G)_{i+1/2} + (phi G)_{i-1/2} + ...`, with the interface value
the minimum of the two cells -- the form of the earlier drafts, kept for
comparison.

The two agree wherever `phi` is uniform, and for [`ConstantChat`](#ConstantChat) they are
the same scheme: `F_HLL(chat) = (chat/c) F_HLL(c)` exactly, term by term. They
differ where `phi` varies, and there only the default is right. The RSLA
changes how fast the radiation relaxes, not where it relaxes to: its steady
states are those of the unmodified equations. With `phi` on the time derivative
that stays true cell by cell, for any `phi(x)`. With `phi` inside the divergence
the steady state instead solves `div F + F . grad(ln phi) = S`, and the spurious
term costs real accuracy: on the Mach 5 supercritical shock a 5 per cent ripple
in an otherwise uniform `phi` takes the error from 0.19 to 2.3 per cent, worse
than the RSLA it replaces. The default also keeps a stateable conservation law:
the flux differences telescope in `E_g/phi_g`, which is exactly the radiation
energy the coupling conserves together with the gas (`e + sum_g E_g/phi_g`).

The minimum at interfaces is not needed by the default form: each cell's update
is scaled by its own `phi`, so the stability of a transparent cell is set by its
own speed whatever its neighbours run at.

## Internals

### `LocalCell` {#LocalCell}

Source: [`src/rsla.jl:49`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/rsla.jl#L49)

```julia
LocalCell(cdt, sdx, chiE, chiF, hrat, dxmin, rinert = 0)
```

What a limiter may read about one cell and one group, all local:

  - `cdt`   : `c dt`, the true speed of light times the substep actually taken;
  - `sdx`   : `sum_d sigma_d / dx_d` over the active directions, where
    `sigma_d = max(0.1, sqrt(T_dd))` is the HLL signal speed along `d` as a
    fraction of `chat` -- exactly the speed `m1_flux` hands the Riemann solver;
  - `chiE`  : `rho kappa_E`, the absorption coefficient that damps `E_rad`;
  - `chiF`  : `rho kappa_F`, the coefficient that damps the flux;
  - `hrat`  : `4 a_rad T^3 kappa_P/kappa_E / (rho c_v)`, the ratio of the
    radiation to the gas heat capacity, weighted by how strongly the cell emits
    relative to how strongly it absorbs (see [`StabilityBound`](#StabilityBound));
  - `dxmin` : the smallest active cell width, which only the fitting form reads;
  - `rinert`: `(1 + T_max) E / (rho c^2)`, the ratio of the radiation to the gas
    inertia that caps the damping of the momentum block, with `E` the radiation
    energy density of all groups and `T_max` the largest diagonal element of
    their Eddington tensor (see [`StabilityBound`](#StabilityBound)). Zero drops the cap.

### `chat_factor` {#chat_factor}

Source: [`src/rsla.jl:276`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/rsla.jl#L276)

```julia
chat_factor(limiter, phi0, cell::LocalCell) -> phi
```

The local speed of light reduction factor, in `[phi0, 1]`, for one cell and one
group. `phi0` is the global nominal reduction `chat/c` the user asked for.

Pointwise and allocation-free: it is called once per cell per group per substep.

### `stability_denominator` {#stability_denominator}

Source: [`src/rsla.jl:288`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/rsla.jl#L288)

```julia
stability_denominator(cell) -> D
```

`D = max(sdx - chiE/(2 + K), sdx - chiF/(2 + KF))` with `K = hrat cdt chiE` and
`KF = rinert cdt chiF`, so that
the bound of [`StabilityBound`](#StabilityBound) is `phi cdt D <= 1`. `D <= 0` means no
bound.



---

<!-- page: reference/coupling.md -->

# Matter-radiation coupling

Docstrings from `src/coupling.jl`, `src/coupling_solvers.jl`, `src/coupling_ode.jl`, `src/source_terms.jl`, `src/dust.jl`, `src/newton.jl`.

## Exported

### `AbstractCoupling` {#AbstractCoupling}

Source: [`src/coupling.jl:53`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L53)

```julia
AbstractCoupling
```

Supertype for matter-radiation coupling solvers. A subtype implements

    solve_coupling(method, state) -> CouplingResult

taking a [`CouplingState`](#CouplingState) for one cell and returning the updated gas
internal energy and group radiation energies.

Three are provided:

  - [`BracketedCoupling`](#BracketedCoupling) -- backward Euler in the natural variables,
    reduced to the single unknown `E_gas` and solved inside a bracket. The
    default;
  - [`QuokkaCoupling`](#QuokkaCoupling)    -- backward Euler in Quokka's replaced base
    variables `(E_gas, R_g)`;
  - [`AdaptiveCoupling`](#AdaptiveCoupling)  -- an error-controlled ODE solve.

They solve the same equations and should agree to their tolerances; that they
do is a test, and the reason the interface exists at all. They agree about as
independently as three solvers can: the first has one unknown, the second has
`1 + NG`, the third has `1 + NG` and a different discretisation, and no two of
them share a residual, an iteration or a linear solve.

### `QuokkaCoupling` {#QuokkaCoupling}

Source: [`src/coupling_solvers.jl:42`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling_solvers.jl#L42)

```julia
QuokkaCoupling(; tolerance = 1e-9, max_iterations = 100,
                 linsolve = ArrowheadSolve())
```

Backward Euler in Quokka's *replaced* base variables `(E_gas, R_g)`, where `R_g`
is the energy handed from gas to radiation group `g` over the step. The
formulation Quokka runs; the default is [`BracketedCoupling`](#BracketedCoupling).

Why not the obvious variables: with `(E_gas, E_g)` the residual for a group is a
difference of two large, nearly-cancelling terms once `tau = chat rho kappa dt`
is big, and its Jacobian entry scales like `tau`, so the linear solve is
ill-conditioned exactly where the physics is stiffest. Writing the unknown as
the *transfer* `R_g` moves `tau` from the residual into the definition, and the
condition number stops tracking it. That is what lets one step cross a coupling
time a hundred million times shorter than `dt`.

The Jacobian is an arrowhead -- diagonal in the groups, plus one dense row and
one dense column for the gas -- so `linsolve` defaults to
[`ArrowheadSolve`](#ArrowheadSolve) and inverts it in `O(NG)` with no matrix ever formed.
The diagonal is the same physical assumption [`group_energies`](#group_energies) makes when
it eliminates the group block, and [`DenseSolve`](#DenseSolve) is the escape hatch and
the cross-check; see [`AbstractJacobianSolve`](#AbstractJacobianSolve).

It is also hand-derived rather than taken from [`coupling_jacobian`](#coupling_jacobian), and
has to be: `R_g` is not a state variable, so there is no `dR_g/dt` to
differentiate. The derivation is written out in the Newton loop.

### `BracketedCoupling` {#BracketedCoupling}

Source: [`src/coupling_solvers.jl:252`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling_solvers.jl#L252)

```julia
BracketedCoupling(; tolerance = 1e-9, max_iterations = 100, root_finder = Brent())
```

Backward Euler in the natural variables `(E_gas, E_g)`, reduced to **one scalar
equation** and handed to a bracketing root-finder. The default.

The solve is two separate statements, and this is the whole of it:

  - **The equation.** The group block is linear in `E_g` at fixed gas
    temperature, so [`group_energy_values`](#group_energy_values) solves it in closed form and
    what is left is [`energy_balance`](#energy_balance): the gas energy at which the cell's
    books balance. One unknown, no `1 + NG` system, no Jacobian, no linear solve.
  - **The algorithm.** Any bracketing method written against SciMLBase's
    `IntervalNonlinearProblem` interface, as `root_finder`. The default is
    BracketingNonlinearSolve's `Brent`: Brent's method as Brent (1973) wrote it,
    with the minimum step and one evaluation per iteration, both since 1.12.8
    (SciML/NonlinearSolve.jl#1340). Over the 240-cell sweep of
    `docs/coupling-new-method.md` it needs 7.7 evaluations of the equation on
    average and 12 at worst, with no failures. The package's other methods plug
    in unchanged -- `ModAB()` is close behind, `Bisection()` is the reference,
    slow and impossible to get wrong on a valid bracket. Before 1.12.8 its
    `Brent` had neither property and took 20.1 evaluations on average and 70 at
    worst, and an in-tree copy of the method, `ZBrent`, stood in for it.

Derivative-free methods are the right fit here even though the derivative is
known in closed form: each evaluation of `G` costs a Planck integral, and its
derivative costs another (`planck_fractions_dT`). A derivative-free method that
needs as few evaluations as a Newton iteration therefore wins outright, and
`Brent`'s 7.7 are fewer than the 9 value-and-derivative evaluations of the
hand-written Newton this replaced.

**Why it is the default: it cannot walk away from the root.** A bracket always
exists (`G <= 0` at the temperature floor, `G >= 0` once the gas holds the whole
cell's energy), and a bracketing method never leaves it. The unsafeguarded
`1 + NG` iteration has no such guard and does not merely overshoot -- with a
steeply temperature-dependent opacity its Newton *direction* can be wrong.
Measured over 240 cells spanning three opacity laws and `tau_cell` from 1e-4 to
1e12, this solver fails none and [`QuokkaCoupling`](#QuokkaCoupling) fails 75.

Three things the solve does that a generic root-finder does not, each for a
reason:

  - **The bracket is built by marching outward from the old gas energy**, by
    factors of two, not taken as `[cv Tfloor, E_tot]`. Where the opacity makes
    `G` non-monotone the step can have several roots, and a bracketing method
    returns *one* of them without saying which. On the sweep's one such cell
    (`kappa ~ T^2`, gas at 0.1 and radiation at 3, three roots at 0.110, 1.17
    and 2.52) the error-controlled ODE ends at 0.109, and which root a method
    returned from the wide bracket depended on the method. Marching from the old
    state isolates the root continuously connected to where the cell started,
    unless two roots lie within a factor of two of each other.
  - **The tolerance is converted.** Every method in the package stops when the
    bracket is narrower than `abstol` in `E_gas`; this solver promises `|G| <=
    tolerance * E_tot`, and `G` is exactly the cell's energy-conservation error.
    The two differ by `dG/dE_gas`, which reaches `1 + (c/chat) 4 a T^3 / cv` --
    thousands, in a radiation-dominated cell. So after the first solve the
    residual is checked, and if it is too large the solve is repeated on the
    library's own final bracket with `abstol` divided by `dG/dE_gas` there, which
    is effectively constant across so narrow a bracket. Convergence is judged on
    the residual, not on the library's return code.
  - **`iterations` counts evaluations this solver makes itself** -- the bracket
    march -- plus one per call to the root-finder. The library does not report its
    own evaluation count, and counting it through the equation would allocate 16
    bytes a cell, which this solver does not.

The reduction inherits one assumption from [`group_energies`](#group_energies): groups
exchange energy with the gas and never directly with each other. That is the same
assumption [`ArrowheadSolve`](#ArrowheadSolve) makes; a term coupling groups directly would
make the group block a matrix and there would be no closed form to eliminate.

### `AdaptiveCoupling` {#AdaptiveCoupling}

Source: [`src/coupling_ode.jl:107`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling_ode.jl#L107)

```julia
AdaptiveCoupling(; reltol = 1e-2, abstol = 1e-10, alg = nothing)
```

Solve the matter-radiation coupling with an adaptive, error-controlled stiff ODE
integrator rather than one implicit step.

This is a **reference solver**, not a production one. Its job is to say what the
coupling ODE's answer actually is, so that [`QuokkaCoupling`](#QuokkaCoupling) and
[`BracketedCoupling`](#BracketedCoupling) -- which take a single backward-Euler step and are
first order in `dt` -- can be checked against something whose error is controlled
rather than assumed. An adaptive integrator takes tens of internal steps per cell
per timestep and allocates its own caches: measured against the one-step solvers
it is 12 times slower at its loosest setting and several hundred at a tight one,
the ratio growing with the stiffness because that is what it is refusing to take
in one step, and it costs 8 to 21 kB a cell where they cost nothing. Use it to
verify, not to run.

  - `reltol` : relative tolerance of the integrator. The default `1e-2` is
    deliberately loose: the point of the comparison is whether the one-step
    solvers land in the right place, and a tolerance far below the discretisation
    error of the scheme they are embedded in buys nothing but wall time.
  - `abstol` : absolute tolerance, quoted as a **fraction of the cell's total
    energy**. The one-step solvers scale their residual test the same way, and for
    the same reason: an absolute energy means one thing in CGS and another in
    code units, and a group holding `1e-30` of the spectrum must not drive the
    step size to zero on its own relative error.
  - `alg`    : the integrator, or `nothing` for the default (`Rosenbrock23`).
    Any stiff `OrdinaryDiffEq` algorithm works -- `Rodas5P()` and `FBDF()` come
    with the package, and anything from a sub-package you load yourself does too
    (`TRBDF2()`, `KenCarp4()`). An explicit method will stall: `chat rho kappa dt`
    reaches `1e8` in an optically thick cell. Whichever you choose, it is handed
    the coupling's analytic Jacobian and an exact `df/dt`, so no algorithm here
    ever differentiates the right-hand side numerically.

```julia
rad = RadiationPhysics(; c = 1.0, a_rad = 1.0, opacity = ConstantOpacity(1e5),
                       coupling = AdaptiveCoupling(reltol = 1e-4))
```

### `AbstractDustModel` {#AbstractDustModel}

Source: [`src/dust.jl:18`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/dust.jl#L18)

```julia
AbstractDustModel
```

Supertype for the dust-gas thermal coupling model carried by
[`RadiationPhysics`](#RadiationPhysics). [`NoDust`](#NoDust), the default, couples the radiation
to the gas directly; [`BateKetoDust`](#BateKetoDust) couples it to dust in instantaneous
equilibrium, and the dust to the gas by collisions.

### `NoDust` {#NoDust}

Source: [`src/dust.jl:28`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/dust.jl#L28)

```julia
NoDust()
```

No dust: the radiation exchanges energy with the gas directly, at the gas
temperature. The default.

### `BateKetoDust` {#BateKetoDust}

Source: [`src/dust.jl:36`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/dust.jl#L36)

```julia
BateKetoDust(; coefficient, particle_mass = 1)
```

Dust in instantaneous thermal equilibrium, coupled to the radiation at its own
temperature `T_d` and to the gas by the collisional rate of Keto & Field (2005),

    Lambda_gd = coefficient * n^2 * sqrt(T) * (T - T_d),   n = rho / particle_mass ,

the energy per unit volume and time the gas hands to the dust. The dust holds no
energy, so `T_d` is whatever makes `Lambda_gd` equal to what the dust radiates
net, and the total `E_gas + sum_g (c/chat_g) E_g` is conserved.

Use it for the cold ISM, where the gas has negligible opacity and cools or heats
only through the dust. With it, the opacity law of [`RadiationPhysics`](#RadiationPhysics) is
the *dust* opacity per unit mass of gas, evaluated at `T_d`, and the gas has no
opacity of its own. The parameters are Quokka's: `coefficient` is its
`radiation.dust_gas_interaction_coeff` (`2.5e-34` erg cm³ s⁻¹ K⁻³ᐟ² in CGS, from
Keto & Field) and `particle_mass` its `mean_molecular_mass`.

Supported by [`BracketedCoupling`](#BracketedCoupling) only, which reduces the step to one
equation in `T_d` for every value of `coefficient`, zero included: the gas is
then isolated and the dust is in radiative equilibrium with the field.

### `AbstractJacobianSolve` {#AbstractJacobianSolve}

Source: [`src/newton.jl:45`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/newton.jl#L45)

```julia
AbstractJacobianSolve
```

How [`QuokkaCoupling`](#QuokkaCoupling) solves the linear system of one Newton step. Two
are provided:

  - [`ArrowheadSolve`](#ArrowheadSolve) -- eliminate the group block into the gas row.
    `O(NG)`, forms no matrix, allocates nothing. The default for both.
  - [`DenseSolve`](#DenseSolve)     -- assemble the Newton matrix and factorise it.
    `O(NG^3)`, allocates, assumes nothing. The reference.

The arrowhead is exact for the coupling as it stands, and it is not a small
saving: at four groups it is the difference between roughly 0.9 kB a call and
none, and between 25 and 70 per cent of the wall time of the whole cell solve
over `NG = 4` to `16`. That is why it is the default.

It is exact because of a *physical assumption*: groups exchange energy with the
gas and never directly with each other, so the group block of
[`CouplingJacobian`](#CouplingJacobian) is diagonal. That is a property of the terms in
[`coupling_rhs`](#coupling_rhs) today, not a truth about radiation. Compton
redistribution between groups, or overlapping lines, would give that block
off-diagonal entries, and the elimination has nowhere to put them.

What makes it acceptable as a default is that the assumption is now *checked*.
`DenseSolve` solves the same system without it, and the suite asserts that the
two agree -- block by block on a matrix built from the real Jacobian, and end to
end through a converged cell. A default may encode an assumption when a checked
alternative exists; it may not when the assumption is silent, and until
`DenseSolve` existed this one was silent: both in-tree solvers called the
elimination, so they could agree with each other and both be wrong.

The cross-check has to exist because the failure would be quiet. Newton stops on
the residual of the true equations, so a damaged matrix cannot converge to a
wrong answer -- it can only fail to converge, and a cell that exhausts
`max_iterations` returns its last iterate and increments a counter rather than
stopping the run. What a broken elimination looks like from outside is a slower,
slightly wrong simulation with a nonzero `newton_failures`, which is exactly the
kind of symptom that gets blamed on the physics. Nothing about a run reports it;
a test has to.

`DenseSolve` stays the reference implementation, and is what to switch to the day
a term is added that couples groups directly. That day is not free there either
-- `rad_rad` is an `SVec` today, so the dense assembly writes a diagonal where it
would have to write a block -- but that is one line of assembly against an
elimination that has no place for the entries at all.

[`QuokkaCoupling`](#QuokkaCoupling) is the only caller. [`BracketedCoupling`](#BracketedCoupling) has one
unknown and so no linear system, and [`AdaptiveCoupling`](#AdaptiveCoupling) hands its matrix
to OrdinaryDiffEq, which factorises it itself.

### `DenseSolve` {#DenseSolve}

Source: [`src/newton.jl:97`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/newton.jl#L97)

```julia
DenseSolve()
```

Assemble the Newton matrix `I - dt J` as an ordinary `(1+NG)x(1+NG)` matrix and
solve it by LU factorisation (LinearAlgebra's `lu!`/`ldiv!`, in place on the
freshly built matrix and right-hand side).

It makes no use of the arrowhead structure, which is what makes it the
reference: it solves the system that [`ArrowheadSolve`](#ArrowheadSolve) assumes something
about, so the two agreeing is a direct test of the assumption rather than of two
copies of it. Pass `linsolve = DenseSolve()` to either solver to run that
comparison, and switch to it for good if a term is added that couples groups
directly -- see [`AbstractJacobianSolve`](#AbstractJacobianSolve).

**It allocates, and it must**: `NG` is a compile-time constant but a `Matrix` is
heap storage, so every Newton iteration of every cell buys a matrix, a
right-hand side and the factorisation's pivot vector. Measured: 272 bytes per
linear solve at one group, 464 at four, 976 at eight, 3.0 kB at sixteen, which
makes a converged three-iteration cell cost 0.54, 0.93, 1.9 and 5.9 kB
respectively. Wall time is 1.3 to 1.7 times [`ArrowheadSolve`](#ArrowheadSolve) at four to
sixteen groups, and 4.7 times at one, where the linear solve is most of what a
grey cell does.

Nothing is on this path unless it is asked for: [`QuokkaCoupling`](#QuokkaCoupling) defaults
to `ArrowheadSolve()`, which is exactly zero bytes per cell.

### `ArrowheadSolve` {#ArrowheadSolve}

Source: [`src/newton.jl:125`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/newton.jl#L125)

```julia
ArrowheadSolve()
```

Solve the Newton step with [`solve_arrowhead`](#solve_arrowhead): eliminate the diagonal
group block into the gas row, `O(NG)`, no matrix formed, nothing allocated. The
default for [`QuokkaCoupling`](#QuokkaCoupling), which is the only solver that forms a
Newton system at all.

Exact while the coupling is the one in [`coupling_rhs`](#coupling_rhs), where groups meet
only through the gas. [`AbstractJacobianSolve`](#AbstractJacobianSolve) says what that assumption
is, what checks that it still holds, and what to do the day it stops.

## Internals

### `CouplingState` {#CouplingState}

Source: [`src/coupling.jl:80`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L80)

```julia
CouplingState{NG,T}
```

Everything the coupling of one cell needs: the old state, the material
properties, and the step.

  - `Egas`      : gas internal energy density at the start of the step
  - `Erad`      : group radiation energy densities at the start of the step
  - `src`       : external radiation energy added to each group over the step
  - `work`      : the lagged `v . F` work term for each group, already times `dt`
  - `rho`, `cv` : density and *volumetric* heat capacity `d(eint)/dT`, which is
    what [`heat_capacity`](#heat_capacity) returns, so `T = E_gas / cv` directly
  - `opacity`   : the opacity law, evaluated at whatever temperature the solver
    is currently at (see [`coupling_opacity`](#coupling_opacity))
  - `dt`, `c`, `a_rad`, `k_B`
  - `chat`      : the reduced speed of light *of each group*. One number per
    group rather than one per cell because a [`AbstractChatLimiter`](#AbstractChatLimiter) sets
    it from the group's own cell optical depth; with the default
    [`ConstantChat`](#ConstantChat) every entry is the same `phys.chat`. The gas side of
    the exchange is never scaled by it -- see [`coupling_rhs`](#coupling_rhs).
  - `groups`    : the frequency group structure, for the Planck fractions
  - `Tfloor`, `Efloor` : admissibility floors on gas temperature and group energy
  - `dust`      : the [`AbstractDustModel`](#AbstractDustModel). With [`NoDust`](#NoDust), the
    default when it is omitted, the radiation couples to the gas; with
    [`BateKetoDust`](#BateKetoDust) it couples to the dust, and `opacity` is the dust's

The *law* is carried, not a frozen pair of numbers, because the coupling is
solved by Newton's method and the exact Jacobian of an emission term whose
opacity moves with temperature contains `dkappa/dT`. A frozen coefficient would
make that term meaningless -- no finite difference of the residual would show
it -- and the two would then be inconsistent, which is worse for a Rosenbrock
method than no Jacobian at all. Quokka re-evaluates the opacity in every Newton
iteration for the same reason, and so does the grey driver in `source_terms.jl`.

### `CouplingResult` {#CouplingResult}

Source: [`src/coupling.jl:139`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L139)

```julia
CouplingResult{NG,T}
```

What a coupling solver returns: the new gas internal energy, the new group
radiation energies, how many iterations it took, whether it converged, and --
with a dust model -- the dust temperature `Tdust`, which the flux update needs
because the opacity is the dust's. Without one `Tdust` is `NaN`: there is no
dust, and the radiation couples at the gas temperature.

`converged = false` is reported rather than thrown so that one stubborn cell in
a large grid shows up in the run's diagnostics instead of killing the run.

### `solve_coupling` {#solve_coupling}

Source: [`src/coupling.jl:162`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L162)

```julia
solve_coupling(method, state) -> CouplingResult
```

Advance one cell's matter-radiation coupling over `state.dt`.

### `gas_temperature_of` {#gas_temperature_of}

Source: [`src/coupling.jl:171`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L171)

```julia
gas_temperature_of(state, Egas) -> T
```

Gas temperature from internal energy, floored. `cv` is volumetric, so `E_int = cv T`.

### `gas_scale` {#gas_scale}

Source: [`src/coupling.jl:178`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L178)

```julia
gas_scale(state) -> SVec{NG}
```

`c / chat_g`: what one unit of group `g`'s radiation energy costs the gas.

The reduced speed of light scales the radiation side of the exchange and not the
matter side, so every quantity that crosses from one to the other picks this up.
It is a vector because each group may run at its own reduced speed; with the
default [`ConstantChat`](#ConstantChat) every entry is the same number and `dot(gas_scale(s), x)`
is `(c/chat) * sum(x)`.

### `thermal_emission` {#thermal_emission}

Source: [`src/coupling.jl:192`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L192)

```julia
thermal_emission(state, T) -> SVec{NG}
```

`4 pi B_g / c = a_rad T^4 f_g(T)`, the equilibrium radiation energy density in
each group at temperature `T`. Sums to `a_rad T^4` exactly, whatever the group
edges, because the Planck fractions do.

### `coupling_opacity` {#coupling_opacity}

Source: [`src/coupling.jl:204`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L204)

```julia
coupling_opacity(state, T) -> (kappaP, kappaE)
```

The Planck- and energy-mean opacity of each group at temperature `T`.

The two coincide, because the multigroup opacity here is piecewise constant
across a group and averaging a constant against any weight returns it (see
`opacity.jl`). They are returned as a pair anyway: this is the one place a model
that separates them would change, and every solver reads the pair rather than
the model.

### `coupling_opacity_dT` {#coupling_opacity_dT}

Source: [`src/coupling.jl:220`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L220)

```julia
coupling_opacity_dT(state, T) -> (dkappaP_dT, dkappaE_dT)
```

`d kappa/dT` of each group at temperature `T`: the derivative of the law
[`coupling_opacity`](#coupling_opacity) evaluates, and what makes
[`coupling_jacobian`](#coupling_jacobian) exact. Zero for an opacity that does not supply one
(see [`dkappa_dT`](#dkappa_dT)).

### `thermal_emission_dT` {#thermal_emission_dT}

Source: [`src/coupling.jl:233`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L233)

```julia
thermal_emission_dT(state, T) -> SVec{NG}
```

`d(4 pi B_g / c)/dT = 4 a T^3 f_g + a T^4 f_g'`.

The second term is what moves energy between groups as the gas heats. A grey
problem has `f = 1` and `f' = 0` and this reduces to `4 a T^3`.

### `coupling_coefficients` {#coupling_coefficients}

Source: [`src/coupling.jl:248`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L248)

```julia
coupling_coefficients(state, T) -> (emission, absorption)
```

The two numbers per group that every formulation of the coupling is built from:

  - `emission_g   = rho kappa_P,g(T) 4 pi B_g(T) / c`, the rate at which the gas
    puts energy into group `g`;
  - `absorption_g = rho kappa_E,g(T)`, the coefficient multiplying `E_g` in the
    rate at which the group gives it back.

so that the unscaled exchange rate of group `g` is `emission_g - absorption_g E_g`,
linear in `E_g` and with every temperature dependence in the two coefficients.

**This is the single source of truth for the coupling physics**, and it is stated
as this pair rather than as a right-hand side because the three solvers need two
*different* things from it and must not each assemble their own:

  - [`AdaptiveCoupling`](#AdaptiveCoupling) integrates the rate, `dE_g/dt = chat_g (emission_g
    - absorption_g E_g)`, which is [`coupling_rhs`](#coupling_rhs) below.
  - [`BracketedCoupling`](#BracketedCoupling) never forms a rate at all. It uses the *same* two
    coefficients to solve the backward-Euler group block in closed form -- see
    [`group_energies`](#group_energies) -- because that block is linear in `E_g`, which is
    exactly the property this pair makes visible.

Writing them as a product rather than as `(kappa_P, B)` separately is also the
more general statement: an opacity model that defines `kappa_P` by an integral
against `B` (Quokka's `PPL_opacity_full_spectrum`) has an emission rate but no
meaningful `kappa_P` on its own. [`thermal_emission`](#thermal_emission) stays available for
[`QuokkaCoupling`](#QuokkaCoupling), whose Jacobian needs `kappa_P/kappa_E` and so cannot
work with the product.

### `coupling_coefficients_dT` {#coupling_coefficients_dT}

Source: [`src/coupling.jl:285`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L285)

```julia
coupling_coefficients_dT(state, T) -> (d emission/dT, d absorption/dT)
```

The temperature derivatives of [`coupling_coefficients`](#coupling_coefficients), and the reason
[`coupling_jacobian`](#coupling_jacobian) is exact rather than merely linear in `E`:

    d emission_g   / dT = rho (dkappa_P,g/dT B_g + kappa_P,g dB_g/dT)
    d absorption_g / dT = rho dkappa_E,g/dT

Both `dkappa/dT` terms are zero for an opacity that does not supply one (see
[`dkappa_dT`](#dkappa_dT)), and the emission derivative then reduces to the familiar
`rho kappa_P 4 a T^3` plus the Planck fractions' own drift between groups.

### `coupling_rhs` {#coupling_rhs}

Source: [`src/coupling.jl:306`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L306)

```julia
coupling_rhs(state, Egas, Erad) -> (dEgas, dErad)
```

The right-hand side of the coupling ODE, without the external source: the rate
at which gas internal energy is lost and each group's radiation energy gained.

Shared by every solver, so all three integrate demonstrably the same equations.

The unscaled exchange rate `rho (kappa_P B_g - kappa_E E_g)` is formed first and
then scaled two different ways: the *radiation* side by that group's `chat`, and
the *gas* side by the full `c`. That asymmetry is the reduced speed of light
approximation itself -- and writing it this way is what lets each group carry its
own `chat` without the gas equation acquiring a group index it has no business
having.

The opacity is evaluated *here*, at `Egas`'s own temperature, rather than
frozen by the caller. That is what makes [`coupling_jacobian`](#coupling_jacobian) the true
derivative of this function when `kappa` depends on temperature.

### `group_energies` {#group_energies}

Source: [`src/coupling.jl:332`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L332)

```julia
group_energies(state, Egas) -> (Erad, dErad_dEgas)
```

**Part 1 of the reduction.** The group radiation energies that solve the
backward-Euler group block exactly at this gas energy, and their derivative with
respect to it.

The group block is

    (E_g - E_g^0 - S_g - W_g) = dt chat_g (emission_g(T) - absorption_g(T) E_g) ,

which is *linear* in `E_g` at fixed `T`, and in which no group appears in
another group's equation -- they meet only through the gas temperature. So it is
not solved by iteration at all:

    E_g(T) = (rad0_g + dt chat_g emission_g) / (1 + dt chat_g absorption_g),
    rad0_g = E_g^0 + S_g + W_g .

With `kappa_P = kappa_E` that is a convex combination of where the group started
and the Planck value at the gas temperature, weighted by the optical depth of
the step: `dt chat rho kappa -> 0` leaves the group alone, `-> infinity` puts it
in equilibrium with the gas. All of the stiffness is in that one weight, and it
is handled in closed form rather than by a Newton iteration, which is why
[`BracketedCoupling`](#BracketedCoupling) has no linear algebra in it.

The derivative follows by differentiating the same expression,

    dE_g/dT = dt chat_g (d emission_g/dT - d absorption_g/dT E_g)
              / (1 + dt chat_g absorption_g) ,

and `dE_g/dE_gas` is that over `cv`. It is returned alongside the energies
because the two share the coefficient evaluation. [`group_energy_values`](#group_energy_values)
is the form without it, and is what a derivative-free root-finder should call.

This is a property of the *backward-Euler step*, not of the coupling ODE: the
group equations are linear in `E_g` with time-dependent coefficients, so along a
trajectory they integrate to a convolution over the gas history and not to any
algebraic `E_g(T)`. [`AdaptiveCoupling`](#AdaptiveCoupling) therefore cannot use this and
integrates the full `1 + NG` system.

### `group_energy_values` {#group_energy_values}

Source: [`src/coupling.jl:382`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L382)

```julia
group_energy_values(state, Egas) -> Erad
```

[`group_energies`](#group_energies) without the derivative: the group energies that solve
the backward-Euler group block at this gas energy, and nothing else.

This is what [`BracketedCoupling`](#BracketedCoupling)'s root-finder evaluates at every trial
gas energy. Its methods are derivative-free, and leaving the derivative out
leaves out `planck_fractions_dT`, which is a large part of what an evaluation
costs -- measured, it is why a derivative-free method taking 13 evaluations beats
a Newton iteration taking 9.

### `energy_balance` {#energy_balance}

Source: [`src/coupling.jl:410`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L410)

```julia
energy_balance(state, Egas, Erad) -> G
```

**Part 2 of the reduction.** The cell's total-energy residual,

    G = (E_gas - gas0) + sum_g (c/chat_g) (E_g - rad0_g) ,
    gas0 = E_gas^0 - sum_g (c/chat_g) W_g ,   rad0_g = E_g^0 + S_g + W_g ,

which expands to `E_gas + sum_g (c/chat_g) E_g` minus the same combination at
the start of the step -- new total energy minus old. The lagged work term
cancels out of it completely and survives only inside `rad0_g`.

It contains **no physics**: no opacity, no Planck function, nothing but the
`c/chat_g` weighting that the reduced speed of light imposes on what one unit of
group energy costs the gas. It is linear in its arguments. That is what makes it
shareable, and it is shared exactly -- [`QuokkaCoupling`](#QuokkaCoupling)'s gas residual
`(E_gas - E_gas^0) + (c/chat) sum_g R_g` reduces to this identically once its
group residual vanishes, work term included.

**It is the residual of the system only where the group block is solved.**
Writing `F_0` for the gas residual and `F_g` for the group ones,

    F_0 = G - sum_g (c/chat_g) F_g ,

so `G` and `F_0` agree exactly when every `F_g = 0` and not otherwise. Hand this
an arbitrary `Erad` and it returns a number that vanishes in the wrong place;
hand it [`group_energies`](#group_energies)'s output and it is the scalar equation the
whole backward-Euler step reduces to. That pairing is the contract between the
two parts, and [`BracketedCoupling`](#BracketedCoupling) is the only thing that relies on it.

### `dust_energy_balance` {#dust_energy_balance}

Source: [`src/coupling.jl:446`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L446)

```julia
dust_energy_balance(state, Td) -> (H, Egas, Erad)
```

The one equation a backward-Euler step with [`BateKetoDust`](#BateKetoDust) reduces to,
with the dust temperature `Td` as the unknown, and the state it implies.

Given `Td`, everything else is closed form:

 1. The group block is the dust-free one with the coefficients evaluated at
    `Td`: `E_g = (rad0_g + dt chat_g emission_g(Td)) / (1 + dt chat_g
    absorption_g(Td))`, which is `_eliminate_groups` unchanged.
 2. The gas energy follows from energy conservation, [`energy_balance`](#energy_balance)
    `= 0` solved for `E_gas`: the dust holds no energy, so whatever the
    radiation gained over the step the gas lost. `T = E_gas / cv`.
 3. What is left is the gas equation,

        H = (gas0 - E_gas) - dt K sqrt(T) (T - Td) ,

    the energy the radiation took from the dust minus the energy the dust took
    from the gas by collisions. It is zero exactly where the dust is in balance.

Steps 1 and 2 hold for every trial `Td`, so the total energy is conserved to
round-off at every iterate, not only at the root. `H` is written with the sign
that makes it increase with `Td` -- hotter dust radiates more and is fed less --
so it brackets like [`energy_balance`](#energy_balance) does in `E_gas`.

`H` is *not* a good convergence test: its collision term multiplies the
round-off in `T - Td` by `dt K sqrt(T)`, which reaches 1e8 of the cell's energy
in a strongly coupled cell. [`BracketedCoupling`](#BracketedCoupling) tests the state across
its final bracket instead; `docs/coupling-new-method-dust.md` §4.

### `CouplingJacobian` {#CouplingJacobian}

Source: [`src/coupling.jl:487`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L487)

```julia
CouplingJacobian{NG,T}
```

The exact Jacobian of [`coupling_rhs`](#coupling_rhs), in four blocks:

  - `gas_gas` : `d(dE_gas/dt)/dE_gas`
  - `gas_rad` : `d(dE_gas/dt)/dE_g`, one entry per group
  - `rad_gas` : `d(dE_g/dt)/dE_gas`, one entry per group
  - `rad_rad` : `d(dE_g/dt)/dE_g`, *diagonal* -- group `g`'s rate sees no other
    group's energy, only the gas temperature they all share

That structure is what the arrowhead elimination in `coupling_solvers.jl`
exploits to cost `O(NG)` rather than `O(NG^3)`. It is a property of the physics
rather than of any solver, which is why it is stated here -- and why it is an
assumption rather than a guarantee: a term that moved energy between groups
directly (Compton redistribution, overlapping lines) would make `rad_rad` a
matrix, and every solver that assumed otherwise would be quietly wrong. See
[`AbstractJacobianSolve`](#AbstractJacobianSolve), which is where that choice is made explicit.

### `coupling_jacobian` {#coupling_jacobian}

Source: [`src/coupling.jl:513`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L513)

```julia
coupling_jacobian(state, Egas, Erad) -> CouplingJacobian
```

The exact Jacobian of [`coupling_rhs`](#coupling_rhs) at `(Egas, Erad)`.

With `exch_g = rho (kappa_P,g B_g(T) - kappa_E,g E_g)` and `T = E_gas / cv`,

    d exch_g / d E_gas = rho (dkappaP_g B_g + kappaP_g dB_g/dT
                              - dkappaE_g E_g) / cv
    d exch_g / d E_g   = -rho kappaE_g

The radiation rows are these times that group's `chat`, and the gas rows are
`-c` times their sum, exactly as in [`coupling_rhs`](#coupling_rhs).

The `dkappa/dT` terms are what make this *exact* rather than merely
linear-in-`E`; they come from the opacity law through
[`coupling_opacity_dT`](#coupling_opacity_dT) and are zero for any law that does not depend on
temperature. Including them cuts `QuokkaCoupling`'s Newton iterations by 25 to
40 per cent wherever the coupling is neither
transparent nor already in equilibrium, and by nothing at all where it is: the
correction is proportional to `B_g - E_g`.

[`AdaptiveCoupling`](#AdaptiveCoupling) hands `J` straight to `ODEFunction` rather than
paying `1 + NG` extra right-hand side evaluations to difference one -- which it
could not do anyway, since an `SVec`'s element type is fixed and no dual number
can flow through [`coupling_rhs`](#coupling_rhs). [`BracketedCoupling`](#BracketedCoupling) does not
use this at all: it needs `dE_g/dE_gas` of the *eliminated* group block, which
[`group_energies`](#group_energies) forms from the same coefficients without assembling any
matrix.

### `apply_energy_floors` {#apply_energy_floors}

Source: [`src/coupling.jl:558`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling.jl#L558)

```julia
apply_energy_floors(state, Egas, Erad) -> (Egas, Erad)
```

Project the solved state onto the admissible set by moving energy between the
gas and the radiation rather than creating it, so the total is unchanged.

### `_energy_bracket` {#_energy_bracket}

Source: [`src/coupling_solvers.jl:426`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/coupling_solvers.jl#L426)

```julia
_energy_bracket(G, state, x0, xmin) -> (lo, hi, evaluations, found)
```

A bracket of an increasing `G` around the root continuously connected to `x0`:
start there, and step by factors of two in the direction the sign of `G` says the
root lies until the sign changes, never below `xmin`.

For the dust-free equation `x0` is the old gas energy and `xmin = cv Tfloor`.
Downwards the walk stops at the temperature floor, where `G <= 0` whenever the
state is admissible; upwards it stops once the gas holds more than the cell's
total energy, where `G >= 0` whenever no group has been handed a negative
starting energy by the lagged work term. For the dust equation `x0` is the old
gas temperature and `xmin = Tfloor`; see [`dust_energy_balance`](#dust_energy_balance). Neither
bound is trusted blindly: if the walk runs out without a sign change the cell is
reported unconverged rather than guessed at.

`G::F` rather than `G`, so the walk specialises on the equation and allocates
nothing -- a function argument that is only passed through is not specialised on
by default, and the measured cost of that was 2.8 kB a cell.

### `SourceStats` {#SourceStats}

Source: [`src/source_terms.jl:29`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/source_terms.jl#L29)

```julia
SourceStats(cells, newton_iterations, max_newton, failures)
```

Diagnostics returned by [`radiation_source_step!`](#radiation_source_step-bang).

`newton_iterations` is the total over all cells and `max_newton` the worst any
single cell needed, both counted *per cell* rather than per outer iteration, so
`newton_iterations / cells <= max_newton` always holds. `failures` counts cells
that exhausted `max_iterations` without converging; those cells did not solve
the coupling at all.

Accumulated into [`Diagnostics`](#Diagnostics) by `advance_radiation!`.

### `radiation_source_step!` {#radiation_source_step-bang}

Source: [`src/source_terms.jl:56`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/source_terms.jl#L56)

```julia
radiation_source_step!(U, R, eos, phys, grid, dt, source, t, floors;
                       update_momentum = true, bfield = nothing)
```

Apply the implicit matter-radiation coupling to the conserved gas state `U` and
radiation state `R` over a time `dt`, in every interior cell.

`source` is either `nothing` or a callable `source(x, y, z, t)` returning a
radiation energy source density (energy per volume per time), e.g. the
luminosity of a star spread over a cell.

`update_momentum = false` freezes the gas momentum, which is what the static
test problems (Marshak wave, matter-radiation equilibration) assume; it is set
automatically when hydrodynamics is disabled.

With MHD, `bfield` is the simulation's [`MagneticField`](#MagneticField). The coupling
does not change the field, so the magnetic energy is taken out of the total
energy before the solve and put back after it, and the gas sees only its internal
energy.

This method is the grey (`NG == 1`) driver; a multigroup `phys` selects
[`multigroup_source_step!`](#multigroup_source_step-bang) instead, by dispatch on the group count, and
so does a grey `phys` with a dust model, which this driver does not have.

Returns a [`SourceStats`](#SourceStats).

### `_group_component` {#_group_component}

Source: [`src/source_terms.jl:321`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/source_terms.jl#L321)

```julia
_group_component(R, i, j, k, Val(NG), Val(C)) -> SVec{NG}
```

Component `C` of every group at cell `(i, j, k)`, gathered into a group vector.

A free function taking `Val(NG)` so the `ntuple` unrolls, and taking `R, i, j, k`
as arguments so that the closure captures nothing the caller assigns -- the
boxing trap CLAUDE.md records.

### `_group_chat` {#_group_chat}

Source: [`src/source_terms.jl:334`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/source_terms.jl#L334)

```julia
_group_chat(chat, i, j, k, Val(NG)) -> SVec{NG}
```

Each group's reduced speed of light at cell `(i, j, k)`.

The same shape as [`_group_component`](#_group_component), and a free function for the same
reason, but the `chat` array is `(NG, i, j, k)` rather than `(4NG, i, j, k)`:
there is one speed per group, not four.

### `_beta_force` {#_beta_force}

Source: [`src/source_terms.jl:346`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/source_terms.jl#L346)

```julia
_beta_force(closure, Erad, F0x, F0y, F0z, kappa, B, m1, m2, m3, c, chat*dt)
    -> (SVec{NG}, SVec{NG}, SVec{NG})
```

The `O(v/c)` terms of the per-group flux update: thermal emission dragged along
by the moving gas, plus the radiation pressure acting on it. The grey driver's
same expression, evaluated once per group.

Every value is an argument for the reason given above; written as a closure over
the outer-iteration variables it would box them.

### `multigroup_source_step!` {#multigroup_source_step-bang}

Source: [`src/source_terms.jl:375`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/source_terms.jl#L375)

```julia
multigroup_source_step!(U, R, eos, phys, grid, dt, source, t, floors;
                        update_momentum = true, bfield = nothing)
```

The multigroup matter-radiation coupling: what [`radiation_source_step!`](#radiation_source_step-bang)
dispatches to when `phys` has more than one frequency group. Same arguments,
same return value, same meaning.

Each interior cell is packed into a [`CouplingState`](#CouplingState) and handed to
`phys.coupling`, so the choice of implicit integrator is a property of the
physics object; `phys.tolerance` and `phys.max_iterations` belong to the grey
driver's own Newton loop and are not consulted here.

`source` returns a *total* radiation energy source density, which is shared out
over the groups by the Planck spectrum at the local gas temperature -- the
spectrum of a thermal emitter, and the only one a scalar can imply. At `NG == 1`
that reduces to the grey source exactly.

Returns a [`SourceStats`](#SourceStats).

### `dust_gas_coefficient` {#dust_gas_coefficient}

Source: [`src/dust.jl:76`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/dust.jl#L76)

```julia
dust_gas_coefficient(dust, rho) -> K
```

`K = coefficient * (rho / particle_mass)^2`, so that the collisional rate is
`K sqrt(T) (T - T_d)`.

### `solve_arrowhead` {#solve_arrowhead}

Source: [`src/newton.jl:19`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/newton.jl#L19)

```julia
solve_arrowhead(J00, J0g, Jg0, Jgg, F0, Fg) -> (dx0, dxg)
```

Solve the bordered ("arrowhead") linear system

    [ J00   J0g^T ] [dx0]   [F0]
    [ Jg0   diag  ] [dxg] = [Fg]

for the Newton update, by eliminating the group block into the gas row. Exact,
`O(NG)`, and forms no matrix -- which matters because this runs per cell, per
Newton step, per timestep.

A group with `Jgg[g] == 0` is decoupled from the gas (zero optical depth), and
contributes nothing to the elimination; its update is zero.

### `solve_jacobian` {#solve_jacobian}

Source: [`src/newton.jl:139`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/newton.jl#L139)

```julia
solve_jacobian(linsolve, J00, J0g, Jg0, Jgg, F0, Fg) -> (dx0, dxg)
```

Solve one Newton step's system, given the four blocks of the Newton matrix and
the two blocks of the right-hand side, in the layout [`solve_arrowhead`](#solve_arrowhead)
draws. Dispatches on an [`AbstractJacobianSolve`](#AbstractJacobianSolve).

The two paths differ once the matrix is singular: the arrowhead treats a zero
group entry as a decoupled group and returns a zero update for it, while an LU
factorisation of the same matrix throws. [`QuokkaCoupling`](#QuokkaCoupling) never produces
one -- it writes a large finite sentinel rather than `-Inf` for a group of zero
optical depth, so its matrix factorises too.



---

<!-- page: reference/chemistry.md -->

# Photoionization chemistry

Docstrings from `src/chemistry.jl`, `src/chemistry_solvers.jl`, `src/chemistry_step.jl`, `src/networks/`.

## Exported

### `AbstractNetwork` {#AbstractNetwork}

Source: [`src/chemistry.jl:38`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L38)

```julia
AbstractNetwork
```

Supertype for chemical networks: what is evolved in one cell over one step, and
nothing about how. Networks are generated by JAFF (<https://github.com/jaff-chemistry/jaff>)
with its `honghu` template from a network file and its `.jfunc`; `networks/` holds those
of the built-in networks, and `networks/regenerate.sh` makes their Julia files. A
generated network is a struct with one field, `options`, a [`NetworkOptions`](#NetworkOptions), and
these methods of its type:

  - [`nspecies`](#nspecies) and [`nbands`](#nbands), the numbers of species and of radiation
    bands;
  - [`species_names`](#species_names), [`species_masses`](#species_masses) (g),
    [`network_reactions`](#network_reactions) and [`band_edges`](#band_edges) (eV);
  - [`jaff_rhs!`](#jaff_rhs-bang) and [`jaff_jacobian!`](#jaff_jacobian-bang), the right-hand side and its
    exact Jacobian as JAFF writes them.

Everything else is common to all networks and defined here: [`chem_rhs!`](#chem_rhs-bang),
[`chem_jacobian!`](#chem_jacobian-bang) and [`chem_scales!`](#chem_scales-bang), which the integrators call, and
[`network_temperature`](#network_temperature). The unknowns are
`u = [n_1 ... n_NS, E, N_1, f_1, ..., N_NB, f_NB]`: number densities in cm^-3 (electrons
included), the internal energy density, and per band the photon number density divided
by `phi = chat / c` and the factor by which the band's flux has been attenuated.
[`nunknowns`](#nunknowns), [`ienergy`](#ienergy), [`iband`](#iband) and [`iflux`](#iflux) give the layout.

The integrators in `chemistry_solvers.jl` are [`RosenbrockChem`](#RosenbrockChem) and
[`BackwardEulerChem`](#BackwardEulerChem); both read the right-hand side and the Jacobian from
the network and nothing else, so they integrate the same problem.

### `NetworkOptions` {#NetworkOptions}

Source: [`src/chemistry.jl:69`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L69)

```julia
NetworkOptions{NB}(; photon_energy, groups = (1, ..., NB), isothermal = nothing, Tmin = 1.0)
```

The settings of a network that are not in its JAFF files, one per network instance.
The keywords of every generated network's constructor are these.

  - `photon_energy` : the mean photon energy of each band, in erg; a number for one band.
    It converts the group's radiation energy density to photons, and belongs to the
    source spectrum rather than to the network. A network's heating per ionization is
    written in its `.jfunc` and must be kept consistent with it by hand.
  - `groups`        : the radiation group each band reads and writes; a number for one
    band. Those groups must have zero thermal opacity.
  - `isothermal`    : a temperature in K that replaces the energy equation. The rates
    see this temperature, `E` is not evolved, and the energy written back to the grid
    is the one that follows from the number densities and this temperature.
  - `Tmin`          : the floor of the temperature the rates see, K.

### `nspecies` {#nspecies}

Source: [`src/chemistry.jl:108`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L108)

```julia
nspecies(net)
```

The number of species of the network, electrons included, which is also the number of
mass scalars a simulation with this network carries. They are the first
`nspecies(net)` unknowns, as number densities in cm^-3. A method of the network's type.

### `nbands` {#nbands}

Source: [`src/chemistry.jl:117`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L117)

```julia
nbands(net)
```

The number of radiation bands the network reads. Each has two unknowns after the
internal energy, the photon density and the flux factor. A method of the network's type.

### `species_names` {#species_names}

Source: [`src/chemistry.jl:125`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L125)

```julia
species_names(net)
```

The names of the species as JAFF writes them (`"H"`, `"H+"`, `"e-"`), in the order of
the state vector. A method of the network's type.

### `species_masses` {#species_masses}

Source: [`src/chemistry.jl:133`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L133)

```julia
species_masses(net)
```

The mass of one particle of each species, in g, in the order of the state vector. They
convert the mass scalars `rho X_s` of the grid to the number densities the network works
in. A method of the network's type.

### `network_reactions` {#network_reactions}

Source: [`src/chemistry.jl:142`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L142)

```julia
network_reactions(net)
```

The reactions of the network as JAFF writes them, for reading. A method of the network's
type.

### `band_edges` {#band_edges}

Source: [`src/chemistry.jl:150`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L150)

```julia
band_edges(net)
```

The edges of the network's radiation bands in eV, `nbands(net) + 1` of them. The
network's photoionization cross-sections are averaged over these bands. A method of the
network's type.

### `AbstractChemSolver` {#AbstractChemSolver}

Source: [`src/chemistry.jl:456`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L456)

```julia
AbstractChemSolver
```

Supertype for chemistry integrators. A subtype implements

    chem_workspace(solver, net, ::Type{T}) -> work
    solve_chemistry!(work, solver, net, cell, u) -> ChemStats

so that a new integrator is a new subtype and two methods, not an edit to the
grid driver. Two are provided: [`RosenbrockChem`](#RosenbrockChem), an adaptive stiff
integrator from OrdinaryDiffEq and the default, and [`BackwardEulerChem`](#BackwardEulerChem),
one backward-Euler step with a Newton iteration, which is the comparison.

### `RosenbrockChem` {#RosenbrockChem}

Source: [`src/chemistry_solvers.jl:53`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry_solvers.jl#L53)

```julia
RosenbrockChem(; alg = Rosenbrock23(linsolve = SimpleLUFactorization()),
               reltol = 1e-2, abstol = 1e-8)
```

Integrate the chemistry of each cell over the step with an adaptive, error-controlled
stiff ODE integrator from OrdinaryDiffEq. This is the default chemistry integrator.
It takes as many internal steps as the cell needs, so a cell that changes little
costs a few and a cell on the ionization front costs more, and it needs no Newton
iteration to converge before it can take a step.

  - `alg`    : the algorithm. Any stiff OrdinaryDiffEq algorithm works: `Rodas5P()`
    and `FBDF()` come with the package, and anything from a sub-package you load
    yourself does too. An explicit method will stall. It is handed the network's
    exact Jacobian and an exact `df/dt = 0`, so it never differentiates the
    right-hand side numerically. The default solves its linear systems with
    LinearSolve's `SimpleLUFactorization`, a dense LU written in Julia, and not with
    the integrator's own default, which calls OpenBLAS: OpenBLAS takes a global lock
    to allocate its buffers on every call, so a threaded chemistry step ran slower
    than a single-threaded one (a 24^3 step took 85 ms on one thread and 184 ms on
    four, against 74 ms and 20 ms with this one). An algorithm you pass keeps its own
    default; give it `linsolve = Honghu.SimpleLUFactorization()` to get the same, which
    needs no `using LinearSolve`.
  - `reltol` : the relative tolerance. The default `1e-2` is deliberately loose,
    as for [`AdaptiveCoupling`](#AdaptiveCoupling).
  - `abstol` : the absolute tolerance, as a **fraction of [`chem_scales!`](#chem_scales-bang)**: the
    integrator is given `abstol * scale[i]` for unknown `i`, so it means the same in
    any unit system and a species with a negligible share of the cell does not
    drive the step size to zero on its own relative error.

OrdinaryDiffEq's own warnings are switched off (`verbose = SciMLLogging.None()`).
A cell that fails is reported through `ChemStats.converged`, which the grid
driver counts and summarises, and a threaded run would otherwise print one long
warning for every failing cell.

It allocates, unlike [`BackwardEulerChem`](#BackwardEulerChem): about 350 bytes per cell and call with
the default algorithm (measured on a 16^3 box; `test/test_performance.jl` bounds it at
2 kB), all inside OrdinaryDiffEq's `reinit!` and `solve!`. The workspace holds one reused
integrator, so give each thread its own and never share one.

```julia
solver = RosenbrockChem(alg = Rodas5P(), reltol = 1e-4)
```

### `BackwardEulerChem` {#BackwardEulerChem}

Source: [`src/chemistry_solvers.jl:154`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry_solvers.jl#L154)

```julia
BackwardEulerChem(; tol = 1e-10, max_iterations = 50)
```

Integrate the chemistry of each cell with one backward-Euler step over the whole
`dt`: Newton's method on `G(u) = u - u0 - dt f(u)` with the matrix `I - dt J`,
using the network's right-hand side and exact Jacobian. There is no adaptivity
and no sub-cycling, so the step is first order in `dt` and is as accurate as one
step of that length can be. It is the comparison for [`RosenbrockChem`](#RosenbrockChem),
and it allocates nothing.

Species and band unknowns are clamped at zero after each Newton update, so an
iterate never carries a negative abundance into a rate. The Newton update is
damped by a backtracking line search on the scaled residual, `max_i |G_i| / scale_i`:
it tries the whole update, then a half, a quarter and so on up to 20 halvings, and
keeps the first trial, clamped as above, whose residual is smaller than the
current one, or the whole update if none is. It is still one backward-Euler step:
the line search changes how the nonlinear equation of that step is solved, never
the equation.

Newton can still fail, and it is the one-step equation and not the damping that is
at fault. Three cases are known. (a) A stiff growth term, such as collisional
ionization with `beta n_H0 dt > 1`: the backward-Euler root is positive, but the
Newton direction from the old state points into the zero clamp, which a residual
line search cannot cross. (b) Photoionization-front cells at `Gamma dt` of order
`1e2` to `1e3`, where the temperature and the clamps interact inside the step.
(c) A discontinuous rate, such as the 100 K switch of the recombination cooling,
can make the iteration cycle across it. Every such cell is reported through
`ChemStats.converged`, which the grid driver counts, and is never hidden; if Newton
does not converge in `max_iterations`, or meets a singular matrix or a non-finite
update, the result says so and `u` holds the last iterate.

  - `tol`            : stop when the largest Newton update, or the largest residual
    `G`, in units of [`chem_scales!`](#chem_scales-bang), is at most this. The scales are taken
    once, at the state the step starts from. The residual test is what ends a
    solve whose update is stuck a rounding error above `tol`.
  - `max_iterations` : the most Newton iterations to take.

`ChemStats.steps` is the number of Newton iterations taken, 0 if the start state
already satisfies the equation to `tol`.

### `Photochemistry` {#Photochemistry}

Source: [`src/chemistry_step.jl:28`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry_step.jl#L28)

```julia
Photochemistry(network; solver = RosenbrockChem(), emission = nothing)
```

Photochemistry for a [`Simulation`](#Simulation): the [`AbstractNetwork`](#AbstractNetwork) to evolve, the
[`AbstractChemSolver`](#AbstractChemSolver) that integrates it in every cell, and the source of ionizing
photons. Pass it as `Simulation(...; chemistry = Photochemistry(net))`; the simulation then
carries `nspecies(network)` mass scalars, one per species, as `rho X_s`.

  - `network`  : what is evolved in one cell, a network generated by JAFF such as
    [`HydrogenIliev2`](#HydrogenIliev2).
  - `solver`   : the integrator, [`RosenbrockChem`](#RosenbrockChem) by default or
    [`BackwardEulerChem`](#BackwardEulerChem).
  - `emission` : `emission(x, y, z, t)` gives the photons emitted per cm^3 and per second
    into the first band of the network at the cell centre, or `nothing` for no source.
    It is evaluated once per cell and per radiation substep, with `t` the *start* of the
    substep. A point source on the grid is a narrow Gaussian normalised to the photon rate.
    It is called from several threads at once, one per row of cells, so it must be thread-safe:
    no shared mutable state, no caching in a global, no unsynchronised counters.

The chemistry step runs after each IMEX radiation substep, over the substep's length,
and does four things in every cell: it adds `phi q dt` to the photon density of the
first band, with `phi = chat / c` of the band's group, which is how the reduced speed of
light enters the source; it integrates the network over the substep; it writes the species
and the gas internal energy back; and it sets the band's energy from the photon density
and multiplies its flux by the factor the network integrated with it. The network works in
`N = n_gamma / phi`, the photon density divided by `phi`, and its rates are written with
`chat N`: the gas sees `c n_gamma`, the photon loss is `chat sigma n_H0 n_gamma`, the budget
`n_H+ + N` is conserved and the ionization equilibrium does not depend on `chat`.

A simulation with chemistry has these requirements, and refuses to be built without them
(an `ArgumentError`): radiation is enabled, the chat limiter is [`ConstantChat`](#ConstantChat),
`beta_order = 0`, every group has zero thermal opacity (the matter-radiation coupling takes
the gas temperature from the constant-mean-molecular-weight equation of state, which ignores
the species and differs from the network's temperature by up to a factor of 2 in ionized gas,
so a group with opacity would drive the gas to the wrong temperature; with none, only the
network changes the gas energy), `nscalars` is 0 or
`nspecies(network)`, and the equation of state has `adiabatic_index(eos) = 5/3`, because
the network's temperature `e / (3/2 k_B n)` is that of a monatomic gas and another gamma would
give the hydrodynamics a pressure inconsistent with it. The network's rates are in CGS, so
the run must be in CGS units. Momentum deposited by the absorbed photons is not modelled.

The species are the mass scalars of the simulation, and they are renormalised to add up to the
gas density on entry to every hydrodynamic right-hand side (the start of each Runge-Kutta stage), at the
start of the radiation advance, where the burn reads them, and at the end of every step ([`enforce_scalar_floors!`](#enforce_scalar_floors-bang)): each `rho X_s` is reconstructed on its own, so
with PLM or PPM the species fluxes do not add up to the mass flux and the sum would drift from
`rho`. The last Runge-Kutta combine is not followed by a right-hand side, which is why the
radiation advance renormalises once more before the chemistry runs.

```julia
net = HydrogenIliev2(photon_energy = 29.65 * Honghu.CGS.eV)
chem = Photochemistry(net; emission = (x, y, z, t) -> 1e-17)
```

### `HydrogenIliev1` {#HydrogenIliev1}

Source: [`src/networks/hydrogen_iliev1.jl:123`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/networks/hydrogen_iliev1.jl#L123)

```julia
HydrogenIliev1(; photon_energy, groups, isothermal = nothing, Tmin = 1.0)
```

The chemical network `HydrogenIliev1`, generated by JAFF with its `honghu` template
(3 species, 1 radiation band(s)). The keywords are those of
[`NetworkOptions`](#NetworkOptions); `photon_energy` is the mean photon energy of each band, in erg.

Species, in the order of the state vector: H, H+, e-.

Reactions:
  - `H + _PHOTON -> H+ + e-`
  - `H+ + e- -> H`

Band edges, in eV: 13.6, Inf.

### `HydrogenIliev2` {#HydrogenIliev2}

Source: [`src/networks/hydrogen_iliev2.jl:164`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/networks/hydrogen_iliev2.jl#L164)

```julia
HydrogenIliev2(; photon_energy, groups, isothermal = nothing, Tmin = 1.0)
```

The chemical network `HydrogenIliev2`, generated by JAFF with its `honghu` template
(3 species, 1 radiation band(s)). The keywords are those of
[`NetworkOptions`](#NetworkOptions); `photon_energy` is the mean photon energy of each band, in erg.

Species, in the order of the state vector: H, H+, e-.

Reactions:
  - `H + _PHOTON -> H+ + e-`
  - `H+ + e- -> H`
  - `H + e- -> H+ + e- + e-`

Band edges, in eV: 13.6, Inf.

## Internals

### `jaff_rhs!` {#jaff_rhs-bang}

Source: [`src/chemistry.jl:159`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L159)

```julia
jaff_rhs!(du, net, nden, photden, rflux, tgas, c_hat)
```

The right-hand side as JAFF generates it: the time derivative of every unknown, from
the tuples of number densities `nden`, photon densities `photden` (divided by `phi`)
and flux factors `rflux`, the temperature `tgas` and the reduced speed of light
`c_hat`. Written by JAFF's `honghu` template for each network; called only by
[`chem_rhs!`](#chem_rhs-bang), which supplies the temperature.

### `jaff_jacobian!` {#jaff_jacobian-bang}

Source: [`src/chemistry.jl:170`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L170)

```julia
jaff_jacobian!(J, net, nden, photden, rflux, tgas, c_hat)
```

The Jacobian of [`jaff_rhs!`](#jaff_rhs-bang) as JAFF generates it, at constant internal energy:
the temperature `tgas = E / (3/2 k_B sum_s n_s)` is a function of the unknowns, and its
derivatives are included. It writes only the entries that can be nonzero; called only by
[`chem_jacobian!`](#chem_jacobian-bang), which zeroes the matrix first.

### `species_mass` {#species_mass}

Source: [`src/chemistry.jl:184`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L184)

```julia
species_mass(net, s)
```

The mass of one particle of species `s`, in g; see [`species_masses`](#species_masses).

### `band_group` {#band_group}

Source: [`src/chemistry.jl:191`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L191)

```julia
band_group(net, b)::Int
```

The index of the radiation group whose energy band `b` of the network reads and
writes, from the network's [`NetworkOptions`](#NetworkOptions). That group must have zero thermal
opacity, so the matter-radiation coupling leaves it alone and only the network changes
its energy.

### `band_photon_energy` {#band_photon_energy}

Source: [`src/chemistry.jl:201`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L201)

```julia
band_photon_energy(net, b)
```

The mean energy `eps_b` of a photon of band `b`, in erg, from the network's
[`NetworkOptions`](#NetworkOptions). It converts the group's radiation energy density to the photon
number density, `E_rad = eps_b phi N_b`.

### `nunknowns` {#nunknowns}

Source: [`src/chemistry.jl:210`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L210)

```julia
nunknowns(net)
```

The length of the unknown vector `u` of the network, `nspecies + 1 + 2 nbands`.

### `ienergy` {#ienergy}

Source: [`src/chemistry.jl:217`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L217)

```julia
ienergy(net)
```

The index of the internal energy density in the unknown vector, `nspecies(net) + 1`.

### `iband` {#iband}

Source: [`src/chemistry.jl:224`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L224)

```julia
iband(net, b)
```

The index of the photon density of band `b` in the unknown vector,
`nspecies(net) + 2b`.

### `iflux` {#iflux}

Source: [`src/chemistry.jl:232`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L232)

```julia
iflux(net, b)
```

The index of the flux factor of band `b` in the unknown vector, `nspecies(net) + 2b + 1`.

### `chem_rhs!` {#chem_rhs-bang}

Source: [`src/chemistry.jl:268`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L268)

```julia
chem_rhs!(du, u, net, cell)
```

Write the time derivative of the unknowns `u` of one cell into `du`, in
cm^-3 s^-1 for the species and the photons, erg cm^-3 s^-1 for the energy and
s^-1 for the flux factors. `cell` is the [`ChemCell`](#ChemCell) of constants the step needs.
It computes the temperature, with the network's `isothermal` and `Tmin`
([`NetworkOptions`](#NetworkOptions)), and calls the generated [`jaff_rhs!`](#jaff_rhs-bang). This and
[`chem_jacobian!`](#chem_jacobian-bang) are the single source of truth for the network's physics: every
integrator's residual and linearisation come from them.

### `chem_jacobian!` {#chem_jacobian-bang}

Source: [`src/chemistry.jl:287`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L287)

```julia
chem_jacobian!(J, u, net, cell)
```

Write the exact Jacobian `df_i/du_j` of [`chem_rhs!`](#chem_rhs-bang) into the dense
`nunknowns x nunknowns` matrix `J`, overwriting every entry. It must be exact,
not a finite difference: a Newton iteration converges quadratically only if it is,
and a Rosenbrock method is handed it so that it never differentiates the
right-hand side numerically.

The generated [`jaff_jacobian!`](#jaff_jacobian-bang) is the Jacobian at constant internal energy.
Where the temperature does not follow the state (isothermal, at the `Tmin` floor), this
turns it into the Jacobian at constant temperature: with `T = E / (c_v sum_s n_s)` and
`c_v = 3/2 k_B`, `df/dn_s` at constant `T` is the column of `n_s` plus `c_v T` times the
column of `E`, and the column of `E` vanishes. The row of `E` vanishes in isothermal mode,
and the column of a number density or photon density clamped at zero vanishes.

### `chem_scales!` {#chem_scales-bang}

Source: [`src/chemistry.jl:352`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L352)

```julia
chem_scales!(scale, u, net, cell)
```

Write one positive absolute scale per unknown into `scale`: the size of that unknown in
this cell, at the state `u`. A solver measures its tolerance as a fraction of it, so a
tolerance means the same thing in any unit system and a species holding a negligible
share of the cell does not drive the step size to zero on its own relative error.
Every species and every photon density is measured against the total particle density,
so a photon density counts as large when it would ionize the cell; the energy against
itself or the energy of the cell at `Tmin`, whichever is larger; the flux factors
against 1. Compare the energy scale of [`AdaptiveCoupling`](#AdaptiveCoupling).

### `network_temperature` {#network_temperature}

Source: [`src/chemistry.jl:379`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L379)

```julia
network_temperature(net, n::AbstractVector, eint)
```

The gas temperature of a cell with species number densities `n[1:nspecies(net)]` and
internal energy density `eint`: a monatomic ideal gas of all the species, electrons
included, in CGS,

    T = eint / (3/2 k_B sum_s n_s) ,

which is the temperature the network's rates see (before the `Tmin` floor) and the one
JAFF writes the Jacobian with. It is what `gas_temperature` reports in place of the
constant-`mu` equation of state, which is wrong in partially ionized gas.

### `network_eint` {#network_eint}

Source: [`src/chemistry.jl:400`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L400)

```julia
network_eint(net, n::AbstractVector, T)
```

The internal energy density of a cell with species number densities
`n[1:nspecies(net)]` at temperature `T`, the inverse of [`network_temperature`](#network_temperature).
`set_initial_conditions!` uses it to turn a `T` key into an energy when a network is
present.

### `chem_internal_energy` {#chem_internal_energy}

Source: [`src/chemistry.jl:416`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L416)

```julia
chem_internal_energy(net, u)
```

The internal energy density to write back to the grid from the unknown vector `u`:
`u[ienergy(net)]`, or in isothermal mode the energy that follows from the number
densities and the fixed temperature.

### `initial_mass_fractions` {#initial_mass_fractions}

Source: [`src/chemistry.jl:428`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L428)

```julia
initial_mass_fractions(net, nt::NamedTuple)
```

The mass fractions `X_s` of the network's species for an initial condition `nt` that
gave no `X` key. It throws an `ArgumentError`, because a generic network cannot know
what the user's keys mean: give `X`, one mass fraction per species in the order of
[`species_names`](#species_names), electrons included.

### `ChemCell` {#ChemCell}

Source: [`src/chemistry.jl:440`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L440)

```julia
ChemCell{T}(rho, c, chat, dt)
```

The constants of one cell and one step: the gas density `rho`, the speed of light `c`,
the reduced speed of light `chat` of the band's group, and the step length `dt`. The
rates read `chat`, which multiplies every photon density in a network's equations
because those are stored divided by `phi = chat / c`. An immutable bit-type, so building
one per cell allocates nothing.

### `ChemStats` {#ChemStats}

Source: [`src/chemistry.jl:471`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L471)

```julia
ChemStats(steps, converged)
```

What a chemistry solve reports for one cell: `steps`, the number of internal
steps an adaptive integrator took or the number of Newton iterations a
backward-Euler step took (zero if the state the step starts from already satisfies
its equation), and whether it `converged`. An unconverged cell is
reported, never hidden: the driver counts it in `Diagnostics`.

### `chem_workspace` {#chem_workspace}

Source: [`src/chemistry.jl:485`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L485)

```julia
chem_workspace(solver, net, ::Type{T})
```

Allocate the scratch space for solving one cell at a time with `solver` on `net`
in precision `T`. One workspace belongs to one user at a time: the grid driver
makes one per row of cells and never shares it between threads, so no workspace is
ever keyed on `Threads.threadid()`.

### `solve_chemistry!` {#solve_chemistry-bang}

Source: [`src/chemistry.jl:495`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry.jl#L495)

```julia
solve_chemistry!(work, solver, net, cell, u::Vector{T}) -> ChemStats
```

Evolve the cell's unknowns `u` over `cell.dt`: on entry `u` is the initial state,
on exit the answer. `work` comes from [`chem_workspace`](#chem_workspace) for the same
`solver`, `net` and `T`. Returns the [`ChemStats`](#ChemStats) of the solve; when it did not
converge, `u` holds the solver's last state, which the caller should not trust.

### `ChemStepStats` {#ChemStepStats}

Source: [`src/chemistry_step.jl:90`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry_step.jl#L90)

```julia
ChemStepStats(cells, steps, max_steps, failures)
```

What one [`chemistry_step!`](#chemistry_step-bang) did: the number of `cells` solved, the `steps` of the
solver summed over them (see [`ChemStats`](#ChemStats)), the most steps any one cell took
(`max_steps`), and the number of cells whose solve did not converge (`failures`). Two add:
the counts sum and the maximum is taken, which is how `advance_radiation!` accumulates the
substeps into [`Diagnostics`](#Diagnostics).

### `chemistry_step!` {#chemistry_step-bang}

Source: [`src/chemistry_step.jl:223`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/chemistry_step.jl#L223)

```julia
chemistry_step!(sim, dt, t) -> ChemStepStats
```

Integrate the chemistry of every interior cell of `sim` over `dt`, from time `t`: the
second half of each radiation substep, which `advance_radiation!` calls right after the IMEX
step. It adds the emission to the photon density, runs the solver of the simulation's
[`Photochemistry`](#Photochemistry) in each cell, and writes the species, the gas internal energy and
the band's energy and flux back; see [`Photochemistry`](#Photochemistry) for what each does. It uses the
workspaces the simulation built, one per row of cells, so it is safe to call from one place
at a time and allocates nothing per cell with [`BackwardEulerChem`](#BackwardEulerChem).

The cells whose solve did not converge are counted in the returned [`ChemStepStats`](#ChemStepStats)
and keep the solver's last state. It throws an `ArgumentError` for a simulation built
without `chemistry`.



---

<!-- page: reference/output.md -->

# Output, plotting and comparison

Docstrings from `src/output.jl`, `src/plotting.jl`, `src/metrics.jl`, `src/compare.jl`.

## Exported

### `write_vtk` {#write_vtk}

Source: [`src/output.jl:81`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L81)

```julia
write_vtk(sim, path) -> String
```

Write the interior state as a VTK image-data file (cell data). `path` may be
given with or without the `.vti` extension; the file name actually written is
returned.

A numbered series such as `data_00000.vti`, `data_00001.vti`, ... is recognised
by ParaView as a time series.

### `write_line` {#write_line}

Source: [`src/output.jl:139`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L139)

```julia
write_line(sim, path; dir = 1, at = nothing)
```

Write a one-dimensional cut through the domain as a whitespace-separated text
table with a header line: coordinate, then every field of
[`output_fields`](#output_fields) component by component.

`dir` selects the axis of the cut and `at` the transverse cell indices (a
2-tuple of interior indices, default the middle of the domain). Intended for
quick plotting of shock tubes and Marshak waves.

### `save_checkpoint` {#save_checkpoint}

Source: [`src/output.jl:204`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L204)

```julia
save_checkpoint(sim, path) -> String
```

Write a raw binary checkpoint (grid metadata plus the full conserved state,
ghost cells included) that [`load_checkpoint!`](#load_checkpoint-bang) can restore. With MHD
the state is the cell-centred `U` and the face-centred field `sim.B`, ghost
faces included. The file extension `.honghu` is added unless the path already
ends in `.honghu`, or in `.h3d`, the extension from the package's old name: a
script that saves to and loads from a fixed `.h3d` path keeps working. The file
is written in the current format either way, format 3:

| bytes | content |
|:---|:---|
| 8 | the magic `HONGHU ` |
| 8 | `sizeof(T)`, the precision |
| 24, 24 | the interior cell counts and the ghost widths, three `Int64` each |
| 24 | `t`, `dt` (`Float64`) and `step` (`Int64`) |
| 8, 16, 8 | flags and counts (`Int64`): radiation, the rows of `U` and `R`, MHD |
| ... | `U`, then `R` with radiation, then `B[1]`, `B[2]`, `B[3]` with MHD, each in native byte order |

### `load_checkpoint!` {#load_checkpoint-bang}

Source: [`src/output.jl:251`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L251)

```julia
load_checkpoint!(sim, path) -> sim
```

Restore a simulation from a checkpoint written by [`save_checkpoint`](#save_checkpoint).
The grid, floating-point precision, presence of radiation and of a magnetic
field, and the number of gas and radiation variables (hence of mass scalars) must
match those of `sim`, or it throws before touching `sim.t`, `sim.dt`, `sim.step`
or the state. A checkpoint of format 2 holds no magnetic field, so it loads only
into a simulation without MHD; one of format 1 and a `.h3d` checkpoint, written
when the package was called Hydro3D, carry no variable counts either, so they
load only into a simulation without MHD and with `nscalars == 0`.

### `coordinates` {#coordinates}

Source: [`src/plotting.jl:9`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L9)

```julia
coordinates(grid, d) -> Vector
```

Cell-centre coordinates of the interior cells along direction `d`.

### `available_fields` {#available_fields}

Source: [`src/plotting.jl:26`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L26)

```julia
available_fields(sim) -> Tuple{Vararg{Symbol}}
```

The field names [`field`](#field) accepts for this simulation. Radiation fields
are only present when the radiation module is enabled.

A multigroup run also lists `:Erad_1`, `:Fx_1`, ... one set per group. A grey
run does not: with one group those names are accepted but they name the same
array as `:Erad`, `:Fx`, ..., and advertising both would suggest a distinction
that is not there.

A run with mass scalars also lists `:X_1`, ..., `:X_ns`, the mass fraction of
each scalar, and a run with MHD lists `:bx`, `:by`, `:bz`, the cell-centred field
(the average of each cell's two faces), and `:magnetic_pressure`, `|b|^2 / 2`.

### `field` {#field}

Source: [`src/plotting.jl:67`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L67)

```julia
field(sim, name) -> (data, label)
```

Extract one named field over the interior as a fresh `(nx, ny, nz)` array,
together with a label suitable for an axis or colour bar.

See [`available_fields`](#available_fields) for the accepted names. `:Erad`, `:Fx`, `:Fy`,
`:Fz` and `:reduced_flux` are summed over the frequency groups, so they mean the
same thing in a grey run and a multigroup one; a trailing group number picks one
group out, as in `field(sim, :Erad_2)`. `:X_s` is the mass fraction
`rho X_s / rho` of mass scalar `s`, not the conserved density.

```julia
rho, lbl = field(sim, :density)
```

### `plotstate` {#plotstate}

Source: [`src/plotting.jl:178`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L178)

```julia
plotstate(sim; var = :density, slice = nothing, kwargs...)
```

Plot one field of the simulation, choosing the representation from the
dimensionality: a line plot in 1D, a heat map in 2D, and a heat map of the
mid-plane slice in 3D.

`var` is any name from [`available_fields`](#available_fields). `slice` overrides the slice
index in 3D. Remaining keyword arguments pass through to Plots.

**Requires `using Plots`.**

```julia
using Plots, Honghu
sim, tmax = Honghu.Problems.kelvin_helmholtz(n = 256)
run!(sim; tmax)
plotstate(sim, var = :density)
```

### `plotpanels` {#plotpanels}

Source: [`src/plotting.jl:199`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L199)

```julia
plotpanels(sim; vars = nothing, kwargs...)
```

A multi-panel overview of the state: density, velocity, pressure and gas
temperature, plus radiation energy and temperature when radiation is enabled.
Pass `vars` to choose the panels yourself.

**Requires `using Plots`.**

### `animate_run` {#animate_run}

Source: [`src/plotting.jl:210`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L210)

```julia
animate_run(sim; tmax, nframes = 100, var = :density, fps = 20,
            filename = "honghu.gif", kwargs...)
```

Integrate `sim` to `tmax` while capturing `nframes` evenly spaced frames of
`var`, and write an animated GIF. Returns the file name.

Named `animate_run` rather than `animate` so that it does not collide with
`Plots.animate` when both packages are in scope.

**Requires `using Plots`.**

```julia
using Plots, Honghu
sim, tmax = Honghu.Problems.kelvin_helmholtz(n = 256)
animate_run(sim; tmax, var = :density, filename = "kh.gif")
```

### `plotcompare` {#plotcompare}

Source: [`src/plotting.jl:230`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L230)

```julia
plotcompare(table_or_path...; metric = nothing, kwargs...)
```

Plot one or more [`ComparisonTable`](#ComparisonTable)s: each metric against resolution, one
line per variant, on log-log axes with the measured convergence rate in the
legend.

Accepts tables or the paths to tables written by [`compare`](#compare), so a figure
can be redrawn from stored numbers without re-running any simulation:

```julia
using Plots, Honghu
plotcompare("radhydro_shock_compare.txt")
```

Give it several tables to put the same schemes on different problems side by
side, each panel labelled with its problem. That comparison is the point --
one problem gives a ranking, two tell you whether the ranking means anything:

```julia
plotcompare("sod_shock_tube_riemann_compare.txt",
            "smooth_advection_riemann_compare.txt")
```

Pass `metric` to draw one panel per table instead of all of them.

A table with only one resolution -- one built by comparing prebuilt
[`Simulation`](#Simulation)s -- is drawn as a bar chart instead. There is no trend to
put on a log-log axis, and an axis that implies one would be a claim the run
never measured.

**Requires `using Plots`.**

### `relative_l1` {#relative_l1}

Source: [`src/metrics.jl:10`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/metrics.jl#L10)

```julia
relative_l1(num, ref) -> Real
```

Relative `L1` error `Σ|num - ref| / Σ|ref|` between a numerical result and a
reference of the same length.

This is the norm Quokka reports for its radiation tests, so a number produced
here is directly comparable with one produced there.

### `relative_l2` {#relative_l2}

Source: [`src/metrics.jl:27`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/metrics.jl#L27)

```julia
relative_l2(num, ref) -> Real
```

Relative `L2` error `√(Σ(num - ref)²/Σ ref²)`. Use when you care about a
localised feature that an `L1` norm would average away.

### `default_metrics` {#default_metrics}

Source: [`src/metrics.jl:41`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/metrics.jl#L41)

```julia
default_metrics(problem) -> NamedTuple
```

The metrics a built-in problem scores itself with, as a `NamedTuple` of
callables `metric(sim) -> Real` evaluated on the finished simulation.
[`compare`](#compare) uses these when you do not pass `metrics` yourself, so

```julia
compare(Honghu.Problems.radhydro_shock, variants; nx = (64, 128, 256))
```

needs no configuration at all.

Defined for the problems that have a reference solution to be scored against.
Problems without one (Kelvin-Helmholtz, the Marshak wave) have no default, and
`compare` then requires explicit `metrics`.

Adding a problem with an exact solution? Give it a method here, in one line, and
the test suite, the verification figures and the comparison harness all pick up
the same definition of "the error".

### `ComparisonTable` {#ComparisonTable}

Source: [`src/compare.jl:15`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L15)

```julia
ComparisonTable
```

The result of [`compare`](#compare): one row per (variant, resolution), a string
`variant` column and a numeric matrix.

Index it like a table -- `t[:l1_Trad]` gives a column, `t.variant` the labels --
or write it with [`write_comparison`](#write_comparison) and read it back with
[`read_comparison`](#read_comparison).

### `compare` {#compare}

Source: [`src/compare.jl:234`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L234)

```julia
compare(variants; sizes, metrics, tmax, name, path, outdir, verbose) -> ComparisonTable
```

Run each variant once per size, score every run, and return the results as a
[`ComparisonTable`](#ComparisonTable) which is also written to disk.

`variants` is a vector of `label => builder`, where a **builder** is a function
of resolution returning `(sim, tmax)` -- the contract the problem factories
already satisfy:

```julia
compare(["HLLC" => nx -> P.sod_shock_tube(; nx, riemann = HLLC()),
         "warm" => nx -> my_own_setup(nx)];
        sizes = (64, 128, 256), metrics = default_metrics(P.sod_shock_tube))
```

Because the builder is arbitrary code, a variant may differ in anything at all
-- a different initial condition, a different geometry, a global flag -- not
only in keywords the harness knows how to pass. A builder may also be a
prebuilt [`Simulation`](#Simulation), which fixes its own resolution and so needs an
explicit `tmax`.

  - `sizes`   : resolutions to sweep, default `(64, 128)`; each is handed to the
    builder. The stored `size` is read back off the grid that was built.
  - `metrics` : `NamedTuple` of `metric(sim) -> Real`. Required here; the forms
    taking a `problem` default it to [`default_metrics`](#default_metrics)`(problem)`.
  - `tmax`    : override the builder's suggested stopping time.
  - `name`    : what the table calls itself, and the stem of the default file.
  - `path`    : where to write the table; defaults to `<name>_compare.txt`
    inside `outdir` (default the working directory). Pass `path = nothing` to
    skip writing.

Every run also records `cells`, `steps`, `wall_s`, `floors` and the Newton
statistics, so a variant that is more accurate *because* it took ten times as
long, or that only converged with help from the positivity floors, is visible
rather than flattering.

Then `plotcompare(t)` (with Plots loaded), or `plotcompare("..._compare.txt")`
in a later session, redraws it without re-running anything.

See also the two sugars: [`compare(problem, variants)`](#compare) and
[`compare(problem, key, values)`](#compare).

Source: [`src/compare.jl:357`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L357)

```julia
compare(problem, variants; kwargs...) -> ComparisonTable
```

Variants as keywords to a problem: `variants` is a `NamedTuple` of keyword
`NamedTuple`s, which labels itself, or an iterable of `label => kwargs`. Each is
splatted into `problem` alongside the resolution.

```julia
compare(P.radhydro_shock,
        (P1 = (closure = EddingtonClosure(),),
         M1 = (closure = LevermoreClosure(),));
        sizes = (64, 128, 256))
```

`metrics` defaults to [`default_metrics`](#default_metrics)`(problem)` and the table names
itself after the problem. A variant's value may also be a builder or a prebuilt
[`Simulation`](#Simulation), so one call can mix "same problem, different keywords"
with "something else entirely". All other keywords are as for [`compare`](#compare).

Source: [`src/compare.jl:384`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L384)

```julia
compare(sims::Simulation...; tmax, metrics, kwargs...) -> ComparisonTable
compare((label => sim)...; tmax, metrics, kwargs...)
```

Compare simulations you have already built, however they differ. There is no
resolution sweep -- every configuration field of `Simulation` is `const`, so an
instance pins its own grid -- which means no convergence rate. For that, give
[`compare`](#compare) builders instead.

```julia
a, _ = P.sod_shock_tube(nx = 256, riemann = HLLC())
b, _ = P.sod_shock_tube(nx = 256, riemann = LLF())
compare("HLLC" => a, "LLF" => b; tmax = 0.2,
        metrics = default_metrics(P.sod_shock_tube))
```

`tmax` is required, because a simulation carries no suggested stopping time.
Unlabelled simulations are called `sim1`, `sim2`, ...; the harness will not
guess a name by inspecting what differs between them. The simulations are run
in place, so they are left finished and ready to plot.

Source: [`src/compare.jl:415`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L415)

```julia
compare(problem, key::Symbol, values; kwargs...) -> ComparisonTable
```

Sweep a single keyword: run `problem` once per entry of `values`, passing it as
`key`, and label each run with the value.

```julia
compare(P.sod_shock_tube, :riemann, (HLLC(), LLF()); sizes = (64, 128, 256))
```

This is the common case -- one knob, several settings -- and it writes the
scheme's name once instead of three times. `HLLC()` labels its rows `HLLC`;
numbers label themselves. Use the general form when a variant needs more than
one keyword, or when you want the labels to say something else.

The default table is `<problem>_<key>_compare.txt`, so sweeping two different
knobs on the same problem gives two files. All other keywords are as for
[`compare`](#compare).

### `write_comparison` {#write_comparison}

Source: [`src/compare.jl:502`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L502)

```julia
write_comparison(table, path) -> path
```

Write a [`ComparisonTable`](#ComparisonTable) as a tab-separated text table with a `#`
comment header carrying the provenance. Readable by hand, by
[`read_comparison`](#read_comparison), and by anything that skips comment lines.

### `read_comparison` {#read_comparison}

Source: [`src/compare.jl:533`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L533)

```julia
read_comparison(path) -> ComparisonTable
```

Read back a table written by [`write_comparison`](#write_comparison). Needs nothing beyond
the package, so a stored comparison can be re-plotted or re-analysed in a
session that never loads a solver.

### `convergence_rate` {#convergence_rate}

Source: [`src/compare.jl:574`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L574)

```julia
convergence_rate(table, metric; variant = nothing) -> Real
```

Least-squares slope of `log(metric)` against `log(size)` for one variant,
negated, so that a second-order scheme returns about `2`.

With one variant in the table `variant` may be omitted.

## Internals

### `_rad_group_sum` {#_rad_group_sum}

Source: [`src/output.jl:13`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L13)

```julia
_rad_group_sum(sim, comps) -> Array{T,4}
```

Sum of the radiation components `comps` -- given as their offsets *within* a
group, so `IERAD:IERAD` or `IFRX:IFRZ` -- over every frequency group, on the
interior, with the component axis kept.

The unsuffixed radiation outputs are group sums so that a grey file and a
multigroup file of the same problem carry the same quantity. With one group the
sum is the group, and the array is the plain slice it always was.

### `output_fields` {#output_fields}

Source: [`src/output.jl:35`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L35)

```julia
output_fields(sim) -> Vector{Tuple{String,Int,Array}}
```

The named fields written by [`write_vtk`](#write_vtk): `(name, ncomponents, data)`
where `data` is laid out with the component index first and then `x, y, z`.

A run with mass scalars adds `mass_fraction_1`, ... after `gas_temperature`: the
mass fraction `X_s`, not the conserved density `rho X_s`. A run with MHD adds
`magnetic_field`, the cell-centred field, after them.

`radiation_energy` and `radiation_flux` are summed over the frequency groups.
A multigroup run adds `radiation_energy_1`, `radiation_flux_1`, ... per group
after them; a grey run does not, since those would be exact duplicates of the
totals, and a grey file is byte for byte what it has always been.

### `has_default_metrics` {#has_default_metrics}

Source: [`src/metrics.jl:72`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/metrics.jl#L72)

```julia
has_default_metrics(problem) -> Bool
```

Whether [`default_metrics`](#default_metrics) has a method for `problem`, as opposed to
falling through to the error.

### `line` {#line}

Source: [`src/metrics.jl:80`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/metrics.jl#L80)

```julia
line(sim, name) -> Vector
```

The named field along the single active direction of a one-dimensional problem,
as a plain vector. A convenience for writing metrics.

### `Base.getindex` {#Base-getindex}

Source: [`src/compare.jl:36`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L36)

```julia
t[name] -> Vector{Float64}
```

The named numeric column of a [`ComparisonTable`](#ComparisonTable).

Source: [`src/compare.jl:48`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L48)

```julia
t[name, variant] -> Vector{Float64}
```

The named column restricted to one variant and ordered by size, which is the
slice most analysis wants:

```julia
t[:l1_density, "HLLC"] ./ t[:l1_density, "LLF"]   # how much the solver bought
```

### `rows` {#rows}

Source: [`src/compare.jl:66`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L66)

```julia
rows(t) -> Vector{NamedTuple}
```

The table as one `NamedTuple` per row, `variant` first. Convenient for filtering
and for feeding a plot.

### `variants` {#variants}

Source: [`src/compare.jl:77`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L77)

```julia
variants(t) -> Vector{String}
```

The distinct variant labels, in the order they were run.

### `BOOKKEEPING` {#BOOKKEEPING}

Source: [`src/compare.jl:86`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L86)

```julia
BOOKKEEPING
```

Column names that record how a run went rather than how good it was. They are
worth storing beside the metrics -- a variant that wins only because it took ten
times as long should be visible -- but they are not scores, so they get no
convergence rate and no panel on a plot.

### `metric_columns` {#metric_columns}

Source: [`src/compare.jl:97`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L97)

```julia
metric_columns(t) -> Vector{String}
```

The columns of a [`ComparisonTable`](#ComparisonTable) that are scores, i.e. everything not
in [`BOOKKEEPING`](#BOOKKEEPING).

### `is_error_metric` {#is_error_metric}

Source: [`src/compare.jl:117`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L117)

```julia
is_error_metric(t, metric) -> Bool
```

Whether `metric` behaves like an error: positive everywhere, and falling under
refinement for at least one variant.

Not every metric is one. `radhydro_shock`'s `spike` converges *to* 4.26 rather
than to zero, so a log-log slope through it is a number with no meaning and a
log axis is the wrong axis. Printing a table and plotting one both ask this,
rather than each deciding for itself.



---

<!-- page: reference/problems.md -->

# Test problems

Docstrings from `src/problems/`.

## Exported

### `sod_shock_tube` {#sod_shock_tube}

Source: [`src/problems/hydro.jl:3`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/hydro.jl#L3)

```julia
sod_shock_tube(; n = 256, gamma = 1.4, kwargs...) -> (sim, tmax)
```

The Sod (1978) shock tube in 1D: `(rho, p) = (1, 1)` for `x < 0.5` and
`(0.125, 0.1)` for `x > 0.5`, at rest, with outflow boundaries. Compare the
result at `tmax = 0.2` against [`sod_exact`](#sod_exact).

### `radiation_streaming` {#radiation_streaming}

Source: [`src/problems/radiation.jl:6`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L6)

```julia
radiation_streaming(; n = 128, chat_over_c = 1.0, closure = LevermoreClosure(),
                    beta_order = 0, kwargs...) -> (sim, tmax)
```

Free-streaming limit: radiation injected at the left boundary of a transparent
(`kappa = 0`), static medium. The front must advance at exactly `chat` while
keeping the reduced flux at the causal limit, which is where the M1 closure
differs from flux-limited diffusion.

At `tmax = 0.5` the front sits at `x = 0.5 chat`.

### `radhydro_shock_exact` {#radhydro_shock_exact}

Source: [`src/problems/exact.jl:7`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/exact.jl#L7)

```julia
radhydro_shock_exact() -> (x, rho, v, Tmat, Trad)
```

Semi-analytic solution of the Mach 3 radiative shock of Lowrie & Edwards (2008),
in the dimensionless units of [`radhydro_shock`](#radhydro_shock).

Columns are position, density, velocity, matter temperature and radiation
temperature, all as `Vector{Float64}` sorted by `x`. The table is a subsample of
the one shipped with Quokka, generated by `extern/LowrieEdwards/radshock.py`,
kept at full resolution across the Zel'dovich spike.

The solution is derived under the Eddington (P1) approximation, which is why
`radhydro_shock` runs with [`EddingtonClosure`](#EddingtonClosure).

The table is parsed once and cached; a convergence study scoring a dozen runs
against it should not re-read 60 kB of text a dozen times. The returned arrays
are shared, so do not mutate them.

### `brio_wu` {#brio_wu}

Source: [`src/problems/mhd.jl:17`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/mhd.jl#L17)

```julia
brio_wu(; n = 256, gamma = 2, kwargs...) -> (sim, tmax)
```

The MHD shock tube of Brio & Wu (1988) in 1D: `(rho, p, b_y) = (1, 1, 1)` for
`x < 0.5` and `(0.125, 0.1, -1)` for `x > 0.5`, at rest, with `b_x = 0.75` and
`gamma = 2`, to `tmax = 0.1`. The solution has a fast rarefaction, a slow compound
wave, a contact, a slow shock and a fast rarefaction. Quokka's
`MHDBrioWuShockTube`, with outflow boundaries (Quokka holds the initial states),
which make no difference until a fast wave reaches one.

### `smooth_advection` {#smooth_advection}

Source: [`src/problems/hydro.jl:19`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/hydro.jl#L19)

```julia
smooth_advection(; n = 64, amplitude = 0.5, velocity = 1.0, gamma = 5/3, kwargs...)
    -> (sim, tmax)
```

A smooth density perturbation `rho = 1 + A sin(2πx)` advected at constant
velocity and pressure through a periodic box. After `tmax = 1/velocity` the
solution equals the initial condition exactly, which makes this the convergence
test of the code: the L1 error should fall like `dx^p` with `p` set by the
reconstruction.

### `stromgren_iliev` {#stromgren_iliev}

Source: [`src/problems/stromgren.jl:31`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/stromgren.jl#L31)

```julia
stromgren_iliev(; test = 1, n = 32, centered = false, chat_factor = 1e-3,
                solver = RosenbrockChem(), kwargs...) -> (sim, tmax)
```

Test 1 or 2 of the Stromgren-sphere comparison of Iliev et al. (2006): an ionizing point
source switched on in a uniform, static, hydrogen-only medium, run with the network
[`HydrogenIliev1`](#HydrogenIliev1) or [`HydrogenIliev2`](#HydrogenIliev2) and the photon band of
[`Photochemistry`](#Photochemistry). `n` is the number of
cells along each side of the box; `chat_factor` is `chat / c`; `solver` is the chemistry
integrator; the other keywords go to [`Simulation`](#Simulation). `tmax` is 500 Myr, the end of the
paper's runs.

From the paper: the box side `L = 6.6` kpc, the hydrogen density `n_H = 1e-3` cm^-3, the
photon rate `Ndot = 5e48` s^-1, the source in the corner of the box with reflecting walls on
the three low faces (the octant `[0, L]^3` of a sphere about the source), and the two tests
below. Test 1 is monochromatic at 13.6 eV, with the gas held at `1e4` K, the recombination
coefficient `alpha_B = 2.59e-13` cm^3 s^-1 and an initial ionization fraction `1.2e-3`.
Test 2 starts neutral and cold (`100` K), and lets the gas heat and cool. The paper's source
in Test 2 is a `1e5` K blackbody.

Choices that the paper does not make, and that are ours:

  - **One band for Test 2.** The blackbody is replaced by a single band with
    `sigma = 1.63e-18` cm^2 and `photon_energy = 29.65 eV`. These are the project's values
    for the `1e5` K blackbody, the number-weighted mean energy of the ionizing photons and
    their photon-number-averaged cross-section, and not numbers the paper prescribes (a
    cross-section `~ nu^-3` gives 29.6 eV and 1.5e-18 cm^2). Each ionization heats the gas
    by `29.65 - 13.6` eV, Quokka's default. That overheats the gas compared with the real
    spectrum, whose energy-weighted value is about 6.3 eV, so the Test 2 temperature behind
    the front is too high; and the paper prescribes no rates (each code used its own), so
    the result is checked for its shape and not against data. The network has the case B
    `alpha_B(T)`, collisional ionization, and recombination, free-free and Lyman alpha
    cooling (`networks/hydrogen_iliev2`).
  - **Test 1 in the network.** `isothermal = 1e4`, no heating, a constant `alpha_B`, and no
    collisional ionization, which keeps the background ionization at `1.2e-3` instead of
    letting `1e4` K gas ionize itself (`networks/hydrogen_iliev1`).
  - **The photon rate of the octant.** With `centered = false` (the default) the box is the
    paper's octant `[0, L]^3`, with [`Reflecting`](#Reflecting) walls on the low faces and
    [`Outflow`](#Outflow) on the high ones. Emitting `Ndot / 8` into it, so that the full sphere
    would receive `Ndot`, is our choice (it is also Quokka's). `centered = true` is the whole
    sphere in `[-L, L]^3`, `Outflow` everywhere, and `Ndot` emitted, at eight times the cells
    for the same cell size.
  - **The source.** A Gaussian at the origin of width `1.5 dx`, cut at `2.5` widths, whose
    rate is normalised so that the cells receive exactly `Ndot / 8` (or `Ndot`) photons per
    second. The width and the cut are Quokka's (`testStromgrenSphere.cpp`), not the paper's.
  - **The radiation.** One group, zero opacity, `beta_order = 0` and a constant reduced
    speed of light, as a chemistry run requires. The initial radiation energy is zero: the
    default `a_r T^4` would put about `1e12` ionizing photons per cm^3 in the box.

The front is measured by [`ionized_radius`](#ionized_radius) and compared with
[`stromgren_radius_analytic`](#stromgren_radius_analytic) (`chat = c`) or [`stromgren_radius_finite_c`](#stromgren_radius_finite_c) (a
reduced speed of light, an approximate reference). At `n = 16` and `chat_factor = 3e-4` the
Test 1 radius is within 3% of the finite-`chat` reference from 0.5 to 2 recombination times,
and the difference grows as `chat_factor` falls (`test/test_stromgren.jl` has the numbers and
the causes not yet examined).

```julia
sim, tmax = stromgren_iliev(test = 1, n = 32, chat_factor = 3e-4)
run!(sim; tmax = 0.5 / (2.59e-13 * 1e-3))
r = ionized_radius(sim; x0 = 1.2e-3)
```

### `ryu_jones_2a` {#ryu_jones_2a}

Source: [`src/problems/mhd.jl:33`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/mhd.jl#L33)

```julia
ryu_jones_2a(; n = 256, gamma = 5/3, kwargs...) -> (sim, tmax)
```

The shock tube of Ryu & Jones (1995), their Fig. 2a, in 1D, to `tmax = 0.2`: all
seven waves, with
`(rho, p, v, b_y) = (1.08, 0.95, (1.2, 0.01, 0.5), 3.6/sqrt(4 pi))` on the left,
`(1, 1, 0, 4/sqrt(4 pi))` on the right, and `b_x = b_z = 2/sqrt(4 pi)`. Quokka's
`MHDRyuJones2aShockTube`, with outflow boundaries.

### `kelvin_helmholtz` {#kelvin_helmholtz}

Source: [`src/problems/hydro.jl:39`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/hydro.jl#L39)

```julia
kelvin_helmholtz(; n = 256, gamma = 1.4, kwargs...) -> (sim, tmax)
```

The Kelvin-Helmholtz instability in a doubly periodic 2D box, in the smoothly
seeded form of Springel (2010): a dense slab `rho = 2` moving at `vx = +1/2`
between two `rho = 1` layers moving at `vx = -1/2`, perturbed by a single
transverse mode localised on the two shear layers.

### `radiation_diffusion` {#radiation_diffusion}

Source: [`src/problems/radiation.jl:39`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L39)

```julia
radiation_diffusion(; n = 128, kappa = 300.0, sigma0 = 0.05,
                    closure = LevermoreClosure(), beta_order = 0, kwargs...)
    -> (sim, tmax)
```

Static-diffusion limit: a Gaussian pulse of radiation energy in a periodic,
purely scattering medium (`kappa_P = kappa_E = 0`, `kappa_F = kappa`), with the
matter held fixed.

The M1 system reduces to `∂E/∂t = D ∂²E/∂x²` with `D = c/(3 rho kappa)`, so the
pulse stays Gaussian with `sigma² = sigma0² + 2 D t` and its peak falls as
`sigma0/sigma`. This is the test of the scheme's asymptotic-preserving property:
the answer must not depend on how many mean free paths a cell spans.

Note that a reduced speed of light rescales `D` by `chat/c`, so this problem is
set up with `chat = c`.

### `orszag_tang` {#orszag_tang}

Source: [`src/problems/mhd.jl:49`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/mhd.jl#L49)

```julia
orszag_tang(; n = 128, gamma = 5/3, kwargs...) -> (sim, tmax)
```

The Orszag-Tang vortex in a doubly periodic unit square: `rho = 25/(36 pi)`,
`p = 5/(12 pi)`, `v = (-sin 2 pi y, sin 2 pi x)`, `b = (-sin 2 pi y, sin 4 pi x)/sqrt(4 pi)`,
to `tmax = 0.5`, where the shocks have interacted into the usual pattern. Quokka's
`OrszagTang` is the same vortex shifted by half the box. Each field component
varies only across its own direction, so the faces set from it are exactly
divergence-free.

### `interpolate_to` {#interpolate_to}

Source: [`src/problems/exact.jl:50`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/exact.jl#L50)

```julia
interpolate_to(xq, x, y) -> Vector
```

Linear interpolation of the samples `(x, y)`, which must be sorted by `x`, onto
the query points `xq`. Values outside the range of `x` are clamped to the end
points.

### `sedov_blast` {#sedov_blast}

Source: [`src/problems/hydro.jl:62`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/hydro.jl#L62)

```julia
sedov_blast(; n = 64, energy = 1.0, gamma = 5/3, kwargs...) -> (sim, tmax)
```

A Sedov-Taylor point explosion in 3D: `energy` deposited as thermal energy in a
small sphere at the centre of a unit-density, cold, unit box with outflow
boundaries. The blast radius should follow `R(t) = ξ (E t² / rho)^(1/5)` with
`ξ ≈ 1.15` for `gamma = 5/3`.

### `alfven_wave` {#alfven_wave}

Source: [`src/problems/mhd.jl:70`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/mhd.jl#L70)

```julia
alfven_wave(; n = 32, amplitude = 0.1, kwargs...) -> (sim, tmax)
```

The circularly polarised Alfven wave of Toth (2000), an exact nonlinear solution,
travelling obliquely across a 2D periodic box `[0, 2] x [0, 1]` of `(2n, n)`
cells, to `tmax` = one period. The wave vector `k = 2 pi (1/2, 1)` puts one
wavelength `lambda = 2/sqrt(5)` across each side, at `atan 2 = 63.4` degrees to
`x`. Along `k`: `rho = 1`, `p = 0.1`, `b_par = 1`, `v_par = 0`, and across it
`b_perp = A (sin phi, cos phi)` and `v_perp = -b_perp`, with `phi = k . x` and
`A = amplitude`, so the wave moves at `v_A = 1` along `k` and the period is
`lambda`. The uniform `b_par` is set from the keys and the rotating part from a
vector potential, so `div b` starts at round-off. After one period the solution
equals the initial condition, which makes this the convergence test of the MHD
scheme (Gardiner & Stone 2005, Sec. 5.1).

### `diffusion_exact` {#diffusion_exact}

Source: [`src/problems/radiation.jl:71`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L71)

```julia
diffusion_exact(x, t; sigma0 = 0.05, E0 = 1.0, D = 1/900, x0 = 0.5)
```

Analytic solution of [`radiation_diffusion`](#radiation_diffusion): a Gaussian of width
`sigma² = sigma0² + 2 D t` whose integral is conserved.

### `sod_exact` {#sod_exact}

Source: [`src/problems/exact.jl:75`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/exact.jl#L75)

```julia
sod_exact(x, t; rhoL = 1.0, uL = 0.0, pL = 1.0,
                rhoR = 0.125, uR = 0.0, pR = 0.1,
                gamma = 1.4, x0 = 0.5) -> (rho, u, p)
```

Exact solution of the Riemann problem with the given left and right states,
sampled at position `x` and time `t`. The defaults are the standard Sod shock
tube.

The star pressure is found by Newton iteration on the pressure function, then
the solution is sampled along the ray `S = (x - x0)/t`.

### `matter_coupling` {#matter_coupling}

Source: [`src/problems/radiation.jl:82`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L82)

```julia
matter_coupling(; n = 4, kappa = 1e3, T_gas = 1.0, T_rad = 0.1, cv = 1.0, kwargs...)
    -> (sim, tmax)
```

Stiff matter-radiation coupling with no spatial structure: a uniform box whose
gas and radiation start far out of equilibrium and relax towards `a_rad T⁴ =
E_rad` on a timescale `1/(c rho kappa)` that is orders of magnitude shorter than
the transport step.

Passing this test means the implicit solve is doing its job: total energy
`E_int + (c/chat) E_rad` must be conserved to round-off, and the final state
must sit on the equilibrium curve regardless of how large the step is.

The state is uniform, so `n` changes nothing but the number of cells solving the
same problem; it exists so that every problem takes resolution under one name.

### `rad_dust` {#rad_dust}

Source: [`src/problems/radiation.jl:111`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L111)

```julia
rad_dust(; n = 8, groups = GREY, chat_over_c = 0.1, coefficient = 1e6,
         kappa = 1e4, kwargs...) -> (sim, tmax)
```

Gas, dust and radiation in a uniform static medium, from Quokka's `RadDust` and
`RadDustMG` tests: the gas starts at `T = 1` with no radiation, and cools by
colliding with dust that radiates. The radiation couples to the dust only
([`BateKetoDust`](#BateKetoDust)), so the gas cools at the collisional rate
`coefficient n^2 sqrt(T) (T - T_d)` rather than at the radiative one -- here a
hundred times slower -- and the dust temperature sits between the two.

Units and numbers are Quokka's: `c = 1e8`, `chat = 0.1 c`, `rho = 1`,
`a_rad = 1`, `cv = 1.5` (`mu = 1`, `k_B = 1`, `gamma = 5/3`), `rho kappa = 1e4`,
`coefficient = 1e6`, and the radiation time step `0.8 dx / chat = 1e-8` at eight
cells. One difference: Quokka replaces `B = a T^4` by `B = a T` so that its
reference solution is a linear ODE; this code has no hook for the emission law,
so it keeps `a T^4`, and [`rad_dust_reference`](#rad_dust_reference) integrates the model's own
ODE instead.

`groups` other than `GREY` gives the multigroup form (`RadDustMG` uses edges
`1e-3, 0.1, 1, 10, 1e3`); with a constant opacity the answer does not depend on
the grouping, which is the point of that test.

### `ionized_radius` {#ionized_radius}

Source: [`src/problems/stromgren.jl:127`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/stromgren.jl#L127)

```julia
ionized_radius(sim; centered = false, x0 = 0.0)
```

The radius of the ionized region of a [`stromgren_iliev`](#stromgren_iliev) run, `r = (3 V / 4 pi)^(1/3)`,
with `V` the volume of ionized gas, `sum max(x - x0, 0) / (1 - x0) dV` over the cells: the
ionization fraction `x = n_H+ / (n_H0 + n_H+)` counted above the background `x0`, which is the
initial `1.2e-3` of Test 1 and zero for Test 2. It is a volume-weighted radius, not the
position of a front, so a sharp front and a smeared one of the same total give the same
`r`. With `centered = false` the grid is the octant and `V` is multiplied by 8.

### `rad_dust_reference` {#rad_dust_reference}

Source: [`src/problems/radiation.jl:150`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L150)

```julia
rad_dust_reference(ts; groups = GREY, chat_over_c = 0.1, coefficient = 1e6,
                   kappa = 1e4) -> (T_gas, E_rad)
```

The error-controlled solution of [`rad_dust`](#rad_dust) at the times `ts`: the gas
temperature and the total radiation energy density. The model's ODE -- `E_gas`
and the `E_g` evolved, `T_d` solved at every evaluation from the dust balance --
integrated with `Rodas5P` at `reltol = 1e-10`. With a constant opacity the dust
balance is monotone in `T_d`, so that inner solve has one root and a bracket.

### `stromgren_radius_analytic` {#stromgren_radius_analytic}

Source: [`src/problems/stromgren.jl:153`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/stromgren.jl#L153)

```julia
stromgren_radius_analytic(t; Ndot = 5e48, n = 1e-3, alpha_B = 2.59e-13)
```

The radius of the ionized sphere of a point source in a uniform neutral medium, at the speed
of light, with the recombination of Test 1 of Iliev et al. (2006): `r_I = r_S (1 - exp(-t /
t_rec))^(1/3)`, with the Stromgren radius `r_S = (3 Ndot / 4 pi alpha_B n^2)^(1/3)` (5.39 kpc
for the defaults) and the recombination time `t_rec = 1 / (alpha_B n)` (122.3 Myr). `t` is in
seconds and the radius in cm. This is the paper's equation for the front of Test 1, which
holds when the front is much slower than light.

### `stromgren_radius_finite_c` {#stromgren_radius_finite_c}

Source: [`src/problems/stromgren.jl:169`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/stromgren.jl#L169)

```julia
stromgren_radius_finite_c(t; chat, Ndot = 5e48, n = 1e-3, alpha_B = 2.59e-13)
```

The radius of the ionized sphere at time `t` when the radiation travels at the speed `chat`,
from the front equation of Shapiro et al. (2006),

    dR/dt = (Ndot - 4 pi R^3 alpha_B n^2 / 3) / (Ndot / chat + 4 pi R^2 n),

which is approximate: its term `Ndot / chat` counts the photons in flight as `Ndot R / chat`
and ignores how many of them recombinations inside `R` have used up. It is integrated from `R = 0` with fourth-order Runge-Kutta. It starts with 256 steps and doubles
the number of steps until two successive radii differ by less than `1e-6` of the result, as
the `integrate_radius` of Quokka's `testStromgrenSphere.cpp` does, and throws an error if
that has not happened after 12 doublings. With `chat` the speed of light it approaches
[`stromgren_radius_analytic`](#stromgren_radius_analytic), and it is the reference of Shapiro et al. (2006) for a
run with a reduced speed of light, which [`stromgren_iliev`](#stromgren_iliev) reduces in the photon
equation while it keeps the chemistry unchanged. `t` is in seconds and the radius in cm.

### `marshak_wave` {#marshak_wave}

Source: [`src/problems/radiation.jl:189`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L189)

```julia
marshak_wave(; n = 256, kappa = 300.0, T_wall = 1.0, cv = 1.0,
             closure = LevermoreClosure(), beta_order = 0, kwargs...)
    -> (sim, tmax)
```

A non-equilibrium Marshak wave: a cold, static, optically thick slab heated from
`x = 0` by a wall held in radiative equilibrium at `T_wall`. Radiation diffuses
inward and drags the matter temperature behind it, so the gas and radiation
temperatures separate at the front and merge behind it.

The wall is imposed as a Dirichlet condition on the radiation moments,
`E = a_rad T_wall⁴` with zero flux; the HLL solver then supplies the inward flux
set by the jump across the boundary.

### `radhydro_shock` {#radhydro_shock}

Source: [`src/problems/radiation.jl:224`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L224)

```julia
radhydro_shock(; n = 256, closure = EddingtonClosure(), beta_order = 1,
               chat_factor = 10.0, chat_limiter = ConstantChat(),
               kwargs...) -> (sim, tmax)
```

The Mach 3 radiative shock of Lowrie & Edwards (2008), in the form used by
Quokka's `RadhydroShock` test. This is the most demanding one-dimensional
radiation-hydrodynamics problem here: every part of the scheme has to be right
at once.

A Mach 3 shock sits in a medium that is optically thick (about nine mean free
paths across the domain) and strongly coupled, so the radiation both preheats
the gas ahead of the shock -- the radiative precursor -- and, immediately behind
the front, leaves the matter temperature briefly *above* its downstream value.
That overshoot is the Zel'dovich spike, `T_matter` reaching 4.26 against a
downstream 3.66, and it is what the test is really for: it only appears if the
velocity-dependent coupling terms, the implicit solve and the shock capturing
are all correct together.

Everything is in the dimensionless units of the reference solution: `c_s0 = 1`
upstream, `T = 1` upstream, `rho = 1` upstream, `a_rad = 1e-4`, absorption cross
section `1e6`, so that `c = sqrt(3 sigma_a) = 1732`. The reduced speed of light
is `10 (v_0 + c_s0) = 40`.

Both ends are held at the upstream and downstream Rankine-Hugoniot states, and
the shock is initialised slightly left of where it settles, because it drifts a
little during the run.

Runs with [`EddingtonClosure`](#EddingtonClosure) rather than M1, to match the assumption the
semi-analytic solution is derived under -- exactly as Quokka overrides
`ComputeEddingtonFactor` for this problem. Pass `closure = LevermoreClosure()`
to measure what that assumption costs; the difference is the closure error, not
a scheme error. `chat_factor` scales the reduced speed of light, whose default
of `10 (v_0 + c_s0)` is Quokka's -- and which is already a fairly aggressive
reduction, `phi0 = chat/c = 0.023`. `chat_factor = 433` recovers `chat = c` and
is the reference a `chat_limiter` should be scored against.

Compare against [`radhydro_shock_exact`](#radhydro_shock_exact); `tmax` is three shock-crossing
times.

### `radhydro_shock_super` {#radhydro_shock_super}

Source: [`src/problems/radiation.jl:279`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L279)

```julia
radhydro_shock_super(; n = 128, chat_over_c = 0.025, closure = EddingtonClosure(),
                     beta_order = 1, chat_limiter = ConstantChat(), kwargs...)
    -> (sim, tmax)
```

The Mach 5 *supercritical* radiative shock of Lowrie & Edwards (2008), in the
form of Quokka's `RadhydroShockSuper` test: the same dimensionless units and
opacity as [`radhydro_shock`](#radhydro_shock), downstream state `rho = 3.5979`,
`T = 8.5572`, on `x in [-0.04, 0.01]` with the shock initially at `x = 0`.

Supercritical means the radiative precursor heats the upstream gas to nearly the
downstream temperature, and that makes it the problem most sensitive to the RSLA:
the strong exchange in the precursor amplifies the RSLA's energy error. Quokka's
default reduction for it is `chat/c = 0.025`. `chat_over_c = 1` is the reference
a limiter should be scored against; `tmax` is three shock-crossing times.

### `radiation_shadow` {#radiation_shadow}

Source: [`src/problems/radiation.jl:352`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L352)

```julia
radiation_shadow(; n = (280, 112), kappa = 1.0, rho_blob = 1e3,
                 closure = LevermoreClosure(), beta_order = 0, kwargs...)
    -> (sim, tmax)
```

The shadow test of Hayes & Norman (2003) in 2D: a collimated beam enters from
the left of a transparent box and strikes an opaque, absorbing elliptical clump
of semi-axes `(0.10, 0.06)` centred at `x = 0.25`.

`n` may be the pair of cell counts or a single number, which is taken as the `x`
resolution and gives `ny = 2 nx / 5` -- the ratio that makes cells square on
this `1 x 0.4` domain, and the one the default `(280, 112)` already has.

A two-moment scheme with the M1 closure preserves the direction of the
radiation and leaves a sharp shadow behind the clump; a diffusion-based scheme
lets radiation leak around the obstacle and fills the shadow in. Far downstream
M1 does fill the shadow in slowly, because it carries a single flux vector per
cell and so cannot represent the two crossing beams that meet there.

The clump is given a very large heat capacity so that it absorbs without
re-emitting, which isolates the transport.

### `marshak_vaytet` {#marshak_vaytet}

Source: [`src/problems/radiation.jl:403`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L403)

```julia
marshak_vaytet(; n = 64, ngroups = 4, Lx = 20.0, chat_over_c = 1.0,
               chat_limiter = ConstantChat(), coupling = QuokkaCoupling(),
               closure = LevermoreClosure(), kwargs...) -> (sim, tmax)
```

The frequency-dependent Marshak wave of Vaytet et al. (2011), in the form of
Quokka's `RadMarshakVaytet` test: a cold slab of `rho = 10⁻³ g cm⁻³` at 300 K,
heated from `x = 0` by a wall in radiative equilibrium at `T_L = 1000 K`, with
an opacity that falls as `nu⁻²`.

This is the multigroup counterpart of [`marshak_wave`](#marshak_wave), and it is here
because the two disagree: with `kappa = 2000 (nu / 4×10¹³ Hz)⁻² cm² g⁻¹` the
groups span four decades of optical depth at once — a mean free path of 10⁻⁵ cm
in the lowest group and 10 cm in the highest — so the high-frequency groups run
ahead of the wave while the low-frequency ones are trapped in it. A grey
calculation, which has one opacity to describe all of that, cannot reproduce the
front. The number of groups is the convergence parameter of the test, hence
`ngroups`: its edges are always logarithmically spaced from `6×10¹⁰` to
`6×10¹⁴ Hz`, which reproduces Quokka's tabulated edges exactly at every group
count it lists (4 gives `6e10, 6e11, 6e12, 6e13, 6e14`).

Everything is CGS, the medium is static (`hydro = false`, `beta_order = 0`) and
`chat = c` unless `chat_over_c` says otherwise. This problem is genuinely
time-dependent, so the answer *does* depend on the reduced speed of light: it is
the one here that measures what a `chat_limiter` buys. The opacity is piecewise constant across a group, evaluated at the
group's geometric centre, which is Quokka's `piecewise_constant_opacity` model.

The domain length is a keyword because the choice matters and Quokka keeps it in
an inputs file rather than in the problem source. `Lx = 20 cm` is the value that
file uses, and it is the right one: at `tmax = 1.36×10⁻⁷ s` and 64 cells the
thermal front (`T_gas = 650 K`, half way from 300 K to the wall) sits at about
3.8 cm, so the wave itself is comfortably inside. What does reach the far
boundary is the top group, whose mean free path is 11 cm: it is optically thin,
it streams across the slab, and it has warmed the far end to about 370 K by
`tmax`. That is the physics the test exists to show, not an error, and it is why
the far boundary is outflow rather than a cold wall — a shorter `Lx` would
simply move the outflow closer, while a longer one costs proportionally more
steps for no extra physics.

Has a [`default_metrics`](#default_metrics) method: the front position and the near-wall
radiation temperature.

### `total_erad` {#total_erad}

Source: [`src/problems/radiation.jl:502`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L502)

```julia
total_erad(sim) -> Array
```

Radiation energy density summed over every frequency group, over the interior.

Redundant, and kept only because `default_metrics(marshak_vaytet)` and
`test/test_radiation_multigroup.jl` call it: `first(field(sim, :Erad))` sums the
groups too and returns the identical array, as does
[`radiation_temperature`](#radiation_temperature) for the temperature it implies. Prefer the
accessors in new code — this dates from before they learned about groups.

### `radhydro_pulse_dyn` {#radhydro_pulse_dyn}

Source: [`src/problems/radiation.jl:524`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/radiation.jl#L524)

```julia
radhydro_pulse_dyn(; n = 128, chat_over_c = 1.0, v0 = 3e7, kappa0 = 500.0,
                   chat_limiter = ConstantChat(), kwargs...) -> (sim, tmax)
```

The advecting radiation pulse in the dynamic diffusion limit of He, Wibking &
Krumholz (2024a), in the form of Quokka's `RadhydroPulseDyn` test, in CGS: a
Gaussian temperature pulse, `T` from `1e7` to `2e7` K over a width of 24 cm, in
pressure balance between gas and radiation, carried by a uniform flow of
`v0 = 3e7` cm/s through a periodic box 1024 cm wide. The opacity is `500 cm² g⁻¹`
at `rho ≈ 1.2 g cm⁻³`, so a cell is thousands of mean free paths thick and the
optical depth of the pulse times `v0/c` is about ten: the radiation is carried
with the gas rather than diffusing through it.

This is the regime in which Wibking & Krumholz (2022) show the RSLA makes
order-unity errors whatever `chat` is, and it is radiation-rich -- radiation
holds about a third of the heat capacity -- which is the regime in which the
stability bound caps `phi` at the RSLA step (see [`StabilityBound`](#StabilityBound)).
`chat_over_c = 1` is the reference; `tmax = 4.8e-6` s moves the pulse by 144 cm.

## Internals

### `Honghu.Problems` {#Honghu-Problems}

Source: [`src/problems/Problems.jl:1`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/Problems.jl#L1)

```julia
Honghu.Problems
```

Ready-made test problems. Each function returns a fully initialised
[`Simulation`](#Simulation) together with a suggested `tmax`, so that a complete run is

```julia
sim, tmax = Honghu.Problems.sod_shock_tube(nx = 512)
run!(sim; tmax)
```

The hydrodynamic problems are the standard verification suite (Sod, smooth
advection, Kelvin-Helmholtz, Sedov); the radiation problems exercise each limit
of the two-moment system in turn: free streaming, static diffusion, stiff
matter coupling, dust-gas coupling, a Marshak wave, a shadow, and the Mach 3 radiative shock.
The photoionization problem is the Stromgren sphere of Iliev et al. (2006), Tests 1 and 2.
The MHD problems are the Brio-Wu and Ryu-Jones 2a shock tubes, the Orszag-Tang
vortex and an oblique circularly polarised Alfven wave.

#### Varying a problem

Every factory forwards unrecognised keywords to [`Simulation`](#Simulation), so the
numerical choices are already free:

```julia
sod_shock_tube(nx = 512, reconstruction = PLM(), integrator = SSPRK2())
```

The *physics* inside a radiation problem is not reachable that way, because the
factory builds its own [`RadiationPhysics`](#RadiationPhysics) from constants that only exist
in its body. Overriding the whole object means re-deriving those constants and
getting a running simulation with different physics if you get one wrong. The
knobs worth varying are therefore named keywords in their own right --
`closure`, `beta_order`, and `chat_factor` on `radhydro_shock`:

```julia
radhydro_shock(nx = 256, closure = LevermoreClosure())   # M1 instead of P1
```

which is also the shape [`compare`](#compare) expects: one flat `NamedTuple` per
variant, splatted into the factory.

### `Honghu.default_metrics` {#Honghu-default_metrics}

Source: [`src/problems/metrics.jl:13`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/metrics.jl#L13)

```julia
default_metrics(sod_shock_tube)
```

`l1_density` against the exact Riemann solution at the final time.

Source: [`src/problems/metrics.jl:27`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/metrics.jl#L27)

```julia
default_metrics(smooth_advection)
```

`l1_density` against the initial profile, which the exact solution returns to
after a whole number of periods. This is the problem the order-of-accuracy
measurements use, so the metric is the one whose slope is the convergence rate.

Source: [`src/problems/metrics.jl:41`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/metrics.jl#L41)

```julia
default_metrics(radiation_diffusion)
```

`l1_Erad` against the analytic Gaussian `sigma² = sigma0² + 2Dt`.

Source: [`src/problems/metrics.jl:56`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/metrics.jl#L56)

```julia
default_metrics(radiation_streaming)
```

`front_error`, the relative error in the position of the radiation front, which
must travel at exactly `chat`.

Source: [`src/problems/metrics.jl:72`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/metrics.jl#L72)

```julia
default_metrics(radhydro_shock)
```

Quokka's own pair for this test:

  - `l1_Trad`, the relative `L1` error in the radiation temperature, with the
    numerical profile interpolated onto the reference abscissae. Quokka's pass
    threshold is 1% at 256 cells.
  - `spike`, the peak matter temperature. The Zel'dovich spike is the feature
    the test exists for and an error norm alone would pass a solution with no
    spike at all; the reference value is 4.2618.

Source: [`src/problems/metrics.jl:93`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/metrics.jl#L93)

```julia
default_metrics(sedov_blast)
```

`radius_error`, the relative error in the shock radius against the
Sedov-Taylor similarity radius `xi (E t²/rho)^(1/5)` with `xi = 1.15` for
`gamma = 5/3`.

Source: [`src/problems/metrics.jl:110`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/problems/metrics.jl#L110)

```julia
default_metrics(marshak_vaytet)
```

Two diagnostics rather than errors, because this problem has no closed-form
solution -- the same shape as `radhydro_shock`'s `spike`:

  - `front`, the position of the `T_gas = 650 K` contour, linearly interpolated
    between the bracketing cells so that the number converges under refinement
    instead of stepping by `dx`. It is what a group-count study measures: more
    groups resolve more of the `nu^-2` opacity range, and the front moves.
  - `Trad_wall`, the radiation temperature of the cell against the wall, summed
    over the groups. It must sit just below `T_L = 1000 K`; if it does not, the
    Dirichlet boundary is not driving the wave.



---

<!-- page: reference/utilities.md -->

# Utilities and constants

Docstrings from `src/staticvec.jl`, `src/constants.jl`.

## Exported

### `CGS.c_light` {#CGS-c_light}

Source: [`src/constants.jl:12`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L12)

Speed of light [cm s⁻¹]

### `CGS.k_B` {#CGS-k_B}

Source: [`src/constants.jl:14`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L14)

Boltzmann constant [erg K⁻¹]

### `CGS.m_u` {#CGS-m_u}

Source: [`src/constants.jl:16`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L16)

Atomic mass unit [g]

### `CGS.m_H` {#CGS-m_H}

Source: [`src/constants.jl:18`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L18)

Hydrogen mass [g]

### `CGS.h_planck` {#CGS-h_planck}

Source: [`src/constants.jl:20`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L20)

Planck constant [erg s]

### `CGS.sigma_SB` {#CGS-sigma_SB}

Source: [`src/constants.jl:22`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L22)

Stefan-Boltzmann constant [erg cm⁻² s⁻¹ K⁻⁴]

### `CGS.a_rad` {#CGS-a_rad}

Source: [`src/constants.jl:24`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L24)

Radiation constant a_r = 4σ/c [erg cm⁻³ K⁻⁴]

### `CGS.G_grav` {#CGS-G_grav}

Source: [`src/constants.jl:26`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L26)

Gravitational constant [cm³ g⁻¹ s⁻²]

### `CGS.M_sun` {#CGS-M_sun}

Source: [`src/constants.jl:28`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L28)

Solar mass [g]

### `CGS.parsec` {#CGS-parsec}

Source: [`src/constants.jl:30`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L30)

Parsec [cm]

### `CGS.au` {#CGS-au}

Source: [`src/constants.jl:32`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L32)

Astronomical unit [cm]

### `CGS.year` {#CGS-year}

Source: [`src/constants.jl:34`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L34)

Year [s]

### `CGS.eV` {#CGS-eV}

Source: [`src/constants.jl:36`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L36)

Electron volt [erg]

## Internals

### `Honghu.CGS` {#Honghu-CGS}

Source: [`src/constants.jl:1`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/constants.jl#L1)

```julia
Honghu.CGS
```

Physical constants in CGS units (2018 CODATA where applicable).

Honghu is unit-agnostic: every physical parameter (`RadiationPhysics.c`,
`IdealGas.cv`, opacities, ...) is supplied by the user. Use these when you want
to run in CGS; use your own numbers when you want code units.

### `SVec` {#SVec}

Source: [`src/staticvec.jl:7`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/staticvec.jl#L7)

```julia
SVec{N,T}
```

Immutable, stack-allocated vector of `N` elements of type `T`.

Supports the arithmetic used by the Riemann solvers: `+`, `-`, scalar `*` and
`/`, indexing, and iteration. Deliberately *not* an `AbstractArray`, so that a
stray broadcast cannot silently allocate a heap array in a hot loop.

```julia
julia> Honghu.SVec(1.0, 2.0) + Honghu.SVec(3.0, 4.0)
SVec{2, Float64}(4.0, 6.0)
```

### `sumvec` {#sumvec}

Source: [`src/staticvec.jl:56`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/staticvec.jl#L56)

```julia
sumvec(a::SVec)
```

Sum of the components. Named to avoid extending `Base.sum`, which would invite
the generic iterator machinery into a hot loop.

### `maxabs` {#maxabs}

Source: [`src/staticvec.jl:64`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/staticvec.jl#L64)

```julia
maxabs(a::SVec)
```

Largest absolute component, for convergence tests on a group vector.

### `dot` {#dot}

Source: [`src/staticvec.jl:71`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/staticvec.jl#L71)

```julia
dot(a::SVec, b::SVec)
```

Euclidean inner product. (Local to Honghu; not `LinearAlgebra.dot`.)

### `norm` {#norm}

Source: [`src/staticvec.jl:78`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/staticvec.jl#L78)

```julia
norm(a::SVec)
```

Euclidean 2-norm.



---

<!-- page: photochemistry.md -->

# Photochemistry

The photochemistry module evolves the ionization state and temperature of hydrogen gas lit by ionizing photons. It follows the ATON scheme of Aubert & Teyssier (2008) in the on-the-spot approximation, as Quokka's photoionization module does, and its benchmark is the Stromgren-sphere comparison of Iliev et al. (2006). This page gives the equations and the numerical method. The functions and types are documented on the reference page [Photoionization chemistry](reference/chemistry.md), and the cost and accuracy are measured in [the findings note](photoionization-findings.md).

## 1. Governing equations

### 1.1 Gas and species

The gas obeys the Euler equations with a heating $\mathcal H$ and a cooling $\Lambda$, and carries the mass density $\rho X_s$ of each species $s$:

$$\begin{aligned}
\frac{\partial\rho}{\partial t} + \nabla\cdot(\rho\mathbf v) &= 0 , \\
\frac{\partial(\rho\mathbf v)}{\partial t} + \nabla\cdot(\rho\mathbf v\mathbf v + p\,\mathsf I) &= 0 , \\
\frac{\partial E}{\partial t} + \nabla\cdot\left[(E + p)\,\mathbf v\right] &= \mathcal H - \Lambda , \\
\frac{\partial(\rho X_s)}{\partial t} + \nabla\cdot(\rho X_s\mathbf v) &= m_s\,\mathcal R_s ,
\end{aligned}$$

with $E = e + \rho v^2/2$, $e$ the internal energy density, $m_s$ the particle mass and $\mathcal R_s$ the net creation rate of species $s$ per unit volume. The species are H$^0$, H$^+$ and electrons, so $n_s = \rho X_s/m_s$ and $\sum_s n_s m_s = \rho$. Every reaction conserves charge, so $n_e = n_{\rm H^+}$. The radiation exerts no force on the gas.

The gas is monatomic, $p = (\gamma - 1)\,e$ with $\gamma = 5/3$, and its temperature counts every particle:

$$e = \frac32\,k_B\,(n_{\rm H^0} + n_{\rm H^+} + n_e)\,T .$$

At fixed $e$, ionizing the gas halves its temperature.

### 1.2 Ionizing photons

The photon number density $N_\gamma$ and flux $\mathbf F_\gamma$ of the ionizing band obey the first two moments of the transfer equation:

$$\begin{aligned}
\frac{\partial N_\gamma}{\partial t} + \phi\,\nabla\cdot\mathbf F_\gamma &= \phi\,\dot N_\gamma - \hat c\,\sigma\,n_{\rm H^0} N_\gamma , \\
\frac{\partial \mathbf F_\gamma}{\partial t} + \hat c\,c\,\nabla\cdot\mathsf P_\gamma &= -\hat c\,\sigma\,n_{\rm H^0}\,\mathbf F_\gamma .
\end{aligned}$$

| Symbol | Definition |
|:---|:---|
| $N_\gamma$, $\mathbf F_\gamma$ | photon number density (cm$^{-3}$) and number flux (cm$^{-2}$ s$^{-1}$) |
| $\mathsf P_\gamma = \mathsf D\,N_\gamma$ | photon pressure tensor, with $\mathsf D$ the Eddington tensor of the M1 closure (Levermore 1984) |
| $\sigma$ | photoionization cross-section, averaged over the band (cm$^2$) |
| $\dot N_\gamma$ | photons emitted by sources (cm$^{-3}$ s$^{-1}$) |
| $\hat c = \phi\,c$ | the reduced speed of light (section 1.6); $\phi = 1$ gives the physical equations |

The band is one frequency group of the M1 radiation, with energy density $E_\gamma = \varepsilon N_\gamma$. Two numbers stand for its spectrum: $\sigma$ and the mean photon energy $\varepsilon$. Iliev's Test 1 is monochromatic at 13.6 eV, with $\sigma = 6.3\times10^{-18}$ cm$^2$. Test 2 is a $10^5$ K blackbody, represented by $\varepsilon = 29.65$ eV and $\sigma = 1.63\times10^{-18}$ cm$^2$, the number-weighted mean photon energy and cross-section. The gas emits no ionizing photons, so the band has no thermal coupling.

### 1.3 Hydrogen chemistry

Photoionization, collisional ionization and recombination give

$$\mathcal R_{\rm H^+} = -\mathcal R_{\rm H^0} = \Gamma\,n_{\rm H^0} + \beta\,n_e n_{\rm H^0} - \alpha_B\,n_e n_{\rm H^+} ,$$

with $\Gamma = c\,\sigma\,N_\gamma$ the photoionization rate per atom and, in CGS units,

| Process | Coefficient (cm$^3$ s$^{-1}$) | Source |
|:---|:---|:---|
| Case B recombination | $\alpha_B = 2.63\times10^{-13}\,(T/10^4\,{\rm K})^{-0.7}$ | Quokka |
| Collisional ionization | $\beta = 5.84\times10^{-11}\,\sqrt{T}\,e^{-\chi_{\rm H}/k_B T}$ | Krumholz et al. (2007) |

with $\chi_{\rm H} = 13.6$ eV. Iliev's Test 1 uses a constant $\alpha_B = 2.59\times10^{-13}$ cm$^3$ s$^{-1}$.

### 1.4 Heating and cooling

Each photoionization deposits a heating energy $\varepsilon_{\rm heat}$, so $\mathcal H = \varepsilon_{\rm heat}\,\Gamma\,n_{\rm H^0}$. The cooling is

$$\Lambda = \chi_{\rm H}\,\beta\,n_e n_{\rm H^0} + (\Lambda_{\rm rec} + \Lambda_{\rm ff})\,n_e n_{\rm H^+} + \Lambda_{\rm ce}\,n_e n_{\rm H^0} ,$$

| Process | Coefficient (erg cm$^3$ s$^{-1}$) | Source |
|:---|:---|:---|
| Collisional ionization | $\chi_{\rm H}\,\beta$ | |
| Recombination | $\Lambda_{\rm rec} = 6.1\times10^{-10}\,k_B\,T^{0.11}$ for $T \geq 100$ K, zero below | Krumholz et al. (2007) |
| Free-free | $\Lambda_{\rm ff} = 1.3\times1.427\times10^{-27}\,\sqrt T$ | Quokka |
| Ly$\alpha$ excitation | $\Lambda_{\rm ce} = 7.5\times10^{-19}\,e^{-118348\,{\rm K}/T}/(1 + \sqrt{T/10^5\,{\rm K}})$ | Cen (1992); Katz et al. (1996) |

These are Quokka's processes for hydrogen, without its metal-line and neutral-ISM terms, plus the Ly$\alpha$ cooling.

Test 2 uses $\varepsilon_{\rm heat} = \varepsilon - \chi_{\rm H}$ (16.05 eV, as in Quokka), which is too large for a broad spectrum. Because $\sigma$ falls steeply with frequency, the low-energy photons do most of the ionizing, and the optically thin value is $\langle\varepsilon\rangle\,\sigma_E/\sigma_N - \chi_{\rm H} \approx 6.3$ eV for a $10^5$ K blackbody. One band cannot get both the ionization and the heating right. The effect on Test 2 is small: the ionized gas is about 10% hotter ([findings, section 4](photoionization-findings.md#the-overheating-of-test-2)).

For Iliev's Test 1 the energy equation is replaced by a fixed temperature, $T = 10^4$ K.

### 1.5 The on-the-spot approximation

A recombination to the ground state emits an ionizing photon. In the on-the-spot approximation that photon is absorbed nearby, so the two events cancel: the recombination coefficient is the case B one, and the diffuse recombination radiation, $n_e n_{\rm H^+}(\alpha_A - \alpha_B)$ in Quokka's note, is dropped. This is good deep inside an H II region and poor near the front and in diffuse ionized gas.

### 1.6 The reduced speed of light

Light crosses an H II region in about $10^4$ years while the region evolves over hundreds of Myr. The reduced speed of light approximation (RSLA; Gnedin & Abel 2001) transports the photons at $\hat c = \phi\,c$, which lengthens the transport step by $1/\phi$. In the equations of section 1.2, $\phi$ multiplies the time derivative of the radiation and nothing on the gas side, so:

- **steady states are physical:** where $\partial_t = 0$, $\phi$ drops out, and the ionization equilibrium does not depend on $\hat c$;
- **the band loses photons at $\hat c\,\sigma n_{\rm H^0} N_\gamma$, the gas ionizes at $c\,\sigma n_{\rm H^0} N_\gamma$,** and sources add $\phi\,\dot N_\gamma$;
- **the photon budget $n_{\rm H^+} + N_\gamma/\phi$ is conserved.**

Quokka writes the same scheme in $N_Q = N_\gamma/\phi$, with unscaled sources and $\hat c$ in both rates.

The RSLA is accurate when $\hat c$ exceeds the speed of the ionization front (section 1.8). Early on the front is faster than any affordable $\hat c$ and is held back by it ([findings, section 3](photoionization-findings.md#the-reduced-speed-of-light-on-test-1)).

### 1.7 Conservation laws

The chemistry conserves hydrogen nuclei and charge. With photoionization alone and $\varepsilon_{\rm heat} = \varepsilon - \chi_{\rm H}$, the local equations also conserve the photon budget and the energy,

$$n_{\rm H^+} + \frac{N_\gamma}{\phi} , \qquad e + \chi_{\rm H}\,n_{\rm H^+} + \varepsilon\,\frac{N_\gamma}{\phi} ,$$

each photon's energy going to the ionization potential and to heat. Both are linear in the unknowns, so the integrators preserve them to round-off, which makes them exact tests.

### 1.8 A reference solution: the H II region

A source of $\dot N$ ionizing photons per second in uniform hydrogen ionizes a sphere that stops growing when recombinations inside it use up all the photons, at the Stromgren radius

$$r_S = \left(\frac{3\dot N}{4\pi\,\alpha_B\,n_{\rm H}^2}\right)^{1/3} .$$

For a sharp front and an infinite speed of light, the radius and speed of the front are

$$r_I = r_S\left(1 - e^{-t/t_{\rm rec}}\right)^{1/3} , \qquad v_I = \frac{r_S}{3t_{\rm rec}}\,e^{-t/t_{\rm rec}}\left(1 - e^{-t/t_{\rm rec}}\right)^{-2/3} , \qquad t_{\rm rec} = \frac{1}{\alpha_B\,n_{\rm H}} .$$

For Iliev's Test 1 ($\dot N = 5\times10^{48}$ s$^{-1}$, $n_{\rm H} = 10^{-3}$ cm$^{-3}$), $r_S = 5.39$ kpc and $t_{\rm rec} = 122.3$ Myr, and the front moves at about 70, 30 and 9 km s$^{-1}$ at 10, 30 and 100 Myr. At a finite $\hat c$, Shapiro et al. (2006) add the photons in flight to the budget:

$$\frac{dR}{dt} = \frac{\dot N - \tfrac{4\pi}{3}R^3\alpha_B n_{\rm H}^2}{\dot N/\hat c + 4\pi R^2 n_{\rm H}} .$$

This is approximate, since it ignores recombinations among the photons in flight. Both solutions are in `Honghu.Problems` ([`stromgren_radius_analytic`](#stromgren_radius_analytic), [`stromgren_radius_finite_c`](#stromgren_radius_finite_c)), with the Iliev tests ([`stromgren_iliev`](#stromgren_iliev)).

## 2. Numerical method

### 2.1 Operator splitting

The equations split into hydrodynamics $\mathcal H$ (with the advection of the species), radiation transport $\mathcal T$, and the local source terms $\mathcal C$ (chemistry, heating and cooling, absorption and emission). One step is

$$U^{n+1} = \Big[\mathcal C_{\Delta t_r}\,\mathcal T_{\Delta t_r}\Big]^{n_{\rm sub}}\,\mathcal H_{\Delta t}\,U^n , \qquad \Delta t_r = \Delta t/n_{\rm sub} ,$$

where the radiation subcycles because its Courant step, $\Delta t_r \propto \Delta x/\hat c$, is much shorter than the hydrodynamic one. Within a substep the photons are transported first and the chemistry then acts over the whole substep, as in ATON and Quokka. The transport operators are those of Honghu's hydrodynamics and radiation transport. This Lie splitting is first order in time.

The emission enters $\mathcal C$ as photons added at the start of the substep. In an opaque cell the gas then ionizes early and recombines for the rest of the substep, which biases the ionization equilibrium low by about $\alpha_B n_{\rm H} x^2\Delta t_r/2$, with $x = n_{\rm H^+}/n_{\rm H}$. In a uniform test with $x = 0.5$ exact, this gave 0.4939 at $\Delta t_r = 0.05\,t_{\rm rec}$ and 0.4450 at $0.5\,t_{\rm rec}$ ([findings, section 5](photoionization-findings.md#two-choices-in-the-scheme-that-the-results-depend-on)). Strang-split or in-ODE emission would remove the bias; neither is implemented. Since $\Delta t_r \propto 1/\hat c$, a smaller $\hat c$ makes the bias larger and the local problem stiffer.

### 2.2 Advection of the species

The flux of each species is the mass flux from the hydrodynamic Riemann solver times the upwind mass fraction:

$$F_{\rho X_s} = F_\rho\,X_s^{\rm upwind} , \qquad X_s^{\rm upwind} = \frac{(\rho X_s)_{\rm face}}{\rho_{\rm face}}\ \text{on the upwind side} .$$

A uniform $X_s$ is then advected exactly. For HLLC this equals Quokka's flux; for local Lax-Friedrichs it is less diffusive. Because each $\rho X_s$ is reconstructed and limited separately, the species fluxes do not add up to the mass flux, and $\sum_s X_s$ drifts from one at second and third order. The species are therefore rescaled to $\sum_s \rho X_s = \rho$ in every cell, at every Runge-Kutta stage and before the chemistry, as Quokka does. This conserves total mass but not each species. Consistent multi-fluid advection (CMA; Plewa & Müller 1999) would conserve each species, and is not implemented.

### 2.3 The local problem: an error-controlled Rosenbrock integrator

In each cell, $\mathcal C$ integrates the stiff system

$$\frac{\mathrm du}{\mathrm dt} = S(u) , \qquad u = (n_{\rm H^0},\, n_{\rm H^+},\, n_e,\, e,\, N,\, f) ,$$

with $S$ the source terms of sections 1.1–1.4 and the photon loss. The photons are stored as $N = N_\gamma/\phi$, Quokka's $N_Q$, so that both rates read $\hat c N$: the gas ionizes at $\hat c\,\sigma n_{\rm H^0} N = c\,\sigma n_{\rm H^0} N_\gamma$, and $N$ loses the same number. The last unknown, $f$, is the factor by which absorption has attenuated the band's flux, $\mathrm df/\mathrm dt = -\hat c\,\sigma\,n_{\rm H^0} f$ from $f = 1$. Every flux component obeys this linear equation, so one factor carries all three; without emission inside $S$ it equals $N^{\rm end}/N^{\rm start}$, Quokka's `SKIP_PHOTOCHEMFLUX`.

The default integrator is `Rosenbrock23` from OrdinaryDiffEq, the method of MATLAB's `ode23s` (Shampine & Reichelt 1997): a linearly implicit, second-order Rosenbrock-W method with an embedded third-order error estimate. Each internal step solves linear systems with $I - \gamma h J$, $J = \partial S/\partial u$, instead of iterating Newton's method, and the step size is adapted to keep the error estimate below $a_i + r\,|u_i|$ for each unknown. So each cell takes the internal steps it needs, and the error is controlled rather than assumed.

The relative tolerance is $r = 10^{-2}$. The absolute tolerances are $10^{-8}$ of a physical scale of each unknown: the total particle density for the species and for $N$ (one photon per particle in the budget of section 1.6), the cell's internal energy for $e$, and 1 for $f$. A tolerance then means the same in every cell and unit system. The Jacobian is exact and analytic, including the temperature dependence of every rate. Negative densities enter the rates as zero, so a trial state slightly below zero cannot create atoms. On the Iliev tests this takes about 15 internal steps and 5–6.5 µs per cell per substep, with no failures ([findings, section 1](photoionization-findings.md#cost-of-the-chemistry-step)).

### 2.4 The alternative: one backward-Euler step

The local problem can also be solved in one backward-Euler step over the substep, the root of $G(u) = u - u^n - \Delta t_r\,S(u)$, by Newton's method with a backtracking line search, keeping the densities non-negative. It is first order and costs about 0.1 µs per cell, 45 to 100 times less than the Rosenbrock integrator.

Newton can fail on this equation:

- in a stiff growth term, such as collisional ionization with $\beta\,n_{\rm H^0}\,\Delta t_r > 1$, where the Newton direction points into the zero bound;
- in very stiff photoionization, $\Gamma\,\Delta t_r \sim 10^2$–$10^3$;
- across a discontinuous rate, such as the 100 K switch of the recombination cooling.

It failed in 10% of a 2592-cell stress grid and nowhere in the Iliev tests. On Test 2 it matches the Rosenbrock radius to 0.1%, and the front temperature to within 29% ([findings, section 2](photoionization-findings.md#the-two-integrators-on-test-2)). Failed cells are always reported.

## 3. Design

The local problem is defined once, by a *network* ([`AbstractNetwork`](#AbstractNetwork)): species, bands, $S(u)$ and its exact Jacobian. It is solved by an *integrator* ([`AbstractChemSolver`](#AbstractChemSolver)) that reads only those. The two integrators thus solve exactly the same problem, and a new network or a new integrator can be added without touching the other. What is not a term of the local ODE (the emission, applying the flux factor, keeping the stored state admissible) is done around the solve, not in $S$.

### 3.1 Networks from JAFF

Networks are not written by hand. They are generated by [JAFF](https://github.com/jaff-chemistry/jaff), the network tool that also writes Quokka's, with its `honghu` template. A network is two files in a folder of `networks/`:

- `name.jet`, the reactions with their rate coefficients, one per line; a photoreaction is marked `PHOTO` with its threshold in eV;
- `name.jet.jfunc`, the rest of the physics as functions of `tgas` and the species densities: the cross-section of each photoreaction (`photoCrossSection<N>`), the energy each reaction gives the gas (`deltaE<N>`), custom rates (`chemRate<N>`) and the cooling (`heatingCoolingRate`);

and a `jaffgen.toml` that names the network and sets its radiation bands. JAFF writes $S(u)$ and its Jacobian from these, symbolically, and `networks/regenerate.sh --jaff-path DIR` writes them into `src/networks/` as Julia. Honghu adds the parts common to every network: the temperature, the isothermal option, the temperature floor, and the scales of the tolerance. The built-in networks are [`HydrogenIliev1`](#HydrogenIliev1) and [`HydrogenIliev2`](#HydrogenIliev2), for the two tests below. The mean photon energy of a band is not part of a network; it is given when the network is built ([`NetworkOptions`](#NetworkOptions)), and the heating per ionization in the `.jfunc` must agree with it.

## 4. Test problems

Both tests are from Iliev et al. (2006): an ionizing source switched on in uniform, static, neutral hydrogen. The figures and the numbers in the tables are made by `julia --project=. -t auto docs/make_figures.jl stromgren`, which takes about 9 minutes on 8 threads.

### 4.1 Iliev Test 1: isothermal H II region

The front radius has an analytic solution (section 1.8), so this test measures the accuracy of the transport, the chemistry and the reduced speed of light together.

| Setup | |
|:---|:---|
| Physics | radiation transport (M1, one ionizing band); photochemistry ([`HydrogenIliev1`](#HydrogenIliev1)), isothermal at $10^4$ K, $\alpha_B = 2.59\times10^{-13}$ cm$^3$ s$^{-1}$, no collisional ionization; hydrodynamics off |
| Domain | the octant $[0, 6.6\ {\rm kpc}]^3$ with the source at the origin, $32^3$ cells ($\Delta x = 206$ pc) |
| Initial condition | $n_{\rm H} = 10^{-3}$ cm$^{-3}$, $T = 10^4$ K, $x = 1.2\times10^{-3}$, $N_\gamma = 0$, $\mathbf F_\gamma = 0$ |
| Boundary conditions | reflecting on the three faces through the source, outflow on the other three |
| Source | $\dot N = 5\times10^{48}$ s$^{-1}$ ($\dot N/8$ into the octant), monochromatic at 13.6 eV with $\sigma = 6.3\times10^{-18}$ cm$^2$, spread over a Gaussian of width $1.5\,\Delta x$ |
| Evolution | $t = 0$ to 500 Myr; $\hat c = 10^{-3}c$; radiation Courant number 0.3; `RosenbrockChem`, relative tolerance $10^{-2}$ |
| Reference | $r_I(t)$ for $\hat c = c$, and the finite-$\hat c$ front of Shapiro et al. (2006) |
| Run | [`stromgren_iliev`](#stromgren_iliev)`(test = 1, n = 32, chat_factor = 1e-3)` |

![Iliev Test 1: the ionized radius against the two references (left), and the spherically averaged neutral fraction (right).](figures/stromgren_test1.png)

| $t$ (Myr) | $r_I$ (kpc) | finite $\hat c$ (kpc) | error | $\hat c = c$ (kpc) | error |
|---:|---:|---:|---:|---:|---:|
| 10 | 1.769 | 1.749 | +1.2% | 2.309 | −23.4% |
| 30 | 2.903 | 2.880 | +0.8% | 3.243 | −10.5% |
| 100 | 4.318 | 4.266 | +1.2% | 4.441 | −2.8% |
| 200 | 5.011 | 4.934 | +1.6% | 5.017 | −0.1% |
| 500 | 5.489 | 5.352 | +2.6% | 5.363 | +2.3% |

The front follows the finite-$\hat c$ solution to within 2.6% at all times. Early on it lags the $\hat c = c$ curve, because many of the photons are still in flight at $\hat c$, and it catches up as the front slows. The excess of about 2.5% at late times does not depend on $\hat c$ ([findings, section 3](photoionization-findings.md#the-reduced-speed-of-light-on-test-1)). The run had no failed chemistry solves.

### 4.2 Iliev Test 2: H II region with heating and cooling

The gas starts cold and is heated by the photoionizations. There is no analytic solution, and the result is checked for its shape.

| Setup | |
|:---|:---|
| Physics | as Test 1, but the network [`HydrogenIliev2`](#HydrogenIliev2), with the energy equation: photoheating and cooling (section 1.4), $\alpha_B(T)$ and collisional ionization |
| Domain, boundary conditions, evolution | as Test 1 |
| Initial condition | as Test 1, but $T = 100$ K and $x = 0$ |
| Source | as Test 1, but a $10^5$ K blackbody as one band: $\varepsilon = 29.65$ eV, $\sigma = 1.63\times10^{-18}$ cm$^2$, $\varepsilon_{\rm heat} = 16.05$ eV |
| Reference | none; the Test 1 solutions are shown for scale |
| Run | [`stromgren_iliev`](#stromgren_iliev)`(test = 2, n = 32, chat_factor = 1e-3)` |

![Iliev Test 2: the ionized radius (left), and the spherically averaged neutral fraction (middle) and temperature (right).](figures/stromgren_test2.png)

| $t$ (Myr) | 10 | 30 | 100 | 200 | 500 |
|:---|---:|---:|---:|---:|---:|
| $r_I$ (kpc) | 1.764 | 2.938 | 4.468 | 5.296 | 5.978 |
| median $T$ where $x > 0.9$ (K) | 19100 | 16200 | 14300 | 13700 | 13700 |

The ionized gas is heated to about $1.4\times10^4$ K and the neutral gas ahead of the front stays at 100 K. Hot gas recombines more slowly ($\alpha_B \propto T^{-0.7}$), so the front ends about 11% beyond the Test 1 radius. By 500 Myr it reaches the outer faces of the box, so the last radius is a lower bound. The single band overheats the ionized gas by about 10% (section 1.4), so these temperatures are not those of a full spectrum. The run had no failed chemistry solves.

## 5. Verification

The unit tests check properties rather than tuned numbers:

- the generated Jacobians against a 256-bit finite difference, including the isothermal and floored cases, and the generated rates against hand-computed values;
- the photon budget, charge and the energy of section 1.7, with a photoionization-only network generated for the tests, to $10^{-10}$ in a cell and $10^{-8}$ in a whole run;
- the ionization equilibrium, and that it does not depend on $\hat c$;
- conservation of hydrogen and $\sum_s X_s = 1$ in moving gas;
- Iliev's Test 1 at $16^3$, within 4.5% of the finite-$\hat c$ solution, and Test 2, a growing front with hot gas behind it and cold gas ahead.

## 6. Limitations

- **Hydrogen only, one band, on the spot.** JAFF can write networks with more species and bands, but the emission goes into the first band only, and diffuse recombination radiation is not followed.
- **What JAFF does not know is set by hand:** the mean photon energy of each band, and so the heating per ionization in the `.jfunc`. JAFF averages a flat cross-section over a band that extends to infinity to only $2\times10^{-8}$.
- **No radiation pressure** (`beta_order = 0`).
- **No thermal radiation groups alongside.** The thermal coupling uses a constant mean molecular weight, which is wrong by up to a factor of 2 in ionized gas, so groups with thermal opacity are refused.
- **A constant reduced speed of light,** a monatomic gas ($\gamma = 5/3$) and CGS units.
- **First-order splitting** (section 2.1), and a species renormalisation that does not conserve each species (section 2.2).
- **One band cannot get the heating right** for a broad spectrum (section 1.4).
- **The front is not quite round** at low resolution, and part of its offset from the finite-$\hat c$ solution is unexplained ([findings, section 3](photoionization-findings.md#the-reduced-speed-of-light-on-test-1)).

## References

- Aubert, D. & Teyssier, R. 2008, MNRAS, 387, 295 (ATON).
- Cen, R. 1992, ApJS, 78, 341.
- JAFF, <https://github.com/jaff-chemistry/jaff>.
- Gnedin, N. Y. & Abel, T. 2001, New Astron., 6, 437.
- Iliev, I. T., et al. 2006, MNRAS, 371, 1057.
- Katz, N., Weinberg, D. H. & Hernquist, L. 1996, ApJS, 105, 19.
- Krumholz, M. R., Stone, J. M. & Gardiner, T. A. 2007, ApJ, 671, 518.
- Levermore, C. D. 1984, J. Quant. Spectrosc. Radiat. Transfer, 31, 149.
- Plewa, T. & Müller, E. 1999, A&A, 342, 179.
- Shampine, L. F. & Reichelt, M. W. 1997, SIAM J. Sci. Comput., 18, 1.
- Shapiro, P. R., Iliev, I. T., Alvarez, M. A. & Scannapieco, E. 2006, ApJ, 648, 922.
- Quokka, `docs/markdown/photoionization.md` and `src/networks/photoionization_H_caseB_handwritten/actual_rhs.H`.


---

<!-- page: mhd.md -->

# Magnetohydrodynamics

The MHD module evolves the equations of ideal MHD with constrained transport, so that the discrete divergence of the magnetic field stays at round-off. It is Quokka's scheme (Kriel et al., in preparation): the HLLD Riemann solver, the Q26 EMF and the averaging of Londrillo & Del Zanna (2004), in one, two or three dimensions. The functions and types are documented on the reference page [Magnetohydrodynamics](reference/mhd.md), and the Riemann solvers on [Hydrodynamics](reference/hydro.md).

## 1. Governing equations

$$\begin{aligned}
\frac{\partial\rho}{\partial t} + \nabla\cdot(\rho\mathbf u) &= 0 , \\
\frac{\partial(\rho\mathbf u)}{\partial t} + \nabla\cdot(\rho\mathbf u\mathbf u - \mathbf b\mathbf b + p_{\rm tot}\,\mathsf I) &= 0 , \\
\frac{\partial E}{\partial t} + \nabla\cdot\left[(E + p_{\rm tot})\,\mathbf u - (\mathbf u\cdot\mathbf b)\,\mathbf b\right] &= 0 , \\
\frac{\partial\mathbf b}{\partial t} &= \nabla\times\boldsymbol\varepsilon , \qquad \boldsymbol\varepsilon = \mathbf u\times\mathbf b ,
\end{aligned}$$

with $p_{\rm tot} = p + b^2/2$, $E = e + \rho u^2/2 + b^2/2$ and $\nabla\cdot\mathbf b = 0$. The field is in units in which the magnetic pressure is $b^2/2$ ($\mathbf b = \mathbf B/\sqrt{4\pi}$ in Gaussian units). The EMF is $\boldsymbol\varepsilon = \mathbf u\times\mathbf b$, Quokka's sign, the opposite of Ohm's law $\boldsymbol\varepsilon = -\mathbf u\times\mathbf b$ used in the papers; every formula below has that sign. The fast magnetosonic speed along direction $d$ is

$$c_{f,d}^2 = \frac{1}{2\rho}\left[\gamma p + b^2 + \sqrt{(\gamma p + b^2)^2 - 4\gamma p\, b_d^2}\right] .$$

## 2. Numerical method

### 2.1 Staggered mesh

The normal component $b_d$ is stored at the centre of each face normal to $d$, and the EMF $\varepsilon_w$ at the centre of each edge along $w$. A cell's field is the average of its two faces, $b_{d,i} = (b_{d,i-1/2} + b_{d,i+1/2})/2$, and its energy $b^2/2$ is part of $E$.

### 2.2 Fluxes

The fluxes of $\rho$, $\rho\mathbf u$ and $E$ follow the method of lines, as for hydrodynamics. The primitives and the two transverse components of the cell-centred field are reconstructed to the faces (PCM, PLM or PPM); the normal component is the face value. The Riemann problem is solved with HLLD (Miyoshi & Kusano 2005), with the low-Mach total pressure and the carbuncle blending toward HLL of Minoshima & Miyoshi (2021), with HLL, or with LLF. HLL uses HLLD's bounding speeds, so the two differ only inside the Riemann fan; it is there to measure what HLLD gains, and has no counterpart in Quokka. Each face keeps the bounding speeds $\alpha^\pm \ge 0$ of its Riemann fan.

### 2.3 The EMF

For the edge along $x_2$, with $x_0$ and $x_1$ the other two directions:

1. **Face velocity (Q26).** On each face, $u^* = (\alpha^+ u_L + \alpha^- u_R)/(\alpha^+ + \alpha^-)$ from the reconstructed normal velocities.
2. **To the edge.** $b_0$ and $u_0^*$ of the $x_0$ faces are reconstructed along $x_1$, giving the values below (B) and above (T) the edge; $b_1$ and $u_1^*$ of the $x_1$ faces along $x_0$, giving left (L) and right (R).
3. **Corners.** $\varepsilon_2^{Q} = u_0^{*} b_1 - u_1^{*} b_0$ at each corner $Q \in \{LB, LT, RB, RT\}$.
4. **Averaging (LD04).** With $\alpha^\pm$ at the edge the larger of the two faces that meet there,

$$\varepsilon_2 = \frac{\alpha_0^+\alpha_1^+\varepsilon^{LB} + \alpha_0^-\alpha_1^+\varepsilon^{RB} + \alpha_0^+\alpha_1^-\varepsilon^{LT} + \alpha_0^-\alpha_1^-\varepsilon^{RT}}{(\alpha_0^+ + \alpha_0^-)(\alpha_1^+ + \alpha_1^-)} + \frac{\alpha_1^+\alpha_1^-}{\alpha_1^+ + \alpha_1^-}\left(b_0^T - b_0^B\right) - \frac{\alpha_0^+\alpha_0^-}{\alpha_0^+ + \alpha_0^-}\left(b_1^R - b_1^L\right) .$$

Along one direction LD04 is the HLL flux of the transverse field, so $\mathbf b$ gets HLL-level dissipation from the edge averaging, not HLLD's. HLLD resolves a rotational discontinuity in its flux, but the field smears across one with either solver, in Quokka as here.

Reconstructing $u^*$ across the sweep needs Riemann solves on faces beyond the interior: 1, 2 or 3 rows into the ghost cells for PCM, PLM or PPM, and one ghost cell more for the carbuncle input of the outermost row.

### 2.4 Time integration

Each stage of the strong-stability-preserving Runge-Kutta method updates the cells and the faces together,

$$U \leftarrow a\,U^0 + b\,U + c\,\Delta t\,L(U), \qquad \mathbf b \leftarrow a\,\mathbf b^0 + b\,\mathbf b + c\,\Delta t\,\nabla_h\times\boldsymbol\varepsilon ,$$

with $\nabla_h\times$ the circulation of the edge EMFs around each face. The discrete divergence of a discrete curl is zero, so every stage of every tableau keeps $\nabla\cdot\mathbf b$ where it was. The time step is $\Delta t = C / \max\sum_d (|u_d| + c_{f,d})/\Delta x_d$.

### 2.5 One and two dimensions

Quokka runs MHD in 3D only. Here a direction with one cell carries one face per cell, whose low and high face are the same face, so averages, differences and reconstructions along it return the value itself. Its faces carry $u^* = u_d$ and $\alpha^\pm = 1$, which cancel out of LD04. A 2D run then equals the same problem in a periodic box four cells deep to the bit, and a 1D run to $10^{-15}$.

### 2.6 Boundaries and floors

Periodic boundaries treat face $hi + 1$ as face $lo$. An outflow boundary is Quokka's MHD diode condition for outflowing gas: ghost cells copy the boundary cell and the transverse ghost faces the boundary row, the normal ghost faces are integrated outward so that $\nabla\cdot\mathbf b = 0$ in every ghost cell, and each ghost cell's total energy is corrected by the difference of its magnetic energy and its source's, so that it has the source's pressure. A static equilibrium then stays at rest up to the boundary.

The total energy contains $b^2/2$, so where $b^2 \gg p$ the internal energy is a small difference of large numbers. A cell floored to the minimum pressure is given the smallest total energy whose internal energy, computed as the conversion to primitives computes it, is above the floor.

### 2.7 Radiation and chemistry

The matter-radiation coupling and the chemistry change the internal energy $e = E - \rho u^2/2 - b^2/2$ and leave the field alone: every solve subtracts the magnetic energy from $E$ before it starts and adds it back after.

## 3. Test problems

The figures and the numbers in the tables are made by `julia --project=. -t auto docs/make_figures.jl mhd`, about half a minute on 8 threads.

### 3.1 Brio-Wu shock tube

A Riemann problem with every MHD wave but the rotational one, compared against Quokka run with the same scheme and the same time step.

| Setup | |
|:---|:---|
| Physics | MHD, HLLD, $\gamma = 2$ |
| Domain | $[0, 1]$, 256 cells (Quokka: a $256\times16\times16$ box periodic across) |
| Initial condition | $(\rho, p, b_y) = (1, 1, 1)$ for $x < 0.5$ and $(0.125, 0.1, -1)$ for $x > 0.5$, at rest, $b_x = 0.75$ |
| Boundary conditions | outflow (Quokka: the initial states) |
| Evolution | $t = 0$ to 0.1 in steps of $2.5\times10^{-4}$; SSPRK2; PCM, PLM (Sweby, $\beta = 1.5$, Quokka's default) or PPM |
| Reference | Quokka's `MHDBrioWuShockTube` with `emf_compute_scheme = Quokka2026`, `emf_averaging_scheme = LondrilloDelZanna2004`, `rk_integrator_order = 2`, in `test/data/quokka` |
| Run | [`brio_wu`](#brio_wu)`(n = 256, reconstruction = PLM(Sweby(1.5)), integrator = SSPRK2())` |

![Brio-Wu at t = 0.1 with PLM: Honghu (dots) against Quokka (line).](figures/mhd_bw.png)

| $L_1$ difference from Quokka | $\rho$ | $u_x$ | $u_y$ | $p$ | $b_y$ |
|:---|---:|---:|---:|---:|---:|
| PCM | $2.4\times10^{-13}$ | $1.8\times10^{-11}$ | $9.9\times10^{-12}$ | $5.8\times10^{-12}$ | $2.8\times10^{-12}$ |
| PLM | $1.9\times10^{-3}$ | $1.7\times10^{-2}$ | $7.5\times10^{-3}$ | $2.3\times10^{-3}$ | $1.9\times10^{-3}$ |
| PPM | $2.8\times10^{-3}$ | $2.7\times10^{-2}$ | $1.6\times10^{-2}$ | $3.6\times10^{-3}$ | $3.1\times10^{-3}$ |

With PCM the two codes run the same scheme and agree to round-off. With PLM and PPM they differ by Quokka's shock flattening, which is always on there and absent here; the PLM limiters are the same.

### 3.2 Ryu-Jones 2a shock tube

All seven MHD waves, with a field out of the plane of the jump.

| Setup | |
|:---|:---|
| Physics | MHD, HLLD, $\gamma = 5/3$ |
| Domain, boundary conditions, reference | as Brio-Wu, with Quokka's `MHDRyuJones2aShockTube`, compared on $x < 0.9$ |
| Initial condition | $(\rho, p, \mathbf u, b_y) = (1.08, 0.95, (1.2, 0.01, 0.5), 3.6/\sqrt{4\pi})$ for $x < 0.5$ and $(1, 1, \mathbf 0, 4/\sqrt{4\pi})$ for $x > 0.5$, $b_x = b_z = 2/\sqrt{4\pi}$ |
| Evolution | as Brio-Wu, to $t = 0.2$ |
| Run | [`ryu_jones_2a`](#ryu_jones_2a)`(n = 256, reconstruction = PLM(Sweby(1.5)), integrator = SSPRK2())` |

![Ryu-Jones 2a at t = 0.2 with PLM: Honghu (dots) against Quokka (line).](figures/mhd_rj.png)

| $L_1$ difference, $x < 0.9$ | $\rho$ | $u_x$ | $u_y$ | $u_z$ | $p$ | $b_y$ | $b_z$ |
|:---|---:|---:|---:|---:|---:|---:|---:|
| PCM | $9.0\times10^{-16}$ | $1.1\times10^{-15}$ | $7.6\times10^{-15}$ | $8.0\times10^{-16}$ | $1.1\times10^{-15}$ | $6.8\times10^{-16}$ | $8.6\times10^{-16}$ |
| PLM | $2.7\times10^{-4}$ | $2.3\times10^{-4}$ | $2.1\times10^{-3}$ | $3.1\times10^{-4}$ | $2.4\times10^{-4}$ | $1.4\times10^{-4}$ | $2.7\times10^{-4}$ |
| PPM | $5.7\times10^{-4}$ | $8.1\times10^{-4}$ | $3.2\times10^{-3}$ | $3.6\times10^{-4}$ | $7.2\times10^{-4}$ | $4.7\times10^{-4}$ | $5.5\times10^{-4}$ |

By $t = 0.2$ the fast shock reaches $x = 1$, where the two boundary conditions differ, hence the window.

### 3.3 Circularly polarised Alfven wave

An exact nonlinear solution of ideal MHD (Toth 2000), oblique to the grid, which measures the order of accuracy.

| Setup | |
|:---|:---|
| Physics | MHD, HLLD, $\gamma = 5/3$ |
| Domain | $[0, 2]\times[0, 1]$, $2n \times n$ cells, periodic |
| Initial condition | along $\mathbf k = 2\pi(1/2, 1)$: $\rho = 1$, $p = 0.1$, $b_\parallel = 1$, $u_\parallel = 0$; across it $\mathbf b_\perp = 0.1(\sin\phi, \cos\phi)$, $\mathbf u_\perp = -\mathbf b_\perp$, $\phi = \mathbf k\cdot\mathbf x$; $\mathbf b_\perp$ from a vector potential |
| Evolution | one period, $t = 2/\sqrt5$; SSPRK2 |
| Reference | the initial condition |
| Run | [`alfven_wave`](#alfven_wave)`(n = 64, reconstruction = PLM(Sweby(1.5)), integrator = SSPRK2())` |

![The $L_1$ error of $b_z$ after one period, over the amplitude.](figures/mhd_alfven.png)

| $n$ | PLM | order | PPM | order |
|---:|---:|---:|---:|---:|
| 16 | $7.27\times10^{-2}$ | | $4.71\times10^{-2}$ | |
| 32 | $2.58\times10^{-2}$ | 1.49 | $1.23\times10^{-2}$ | 1.94 |
| 64 | $7.05\times10^{-3}$ | 1.87 | $3.20\times10^{-3}$ | 1.94 |
| 128 | $1.77\times10^{-3}$ | 2.00 | $8.24\times10^{-4}$ | 1.96 |

Both converge at second order, the order of SSPRK2.

### 3.4 Orszag-Tang vortex

Interacting MHD shocks in 2D; the test of robustness and of $\nabla\cdot\mathbf b$.

| Setup | |
|:---|:---|
| Physics | MHD, HLLD, $\gamma = 5/3$ |
| Domain | $[0, 1]^2$, $256^2$ cells, periodic |
| Initial condition | $\rho = 25/(36\pi)$, $p = 5/(12\pi)$, $\mathbf u = (-\sin 2\pi y, \sin 2\pi x)$, $\mathbf b = (-\sin 2\pi y, \sin 4\pi x)/\sqrt{4\pi}$ |
| Evolution | $t = 0$ to 0.5; SSPRK2; PPM; Courant number 0.4 |
| Reference | none; Quokka's `OrszagTang` is the same vortex shifted by half the box |
| Run | [`orszag_tang`](#orszag_tang)`(n = 256, integrator = SSPRK2())` |

![Orszag-Tang at t = 0.5: density, pressure and magnetic pressure.](figures/mhd_orszag_tang.png)

| steps | $\max\lvert\nabla\cdot\mathbf b\rvert\,\Delta x/\max\lvert\mathbf b\rvert$ | mass drift | energy drift | floor repairs |
|---:|---:|---:|---:|---:|
| 1440 | $1.5\times10^{-14}$ | $2.3\times10^{-13}$ | $1.9\times10^{-14}$ | 0 |

## 4. Verification

The unit tests check properties rather than tuned numbers:

- $\nabla\cdot\mathbf b$ below $10^{-13}$ after many steps, with the three solvers and every reconstruction and tableau, in 2D and in 3D;
- conservation of mass, momentum and energy on a periodic box, and a uniform oblique state preserved;
- periodic face images that stay equal to the bit, and the same shock tube along $x$, $y$ and $z$;
- 1D and 2D runs equal to thin periodic 3D boxes, and periodic face images that stay equal to the bit with noisy 2D data, which pins how far into the ghost cells the Riemann solves reach;
- a static current-free field at rest in an outflow box, and an Orszag-Tang run at plasma $\beta \approx 0.3$ that needs the floors;
- HLLD's flux exact at a stationary contact and a rotational discontinuity, a contact that stays sharp with HLLD and smears with HLL and LLF, HLL equal to HLLD with its blending weight at zero, and LD04 equal to the HLL flux of $b_t$ in 1D;
- radiation and chemistry steps in a magnetised cell that give the internal energy of the same run without a field;
- a checkpoint, which holds the face-centred field as well as the cells, from which a run continues to the bit;
- the comparisons with Quokka and the convergence of section 3, and a 2D comparison: Quokka's `OrszagTang` with PCM for 40 steps, which this code reproduces to $2\times10^{-15}$ (with PPM they differ by $2\times10^{-3}$; the PPM kernels are the same, and Quokka's flattening, whose shock detector can fire at pressure extrema at this resolution, is the likely cause, not isolated).

## 5. Limitations

- **One EMF scheme.** Q26 with LD04; not Quokka's B25b averaging or FS18 and B25a EMFs, and no EMF consistent with HLLD (UCT-HLLD, Mignone & Del Zanna 2021), so rotational discontinuities smear (section 2.3).
- **No first-order flux correction and no shock flattening,** both of which Quokka has.
- **No dual energy.** The internal energy is $E - \rho u^2/2 - b^2/2$, accurate only to the round-off of $b^2/2$ at low plasma $\beta$ (Quokka evolves it separately as well).
- **Boundaries:** periodic and outflow (Quokka's diode condition for outflowing gas, applied whatever the direction of the flow) only.
- **No resistivity, AMR or tiling;** the MHD sweep runs on the CPU only.

## References

- Brio, M. & Wu, C. C. 1988, J. Comput. Phys., 75, 400.
- Felker, K. G. & Stone, J. M. 2018, J. Comput. Phys., 375, 1365.
- Gardiner, T. A. & Stone, J. M. 2005, J. Comput. Phys., 205, 509.
- Kriel, N., et al., in preparation (Quokka's MHD module).
- Londrillo, P. & Del Zanna, L. 2004, J. Comput. Phys., 195, 17.
- Mignone, A. & Del Zanna, L. 2021, J. Comput. Phys., 424, 109748.
- Minoshima, T. & Miyoshi, T. 2021, J. Comput. Phys., 446, 110639.
- Miyoshi, T. & Kusano, K. 2005, J. Comput. Phys., 208, 315.
- Orszag, S. A. & Tang, C.-M. 1979, J. Fluid Mech., 90, 129.
- Ryu, D. & Jones, T. W. 1995, ApJ, 442, 228.
- Toth, G. 2000, J. Comput. Phys., 161, 605.
- Quokka, `src/hydro/mhd_system.hpp`, `src/hydro/HLLD.hpp` and `src/hydro/LLF_mhd.hpp`.


---

<!-- page: coupling-new-method.md -->

# The production matter-radiation coupling: `BracketedCoupling`

This document describes the multigroup matter-radiation coupling solver Honghu uses in production, `BracketedCoupling`, and is complete on its own: the physics, the derivation, the algorithm, the choice of root-finder, and the measurements. It is the default for every run with $N_G \ge 2$ frequency groups; `RadiationPhysics(coupling = BracketedCoupling())` states it explicitly. The code is `solve_coupling(::BracketedCoupling, …)` in `src/coupling_solvers.jl` and the functions it calls in `src/coupling.jl`. Every number below is reproduced by `docs/coupling-experiments/coupling_study.jl` (§8).

In one paragraph: one backward-Euler step of the coupling is a system of $1 + N_G$ nonlinear equations, but its $N_G$ group equations are linear in the group energies, so they are solved in closed form and the whole step reduces to **one scalar equation in the gas energy** — the statement that the cell's total energy is unchanged. That equation always has a sign change on a known interval, so it is handed as a lambda to a **bracketing root-finder** — by default the `Brent` of SciML's BracketingNonlinearSolve, Brent's method as Brent wrote it. Nothing in the solve forms a matrix or allocates memory, and over a 240-cell sweep spanning three opacity laws and sixteen decades of optical depth it fails on none.

## 1. The problem

### 1.1 The equations

In each cell, the gas internal energy $E_\mathrm{gas}$ and the group radiation energies $E_g$, $g = 1 \ldots N_G$, exchange energy by emission and absorption:

$$\frac{dE_g}{dt} = \hat c_g \left(\varepsilon_g(T) - \alpha_g(T)\,E_g\right) , \qquad \frac{dE_\mathrm{gas}}{dt} = -c \sum_g \left(\varepsilon_g(T) - \alpha_g(T)\,E_g\right) ,$$

with gas temperature $T = E_\mathrm{gas}/c_V$ and two coefficients per group,

$$\varepsilon_g(T) = \rho\,\kappa_{P,g}(T)\,\frac{4\pi B_g(T)}{c} , \qquad \alpha_g(T) = \rho\,\kappa_{E,g}(T) .$$

$\varepsilon_g$ is the rate at which the gas emits into group $g$, $\alpha_g$ the coefficient of the rate at which the group is absorbed, and $4\pi B_g/c = a_\mathrm{rad} T^4 f_g(T)$ is the Planck energy density in the group, with $f_g$ the fraction of a Planck spectrum between the group's edges. $\kappa_{P,g}$ and $\kappa_{E,g}$ are the Planck- and energy-mean opacities; in this code they are equal, because the multigroup opacity is piecewise constant across a group.

The two equations differ by the factor $c/\hat c_g$. That asymmetry is the reduced speed of light approximation: the radiation side runs at $\hat c_g \le c$ and the gas side at the full $c$. It means the conserved quantity is not $E_\mathrm{gas} + \sum_g E_g$ but

$$E_\mathrm{gas} + \sum_g \frac{c}{\hat c_g}\,E_g ,$$

which every formula below respects.

The system is stiff. In an optically thick cell the coupling time $1/(\hat c\,\rho\,\kappa)$ is shorter than the transport step by factors up to $10^{12}$ in the cells tested here, so an explicit step is out of the question.

### 1.2 One backward-Euler step

Over a step $\Delta t$, two increments are held constant and supplied by the driver: an external radiation source $S_g$, and the lagged $\boldsymbol{v}\cdot\boldsymbol{F}$ work term $W_g$. Folding them into the old state,

$$\mathrm{gas0} = E_\mathrm{gas}^0 - \sum_g \frac{c}{\hat c_g} W_g , \qquad \mathrm{rad0}_g = E_g^0 + S_g + W_g ,$$

and writing the step's two optical depths as

$$\tau_g(T) = \Delta t\,\hat c_g\,\rho\,\kappa_{P,g}(T) , \qquad a_g(T) = \Delta t\,\hat c_g\,\alpha_g(T) = \Delta t\,\hat c_g\,\rho\,\kappa_{E,g}(T) ,$$

the backward-Euler step $u - u^0 - \Delta t\,f(u) = 0$ is

$$F_g \equiv (1 + a_g)\,E_g - \mathrm{rad0}_g - \Delta t\,\hat c_g\,\varepsilon_g(T) = 0 , \qquad g = 1 \ldots N_G ,$$

$$F_0 \equiv (E_\mathrm{gas} - \mathrm{gas0}) + \sum_g \frac{c}{\hat c_g}\left(\Delta t\,\hat c_g\,\varepsilon_g(T) - a_g E_g\right) = 0 .$$

That is $1 + N_G$ nonlinear equations in $1 + N_G$ unknowns. The obvious approach is Newton's method on all of them. `BracketedCoupling` does not do that.

## 2. The reduction to one equation

### 2.1 The group block is linear: eliminate it

No group appears in another group's equation; the groups meet only through the gas temperature. So at a fixed $E_\mathrm{gas}$ — hence a fixed $T$ — the $N_G$ equations $F_g = 0$ are independent and **linear** in $E_g$, and are solved outright:

$$\boxed{\;E_g(T) = \frac{\mathrm{rad0}_g + \Delta t\,\hat c_g\,\varepsilon_g(T)}{1 + \Delta t\,\hat c_g\,\alpha_g(T)}\;}$$

With $\kappa_{P,g} = \kappa_{E,g}$ this reads

$$E_g(T) = \frac{1}{1+\tau_g}\,\mathrm{rad0}_g + \frac{\tau_g}{1+\tau_g}\,\frac{4\pi B_g(T)}{c} ,$$

a **convex combination of where the group started and the Planck value at the gas temperature**, weighted by the optical depth of the step. As $\tau_g \to 0$ the group keeps its energy; as $\tau_g \to \infty$ it is in equilibrium with the gas. All of the stiffness is in that one weight, and it is handled exactly, with no iteration.

### 2.2 What is left is energy conservation

Rearranging $F_g = 0$ gives $\Delta t\,\hat c_g\,\varepsilon_g - a_g E_g = E_g - \mathrm{rad0}_g$: the net energy the gas hands to group $g$ over the step is the change in that group's energy. Substituting it into $F_0$ removes the emission and absorption terms and leaves one scalar equation in one unknown,

$$G(E_\mathrm{gas}) \equiv (E_\mathrm{gas} - \mathrm{gas0}) + \sum_g \frac{c}{\hat c_g}\left(E_g(T) - \mathrm{rad0}_g\right) = 0 .$$

Expanding `gas0` and `rad0`, the work term cancels out of $G$ completely — it survives only inside $E_g(T)$ — and

$$G(E_\mathrm{gas}) = E_\mathrm{gas} + \sum_g \frac{c}{\hat c_g}\,E_g(T) - \mathcal{E} , \qquad \mathcal{E} \equiv E_\mathrm{gas}^0 + \sum_g \frac{c}{\hat c_g}\left(E_g^0 + S_g\right) .$$

**$G$ is the new total energy minus the old.** The step is: find the gas energy at which the cell's books balance. It also means that $G$ at the returned answer is, exactly, the solver's energy-conservation error, which matters in §4.3.

One contract follows from the derivation and is worth stating because it is easy to break. Exactly, $F_0 = G - \sum_g (c/\hat c_g)\,F_g$, so $G$ is the residual of the step **only where the group block is solved**. Given arbitrary group energies it vanishes in the wrong place; given the $E_g(T)$ of §2.1 it is the whole problem.

### 2.3 In the code

The physics is written once and everything else is built from it:

| function (`src/coupling.jl`) | returns | role |
|:---|:---|:---|
| `coupling_coefficients(s, T)` | $(\varepsilon_g, \alpha_g)$ | the single source of truth for the coupling physics |
| `coupling_coefficients_dT(s, T)` | $(d\varepsilon_g/dT,\, d\alpha_g/dT)$ | their temperature derivatives |
| `group_energy_values(s, Egas)` | $E_g(T)$ | §2.1; what the root-finder evaluates |
| `group_energies(s, Egas)` | $E_g(T)$, $dE_g/dE_\mathrm{gas}$ | §2.1 plus derivative; used once per cell, in §4.3 |
| `energy_balance(s, Egas, Erad)` | $G$ | §2.2; contains no physics, only the $c/\hat c_g$ weights |

The same two coefficients also build `coupling_rhs` and `coupling_jacobian`, which the error-controlled reference solver `AdaptiveCoupling` integrates, so the production solver and its reference cannot drift apart.

## 3. The bracket, and which root

### 3.1 A sign change always exists

$G$ is a function of a *trial* gas energy, and bracketing means evaluating it at trial values deliberately below and above the answer — including values the cell could never physically have — and checking that the sign differs.

**Below: $E_\mathrm{gas} = c_V T_\mathrm{floor}$.** Every $4\pi B_g/c \to 0$ there, and $E_g$ is a convex combination of $\mathrm{rad0}_g$ and $4\pi B_g/c$, so $E_g \le \mathrm{rad0}_g$ and

$$G(c_V T_\mathrm{floor}) \le c_V T_\mathrm{floor} + \sum_g \frac{c}{\hat c_g}W_g - E_\mathrm{gas}^0 \le 0 .$$

The last inequality holds whenever the gas starts above its floor and the work term does not by itself exceed the gas energy; with $W_g = 0$ it is unconditional. It also needs $\kappa_{P,g}B_g \to 0$ as $T \to 0$, true for $\kappa \propto T^n$ with $n > -4$ and for any physical opacity.

**Above: $E_\mathrm{gas} = \mathcal{E}$**, the whole cell's energy in the gas. The first and last terms of $G$ cancel outright:

$$G(\mathcal{E}) = \sum_g \frac{c}{\hat c_g}\,E_g(T = \mathcal{E}/c_V) \ge 0 ,$$

because every group energy is non-negative whenever $\mathrm{rad0}_g \ge 0$. Asking the gas to hold the whole cell's energy leaves the radiation with some over, so the books over-balance.

$G$ is continuous, so a root lies in $[c_V T_\mathrm{floor}, \mathcal{E}]$ — which also shows that the solved gas energy never exceeds the cell's total. Checked over the 240-cell sweep of §5.2: the identity $G(\mathcal{E}) = \sum_g (c/\hat c_g)E_g$ holds to one ulp, and the interval brackets the root in every cell.

### 3.2 How $G$ behaves, and why a bracket is still needed

Differentiating §2.1,

$$\frac{dG}{dE_\mathrm{gas}} = 1 + \sum_g \frac{c}{\hat c_g}\,\frac{dE_g}{dE_\mathrm{gas}} , \qquad \frac{dE_g}{dE_\mathrm{gas}} = \frac{\Delta t\,\hat c_g\left(\varepsilon_g' - \alpha_g' E_g\right)}{c_V\,(1 + \Delta t\,\hat c_g\,\alpha_g)} ,$$

with $' = d/dT$. For $\kappa \propto T^n$ and $\kappa_P = \kappa_E$, substituting the eliminated $E_g$:

$$\frac{dE_g}{dT} = \underbrace{\frac{\tau_g}{1+\tau_g}\,\frac{d}{dT}\!\left(\frac{4\pi B_g}{c}\right)}_{\text{emission, always} > 0} + \underbrace{\frac{n\,\tau_g}{T\,(1+\tau_g)^2}\left(\frac{4\pi B_g}{c} - \mathrm{rad0}_g\right)}_{\text{opacity moving with } T} .$$

The second term vanishes when the opacity is constant, and decays like $1/\tau_g$ in the optically thick limit, where

$$\frac{dG}{dE_\mathrm{gas}} \to 1 + \frac{c}{\hat c}\,\frac{4 a_\mathrm{rad} T^3}{c_V} > 0 .$$

So **$G$ is monotone for a constant opacity, and monotone at large $\tau$ for any opacity law**. At moderate $\tau$, with a steep opacity law and a cell far from equilibrium, the second term can win and $G$ can have more than one root. That is why the solver needs a bracket at all, and why the bracket needs care (§3.3).

A worked example of $G$ at a hard cell — gas at $T = 0.5$, radiation at $1.3$, $\kappa \propto T^2$, $\tau = 2.5\times10^{8}$, four groups, code units — shows the reduction behaving well where the unreduced $(1+N_G)$-dimensional Newton does not. At the opening iterate $E_\mathrm{gas} = 0.5$ the eliminated group energies are already near equilibrium with the gas ($\sum_g E_g = 0.0625$), $G = -2.79$ and $dG/dE_\mathrm{gas} = 1.500$ against the predicted $1 + 4a_\mathrm{rad}T^3/c_V = 1.5$, so the first step points at the root, $E_\mathrm{gas} = 1.2103$. An iteration that keeps $E_g$ as independent unknowns linearises instead about the initial group energies ($\sum_g E_g = 2.856$), where the opacity term above is $-11.2$; its derivative comes out $-9.67$ and its first step points the wrong way.

### 3.3 Which root: march from the old state

A bracketing method returns *a* root in its bracket and does not say which. On the sweep of §5.2 one cell has three: $\kappa \propto T^2$, gas at $0.1$, radiation at $3$, $\tau = 10^{-2}$, where $G$ changes sign at $E_\mathrm{gas} = 0.110$, $1.17$ and $2.52$. An error-controlled integration of the ODE of §1.1 across the step ends at $0.109$, so $0.110$ is the physical root. Solved on the wide bracket $[c_V T_\mathrm{floor}, 4\mathcal{E}]$, ModAB and Bisection both returned $2.52$ — the gas handed 23 times the energy it physically reaches — while the library's Brent and ITP happened to return $0.110$. Which root came back depended on the method.

So the bracket is not taken as the whole interval of §3.1. It is **built by marching outward from the old gas energy** by factors of two, in the direction the sign of $G$ says the root lies, until the sign changes (`_energy_bracket` in `src/coupling_solvers.jl`). This isolates the root continuously connected to where the cell started — the one a small $\Delta t$ would reach — unless two roots lie within a factor of two of each other. With it, every bracketing method tried (`ZBrent`, the library's Brent, ModAB, ITP, Bisection) returns $0.110$ on that cell and agrees with the others to $10^{-9}$ on all 240. The march stops at the temperature floor going down and after 200 doublings going up, and if it finds no sign change the cell is reported unconverged rather than guessed at; this never happened on the sweep or the test problems. Typical cost is one or two evaluations of $G$.

## 4. The algorithm

### 4.1 The solve

```julia
G = (Egas, s) -> energy_balance(s, Egas, group_energy_values(s, Egas))   # the equation
lo, hi, nbracket, found = _energy_bracket(G, s)                          # §3.3
sol = solve(IntervalNonlinearProblem{false}(G, (lo, hi), s), m.root_finder;
            abstol = atol, maxiters = m.max_iterations)                  # the algorithm
```

The root-finder is a field of the solver, `BracketedCoupling(root_finder = Brent())` by default, the `Brent` of SciML's BracketingNonlinearSolve. It is called through SciMLBase's `IntervalNonlinearProblem` interface, so any bracketing method written to that interface is interchangeable with it, in particular the package's other methods; §5 compares them. Both packages were already in OrdinaryDiffEq's dependency tree and already loaded, so using them added nothing to the install or to the load time.

The cell state travels as the problem parameter rather than being captured by the lambda, so the lambda closes over nothing and costs nothing. `_energy_bracket` takes the equation as `G::F … where {F}`, because Julia does not specialise on a function argument it only passes through, and without that the same code allocated 2.8 kB per cell.

### 4.2 Why derivative-free

$dG/dE_\mathrm{gas}$ is known in closed form (§3.2), so Newton's method is an obvious alternative. It is not the better one, because of what an evaluation costs: $G$ needs one incomplete Planck integral per call, and $dG/dE_\mathrm{gas}$ needs its temperature derivative as well. At $N_G \ge 2$ that integral dominates the cost of the whole solve. A derivative-free method that takes about as many, cheaper evaluations wins: Brent's and `ModAB`'s 12 value-only evaluations per cell take 0.57 of the time of the 9 value-and-derivative evaluations a Newton-in-bracket needed on the same sweep.

### 4.3 Converting the tolerance

Every bracketing method in BracketingNonlinearSolve, `Brent` included, stops when the bracket is narrower than `abstol` **in $E_\mathrm{gas}$**. The solver promises something else: $|G| \le \mathrm{tol}\cdot\mathcal{E}$, and by §2.2 $G$ is the cell's energy-conservation error. The two differ by $dG/dE_\mathrm{gas}$, which by §3.2 reaches $1 + (c/\hat c)\,4a_\mathrm{rad}T^3/c_V$ — thousands in a radiation-dominated cell, and more under a strongly reduced $\hat c$. Passing $\mathrm{tol}\cdot\mathcal{E}$ as `abstol` alone silently loosens conservation by that factor: measured with `ZBrent` over the sweep, 72 of 240 cells then conserve energy only to $1.9\times10^{-6}$ against a promised $10^{-9}$.

So after the first solve the residual is checked. If it is too large, the solve is repeated on the library's own final bracket, `(sol.left, sol.right)`, with `abstol` divided by $dG/dE_\mathrm{gas}$ evaluated at the answer — effectively constant across a bracket that narrow, so one repeat always suffices, and it starts from an interval a few `abstol` wide. This is the one place the derivative is used, through `group_energies`. **Convergence is judged on $|G|$, not on the library's return code.**

### 4.4 A convergence test that $\tau$ cannot break

In a Newton iteration on the $1 + N_G$ equations of §1.2, the group residual contains $\tau_g\,(4\pi B_g/c - E_g)$. At the solution $4\pi B_g/c$ and $E_g$ agree to round-off, so the difference carries an absolute error of $\varepsilon_\mathrm{mach}\cdot 4\pi B_g/c$ and the residual an error of $\varepsilon_\mathrm{mach}\,\tau_g$ times the cell's energy. A residual test at tolerance $10^{-11}$ cannot then be satisfied once $\tau_g \gtrsim 10^{5}$, however exact the answer. $G$ contains no such term: the cancellation was carried out analytically in §2.2, and $G$ is a difference of energies of ordinary size. The tolerance means what it says at every optical depth.

### 4.5 What `iterations` reports

`CouplingResult.iterations`, which feeds the run's `newton_mean` / `newton_max` diagnostics, counts the evaluations of $G$ made by the bracket march plus one per call to the root-finder. The root-finder interface returns no evaluation count without allocating (SciMLBase's statistics type is mutable), and counting through the lambda allocates 16 bytes per cell. Read a `newton_mean` of about 3 for this solver as "one march step each way plus one solve", not as three Newton iterations.

## 5. The root-finder: Brent's method, and how it compares

Three bracketing methods are compared here. All interpolate where interpolation helps and never leave the bracket. Until 2026-10-17 the default was `ZBrent`, an in-tree copy of Brent's method, written because the library's `Brent` was not that method (§5.1). The fix went upstream and `ZBrent` is gone (§5.6). The measurements below were taken with `ZBrent`; the library's `Brent` from 1.12.8 on reproduces its rows exactly, so in the tables `ZBrent()` stands for today's default and "`Brent()` (library)" for the library before 1.12.8.

- **`ZBrent`**, the default until 2026-10-17, formerly in `src/rootfind.jl`: Brent's method as Brent (1973) wrote it and as Numerical Recipes transcribes it in `zbrent` — inverse quadratic interpolation or a secant step when either shrinks the bracket fast enough, bisection otherwise, and a minimum step (§5.1).
- **`Brent`** from SciML's BracketingNonlinearSolve before 1.12.8, which was a transcription of textbook pseudocode rather than of Brent's algorithm.
- **`ModAB`** from the same package, a modified Anderson–Björck method: regula falsi with a correction that stops one end of the bracket from sticking.

All three plug into the same interface, and the test suite checks the default against `ModAB`, `ITP` and `Bisection`.

### 5.1 What the library's `Brent` got wrong before 1.12.8

Two defects, both visible in its source then and both measured:

- **No minimum step.** When the interpolated step would move the estimate $b$ by less than $\mathrm{tol}_1 = 2\varepsilon_\mathrm{mach}|b| + \mathtt{abstol}$, Brent's algorithm moves it by $\mathrm{tol}_1$ towards the contrapoint instead. On a smooth convex function the interpolated iterates converge to the root from one side, so without that step the far end of the bracket is never replaced except by bisection — and the method stops only when the *bracket* is narrow, which then takes many halvings. The minimum step deliberately probes just past the root, and the far end collapses in one evaluation.
- **Two evaluations per iteration.** It recomputes $f(c)$ at the top of every iteration, where $c$ is always an earlier point whose value is already known.

On two analytic functions, counting every evaluation of $f$:

| $f(x)$, bracket, `abstol` | `ZBrent` | library `Brent` | `ModAB` | `ZBrent` without the minimum step |
|:---|---:|---:|---:|---:|
| $x^2 - 2$, $[1, 2]$, $10^{-15}$ | 9 | 20 (9 distinct points) | 10 | 9 |
| $x^4 - 2$, $[0, 4]$, $5\times10^{-11}$ | **12** | 62 (30 distinct points) | 15 | 50 |

$x^2 - 2$ shows the second defect alone: the library's `Brent` visits the same 9 points as `ZBrent` but evaluates most of them twice. $x^4 - 2$ — the same $T^4$ shape as the energy balance $G$ — shows the first: with the minimum step removed, `ZBrent` itself needs 50 evaluations instead of 12. (A report that prompted this comparison found $x^2 - 2$ taking 37 evaluations instead of 8 under FMA contraction in compiled C and CUDA. Julia does not contract $x^2 - 2$, and there the minimum step makes no difference; on $x^4 - 2$ and on $G$ it does.)

On $G$ itself, over the sweep of §5.2 and counting only the root-finder's own evaluations: the library's `Brent` takes 20.1 on average and 70 in the worst cell; `ZBrent` without the minimum step 13.0 and 61; `ZBrent` 7.7 and 12; `ModAB` 9.5 and 12.

### 5.2 Robustness and cost over the sweep

The sweep is 240 single cells: 8 initial gas and radiation temperature pairs (gas hotter, radiation hotter, and both near equilibrium, over two decades), 10 optical depths $\tau$ from $10^{-4}$ to $10^{12}$, and three opacity laws — constant, $\kappa \propto T^{-3.5}$ and $\kappa \propto T^{2}$ — at four groups and tolerance $10^{-9}$. "$G$ evaluations" counts everything the solve does: the bracket march, the root-finder, and the §4.3 repeat. "vs ref" is the largest difference in $E_\mathrm{gas}$ from a Bisection solve at tolerance $10^{-13}$, and "energy error" the largest $|E_\mathrm{gas} + \sum_g E_g - \mathcal{E}|$; both are in units of the cell's total energy.

| `root_finder` | failures | $G$ evaluations | cells re-solved (§4.3) | vs ref | energy error | time per cell |
|:---|---:|---:|---:|---:|---:|---:|
| `ZBrent()` (default) | 0 / 240 | **12.0** | 72 | $3.5\times10^{-10}$ | $4.9\times10^{-10}$ | **1.88 μs** |
| `Brent()` (library) | 0 / 240 | 25.0 | 24 | $9.3\times10^{-10}$ | $9.3\times10^{-10}$ | 3.33 μs |
| `ModAB()` | 0 / 240 | 12.7 | 0 | $6.8\times10^{-14}$ | $8.8\times10^{-16}$ | **1.88 μs** |

All three are perfectly robust on the sweep, and `ZBrent` and `ModAB` cost the same. They differ in how they finish. Both Brent variants stop essentially when the bracket reaches the requested width, so their answers sit just inside the tolerance and many cells need the §4.3 repeat — 72 for `ZBrent`, whose narrow final brackets put its answers closer to the edge. `ModAB`'s final steps converge superlinearly past the requested width, so it lands at machine precision and never needs the repeat. `ZBrent` makes up the repeats with fewer evaluations to get there.

### 5.3 Cost against group count

One cell, constant opacity, $\tau = 10^{4}$, out of equilibrium; minimum over 200 samples.

| `root_finder` | $N_G = 2$ | $N_G = 4$ | $N_G = 8$ | $N_G = 16$ |
|:---|---:|---:|---:|---:|
| `ZBrent()` | **0.88 μs** | **1.50 μs** | **2.69 μs** | **5.51 μs** |
| `Brent()` (library) | 1.29 μs | 2.26 μs | 4.13 μs | 8.43 μs |
| `ModAB()` | 0.94 μs | 1.66 μs | 2.84 μs | 6.63 μs |

All three allocate **0 bytes** at every group count, and all scale linearly in $N_G$, because each evaluation of $G$ is one pass over the groups. `ZBrent` is 1.5 times faster than the library's `Brent` and 5 to 17 per cent faster than `ModAB`.

### 5.4 The test problems

Each problem run to completion at four groups; error is the relative $L_1$ difference in gas temperature from `AdaptiveCoupling` at relative tolerance $10^{-8}$, which integrates the ODE of §1.1 rather than taking one backward-Euler step.

| problem | `ZBrent()` | `Brent()` (library) | `ModAB()` | error in $T_\mathrm{gas}$ |
|:---|---:|---:|---:|---:|
| `marshak_vaytet`, $n = 64$ | **2.47 s** | 4.91 s | 2.82 s | $7.61\times10^{-4}$ (all three) |
| stiff relaxation, $\kappa = 10^{12}$ | 0.15 s | 0.15 s | 0.15 s | $1.2\times10^{-10}$, $1.9\times10^{-10}$, $1.4\times10^{-15}$ |
| Marshak wave, $\kappa = 300\,T^{-3.5}$ | 0.18 s | 0.21 s | 0.17 s | $5.859\times10^{-4}$ (all three) |
| Marshak wave, $\kappa = 3\times10^{5}\,T^{2}$ | < 0.01 s | < 0.01 s | < 0.01 s | $2.497\times10^{-3}$ (all three) |

No solve failed on any problem. `marshak_vaytet` is the code's built-in multigroup test problem (Vaytet et al., frequency-dependent opacity, 16309 steps). The stiff relaxation is a periodic box with $\tau_\mathrm{cell} \approx 3\times10^{9}$. The last two are Marshak waves with temperature-dependent opacity; the $T^{2}$ one is where solvers that iterate on all $1 + N_G$ unknowns fail on some cells and leave the temperature field 7% wrong.

The three root-finders give the same temperature field on every problem, to the digits shown, except where all are already at the $10^{-10}$ level. The errors in the table are not the root-finders' errors but the discretisation error of taking one backward-Euler step, which all three share (§6.2). The difference is cost: on `marshak_vaytet`, where the coupling runs in every cell of 16309 steps, the library's `Brent` takes twice as long as `ZBrent`.

### 5.5 Which to use

**Brent's method is the default**, now as the library's `Brent()` from 1.12.8, which is the `ZBrent` of the tables: the fastest of the three per cell and on the one test problem long enough to time, and it keeps the solver's promise exactly — conservation to the requested tolerance. **`ModAB` is equivalent** in robustness and cost on everything measured, and conserves energy to machine precision rather than to the tolerance; pass `BracketedCoupling(root_finder = ModAB())` if that margin is wanted, with `using BracketingNonlinearSolve: ModAB`. **The library's `Brent` before 1.12.8** was as robust but twice as expensive, for the reasons of §5.1; `Project.toml` now requires 1.12.8. Keep `Bisection()` for checking: it is slow — 37 evaluations on average — and cannot return a wrong answer from a valid bracket, which is what makes it a reference.

### 5.6 The upstream fix, and the switch to it

The two defects of §5.1 are reported upstream with a fix, as [SciML/NonlinearSolve.jl#1340](https://github.com/SciML/NonlinearSolve.jl/pull/1340) (opened 2026-09-28, from the branch `brent-zbrent-minimum-step` of the fork `chongchonghe/NonlinearSolve.jl`). It replaces the library's loop with Brent's `zero` / `zbrent`, so the library's `Brent` evaluates $f$ once per iteration and takes the minimum step. On the functions of §5.1 it brings the library's counts down to `ZBrent`'s: 20 to 9 on $x^2 - 2$ and 62 to 12 on $x^4 - 2$. It was merged the same day and released in BracketingNonlinearSolve 1.12.8 on 2026-09-29.

**Honghu now uses it.** On 2026-10-17 `BracketingNonlinearSolve.Brent()` became the default `root_finder`, BracketingNonlinearSolve moved from `[extras]` to `[deps]` with compat 1.12.8, and `src/rootfind.jl` was deleted. Three checks came first, on 1.12.8:

1. The `rootfind` section of `coupling_study.jl`, run with both: over the sweep the same 12.0 evaluations of $G$ a cell, the same 72 re-solves and the same deviations to every printed digit, 1.76 against 1.76 μs a cell; 0 bytes at every group count; and the same results on all four test problems.
2. On $x^2 - 2$ and $x^4 - 2$, at the positive tolerances the solver uses, the two visit the same points and return the same root to the last bit. At `abstol = 0` the library takes one evaluation more and stops with `FloatingPointLimit`, which the solver never asks for.
3. `test/test_rootfind.jl` now tests the library's `Brent` as the default: each point evaluated once, the minimum step on $x^4 - 2$ in at most 14 evaluations, zero allocation.

## 6. Accuracy and cost

### 6.1 The solve is exact to its tolerance

Over the sweep of §5.2 the solver never fails and every answer is within $10^{-9}$ of the cell's energy of a Bisection solve at $10^{-13}$, for each of the three root-finders. It allocates nothing and costs $O(N_G)$ per evaluation, with no matrix formed and no linear system solved.

### 6.2 One backward-Euler step is not exact

`BracketedCoupling` solves the backward-Euler equations exactly; those equations are a first-order discretisation of the ODE of §1.1, and one step of them has an error. It is largest where the coupling time and $\Delta t$ are comparable, and vanishes in both limits: nothing happens in a thin cell, and a thick cell goes to the same equilibrium either way. Measured on one cell (four groups, gas at 1.3, radiation at 0.5, constant opacity) against two independent stiff integrators at $10^{-12}$, in units of the cell's total energy:

| $\tau$ | $10^{-4}$ | $10^{-2}$ | $10^{-1}$ | $1$ | $3$ | $10$ | $10^{2}$ | $10^{4}$ | $10^{9}$ |
|:---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| error of one step | $1.0\times10^{-7}$ | $8.3\times10^{-4}$ | $2.7\times10^{-2}$ | $6.2\times10^{-2}$ | $2.8\times10^{-2}$ | $9.3\times10^{-3}$ | $9.6\times10^{-4}$ | $9.7\times10^{-6}$ | $9.7\times10^{-11}$ |

The peak, 6% at $\tau \sim 1$, is a property of the time discretisation, not of the solver, and in a run it sits inside the operator-splitting error of coupling to transport. `AdaptiveCoupling` integrates the ODE with error control and removes it, at about 12 times the cost on its loosest setting and hundreds of times on a tight one, plus 8 to 21 kB of allocation per cell; it is the reference for checking, not a production option.

## 7. Limitations

- **Groups exchange energy only through the gas.** The closed form of §2.1 is a per-group division because no group appears in another's equation. A term that couples groups directly — Compton redistribution, overlapping lines — makes the group block a matrix, and the reduction to one equation is gone. `BracketedCoupling` would have to be replaced, not adjusted.
- **Roots closer than a factor of two.** The march of §3.3 isolates the root connected to the old state unless another root lies within a factor of two of it. None did on the sweep.
- **Negative starting group energies.** The bracket of §3.1 needs $\mathrm{rad0}_g = E_g^0 + S_g + W_g \ge 0$; a lagged work term more negative than a group's own energy can break it. The march then finds no sign change and the cell is reported unconverged, not solved wrongly.
- **What has been tested.** One-dimensional problems, double precision, `beta_order = 0` on the multigroup problems (so the lagged $\boldsymbol{v}\cdot\boldsymbol{F}$ outer iteration is not exercised), and power-law opacities. A tabulated opacity with structure in it may produce the non-monotone $G$ of §3.2 more often than the sweep did.

## 8. Code map and reproducing

| where | what |
|:---|:---|
| `src/coupling.jl` | `coupling_coefficients`, `group_energy_values`, `group_energies`, `energy_balance` (§2.3) |
| `src/coupling_solvers.jl` | `BracketedCoupling`, its `solve_coupling`, `_energy_bracket` (§3.3, §4) |
| `src/Honghu.jl` | the selective imports of `IntervalNonlinearProblem` from SciMLBase and `Brent` from BracketingNonlinearSolve |
| `test/test_rootfind.jl` | the library's `Brent`, as the default: each point evaluated once, the minimum step on $x^4 - 2$ (fails without it: 50 evaluations against a limit of 14), zero allocation |
| `test/test_radiation_multigroup.jl` | zero-byte allocation of the coupling; the testset "BracketedCoupling: the root-finder chooses how, not what", which pins §3.3, §4.3 and agreement between Brent, ModAB, ITP and Bisection |

```bash
julia --project=. -t 4 docs/coupling-experiments/coupling_study.jl rootfind     # §5, every table
julia --project=. -t 4 docs/coupling-experiments/coupling_study.jl derivation   # §3.1, §3.2
julia --project=. -t 4 docs/coupling-experiments/coupling_study.jl ode          # §6.2
julia --project=. -t 4 test/runtests.jl                                          # the full suite
```

The `rootfind` section counts evaluations with a re-assembly of the solve that carries a counter, and asserts that it returns the shipped solver's gas energy to the last bit before reporting its counts. Timings are from an Apple-silicon laptop and are meaningful only as ratios.


---

<!-- page: coupling-new-method-dust.md -->

# Dust-gas thermal coupling with the one-variable method: implementation plan

Status: **implemented, 2026-09-28.** All five recommendations in §8 were accepted as written. §9 says what was built and what it measured. The math in §2–§5 was first checked by a prototype, `docs/coupling-experiments/dust_prototype.jl`, and §6 gives its numbers.

Scope: the thermal coupling of gas, dust and multigroup radiation, with the Bate & Keto (2015) dust model as used in the draft `external/quokka-dust-gas-tex/main.tex` §2.1 and in Quokka's `SolveGasDustRadiationEnergyExchange`. Photoelectric heating, cosmic-ray heating and line cooling are out of scope. The numerical method is **not** the draft's: the draft (and Quokka) runs a $(1+N_G)$ Newton iteration in $(E_{\rm gas}, R_g)$ with a regime switch between "well-coupled" and "decoupled" dust. This plan reduces the step to one scalar equation in the dust temperature, solved inside a bracket, in the same way `BracketedCoupling` reduces the dust-free step to one equation in $E_{\rm gas}$ (`docs/coupling-new-method.md`).

## 1. The physics

Radiation interacts with the dust only. The gas has no opacity. The dust has no heat capacity, so at every instant it is in energy balance: what it gains from the gas by collisions it loses to the radiation. The three equations are (draft eqs. 2.1, 2.2, dust1 and Td, without transport)

$$\frac{\partial E_{\rm gas}}{\partial t} = -\Lambda_{\rm gd},$$

$$\frac{\partial E_g}{\partial t} = \hat{c}\left[\rho\kappa_{P,g}(T_d)\,\frac{4\pi B_g(T_d)}{c} - \rho\kappa_{E,g}(T_d)\,E_g\right],$$

$$\Lambda_{\rm gd} = c\sum_g \left[\rho\kappa_{P,g}(T_d)\,\frac{4\pi B_g(T_d)}{c} - \rho\kappa_{E,g}(T_d)\,E_g\right],$$

with the collisional rate of Keto & Field (2005)

$$\Lambda_{\rm gd} = \Lambda^0_{\rm gd}\, n_{\rm H}^2\, T^{1/2}\,(T - T_d) \equiv K\, T^{1/2}(T - T_d), \qquad K = \Lambda^0_{\rm gd}\, n_{\rm H}^2 .$$

Here $T$ is the gas temperature, $T_d$ the dust temperature, and $\kappa$ the dust opacity per unit mass of gas (it includes the dust-to-gas ratio), evaluated at $T_d$. The third equation is algebraic, so $T_d$ is not a state variable: it is fixed at each instant by $T$ and the $E_g$. The sign in the draft's eq. 2.2 is a typo; eq. 3.2 and the equations above have the physical sign.

Quokka writes the same model. With `enable_dust_gas_thermal_coupling_model`, it evaluates the emission and every opacity at $T_d$, and uses $n_{\rm H} = \rho / m$, with $m$ = `mean_molecular_mass`. Its `coeff_n` is $(\hat{c}/c)\,\Delta t\, K$, the draft's $N_{\rm dust}$.

Two properties follow directly and are used below:

- **Total energy is conserved.** $E_{\rm gas} + \sum_g (c/\hat{c}_g) E_g$ does not change, because the dust holds no energy. Both terms are shifted by $\Lambda_{\rm gd}$ with opposite signs.
- **The two limits are known.** As $K \to \infty$ the dust is locked to the gas, $T_d \to T$, and the system becomes the dust-free coupling with $\kappa$ evaluated at $T$. As $K \to 0$ the gas is isolated, and the dust is in radiative equilibrium with the field.

## 2. The backward-Euler step, reduced to one unknown

Take one backward-Euler step of length $\Delta t$. Use the same notation as `CouplingState`: $S_g$ is the external source and $W_g$ the lagged work term, and

$$\mathrm{rad0}_g = E_g^0 + S_g + W_g, \qquad \mathrm{gas0} = E_{\rm gas}^0 - \sum_g \frac{c}{\hat{c}_g} W_g .$$

The unknowns are $E_{\rm gas}$, $E_g$ and $T_d$. Write $\varepsilon_g(T_d) = \rho\kappa_{P,g}(T_d)\,4\pi B_g(T_d)/c$ and $\alpha_g(T_d) = \rho\kappa_{E,g}(T_d)$, which are exactly what `coupling_coefficients(s, T_d)` returns. The discrete system is

$$E_g - \mathrm{rad0}_g = \Delta t\,\hat{c}_g\,(\varepsilon_g - \alpha_g E_g), \tag{a}$$

$$E_{\rm gas} - \mathrm{gas0} = -\Delta t\, K\, T^{1/2}(T - T_d), \tag{b}$$

$$K\, T^{1/2}(T - T_d) = c \sum_g (\varepsilon_g - \alpha_g E_g). \tag{c}$$

**Choose $T_d$ as the unknown.** Everything else then follows from it in closed form.

1. **Group energies.** Equation (a) is linear in $E_g$ at fixed $T_d$, and no group appears in another's equation:
   $$E_g(T_d) = \frac{\mathrm{rad0}_g + \Delta t\,\hat{c}_g\,\varepsilon_g(T_d)}{1 + \Delta t\,\hat{c}_g\,\alpha_g(T_d)} .$$
   This is `_eliminate_groups` evaluated at $T_d$ rather than at $T$, unchanged.
2. **Gas energy, from conservation.** Add (b) to $\sum_g (c/\hat{c}_g)\times$(a), and substitute (c). The exchange terms cancel:
   $$E_{\rm gas}(T_d) = \mathrm{gas0} - \sum_g \frac{c}{\hat{c}_g}\left[E_g(T_d) - \mathrm{rad0}_g\right] .$$
   This is `energy_balance(s, E_gas, E_rad) = 0` solved for $E_{\rm gas}$, so it is $-$`energy_balance(s, 0, E_rad)`. Then $T = E_{\rm gas}/c_V$.
3. **The one equation left** is (b), the gas equation:
   $$H(T_d) \equiv E_{\rm gas}(T_d) - \mathrm{gas0} + \Delta t\, K\, T^{1/2}\,(T - T_d) = 0, \qquad T = T\!\left(E_{\rm gas}(T_d)\right).$$

Steps 1 and 2 make (a) and the sum of (b) and (c) hold exactly, for every trial $T_d$. So **the total energy is conserved to round-off at every iterate, not only at convergence.** $H$ is the part of the gas equation that is left, in energy units.

### Why $T_d$ and not $E_{\rm gas}$

With $E_{\rm gas}$ as the unknown (the dust-free method's choice), each evaluation of the outer equation needs $T_d$ at the trial $T$, which is a root of (c) with (a) substituted: a nested root-find, costing about ten evaluations per outer evaluation. With $T_d$ as the unknown, one evaluation of $H$ costs one evaluation of `coupling_coefficients`, the same as one evaluation of the dust-free equation. The cost per cell should therefore be about the same as `BracketedCoupling` today.

### Why no regime switch is needed

Quokka and the draft recover the dust temperature from the transfer, $T_d = T - \sum_g R_g / (N_{\rm dust}\sqrt{T})$. This divides by $N_{\rm dust} \propto K$, so it breaks down when the dust decouples. That is why they need a second, "decoupled" model with its own Jacobian, selected by `gas_dust_coupling_threshold`, and adaptive damping when that branch oscillates. In the formulation above, $K$ only multiplies. At $K = 0$, $H$ becomes $E_{\rm gas}(T_d) - \mathrm{gas0}$, whose root is the dust in radiative equilibrium with the gas untouched, which is the correct decoupled answer. One equation covers every $K$ from $0$ to $\infty$, and §6 checks both ends.

## 3. The bracket

**Lower end, $T_d = T_{\rm floor}$.** There $\varepsilon_g \approx 0$, so step 1 gives $E_g \le \mathrm{rad0}_g$. Step 2 then gives $E_{\rm gas} \ge \mathrm{gas0}$, so $T \ge T_{\rm floor}$ and the collision term is $\ge 0$. Therefore $H(T_{\rm floor}) \ge 0$, up to the thermal emission at the floor temperature.

**Upper end, $T_d \to \infty$.** Here $\varepsilon_g \to \infty$ in any group with $\kappa_P > 0$. The group energies grow without bound, $E_{\rm gas}(T_d) \to -\infty$, and $H \to -\infty$. For $E_{\rm gas} < c_V T_{\rm floor}$, $T$ is held at the floor. The collision term is then negative too, so $H < 0$ throughout that region. Therefore every root has $E_{\rm gas} \ge c_V T_{\rm floor}$, and the floor on $T$ never selects the answer.

**The march.** As in `_energy_bracket`, start from a guess and step by factors of two in the direction the sign of $H$ indicates, until the sign changes. Stop at $T_{\rm floor}$ going down; going up, the sign change is guaranteed. The guess is $T_d^{\rm init} = T^0$, the gas temperature at the start of the step. That is also Quokka's choice: it calls `ComputeDustTemperatureBateKeto(T_gas0, T_gas0, …)`, whose second argument is the initial guess. The walk needs `_energy_bracket` with the lower bound and the starting point as arguments instead of `c_V T_floor` and `E_gas^0`. That generalisation leaves the dust-free call identical.

**Uniqueness.** Two separate facts:

- The collision law by itself is harmless. At fixed $T_d$, the backward-Euler gas equation $T - T^0 = k\sqrt{T}(T_d - T)$ has exactly one root in $(0, T_d)$, because $\sqrt{T}(T_d - T)$ is concave.
- The dust balance can have several roots when the dust opacity rises steeply with $T_d$. With $\kappa \propto T_d^2$, the absorption term $\rho\kappa(T_d)(B(T_d) - E)$ is not monotone in $T_d$. The multiple roots are then equilibria of the model itself, not artefacts of the discretisation: an ODE integration faces the same choice at $t = 0$. The prototype sweep found this in 2 of 1600 cells (one case, for both $N_G = 1$ and $N_G = 4$): $\kappa \propto T_d^2$, gas at $0.01$, radiation at $1$, with roots at $T_d = 0.0114$, $0.134$ and $0.738$. The march from $T^0 = 0.01$ returns $0.0114$, the root continuously connected to cold dust in cold gas. This is the same selection rule the dust-free solver uses, and the same starting point Quokka uses.

## 4. The convergence test: on the state, not the residual

**The residual test fails.** $H$ has the same round-off amplification that Quokka's replaced variables were designed to avoid. The amplification now comes from the collision term instead of the radiation term: $\Delta t K \sqrt{T}(T - T_d)$ multiplies round-off in $T - T_d$ by $\Delta t K \sqrt{T}$. In the prototype sweep with tolerance $10^{-9}$, the test $|H| \le {\rm tol}\cdot E_{\rm tot}$ fails in 255 of the 320 cells at $\Delta t K / c_V = 10^8$. It fails even when $T_d$ is converged to $10^{-13}$, and it fails nowhere else. The answer is accurate; only the test is wrong.

**The test to use.** Conservation holds exactly by construction (§2), so the only thing left to control is how the energy is shared between gas and radiation. A bracketing method returns a final bracket $[T_d^-, T_d^+]$ that contains the root. So test the state across it:

$$\left|E_{\rm gas}(T_d^-) - E_{\rm gas}(T_d^+)\right| \le {\rm tol}\cdot E_{\rm tot} .$$

This bounds the error of the returned $E_{\rm gas}$, and through conservation the error of $\sum_g (c/\hat{c}_g)E_g$, by ${\rm tol}\cdot E_{\rm tot}$. It is not amplified by anything. It costs two extra evaluations of steps 1 and 2 (no root-finder call).

**The tolerance conversion.** The root-finder stops on bracket width in $T_d$. Start with `abstol` $= \tfrac12\,{\rm tol}\, T_d^+$. If the state test fails, re-solve on the returned bracket with `abstol` $= {\rm tol}\,E_{\rm tot} / (4\,|\Delta E_{\rm gas} / \Delta T_d|)$, using the slope measured across the current bracket. Repeat at most three times. The factor 4 is there because the root-finder stops at a half-width of `abstol`: a factor of 2 turns that into full width, and another factor of 2 is a margin for the slope changing across a wide first bracket. Without that margin, 21 cells failed. This is the same pattern as the dust-free solver's conversion, but it converts through $dE_{\rm gas}/dT_d$ instead of $dG/dE_{\rm gas}$.

## 5. Algorithm, per cell

1. Guess: $T_d \leftarrow \max(E_{\rm gas}^0 / c_V,\ T_{\rm floor})$.
2. March by factors of two on $H(T_d)$ until the sign changes. If no sign change is found, report the cell unconverged and keep the old state, as `BracketedCoupling` does.
3. `solve(IntervalNonlinearProblem(H, (lo, hi), s), root_finder; abstol, maxiters)`, with `Brent()` as the default.
4. Test the state across the final bracket and convert the tolerance (§4).
5. Set $E_g = E_g(T_d)$ and $E_{\rm gas} = E_{\rm gas}(T_d)$. Apply `apply_energy_floors`. Return $T_d$ too, because the flux update needs it (§7).

## 6. What the prototype shows

`julia --project=. docs/coupling-experiments/dust_prototype.jl` reproduces every number here.

**Sweep.** 1600 one-step cells: $N_G \in \{1, 4\}$; constant and $\kappa \propto T_d^2$ dust opacity; gas temperature $\{0.01, 0.3, 1, 10\}$; radiation temperature $\{0, 0.1, 1, 5\}$; $\tau = \Delta t\,\hat{c}\rho\kappa \in \{10^{-4}, 1, 10^4, 10^8, 10^{12}\}$; $\Delta t K / c_V \in \{0, 10^{-6}, 1, 10^4, 10^8\}$; tolerance $10^{-9}$.

| quantity | result |
|:---|:---|
| cells that failed to converge | 0 of 1600 |
| worst state error across the final bracket | $9.8\times10^{-10}\,E_{\rm tot}$ |
| march steps plus root-finder calls, mean per cell | 5.7 |
| cells with more than one root (scan of $H$ on 4000 points) | 2 (see §3) |
| residual-test failures with a $10^{-13}$-converged $T_d$ | 255, all at $\Delta t K / c_V = 10^8$ |

**Time accuracy.** Quokka's `RadDust` problem: $c = 10^8$, $\hat{c} = 10^7$, $\rho\kappa = 10^4$, $\Lambda^0_{\rm gd} n_{\rm H}^2 = 10^6$, $c_V = 1.5$, $T^0 = 1$, $E^0 = 0$, run to $t = 3\times10^{-5}$. It uses $B = aT^4$, not Quokka's linearised $B = aT$; see decision 4 in §8. The reference is the reduced ODE ($T_d$ solved inside the right-hand side) integrated with `Rodas5P` at `reltol = 1e-11`.

| $\Delta t$ | error in $T$ | error in $E$ | energy error |
|:---|:---|:---|:---|
| $10^{-7}$ | $5.2\times10^{-9}$ | $-5.6\times10^{-9}$ | $4\times10^{-16}$ |
| $10^{-8}$ | $5.0\times10^{-10}$ | $-5.7\times10^{-10}$ | $2\times10^{-15}$ |
| $10^{-9}$ | $1.1\times10^{-9}$ | $-1.2\times10^{-9}$ | $9\times10^{-16}$ |

The first two rows are first order in $\Delta t$. At $10^{-9}$ the $3\times10^4$ steps are limited by the per-step tolerance instead. The end time is near equilibrium, so these errors are small in absolute terms; the implemented test will compare the whole history, as Quokka's does.

**Limits.** At $\Delta t K / c_V = 10^{12}$, the dust solve reproduces the dust-free `BracketedCoupling` result to $6\times10^{-13}$ in $E_{\rm gas}$, with $|T_d/T - 1| \le 6\times10^{-13}$. At $K = 0$ the gas energy is unchanged to $6\times10^{-13}$. Both hold for $N_G = 1$ and $4$ and for constant and $\kappa \propto T^{-3/2}$ opacity.

## 7. Implementation plan

About 250 lines in `src/` and 200 in `test/`. About half a day, including the test problem.

**Physics: the dust model** (new file `src/dust.jl`, included after `opacity.jl`):

- `AbstractDustModel`; `NoDust()`, the default; `BateKetoDust(; coefficient, particle_mass = 1)`.
- `dust_gas_coefficient(d, rho) = d.coefficient * (rho / d.particle_mass)^2`, which is $K$. `particle_mass` is Quokka's `mean_molecular_mass`, so `coefficient` is Quokka's `dust_gas_interaction_coeff`, and $K$ is the same number in both codes.

**The state** (`src/coupling.jl`):

- `CouplingState` gets a `dust` field and a type parameter for it. The dust law travels on the state, like the opacity law.
- A new method `dust_energy_balance(s, Td) -> (H, Egas, Erad)`: steps 1–3 of §2, built only from `coupling_coefficients`, `_eliminate_groups` and `energy_balance`. There is no new physics formula except the collision rate.
- `CouplingResult` gets `Temit`: the temperature the emitting matter is at. It is $T$ without dust and $T_d$ with dust.

**The solver** (`src/coupling_solvers.jl`):

- A second `solve_coupling(m::BracketedCoupling, s)` method, dispatching on `s.dust isa BateKetoDust`. It uses the same `tolerance`, `max_iterations` and `root_finder`, so users choose the solver exactly as today.
- `_energy_bracket` gets the lower bound and the starting point as arguments. The dust-free call passes today's values.

**The driver** (`src/source_terms.jl`, `src/radiation_system.jl`):

- `RadiationPhysics` gets `dust = NoDust()`. The constructor throws an `ArgumentError` if a dust model is combined with `QuokkaCoupling` or `AdaptiveCoupling` (see decision 2).
- `multigroup_source_step!` evaluates the flux-mean opacity, the Planck term in `_beta_force`, and the work term at `res.Temit` instead of at the gas temperature. Quokka does the same (`ComputeModelDependentKappaFAndDeltaTerms(T_d, …)`). The first work estimate uses $T^0$, as it does now.
- The grey driver (`NG = 1`, the inline 2×2 Newton) has no dust. Its dispatch is narrowed to `NoDust`, so a grey run with dust goes to `multigroup_source_step!`, which works unchanged for one group. Grey runs without dust are not affected.

**Tests** (`test/test_dust.jl`, new):

- Both limits of §6, as invariants: at large $K$ the result equals dust-free `BracketedCoupling`; at $K = 0$ the gas is unchanged.
- Exact energy conservation on every cell of a small sweep, and 0 failures on it.
- The multi-root cell: the march returns the root near cold dust.
- 0 bytes allocated per cell, added to `test_performance.jl`.
- `RadDust` end to end against the `Rodas5P` reference of §6, over the whole history.

**Problems and docs:**

- `Problems.rad_dust` (grey), and `rad_dust_mg` (Quokka's 4-group `RadDustMG`), if you want it.
- Results appended to this file.
- A CLAUDE.md paragraph under "The multigroup coupling solvers".

**Not planned:** photoelectric heating, cosmic-ray heating, line cooling; gas and dust opacity at the same time (§8, decision 3); storing $T_d$ between steps (§8, decision 5).

## 8. Decisions (all five recommendations accepted)

1. **The API shape.** Recommended: `RadiationPhysics(…; dust = BateKetoDust(coefficient = 1e6))`. Dust is part of the physics, not the solver, and `coupling = BracketedCoupling()` stays the solver choice. The alternative, a separate `DustCoupling <: AbstractCoupling`, would mix physics and solver in one type.
2. **The other two solvers.** Recommended: dust is supported by `BracketedCoupling` only, and the constructor refuses the other combinations. `QuokkaCoupling` with dust would mean porting Quokka's two-regime Newton, which this plan exists to replace. `AdaptiveCoupling` with dust would need an inner $T_d$ solve inside every right-hand-side evaluation, plus its implicit-function Jacobian. That is a useful reference, but the test can build its own reference, as §6 does.
3. **Gas opacity together with dust.** Recommended: not now. The draft and Quokka both assume the gas has no opacity when the dust model is on. Supporting both at once would bring back two temperatures in the emission, and then no single-variable closed form exists. It would need a nested bracket.
4. **The `RadDust` reference.** Quokka's test replaces $B = aT^4$ by $B = aT$, so that its exact solution can be written down. Honghu has no hook to override the emission law. Recommended: keep $aT^4$ and use the `Rodas5P` reference of §6, which the test can compute in a few seconds. The alternative is an emission-law hook, which is a new API for one test.
5. **The initial guess for $T_d$.** Recommended: $T^0$, as Quokka does. Storing $T_d$ as a diagnostic field would give a better starting point, and root continuity across steps in the multi-root case, but it adds a field to the state arrays.

## 9. Implementation and results

The code follows §7. The only difference from the plan is in method dispatch. The dust-free `solve_coupling` methods of all three solvers are now written for `CouplingState{…,NoDust}`, and one fallback `solve_coupling(::AbstractCoupling, ::CouplingState{…,<:BateKetoDust})` throws `ArgumentError`. With the methods left general, Julia reported the `BracketedCoupling` dust method as ambiguous. A hand-built dust state handed to `QuokkaCoupling` or `AdaptiveCoupling` now fails loudly; it cannot be solved as if there were no dust.

| file | what |
|:---|:---|
| `src/dust.jl` | `AbstractDustModel`, `NoDust`, `BateKetoDust(; coefficient, particle_mass = 1)`, `dust_gas_coefficient` |
| `src/coupling.jl` | `CouplingState` gains `dust` (the old 15-argument constructor still works and means `NoDust`); `CouplingResult` gains `Tdust` (`NaN` without dust); `dust_energy_balance(s, Td) -> (H, Egas, Erad)` |
| `src/coupling_solvers.jl` | the `BateKetoDust` method of `solve_coupling(::BracketedCoupling, …)`; `_energy_bracket(G, s, x0, xmin)` |
| `src/radiation_system.jl` | `RadiationPhysics(; dust = NoDust())`, and the refusal of any other solver |
| `src/source_terms.jl` | the grey driver is `NoDust` only; the multigroup driver passes the dust model and evaluates the flux opacity and $B$ at `res.Tdust` |
| `src/problems/radiation.jl` | `Problems.rad_dust(; groups)` and `Problems.rad_dust_reference(ts; groups)` |
| `test/test_dust.jl` | the tests below |

`H` is defined as the negative of §2's, so that it increases with $T_d$. The march and the root-finder are then the same ones the dust-free equation uses.

**Tests** (58 new, and the suite passes 1401 of 1401):

- A sweep of 432 cells ($N_G \in \{1,4\}$; two opacity laws; gas temperature, radiation temperature, $\rho$ and $K$ spread over the regimes of §6): 0 failures, worst relative energy error below $10^{-13}$, and the state within $1.01\times10^{-9}\,E_{\rm tot}$ of a solve at tolerance $10^{-12}$. A mutation check confirms the width test matters: with the residual test instead, this sweep reports 127 cells unconverged.
- $K \to \infty$ equals dust-free `BracketedCoupling` to $10^{-11}$, and $K = 0$ leaves the gas unchanged with the dust balance satisfied.
- The multi-root cell of §3 returns $T_d \in (0.0113, 0.0115)$.
- The `ArgumentError`s, and 0 bytes per cell (`test_dust.jl`, and `test_performance.jl` through the full grey driver with dust and `beta_order = 1`).
- `RadDust` over the full history against `rad_dust_reference`, grey and with `RadDustMG`'s four groups: relative L1 error $2.2\times10^{-4}$ for both (Quokka's tolerance is $3\times10^{-3}$), 0 failures, 5.1 iterations per cell on average, 8 at most, about 1 s for 3000 steps.


---

<!-- page: coupling-findings.md -->

# The matter-radiation coupling: three ways to solve it, and what the measurements say

> **Update, 2026-09-24 — what was decided.** The measurements below stand exactly as taken. The code they describe has since changed in response to them, and some of the names in them no longer exist.
>
> - **`BracketedCoupling` — §5's scalar reduction — is now in `src/coupling_solvers.jl`, and is the package default.** Verified in place: 0 bytes per cell at 1 to 16 groups, and 0 failures over the same 240 cells.
> - **`DirectCoupling` and its two steppers are deleted**, and with them `newton_solve` and two `[deps]` entries, `OrdinaryDiffEqSDIRK` and `OrdinaryDiffEqNonlinearSolve`, which existed only to name `ImplicitEuler` and `NLNewton`.
> - **`QuokkaCoupling` stays**, no longer as the default, for fidelity to Quokka and as the independent cross-check: one unknown against $1 + N_G$, sharing no residual, no iteration and no linear solve. **`AdaptiveCoupling` is untouched** — §5.5's caveat is why, since `Rosenbrock23` is linearly implicit and has no nonlinear stage to bracket.
> - **The single source of truth moved down a level**, to `coupling_coefficients`: the per-group emission rate $\varepsilon_g = \rho\kappa_{P,g}B_g$ and absorption coefficient $\alpha_g = \rho\kappa_{E,g}$. `coupling_rhs` / `coupling_jacobian` and `group_energies` / `energy_balance` are both built from it, so the rate and the elimination cannot drift apart. That is what §5.7 asked for.
> - **Update, 2026-09-28: `BracketedCoupling`'s scalar equation now goes to a generic root-finder**, first SciML's BracketingNonlinearSolve and then `ZBrent` (`src/rootfind.jl`), Brent's method as Numerical Recipes' `zbrent` writes it, replacing the hand-written Newton-in-bracket of §5.6. The library's `Brent` lacks the minimum step and evaluates twice per iteration, and took 20.1 evaluations of $G$ a cell against `ZBrent`'s 7.7; `docs/coupling-new-method.md` §5 has the comparison. Since 2026-10-17 the default is the library's own `Brent` again: the fix went upstream in BracketingNonlinearSolve 1.12.8, and `ZBrent` is gone. Derivative-free is the better fit even though $dG/dE_\mathrm{gas}$ is known: a value-only evaluation skips the Planck integral's temperature derivative, so about 12 of them take 0.57 of the time of the 9 value-and-derivative ones. Adopting it surfaced the multi-root case §5.8 warns about on one sweep cell ($\kappa \propto T^{2}$, gas at 0.1, radiation at 3, roots at 0.110, 1.17 and 2.52, ODE trajectory 0.109): which root came back from the wide bracket $[c_V T_\mathrm{floor}, \mathcal{E}]$ depended on the method. The bracket is now marched outward from $E_\mathrm{gas}^0$ by factors of two, which isolates the root connected to the old state; every method then agrees to $10^{-9}$ over all 240 cells.
>
> One row of the tables below is no longer reproducible by the script, `natural, ImplicitEuler`, because the dependency went with it; it re-runs at commit `2190e3c` or earlier. `natural, resid+raise` is now produced by `PlainDirect(test = :residual, raise = true)`, which applies the identical tolerance rule. Everything else re-runs unchanged.

Honghu ships three solvers for the per-cell matter-radiation energy exchange, and the point of having three is to be able to measure what each one is worth. This document does that. The three are `QuokkaCoupling` (backward Euler in Quokka's replaced base variables), `DirectCoupling` (backward Euler in the natural base variables, by either of two steppers), and `AdaptiveCoupling` (an error-controlled stiff ODE solve). Everything below is reproduced by `docs/coupling-experiments/coupling_study.jl`, which also defines two further steppers that are deliberately *not* in `src/` — a natural-variable Newton with a switchable convergence test, and a bracketed scalar solver — because the argument turns on them.

The headline, stated up front so the rest can be read as evidence for it:

1. The two backward-Euler solvers are **the same nonlinear system**, written in two sets of unknowns. Any difference between them is floating point, not mathematics.
2. The round-off amplification that motivates Quokka's replaced variables is **real and exactly as large as claimed** — at Quokka's own default tolerance of $10^{-11}$ the natural-variable residual test starts failing at $\tau_\mathrm{cell} \approx 10^5$ and fails everywhere by $3\times10^5$.
3. But what the amplification breaks is the **convergence test, not the answer**. The iteration that "fails" is sitting on the right root, to $10^{-16}$ of the cell's energy. Dividing the group residual by its own Jacobian diagonal — one line — removes the amplification completely, without changing the base variables, and delivers a *more* accurate answer than the replaced variables do.
4. Where a one-step backward Euler genuinely fails is **not round-off but the nonlinearity of a temperature-dependent opacity** — and there the replaced variables are markedly *worse*: 36 failures out of 66 cases on a $\kappa \propto T^{-3.5}$ sweep, against 0 for a damped natural-variable Newton.
5. Reducing the natural-variable system to **one scalar equation with a guaranteed bracket** gives a solver that converged in all 240 sweep cases and in every test problem, at zero allocation and $O(N_G)$ per iteration. It is the only one-step solver that gets the hardest test problem here right. §5 derives it in full and says what shipping it would take; the note above says what was then shipped.
6. The error-controlled ODE solve never fails and is 2 to 6 orders of magnitude more accurate in the intermediate regime, at 12 times the cost of a hand-written Newton step on its loosest setting and several hundred times on a tight one, plus 8 to 21 kB of allocation per cell. It is a reference solver, and should stay one.

## 1. The three methods, and why two of them are one method

Per cell, the coupling is a stiff ODE in the gas internal energy and the $N_G$ group radiation energies,

$$\frac{dE_\mathrm{gas}}{dt} = -c\,\rho \sum_g \left(\kappa_{P,g} B_g(T) - \kappa_{E,g} E_g\right), \qquad \frac{dE_g}{dt} = +\hat c\,\rho \left(\kappa_{P,g} B_g(T) - \kappa_{E,g} E_g\right),$$

writing $B_g$ for $4\pi B_g/c = a_\mathrm{rad} T^4 f_g(T)$. Two of the three solvers take one backward-Euler step of this over $\Delta t$; the third integrates it with an adaptive stiff method and error control.

**Natural base variables.** The unknowns are $(E_\mathrm{gas}, E_g)$ and the residual is $u - u^0 - \Delta t\, f(u)$, so with $\tau_g = \Delta t\,\hat c\,\rho\,\kappa_{P,g}$ and $a_g = \Delta t\,\hat c\,\rho\,\kappa_{E,g}$ the group equation reads

$$F_g = \left(E_g - E_g^0\right) - \tau_g B_g(T) + a_g E_g = 0 .$$

**Quokka's replaced base variables.** The unknowns are $(E_\mathrm{gas}, R_g)$, where $R_g$ is the energy handed from gas to group $g$ over the whole step,

$$R_g = \Delta t\,\hat c\,\rho\left(\kappa_{P,g} B_g(T) - \kappa_{E,g} E_g\right) + W_g ,$$

with $W_g$ the lagged $\boldsymbol{v}\cdot\boldsymbol{F}$ work term. The residuals are $F_0 = (E_\mathrm{gas} - E_\mathrm{gas}^0) + (c/\hat c)\sum_g R_g$ and $F_g = (E_g - E_g^0) - (R_g + S_g)$, and $E_g$ is recovered from $R_g$ in closed form as $E_g = (\kappa_{P,g}/\kappa_{E,g})\left(B_g - (R_g - W_g)/\tau_g\right)$.

Substituting that closed form back into $F_g$ returns the natural-variable group equation term for term, and substituting it into $F_0$ returns the natural-variable gas equation. **The two are the same nonlinear system.** The measurement agrees: in 256-bit arithmetic the two formulations land on the same root to better than $10^{-40}$, and in double precision their answers agree to $10^{-11}$ or better at every optical depth from $10^{-4}$ to $10^{12}$ (§6, columns "BE Quokka" and "BE natural"). This matters because it fixes what the comparison can possibly be about: not accuracy of the discretisation, only conditioning and iteration behaviour.

Quokka has a further switch, `use_D_as_base`, which rescales the unknown to $D_g = R_g/\tau_g^{(0)}$. It is `false` by default, and it is a diagonal rescaling of the unknowns, to which Newton's method is invariant in exact arithmetic — so it changes step-length bookkeeping and floating-point detail, not the method. Honghu's `QuokkaCoupling` implements the production default, $R_g$.

**Error-controlled ODE solve.** `AdaptiveCoupling` hands the same right-hand side and the same analytic Jacobian to an adaptive stiff integrator (`Rosenbrock23` by default) over $[0, \Delta t]$, and lets it choose its own internal steps. It is not a discretisation of the coupling with a fixed error; it is a statement of what the coupling ODE's answer actually is, to a tolerance you ask for.

## 2. The conditioning claim is right, and this is how big it is

The natural-variable Newton matrix has a condition number proportional to $\tau_\mathrm{cell}$. The replaced-variable one does not. Measured at the exact root, four groups, constant opacity:

| $\tau_\mathrm{cell}$ | cond, natural | cond, replaced | residual noise / $E_\mathrm{tot}$ | $\varepsilon\,\tau_\mathrm{cell}$ |
|---:|---:|---:|---:|---:|
| $10^{-4}$ | 1.00 | $9.99\times10^{3}$ | $2.9\times10^{-17}$ | $2.2\times10^{-20}$ |
| $10^{-2}$ | 1.10 | $9.37\times10^{1}$ | $4.1\times10^{-17}$ | $2.2\times10^{-18}$ |
| $10^{0}$ | 6.24 | 2.51 | $1.2\times10^{-16}$ | $2.2\times10^{-16}$ |
| $10^{2}$ | $5.04\times10^{2}$ | 3.36 | $8.4\times10^{-15}$ | $2.2\times10^{-14}$ |
| $10^{4}$ | $5.04\times10^{4}$ | 3.39 | $5.5\times10^{-13}$ | $2.2\times10^{-12}$ |
| $10^{6}$ | $5.04\times10^{6}$ | 3.39 | $1.6\times10^{-10}$ | $2.2\times10^{-10}$ |
| $10^{8}$ | $5.04\times10^{8}$ | 3.39 | $5.6\times10^{-9}$ | $2.2\times10^{-8}$ |
| $10^{9}$ | $5.04\times10^{9}$ | 3.39 | $3.5\times10^{-8}$ | $2.2\times10^{-7}$ |
| $10^{10}$ | $5.04\times10^{10}$ | 3.39 | $1.1\times10^{-6}$ | $2.2\times10^{-6}$ |
| $10^{12}$ | $5.04\times10^{12}$ | 3.39 | $1.4\times10^{-4}$ | $2.2\times10^{-4}$ |

The fourth column is the measurement that matters: it is the natural-variable residual evaluated **at the exact root**, in double precision, in units of the cell's total energy. It should be zero and it is not, because at the root $B_g$ and $E_g$ agree to round-off and the difference $\tau_g(B_g - E_g)$ is a cancellation whose absolute error is $\varepsilon\,\tau_g B_g$. Measured, the noise is $0.2$ to $0.7$ times $\varepsilon\,\tau_\mathrm{cell}$ — it is one realisation of a rounding error, so the prefactor wanders, but the $\tau$ scaling holds across sixteen orders of magnitude. Asking a residual test for $10^{-9}$ at $\tau = 10^{12}$ asks for a number ten million times smaller than the noise in computing it.

Note also the first two rows of the third column. The replaced variables are ill-conditioned in the *optically thin* limit, where $J_{gg} = -\kappa_P/(\kappa_E \tau_g) - 1$ blows up — which is precisely why Quokka carries an explicit optically-thin shortcut and Honghu's `QuokkaCoupling` carries the same one. Each set of base variables has a limit it cannot see through, and each carries a patch for it; they are just at opposite ends of the $\tau$ axis.

Where the natural-variable residual test gives up, as a function of the tolerance it is asked for, over eight initial states at four groups:

| $\tau_\mathrm{cell}$ | tol $10^{-7}$ | tol $10^{-9}$ | tol $10^{-11}$ | tol $10^{-13}$ |
|---:|---:|---:|---:|---:|
| $10^{3}$ | 0/8 | 0/8 | 0/8 | 3/8 |
| $10^{4}$ | 0/8 | 0/8 | 0/8 | 8/8 |
| $10^{5}$ | 0/8 | 0/8 | 4/8 | 8/8 |
| $3\times10^{5}$ | 0/8 | 0/8 | 8/8 | 8/8 |
| $10^{6}$ | 0/8 | 0/8 | 8/8 | 8/8 |
| $10^{7}$ | 0/8 | 1/8 | 8/8 | 8/8 |
| $3\times10^{7}$ | 0/8 | 5/8 | 8/8 | 8/8 |
| $10^{8}$ | 0/8 | 8/8 | 8/8 | 8/8 |
| $10^{9}$ | 2/8 | 8/8 | 8/8 | 8/8 |

The replaced variables give 0/8 in every one of those cells, at every tolerance down to $10^{-13}$ and at $\tau$ up to $10^{12}$.

Quokka's default `radiation_iteration_tolerance` is $10^{-11}$, and the table says the onset at that tolerance is $\tau_\mathrm{cell} \approx 10^{5}$, with total failure by $3\times10^{5}$. That is the number in this project's folklore, now measured rather than estimated. The rule $\tau_\mathrm{cell} \gtrsim \mathrm{tol}/(0.6\,\varepsilon)$ predicts the first failure in every column of the table to within 30%: $7.5\times10^{8}$, $7.5\times10^{6}$, $7.5\times10^{4}$ and $7.5\times10^{2}$ against measured onsets of $10^{9}$, $10^{7}$, $10^{5}$ and $10^{3}$.

## 3. What the amplification actually costs is the test, not the answer

The natural-variable iteration that "fails" in the table above is sitting on the correct root. The table below measures it: at every $\tau$ from $10^{8}$ to $10^{12}$ the residual test burns 100 iterations instead of 7, reports `converged = false`, and hands back an answer within $10^{-16}$ of the cell's energy of the exact root — machine precision.

The reason is that **the same $\tau_g$ that amplifies the residual sits on the Jacobian's diagonal and divides it back out.** For the group block, $\partial F_g/\partial E_g = 1 + a_g$, so the Newton increment for that group is $\delta E_g \approx -F_g/(1 + a_g)$. Noise of size $\varepsilon\,\tau_g B_g$ in $F_g$ becomes noise of size $\varepsilon\,B_g$ in the increment. The amplification and the de-amplification are the same factor, and only the convergence test — which reads the un-preconditioned residual — sees the amplified one.

That is a stronger statement than "the amplification is tolerable". It says the failure mode is a *false report of non-convergence*, and the cure is to fix the report. Three ways to do that, all in the natural variables, at a tolerance held fixed at $10^{-9}$ with no automatic degradation, four groups, constant opacity (error in units of cell energy; `!` marks a reported failure):

| $\tau_\mathrm{cell}$ | residual | it | scaled residual | it | increment | it | `ImplicitEuler` | it |
|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| $10^{0}$ | $6.9\times10^{-17}$ | 6 | $6.9\times10^{-17}$ | 6 | $6.9\times10^{-17}$ | 6 | $6.9\times10^{-17}$ | 6 |
| $10^{2}$ | $1.9\times10^{-12}$ | 6 | $1.9\times10^{-12}$ | 6 | $9.4\times10^{-17}$ | 6 | $9.9\times10^{-17}$ | 6 |
| $10^{4}$ | $2.3\times10^{-17}$ | 7 | $2.1\times10^{-12}$ | 6 | $2.3\times10^{-17}$ | 6 | $9.6\times10^{-17}$ | 6 |
| $10^{6}$ | $7.5\times10^{-17}$ | 7 | $2.1\times10^{-12}$ | 6 | $7.5\times10^{-17}$ | 6 | $1.3\times10^{-16}$ | 6 |
| $10^{7}$ | $4.5\times10^{-17}$ | 7 | $2.1\times10^{-12}$ | 6 | $4.5\times10^{-17}$ | 6 | $3.5\times10^{-17}$ | 6 |
| $10^{8}$ | $6.5\times10^{-17}$ | 100 ! | $2.1\times10^{-12}$ | 6 | $4.7\times10^{-17}$ | 6 | $1.2\times10^{-16}$ | 6 |
| $10^{9}$ | $2.9\times10^{-17}$ | 100 ! | $2.2\times10^{-12}$ | 6 | $4.6\times10^{-17}$ | 6 | $2.1\times10^{-17}$ | 6 |
| $10^{10}$ | $6.0\times10^{-17}$ | 100 ! | $4.2\times10^{-12}$ | 6 | $1.0\times10^{-16}$ | 6 | $6.0\times10^{-17}$ | 6 |
| $10^{12}$ | $8.5\times10^{-17}$ | 100 ! | $3.0\times10^{-10}$ | 6 | $2.5\times10^{-15}$ | 6 | $3.1\times10^{-15}$ | 6 |

The **scaled residual** test — stop on $\max_i |F_i / J_{ii}| \le \mathrm{tol}\cdot E_\mathrm{tot}$ instead of $\max_i |F_i|$ — is one line and it removes the $\tau$ dependence entirely: six iterations at every optical depth, exactly like the replaced variables. The **increment** test does the same and is more accurate, because it takes the step before testing it, so it delivers the extra Newton iteration for free.

The last column is worth noting for what it says about the code as it stands. `DirectCoupling`'s default stepper, OrdinaryDiffEq's `ImplicitEuler`, measures its own increment rather than the residual, so it is immune already — and this column is it run at the *un-raised* tolerance, bypassing the automatic degradation `DirectCoupling` applies. It never needed that degradation. The degradation is there for the hand-written `NewtonStepper`, which tests the residual, and the better fix for that stepper is the scaled test, because raising the tolerance to $4\varepsilon\tau$ makes the failures go away by *asking for less* rather than by asking correctly. The cost shows up in the sweep of §4: with the tolerance raise the worst error over 80 cases is $2.3\times10^{-10}$, and with the increment test it is $1.6\times10^{-14}$.

## 4. Where backward Euler really fails: the opacity, not the arithmetic

The sweep is 8 initial gas/radiation temperature pairs $\times$ 10 optical depths from $10^{-4}$ to $10^{12}$ $\times$ 3 opacity laws, at four groups. Each case is scored against the exact root of its own backward-Euler system, computed in 256-bit arithmetic and verified by evaluating its own residual there. Cases where even that 256-bit solve could not be verified are excluded and counted separately.

**Constant opacity — 80 cases, all references verified.**

| method | failures | worst error | mean iterations |
|:---|---:|---:|---:|
| Quokka, $R$ base | 0/80 | $9.2\times10^{-11}$ | 5.7 |
| natural, residual test | 32/80 | $2.3\times10^{-10}$ | 8.4 |
| natural, residual + tolerance raise (as shipped) | 0/80 | $2.3\times10^{-10}$ | 9.5 |
| natural, increment test | 0/80 | $1.6\times10^{-14}$ | 9.0 |
| natural, increment + damping | 0/80 | $6.7\times10^{-15}$ | 6.3 |
| natural, bracketed scalar | 0/80 | $3.2\times10^{-10}$ | 9.2 |
| natural, `ImplicitEuler` | 0/80 | $2.7\times10^{-8}$ | 9.0 |
| adaptive, $10^{-2}$ | 0/80 | — | 20.3 |
| adaptive, $10^{-8}$ | 0/80 | — | 589.5 |

With a constant opacity, only the naive residual test fails, and only at $\tau \ge 10^{8}$ — which is the whole of the round-off story. Everything else in the table is a tie.

**$\kappa \propto T^{-3.5}$ — 66 cases scored, 14 with no verifiable reference.**

| method | failures | worst error | mean iterations |
|:---|---:|---:|---:|
| Quokka, $R$ base | **36/66** | $9.9\times10^{-1}$ | 6.2 |
| natural, residual test | 20/66 | $6.2\times10^{-1}$ | 9.2 |
| natural, residual + tolerance raise | 1/66 | $6.2\times10^{-1}$ | 10.0 |
| natural, increment test | 0/66 | $6.2\times10^{-1}$ | 9.6 |
| natural, increment + damping | 0/66 | $4.8\times10^{-14}$ | 8.6 |
| natural, bracketed scalar | **0/66** | $7.9\times10^{-10}$ | 7.4 |
| natural, `ImplicitEuler` | 0/66 | $6.2\times10^{-1}$ | 10.4 |
| adaptive, $10^{-2}$ | 0/66 | — | 21.2 |

**$\kappa \propto T^{+2}$ — 55 cases scored, 25 with no verifiable reference.**

| method | failures | worst error | mean iterations |
|:---|---:|---:|---:|
| Quokka, $R$ base | 1/55 | $3.9\times10^{-1}$ | 6.4 |
| natural, residual test | 20/55 | $7.4\times10^{-10}$ | 7.1 |
| natural, residual + tolerance raise | 0/55 | $7.4\times10^{-10}$ | 8.1 |
| natural, increment test | 0/55 | $4.4\times10^{-16}$ | 7.8 |
| natural, increment + damping | 1/55 | $3.6\times10^{-1}$ | 7.5 |
| natural, bracketed scalar | **0/55** | $6.9\times10^{-10}$ | 6.1 |
| natural, `ImplicitEuler` | 0/55 | $5.4\times10^{-10}$ | 7.7 |
| adaptive, $10^{-2}$ | 0/55 | — | 21.1 |

Three things to take from these two tables, and the first is the one that changes the picture.

**The replaced base variables are less robust, not more, once the opacity moves with temperature.** 36 failures out of 66, with errors up to 99% of the cell's energy. The mechanism is visible in the formulation: $E_g$ is not an unknown but is *derived* from $R_g$ through $\tau_g(T)$, so when $\kappa$ swings by orders of magnitude between iterates the implied group energies swing with it, and there is nothing holding them. The natural variables keep $E_g$ as an independent unknown that only moves by a Newton step. Written the other way round: $R_g$ is a well-scaled unknown exactly while $\tau$ is nearly constant over the iteration, which is what a constant opacity guarantees and a realistic one does not.

**A worst error of 0.62 alongside "0 failures" is worse than a failure.** The plain increment test and `ImplicitEuler` both report success on cases where they are 62% wrong. An increment test cannot distinguish "the iteration has converged" from "the iteration has stalled", and both stall against the temperature floor, where $\kappa \propto T^{-3.5}$ is $10^{35}$ and nothing recovers. The damped variant — which forbids the gas energy leaving $[\max(E_\mathrm{floor}, x/4),\, 4x]$ in one step — fixes this case entirely ($4.8\times10^{-14}$), and is one `while` loop.

**But damping is not a general answer.** It fails one $\kappa \propto T^{+2}$ case, and that failure is instructive: with a strongly absorbing temperature-dependent opacity, $\partial(\kappa_P B_g - \kappa_E E_g)/\partial T$ can change sign, so the scalar residual is not monotone and the Newton direction points *away* from the root from the very first iterate. Tracing that cell, the iteration walks the gas energy from $0.5$ down through $10^{-6}$, halving each step, while the root is at $1.21$. No step-length rule saves an iteration whose direction is wrong. Both bases do this; it is the physics of the residual, not the choice of unknown.

## 5. A natural-variable backward Euler that does not fail

This section derives the method in full, because the idea is simple but the reason it works is not the obvious one. It is **not implemented in `src/`**: it lives as `BracketedDirect` in `docs/coupling-experiments/coupling_study.jl`, as an ordinary `AbstractCoupling` subtype with its own `solve_coupling` method, so it can be passed as `RadiationPhysics(coupling = BracketedDirect())` and was run that way for every number below. §5.7 says what moving it into the tree would take.

### 5.1 The system, written out

Write the two step-constant increments the driver supplies — the external radiation source $S_g$ and the lagged $\boldsymbol{v}\cdot\boldsymbol{F}$ work term $W_g$ — into the old state, exactly as `backward_euler` does at `src/coupling_solvers.jl:361-363`:

$$\mathrm{gas0} = E_\mathrm{gas}^0 - \sum_g \frac{c}{\hat c_g} W_g , \qquad \mathrm{rad0}_g = E_g^0 + S_g + W_g .$$

Define the two optical depths of the step, one for emission and one for absorption,

$$\tau_g(T) = \Delta t\,\hat c_g\,\rho\,\kappa_{P,g}(T) , \qquad a_g(T) = \Delta t\,\hat c_g\,\rho\,\kappa_{E,g}(T) .$$

The backward-Euler system $u - u^0 - \Delta t\,f(u) = 0$ is then, with $T = E_\mathrm{gas}/c_V$,

$$F_g = \left(1 + a_g\right) E_g - \mathrm{rad0}_g - \tau_g B_g(T) = 0 , \qquad g = 1 \ldots N_G,$$

$$F_0 = \left(E_\mathrm{gas} - \mathrm{gas0}\right) + \sum_g \frac{c}{\hat c_g}\left(\tau_g B_g(T) - a_g E_g\right) = 0 .$$

The gas equation picks up $c/\hat c_g$ per group because the exchange rate is formed once and then scaled by $\hat c_g$ on the radiation side and by $c$ on the gas side — that asymmetry is the reduced speed of light approximation itself.

### 5.2 Step 1: the group block is linear, so eliminate it

Nothing in $F_g$ couples group $g$ to group $h$: the groups meet only through $T$. So **at a fixed $E_\mathrm{gas}$ the group block is $N_G$ independent linear equations**, and they can be solved outright rather than iterated on,

$$\boxed{\;E_g(T) = \frac{\mathrm{rad0}_g + \tau_g(T)\,B_g(T)}{1 + a_g(T)}\;}$$

which is `coupling_study.jl:196`. In this code $\kappa_{P,g} = \kappa_{E,g}$, because the multigroup opacity is piecewise constant across a group and averaging a constant against any weight returns it (`coupling_opacity`, `src/coupling.jl`), so $\tau_g = a_g$ and the formula reads

$$E_g(T) = \frac{1}{1+\tau_g}\,\mathrm{rad0}_g \;+\; \frac{\tau_g}{1+\tau_g}\,B_g(T) ,$$

a **convex combination of where the group started and the Planck value at the gas temperature**, with the weight set by the optical depth of the step. At $\tau_g \to 0$ the group keeps its energy; at $\tau_g \to \infty$ it is in equilibrium with the gas. That single line contains the whole of the stiffness, and it is exact.

### 5.3 Step 2: what remains is energy conservation

Rearranging $F_g = 0$ gives $\tau_g B_g - a_g E_g = E_g - \mathrm{rad0}_g$: the net energy the gas hands to group $g$ over the step is just the change in that group's energy. Substituting that into $F_0$ collapses the emission and absorption terms and leaves one scalar equation in one unknown,

$$G(E_\mathrm{gas}) \;\equiv\; \left. F_0 \right|_{E_g = E_g(T)} \;=\; \left(E_\mathrm{gas} - \mathrm{gas0}\right) + \sum_g \frac{c}{\hat c_g}\left(E_g(T) - \mathrm{rad0}_g\right) = 0 ,$$

which is `coupling_study.jl:198`. Expanding `gas0` and `rad0` shows that the work term cancels out of $G$ entirely — it survives only inside $E_g(T)$, through $\mathrm{rad0}_g$ — and that what is left is the statement that the cell's total energy does not change:

$$G(E_\mathrm{gas}) = E_\mathrm{gas} + \sum_g \frac{c}{\hat c_g} E_g(T) \;-\; \mathcal{E} , \qquad \mathcal{E} \equiv E_\mathrm{gas}^0 + \sum_g \frac{c}{\hat c_g}\left(E_g^0 + S_g\right) .$$

$G$ is (new total energy) minus (old total energy). That is worth saying plainly, because it is what makes the next step easy: we are not looking for the root of an abstract residual, we are looking for the gas energy at which the books balance.

### 5.4 Step 3: the bracket, and why it always exists

One thing to fix before the algebra, because it is the easiest step to misread. $G$ is a *function of a trial value* of $E_\mathrm{gas}$, not a statement about the cell. We are free to evaluate it anywhere, including at gas energies the cell could never actually have, and that is exactly what bracketing means: probe below the answer and above it, and check that the sign differs. The probe points below are deliberately too cold and the probe points above are deliberately impossible.

**Lower end: probe $E_\mathrm{gas} = c_V T_\mathrm{floor}$, too cold to be the answer.** Every $B_g(T) \to 0$ there, and $E_g$ is a convex combination of $\mathrm{rad0}_g$ and $B_g$, so $E_g \le \mathrm{rad0}_g$. Hence

$$G(c_V T_\mathrm{floor}) \;\le\; c_V T_\mathrm{floor} + \sum_g \frac{c}{\hat c_g}\,W_g - E_\mathrm{gas}^0 \;\le\; 0 ,$$

the last step holding whenever the gas starts above its own floor and the work term does not by itself exceed the gas energy. With $W_g = 0$ — every run in this study, and any run with `beta_order = 0` — it is unconditional, because the state is admissible between steps. It also needs $\kappa_{P,g}B_g \to 0$ as $T \to 0$, which holds for any $\kappa \propto T^n$ with $n > -4$ and for any physical opacity.

**Upper end: probe $E_\mathrm{gas} = \mathcal{E}$, the whole cell's energy in the gas.** That state is impossible — the gas cannot hold every erg in the cell while the radiation still holds some — and its impossibility is the point, because it is what forces the sign. Put $E_\mathrm{gas} = \mathcal{E}$ into

$$G(E_\mathrm{gas}) = E_\mathrm{gas} + \sum_g \frac{c}{\hat c_g} E_g(T) - \mathcal{E}$$

and the first and last terms cancel outright, leaving

$$G(\mathcal{E}) \;=\; \sum_g \frac{c}{\hat c_g}\,E_g\!\left(T = \mathcal{E}/c_V\right) \;\ge\; 0 .$$

No inequality was needed and no property of the opacity entered. The probe point was chosen so that the only thing left is a sum of group energies, and those are non-negative whenever $\mathrm{rad0}_g \ge 0$, since $E_g = (\mathrm{rad0}_g + \tau_g B_g)/(1+a_g)$ with $\tau_g, a_g, B_g \ge 0$. Read physically: *ask the gas to hold the whole cell's energy and the radiation still has energy left over, so the books over-balance* — $G > 0$. Checked over the 240 sweep cases, that identity holds to one ulp and $[c_V T_\mathrm{floor},\, \mathcal{E}]$ brackets the root in every one.

The one way $\mathrm{rad0}_g = E_g^0 + S_g + W_g$ can go negative is a lagged work term more negative than the group's own energy, which is the same failure mode that used to drain cells in `QuokkaCoupling` (see the end of `test/test_radiation_multigroup.jl`). So the code does not rely on the bound being tight: it starts the upper probe at $\max(4\mathcal{E},\, 4E_\mathrm{gas}^0)$, widens it by factors of four while $G$ is still negative (`coupling_study.jl:220-224`), and then checks both ends and returns `converged = false` rather than guessing if the sign change is still not there (`:225`). That branch never fired.

**So $G$ is non-positive at $c_V T_\mathrm{floor}$, non-negative at $\mathcal{E}$, and continuous in between, and therefore has a root there.** That also settles the physical question the upper probe skirted: because the root lies below $\mathcal{E}$, the solved gas energy never exceeds the cell's total — as it must not. Bisection alone would converge on this bracket; Newton inside it converges fast and cannot leave.

### 5.5 Step 4: the elimination fixes the Newton *direction*, not just the step length

This is the part that matters, and it is not what "add a bracket" suggests. Differentiating $E_g(T)$ and using $E_g(1+a_g) = \mathrm{rad0}_g + \tau_g B_g$,

$$\frac{dG}{dE_\mathrm{gas}} = 1 + \sum_g \frac{c}{\hat c_g}\frac{1}{c_V}\frac{dE_g}{dT} , \qquad \frac{dE_g}{dT} = \frac{\tau_g' B_g + \tau_g B_g' - a_g' E_g}{1 + a_g} ,$$

with $' = d/dT$ — `coupling_study.jl:199-204`. For $\kappa \propto T^n$ and $\kappa_P = \kappa_E$, substituting the eliminated $E_g$ back in gives

$$\frac{dE_g}{dT} = \underbrace{\frac{\tau_g B_g'}{1+\tau_g}}_{\text{emission, always} > 0} \;+\; \underbrace{\frac{n\,\tau_g}{T\,(1+\tau_g)^2}\left(B_g - \mathrm{rad0}_g\right)}_{\text{opacity moving with } T} .$$

Compare that with the same quantity in the **unreduced** $(1+N_G)$-dimensional Newton, where $E_g$ is a free iterate rather than the eliminated value. There the corresponding object is the Schur complement of the arrowhead system, and the second term reads

$$\frac{n\,\tau_g}{T\,(1+\tau_g)}\left(B_g - E_g\right) ,$$

with **one** power of $(1+\tau_g)$ instead of two, and the *current iterate* $E_g$ instead of the initial $\mathrm{rad0}_g$. Both differences matter, and together they are the whole failure of §4:

- In the eliminated form the term decays like $1/\tau_g$ and vanishes deep in the optically thick regime, so $dG/dE_\mathrm{gas} \to 1 + (c/\hat c)\,4 a_\mathrm{rad} T^3/c_V > 0$. **$G$ is guaranteed monotone at large $\tau$**, whatever the opacity exponent.
- In the unreduced form it survives at large $\tau_g$, and $B_g - E_g$ is the full departure from equilibrium rather than a small residual — so it can dominate and flip the sign.

Worked on the exact cell §4 traces ($T_\mathrm{gas} = 0.5$, $T_\mathrm{rad} = 1.3$, $\kappa \propto T^{+2}$, $\tau(T^0_\mathrm{gas}) = 2.5\times10^{8}$, four groups, $c = \hat c = c_V = a_\mathrm{rad} = 1$), at the opening iterate $E_\mathrm{gas} = E_\mathrm{gas}^0 = 0.5$:

| | eliminated $G$ | unreduced Schur complement |
|:---|---:|---:|
| value of $E_g$ used | $\sum_g E_g(T^0) = 0.0625$ | $\sum_g E_g^0 = 2.8561$ |
| emission term $4a_\mathrm{rad}T^3/c_V$ | $+0.500$ | $+0.500$ |
| opacity term $(n/T)\sum_g(B_g - \cdot)$ | $\to 0$ (extra $1/\tau$) | $-11.174$ |
| derivative | $+1.5000$ | $-9.6744$ |
| first Newton step | $+1.862$ | $-0.2888$ |
| root | $1.2103$ | $1.2103$ |

Measured: $dG/dE_\mathrm{gas} = 1.4999999$ against the predicted $1.5$, and the unreduced Schur complement $-9.674400$ against the predicted $-9.674400$. The unreduced iteration's first step points **away** from the root, and §4's trace shows it then halving the gas energy for twenty iterations down to $10^{-6}$. The eliminated one overshoots to $2.36$, in the right direction, and the bracket catches the overshoot.

So the elimination is not bookkeeping. It linearises about a state where the group block is *already satisfied*, and that is what keeps the sign of the derivative right. The bracket is the belt to that pair of braces: it handles whatever is left at moderate $\tau$, where neither limit's monotonicity argument applies and $G$ can genuinely be non-monotone.

One more thing separates the two columns, beyond the point they are evaluated at. Algebraically the Schur complement $J_{00} - \sum_g J_{0g}J_{g0}/J_{gg}$ *is* $dG/dE_\mathrm{gas}$ — the identity is exact — but the two terms being subtracted are each of order $\tau$ while their difference is of order one, so forming it that way costs a relative $\varepsilon\tau$. This is §2's cancellation again, now in the Jacobian rather than in the residual. Measured at the same eliminated point, the two expressions agree to $3\times10^{-16}$ at $\tau = 10^{-4}$ and to only $8\times10^{-3}$ at $\tau = 10^{12}$, tracking $\varepsilon\tau$ across ten orders of magnitude. It costs the arrowhead solvers nothing in the end — an inexact Newton *direction* only ever costs an iteration, since the residual is recomputed from scratch each time, which is the §3 argument over again — but the eliminated form gets the same number with nothing cancelled, for free.

### 5.6 The algorithm

Given the bracket $[E_\mathrm{lo}, E_\mathrm{hi}]$ from §5.4 and an opening iterate $x = E_\mathrm{gas}^0$, repeat:

1. evaluate $E_g(T)$, $G(x)$ and $G'(x)$ from §5.2 and §5.5 — one pass over the groups, no matrix;
2. tighten the bracket on the sign of $G$: $G(x) < 0 \Rightarrow E_\mathrm{lo} \leftarrow x$, else $E_\mathrm{hi} \leftarrow x$;
3. stop if $|G(x)| \le \mathrm{tol}\cdot\mathcal{E}$;
4. take $x_\mathrm{new} = x - G/G'$, and replace it by the bisection $ (E_\mathrm{lo}+E_\mathrm{hi})/2$ if it falls outside the bracket;
5. stop if the bracket has closed to round-off.

Finally recover $E_g$ at the accepted $x$ and apply `apply_energy_floors`. In the code these are `coupling_study.jl:230`, `:231`, `:232`, `:236-237`, `:238` and `:245-246`.

Note what the convergence test is. $G$ is an energy difference, not a stiff residual: it contains no $\tau_g(B_g - E_g)$ to cancel, because that cancellation was performed analytically in §5.3. **The whole of §2 and §3 is therefore moot for this solver** — there is nothing left for $\tau$ to amplify, and the residual test is safe at any optical depth and any tolerance.

### 5.7 What it measures, and what it would take to ship

All 240 sweep cases of §4, including the 39 where the unsafeguarded 256-bit Newton could not produce a verifiable reference:

| opacity | failures | worst error | mean iterations |
|:---|---:|---:|---:|
| constant | 0/80 | $3.2\times10^{-10}$ | 9.2 |
| $\kappa \propto T^{-3.5}$ | 0/80 | $7.9\times10^{-10}$ | 7.7 |
| $\kappa \propto T^{+2}$ | 0/80 | $6.9\times10^{-10}$ | 10.4 |

Zero failures, and every answer inside the $10^{-9}$ it was asked for. It costs $O(N_G)$ per iteration, allocates nothing, and needs no linear solve at all — not even the arrowhead elimination, since the group block is inverted in closed form. Against `QuokkaCoupling` it is 9% slower at one group and 40% slower from four groups to sixteen (§7), which is the cost of the extra $G$ evaluations the bracket asks for; across the test problems the gap runs from nothing to 60%.

Four things stand between this and `src/`, and the first is the one that matters.

**It contains its own copy of the physics.** `_reduced` calls `thermal_emission`, `coupling_opacity` and their temperature derivatives directly and then assembles $\tau_g$, $a_g$, $E_g(T)$ and $G$ from them by hand. Every other solver in the tree instead goes through `coupling_rhs` and `coupling_jacobian`, which the header of `src/coupling.jl` designates as the only place the coupling equations are written down. The practical consequence is concrete: add a term to `coupling_rhs` — Compton exchange, a cosmic-ray heating rate, a change in how $\hat c$ scales — and `DirectCoupling` picks it up for free, while `BracketedDirect` would go on silently solving the old equations.

That is fixable, and the fix is short, because everything the elimination needs can be **read off** the two shared functions instead of re-derived. $F_g$ is linear in $E_g$, so evaluating the shared pair at any convenient group energies $\tilde E_g$ gives, exactly,

$$a_g = -\Delta t\,J_{\mathrm{rad,rad},g} , \qquad \tau_g B_g = \Delta t\,\dot E_g(\tilde E) + a_g \tilde E_g , \qquad \frac{dE_g}{dE_\mathrm{gas}} = \frac{\Delta t\,J_{\mathrm{rad,gas},g}}{1 - \Delta t\,J_{\mathrm{rad,rad},g}} ,$$

from which §5.2's $E_g(T)$, §5.3's $G$ and §5.5's $dG/dE_\mathrm{gas}$ follow with no physics restated. It takes two passes rather than one, because $J_{\mathrm{rad,gas}}$ carries a $-(d\kappa_E/dT)\,E_g$ term and so has to be evaluated at the *eliminated* $E_g$, not at the probe $\tilde E_g$. Built that way and compared against the hand-written `_reduced` over the whole sweep, at three gas energies per cell: $E_g$ agrees to $2.6\times10^{-12}$ of the cell energy, $G$ to $3.7\times10^{-16}$, and $dG/dE_\mathrm{gas}$ to $1.1\times10^{-11}$, with no growth in $\tau$.

The other three are smaller. It has no optically-thin shortcut, and the sweep did not stress transparent cells hard enough to say it does not need one. It is not in the three-way agreement testset of `test/test_coupling_adaptive.jl`. And its zero-byte allocation is measured but not pinned by an assertion in `test/test_radiation_multigroup.jl` alongside the existing ones.

### 5.8 Two caveats

Where $G$ is non-monotone the backward-Euler system genuinely has more than one root, and a bracketed method returns one of them without saying which. Only following the trajectory settles which root the physics meant, which is what §6 is about; the bracket guarantees convergence to *a* solution of the step, not uniqueness of it.

The elimination assumes the group block is diagonal — that groups exchange energy with the gas and never directly with each other. That is the same assumption `ArrowheadSolve` makes and the same one documented in `AbstractJacobianSolve`, and it would fail the same way: a Compton redistribution or line-overlap term would make the group block a matrix, the closed form of §5.2 would no longer be a per-group scalar division, and the reduction to one unknown would be gone with it.

## 6. What the error-controlled ODE solve buys, and what it costs

One backward-Euler step is second-order accurate *as a step*, so its error against the true trajectory is largest where the coupling time and $\Delta t$ are comparable and vanishes in both limits. Measured against two independent stiff integrators at $10^{-12}$, which agree with each other to the last column:

| $\tau_\mathrm{cell}$ | BE, $R$ base | BE, natural | adaptive $10^{-2}$ | steps | adaptive $10^{-8}$ | steps | reference check |
|---:|---:|---:|---:|---:|---:|---:|---:|
| $10^{-4}$ | $1.0\times10^{-7}$ | $1.0\times10^{-7}$ | $3.1\times10^{-12}$ | 1 | $3.1\times10^{-12}$ | 1 | $7.4\times10^{-13}$ |
| $10^{-2}$ | $8.3\times10^{-4}$ | $8.3\times10^{-4}$ | $3.1\times10^{-6}$ | 1 | $4.4\times10^{-9}$ | 32 | $6.2\times10^{-12}$ |
| $10^{-1}$ | $2.7\times10^{-2}$ | $2.7\times10^{-2}$ | $2.3\times10^{-3}$ | 1 | $7.2\times10^{-8}$ | 143 | $7.7\times10^{-12}$ |
| $10^{0}$ | $\mathbf{6.2\times10^{-2}}$ | $\mathbf{6.2\times10^{-2}}$ | $6.6\times10^{-4}$ | 12 | $1.4\times10^{-7}$ | 465 | $3.2\times10^{-13}$ |
| $3\times10^{0}$ | $2.8\times10^{-2}$ | $2.8\times10^{-2}$ | $1.0\times10^{-4}$ | 16 | $3.9\times10^{-8}$ | 647 | $1.2\times10^{-13}$ |
| $10^{1}$ | $9.3\times10^{-3}$ | $9.3\times10^{-3}$ | $2.8\times10^{-6}$ | 19 | $3.9\times10^{-9}$ | 826 | $6.3\times10^{-13}$ |
| $10^{2}$ | $9.6\times10^{-4}$ | $9.6\times10^{-4}$ | $1.5\times10^{-9}$ | 21 | $3.3\times10^{-15}$ | 851 | $7.9\times10^{-13}$ |
| $10^{4}$ | $9.7\times10^{-6}$ | $9.7\times10^{-6}$ | $4.1\times10^{-16}$ | 24 | $8.2\times10^{-17}$ | 854 | $5.6\times10^{-12}$ |
| $10^{9}$ | $9.9\times10^{-11}$ | $9.7\times10^{-11}$ | $8.6\times10^{-16}$ | 29 | $3.3\times10^{-16}$ | 859 | $3.3\times10^{-12}$ |
| $10^{12}$ | $3.5\times10^{-12}$ | $9.8\times10^{-14}$ | $3.3\times10^{-16}$ | 32 | $5.3\times10^{-16}$ | 862 | $9.9\times10^{-12}$ |

The two backward-Euler columns are identical to every digit printed until $\tau = 10^{12}$, where they differ only because their stopping tests differ — which is the empirical form of the claim in §1 that they are one method. The peak error is 6.2% of the cell's energy at $\tau_\mathrm{cell} \approx 1$, and that is the whole of what an error-controlled solve has to sell.

Buying that accuracy by substepping backward Euler is expensive, because backward Euler is first order once you take more than one step. Splitting the same $\Delta t$ into $n$ substeps of `QuokkaCoupling` (total Newton iterations in brackets):

| $\tau_\mathrm{cell}$ | $n=1$ | $n=2$ | $n=4$ | $n=8$ | $n=16$ | $n=64$ |
|---:|---:|---:|---:|---:|---:|---:|
| $10^{-1}$ | $2.7\times10^{-2}$ (5) | $1.5\times10^{-2}$ (8) | $8.4\times10^{-3}$ (16) | $4.4\times10^{-3}$ (32) | $2.2\times10^{-3}$ (50) | $5.7\times10^{-4}$ (192) |
| $10^{0}$ | $6.2\times10^{-2}$ (6) | $3.2\times10^{-2}$ (10) | $1.5\times10^{-2}$ (18) | $7.1\times10^{-3}$ (33) | $3.4\times10^{-3}$ (58) | $8.1\times10^{-4}$ (203) |
| $10^{1}$ | $9.3\times10^{-3}$ (6) | $1.3\times10^{-3}$ (10) | $2.3\times10^{-4}$ (16) | $5.8\times10^{-5}$ (27) | $1.6\times10^{-5}$ (48) | $2.1\times10^{-6}$ (156) |
| $10^{2}$ | $9.6\times10^{-4}$ (6) | $1.6\times10^{-5}$ (9) | $7.0\times10^{-8}$ (15) | $4.4\times10^{-11}$ (23) | $8.7\times10^{-11}$ (34) | $3.4\times10^{-10}$ (95) |

At $\tau = 1$, 64 backward-Euler substeps and 203 Newton iterations reach $8.1\times10^{-4}$; the adaptive Rosenbrock at its loosest setting reaches $6.6\times10^{-4}$ in 12 internal steps. A second-order L-stable method with error control is simply the right tool for that regime, and substepping a first-order one is not competitive.

The question the tables cannot answer is whether the intermediate regime matters in a run, where the coupling is operator-split against transport and the splitting error is itself $O(\Delta t)$. §8 says: on the code's own test problems it does not, except where a solver fails.

## 7. Cost

One cell solve, constant opacity at $\tau_\mathrm{cell} = 10^{4}$, out of equilibrium. Minimum of 200 samples, and allocation per call:

| method | $N_G = 1$ | $N_G = 2$ | $N_G = 4$ | $N_G = 8$ | $N_G = 16$ |
|:---|---:|---:|---:|---:|---:|
| Quokka, $R$ base | 127 ns | 1.3 $\mu$s | 2.3 $\mu$s | 4.3 $\mu$s | 9.5 $\mu$s |
| natural, residual + raise | 190 ns | 1.7 $\mu$s | 2.9 $\mu$s | 5.5 $\mu$s | 11.5 $\mu$s |
| natural, increment | 131 ns | 1.6 $\mu$s | 2.8 $\mu$s | 5.2 $\mu$s | 11.1 $\mu$s |
| natural, increment + damping | 140 ns | 1.6 $\mu$s | 2.7 $\mu$s | 5.1 $\mu$s | 10.9 $\mu$s |
| natural, bracketed scalar | 138 ns | 1.7 $\mu$s | 3.3 $\mu$s | 6.4 $\mu$s | 13.6 $\mu$s |
| natural, `ImplicitEuler` | 7.2 $\mu$s | 8.5 $\mu$s | 10.5 $\mu$s | 13.4 $\mu$s | 24.3 $\mu$s |
| adaptive, $10^{-2}$ | 10.6 $\mu$s | 17.1 $\mu$s | 27.2 $\mu$s | 47.0 $\mu$s | 96.4 $\mu$s |
| adaptive, $10^{-8}$ | 211 $\mu$s | 502 $\mu$s | 861 $\mu$s | 1.84 ms | 4.33 ms |

Every hand-written stepper allocates **0 bytes**. `ImplicitEuler` allocates 8.6 to 20.5 kB per cell and the adaptive solvers 8.0 to 21.5 kB, both unavoidably: a `solve` call builds an integrator, a nonlinear solver, their caches and a solution object for a problem in $1 + N_G$ unknowns.

One thing the table says that is easy to miss: the jump from $N_G = 1$ to $N_G = 2$ is a factor of ten, far more than the linear algebra can explain. At two groups and above the cost is dominated by `planck_fractions` — the incomplete Planck integral and its temperature derivative, evaluated once per Newton iteration. **The choice of formulation is a second-order effect on cost; the Planck integral is the first-order one.** Anything that cuts iterations pays; anything that only changes the linear solve barely shows.

## 8. The test problems

Each problem run to completion with each solver, at four groups. The reference row is the adaptive solve at $10^{-8}$, and the score is the relative $L_1$ difference in gas and radiation temperature over the interior.

### `marshak_vaytet`, 4 groups, $n = 64$ — the code's own multigroup problem

| method | wall | Newton mean / max | failures | $\Delta T_\mathrm{gas}$ | $\Delta T_\mathrm{rad}$ |
|:---|---:|---:|---:|---:|---:|
| Quokka, $R$ base | 2.1 s | 2.00 / 3 | 0 | $7.61\times10^{-4}$ | $2.59\times10^{-3}$ |
| natural, residual test | 1.8 s | 2.00 / 3 | 0 | $7.60\times10^{-4}$ | $9.75\times10^{-4}$ |
| natural, residual + raise | 1.4 s | 2.00 / 3 | 0 | $7.60\times10^{-4}$ | $9.75\times10^{-4}$ |
| natural, increment + damping | 1.7 s | 2.00 / 3 | 0 | $7.61\times10^{-4}$ | $9.92\times10^{-4}$ |
| natural, bracketed scalar | 3.4 s | 2.00 / 3 | 0 | $7.60\times10^{-4}$ | $2.59\times10^{-3}$ |
| natural, `ImplicitEuler` | 21.2 s | 2.44 / 3 | 0 | $7.61\times10^{-4}$ | $9.92\times10^{-4}$ |
| adaptive, $10^{-2}$ | 18.6 s | 4.73 / 22 | 0 | $3.42\times10^{-6}$ | $2.39\times10^{-3}$ |
| adaptive, $10^{-8}$ | 62.7 s | 29.3 / 759 | 0 | — | — |

Nothing fails, and the six one-step solvers agree with each other on the gas temperature to $8\times10^{-7}$ — a thousand times below the $7.6\times10^{-4}$ they all share as their offset from the reference, which is therefore the backward-Euler discretisation error and nothing else. The radiation temperature splits them into two groups, $9.8\times10^{-4}$ and $2.6\times10^{-3}$, a spread as large as the offset itself: 16309 steps is long enough for sub-tolerance differences in where each iteration stops to grow into the third digit of a diagnostic that is dominated by the cold far field. The reason nothing fails is measurable: the largest cell optical depth this problem reaches over those steps is $\tau_\mathrm{cell} = 2.2\times10^{4}$, which the table in §2 puts below the onset of round-off trouble at $10^{-9}$ — though not at $10^{-13}$. **The code's only built-in multigroup test problem does not reach the regime the base-variable replacement exists for.** That is worth knowing before drawing conclusions from it.

The cost column is the real content here. The allocation-free hand-written steppers run in 1.4 to 3.4 s; `ImplicitEuler` and the two adaptive settings cost 13, 15 and 45 times the fastest of them for an answer that is the same to $10^{-3}$, and the adaptive gain in gas temperature ($3.4\times10^{-6}$ against $7.6\times10^{-4}$) buys two decimal places at 13 times the wall clock.

### Stiff relaxation, $\kappa = 10^{12}$, $\tau_\mathrm{cell} \approx 3\times10^{9}$

| method | Newton mean / max | failures | $\Delta T_\mathrm{gas}$ |
|:---|---:|---:|---:|
| Quokka, $R$ base | 3.09 / 7 | 0 | $1.4\times10^{-10}$ |
| natural, residual test | **86.4 / 100** | **330** | $1.4\times10^{-15}$ |
| natural, residual + raise | 3.28 / 7 | 0 | $2.2\times10^{-15}$ |
| natural, increment + damping | 2.48 / 7 | 0 | $1.3\times10^{-15}$ |
| natural, bracketed scalar | 2.52 / 7 | 0 | $1.3\times10^{-10}$ |
| natural, `ImplicitEuler` | 2.37 / 6 | 0 | $4.3\times10^{-15}$ |

This is §2 and §3 reproduced in a run. The naive residual test does 26 times the Newton work and reports 330 failures, and its answer is the most accurate in the table. Every fix — the tolerance raise, the increment test, the library stepper — removes both symptoms.

### Multigroup Marshak wave, $\kappa = 300\,T^{-3.5}$

Every solver converges, in 1.1 mean Newton iterations, and all six one-step answers agree to five digits ($\Delta T_\mathrm{gas} = 5.86\times10^{-4}$ against the reference for all of them). The radiation CFL step keeps $\tau_\mathrm{cell}$ modest, so the hard single-cell regime of §4 never arises. This is the common case.

### Multigroup Marshak wave, $\kappa = 3\times10^{5}\,T^{+2}$ — the case that separates them

| method | Newton mean / max | failures | $\Delta T_\mathrm{gas}$ | $\Delta T_\mathrm{rad}$ |
|:---|---:|---:|---:|---:|
| Quokka, $R$ base | 1.36 / 100 | 2 | $6.9\times10^{-2}$ | $5.3\times10^{-2}$ |
| natural, residual test | 2.45 / 100 | 9 | $7.1\times10^{-2}$ | $5.7\times10^{-2}$ |
| natural, residual + raise | 2.45 / 100 | 9 | $7.1\times10^{-2}$ | $5.7\times10^{-2}$ |
| natural, increment + damping | 2.46 / 100 | 9 | $7.3\times10^{-2}$ | $6.0\times10^{-2}$ |
| natural, bracketed scalar | **1.07 / 4** | **0** | $\mathbf{2.5\times10^{-3}}$ | $\mathbf{2.5\times10^{-3}}$ |
| natural, `ImplicitEuler` | 2.46 / 100 | **0** | $7.1\times10^{-2}$ | $5.7\times10^{-2}$ |
| adaptive, $10^{-2}$ | 2.38 / 31 | 0 | $1.9\times10^{-8}$ | $4.3\times10^{-6}$ |

A handful of cells per step fail, and the temperature field is 7% wrong. The bracketed scalar solver is the only one-step method that gets it right, at a quarter of the Newton work, and its remaining $2.5\times10^{-3}$ is the honest one-step discretisation error rather than a failure. The adaptive solve is exact for practical purposes.

The `ImplicitEuler` row is the one to be uncomfortable about: **0 failures reported, 7% wrong**. Its increment test cannot distinguish convergence from a stall, so the only diagnostic a run has — `newton_failures` — says nothing is wrong. Every other solver at least raised its hand.

## 9. What follows from this

**On the base variables.** The replacement is a correct response to a real problem, but it is aimed at a symptom. What breaks in the natural variables at large $\tau_\mathrm{cell}$ is the convergence test, and the test can be fixed directly: divide each residual component by its own Jacobian diagonal, or test the increment. Either is one line, either removes the $\tau$ dependence completely, and either leaves the answer more accurate than the replaced variables deliver, because the replaced variables carry their own $10^{-11}$-level stopping error. Against that, the replacement costs robustness wherever the opacity depends on temperature — 36 failures in 66 cases at $\kappa \propto T^{-3.5}$, against zero for a damped natural-variable Newton — which is a live concern for any run with a realistic opacity table rather than a constant.

**On what to change first.** The failures that damage an answer in these tests are nonlinearity, not round-off. The round-off failures are loud and harmless; the nonlinearity failures are quiet and cost 7% of the temperature field. If one change is to be made, it is the bracket: eliminate the group block analytically, reduce to the scalar energy balance, and safeguard Newton with bisection inside the bracket the physics guarantees. It converged in all 240 sweep cases and in all four test problems, allocates nothing, is $O(N_G)$, and costs 8% at four groups. It also makes the residual-conditioning question moot, since the scalar residual has no cancelling $\tau_g(B_g - E_g)$ in it.

**On the error-controlled solve.** It never failed, anywhere, and it is the only method that resolves the intermediate regime and the multi-root ambiguity. It also costs 10 to 100 times a hand-written Newton step and 8 to 21 kB per cell, and the accuracy it buys is invisible on three of the four test problems here, where the coupling's own error is dwarfed by the operator splitting it sits inside. Keep it as the reference — the thing that says what the answer is when two production solvers disagree, which is exactly the role it played in producing this document.

**On what is still open.** All of this is one-dimensional, in double precision, with `beta_order = 0` on the multigroup problems, so the lagged $\boldsymbol{v}\cdot\boldsymbol{F}$ outer iteration is untested here. The two hard opacity laws are power laws; a tabulated opacity with structure in it may behave differently again, and the non-monotone residual of §4 is the mechanism to watch for. And the bracketed reduction inherits the assumption that groups exchange energy only through the gas — the same assumption `ArrowheadSolve` makes, documented in the same place, and it would need the same rethink if a Compton or line-overlap term were added.

## 10. Reproducing this

```bash
julia --project=. -t 4 docs/coupling-experiments/coupling_study.jl              # every table
julia --project=. -t 4 docs/coupling-experiments/coupling_study.jl cost runs    # named sections
```

Sections are `conditioning`, `test`, `robust`, `derivation`, `ode`, `cost` and `runs`, producing the tables of §2, §3, §4 and §5.7, §5.5, §6, §7 and §8 respectively. The script defines `PlainDirect` and `BracketedDirect` — the candidate steppers this document argues about — as `AbstractCoupling` subtypes outside `src/`, so the measurements can be redone without adding an unused solver to the package. `BracketedDirect`'s own derivation is at `coupling_study.jl:159-248`, and §5 quotes its line numbers as it goes. Timings are from an Apple-silicon laptop and are meaningful only as ratios.


---

<!-- page: rsla-findings.md -->

# Standard and adaptive reduced speed of light approximations

This note records measurements of the reduced speed of light in Honghu in two parts. **Standard RSLA** covers the global reduction $\phi_0 = \hat{c}/c$, which is the default (`ConstantChat()`). **ARSA** covers the adaptive reduced speed of light approximation of He, Krumholz & Wibking, "An Adaptive Reduced Speed of Light Approximation" ([arXiv:2611.21353](https://scixplorer.org/abs/2026arXiv261121353H/abstract)), for which Honghu is the reference implementation (named IRSLA in the code, with limiter `StabilityBound()`). The implementation lives in `src/rsla.jl` and the array drivers of `src/radiation_system.jl` (`update_chat!`, `scale_by_phi!`, `floor_rad_energy!`, `energy_exchange_dt`), tested in `test/test_rsla.jl`.

Errors are reported as the relative $L_1$ error in gas temperature against a $\hat{c} = c$ reference at the same resolution and (unless noted otherwise) at the same step count as the standard RSLA, so every comparison is at equal cost.

The ARSA took its present form in commit `b287f03` (the squash of branch `irsla-variable-chat-stage2`, archived at tag `archive/irsla-variable-chat-stage2`). Section A1 summarises what that commit changed and quotes its measurements; `examples/irsla_paper.jl` reproduces them along with all numbers in Section 5 of the paper. Sections A2 to A9 record the earlier experiments that led to `b287f03`, measured with the prior limiter (which defined the cell optical depth as $\chi\,\Delta x_\mathrm{min}$, used a single $\phi$ per cell, and placed $\phi$ inside the flux divergence). Because `examples/rsla_limiter.jl` now runs the current limiter and `b287f03` also updated pre-solve floor repairs for all limiters, re-running that script today produces the current limiter's numbers rather than the historical tables in A2 to A9. Where a design choice from those earlier sections was later reversed, the text notes it explicitly.

## Standard RSLA

### S1. Its error is a modelling error that does not refine away

The standard RSLA multiplies the radiation source terms by $\phi_0$ while leaving the matter source terms unchanged, shifting the intermediate equilibrium temperature between gas and radiation. The error is largest at high optical depth, where implicit coupling already damps the stiff terms and no speed-of-light reduction is needed for stability. As $\phi_0$ decreases, the error grows: on the Lowrie & Edwards Mach 3 radiative shock at $n = 256$, it rises from 0.11% at $\phi_0 = 0.023$ to 2.5% at $\phi_0 = 0.0023$, a factor of 22 (table in A2). Because this error comes from the modified equations rather than the spatial discretisation, refining the grid does not reduce it: on the same shock at $\phi_0 = 0.0069$, it remains between 0.54% and 0.67% from $n = 64$ to $n = 512$ (table in A6).

### S2. With a uniform $\phi$, the energy error depends only on the net gas energy change

Summing the source terms of the gas and the radiation groups gives

$$\frac{d}{dt}\left[e + \sum_g E_g\right] = c\,\rho \sum_g \left(\phi_g - 1\right)\left(\kappa_P B_g - \kappa_E E_g\right) .$$

When $\phi$ is uniform across groups and cells, the sum collapses onto the gas energy equation, leaving the exact identity

$$\Delta\left[e + \sum_g E_g\right] = \left(1 - \phi\right) \Delta e .$$

Thus the total energy drift over a step or a run depends solely on the net change in gas energy $\Delta e$, regardless of the spectrum, the number of absorption and re-emission cycles, or which frequency groups carried the energy. In a single-cell relaxation test over 400 coupling steps with no transport, this identity holds to five decimal places at both $\phi = 0.1$ and $\phi = 0.01$.

The identity requires a globally uniform reduction. When $\phi$ varies across cells or groups, the sum no longer collapses; A5 measures the resulting drift and states the modified invariant that a local $\phi$ conserves instead.

### S3. Time step: closure signal speed and removal of the radiation-pressure limit

The stable transport step is set by the closure's actual signal speed rather than the P1 speed $c/\sqrt{3}$. Where M1 free-streams, the Eddington factor approaches 1 and the HLL wave speeds reach $\pm\hat{c}$. The table below runs the Vaytet multigroup Marshak wave ($n = 64$, four groups) at $\hat{c} = c$ without a limiter, isolating the explicit transport step across four values of the radiation CFL number $\nu$:

| reconstruction | $\nu = 0.8$ | $\nu = 1.2$ | $\nu = 1.5$ | $\nu = \sqrt{3}$ |
|:---|---:|---:|---:|---:|
| PCM | 2.51% | 2.61% | 32.6% | 79.8% |
| PLM | 0.39% | 0.93% | 139.6% | overflow |
| PPM | 0.05% | 0.65% | 128.7% | overflow |

The scheme goes unstable between $\nu = 1.2$ and $\nu = 1.5$ for all three reconstructions, including first-order PCM, showing that the limit comes from the M1 closure's wave speed rather than the reconstruction order. At $\nu = \sqrt{3}$ (unit Courant number for the P1 wave speed), PLM and PPM overflow. Section A3 shows how this affects the ARSA stability bound. For the standard RSLA, it sets the maximum stable Courant number: the paper runs in `examples/irsla_paper.jl` use a safety factor $\beta = 0.9$, giving $C_r = 0.9\sqrt{3}$ for P1 and $C_r = 0.9\sqrt{D}$ for M1 (in Honghu's convention $C_r = D\,\nu_0$).

The standard RSLA does not require an additional timestep restriction from radiation pressure at any $P_\mathrm{rad}/P_\mathrm{gas}$. In the exact stability bound of A1 evaluated at $\phi = \phi_0$, the left-hand side is bounded by the CFL number times $\sigma$ regardless of the heat capacities, and the checkerboard test in `test/test_rsla.jl` confirms that checkerboard modes decay at the standard RSLA step for $\mathcal{P} = 1$ and $100$ in 1D and 2D. Commit `b287f03` therefore removed the earlier `radiation_pressure_dt` constraint (from eq. 33 of the initial paper draft), which had previously increased the step count on the static Vaytet Marshak wave by $5.4\times$ without changing the solution.

### S4. The wave-speed correction applies only to the standard RSLA

`RadiationPhysics(wavespeed_correction = true)` scales the HLL numerical dissipation of the radiation energy at each face by $\epsilon = \min(1, 1/\tau)$, where $\tau$ is the harmonic mean of the two adjacent cells' optical depths (Skinner et al. 2019; optional in Quokka). In optically thick cells, unmodified HLL dissipation introduces numerical diffusion that exceeds the physical diffusion rate $c/(3\tau)$, and the $\epsilon$ factor suppresses it. Honghu restricts this correction to `ConstantChat`; section A1 explains why it is incompatible with a local limiter.

## ARSA

### A1. The current formulation (`b287f03`)

Every cell and frequency group runs at the largest reduced speed of light that the IMEX PD-ARS step supports stably at the timestep of the standard RSLA:

$$\phi = \min\left\{1,\ \max\left[\phi_0,\ \frac{\beta}{c\,\Delta t\,\Lambda}\right]\right\},$$

where $\Lambda$ is `stability_denominator` and $\beta = 0.9$ by default. Relative to the earlier limiter used in A2 through A9, `b287f03` changed the following:

- The stability bound is the exact von Neumann boundary in $D$ dimensions. The grid-scale checkerboard is always the most unstable mode, where the linearised update decouples into an energy block and a momentum block, each bounded by $$\phi\,c\,\Delta t\left[\sum_d \frac{\sigma_d}{\Delta x_d} - \frac{\chi}{2 + K}\right] \leq 1 ,$$ with $\chi = \rho\kappa_E$ and $K = 4 a_R T^3 \kappa_P\, c\,\Delta t / c_v$ for the energy block, and $\chi = \rho\kappa_F$ (with $K$ smaller by $(a/c)^2$ and omitted) for the momentum block; $\Lambda$ is the larger of the two brackets. In 1D, 2D, and 3D, a checkerboard mode decays at $0.9\times$ the bound, grows at $1.1\times$ the bound, and sits at $|g| = 1$ to within $10^{-3}$ at $\beta = 1$. The earlier limiter defined the cell optical depth as $\chi\,\Delta x_\mathrm{min}$ rather than $\chi / \sum_d (1/\Delta x_d)$, which is $D$ times too permissive in $D$ dimensions and caused checkerboard modes to grow by $1.06\times$ to $1.88\times$ per substep in 2D and 3D. When radiation energy is significant, the heat-capacity term $K$ in the energy block is the active constraint. Signal speeds $\sigma_d$ are evaluated per direction (A3).
- $\phi$ multiplies the time derivative rather than the flux divergence: each cell's transport update multiplies the unreduced HLL flux difference by the cell's own $\phi_i$. Steady states then satisfy $\nabla\cdot\boldsymbol{F} = S$ for any spatial profile $\phi(x)$, the flux differences telescope in the conserved quantity $E/\phi$, and no face-interpolated $\phi_{i+1/2}$ is required. Placing $\phi$ inside the divergence (as in earlier drafts) adds a spurious $\boldsymbol{F}\cdot\nabla\ln\phi$ term to the steady state; on the Mach 5 supercritical shock, a 5% ripple in $\phi$ raised the $L_1$ error from 0.19% to 2.3%, worse than the standard RSLA. For uniform $\phi$ the two forms are identical; `flux_form = true` retains the divergence form for comparison.
- `StabilityBound` always uses one $\phi$ per group (`per_group` is true; see A5), computed once at the start of each IMEX substep and held fixed across both stages to match the von Neumann analysis. Recomputing $\phi$ between stages would leave an uncancelled $(E^{(2)} - E^n)(1/\phi_b - 1/\phi_a)$ conservation residual.
- Pre-solve state repair is restricted to non-positive total energy budgets. An optically thick cell with $\phi = 1$ steps at a local transport Courant number well above unity, so its explicit transport stage can produce $|\boldsymbol{F}| \gg cE$ or (at steep jumps in $\phi$) $E < 0$. The implicit coupling solve divides the flux by $1 + \hat{c}\rho\kappa_F\Delta t$, recovering the diffusion flux, and yields a positive temperature whenever $e + \sum_g E_g/\phi_g > 0$. Clipping $|\boldsymbol{F}|$ to $cE$ before the solve discarded the diffusion flux and raised the thick hot-spot error from 0.0003% to 0.80% (versus 0.37% for the standard RSLA). Flooring $E$ unconditionally before the solve injected spurious energy every substep, making the 64-cell Ensman supercritical shock $17\times$ less accurate than the standard RSLA. Honghu now floors $E$ before the solve only when $e + \sum_g E_g/\phi_g \le 0$, deferring full flux and energy repair (`amend_rad_state!`) until after the solve. `Diagnostics` tracks the two counts separately as `floors_presolve` and `repairs_postsolve`.
- The energy-exchange timestep (`energy_step = true`) is opt-in. When radiation dominates the heat capacity ($K \gg 2$), the energy-block damping $\chi_E/(2 + K)$ saturates and caps $\phi$ near $\phi_0/(\sigma C_r)$ at the standard RSLA step. Passing `StabilityBound(energy_step = true)` enables `energy_exchange_dt` ($\xi = 0.5$), which shortens the step enough for optically thick cells to reach $\phi = 1$, floored at the unreduced ($\hat{c} = c$) CFL step so that radiation-dominated runs like `radhydro_pulse_dyn` never subcycle finer than $\hat{c} = c$.
- `RadiationPhysics(wavespeed_correction = true)` throws an error unless the limiter is `ConstantChat`. Because the face factor $\epsilon$ depends on both adjacent cells, a thick cell next to a thin cell had its damping reduced by the shared face while still running at $\phi = 1$, growing by $\sim 10^{43}$ in 200 steps; in uniform media, reduced HLL dissipation also destabilises intermediate-wavelength modes ($\sim \lambda = 4\Delta x$) that the checkerboard bound does not capture.

On `radhydro_shock_super` (the Mach 5 Lowrie & Edwards supercritical shock matching Quokka's `RadhydroShockSuper`), the current ARSA achieves an $L_1$ error of 0.17% versus 3.39% for the standard RSLA. In `examples/linear_waves_rhd.jl`, complex eigenfrequencies of linearised radiation-hydrodynamic waves match exact linear theory to within ~1% across $\tau = 0.1$ to $10^3$ for $\hat{c} = c$, standard RSLA, and ARSA alike.

### A2. Removing the $\hat{c}$ dependence on the radiative shock

Lowrie & Edwards Mach 3 radiative shock, $n = 256$, evolved for three shock-crossing times (IRSLA column measured with the pre-`b287f03` limiter):

| $\phi_0$ | RSLA | IRSLA | gain | steps |
|---:|---:|---:|---:|---:|
| 0.0231 | 0.1129% | 0.1321% | 0.85$\times$ | 2726 / 2726 |
| 0.0069 | 0.6066% | 0.1307% | 4.64$\times$ | 2724 / 2726 |
| 0.0023 | 2.5124% | 0.1309% | 19.19$\times$ | 2721 / 2726 |

The IRSLA error stays constant at 0.131% across all three values of $\phi_0$, while the standard RSLA error grows by a factor of 22 over the same range. The "gain" ratio simply reflects how far the standard RSLA degrades as $\phi_0$ decreases. At $\phi_0 = 0.0231$, the standard RSLA error (0.113%) is already at the spatial discretisation floor of the scheme, so raising $\phi$ locally cannot reduce it further.

![The Mach 3 radiative shock at $\phi_0 = 0.0069$: the improved RSLA sits on the $\hat{c} = c$ reference through the precursor and the Zel'dovich spike, where the standard RSLA does not. The lower panel is the reduction factor the limiter chose. Drawn with the earlier limiter.](figures/rsla_limiter.png)

On the multigroup Marshak wave of Vaytet et al. ($n = 64$, four groups), the error improves by roughly a factor of two while retaining a $\phi_0$ dependence:

| $\phi_0$ | RSLA | IRSLA | gain |
|---:|---:|---:|---:|
| 0.03 | 5.276% | 3.172% | 1.66$\times$ |
| 0.01 | 13.303% | 4.903% | 2.71$\times$ |
| 0.003 | 28.620% | 22.894% | 1.25$\times$ |

Here the groups carrying the front's energy sit at $\tau_\mathrm{cell} \lesssim 1$, where the stability bound genuinely restricts $\phi$, so a stability-limited local $\hat{c}$ cannot eliminate the $\phi_0$ dependence.

### A3. Using the M1 signal speed in the stability bound

In the initial paper draft, the transport-versus-damping bound balanced the amplification $2\nu_\phi/\sqrt{3} - 1$ of an upwind P1 step against the implicit damping $1/(1 + \nu_\phi \tau_\mathrm{cell})$, yielding

$$\nu_\phi\left(\frac{2}{\sqrt{3}} - \tau_\mathrm{cell}\right) \leq 2 .$$

The factor $2/\sqrt{3}$ uses the isotropic P1 wave speed $c/\sqrt{3}$. Under the M1 closure in free-streaming regions, the Eddington factor approaches 1 and the HLL wave speeds reach $\pm\hat{c}$, making the P1 bound too permissive by a factor of $\sqrt{3}$ in optically thin cells where source damping is absent. With the $2/\sqrt{3}$ bound, the Vaytet Marshak wave has an $L_1$ error of 130% at every $\phi_0$, and the slab heated by a 1000 K boundary overshoots to 2158 K (consistent with the $\nu = \sqrt{3}$ overflow in S3).

Replacing $1/\sqrt{3}$ with the closure's signal speed $\sigma$ gives

$$\nu_\phi\left(2\sigma - \tau_\mathrm{cell}\right) \leq 2 ,
\qquad
\sigma = \sqrt{\chi\!\left(|\boldsymbol{F}|/cE\right)} ,$$

evaluated per cell from `eddington_factor`. This recovers $1/\sqrt{3}$ in isotropic regions and tightens by $\sqrt{3}$ in free-streaming beams, reducing the Vaytet Marshak wave error from 130% to 3.2% (the value reported in A2). Consequently, the optical depth threshold above which $\phi = 1$ is unconditionally stable shifts from $2/\sqrt{3} \approx 1.15$ to $2\sigma$ (up to $2$ in a beam), and the optically thin limit becomes $\phi \leq \phi_0/(\sigma\, C_r)$.

The current bound in A1 refines this further by evaluating $\sigma_d = \max(0.1, \sqrt{T_{dd}})$ along each active axis $d$ and summing $\sigma_d/\Delta x_d$ (`_signal_sum`), so a beam aligned with one axis in 2D or 3D only tightens the bound along that axis. In 1D with $K \ll 2$, A1's energy block reduces to the formula above.

### A4. Non-monotonicity in $\beta$ on the Mach 3 shock (not seen in Quokka)

**Cross-check (2026-08-19):** Running the same $\beta$ scan on Quokka's Mach 5 supercritical shock gives a monotonically decreasing $L_1$ error right up to the stability limit: 1.29%, 0.50%, 0.23%, 0.12%, and 0.068% at $\beta = 0.3, 0.5, 0.7, 0.9, 1.0$, followed by instability (172%) at $\beta = 1.2$. The non-monotonicity below is specific to the Mach 3 setup or the earlier limiter in Honghu and does not carry over to Quokka.

Scanning the safety factor $\beta$ in Honghu with the earlier limiter gives:

| $\beta$ | shock $L_1$ | Vaytet $L_1$ | Vaytet max $T$ |
|---:|---:|---:|---:|
| 0.3 | 0.1233% | 13.301% | 932 K |
| 0.6 | **0.0590%** | 12.346% | 934 K |
| 0.9 | 0.1307% | 4.903% | 937 K |
| 1.0 | 0.2165% | **3.663%** | 936 K |
| 1.5 | 290.5% | 412.1% | 2947 K |
| 2.0 | 301.5% | 460.3% | 3272 K |

On the Marshak wave, error decreases monotonically up to $\beta = 1$. On the Mach 3 shock with the earlier limiter, error reaches a minimum at $\beta = 0.6$ before rising to 0.217% at $\beta = 1.0$ (possibly because higher $\phi$ in optically thin cells increases HLL numerical diffusion, which scales with the wave speed). Above $\beta = 1$, both problems go unstable between $\beta = 1.0$ and $1.5$, matching the analytical stability boundary; on the Marshak wave, $\beta = 1.5$ completes in the same number of steps while producing a 412% temperature error.

### A5. Conservation and accuracy of per-group versus per-cell $\phi$

Although frequency groups are independent during explicit transport, they couple through the shared gas temperature during the implicit source step. When $\phi_g$ varies across groups, the energy identity of S2 no longer collapses. In a single-cell two-group relaxation test over 400 steps without transport, setting $\phi = (1, 0.1)$ produces a $-44.5\%$ drift in $e + \sum_g E_g$, and $\phi = (1, 0.01)$ produces $-56.7\%$.

Initially, this led us to default to a single $\phi$ per cell (taking the minimum over groups). **Commit `b287f03` reversed that choice.** Because the S2 identity also requires $\phi$ to be uniform across space, any spatially varying limiter already loses conservation of $e + \sum_g E_g$. Instead, the time-derivative formulation of A1 exactly conserves the weighted energy $e + \sum_g E_g/\phi_g$, both in the local coupling step and across cell interfaces, whether $\phi$ is chosen per cell or per group. Since both choices are stable under the coupled multigroup von Neumann analysis, the choice is decided by accuracy on multigroup problems such as the Vaytet Marshak wave:

| $\phi_0$ | earlier limiter, per cell | earlier limiter, per group | current limiter, per cell | current limiter, per group |
|---:|---:|---:|---:|---:|
| 0.03 | 3.172% | 3.975% | 4.3% | 2.7% |
| 0.01 | 4.903% | 2.830% | 11.5% | 7.8% |
| 0.003 | 22.894% | 18.579% | 26.0% | 21.2% |

With the current limiter (`src/rsla.jl`), per-group $\phi$ is more accurate at all three $\phi_0$ values at identical cost. `StabilityBound` therefore always uses one $\phi$ per group (matching Quokka; see A7), while `OpticalDepthFit` retains a `per_group` keyword to reproduce older runs.

### A6. Behaviour under grid refinement

Because $\tau_\mathrm{cell} \propto \Delta x$ decreases as the grid is refined, cells move toward the optically thin regime where the limiter has less headroom to raise $\phi$. Even so, refining the Mach 3 shock at $\phi_0 = 0.0069$ (measured with the earlier limiter) increases the relative advantage over the standard RSLA:

| $n$ | RSLA | IRSLA | gain |
|---:|---:|---:|---:|
| 64 | 0.6491% | 0.2164% | 3.00$\times$ |
| 128 | 0.5379% | 0.1755% | 3.07$\times$ |
| 256 | 0.6066% | 0.1307% | 4.64$\times$ |
| 512 | 0.6742% | 0.0624% | 10.81$\times$ |

From $n = 64$ to $n = 512$, the IRSLA error drops by a factor of 3.5 as the grid resolves the shock, whereas the standard RSLA error stalls around 0.6% because its equilibrium mismatch is a resolution-independent modelling error (S1).

### A7. Cross-checks and fixes in Quokka

Checking A3 and A5 against Quokka's `ComputeReducedSpeedOfLightFactor` and multigroup source term (`0bf3741b` on `chong/iRSLA-framework-202607-improved`, with `radiation.variable_chat_legacy` preserving the prior behaviour) confirmed four issues:

| Issue | Effect on Quokka's tests |
|:---|:---|
| P1 signal speed in the bound (A3) | supercritical shock 0.159% $\to$ 0.116%; Vaytet at $\phi_0 = 0.01$, 8.30% $\to$ 3.65% |
| bound evaluated at nominal rather than actual CFL (A8) | Vaytet 3.65% $\to$ 1.97% with $\sigma$ also fixed, versus **57%** if fixed without $\sigma$ |
| $\beta$ multiplying an unreduced cap, limiting thick cells to $\phi = 0.9$ | negligible $L_1$ change; restores exact $\phi = 1$ in thick cells |
| face interpolation indexing a non-adjacent cell (Quokka-specific bug) | $\leq 0.2\%$ on Vaytet wave, zero on shock |

In the second row, Quokka's Vaytet setup ran at $C_r = 0.4$ while evaluating the stability bound with $C_r = 0.3$, allowing $\phi$ to exceed the bound by a third. Fixing only the CFL mismatch pushed $\phi$ into the unstable region left open by the P1 signal speed, raising the error from 8.3% to 57% (and the slab temperature to 1118 K under a 1000 K boundary); fixing both the CFL input and the M1 signal speed reduced the error to 1.97%.

Quokka also uses per-group $\phi_g$ (`cscale[g] = 1/phi_g`), which both codes now retain for accuracy on multigroup problems (A5).

### A8. Additional details

**Interface value in the flux-divergence form.** Section 5 of the initial paper draft defined $\phi_{i+1/2} = \min(\phi_i, \phi_{i+1})$ in the prose (so a thick cell cannot impose a CFL-violating wave speed on an adjacent thin cell) while writing $\hat{c}_{i+1/2} = \max(\phi_i, \phi_{i+1})c$ in the end-of-section summary table. With $\phi$ on the time derivative (`flux_form = false`, the default since `b287f03`), no face value is needed; when `flux_form = true`, Honghu uses $\min(\phi_i, \phi_{i+1})$, verified in `test/test_rsla.jl`.

**Evaluating the bound with the actual substep $\Delta t$.** Writing the bound in terms of the nominal radiation CFL number $C_r$ assumes $\Delta t = C_r \Delta x/(\phi_0 c)$. Whenever $\Delta t$ is smaller (because hydrodynamics restricted the step or subcycling divided it unevenly), using the actual $\Delta t$ passed to `update_chat!` allows a larger stable $\phi$. Because `run!` shortens the final step to hit `tmax` exactly, $\phi$ on that final step is larger than during the rest of the run; `examples/irsla_paper.jl` therefore records $\phi$ from the last full step.

### A9. Open questions

If the Mach 3 non-monotonicity in A4 comes from HLL numerical diffusion growing with $\phi\,c\,\Delta x$ in thin cells while the RSLA source error scales with $(1-\phi)$, choosing $\phi$ to minimise their sum (subject to the stability bound) could improve accuracy below the stability limit. In addition, the directional signal speed $\sigma_d$ is currently evaluated at the start of the IMEX substep and held fixed across both stages; in a cell that transitions from isotropic to free-streaming within a single step, the end-of-step wave speed exceeds the start-of-step estimate.



---

<!-- page: photoionization-findings.md -->

# Photoionization: the chemistry integrators and the reduced speed of light, measured

This note reports what was measured on the Stromgren-sphere tests of Iliev et al. (2006), which Honghu runs through `Honghu.Problems.stromgren_iliev` with the hydrogen network `HydrogenOTSA` and the photon band of `Photochemistry`. That hand-written network has since been replaced by networks generated by JAFF, which agree with it to $2\times10^{-8}$ in every rate; the measurements here were taken with it, at commit `cbf6fae`. It answers four questions: what the chemistry costs per cell, how far the single-step `BackwardEulerChem` is from the adaptive `RosenbrockChem` on a real problem, how small the reduced speed of light $\hat c$ can be before the result changes, and how much the default heating per ionization overheats Test 2. It also records two choices in the scheme that the results depend on (section 5).

Every number in the tables of parts 1 to 3 below is produced by `docs/photoionization-experiments/measure.jl` and written to `docs/photoionization-experiments/measure.txt`, which also holds the radial profiles and the counts that this note does not repeat. Other numbers have other sources, and each one says where it comes from: a single run of `examples/stromgren_sphere.jl` (the centred $64^3$ run and the $n = 32$ octant), the work on the two integrators and on the photochemistry step (named by commit, because the measuring scripts are not in the repository), or a formula (the front speed, $3c_s$). The numbers come from one machine (Apple silicon, Julia 1.12.6, `-t 8`), so the timings are for that machine and the physics is not.

## What was measured

```bash
julia --project=. -t 8 docs/photoionization-experiments/measure.jl          # all three parts, about 3 minutes
julia --project=. -t 8 docs/photoionization-experiments/measure.jl cost     # one part (it only prints)
```

The one-thread timings need a second Julia process, because the threaded loops follow `Threads.nthreads()`. The script starts it itself.

| Part | Setup |
|:---|:---|
| 1. Cost | `chemistry_step!` on a $32^3$ octant of each test with $\hat c = 3\times10^{-4}c$, after $0.25\,t_{\rm rec}$ so that the front is in the box. The median of 5 calls that all start from the same state, on 1 and on 8 threads, with both integrators. |
| 2. Integrators | Test 2 at $n = 16$ and $\hat c = 3\times10^{-4}c$, to 100 and 500 Myr, with `RosenbrockChem()` (relative tolerance $10^{-2}$, the default), the same with $10^{-4}$ (a check on the reference) and `BackwardEulerChem()`. The ionized radius, the temperature and neutral fraction averaged in 16 radial bins, and the wall time. Also the same run with the heating per ionization set to 6.3 eV. |
| 3. Reduced speed of light | Test 1 at $n = 16$ with $\hat c/c = 10^{-4}$, $3\times10^{-4}$, $10^{-3}$ and $3\times10^{-3}$, the ionized radius at 10, 30, 100 and 500 Myr against `stromgren_radius_finite_c` and `stromgren_radius_analytic`. Also, at each time, where the front lies along an axis and along the body diagonal, and at 500 Myr the radius of the recombination volume and how the gap between $\sum x$ and $\sum x^2$ is made up. |

The radius $r_I$ is `ionized_radius`: the radius of a sphere with the volume of the ionized gas, $\sum (x - x_0)/(1 - x_0)\,dV$ over the cells. The recombination time is $t_{\rm rec} = 1/(\alpha_B n_{\rm H}) = 122.3$ Myr and the analytic Stromgren radius is $r_S = 5.39$ kpc, both from the formulas in the docstring of `stromgren_radius_analytic`.

## Headlines

- The cost gate passed with room to spare (section 1), so no fast path and no in-tree integrator was needed. A run of the default example takes minutes on 8 threads.
- On Test 2 the single backward-Euler step agrees with the Rosenbrock reference to a fraction of a percent in the ionized radius and in the temperature of the ionized gas, differs where the profile is a few cells wide, at the front, and makes the whole run about 4.5 times faster (section 2). That is one problem at one substep; section 2 and the `BackwardEulerChem` docstring say where backward Euler is known to fail.
- The run follows the finite-$\hat c$ reference for $\hat c \geq 10^{-3}c$ at all times and for $3\times10^{-4}c$ from 100 Myr on, and not at $10^{-4}c$ (section 3). That is consistent with the expectation $\hat c > 3c_s$, but the sweep cannot place the threshold. A $\hat c$-independent excess of the saturated radius is a feature of how the front is counted, and the photon budget closes.
- The default heating per ionization is 2.5 times the optically thin value and raises the temperature of the ionized gas by about a tenth (section 4).
- Two things in the scheme bias the result and are not removed: the emission is injected before the burn, and the species are renormalised, not advected conservatively (section 5).

## 1. Cost of the chemistry step

| Test | Integrator | 1 thread ($\mu$s per cell) | 8 threads ($\mu$s per cell) | Solver steps per cell, mean / max (Newton iterations for backward Euler) |
|:---|:---|---:|---:|:---|
| 1 | `RosenbrockChem` | 5.02 | 0.73 | 15.0 / 20 |
| 1 | `BackwardEulerChem` | 0.085 | 0.016 | 1.03 / 3 |
| 2 | `RosenbrockChem` | 6.49 | 0.94 | 15.0 / 19 |
| 2 | `BackwardEulerChem` | 0.064 | 0.014 | 0.15 / 3 |

The gate was 20 $\mu$s per cell on one thread for `RosenbrockChem`; it passes by a factor of 3 to 4. Eight threads speed it up by a factor of 6.9 in both tests.

That scaling needs the pure-Julia linear solver the integrator uses. With the integrator's default factorisation, which calls OpenBLAS, one $24^3$ chemistry step took 84.7 ms on one thread and 183.7 ms on four, because OpenBLAS takes a global lock to allocate its buffers on every call. With LinearSolve's `SimpleLUFactorization` the same step took 73.7 ms and 20.0 ms. Those two pairs were measured when the fix was made (commit `9668501`) and `measure.jl` does not reproduce them; its 8-thread scaling above is an independent confirmation on a different problem.

The Rosenbrock cost is nearly the same in all cells: a mean of 15 steps and a maximum of 20, with only 1.8% of the cells ionized. So most of the cost is the integrator taking about 15 steps in cells where little changes, and not the physics of the front. I did not look at the steps of a single quiet cell. A fast path for cells whose state does not change would cut the cost, and was not built.

The default example, the centred $64^3$ box at $\hat c = 3\times10^{-4}c$ over 500 Myr (`examples/stromgren_sphere.jl`), was run once on 8 threads, with figures: it took 8 min 40 s, with 0 failed chemistry solves in 585 million and 15.1 solver steps per cell on average. That is well inside the 30 minutes that the 20 $\mu$s gate stood for. Its $r_I$ at 100, 200 and 500 Myr (3.906, 4.830 and 5.463 kpc) is the same to 0.01% as that of the octant of the example at $n = 32$, which has the same cell size (`examples/stromgren_sphere.jl 1 32 octant`), so the whole sphere with outflow walls and the corner octant with reflecting walls agree. Both are outputs of the example and are not in `measure.txt`.

## 2. The two integrators on Test 2

| | `RosenbrockChem` | Rosenbrock, tolerance $10^{-4}$ | `BackwardEulerChem` |
|:---|---:|---:|---:|
| Wall time to 500 Myr, 8 threads | 5.9 s | 6.0 s | 1.3 s |
| Solver steps per cell, mean / max (Newton iterations for backward Euler) | 16.0 / 20 | 16.5 / 31 | 1.33 / 5 |
| Failed solves, of 4.57 million | 0 | 0 | 0 |

The substep of this run is 0.45 Myr, 0.4% of $t_{\rm rec}$. Against the default Rosenbrock result:

| | 100 Myr | 500 Myr |
|:---|---:|---:|
| Backward Euler, $r_I$ | $-0.018\%$ | $+0.098\%$ |
| Backward Euler, temperature of the cells with $x_{\rm H^+} > 0.9$ | $-0.055\%$ | $-0.056\%$ |
| Backward Euler, largest bin-averaged $T$ difference | 28.8% | 2.4% |
| Backward Euler, largest $x_{\rm HI}$ difference | $8.1\times10^{-3}$ | $8.3\times10^{-3}$ |
| Rosenbrock at $10^{-4}$, $r_I$ | $0.000\%$ | $0.000\%$ |
| Rosenbrock at $10^{-4}$, largest bin-averaged $T$ difference | 1.7% | 0.009% |

Behind the front backward Euler is as good as the reference allows: the ten bins inside the front agree to better than 0.5% at 100 Myr. The differences are in the bins that hold the front. At 100 Myr those are bins 11 to 13, where the mean temperature is 9401, 1538 and 120 K for backward Euler and 8961, 1195 and 108 K for the reference. At 500 Myr the front is in the last bin, 9545 against 9318 K. These are averages over the few cells that the front crosses, and one backward-Euler step is first order in time there. I did not test that, for instance by shortening the substep, so the cause is a guess.

The reference is itself good to the level it is used at: tightening the tolerance from $10^{-2}$ to $10^{-4}$ moves $r_I$ by less than $10^{-5}$ in relative terms and the front bins by up to 1.7%, which is 17 times less than the backward-Euler difference there.

The cost: backward Euler is 45 to 100 times cheaper per cell (section 1), and makes the whole run 4.5 times faster. The 4.6 s that the two wall times differ by is the chemistry, which is then about three quarters of the Rosenbrock run, if the rest of the step costs the same in both.

**Backward Euler failed nowhere in this run, and that does not carry over.** A stress sweep run when `BackwardEulerChem` was written (final solver in commit `bba25f9`; the script is not in the repository, and its numbers are not reproduced by `measure.jl`) used a synthetic grid of 2592 cells with $n_{\rm H} = 10^{-4}$, $10^{-2}$ and $1$ cm$^{-3}$, $T$ from 30 K to $10^5$ K, $x_{\rm H^+}$ from 0 to 0.999, several photon densities and steps of $10^8$, $10^{11}$ and $10^{13}$ s, and not the states of this problem. It left 269 cells (10.4%) unconverged even with the line search: 182 of 300 where collisional growth is stiff ($\beta n_{\rm H^0}\Delta t > 1$), 74 of 123 at the front with $\Gamma\Delta t \geq 10^2$, and 13 of 2169 (0.6%) elsewhere. A second group at exactly 100 K left 150 of 432 cells unconverged: 130 of the 404 cells away from the front, where the recombination cooling switches on at 100 K and the energy iterate alternates across it, and 20 of the 28 front cells. `RosenbrockChem` converged in all 3888 cells of the three sweeps, which also include steps of $3\times10^{14}$ s. So backward Euler is a good answer on this problem at this substep, and it is the cheap choice, but only `RosenbrockChem` is safe where the gas is hot and neutral or the step is long. How the backward-Euler error depends on $\hat c$ and $n$, which set the substep through $\Delta t \propto \Delta x/\hat c$, was measured at one pair only.

## 3. The reduced speed of light on Test 1

The error of the ionized radius against the finite-$\hat c$ front equation, $r_I/r_{\rm ref} - 1$, at $n = 16$:

| $\hat c/c$ | $\hat c$ (km s$^{-1}$) | 10 Myr | 30 Myr | 100 Myr | 500 Myr |
|:---|---:|---:|---:|---:|---:|
| $10^{-4}$ | 30 | $+382.27\%$ | $+90.93\%$ | $+7.80\%$ | $+4.54\%$ |
| $3\times10^{-4}$ | 90 | $+76.29\%$ | $+6.67\%$ | $+2.63\%$ | $+2.94\%$ |
| $10^{-3}$ | 300 | $+4.95\%$ | $+1.32\%$ | $+1.41\%$ | $+2.70\%$ |
| $3\times10^{-3}$ | 900 | $+0.88\%$ | $+0.66\%$ | $+1.02\%$ | $+2.66\%$ |

The same radii against the $\hat c = c$ curve are in `measure.txt`.

**Where it follows.** At 500 Myr the three runs with $\hat c \geq 3\times10^{-4}c$ agree to 0.52% ($r_I = 5.474$, $5.496$ and $5.502$ kpc), as the equilibrium requires: the Stromgren radius does not depend on $\hat c$. The $\hat c = 10^{-4}c$ run has not saturated. The radius of its recombination volume (see below) is 5.22 kpc, 2.6% below the analytic radius at 500 Myr, 5.363 kpc, and its $r_I = 5.362$ kpc is 4.5% above the finite-$\hat c$ reference of 5.129 kpc. Before 500 Myr, the run follows the reference to within 5% at every time shown from $10^{-3}c$ on (4.95% at worst), and from 100 Myr on at $3\times10^{-4}c$ (2.6%). At $10^{-4}c$ it is 7.8% and 4.5% off at 100 and 500 Myr.

**The early-time errors at low $\hat c$ are large, and the source size may contribute to them.** At 10 Myr the reference radius of the two smallest $\hat c$ is 0.31 and 0.87 kpc, which is less than one and about two cells (0.41 kpc at $n = 16$), and less than the extent of the source, a Gaussian of width $1.5\,\Delta x = 0.62$ kpc that is cut at 1.55 kpc. For the two largest $\hat c$ the reference radius (1.75 and 2.12 kpc) is larger than the source and the errors are 4.95% and 0.88%. The radii the two smallest runs report, 1.48 and 1.54 kpc, sit near the source size, which suggests the source sets $r_I$ there. A run at $n = 32$ ($3\times10^{-4}c$, the octant of the example) gives 1.10 kpc: closer to the reference (0.87 kpc) but still above it, and above the source's cut radius at that resolution (0.77 kpc). So the error falls with resolution, and I did not establish how much of it the source extent explains. The $n = 32$ value is an output of the example and is not in `measure.txt`.

**Against the expectation $\hat c > 3c_s$.** The design specification takes $3c_s \approx 45$ km s$^{-1}$, between $10^{-4}c$ (30 km s$^{-1}$, which does not follow) and $3\times10^{-4}c$ (90 km s$^{-1}$, which does from 100 Myr on). So the sweep is consistent with the expectation, and it cannot say more: it has no point between the two. With hydrodynamics off the gas does not move, so $c_s$ does not enter this test. What matters is the speed of the front, $v_I = (r_S/3t_{\rm rec})\,e^{-t/t_{\rm rec}}(1 - e^{-t/t_{\rm rec}})^{-2/3}$ with $r_S/3t_{\rm rec} = 14.4$ km s$^{-1}$, which is about 70, 30 and 9 km s$^{-1}$ at 10, 30 and 100 Myr (computed from this formula), and which $\hat c$ must exceed for the run to resemble the $\hat c = c$ solution. That is a stronger condition than following the finite-$\hat c$ reference: against the $\hat c = c$ curve at 100 Myr the radii are $-11.7\%$ at $3\times10^{-4}c$, $-2.6\%$ at $10^{-3}c$ and $-0.3\%$ at $3\times10^{-3}c$.

**The excess of 2.7% to 2.9% at 500 Myr does not depend on $\hat c$,** for $\hat c \geq 3\times10^{-4}c$, so it is not a $\hat c$ effect. What was measured: $r_I$ counts ions, $\sum x\,dV$, while the recombinations that balance the photons go as $\sum x^2\,dV$. The radius of the recombination volume, $8\sum x^2\,dV$ with $x = x_{\rm H^+}$ in the octant, is 0.9%, 0.6% and 0.5% below the analytic radius at 500 Myr (5.363 kpc) for $3\times10^{-4}c$, $10^{-3}c$ and $3\times10^{-3}c$, so the photon budget closes to about 1%, and $r_I$ is high because $\sum x$ exceeds $\sum x^2$ by $\sum x(1-x)$. Two things contribute to that sum, and I did not separate them. One is the neutral fraction left behind the front: in the three saturated runs the mean over the cells with $x > 0.5$ is 0.07 to 0.08, and 29% to 30% of $\sum x(1-x)$ comes from the cells with $x > 0.9$. The other is the transition layer itself: 397 to 415 of the 4096 cells have $0.1 < x < 0.9$ in those runs, and the rest of the sum (70% to 71%) comes from the cells with $x \leq 0.9$, which include that layer. A front narrower than a cell is not the whole explanation: if it were, the excess should roughly halve when the cell does, and it does not; the $n = 32$ octant of the example gives $+2.75\%$ against the finite-$\hat c$ reference at 500 Myr, against $+2.94\%$ at $n = 16$ for the same $\hat c$ (an output of the example, not in `measure.txt`). So the excess is not set by the cell size alone, and the width of the transition layer, numerical or physical, was not examined.

The part of the error that grows as $\hat c$ falls (at 100 Myr: 1.02%, 1.41%, 2.63% and 7.80% from $3\times10^{-3}c$ to $10^{-4}c$) is not explained here. The candidates are that the HLL scheme diffuses the photons in flight, the source size above, and the reference itself. The reference of Shapiro et al. (2006), `stromgren_radius_finite_c`, counts the photons in flight as $\dot N R/\hat c$ and ignores their depletion by recombinations inside $R$. A sharp-front version of that term, $(\dot N - 4\pi R^3\alpha_B n^2/3)/\hat c$, moves the reference radius by +1.5% to +1.9% at $\hat c = 3\times10^{-4}c$ and +0.6% at $10^{-3}c$. That estimate was made when the reference was written (the wording of its docstring is from commit `d482aa3`), it is not in the code or in `measure.txt`, and it has the sign and the $\hat c$ trend of the unexplained part. I list it as a candidate, not a finding. None of the candidates was tested.

**The front is not round.** The last lines of each block of part 3 in `measure.txt` give the position where $x_{\rm H^+}$ falls through 0.5 along the row of cells next to an axis and along the body diagonal. At $n = 16$ and $\hat c = 3\times10^{-4}c$ the diagonal is 9% behind the axis at 100 Myr (3.64 against 3.99 kpc) and 3% ahead at 500 Myr (5.58 against 5.41 kpc); at $10^{-3}c$ and $3\times10^{-3}c$ it is 1.5% and 4.3% behind at 100 Myr and 3.1% and 3.0% ahead at 500 Myr. The centred $64^3$ run shows it as lobes in the slice of the neutral fraction. A saturated Stromgren sphere should be round, so this is probably a grid imprint of the transport scheme at this resolution. It averages out of $r_I$ to first order, since $r_I$ is a volume, and I did not look for its cause.

## 4. The overheating of Test 2

The default heating per ionization of the network is $\varepsilon_b - 13.6$ eV $= 16.05$ eV for the 29.65 eV band of Test 2. The optically thin value for the $10^5$ K blackbody is about 6.3 eV (design specification, section 4.3), so the default is 2.5 times too large. The same run with `heating_energy = 6.3 eV` (part 2 of the script builds it itself; the replica reproduces the factory run exactly) gives:

| Heating per ionization | $T$ of the cells with $x_{\rm H^+} > 0.9$, 100 Myr | 500 Myr | $r_I$, 100 Myr | 500 Myr |
|:---|---:|---:|---:|---:|
| 16.05 eV (default) | 14756 K | 13704 K | 3.995 kpc | 5.932 kpc |
| 6.3 eV | 12988 K | 12317 K | 3.963 kpc | 5.806 kpc |

So 2.5 times the heating raises the temperature of the ionized gas by 13.6% and 11.3%, and the radius by 0.8% and 2.2%, through $\alpha_B(T)$. The temperature responds weakly because the cooling rises steeply with it, in particular the Lyman $\alpha$ term, which is exponential in $1/T$. That is my reading, and I did not isolate it. Near the source the default run reaches 23900 K in the innermost bin, against 9300 K in the front bin at 500 Myr. Neither run is the real spectrum: a single band has no hardening of the spectrum with radius, so these temperatures should not be compared with the paper's profile. The numbers say only how much the gas temperature moves with the heating energy when everything else is kept.

## 5. Two choices in the scheme that the results depend on

Neither was measured by `measure.jl`. Both are recorded here because they bias what the sections above report, and because each has a follow-up that is the user's decision.

**The emission is injected all at once at the start of each substep.** The chemistry step adds $\phi\,\dot N\,\Delta t$ to the photon density before it integrates the cell, as Quokka does for its chemical bands. In an opaque cell the burn absorbs those photons within a small part of the step, so the ionization fraction at the end of the step sits below its equilibrium by about $\alpha n x^2\Delta t/2$: the scheme is first order in the substep. In the uniform opaque test box of `test/test_chemistry.jl`, measured when the step was written (commit `8e86f10`), the equilibrium $x = 0.5$ came out as 0.4939 at $\hat c = 10^{-2}c$ ($\Delta t = 0.05\,t_{\rm rec}$) and as 0.4450 at $\hat c = 10^{-3}c$ ($\Delta t = 0.5\,t_{\rm rec}$), and it converged to 0.5 linearly in $\Delta t$ when the substep was cut (0.49938 and 0.49993 for a substep 10 and 100 times smaller at $\hat c = 10^{-2}c$). The substep is set by $\hat c$, so a smaller $\hat c$ means a larger bias. I did not measure the bias in the Stromgren runs. Two follow-ups would remove it: injecting the emission with Strang splitting, half before and half after the burn, or putting the emission inside the ODE. The second is kept out of the ODE on purpose (`chemistry.jl`), so that the two integrators solve one problem, and it needs a decision.

**The species are renormalised to add up to $\rho$.** Each $\rho X_s$ is reconstructed and limited on its own, so the species fluxes do not add up to the mass flux. With PLM or PPM the per-cell sum $\sum_s X_s$ then drifted from 1: after 10 steps of a two-species run on an 8-cell sine, the largest deviation was $4\times10^{-16}$ with PCM, $1.1\times10^{-2}$ with PLM and $3.7\times10^{-2}$ with the default PPM (measured in the work behind commit `9668501`, not reproduced by `measure.jl`). With a network, `enforce_scalar_floors!` therefore rescales the species of each cell so that they add up to $\rho$, which is Quokka's cure in `EnforceLimits`. The rescaling does not conserve each species separately. The conservative alternative, CMA (Plewa & Mueller 1999), is not implemented. The Stromgren tests here have hydrodynamics off, so nothing advects the species in them.

## What is not known

- Which part of the backward-Euler error at the front is the time step. The cheap test is the same run at a larger $\hat c$, which shortens the substep.
- The origin of the part of the radius excess that grows as $\hat c$ falls (section 3), and whether the finite-$\hat c$ reference or the scheme is closer to the truth there; and the width of the transition layer behind the $\hat c$-independent excess.
- How much of the early-time error at low $\hat c$ the source extent explains.
- The cause of the anisotropy of the front, and how it scales with $n$.
- The size of the emission-injection bias in the Stromgren runs.
- Anything at $n > 16$ for parts 2 and 3. The octant example at $n = 32$ gives $r_I = 5.463$ kpc at 500 Myr against 5.474 kpc at $n = 16$ for the same $\hat c$.
- The Test 2 profile against published data. The band is one cross-section and one photon energy, so only the shape is checked.


---

<!-- page: parallel-findings.md -->

# Shared-memory parallelism: what the measurements say

How Honghu uses the cores of one shared-memory node, what was changed to make it use them better, and what each change bought. Every number here is a step of the 3D Sedov blast (`Problems.sedov_blast`: PPM, HLLC, SSPRK3, outflow boundaries), timed by `test/benchmarks_parallel.jl`.

## Summary

The 3D Sedov blast at 128³, the same machine, the code before and after, run back to back:

| | before | after | gain |
|:---|---:|---:|---:|
| 1 thread | 1381 ms | 1201 ms | 1.15× |
| 32 threads | 141 ms | 93 ms | 1.52× |
| 32 threads, pinned | 136 ms | 82 ms | 1.66× |
| speedup over 1 thread (32, pinned) | 10.2× | 14.6× | |

The answers are the same to the bit, on every problem checked, at every thread count. Three changes carry it. **Tiling** the hydrodynamic sweep (section 7) moves the interface states and fluxes out of whole-grid arrays and into cache. **Forming the Runge–Kutta stage in the last sweep** (section 8) removes a four-array pass per stage. **Splitting each kernel's body into a row function** that the tile driver shares made one thread 13% faster on its own (section 7). Pinning the threads is worth another 10% at 32 threads, but only when the job uses every core (section 6). The goal set at the outset, 70 ms at 32 threads, was not reached. The measurement in section 7 says why it could not have been: with every core busy, each core runs 1.47× slower than one core alone, so the ideal is about 56 ms, and the sweeps are now within 10–15% of their share of it. Section 9 lists what remains. Section 10 then rewrites the sweep's kernels as functions of one cell behind a single launch point, as AMReX and Quokka do, at no cost to the CPU, and runs the same kernels on a GPU, where they agree with the CPU to round-off. Section 11 measures an Apple M5 Max, where tiling is slower at every thread count, so the default does not tile there.

## Machine and method

- AMD Ryzen Threadripper PRO 7975WX: 32 cores, 64 hardware threads, one socket, one NUMA node. 1 MiB L2 per core, 128 MiB L3 in four 32 MiB slices (one per 8-core CCD). 124 GB RAM. Julia 1.13.4, Linux 6.12.
- `julia --project=. -t N test/benchmarks_parallel.jl n [--passes]`. The script takes three warm-up steps, then reports the minimum over 7 steps at a fixed `dt`. Threads are unpinned unless a row says otherwise.
- The node is shared, with a load average of about 4 from other users during these measurements. Differences under about 5% are within the noise and are not claimed.
- Every change is checked bit for bit against the state before any change, after 10 steps of seven problems: Sedov at 48³ and 37³ (PPM and PLM), a 2D Kelvin–Helmholtz, a 1D Sod, a 3D run with two mass scalars, and a 3D radiation-hydrodynamics run. The check compares `U`, `R`, `t` and the floor counters with `==`.

## Baseline

| threads | 128³ ms/step | speedup | 256³ ms/step | speedup |
|---:|---:|---:|---:|---:|
| 1 | 1373 | 1.0 | 10892 | 1.0 |
| 2 | 717 | 1.9 | | |
| 4 | 407 | 3.4 | | |
| 8 | 250 | 5.5 | 1994 | 5.5 |
| 16 | 188 | 7.3 | | |
| 32 | 137 | 10.0 | 1037 | 10.5 |
| 64 | 139 | 9.9 | 1027 | 10.6 |

Per pass, 128³ (each step runs three right-hand sides, each with one sweep per direction):

| pass | 1 thread | 32 threads | speedup |
|:---|---:|---:|---:|
| sweep (reconstruct + HLLC + divergence), each | 145 ms | 11.0 ms | 13 |
| of which HLLC | 89 ms | 5.0 ms | 18 |
| of which PPM | 48 ms | 3.9 ms | 12 |
| of which divergence | 6.5 ms | 1.7 ms | 4 |
| `cons2prim!` | 4.7 ms | 1.7 ms | 2.8 |
| `enforce_floors!` | 3.6 ms | 0.45 ms | 8 |
| `fill!(dU, 0)` (serial) | 2.6 ms | 2.5 ms | 1 |
| `copyto!(U0, U)` (serial) | 4.4 ms | 4.4 ms | 1 |
| `combine!` | 8.6 ms | 2.5 ms | 3.4 |
| `hydro_rhs!` total | 447 ms | 40 ms | 11 |

The arithmetic scales: HLLC reaches 18× on 32 cores. The passes that only move memory do not, and two of them do not run in parallel at all. Each sweep writes the full-grid interface states `qL` and `qR` and the full-grid `flux`, 84 MB each at 128³, and reads them back in the next pass, so past about 8 threads a step is bound by memory traffic and serial code, not by arithmetic. The 64 hardware threads give nothing over 32 cores.

## Changes, in the order they were made

### 1. Thread the serial whole-array copies

`hydro_rhs!` zeroed `dU` with `fill!`, `advance_hydro!` saved the stage-0 state with `copyto!`, and the radiation path did the same with `dR` and `Utmp`. All four were serial, and a single core cannot saturate the memory bus. `threaded_fill!` and `threaded_copyto!` (`src/grid.jl`) split the array into one contiguous chunk per thread through `threaded_chunks`.

| pass, 128³, 32 threads | before | after |
|:---|---:|---:|
| `copyto!(U0, U)` | 4.4 ms | 1.6 ms |
| `fill!(dU, 0)` | 2.5 ms | 0.8 ms |
| step | 137 ms | 131–133 ms |

That is about 8 ms of serial work a step, 4% at 32 threads. The 1-thread step is unchanged (1380 ms). Results are bit-identical.

### 2. Ghost filling: not threaded, deliberately

The plan was to split each built-in boundary face over threads. Measured first, the whole `fill_ghosts!` of the gas state costs 0.47 ms at 128³ on one thread, and it runs once per right-hand side, so at most 1.4 ms of a 131 ms step (1%) is there to be won. Ghost work scales with the surface (n²), not the volume (n³), so the fraction falls as the grid grows. That is within the noise of these measurements, and it is not worth complicating `fill_face!`, which users extend. It stays serial.

### 3. Fold the zeroing of `dU` into the first sweep

`flux_divergence!` takes `overwrite = true` for the first active direction, which stores `-ΔF/Δx` instead of subtracting it, so `hydro_rhs!` and `rad_rhs!` no longer zero `dU` and `dR` first. This removes one whole-array write per right-hand side, three per step. Only the sign of an exact zero can differ (`-0.0` against `0.0`), which `==` does not see, and nothing reads the ghost cells of `dU`. Measured: 131 → 130 ms at 32 threads, 1380 → 1366 ms at 1 thread. That is within the noise, as expected after change 1 had already made the zeroing 0.8 ms. It is kept because it costs nothing and removes a pass.

### 4. Fusing the floors into the conversion: not done

The plan was to fold `enforce_floors!` and `enforce_scalar_floors!` into `cons2prim!` in a single pass. The pass this would remove costs 0.45 ms at 32 threads (the scalar floors return at once without scalars), so at most 1.4 ms of a 130 ms step is there to be won. That is below the noise, and it would touch the split between projection and read-only conversion, which CLAUDE.md asks to preserve. Not done.

### 5. Static, contiguous scheduling: no gain, reverted

`Threads.@threads` defaults to dynamic scheduling. A variant of `threaded_jk` that gives each thread one contiguous block of `(j, k)` rows, so neighbouring rows share a core's cache, was tried on every hydrodynamic kernel (reconstruction, Riemann fluxes, divergence, floors, conversion, combine):

| threads | dynamic | static |
|---:|---:|---:|
| 1 | 1366 ms | 1376 ms |
| 8 | 250 ms | 241 ms |
| 32 | 130 ms | 134 ms |
| 64 | 139 ms | 129 ms |

All within the noise. The passes are bound by memory traffic, not by the scheduler or by cache reuse between neighbouring rows: a row of 128 cells is 5 kB per variable array, and the stencil of a `y` or `z` sweep reaches rows a whole plane away. Reverted.

### 6. Thread pinning: 10–16%, for free

`JULIA_EXCLUSIVE=1` pins Julia's thread `i` to CPU `i`. On this node CPUs 0–31 are the 32 physical cores and 32–63 their hyperthread siblings (`lscpu -e`), so `-t 32` gets one thread per core. Unpinned, the OS migrates threads between cores, and each thread loses the L2 contents its rows left behind. Measured twice at 32 threads:

| threads | unpinned | `JULIA_EXCLUSIVE=1` | gain |
|---:|---:|---:|---:|
| 16 | 194 ms | 164 ms | 16% |
| 32 | 132, 131 ms | 119, 119 ms | 10% |
| 64 | 129–139 ms | 123 ms | |

No code change. The README recommends it. Two caveats: it assumes the job has the whole node, or at least CPUs `0:N-1`, because a batch system that hands out other CPUs needs its own binding (`taskset`, or `srun --cpu-bind=cores`); and on a node with more than one NUMA domain the first-touch placement of the arrays would also matter, which this single-domain node cannot measure.

### 7. The tiled hydrodynamic sweep

`src/tiling.jl`. The sweep along `D` no longer makes three passes over whole-grid arrays. It goes box by box: reconstruct, solve the Riemann problems and take the divergence for one box, with the box's interface states and fluxes in a per-task scratch array that stays in cache. Only `dU` is written to the whole grid. This is AMReX's tiling, and Quokka's: box-local temporaries around the same pointwise kernels. Here the kernels are literally the same. Each kernel's per-row body became an `@inline` function (`_reconstruct_row!`, `_hydro_flux_row!`, `_divergence_row!`) that the whole-grid kernel and the tile driver both call, and the scratch is a `TileArray`, indexed with global cell indices like AMReX's `Array4`. Results are bit-identical, with any tile, to the untiled sweep and to the code before any change. `test/test_parallel.jl` checks this on 3D, 2D and 1D problems, with PCM, PLM and PPM, with and without mass scalars, and on grids that the tile does not divide.

**Tile shape.** A box spans the whole interior along the sweep, so no face is computed twice, and blocks of `tile[e]` cells along each other direction `e`. Pinned, 32 threads:

| tile | 64³ | 128³ | 256³ |
|:---|---:|---:|---:|
| untiled | 26.6 | 121 | 976 |
| (8, 8, 8) | | 94 | 801 |
| (4, 4, 4) | 17.2 | 92 | 691 |
| (8, 2, 2) | 16.8 | 87–89 | 606–662 |
| (16, 1, 1) | | 85 | 651 |
| (32, 1, 1) | | 85–86 | 631–678 |
| (128, 1, 1) | | 86 | 755 |

Two things set the optimum. The scratch of a box is `3 nvar (n_D + 3) b b'` numbers, and it has to fit in a core's 1 MiB L2: (128, 1, 1) is as good as any at 128³, but at 256³ its 4 MB scratch spills and it loses. Short rows cost loop overhead: (2, 2, 2) is 112 ms. `DEFAULT_TILE = (32, 1, 1)` is among the best at both sizes, with a scratch of 0.5 MB at 128³ and 1 MB at 256³.

**Not on one core.** On one thread every tile was 5–10% slower than untiled, repeatably (1276–1335 ms against 1211 ms at 128³). That holds in each direction, the `x` sweep included, whose rows are full length, so it is not row length. Wrapping the scratch as a plain `Array` made it worse (`x` sweep 182 ms against 131 ms). A single core has no contention on the memory bus for tiling to relieve. The crossover, untiled against `(32, 1, 1)`:

| threads | 2 | 4 | 8 | 16 | 32 |
|:---|---:|---:|---:|---:|---:|
| untiled | 663 | 375 | 230 | 159 | 121 |
| tiled | 693 | 382 | 219 | 147 | 85 |

So `Simulation(tile = :auto)`, the default, tiles from `TILE_MIN_THREADS = 8` threads and not below, and never on Apple Silicon (section 11). A tuple forces a tile, and `nothing` forces the untiled sweep.

**Not on a grid with too few boxes.** The tile was tuned on 3D Sedov, but a sweep's tasks are its boxes, and a 2D run's transverse sweep has few of them: `ceil(n1/32)` with `(32, 1, 1)`. The final review measured Kelvin–Helmholtz at 32 threads. At 256² the step was unchanged by tiling, at 512² (16 boxes, half the threads idle) it was 4% slower, and at 1024² it was 18% faster (51.4 → 42.1 ms). So `:auto` also requires at least one box per thread in every active direction. That covers every 3D grid from about 32³ on, and 2D grids from 1024² at 32 threads.

**A bug worth recording.** The first version picked up each task's scratch in the spawning loop, in the same function as the one-task branch, which assigned the same local names. The loop's assignments then rebound variables the spawned closures had captured (the boxing trap of CLAUDE.md's performance rules), so tasks shared one scratch and the result depended on timing. The allocation test could not see it, since it costs bytes per task and not per cell, and on one thread it cannot happen. The bit-identity tests at `-t 4` caught it at once. Each task now takes its scratch from its chunk number inside the task.

**Where it stands.** At 128³, 32 threads: unpinned 97 ms, pinned 85.5 ms (from 137 and 121 before tiling). A sweep takes 6.4–8 ms, against 11 ms untiled. One more measurement puts that in proportion. The same HLLC row kernel on a cache-resident grid, one private copy per task, runs 1.47× slower per core with 32 tasks than with one (1.32× with 8, 2.40× per hardware thread with 64). Nothing is shared there, so this is the clock dropping from its single-core boost, plus the other users of the node, and it is a ceiling no software change moves. Scaled by it, the ideal 32-core step is 1217 × 1.47 / 32 ≈ 56 ms, and the sweeps, about 60 ms a step, are close to their share of it. What is left above that is the passes that still stream whole arrays: about 20 ms a step.

### 8. The Runge–Kutta stage formed in the last sweep

`combine!` formed each stage, `U = a U0 + b U + c Δt dU`, as a pass of its own over four whole arrays: 2.3 ms at 32 threads, three times a step. Now `hydro_rhs!(dU, U, sim; update = (a, U0, b, c Δt))` hands the stage to the last active sweep, whose divergence row forms `U` directly from the fluxes, with the same arithmetic as `combine!`, and never stores the final `dU`. This is safe because the sweeps read `prim`, never `U`. It is also how Quokka forms its stages: from the fluxes, with no stored right-hand side. Bit-identical, checked against `hydro_rhs!` followed by `combine!` in 3D, 2D and 1D, tiled and untiled. Pinned, 32 threads: 85.5 → 82.0 ms. Unpinned: 97 → 93.5 ms. 64 threads pinned: 78.4 ms.

### 9. Final numbers, and what is left

Sedov, final code, one run each (128³ before and after are also in the summary, run back to back):

| threads | 128³ unpinned | 128³ pinned | 256³ unpinned | 256³ pinned |
|---:|---:|---:|---:|---:|
| 1 | 1201 | 1249 | 9526 | 9864 |
| 2 | 628 | 657 | | |
| 4 | 354 | 363 | | |
| 8 | 198 | 216 | 1625 | 1747 |
| 16 | 115 | 140 | 881 | 1064 |
| 32 | 93 | 82 | 690 | 670 |
| 64 | 90 | 78 | 634 | 640 |

At 256³ the step went from 1037 ms to 690 ms at 32 threads (1.50×), and from 10.9 s to 9.5 s on one thread.

**Pinning, revised.** Section 6 measured pinning before tiling, when it won at 16 threads as well. Measured again on the final code, it wins only when every core is used. `JULIA_EXCLUSIVE=1` puts thread `i` on CPU `i`, so a 16-thread run sits on CPUs 0–15: two of the four 8-core CCDs, with two of the four L3 slices and memory links. That made it 20% slower than unpinned at 16 threads (140 against 115 ms) and 9% slower at 8. Pin a run that has the whole node. Leave a smaller one unpinned, or bind it to cores spread over the CCDs.

**Where a 32-thread step goes now** (pinned, 128³, 82 ms): three right-hand sides of 24.4 ms each. Each is three sweeps of 6.4–7.0 ms, plus the floors, the conversion and the ghost fill (2.5 ms together) and task start-up. The rest of the step is the stage copy (1.6 ms), the CFL scan, which converts the whole grid to primitives first (2.3 ms), and the end-of-step floors (0.3 ms).

What is left, largest first:

- **The kernels on one core.** The sweeps are within 10–15% of their clock-limited share, so further gains in them have to come from making each core faster, not from more parallelism. The HLLC row and the PPM row are scalar loops over faces. Vectorising them across `i` (SIMD, 8 doubles with AVX-512 on this CPU) is the largest remaining lever, and it is a separate piece of work.
- **The remaining whole-grid passes**, about 10 ms a step: the floor pass, the ghost fill, the conversion, the stage copy and the CFL scan. Fusing the floors into the conversion, threading the ghost fill and reusing the conversion in the CFL scan would save perhaps 5 ms (6%). Each was set aside as too small to measure at the time (sections 2 and 4). Together they are no longer below the noise.
- **The radiation sweep** is untouched. It has the same structure, reconstruct then HLL then divergence, so the same tiling would apply, but the implicit coupling dominates a radiation step.
- **NUMA.** This node has one NUMA domain, so first-touch placement of the arrays, which matters on a two-socket node, could not be measured.

### 10. Kernels for one cell, and the same kernels on a GPU

Everything above made the CPU fast by writing CPU threading into each kernel. Quokka, which these algorithms are written for, runs on GPUs and under MPI through AMReX, where a kernel is a function of one cell handed to `ParallelFor`, and tiling is a cache policy of the CPU only. This section reshapes the hydrodynamic sweep that way, checks that the CPU loses nothing, and runs the sweep on the GPU of this node (an NVIDIA RTX PRO 6000 Blackwell, whose double-precision rate is a small fraction of its single-precision one).

**What changed.**

- The row functions of section 7 became functions of one cell or face, `_reconstruct_cell!`, `_hydro_flux_cell!` and `_divergence_cell!`.
- They run through one launch point, `launch!(backend, box, f, args...)` (`src/launch.jl`). Its arguments are passed explicitly, not captured, so a device backend can convert them, and the boxing of section 7's bug cannot happen inside a kernel.
- `CPUThreads` spreads the rows of a box over the threads with an inner loop over `i`, which is the loop structure the row functions had, and it compiles to the same speed. `CPUSerial` runs a box on the calling task, for a tile. `KABackend` launches a KernelAbstractions kernel with one work-item per cell, from a weak-dependency extension.
- The flags `overwrite` and `update` became types before the launch (`Val(overwrite)`, a tuple or `nothing`), so no cell tests them. Done first with `Val` built per tile, it allocated 8.6 MB a step at 32 threads, a dynamic dispatch per tile. The conversion now happens once per sweep, behind a function barrier.
- One driver, `hydro_sweep!`, replaced the tiled driver and the untiled branch. Each box gets the same three launches (`_sweep_box!`). Tiled, each task launches its tiles serially into its own `TileArray`. Untiled, the whole interior is one box, launched on the workspace's backend. That second form is how a GPU runs it: as in AMReX, a GPU never tiles.
- Nothing measured in sections 1–9 was dropped. The Runge–Kutta stage formed in the last sweep, the overwriting first sweep and the static chunks are all pointwise or per-box and carry over unchanged. Only the duplicated driver and the row functions went.

**The CPU, against `a20743c`** (the end of section 9). Sedov 128³, the two branches interleaved, three runs each; the node was less loaded than in section 9, so both are faster than the numbers there:

| | `a20743c` | cell kernels | change |
|:---|---:|---:|---:|
| 1 thread (median) | 1194 ms | 1196 ms | +0.2% |
| 32 threads, pinned (median) | 68.9 ms | 67.1 ms | −2.7% |

The answers are bit-identical on the seven reference problems at 1, 8 and 32 threads.

**The device path without a device.** `test/test_portable.jl` runs three steps of six problems with the sweeps launched through `KABackend(KernelAbstractions.CPU())`: Sedov tiled and untiled, Kelvin–Helmholtz in 2D, Sod in 1D, two mass scalars, and PLM. KernelAbstractions 0.10 compiles that backend through POCL, an OpenCL compiler, rather than as ordinary Julia. All six end bit-identical (`==`) to `CPUThreads`.

**On the GPU.** `test/gpu/gpu_sweep.jl` runs each sweep, along x, y and z, in each of its three modes, once with `CPUThreads` and once with `KABackend(CUDABackend())` on `CuArray` copies of the same Float64 arrays:

- **Accuracy:** the largest difference of any variable, over that variable's largest value, is 3–6e-16. The GPU compiles the same arithmetic with fused multiply-adds and its own math library, so the results are not bit-identical; they agree to round-off.
- **Measured cell by cell:** the relative difference reached 1.4e-7, at a cell where two nearly equal fluxes cancel to a `dU` of 8e-13, off by 1e-19.
- **Speed at 128³:** one sweep takes 2.0–2.3 ms on the GPU, against 4.5–5.2 ms tiled on all 32 cores and about 10 ms untiled. This is a card built for single precision, so a data-centre GPU would do better.

Only the sweep runs there. Ghost filling, floors, conversion, the CFL scan and radiation are still `threaded_jk` loops over `Array`s, and are the next kernels to convert the same way.

**What MPI would need.** Nothing in the sweep assumes the grid is the whole domain: it reads `prim` over the ghost cells of whatever `CartesianGrid` it is given, as an AMReX box does. What a distributed run adds lies outside it:

- **Halo exchange.** `fill_ghosts!` is already the single entry point that fills ghost cells, dispatching on the boundary type. A halo exchange would be one more boundary type on the faces shared with another rank.
- **Global reductions.** Three reductions span the whole grid, and each would need an `Allreduce`:
  - the CFL maximum (`reduce_max_jk`, under `hydro_timestep`);
  - the floor-repair counters of `enforce_floors!` (an atomic sum);
  - the counters of `enforce_scalar_floors!` (also an atomic sum).

None of this is implemented, and MPI is not installed on this node.

**Storage order.** The arrays are still `(nvar, i, j, k)`, one cell's variables together. A GPU warp reading one variable of 32 neighbouring cells would read 32 contiguous numbers with AMReX's `(i, j, k, n)`, and five times that span here. The kernels now index `[n, i, j, k]` on any `AbstractArray`, so trying the other order is a matter of allocating it (a `PermutedDimsArray` over `(i, j, k, n)` storage) and measuring, not of rewriting the kernels.

### 11. Apple Silicon: tiling does not pay

Measured on an Apple M5 Max laptop: 18 cores in two clusters of 6 and 12, unified memory, Julia 1.12.6, macOS. The test suite passes there as it does on the node. Sedov, `test/benchmarks_parallel.jl`, ms per step, one run each:

| threads | 1 | 4 | 6 | 8 | 12 | 18 |
|:---|---:|---:|---:|---:|---:|---:|
| 128³ untiled | 525 | 151 | 124 | 102 | 77 | 72 |
| 128³ tiled (32, 1, 1) | 565 | 187 | 142 | 118 | 94 | 89 |

At 256³ on 18 threads the untiled step takes 586 ms and the tiled one 632 ms. Tiling is slower at every thread count, by 8–23% at 128³, and the gap does not close as threads are added, as it did on the node. Why was not measured: one guess is that 18 cores do not saturate this chip's memory bandwidth, so there is no contention for tiling to relieve, but no bandwidth figure was taken. With `TILE_MIN_THREADS = 8`, a default run at 8 threads or more was 15–22% slower than it needed to be, so `:auto` now never tiles on Apple Silicon (`Sys.isapple() && Sys.ARCH === :aarch64`). A tuple still forces a tile there. The answers are unchanged, since tiling is bit-identical.


---

<!-- page: documentation.md -->

# How this documentation is built

This page explains how the documentation site of Honghu.jl is made, where each page comes from, and what to edit to change it. It is written for anyone who changes the code or the documentation, coding agents included.

## What the site contains

| Part | Source | How it gets onto the site |
|:---|:---|:---|
| Home page | `README.md` | copied to `docs/index.qmd` by `docs/make.jl`, with a few links rewritten |
| Reference | the docstrings in `src/` | written to `docs/reference/*.qmd` by `docs/make.jl` |
| Physics guides | `docs/*.md` listed in the Physics menu: one per physics module, such as `photochemistry.md` | rendered as they are |
| Notes | `docs/*.md` listed in the Notes menu: the technical notes and this page | rendered as they are |
| Figures | `docs/figures/` | made by `docs/make_figures.jl` and `docs/make_animations.jl`, except the logo images `honghu-*.png`, which no script makes |

Every page is published twice, from the same source and in the same build: as HTML, and as Markdown. The Markdown copy of `x.html` is `x.md` in the same folder, and the line "Markdown: this page" at the top of each HTML page links to it. The copy is the page's source itself. The only change is that links to other pages point at their `.md` copies instead of their `.qmd` sources. Two more files sit at the site root: `honghu-docs.md`, which holds all pages in one file in navigation order, and `llms.txt`, an index of the Markdown pages in the llms.txt format. Both exist so that a person or a coding agent can read the whole documentation as plain text. Each page links to its own copy and to the bundle; `llms.txt` is not linked from the pages, because it is the same site-wide index everywhere and agents look for it at `/llms.txt` by convention.

`docs/index.qmd` and everything in `docs/reference/` are build products. They are not in git, and the next build overwrites them, so edit the README and the docstrings instead.

## How a build runs

`julia --project=. docs/make.jl` does five things, in this order.

1. **Collect the docstrings.** It loads Honghu and reads every docstring in `Honghu`, `Honghu.Problems` and `Honghu.CGS` through `Docs.meta`. Each documented name becomes one entry, on the reference page its source file belongs to; the `PAGES` table at the top of `docs/make.jl` assigns files to pages. On each page, exported names come first, under "Exported", and documented names that are not exported come after, under "Internals". The constants in `CGS` count as public, because that module exports nothing by design. A name without a docstring does not appear at all.
2. **Write the pages.** Each docstring is copied as written, with five small changes (see [A docstring](#a-docstring) below). The script also writes `docs/reference/index.qmd`, which holds the `Honghu` module docstring and a list of all pages with their exported names, and `docs/index.qmd` from the README.
3. **Render.** `quarto render docs` turns the pages into HTML in `docs/_site/`. The Quarto project is `docs/_quarto.yml`. Its `render:` list says which files are pages, so the scripts and the internal notes elsewhere in `docs/` stay off the site. The Lua filter `docs/source-links.lua` adds the Markdown links to the top of every page, and makes the leading `# Title` of a note its page title.
4. **Write the Markdown copies,** the bundle `honghu-docs.md` and `llms.txt` into `docs/_site/`.
5. **Check,** and fail on any problem listed in [What fails the build](#what-fails-the-build).

After Honghu is precompiled, a full build takes about 15 seconds. It runs no simulation, and no code block in a docstring or a page is ever executed.

## Building and previewing locally

You need Julia, with the project's own environment (there is no separate docs environment), and Quarto 1.9 or newer on the `PATH`. CI uses Quarto 1.9.38.

```bash
julia --project=. docs/make.jl                  # full build into docs/_site
julia --project=. docs/make.jl --generate-only  # write the pages only, no render
quarto preview docs                             # live preview, after --generate-only
python3 -m http.server -d docs/_site            # serve a full build at http://localhost:8000
```

`quarto preview` updates the HTML when a README-derived page or a note is saved, but not when a docstring changes. The reference pages are written from the docstrings, so re-run `docs/make.jl --generate-only` after editing one. The Markdown copies, the bundle and the link check exist only in a full build. Run one before you commit.

## How to update

### A docstring

Edit it in `src/`. The next build picks it up and nothing else needs to change. Write docstrings as you would for Documenter:

- Start with the signature, indented by four spaces. It becomes a highlighted Julia code block.
- Link to another documented name with `` [`name`](@ref) ``. The forms `` [`Honghu.name`](@ref) `` and `` [`name(args)`](@ref) `` link to the same entry. The target must have a docstring: a link to an undocumented name fails the build. Fix that by writing the missing docstring, not by removing the brackets. The form `[text](@ref name)` is not supported and also fails.
- Headers such as `# Example` are moved down three levels, so that they sit below the entry's own heading.
- An admonition, `!!! warning "Title"` followed by a body indented by four spaces, becomes a Quarto callout. `note`, `tip`, `warning` and `danger` are recognised.
- A `jldoctest` block is shown as a plain `julia` block.
- Write formulas as plain text in code, as the existing docstrings do, for example `phi c dt [ ... ] <= 1`. No math is rendered inside docstrings. Documenter's double-backtick math is not converted and shows as code, and a `$` in a docstring is string interpolation in Julia.

### A new source file

If a new file in `src/` holds docstrings, add it to the `PAGES` table in `docs/make.jl`, under the page it belongs to. Until you do, the build fails with "no reference page for these files". An entry that ends in `/`, like `"problems/"`, takes every file in that directory.

### A new reference page

Add an entry `"name" => ("Title", ["file.jl", ...])` to `PAGES`, and add `reference/name.qmd` to the Reference menu in `docs/_quarto.yml`. The `render:` list already takes every file in `reference/`.

### The front page

Edit `README.md`. The build copies it to `docs/index.qmd`. It drops the first line, `# Honghu.jl`, which becomes the page title, and it rewrites the links that are written for GitHub's view of the repository: `docs/figures/...` becomes `figures/...`, in Markdown links and in HTML `src` attributes, and the link to `future.md` becomes a GitHub URL (`write_index` in `docs/make.jl`). Any other relative link in the README must point at something on the site, or the link check fails. To link to another file in the repository, use its full GitHub URL.

### A note

The notes are plain Markdown files in `docs/` that also read well on GitHub. To add one:

1. Write `docs/name.md`. Begin it with `# Title`, which becomes the page title, and give it no YAML front matter. Use `$...$` and `$$...$$` for math. MathJax renders it on the site, and the Markdown copy keeps it exactly as written.
2. Add `name.md` to `NOTES` in `docs/make.jl`. This gives it a Markdown copy and a place in the bundle and in `llms.txt`.
3. Add `name.md` to the `render:` list and to the Notes menu in `docs/_quarto.yml`.

The build checks that every name in `NOTES` and every reference page also appears in `docs/_quarto.yml`. If you miss step 3, the build fails instead of leaving the page off the site.

To link from one note to another, use a relative link to its `.md` file, such as `[the findings](rsla-findings.md)`. Quarto turns it into a link to the HTML page, and the Markdown copy keeps it, where it points at the other copy. Images go in `docs/figures/` and are linked as `figures/name.png`. A link to a file that is not on the site, such as a script in `examples/`, must be a full GitHub URL.

### A physics guide

A physics guide is a note that explains one physics module from the ground up. It starts with the governing equations, then gives the numerical method at the level of techniques (operator splitting, the method of lines, the time integrators and why they were chosen), and ends with the module's limitations. Which file or type does what, and the details of an implementation, belong to the reference page, not to the guide. `docs/photochemistry.md` is the first. It is added like any other note, except that step 3 puts it in the Physics menu instead of the Notes menu, and `NOTES` lists the guides before the notes. A guide does not repeat what the docstrings say. It links into the module's reference page instead, with a link to the generated page and the anchor of the entry, such as `[HydrogenIliev2](#HydrogenIliev2)` (see the end of [What fails the build](#what-fails-the-build) for how anchors are formed). Those pages exist only after a build, so the links resolve on the site and in its Markdown copies, but not in GitHub's view of the repository. The link check of the build catches a wrong page or anchor.

### A test problem

Each test problem is documented in the Test problems section of its physics guide, as one subsection in this form:

````markdown
### N.M Name of the problem

One or two sentences: what the problem tests, and what it is compared against.

| Setup | |
|:---|:---|
| Physics | the modules that are on (hydrodynamics, radiation transport, photochemistry, passive scalars, ...) and their options |
| Domain | the box and the resolution |
| Initial condition | ... |
| Boundary conditions | ... |
| Source | if there is one |
| Evolution | the start and end times, the Courant numbers, the reduced speed of light, the integrators |
| Reference | the analytic, published or converged solution, or "none" |
| Run | the problem function and its arguments |

![What the figure shows.](figures/name.png)

| an error table at a few times or resolutions |

A few sentences on what the results show.
````

A problem that differs little from the one before it may write "as ..., but ..." in a row. Every figure and every number in the table is made by a function in `docs/make_figures.jl`, which runs only the figures named on its command line (`docs/make_figures.jl stromgren`) and prints the numbers it plots, so that both can be made again.

### The navigation and the look

`docs/_quarto.yml` holds the navbar, the menus and the theme, and names the navbar icon and the favicon. It is written by hand and no script regenerates it.

## What fails the build

The build stops with an error, and writes nothing to deploy, in each of these cases.

| Message | Cause | Fix |
|:---|:---|:---|
| `no reference page for these files; add them to PAGES` | a file in `src/` has docstrings but no page | add it to `PAGES` in `docs/make.jl` |
| `@ref links with no docstring behind them` | a `` [`name`](@ref) `` whose `name` has no docstring, or an unsupported `@ref` form | write the docstring, or correct the name |
| `not in docs/_quarto.yml` | a note or reference page that `docs/_quarto.yml` does not list | add it to the `render:` list and the menu |
| `duplicate anchors` | two entries would get the same anchor | rename one of them, or refine `slug` in `docs/make.jl` |
| `quarto warned` | any warning from `quarto render` | read the warning; usually a link to a `.qmd` or `.md` that does not exist |
| `quarto render failed` | Quarto itself stopped | read Quarto's output above the error |
| `broken links` | a relative `href`, `src` or `#anchor` in the HTML, or a relative link in a Markdown copy, that does not resolve | fix the link in its source; the message names the page |

The anchor of an entry is its name, with `!` written as `-bang` and every other character that is not a letter, a digit, `_` or `-` replaced by `-`. So `run!` is `#run-bang` and `CGS.a_rad` is `#CGS-a_rad`.

## Deployment

`.github/workflows/docs.yml` builds the site on every push and every pull request, and deploys it to GitHub Pages from `main`, at <https://chongchonghe.github.io/Honghu.jl/>. A pull request that breaks the build fails its check before it is merged. Deployment needs one setting in the repository: Settings, Pages, Build and deployment, Source "GitHub Actions". The workflow pins Quarto to 1.9.38, the version the site was built and checked with. Raise it on purpose, after a local build with the new version, because Quarto's link handling has changed between releases.

## Why it is built this way

- **Quarto and a script in the repository, not Documenter or QuartoDocBuilder.jl.** The site needs HTML and Markdown from one source, and Documenter's Markdown backend is no longer maintained. QuartoDocBuilder.jl was examined and rejected. It is not registered, it leaves Documenter's `@ref` links broken (the docstrings have 258 of them), it cannot put several names on one page, and it rewrites `_quarto.yml` on every build. `docs/make.jl` is about 420 lines and does only what this package needs.
- **The Markdown copy is the source, published as `.md`.** GitHub Pages serves `.qmd` files as downloads and `.md` files as text. Publishing the source itself, rather than rendering a second output format, means the copy cannot drift from the HTML, and the math stays exactly as written.
- **No Quarto `llms-txt`.** In Quarto 1.9 the Markdown it produces garbles math, and the fix is only in the 1.11 pre-releases. `docs/make.jl` writes `llms.txt` itself. A Quarto release with the fix could take over that file, but the bundle and the per-page links would still be needed.
- **A link check of its own.** Quarto warns about some missing links and has no strict mode, so `docs/make.jl` checks every link and anchor in the rendered site.
- **`data-noresolveinput` on the Markdown links.** Quarto resolves every link in a page against the project's inputs, raw HTML included. It would warn about the `.md` copies, which do not exist yet while it renders. The undocumented attribute `data-noresolveinput` turns that off for the two links the filter adds.

