cosmograd
Differentiable cosmology in JAX behind a small protocol contract.
Consumers depend on two protocols, Background (expansion history and
distances) and Perturbations (growth and power spectra), not on any one
implementation. The core depends on JAX, jaxtyping and Diffrax; emulator
backends sit behind optional extras.
Install
uv add cosmograd # core: protocols + native backgrounds and linear power
uv add 'cosmograd[cosmopower]' # CosmoPower-JAX backend
uv add 'cosmograd[bacco]' # bacco emulator backend
Usage
import jax
import jax.numpy as jnp
from cosmograd import FlatLCDM
cosmo = FlatLCDM(H0=67.36, omega_m=0.3153)
z = jnp.linspace(0.1, 2.0, 20)
cosmo.luminosity_distance(z) # Mpc
jax.jacfwd(lambda c: c.luminosity_distance(z))(cosmo) # FlatLCDM-shaped Jacobian
FlatW0WaCDM adds CPL dark energy, $w(a) = w_0 + w_a (1 - a)$, with w0 and wa
as extra differentiable parameters:
from cosmograd import FlatW0WaCDM
cosmo = FlatW0WaCDM(H0=67.36, omega_m=0.3153, w0=-0.9, wa=0.2)
jax.grad(lambda c: c.comoving_distance(1.0))(cosmo).w0
W0WaCDM is the general background, adding a curvature parameter omega_k;
LCDM, FlatW0WaCDM and FlatLCDM are the same model with omega_k, w0
and wa fixed, so they are leaves of the pytree only for the parameters they
leave free. Curvature enters the expansion rate and the transverse distances
(luminosity_distance, angular_diameter_distance); the inverse of
comoving_distance is the line-of-sight one.
from cosmograd import W0WaCDM
cosmo = W0WaCDM(H0=67.36, omega_m=0.3153, omega_k=0.02)
cosmo.luminosity_distance(z)
Every class also takes omega_b, n_s and ln10as, so that one object holds
the whole cosmology. No background method reads them. They default to the
Planck 2018 values (0.04897, 0.9665 and 3.047), which the perturbation backends
then use without warning, so set them whenever you compute spectra. Standard
cosmologies carry their own:
from cosmograd.cosmologies import Planck18
Planck18.luminosity_distance(z)
Planck18.with_parameters(omega_m=0.30) # a modified copy
Here omega_b is $\Omega_b$ today, with 0 < omega_b < omega_m, and ln10as is
$\ln(10^{10} A_s)$ at the pivot $0.05,\mathrm{Mpc}^{-1}$.
The perturbation backends below take such a cosmology plus their own settings.
They assume a flat universe: EisensteinHu and BaccoEmu accept either flat class;
CosmoPower is trained on $\Lambda\mathrm{CDM}$ and takes a FlatLCDM only.
The native EisensteinHu backend provides linear matter power with EH98 baryon
acoustic oscillations, normalised by the primordial amplitude:
from cosmograd import EisensteinHu
pert = EisensteinHu(Planck18)
k = jnp.geomspace(1e-4, 1.0, 100) # 1/Mpc
pert.background is Planck18 # True
pert.matter_power_spectrum(k, z[:, None]) # Mpc^3, shape (20, 100)
pert.growth_function(z) # normalised to 1 at z = 0
# One FlatLCDM-shaped gradient over H0, omega_m, omega_b, n_s and ln10as.
jax.grad(lambda c: EisensteinHu(c).matter_power_spectrum(0.1, 0.5))(Planck18)
Growth is scale independent and neglects
radiation, using a Diffrax ODE initialized with $D = a$ at $a = 0.001$ and checked
through $z = 10$; background distances retain radiation. Massive neutrinos are
unsupported, and constructing with nonlinear=True raises
NotImplementedError.
The reusable growth solver accepts any differentiable Background:
from cosmograd.perturbations import linear_growth
# Matter-era initial conditions require negligible radiation at a_initial.
growth_background = FlatLCDM(H0=67.36, omega_m=0.3153, t_cmb=0.0)
D, f = linear_growth(growth_background, z) # D(0) = 1, f = d ln D / d ln a
D_md, f = linear_growth(growth_background, z, normalize=False) # initial D = a
The solver uses the supplied $H(z)$ and $\Omega_m(z)$, supporting curvature and smooth
dark energy within GR and scale-independent, subhorizon growth. Set
a_initial inside matter domination and check sensitivity to this choice.
The default of 0.001 ($z = 999$) is appropriate only for radiation-free
backgrounds (t_cmb=0); with radiation, $D$ and $f$ shift by roughly $10^{-4}$ to
$10^{-3}$ at the default, which rtol does not control. Such backgrounds need a larger
a_initial, late enough for radiation to be negligible but early enough that
dark energy and curvature still are. Redshifts must lie between 0 and
1/a_initial - 1, outside which the result is NaN, and may have any shape or
order. Solver failures, such as exceeding max_steps, raise an error. Both
forward- and
reverse-mode parameter derivatives are supported. EH keeps its FlatLCDM
transfer-function inputs and supplies a radiation-free expansion to this solver.
With the bacco extra, BaccoEmu emulates linear and nonlinear matter power
spectra. Weights are downloaded on first use into
the user cache directory (~/.cache/cosmograd/baccoemu on Linux), checked against
pinned SHA-256 digests and symlinked into baccoemu's install directory, so
they survive rebuilding the environment. Select the spectrum with the
constructor's nonlinear option, which defaults to False for every backend:
from cosmograd.perturbations.baccoemu import BaccoEmu
pert = BaccoEmu(Planck18, nonlinear=True)
k = jnp.geomspace(1e-3, 3.0, 100) # 1/Mpc
z = jnp.linspace(0.0, 1.5, 16)
pert.check_bounds(k, z) # eager check of the training ranges
pert.matter_power_spectrum(k, z[:, None]) # Mpc^3, shape (16, 100)
pert.linear_matter_power_spectrum(k, z[:, None]) # linear, whatever `nonlinear` is
BaccoEmu also takes neutrino_mass (the cosmology's omega_m is then the
total matter density, $\Omega_{cb} + \Omega_\nu$) and sigma8_cold, which sets the amplitude
in place of the cosmology's ln10as. With the cosmopower extra,
CosmoPower(Planck18, c_min=3.13, eta_0=0.603, nonlinear=True) works the same
way, with the HMcode feedback parameters as its own differentiable fields.
Units: distances in Mpc, wavenumbers in $\mathrm{Mpc}^{-1}$, $H$ in $\mathrm{Mpc}^{-1}$ ($c = 1$), power spectra in $\mathrm{Mpc}^3$. Inputs are not validated; each method documents the range it expects.
Calculation references
The EisensteinHu calculations follow:
- Eisenstein & Hu (1998), Baryonic Features in the Matter Transfer Function, equations (2)–(24): equality and drag scales, CDM and baryon contributions, acoustic oscillations and Silk damping.
- Heath (1977) and
Hamilton (2001), Formulae for growth factors,
equations (1)–(2): the growing-mode integral for matter plus $\Lambda$, used as an
independent reference in the ODE tests. The Diffrax solver integrates the
equivalent Sturm–Liouville form $(a^2 E D')' = \tfrac{3}{2} a^2 E \Omega_m D$ in
$\ln a$, using the variables described in the
linear_growthnotes, so $H$ is never differentiated. Matter-era growth starts with $D_\mathrm{md} = a$ and $D_\mathrm{md}' = a$; the public growth function is $D(z) = D_\mathrm{md}(z) / D_\mathrm{md}(0)$. - Smith & Angulo (2019), Precision modelling of the matter power spectrum in a Planck-like Universe, equations (8) and (10): the primordial spectrum (with zero running) and its conversion to matter power. Their $a g$ corresponds to $D_\mathrm{md}$ here; using today-normalised $D$ instead would change the absolute power normalisation.
- Planck Collaboration (2020), Planck 2018 results. VI. Cosmological parameters, section 2.1: the pivot $k = 0.05,\mathrm{Mpc}^{-1}$ and $\ln(10^{10} A_s)$ parameter convention.
Equation references also appear beside the corresponding calculations in
src/cosmograd/perturbations/eisenstein_hu.py.
Setup
Install uv and Just, then run:
just setup
uv run prek install
The underlying command is uv sync --all-groups if Just is unavailable.
Development
Spectrum comparison notebook
Install the notebook dependencies with uv sync --group notebook, then open
notebooks/perturbation_benchmark.py in a
notebook editor that supports Jupytext py:percent scripts (for example, VS Code's
Python Interactive window). Select the repository's .venv kernel and run all
cells. The first code cell contains imports; the second holds all editable
settings and enables Retina figures. First use may download emulator weights
and requires internet access.
The notebook compares linear and nonlinear spectra against CAMB at a shared
primordial amplitude; it does not benchmark runtime.
Only the percent script is maintained. To execute a temporary notebook from the repository root:
uv run --group notebook jupytext --to ipynb notebooks/perturbation_benchmark.py -o /tmp/perturbation_benchmark.ipynb
uv run --group notebook jupyter nbconvert --to notebook --execute /tmp/perturbation_benchmark.ipynb --output /tmp/perturbation_benchmark.executed.ipynb --ExecutePreprocessor.timeout=600
Repository checks
just fmt # uv run ruff check --fix . && uv run ruff format .
just lint # uv run ruff check .
just typecheck # uv run ty check
just test # uv run pytest
just hooks # uv run prek run --all-files
just check # full validation, tests, and package build
Tests check shape and dtype annotations through jaxtyping’s pytest import hook and beartype. Normal library imports do not enable runtime checking or require beartype. Shape annotations document conventions; static type checking does not verify array shapes.
Metadata
Release files for cosmograd 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cosmograd-0.1.0.tar.gz | 35.9 kB | With provenance | Details for cosmograd-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cosmograd-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for cosmograd-0.1.0-py3-none-any.whl |
Total release size: 84.7 kB
Release files / cosmograd-0.1.0.tar.gz
| Download URL | cosmograd-0.1.0.tar.gz |
|---|---|
| Size | 35.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6c6f96e9bdae2da879a2d7d7002ab21729d2f50a63e968e2b7d9cccbcf06704f
|
|
BLAKE2b-256 checksum How to use checksums |
5ceb405c0dd6277ea488560e6eee40e206c55fc7b1f022113577550fbf038b0d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.
Transparency logRelease files / cosmograd-0.1.0-py3-none-any.whl
| Download URL | cosmograd-0.1.0-py3-none-any.whl |
|---|---|
| Size | 48.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
bf3fdaf23480588f6ce55565cbeeeb5c297997a8bbfacec40978807f79c3d30b
|
|
BLAKE2b-256 checksum How to use checksums |
15743370a8f3437f2dc834c4c8afc2c3ab0788860f350fa6e08b2127bc74f3f1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.
Transparency logSecurity for cosmograd 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for cosmograd-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.