"""``solve_eb``, the interface to the Einstein-Boltzmann solve.
It runs one modax launch over every (wave mode, cosmology) pair and
records only the named quantities at the scale factors given. The
values are differentiable in every parameter of the cosmologies, in forward
and reverse mode.
"""
from collections.abc import Sequence
from typing import Annotated
import jax
import jax.numpy as jnp
import numpy as np
from ..components.recombination import THERMO_ERROR_WEIGHT
from ..models._model import Model, _batch_of, _is_concrete, _model_of
from ._kernel import (
A_START,
PERTURB_ATOL,
PERTURB_FIRST_STEP,
PERTURB_MAX_STEPS,
PERTURB_RTOL,
_columns,
_hook_reads,
_keep_hook,
_launch,
_pack,
_prepare_solve,
density_parameters,
modax,
parameter_layout,
)
def _overrides(cosmologies, columns, model, extra=()) -> dict[str, jax.Array]:
"""Return the derived columns the cosmologies' :meth:`~discoeb.models.Model.replace` set, ``(n_cosmologies,)`` each.
A cosmology that set no value for a column another one set takes the
value its parameters imply.
"""
batch = (cosmologies,) if isinstance(cosmologies, Model) else tuple(cosmologies)
names = sorted(set().union(*(c._overrides for c in batch)))
if not names:
return {}
n = len(batch)
computed = density_parameters(columns, model=model, extra=extra)
out = {}
for name in names:
default = jnp.broadcast_to(jnp.asarray(computed[name], jnp.float64), (n,))
out[name] = jnp.stack(
[
jnp.asarray(c._overrides[name], jnp.float64)
if name in c._overrides
else default[i]
for i, c in enumerate(batch)
]
)
return out
def _flat_names(keep) -> tuple[str, ...]:
"""Return the names of ``keep``, a name or a sequence of names and sequences of names, flattened in order."""
if isinstance(keep, str):
return (keep,)
return tuple(name for item in keep for name in _flat_names(item))
[docs]
def solve_eb(
cosmologies: Model | Sequence[Model],
k_values,
a,
*,
extra=(),
keep: Sequence[str | Sequence[str]] | None = None,
rtol: float = PERTURB_RTOL,
atol: float = PERTURB_ATOL,
first_step: float = PERTURB_FIRST_STEP,
max_steps: int = PERTURB_MAX_STEPS,
error_weights=None,
thermo_weight: float = THERMO_ERROR_WEIGHT,
split_derivatives: bool = False,
) -> Annotated[jax.Array, ("cosmology", "name", "k", "a")]:
"""Solve the Einstein-Boltzmann system of ``cosmologies`` and keep ``keep`` at the scale factors ``a``.
One modax solve integrates the background of every cosmology and,
against it, the perturbations of every (wave mode, cosmology) pair
(:func:`~discoeb.solver._kernel._launch`).
At each save the kernel evaluates the quantities named in ``keep`` from
the dense-output state and stores them, so the device holds ``n_k *
n_cosmologies * len(a) * len(keep)`` values and never the history.
Parameters
----------
cosmologies
A cosmology, ``LCDM(omega_b=..., ...)``, or a sequence of cosmologies of
one model. The model sets the species and interactions the solve
evolves, and each model compiles one kernel. A parameter may be a
JAX array, traced under ``jit`` or not, and differentiated.
k_values
Wave numbers in 1/Mpc, in any order. They must be concrete numbers,
since they set the launch's shape.
a
Strictly increasing scale factors at which to record, from
:data:`A_START` on. The solve integrates in ``a``, and 1 is today
for every cosmology. Traced values must start after ``A_START``.
Every launch starts there, so a first value equal to it records the
initial state. Keep ``tau`` for the conformal time at each ``a``.
Its value at 1 is the conformal age.
extra
Components to append to the model for the hook: stateless
:class:`~discoeb.components.Component` subclasses whose providers
read the model's quantities and add their own (DISCO-CMB's
line-of-sight sources). The hook cache tells them apart by class.
keep
Names of the quantities to record, or sequences of names, which are
flattened in order: ``[LineOfSightSources.keep, "delta_c"]`` keeps a
component's list and one more name. A name is a state element
(:meth:`~discoeb.models.Model.state_names`, or the recombination
block's ``tau``, ``thermo_0``, ``thermo_1``, ``thermo_2``, ``kappa``,
``kappa_reio``) or a quantity the model provides, such as the
comoving curvature perturbation ``R``, the shear ``alpha``, the
expansion rate ``aH`` or the ``opacity``. Default: every element of
the perturbation state. A quantity of the background alone, one the
perturbations read of it (``tau``, ``opacity``, ``cs2``, the
recombination block's states), comes from the background's own
saves, once per cosmology, unless nothing else is kept.
rtol, atol, first_step, max_steps
Settings of the Rodas5P step controller.
error_weights
Either ``{state name: weight}`` or modax's array ``(n_k *
n_cosmologies, nvar)`` in launch order (wave modes ascending,
cosmologies within). In the dictionary each weight is a number or a
function of the trajectories' wave numbers that returns one per
trajectory, and unnamed states keep their declared weight (one,
and zero for the massive-neutrino bins ``psi``).
thermo_weight
Weight of the background states in the error norm of their solve.
split_derivatives
How a derivative uses the device's threads. By default a trajectory
and its sensitivity columns share one thread, which costs the least
work and suits a batch that fills the device. With ``True`` each
direction gets a copy of every trajectory in a thread of its own,
holding the state and one column. The copies repeat the primal but
run side by side, so one cosmology finishes sooner, and a thread's
memory does not grow with the number of parameters.
Returns
-------
jax.Array
The kept quantities, ``(n_cosmologies, len(keep), n_k, n_a)``:
cosmologies in the order given, quantities in ``keep`` order, wave
modes and scale factors in the caller's order.
``jnp.unstack(values, axis=1)`` splits it into one
``(n_cosmologies, n_k, n_a)`` array per name.
Notes
-----
The hook compiles once per model and set of names. Before the launch
``solve_eb`` computes only the parameter rows and the initial states, in
JAX, so it traces under ``jit``. Under ``jit`` the model cannot check the
cosmologies, since their values are not known.
The returned values are differentiable in every parameter of the
cosmologies and every input, in forward and reverse mode. Under
``jax.jvp`` and ``jax.jacfwd``, with or without ``jit``, modax
integrates one sensitivity column per tangent direction in both blocks,
the background's derivatives reach the perturbations through the nodes
it publishes, and each kept quantity's derivative is stored beside it.
Over a batch in forward mode take ``jax.vmap(jax.jacfwd(f))`` of a
function of one cosmology, since ``jacfwd`` of the batch would ask every
cosmology for every other's directions. Reverse mode (``jax.grad``,
``jax.vjp``, ``jax.jacrev``) integrates one forward column per moving
parameter, seeded in every cosmology at once, since a cosmology's values
depend on its own parameters alone, and JAX transposes the result
(``modax.by_forward_mode`` with ``independent_rows``). A gradient over a
batch then costs what ``jax.jacfwd`` of one cosmology costs, and needs
no wrapper. ``jit`` must sit outside the reverse-mode transform. The derivative holds the scale factor fixed, so it is the
derivative at fixed redshift. A parameter the solve never reads
(``A_s``, ``n_s``, ``k_p``) has a zero derivative.
"""
model, dicts = _batch_of(cosmologies)
n_cosmo = len(dicts)
names = tuple(model.state_names()) if keep is None else _flat_names(keep)
if len(set(names)) != len(names):
raise ValueError(f"keep names a quantity twice: {names}")
a = jnp.asarray(a, dtype=jnp.float64).reshape(-1)
if a.size == 0:
raise ValueError("a must be a non-empty array of scale factors")
if _is_concrete(a):
checked = np.asarray(a)
if not np.all(np.isfinite(checked)):
raise ValueError("a must be an array of finite scale factors")
if checked[0] < A_START or np.any(np.diff(checked) <= 0.0):
raise ValueError(
f"a must be strictly increasing and from A_START = {A_START} on"
)
# The launch starts at A_START, so the hook always records it. Drop
# that row unless the caller asked for it.
drop_first = bool(checked[0] > A_START)
else:
drop_first = True # traced values must lie after A_START
a_grid = jnp.concatenate((jnp.asarray([A_START]), a)) if drop_first else a
columns = _columns(dicts, model)
prepared = _prepare_solve(model, dicts, k_values, extra, columns)
layout = prepared.layout
n_k = len(prepared.k_sorted)
# The derived columns the cosmologies' replace set, in place of the computed ones.
given = _overrides(cosmologies, columns, model, extra)
# A kept quantity of the background alone (the conformal time, the opacity,
# the optical depth) is the same in every wave mode, and the background
# block saves it once per cosmology. Stored by every mode, they were 3 of
# the 7 numbers a CMB source solve wrote per save and trajectory, 8 percent
# of its launch at 128 cosmologies. A solve that keeps nothing else stores
# them per mode as before.
background = prepared.kernels.output_names
shared = tuple(name for name in names if name in background)
own = tuple(name for name in names if name not in background) or names
if own is names:
shared = ()
keys, given_keys = tuple(columns), tuple(given)
# The save times and an array of error weights go in as arguments, held
# fixed: under jit they are tracers, which the derivative rule below may
# not close over.
weights_array = isinstance(error_weights, jax.Array)
held = (jax.lax.stop_gradient(a_grid),) + (
(jax.lax.stop_gradient(error_weights),) if weights_array else ()
)
def kept(*leaves):
"""The kept values, ``(n_cosmologies, names, n_k, n_a)``, of the parameter columns and the set derived columns."""
n_cols, n_given = len(keys), len(given_keys)
cols = dict(zip(keys, leaves[:n_cols]))
given_now = dict(zip(given_keys, leaves[n_cols : n_cols + n_given]))
save_a, *rest = leaves[n_cols + n_given :]
weights = rest[0] if weights_array else error_weights
# A derivative reaches the launch through the parameter rows and the
# initial state, and modax integrates a sensitivity column along their
# tangent. The save times are held fixed.
params, y0 = _pack(
prepared.cosmology_model,
tuple(extra),
tuple(prepared.k_sorted.tolist()),
cols,
)
if given_now:
# the set derived columns in place of the computed ones
moved = density_parameters(cols, model=model, extra=extra)
moved.update(given_now)
for name, column in layout.values:
value = jnp.broadcast_to(
jnp.asarray(moved[name], jnp.float64), (n_cosmo,)
)
params = params.at[:, column].set(jnp.tile(value, n_k))
# the perturbations' outputs: their final state, then the kept quantities
out_bg, (_, out) = _launch(
prepared,
params,
y0,
save_a,
error_weights=weights,
save_hook=_keep_hook(prepared.cosmology_model, tuple(extra), own),
# the states the hook reads: the saves evaluate no others
save_states=_hook_reads(
prepared.cosmology_model, tuple(extra), own, prepared.kernels.n
),
save_history=False,
background_history=bool(shared),
split_derivatives=split_derivatives,
rtol=rtol,
atol=atol,
first_step=first_step,
max_steps=max_steps,
thermo_weight=thermo_weight,
)
# Rows are k-major (row = k_idx * n_cosmo + cosmology_idx) and each hook
# row save-major, so this reshape is a view. The transpose to
# cosmology-major copies only the kept values.
values = out.reshape(n_k, n_cosmo, save_a.shape[0], len(own))
values = jnp.transpose(values[:, :, int(drop_first) :, :], (1, 3, 0, 2))
if shared:
# the background's outputs at every save, (n_cosmo, n_a, outputs), in every mode
saved = out_bg[1][:, int(drop_first) :]
by_name = {name: values[:, i : i + 1] for i, name in enumerate(own)}
for name in shared:
column = saved[:, None, None, :, background.index(name)]
by_name[name] = jnp.broadcast_to(
column, (n_cosmo, 1, n_k, saved.shape[1])
)
values = jnp.concatenate([by_name[name] for name in names], axis=1)
return values
# Reverse mode takes a forward column per moving parameter column, seeded
# in every cosmology at once: a cosmology's values depend on its own row
# alone. modax's own reverse mode would seed a unit column per initial
# state and row column, which cancel at low k and magnify their error.
values = modax().by_forward_mode(kept, independent_rows=True)(
*columns.values(), *given.values(), *held
)
if np.any(prepared.order != np.arange(n_k)):
values = values[:, :, jnp.asarray(np.argsort(prepared.order)), :]
return values
[docs]
def derived_parameters(cosmologies) -> dict[str, jax.Array]:
"""Return the parameter-row columns the cosmologies imply, ``(n_cosmologies,)`` each, by name.
``cosmologies`` is a cosmology or a sequence of cosmologies of one
model. The kernel reads these columns: the parameters its methods
name (``omega_c``, ``omega_b``, ``Y_He``, ``T_cmb``, ...) and the
quantities the host computes from parameters for them (``omega_g``,
``omega_ur``, ``amnu``, ...), or the values
:meth:`~discoeb.models.Model.replace` set for those. Each is a name
``replace`` takes. JAX arrays, traceable under ``jit``.
"""
model, dicts = _batch_of(cosmologies)
columns = _columns(dicts, model)
values = density_parameters(columns, model=model)
values |= _overrides(cosmologies, columns, model)
return {
name: jnp.asarray(values[name], dtype=jnp.float64)
for name, _ in parameter_layout(model).values
}
[docs]
def state_names(model: type[Model]) -> tuple[str, ...]:
"""Return the perturbation state names of ``model``, for ``keep`` and ``error_weights``."""
return _model_of(model).state_names()