Components#

Components are the building blocks that define cosmological models in DISCO-EB, including gravity terms, fluid species and interactions between species.

This module defines the public API for components.

class discoeb.components.Component(**overrides)[source]#

Bases: object

Provides quantities and may own settings, parameters and state variables (see the module docstring).

A component may define a check classmethod whose parameters name the cosmology keys it validates (check(cls, w_DE_0, w_DE_a)), raising ValueError for values it cannot represent. Model.validate calls it with their values, unless one of them is traced. check is never a provider.

fixes_gauge: ClassVar[bool] = False#

Whether the component’s rest frame fixes the gauge the model’s equations are written in.

classmethod provided_names() → tuple[str, ...][source]#

The quantities the class’s methods provide, as written (derivatives left out).

classmethod named(name: str)[source]#

Return this component under a name of its own: Fluid.named("dr").

The copy is a subclass whose states, parameters and quantities carry the prefix name_: the state delta becomes dr_delta, the key Omega dr_Omega, the quantity density dr_density. Its functions are the class’s own, and each name in their signatures that the component itself declares resolves to the prefixed one. Every other name, and a contribution to one of the model’s sums, stays as written. So one model may list a component several times, each copy with its own state and parameters: two dark fluids, two scalar fields. Settings are shared.

classmethod declared_states() → list[tuple[str, State]][source]#

The State attributes, in declaration order, base classes first.

classmethod declared_sums() → tuple[str, ...][source]#

The names of the Sum attributes, base classes first.

classmethod declared_parameters() → list[tuple[str, ParameterDeclaration]][source]#

The parameter attributes (Parameter()), in declaration order, base classes first.

constants() → dict[str, object][source]#

The settings and every other public numeric attribute: what self holds on the device.

device_self()[source]#

self as the device sees it: a named tuple of constants().

numba types a named tuple’s fields individually, so an int setting, a float and a tuple of floats each keep their type, and a global instance is a compile-time constant the optimiser folds.

class discoeb.components.Species(**overrides)[source]#

Bases: Component

A component with a density: it contributes to the model’s sums.

class discoeb.components.Gravity(**overrides)[source]#

Bases: Component

A component of the theory of gravity: the expansion rate, the metric and its constraints.

The species read what these provide, the conformal Hubble rate aH and the metric sources h_prime and alpha, and never each other, so a model changes its theory of gravity by replacing them.

class discoeb.components.Interaction(**overrides)[source]#

Bases: Component

A component without state, writing the derivatives of species’ state.

class discoeb.components.State(shape=(), initial: Callable | None = None, error_weight: float = 1.0)[source]#

Bases: object

A state variable declared on a component: eta = State(), F = State(16).

shape is () for a scalar, n for a vector, (n, m) for a matrix, or a function of the component instance returning one of those. initial is the initial condition (see the module docstring). error_weight weights the state’s elements in the solver’s error norm unless a launch names its own: one by default, and zero takes the state out of step-size control.

discoeb.components.Parameter(default: Any = REQUIRED) → Any[source]#

Declare a cosmology key: omega_c: ArrayLike = Parameter().

It is an argument of every model whose components include the class: required without a default, optional with one. A provider reads it by naming it in its signature, which puts it in the kernel’s parameter row (ParameterDeclaration). The annotation is required, since a type checker reads the argument from it (the dataclass_transform on Component).

class discoeb.components.Setting(default: T)[source]#

Bases: Generic[T]

A component setting, LMAX_G = Setting(15), loaded from DISCO_LMAX_G.

On the class it reads as the loaded value, on an instance as the constructor’s override or the loaded value. The default’s type types the descriptor, so a type checker sees self.LMAX_G as an int.

class discoeb.components.Sum[source]#

Bases: object

A quantity summed over the components that contribute to it: rho = Sum().

The component that reads a sum declares it, and any component of the model adds to it with contributes(). A model’s sums are those its components declare. A sum keeps its name in a named component (Component.named()).

discoeb.components.contributes(*quantities: str) → Callable[[F], F][source]#

Mark a method as a contribution to a sum or a derivative: @contributes("delta_rho").

A method otherwise provides the quantity it is named after, and a sum (rho, delta_rho, …) or a state’s derivative d_x takes a contribution from several components. Under their shared name, those methods would clash in a model class that inherits them all, which type checkers report. So each contribution gets a name of its own and says what it contributes to:

