Skip to content

Core API

Spec

Trace dataclass

Trace(x: ndarray, y: ndarray, label: str = '', color_value: float | None = None, style: dict[str, Any] = dict())

A single data series within a PlotSpec.

Attributes:

Name Type Description
x ndarray

Array of x-axis values.

y ndarray

Array of y-axis values.

label str

Legend label for this trace. Empty string means no legend entry.

color_value float | None

Scalar used for colormap-based coloring (XYZColored plots). None means use the theme palette instead.

style dict[str, Any]

Backend-specific keyword arguments passed through to the underlying draw call (e.g. {"linestyle": "--"} for matplotlib).

PlotSpec dataclass

PlotSpec(traces: list[Trace | BandTrace], x_label: str = '', y_label: str = '', title: str = '', x_scale: Literal['linear', 'log'] = 'linear', y_scale: Literal['linear', 'log'] = 'linear', theme: ThemeSpec | None = None, figsize: tuple[float, float] | None = None, colormap: str | None = None, z_label: str = '', colorbar: bool = True, colorbar_pad: float | None = None, colorbar_scale: float = 1.175, latex_labels: bool = False, secondary_x_axis: SecondaryAxisSpec | None = None)

Backend-agnostic intermediate representation for a single plot panel.

PlotSpec is the decoupling boundary between Plot subclasses and backends. Plot subclasses produce it; backends consume it. Neither side imports the other.

Attributes:

Name Type Description
traces list[Trace | BandTrace]

Ordered list of data series to draw.

x_label str

Axis label for the x-axis. May contain LaTeX when latex_labels=True.

y_label str

Axis label for the y-axis.

title str

Panel title.

x_scale Literal['linear', 'log']

Scale type for the x-axis ("linear" or "log").

y_scale Literal['linear', 'log']

Scale type for the y-axis.

theme ThemeSpec | None

Visual theme. None uses each backend's own defaults.

figsize tuple[float, float] | None

Figure size (width, height) in inches. None uses the backend default.

colormap str | None

Named colormap (e.g. "viridis") for XYZColored plots. None means use the theme palette.

z_label str

Colorbar label, used when colormap is set.

colorbar bool

Whether to draw a colorbar when colormap is set.

latex_labels bool

When True, axis/title strings are passed raw to the backend (suitable for backends with MathJax support such as plotly HTML export). When False, labels are stripped to plain Unicode via :func:~cplots.core.labels.strip_latex.

SecondaryAxisSpec dataclass

SecondaryAxisSpec(forward: Callable[[ndarray], ndarray], inverse: Callable[[ndarray], ndarray], label: str = '')

Secondary (twin) top x-axis specification, backend-agnostic.

Attributes:

Name Type Description
forward Callable[[ndarray], ndarray]

Maps primary-axis values to secondary-axis values (e.g. k → ℓ).

inverse Callable[[ndarray], ndarray]

Maps secondary-axis values back to primary (e.g. ℓ → k).

label str

Label for the secondary axis.

PanelSpec dataclass

PanelSpec(plot: PlotSpec, row: int, col: int, rowspan: int = 1, colspan: int = 1)

Position and content of one panel inside a multi-panel figure.

Attributes:

Name Type Description
plot PlotSpec

The PlotSpec rendered in this panel.

row int

Zero-based row index in the grid.

col int

Zero-based column index in the grid.

rowspan int

Number of grid rows this panel occupies.

colspan int

Number of grid columns this panel occupies.

FigureSpec dataclass

FigureSpec(panels: list[PanelSpec], nrows: int, ncols: int, figsize: tuple[float, float] | None = None, width_ratios: list[float] | None = None, height_ratios: list[float] | None = None, theme: ThemeSpec | None = None, sharex: bool = False, sharey: bool = False, latex_labels: bool = False, colormap: str | None = None, z_label: str = '', colorbar: bool = False, colorbar_pad: float | None = None, colorbar_scale: float = 1.175, hspace: float | None = None, wspace: float | None = None)

Backend-agnostic IR for multi-panel figures (the multi-panel PlotSpec).

Attributes:

Name Type Description
panels list[PanelSpec]

List of panels that make up the figure.

nrows int

Total number of rows in the grid.

ncols int

Total number of columns in the grid.

figsize tuple[float, float] | None

Overall figure size (width, height) in inches.

width_ratios list[float] | None

