Photoionization chemistry

Docstrings from src/chemistry.jl, src/chemistry_solvers.jl, src/chemistry_step.jl, src/networks/.

Exported

AbstractNetwork

Source: src/chemistry.jl:38

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, and these methods of its type:

Everything else is common to all networks and defined here: chem_rhs!, chem_jacobian! and chem_scales!, which the integrators call, and 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, ienergy, iband and iflux give the layout.

The integrators in chemistry_solvers.jl are RosenbrockChem and BackwardEulerChem; both read the right-hand side and the Jacobian from the network and nothing else, so they integrate the same problem.

NetworkOptions

Source: src/chemistry.jl:69

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

Source: src/chemistry.jl:108

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

Source: src/chemistry.jl:117

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

Source: src/chemistry.jl:125

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

Source: src/chemistry.jl:133

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

Source: src/chemistry.jl:142

network_reactions(net)

The reactions of the network as JAFF writes them, for reading. A method of the network’s type.

band_edges

Source: src/chemistry.jl:150

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

Source: src/chemistry.jl:456

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, an adaptive stiff integrator from OrdinaryDiffEq and the default, and BackwardEulerChem, one backward-Euler step with a Newton iteration, which is the comparison.

RosenbrockChem

Source: src/chemistry_solvers.jl:53

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.
  • abstol : the absolute tolerance, as a fraction of chem_scales!: 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: 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.

solver = RosenbrockChem(alg = Rodas5P(), reltol = 1e-4)

BackwardEulerChem

Source: src/chemistry_solvers.jl:154

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

Source: src/chemistry_step.jl:28

Photochemistry(network; solver = RosenbrockChem(), emission = nothing)

Photochemistry for a Simulation: the AbstractNetwork to evolve, the 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.
  • solver : the integrator, RosenbrockChem by default or 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, 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!): 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.

net = HydrogenIliev2(photon_energy = 29.65 * Honghu.CGS.eV)
chem = Photochemistry(net; emission = (x, y, z, t) -> 1e-17)

HydrogenIliev1

Source: src/networks/hydrogen_iliev1.jl:123

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

Source: src/networks/hydrogen_iliev2.jl:164

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

Source: src/chemistry.jl:159

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!, which supplies the temperature.

jaff_jacobian!

Source: src/chemistry.jl:170

jaff_jacobian!(J, net, nden, photden, rflux, tgas, c_hat)

The Jacobian of jaff_rhs! 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!, which zeroes the matrix first.

species_mass

Source: src/chemistry.jl:184

species_mass(net, s)

The mass of one particle of species s, in g; see species_masses.

band_group

Source: src/chemistry.jl:191

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

Source: src/chemistry.jl:201

band_photon_energy(net, b)

The mean energy eps_b of a photon of band b, in erg, from the network’s NetworkOptions. It converts the group’s radiation energy density to the photon number density, E_rad = eps_b phi N_b.

nunknowns

Source: src/chemistry.jl:210

nunknowns(net)

The length of the unknown vector u of the network, nspecies + 1 + 2 nbands.

ienergy

Source: src/chemistry.jl:217

ienergy(net)

The index of the internal energy density in the unknown vector, nspecies(net) + 1.

iband

Source: src/chemistry.jl:224

iband(net, b)

The index of the photon density of band b in the unknown vector, nspecies(net) + 2b.

iflux

Source: src/chemistry.jl:232

iflux(net, b)

The index of the flux factor of band b in the unknown vector, nspecies(net) + 2b + 1.

chem_rhs!

Source: src/chemistry.jl:268

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 of constants the step needs. It computes the temperature, with the network’s isothermal and Tmin (NetworkOptions), and calls the generated jaff_rhs!. This and chem_jacobian! are the single source of truth for the network’s physics: every integrator’s residual and linearisation come from them.

chem_jacobian!

Source: src/chemistry.jl:287

chem_jacobian!(J, u, net, cell)

Write the exact Jacobian df_i/du_j of chem_rhs! 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! 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!

Source: src/chemistry.jl:352

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.

network_temperature

Source: src/chemistry.jl:379

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

Source: src/chemistry.jl:400

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. set_initial_conditions! uses it to turn a T key into an energy when a network is present.

chem_internal_energy

Source: src/chemistry.jl:416

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

Source: src/chemistry.jl:428

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

ChemCell

Source: src/chemistry.jl:440

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

Source: src/chemistry.jl:471

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

Source: src/chemistry.jl:485

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!

Source: src/chemistry.jl:495

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 for the same solver, net and T. Returns the ChemStats of the solve; when it did not converge, u holds the solver’s last state, which the caller should not trust.

ChemStepStats

Source: src/chemistry_step.jl:90

ChemStepStats(cells, steps, max_steps, failures)

What one chemistry_step! did: the number of cells solved, the steps of the solver summed over them (see 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.

chemistry_step!

Source: src/chemistry_step.jl:223

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 in each cell, and writes the species, the gas internal energy and the band’s energy and flux back; see 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.

The cells whose solve did not converge are counted in the returned ChemStepStats and keep the solver’s last state. It throws an ArgumentError for a simulation built without chemistry.