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).
|
style |
dict[str, Any]
|
Backend-specific keyword arguments passed through to the
underlying draw call (e.g. |
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
|
y_label |
str
|
Axis label for the y-axis. |
title |
str
|
Panel title. |
x_scale |
Literal['linear', 'log']
|
Scale type for the x-axis ( |
y_scale |
Literal['linear', 'log']
|
Scale type for the y-axis. |
theme |
ThemeSpec | None
|
Visual theme. |
figsize |
tuple[float, float] | None
|
Figure size |
colormap |
str | None
|
Named colormap (e.g. |
z_label |
str
|
Colorbar label, used when |
colorbar |
bool
|
Whether to draw a colorbar when |
latex_labels |
bool
|
When |
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
¶
Position and content of one panel inside a multi-panel figure.
Attributes:
| Name | Type | Description |
|---|---|---|
plot |
PlotSpec
|
The |
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_ratios |
list[float] | None
|
Relative widths of each column. Length must equal
|
height_ratios |
list[float] | None
|
Relative heights of each row. Length must equal
|
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: |
Secondary axis helpers¶
multipole_axis
¶
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
¶
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. |
font_size |
int
|
Base font size in points. |
background_color |
str
|
Background color string. Use |
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 |
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
TriangleData
dataclass
¶
TriangleData(samples: ndarray, parameter_names: list[str], weights: ndarray | None = None, truths: dict[str, float] = dict())
Bases: PlotData
Labels¶
strip_latex
¶
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
¶
Retrieve a backend by name. Alias for :meth:BackendRegistry.get.
register_backend
module-attribute
¶
Register a backend instance. Alias for :meth:BackendRegistry.register.
Backend selection¶
backend
¶
Temporarily override the active backend within a block.
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
¶
Extract background cosmological evolution.
Returns:
| Type | Description |
|---|---|
BackgroundData
|
class: |
BackgroundData
|
and named quantity arrays (e.g. H(z), distances). |
pk
abstractmethod
¶
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. |
{}
|
Returns:
| Type | Description |
|---|---|
PKData
|
class: |
cl
abstractmethod
¶
primordial
¶
Extract the primordial scalar power spectrum.
Not all solvers expose this output. Override to provide an
implementation; raises :class:NotImplementedError by default.
thermodynamics
¶
Extract thermodynamics evolution (e.g. visibility function).
Not all solvers expose this output. Override to provide an
implementation; raises :class:NotImplementedError by default.
ClassOutput
¶
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
|
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 |
0.0001
|
k_max
|
float
|
Maximum wavenumber (units set by |
1.0
|
n_k
|
int
|
Number of k points (log-spaced). |
200
|
nonlinear
|
bool
|
Use non-linear P(k) (requires |
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 ( |
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 |
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'
|
Returns:
| Type | Description |
|---|---|
dict[str, ClData]
|
Dict mapping spectrum name ( |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If CMB spectra are unavailable. |
ValueError
|
If |
primordial
¶
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 |
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
¶
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
|
None
|
quantities
|
Sequence[str] | None
|
Keys to extract. Must be a subset of
|
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: |
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 |
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: |
PKData
|
axis labels. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the CAMB call fails (e.g. |
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 |
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'
|
Returns:
| Type | Description |
|---|---|
dict[str, ClData]
|
Dict mapping spectrum name to :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If units is not one of the accepted values. |
RuntimeError
|
If the CAMB call fails. |
primordial
¶
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: |