Relative widths of each column. Length must equal ncols when provided.

height_ratios list[float] | None

Relative heights of each row. Length must equal nrows when provided.

theme ThemeSpec | None

Visual theme applied to all panels.

sharex bool

Whether panels in the same column share an x-axis.

sharey bool

Whether panels in the same row share a y-axis.

latex_labels bool

Propagated to all panels; see :class:PlotSpec.

Secondary axis helpers

multipole_axis

multipole_axis(chi: float, label: str = 'ℓ') -> SecondaryAxisSpec

Secondary axis mapping k → ℓ = k · chi for PKSpectrum plots.

Parameters:

Name Type Description Default
chi float

Comoving distance in the same units as k (e.g. Mpc/h).

required
label str

Label for the secondary axis.

'ℓ'
Example

PKSpectrum(k, pk, secondary_x_axis=multipole_axis(chi=13890)).show()

wavenumber_axis

wavenumber_axis(chi: float, label: str = 'k') -> SecondaryAxisSpec

Secondary axis mapping ℓ → k = ℓ / chi for ClSpectrum plots.

Parameters:

Name Type Description Default
chi float

Comoving distance in the same units as k (e.g. Mpc/h).

required
label str

Label for the secondary axis.

'k'
Example

ClSpectrum(ell, cl, secondary_x_axis=wavenumber_axis(chi=13890)).show()

Theme

ThemeSpec dataclass

ThemeSpec(font_family: str = 'sans-serif', font_size: int = 12, background_color: str = 'white', palette: tuple[str, ...] = ('#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd'), figsize: tuple[float, float] = (6.4, 4.8), extra: dict[str, Any] = dict())

Immutable visual theme applied across all backends.

Pass a ThemeSpec to any plot constructor or to :class:~cplots.Figure to override the backend's defaults.

Attributes:

Name Type Description
font_family str

Font family name (e.g. "serif", "sans-serif").

font_size int

Base font size in points.

background_color str

Background color string. Use "none" for a transparent background (blends with dark slides/notebooks).

palette tuple[str, ...]

Tuple of hex color strings cycled across traces.

extra dict[str, Any]

Backend-specific rcParams or config overrides. The matplotlib backend applies these directly to mpl.rcParams; other backends may ignore unknown keys.

Data containers

PlotData dataclass

PlotData()

Marker base for all typed plot data containers.

XYData dataclass

XYData(x: ndarray, y: ndarray, x_label: str = '', y_label: str = '', uncertainties: ndarray | None = None)

Bases: PlotData

PKData dataclass

PKData(x: ndarray, y: ndarray, x_label: str = '', y_label: str = '', uncertainties: ndarray | None = None, redshift: float = 0.0)

Bases: XYData

ClData dataclass

ClData(x: ndarray, y: ndarray, x_label: str = '', y_label: str = '', uncertainties: ndarray | None = None)

Bases: XYData

BackgroundData dataclass

BackgroundData(redshift: ndarray, quantities: dict[str, ndarray], labels: dict[str, str] = dict())

Bases: PlotData

TriangleData dataclass

TriangleData(samples: ndarray, parameter_names: list[str], weights: ndarray | None = None, truths: dict[str, float] = dict())

Bases: PlotData

XYZData dataclass

XYZData()

Bases: PlotData

Marker type for XYZColored plots.

Labels

strip_latex

strip_latex(text: str) -> str

Convert a LaTeX-formatted label to plain Unicode text.

Handles Greek letters, common symbols, super/subscripts, and removes math-mode delimiters. Intended for backends without a LaTeX renderer.

Examples::

>>> strip_latex(r"$k$ [$h$ Mpc$^{-1}$]")
'k [h Mpc⁻¹]'
>>> strip_latex(r"$\Omega_m$")
'Ω_m'
>>> strip_latex(r"$\ell(\ell+1)C_\ell/2\pi$")
'ℓ(ℓ+1)Cℓ/2π'

Registry

get_backend module-attribute

get_backend = _registry.get

Retrieve a backend by name. Alias for :meth:BackendRegistry.get.

register_backend module-attribute

register_backend = _registry.register

Register a backend instance. Alias for :meth:BackendRegistry.register.

Backend selection

backend

backend(name: str) -> Generator[None, None, None]

Temporarily override the active backend within a block.

set_backend

set_backend(name: str) -> None

Set the process-wide default backend.

