---
title: "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`](radiation.md#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`](radiation.md#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`](hydro.md#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`](rsla.md#AbstractChatLimiter) sets
    it from the group's own cell optical depth; with the default
    [`ConstantChat`](rsla.md#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`](rsla.md#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`](radiation.md#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`](radiation.md#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`](simulation.md#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`](mhd.md#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.

