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

Source: src/simulation.jl:15

Diagnostics

Running counters describing how hard the solver had to work, accumulated from construction and reported by run!. Read them off sim.diag, or reset them with reset_diagnostics!.

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!)
chem_steps chemistry solver steps summed over those cells (Newton iterations for 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!

Source: src/simulation.jl:65

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

Source: src/simulation.jl:113

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

Source: src/simulation.jl:192

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 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.
  • 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) and set from the key X of set_initial_conditions!. 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 of face-centred components, set by the keys bx, by, bz or the vector_potential of set_initial_conditions!, and its energy is part of the total energy in sim.U. Only Periodic and Outflow boundaries are supported with it; any other is an ArgumentError.
  • chemistry = nothing : a 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 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!).

Numerics

  • reconstruction = PPM() : PCM, PLM or 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 or LLF; with mhd = true an MHD solver, HLLD (the default), HLLMHD or 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 with 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! 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

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!

Source: src/simulation.jl:515

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 of the network
bx, by, bz magnetic field (mhd = true only) 0

With mhd = true the field is face-centred (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), 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 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; leaving it out is an error (initial_mass_fractions). A T key then goes through the network’s equation of state, 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 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.

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

Source: src/simulation.jl:961

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!

Source: src/simulation.jl:989

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

Source: src/simulation.jl:1070

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!

Source: src/simulation.jl:1112

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

Source: src/simulation.jl:1222

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

Source: src/simulation.jl:1263

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

Source: src/simulation.jl:1281

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 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

Source: src/simulation.jl:1316

radiation_temperature(sim)

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

CartesianGrid

Source: src/grid.jl:8

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

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

Periodic

Source: src/boundary.jl:26

Periodic()

Wrap around to the opposite side of the domain.

Outflow

Source: src/boundary.jl:33

Outflow()

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

Reflecting

Source: src/boundary.jl:40

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

Source: src/boundary.jl:48

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 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

Source: src/boundary.jl:76

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 documents.

The time-dependent counterpart of 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:

# 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

Source: src/boundary.jl:100

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

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

Boundaries(Periodic())
Boundaries((Outflow(), Outflow()), (Periodic(), Periodic()), (Periodic(), Periodic()))

ForwardEuler

Source: src/integrators.jl:21

ForwardEuler()

First-order explicit Euler. Only first-order accurate in time, so it is useful mainly with PCM or for debugging.

SSPRK2

Source: src/integrators.jl:29

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

Source: src/integrators.jl:40

SSPRK3()

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

Internals

HydroWorkspace

Source: src/simulation.jl:127

HydroWorkspace{T}

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

backend is the AbstractBackend the sweeps launch their cell kernels on, 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. Any backend but CPUThreads runs the sweep as one whole-grid box, never tiled.

RadiationWorkspace

Source: src/simulation.jl:161

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!). It is filled with the constant phys.chat when the simulation is built, so a run with the default ConstantChat limiter reads exactly the number it always did and never writes to it again.

has_radiation

Source: src/simulation.jl:438

has_radiation(sim)

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

has_mhd

Source: src/simulation.jl:445

has_mhd(sim)

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

nhydrovars

Source: src/simulation.jl:453

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!

Source: src/simulation.jl:685

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!), 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!).

rad_rhs!

Source: src/simulation.jl:739

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!

Source: src/simulation.jl:769

advance_hydro!(sim, dt)

One explicit SSP-RK step of the Euler equations.

imex_substep!

Source: src/simulation.jl:835

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 limiter the update_chat! 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!

Source: src/simulation.jl:896

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!

Source: src/simulation.jl:1025

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

Apply the user’s operator-split source terms over dt, which is half the step: step! 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.

# 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!

Source: src/simulation.jl:1080

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

Source: src/grid.jl:69

ndim(grid)

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

cellcenter

Source: src/grid.jl:76

cellcenter(grid, i, j, k)

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

cellvolume

Source: src/grid.jl:86

cellvolume(grid)

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

interior

Source: src/grid.jl:93

interior(grid)

CartesianIndices spanning the interior (non-ghost) cells.

interior_box

Source: src/grid.jl:102

interior_box(grid)

The interior cells as a box (irange, jrange, krange), the form launch! takes.

boxsize

Source: src/grid.jl:110

boxsize(grid)

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

allocate

Source: src/grid.jl:117

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

Source: src/grid.jl:134

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

cell_ranges

Source: src/grid.jl:139

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

Source: src/grid.jl:152

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

Source: src/grid.jl:165

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

Source: src/grid.jl:191

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

Source: src/grid.jl:210

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!

Source: src/grid.jl:259

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!

Source: src/grid.jl:275

threaded_fill!(A, x)

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

AbstractBackend

Source: src/launch.jl:15

AbstractBackend

Where launch! runs a cell kernel. CPUThreads and CPUSerial are built in; KABackend runs on any device KernelAbstractions supports, a GPU included, once that package is loaded.

CPUThreads

Source: src/launch.jl:24

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

Source: src/launch.jl:34

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

Source: src/launch.jl:43

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 CuArrays, 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!

Source: src/launch.jl:56

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

Source: src/launch.jl:108

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! hands a cell kernel on the CPU in place of an Array{T,4} or a 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

Source: src/variables.jl:20

Number of hydrodynamic variables.

NRAD

Source: src/variables.jl:22

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

Source: src/variables.jl:42

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

Source: src/variables.jl:52

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

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

prim2cons

Source: src/variables.jl:68

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

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

kinetic_energy

Source: src/variables.jl:81

kinetic_energy(u::SVec{5})

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

internal_energy

Source: src/variables.jl:90

internal_energy(u::SVec{5})

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

Source: src/eos.jl:71

internal_energy(eos, rho, p)

Internal energy density from mass density and pressure.

rad_cons2prim

Source: src/variables.jl:97

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

Source: src/variables.jl:109

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

Inverse of rad_cons2prim.

BoundaryCondition

Source: src/boundary.jl:8

BoundaryCondition

Supertype for boundary conditions. Built-in conditions are Periodic, Outflow, Reflecting, Fixed and FunctionBC.

To add your own, define

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!

Source: src/boundary.jl:136

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 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

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! fills them as it fills cells. Along it there is one more face than cells:

  • 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: 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 refuses the others when the simulation is built. The ghost cells of the gas state then need mhd_ghost_energy!.

fill_face!

Source: src/boundary.jl:169

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

Source: src/integrators.jl:13

AbstractIntegrator

Supertype of the explicit time integrators: ForwardEuler, SSPRK2, SSPRK3.

tableau

Source: src/integrators.jl:49

tableau(integrator)

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

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

nstages

Source: src/integrators.jl:60

nstages(integrator)

Number of right-hand-side evaluations per step.

combine!

Source: src/integrators.jl:67

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

Source: src/integrators.jl:92

Explicit tableau entries of the IMEX PD-ARS scheme.

IMEX_AIM_22

Source: src/integrators.jl:96

Implicit tableau entries of the IMEX PD-ARS scheme.

IMEX_ALPHA

Source: src/integrators.jl:100

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

combine_gas!

Source: src/integrators.jl:103

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, 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.