resolve_backend

resolve_backend() -> str

Return the currently active backend name.

Solver adapters

Observables

Bases: ABC

Abstract base for cosmological solver adapters.

Subclass this and implement :meth:background, :meth:pk, and :meth:cl to make any Boltzmann solver (CLASS, CAMB, custom) compatible with cplots plots without modifying any cplots internals.

The three required methods return cplots-native :class:~cplots.core.data.PlotData objects that plot constructors accept directly. Two optional methods, :meth:primordial and :meth:thermodynamics, raise :class:NotImplementedError by default; override them if your solver supports those outputs.

Example::

import numpy as np
import cplots
from cplots import Observables, BackgroundData, PKData, ClData

class MyCAMB(Observables):
    def __init__(self, results):
        self._results = results

    def background(self, **kwargs) -> BackgroundData:
        z, H = self._results.get_background()
        return BackgroundData(redshift=z, quantities={"H": H})

    def pk(self, z: float = 0.0, **kwargs) -> PKData:
        k, pk = self._results.get_matter_power(z=z)
        return PKData(x=k, y=pk, redshift=z)

    def cl(self, **kwargs) -> dict[str, ClData]:
        ell, cl_tt = self._results.get_cmb_cls()
        return {"tt": ClData(x=ell, y=cl_tt)}

out = MyCAMB(camb_results)
cplots.PKSpectrum(out.pk(z=0.0)).show()

Methods:

background abstractmethod
background(**kwargs: Any) -> BackgroundData

Extract background cosmological evolution.

Returns:

Type Description
BackgroundData

class:~cplots.core.data.BackgroundData with a redshift array

BackgroundData

and named quantity arrays (e.g. H(z), distances).

pk abstractmethod
pk(z: float = 0.0, **kwargs: Any) -> PKData

Extract the matter power spectrum P(k) at redshift z.

Parameters:

Name Type Description Default
z float

Redshift at which to evaluate P(k).

0.0
**kwargs Any

Solver-specific options (e.g. k_min, nonlinear, h_units).

{}

Returns:

Type Description
PKData

class:~cplots.core.data.PKData.

cl abstractmethod
cl(**kwargs: Any) -> dict[str, ClData]

Extract CMB angular power spectra.

Parameters:

Name Type Description Default
**kwargs Any

Solver-specific options (e.g. lensed, l_max, spectra, ell_factor).

{}

Returns:

Type Description
dict[str, ClData]

Mapping of spectrum name ("tt", "ee", …) to

dict[str, ClData]

class:~cplots.core.data.ClData.

primordial
primordial(**kwargs: Any) -> PKData

Extract the primordial scalar power spectrum.

Not all solvers expose this output. Override to provide an implementation; raises :class:NotImplementedError by default.

thermodynamics
thermodynamics(**kwargs: Any) -> BackgroundData

Extract thermodynamics evolution (e.g. visibility function).

Not all solvers expose this output. Override to provide an implementation; raises :class:NotImplementedError by default.

ClassOutput

ClassOutput(cosmo: Any)

Bases: Observables

Adapter facade for a computed classy.Class run.

Extracts cosmological quantities from a CLASS instance into cplots-native PlotData objects. The CLASS run must already be computed (cosmo.compute() called) before wrapping it here.

Example::

import cplots
from classy import Class

cosmo = Class()
cosmo.set({"output": "tCl pCl lCl mPk", "lensing": "yes"})
cosmo.compute()

out = cplots.ClassOutput(cosmo)
cplots.BackgroundEvolution(out.background()).show()
cplots.PKSpectrum(out.pk(z=0.0)).show()
cplots.ClSpectrum(out.cl(spectra=["tt", "ee"])).show()

Methods:

background
background(quantities: Sequence[str] | None = None, labels: dict[str, str] | None = None, **kwargs: Any) -> BackgroundData

Extract background cosmological evolution.

Parameters:

Name Type Description Default
quantities Sequence[str] | None

CLASS background dict keys to extract. Defaults to ["H [1/Mpc]", "lum. dist.", "ang.diam.dist.", "comov. dist."].

None
labels dict[str, str] | None

Display labels keyed by quantity name. Known quantities get sensible LaTeX defaults; unknown quantities fall back to the key.

None

Returns:

Type Description
BackgroundData

BackgroundData with redshift and requested quantity arrays.

Raises:

Type Description
RuntimeError