@contributes("delta_rho")
def delta_rho_b(self, rho_b, delta_b):
    return rho_b * delta_b

One method may add the same value to several sums:

@contributes("rho", "rho_radiation")
def rho_photons(self, rho_g):
    return rho_g
discoeb.components.derivative(state: str) → Callable[[F], F][source]#

Mark a method as a contribution to a state’s rate: @derivative("theta_b").

A scalar state’s contribution is returned. A vector state’s is written into the method’s output. Several components may contribute to one state, and the rate is their sum:

@derivative("theta_b")
def euler_b(self, aH, theta_b, k, cs2, delta_b):
    return -aH * theta_b + k * k * cs2 * delta_b

The rate itself is the quantity d_theta_b, which a provider or a save hook may read.

class discoeb.components.Equations(components: Iterable[Component], time: str = 'tau', clock: str | None = None, last: Sequence[str] = ())[source]#

Bases: object

The equations of a list of components, on the host and on the device.

The components declare states, parameters, sums and providers, and an Equations resolves them into one system. It lays the states out in a flat state vector and orders the providers by the names in their signatures. Every method below works from that resolution.

On the host, evaluate() computes any quantity from given values, with math or jax.numpy. initial_state() fills the state vector from the states’ initial conditions, and state_values() splits a state array back into named states. hoisted() and frontier() find the quantities that depend on nothing but the parameters, and the columns the kernel reads.

The structure of the system comes from tracing the providers. sparsity() returns the Jacobian’s nonzero pattern. stages() splits the states into a background block and a perturbation block, and published() names the quantities the background hands to the perturbations.

On the device, build() generates the right-hand side rhs(y, t, p) -> tuple that modax integrates, for the full system or one block of it. build_function() generates a device function for any other quantities, such as a save hook’s outputs.

A model’s build() returns its Equations, and joint_model() adds the recombination block and builds with time="a" and clock="a_prime", so every solve integrates in the scale factor:

equations = joint_model(LCDM)
background, perturbations = equations.stages()
pattern = equations.sparsity()  # (nnz, 2)
Parameters:
  • components – The component instances, in state order.

  • time – The name of the independent variable of build(), tau by default.

  • clock – The name of the rate of time in conformal time. The components write their rates in conformal time, and build() divides each by clock, so the system integrates in time. Without a clock, build() returns the rates as written.

  • last – States that go after all the others in the state vector. The rest keep declaration order. A solve in two blocks lays out one block after the other, so the joint model puts its background states last.

hoisted(parameters: Iterable[str]) → tuple[str, ...][source]#

The quantities that depend on the parameters and on nothing else, in provider order.

A quantity is hoisted when every name it reads, directly or through other quantities, is one of parameters, and it reads at least one. It is then the same at every time and wave number, so a solve evaluates it once per cosmology on the host (evaluate()) and hands the kernel its value (frontier()). Nothing declares this: it is read off the signatures. A quantity that reads the time, a state or any other input stays in the kernel, as does one that reads nothing, which the compiler folds.

frontier(parameters: Iterable[str]) → tuple[str, ...][source]#

Returns the columns of the parameter row that the kernel will read.

Every provider except the hoisted ones (hoisted()) runs in the kernel. When one of them names a parameter or a hoisted quantity in its signature, the host passes that value to the kernel as a column of the parameter row. Parameters that only hoisted quantities read, and hoisted quantities that only other hoisted quantities read, stay on the host. The row lists the parameters first, in the order given, then the hoisted quantities in provider order.

sparsity() → ndarray[source]#

The (nnz, 2) index array of the Jacobian’s nonzeros, traced through the providers.

Runs the same resolution as evaluate(), but on values that carry the set of state elements they depend on instead of numbers (_TracedValues). Each contribution to d_<state> comes back carrying the columns of that row, a vector’s element by element through the output it fills. The pattern is exact except at data-dependent branches, where a provider counts as reading all of its inputs, which gives the superset a colouring needs. The solver adds the diagonal of the Rosenbrock matrix I/(h gamma) - J, which the pattern leaves out. Rows come sorted.

reads_state(quantity: str) → bool[source]#

Whether quantity depends on any state element, by the trace of sparsity().

state_reads(quantities: Sequence[str]) → tuple[int, ...][source]#

The state elements quantities depend on, increasing, by the trace of sparsity().

A quantity that is a state element reads itself.

stages() → tuple[tuple[str, ...], tuple[str, ...]][source]#

