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:
objectProvides quantities and may own settings, parameters and state variables (see the module docstring).
A component may define a
checkclassmethod whose parameters name the cosmology keys it validates (check(cls, w_DE_0, w_DE_a)), raisingValueErrorfor values it cannot represent.Model.validatecalls it with their values, unless one of them is traced.checkis 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 statedeltabecomesdr_delta, the keyOmegadr_Omega, the quantitydensitydr_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
Stateattributes, in declaration order, base classes first.
- classmethod declared_sums() tuple[str, ...][source]#
The names of the
Sumattributes, 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
selfholds on the device.
- device_self()[source]#
selfas the device sees it: a named tuple ofconstants().numba types a named tuple’s fields individually, so an
intsetting, afloatand 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:
ComponentA component with a density: it contributes to the model’s sums.
- class discoeb.components.Gravity(**overrides)[source]#
Bases:
ComponentA component of the theory of gravity: the expansion rate, the metric and its constraints.
The species read what these provide, the conformal Hubble rate
aHand the metric sourcesh_primeandalpha, and never each other, so a model changes its theory of gravity by replacing them.
- class discoeb.components.Interaction(**overrides)[source]#
Bases:
ComponentA 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:
objectA state variable declared on a component:
eta = State(),F = State(16).shapeis()for a scalar,nfor a vector,(n, m)for a matrix, or a function of the component instance returning one of those.initialis the initial condition (see the module docstring).error_weightweights 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 (thedataclass_transformonComponent).
- class discoeb.components.Setting(default: T)[source]#
Bases:
Generic[T]A component setting,
LMAX_G = Setting(15), loaded fromDISCO_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_Gas anint.
- class discoeb.components.Sum[source]#
Bases:
objectA 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 derivatived_xtakes 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:
objectThe equations of a list of components, on the host and on the device.
The components declare states, parameters, sums and providers, and an
Equationsresolves 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, withmathorjax.numpy.initial_state()fills the state vector from the states’ initial conditions, andstate_values()splits a state array back into named states.hoisted()andfrontier()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, andpublished()names the quantities the background hands to the perturbations.On the device,
build()generates the right-hand siderhs(y, t, p) -> tuplethat 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 itsEquations, andjoint_model()adds the recombination block and builds withtime="a"andclock="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(),tauby default.clock – The name of the rate of
timein conformal time. The components write their rates in conformal time, andbuild()divides each byclock, so the system integrates intime. 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
parametersand 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 tod_<state>comes back carrying the columns of that row, a vector’s element by element through theoutputit 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 matrixI/(h gamma) - J, which the pattern leaves out. Rows come sorted.
- reads_state(quantity: str) bool[source]#
Whether
quantitydepends on any state element, by the trace ofsparsity().
- state_reads(quantities: Sequence[str]) tuple[int, ...][source]#
The state elements
quantitiesdepend on, increasing, by the trace ofsparsity().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
knor 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 assparsity()finds it, withkfollowed 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
quantitieson the host from thebasevalues.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.
mathis the module the providers’math.sqrtand friends use: the standard library for floats,jax.numpyfor JAX arrays. That makes the background expansion rate the model’s ownrhoandaH, traced underjit. 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.baseholds the quantities the initial conditions may name besidesk: 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:
kis the full array,numpystands in formathso the initial conditions’ algebra broadcasts over it, and a vector state’s filler writes rows ofn_kvalues (batch_shapeof_HostValues). Resolving once per mode would inspect every initial condition’s signature at every mode.xpis the array module,numpyorjax.numpy. Withjax.numpythe base values may be traced: nothing is written in place, so the initial state traces underjitand stays on the device.
- 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]andpsi[i, l]index the component and broadcast over the rest. That letsevaluate()run the model over a full history on the host.xpisnumpyorjax.numpy, matchingy.
- 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) -> tupleand return it as a plain Python function.The time is the model’s
time,tauby default, and with aclockthe rates returned are the components’ divided by it.paramsmaps parameter names to their column in the rowp. By default the build compiles the providers withcuda.jit(device=True)against the CUDAcudaandfloat64. A test may passjit(an identity for plain Python) and stand-ins for the two device names to run the model on the host.statesrestricts the function to a block of the model:ythen holds only those states, packed in model order, and the function returns their rates.quantitiesare names the function takes as given, in a tupleqafterp(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 outsidestatesfails 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.inputsare 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 asbuild()does (only the blockstateswhen given, packed in model order), and an output may name one of its elements (tau,thermo_0), which comes straight fromy. Withparamsthe function takes the parameter rowplast. 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.