If the background table is unavailable.

KeyError

If a requested quantity key is absent from CLASS output.

pk
pk(z: float = 0.0, k_min: float = 0.0001, k_max: float = 1.0, n_k: int = 200, nonlinear: bool = False, h_units: bool = True, **kwargs: Any) -> PKData

Extract matter power spectrum P(k) at a given redshift.

Parameters:

Name Type Description Default
z float

Redshift at which to evaluate P(k).

0.0
k_min float

Minimum wavenumber (units set by h_units).

0.0001
k_max float

Maximum wavenumber (units set by h_units).

1.0
n_k int

Number of k points (log-spaced).

200
nonlinear bool

Use non-linear P(k) (requires non_linear in CLASS params).

False
h_units bool

If True (default), k is in h/Mpc and P(k) in (Mpc/h)³. If False, k is in 1/Mpc and P(k) in Mpc³.

True

Returns:

Type Description
PKData

PKData with k array, P(k) array, redshift, and axis labels.

Raises:

Type Description
RuntimeError

If P(k) is unavailable (mPk not in CLASS output).

cl
cl(lensed: bool = True, spectra: Sequence[Literal['tt', 'ee', 'bb', 'te', 'pp']] | None = None, l_max: int = 2500, ell_factor: bool = True, units: Literal['muK2', 'K2', 'dimensionless'] = 'muK2', **kwargs: Any) -> dict[str, ClData]

Extract CMB angular power spectra.

Parameters:

Name Type Description Default
lensed bool

Use lensed (True, default) or unlensed spectra.

True
spectra Sequence[Literal['tt', 'ee', 'bb', 'te', 'pp']] | None

Which spectra to extract. Defaults to ["tt"]. Available: "tt", "ee", "bb", "te", "pp".

None
l_max int

Maximum multipole to request from CLASS.

2500
ell_factor bool

If True (default), apply the ℓ(ℓ+1)/2π scaling standard in CMB plotting.

True
units Literal['muK2', 'K2', 'dimensionless']

Temperature unit for the output spectra. "muK2" (default) multiplies by T_CMB² in μK², "K2" gives K², and "dimensionless" applies no conversion (CLASS native units).

'muK2'

Returns:

Type Description
dict[str, ClData]

Dict mapping spectrum name ("tt", "ee", …) to ClData.

Raises:

Type Description
RuntimeError

If CMB spectra are unavailable.

ValueError

If units is not one of the accepted values.

primordial
primordial(**kwargs: Any) -> PKData

Extract primordial scalar power spectrum.

Returns:

Type Description
PKData

PKData with k in 1/Mpc and P_s(k).

Raises:

Type Description
RuntimeError

If primordial spectrum is unavailable.

thermodynamics
thermodynamics(quantities: Sequence[str] | None = None, labels: dict[str, str] | None = None, **kwargs: Any) -> BackgroundData

Extract thermodynamics evolution.

Parameters:

Name Type Description Default
quantities Sequence[str] | None

CLASS thermodynamics dict keys to extract. Defaults to ["g [Mpc^-1]"] (visibility function).

None
labels dict[str, str] | None

Display labels keyed by quantity name.

None

Returns:

Type Description
BackgroundData

BackgroundData with redshift and requested quantity arrays.

Raises:

Type Description
RuntimeError

If thermodynamics table is unavailable.

KeyError

If a requested quantity key is absent from CLASS output.

CambOutput

CambOutput(results: Any)

Bases: Observables

Adapter facade for a computed CAMB results object.

Extracts cosmological quantities from a camb.CAMBdata instance into cplots-native :class:~cplots.core.data.PlotData objects. The CAMB run must already be computed (camb.get_results(pars) called) before wrapping it here.

Example::

import camb
import cplots

pars = camb.set_params(
    H0=67.4, ombh2=0.022, omch2=0.12, mnu=0.06,
    omk=0, tau=0.054, As=2.1e-9, ns=0.965,
    lmax=2500, redshifts=[0.0, 1.0],
)
results = camb.get_results(pars)

out = cplots.CambOutput(results)
cplots.BackgroundEvolution(out.background()).show()
cplots.PKSpectrum(out.pk(z=0.0)).show()
cplots.ClSpectrum(out.cl(spectra=["tt", "ee"])).show()

Methods:

background
background(z: Any | None = None, quantities: Sequence[str] | None = None, labels: dict[str, str] | None = None, **kwargs: Any) -> BackgroundData

Extract background cosmological evolution.

Unlike CLASS, CAMB evaluates background quantities on demand over a caller-supplied redshift grid rather than from a pre-computed table.

Parameters:

Name Type Description Default
z Any | None

Redshift array at which to evaluate quantities. Defaults to np.linspace(0, 3, 300).

None
quantities Sequence[str] | None

Keys to extract. Must be a subset of ["H [km/s/Mpc]", "lum. dist.", "ang.diam.dist.", "comov. dist."]. Defaults to all four.

None
labels dict[str, str] | None

Display labels keyed by quantity name. Known quantities get sensible LaTeX defaults; unknown quantities fall back to their key string.

None

Returns:

Type Description
BackgroundData

class:~cplots.core.data.BackgroundData with z and the

BackgroundData

requested quantity arrays.

Raises:

Type Description
KeyError

If a requested quantity key is not recognised.

RuntimeError

If a CAMB call fails (e.g. results not computed).

pk
pk(z: float = 0.0, k_min: float = 0.0001, k_max: float = 1.0, n_k: int = 200, nonlinear: bool = False, h_units: bool = True, **kwargs: Any) -> PKData

Extract matter power spectrum P(k) at a given redshift.

Uses results.get_matter_power_interpolator() internally, so z does not need to exactly match the redshifts passed to camb.set_params(redshifts=[...]).

Parameters:

Name Type Description Default
z float

Redshift at which to evaluate P(k).

0.0
k_min float

Minimum wavenumber (h/Mpc when h_units=True, else 1/Mpc).

0.0001
k_max float

Maximum wavenumber (same units as k_min).

1.0
n_k int

Number of k points (log-spaced).

200
nonlinear bool

Use non-linear P(k) (requires a non-linear model configured in the CAMB params).

False
h_units bool

If True (default), k is in h/Mpc and P(k) in (Mpc/h)³. If False, k is in 1/Mpc and P(k) in Mpc³.

True

Returns:

Type Description
PKData

class:~cplots.core.data.PKData with k, P(k), redshift, and

PKData

axis labels.

Raises:

Type Description
RuntimeError

If the CAMB call fails (e.g. WantTransfer not set or results not computed).

cl
cl(lensed: bool = True, spectra: Sequence[Literal['tt', 'ee', 'bb', 'te', 'pp']] | None = None, l_max: int | None = None, ell_factor: bool = True, units: Literal['muK2', 'K2', 'dimensionless'] = 'muK2', **kwargs: Any) -> dict[str, ClData]

Extract CMB angular power spectra.

CAMB handles the ell-factor and unit conversion natively, so the implementation maps directly to results.get_cmb_power_spectra().

Parameters:

Name Type Description Default
lensed bool

Use lensed (True, default) or unlensed spectra.

True
spectra Sequence[Literal['tt', 'ee', 'bb', 'te', 'pp']] | None

Which spectra to extract. Defaults to ["tt"]. Available: "tt", "ee", "bb", "te", "pp".

None
l_max int | None

Maximum multipole to include. Defaults to the full array returned by CAMB.

None
ell_factor bool

If True (default), apply the ℓ(ℓ+1)/2π scaling standard in CMB plotting.

True
units Literal['muK2', 'K2', 'dimensionless']

Temperature unit. "muK2" (default), "K2", or "dimensionless".

'muK2'

Returns:

Type Description
dict[str, ClData]

Dict mapping spectrum name to :class:~cplots.core.data.ClData.

Raises:

Type Description
ValueError

If units is not one of the accepted values.

RuntimeError

If the CAMB call fails.

primordial
primordial(k_min: float = 0.0001, k_max: float = 1.0, n_k: int = 200, **kwargs: Any) -> PKData

Extract primordial scalar power spectrum.

Computes the power-law spectrum analytically from the InitialPowerLaw parameters stored in results.Params.InitPower. This works for the default scalar power-law model; subclass and override for running-index or tabulated spectra.

Parameters:

Name Type Description Default
k_min float

Minimum wavenumber in 1/Mpc.

0.0001
k_max float

Maximum wavenumber in 1/Mpc.

1.0
n_k int

Number of k points (log-spaced).

200

Returns:

Type Description
PKData

class:~cplots.core.data.PKData with k in 1/Mpc and P_s(k).