(background states, perturbation states), read off the equations.

A state belongs to the background if its derivative depends neither on the wave number k nor on a state that does, so the background is the largest set of states that evolves on its own. Nothing declares the split. The same trace as sparsity() finds it, with k followed like a state: the conformal time, the recombination history and a scalar field’s homogeneous value come out as the background of whatever model lists them.

published() → tuple[str, ...][source]#

The background quantities the perturbation equations take as given, as few as will do.

The background block of a solve steps ahead of the perturbations and hands them what they read of it. Any set of quantities that separates the background states from the perturbation equations would do. This returns the smallest, counted in numbers handed over (a minimum vertex cut of the dependency graph), and among equals the one nearest the perturbations, so that work a quantity hides (the recombination rates behind the opacity) stays in the background block. A background state the perturbations read directly is published itself.

evaluate(*quantities, math=<module 'math' (built-in)>, **base)[source]#

Evaluate quantities on the host from the base values.

A name resolves as a base value, a state’s initial value, a sum over the components, or a provider, whose dependencies resolve the same way. math is the module the providers’ math.sqrt and friends use: the standard library for floats, jax.numpy for JAX arrays. That makes the background expansion rate the model’s own rho and aH, traced under jit. Returns one value or a tuple.

initial_state(k_values, xp=<module 'numpy' from '/home/runner/work/DISCO-EB/DISCO-EB/.venv/lib/python3.13/site-packages/numpy/__init__.py'>, **base)[source]#

The initial state, (n_k, nvar), from the states’ initial conditions.

base holds the quantities the initial conditions may name besides k: the time and the background parameters. A name resolves as a base quantity, a state (its own initial value), or a provider evaluated on the host from the same pool.

One resolution covers all wave modes: k is the full array, numpy stands in for math so the initial conditions’ algebra broadcasts over it, and a vector state’s filler writes rows of n_k values (batch_shape of _HostValues). Resolving once per mode would inspect every initial condition’s signature at every mode.

xp is the array module, numpy or jax.numpy. With jax.numpy the base values may be traced: nothing is written in place, so the initial state traces under jit and stays on the device.

error_weights() → ndarray[source]#

The states’ declared error weights, one per element: (nvar,).

state_indices(states) → list[int][source]#

The flat indices of the elements of states, in model order.

state_values(y, xp=<module 'numpy' from '/home/runner/work/DISCO-EB/DISCO-EB/.venv/lib/python3.13/site-packages/numpy/__init__.py'>) → dict[source]#

The states of a flat state array y (last axis), by name.

A vector state comes back with its components as the leading axis (a matrix with two), so a provider’s F[l] and psi[i, l] index the component and broadcast over the rest. That lets evaluate() run the model over a full history on the host. xp is numpy or jax.numpy, matching y.

build(params: Mapping[str, int], *, name: str = 'rhs', states: Sequence[str] | None = None, quantities: Sequence[str] = (), jit: Callable | None = None, cuda=None, float64=None) → Callable[source]#

Generate rhs(y, tau, p) -> tuple and return it as a plain Python function.

The time is the model’s time, tau by default, and with a clock the rates returned are the components’ divided by it.

params maps parameter names to their column in the row p. By default the build compiles the providers with cuda.jit(device=True) against the CUDA cuda and float64. A test may pass jit (an identity for plain Python) and stand-ins for the two device names to run the model on the host.

states restricts the function to a block of the model: y then holds only those states, packed in model order, and the function returns their rates. quantities are names the function takes as given, in a tuple q after p (rhs(y, tau, p, q)), in place of their providers. The perturbations of a solve read these from the table its background solve keeps. A function whose rates need a state outside states fails to compile, which checks that the coupling is one-way.

build_function(outputs: Sequence[str], *, inputs: Sequence[str] = (), params: Mapping[str, int] | None = None, name: str = 'quantities', states: Sequence[str] | None = None, jit: Callable | None = None, cuda=None, float64=None) → Callable[source]#

Generate a device function returning the tuple of quantities outputs.

inputs are the base quantities it takes as positional arguments, in that order. The name "y" among them stands for the flat state, read into the states as build() does (only the block states when given, packed in model order), and an output may name one of its elements (tau, thermo_0), which comes straight from y. With params the function takes the parameter row p last. The components provide everything else the outputs need, so a kernel that needs the expansion rate or the line-of-sight sources computes them from the same equations as the right-hand side.