Skip to content

Core API

Spec

PlotSpec dataclass

PlotSpec(traces: Sequence[Trace | BandTrace | PolylineCollectionTrace | MarkerTrace | TextTrace | TriangleTrace | ScatterTriangleTrace], x_label: str = '', y_label: str = '', title: str = '', x_scale: Scale = 'linear', y_scale: Scale = 'linear', style: Style | None = None, figsize: tuple[float, float] | None = None, colorbar: ColorbarSpec | None = None, latex_labels: bool = False, secondary_x_axis: SecondaryAxisSpec | None = None, secondary_y_axis: SecondaryAxisSpec | None = None, x_lim: tuple[float, float] | None = None, y_lim: tuple[float, float] | None = None, equal_aspect: bool = False, scene: Scene3DSpec | None = None, legend: LegendSpec | None = None, grid: bool | None = None, layout_engine: LayoutEngine | None = None, x_ticks: TickSpec | None = None, y_ticks: TickSpec | 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 Sequence[Trace | BandTrace | PolylineCollectionTrace | MarkerTrace | TextTrace | TriangleTrace | ScatterTriangleTrace]

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 Scale

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

y_scale Scale

Scale type for the y-axis.

style Style | None

Visual style of this plot. At render time it is layered over the global and context styles (:func:cplots.config.resolve_style), which start from :data:~cplots.core.theme.DEFAULT; None adds nothing.

figsize tuple[float, float] | None

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

colorbar ColorbarSpec | None

Colour mapping and colourbar. None colours traces from the style palette (or their explicit colours).

x_lim tuple[float, float] | None

Explicit x-axis limits (low, high). None autoscales.

y_lim tuple[float, float] | None

Explicit y-axis limits (low, high). None autoscales.

equal_aspect bool

Force equal data-unit scaling on both axes.

legend LegendSpec | None

Legend settings. None shows a default legend when any trace is labelled.

grid bool | None

Draw a grid. None defers to the style.

layout_engine LayoutEngine | None

How matplotlib arranges the figure. None uses "constrained".

x_ticks / y_ticks

Tick positions, labels and format. None keeps the backend's ticks.

scene Scene3DSpec | None

3D settings. None is a planar panel; see :attr:dim.

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.

secondary_x_axis SecondaryAxisSpec | None

Extra top x-axis; the primary's top ticks are hidden.

secondary_y_axis SecondaryAxisSpec | None

Extra right y-axis; the primary's right ticks are hidden.

Attributes

dim property
dim: Literal[2, 3]

3 when the panel has a :attr:scene, else 2.

Methods:

traces_of
traces_of(kind: type[_T]) -> list[_T]

The traces that are instances of kind, in drawing order.

with_colorbar
with_colorbar(**changes: Any) -> PlotSpec

Copy with :attr:colorbar fields replaced; unchanged if not colour-mapped.

ColorbarSpec dataclass

ColorbarSpec(colormap: str = DEFAULT_COLORMAP, label: str = '', show: bool = True, lim: tuple[float, float] | None = None, loc: Literal['right', 'left', 'top', 'bottom'] = 'right', label_loc: Literal['auto', 'top', 'bottom'] = 'auto', pad: float | None = None, scale: float = 1.175)

Colour mapping of a panel (or a shared figure-wide scale) and its colourbar.

Attributes:

Name Type Description
colormap str

Named colormap. Defaults to :data:~cplots.core.theme.DEFAULT_COLORMAP ("magma").

label str

Colourbar label.

show bool

Draw the bar. The colour mapping applies either way.

lim tuple[float, float] | None

Colour-scale limits (vmin, vmax). None uses the data range.

loc Literal['right', 'left', 'top', 'bottom']

Bar side, matplotlib location values.

label_loc Literal['auto', 'top', 'bottom']

Where label sits: "auto" (the backend's normal placement), "top" (unrotated title above the bar) or "bottom" (unrotated label below it).

pad float | None

Gap between plot and bar, in backend units: a fraction of the parent axes for matplotlib/ultraplot (default 0.02), pixels for plotly (default 5); ignored by altair.

scale float

Plotly only: multiplier on the computed bar length.

Scene3DSpec dataclass

Scene3DSpec(z_label: str = '', z_lim: tuple[float, float] | None = None, camera: CameraSpec = CameraSpec())

Extra settings of a 3D scene. Its presence on a :class:PlotSpec makes it 3D.

Attributes:

Name Type Description
z_label str

Label of the z-axis.

z_lim tuple[float, float] | None

Explicit z-axis limits. None autoscales.

camera CameraSpec

Viewpoint.

CameraSpec dataclass

CameraSpec(elev: float = 30.0, azim: float = -60.0, zoom: float = 1.0)

Viewpoint of a 3D scene, in matplotlib's view_init convention.

Attributes:

Name Type Description
elev float

Elevation above the xy-plane, in degrees.

azim float

Azimuth measured from the x-axis towards the y-axis, in degrees.

zoom float

Magnification; values above 1 move the camera closer.

Traces

Trace dataclass

Trace(x: NDArray[Any], y: NDArray[Any], label: str = '', color_value: float | None = None, color: str | None = None, alpha: float | None = None, linewidth: float | None = None, linestyle: TraceLineStyle | None = None, marker: MarkerSymbol | None = None, yerr: NDArray[Any] | None = None, color_index: int | None = None, style: dict[str, Any] = dict())

A single data series within a PlotSpec.

Colour priority in every backend: the colormap colour when the panel is colour-mapped (PlotSpec.colorbar set) and color_value is given, else color, else the style palette.

Attributes:

Name Type Description
x NDArray[Any]

Array of x-axis values.

y NDArray[Any]

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).

color str | None

Explicit colour. None delegates to the colormap or palette.

alpha float | None

Opacity in [0, 1]. None is opaque.

linewidth float | None

Line width in points. None uses the backend default.

linestyle TraceLineStyle | None

"solid", "dashed", "dotted" or "none" (markers only). None is solid.

marker MarkerSymbol | None

Marker drawn at every point. None draws no markers.

yerr NDArray[Any] | None

Symmetric errors of shape (N,) or (2, N) [lower, upper].

color_index int | None

Palette slot to colour this trace with, instead of its position in PlotSpec.traces (keeps derived plots, e.g. residuals, in the colours of the plot they came from).

style dict[str, Any]

Extra matplotlib keyword arguments for the draw call (e.g. {"zorder": 3}). Matplotlib-family backends pass them through; other backends ignore them.

BandTrace dataclass

BandTrace(x: NDArray[Any], y_lower: NDArray[Any], y_upper: NDArray[Any], y_center: NDArray[Any] | None = None, label: str = '', alpha: float = 0.3, color: str | None = None, color_index: int | None = None, style: dict[str, Any] = dict())

A shaded confidence band rendered as a filled region between y_lower and y_upper.

Backends render this as a filled area. y_center, when set, is drawn as a solid line through the band (typically the median). Backends that cannot render fills fall back to drawing y_center only.

Attributes:

Name Type Description
x NDArray[Any]

Shared x-axis values.

y_lower NDArray[Any]

Lower boundary of the band.

y_upper NDArray[Any]

Upper boundary of the band.

y_center NDArray[Any] | None

Central value line (e.g. median). None means no center line.

label str

Legend label. Empty string means no legend entry.

alpha float

Fill opacity in [0, 1].

color str | None

Explicit color string. None delegates to the style palette.

color_index int | None

Palette slot to colour this band with when color is None, instead of its position (lets several bands share one colour).

style dict[str, Any]

Backend-specific passthrough kwargs for the fill call.

PolylineCollectionTrace dataclass

PolylineCollectionTrace(curves: list[NDArray[Any]], values: list[NDArray[Any]] | None = None, arrows: bool = False, arrow_size: float = 1.0, label: str = '', color: str | None = None, linewidth: float = 1.2, linestyle: LineStyle = 'solid', alpha: float = 1.0, style: dict[str, Any] = dict())

A collection of open polylines, optionally coloured by a per-vertex scalar.

Used for streamlines, trajectories and any other family of curves that share one colour scale. Curves may have different lengths.

Attributes:

Name Type Description
curves list[NDArray[Any]]

One (N_i, d) array of vertices per curve, with d = 2 or 3.

values list[NDArray[Any]] | None

Per-vertex scalar for each curve (same lengths as curves), mapped through PlotSpec.colorbar. None draws every curve in a single flat colour.

arrows bool

Draw one direction arrowhead per curve, placed so heads never pile up.

arrow_size float

Multiplier on the default arrowhead size (1.0).

label str

Legend label. Empty string means no legend entry.

color str | None

Flat colour used when values is None. None delegates to the style palette.

linewidth float

Line width in points.

linestyle LineStyle

"solid", "dashed" or "dotted".

alpha float

Opacity in [0, 1].

style dict[str, Any]

Backend-specific passthrough kwargs (reserved).

MarkerTrace dataclass

MarkerTrace(points: NDArray[Any], label: str = '', color: str | None = None, symbol: MarkerSymbol = 'circle', size: float = 6.0, filled: bool = True, texts: list[str] | None = None, style: dict[str, Any] = dict())

Isolated point markers (e.g. fixed points, seeds, endpoints).

Attributes:

Name Type Description
points NDArray[Any]

Marker positions, shape (M, d) with d = 2 or 3.

label str

Legend label. Empty string means no legend entry.

color str | None

Marker colour. None delegates to the style palette.

symbol MarkerSymbol

One of :data:MarkerSymbol; each backend maps it to its own marker vocabulary.

size float

Marker size in points.

filled bool

False draws hollow markers.

texts list[str] | None

Optional per-point hover/annotation text, length M.

style dict[str, Any]

Backend-specific passthrough kwargs (reserved).

TriangleTrace dataclass

TriangleTrace(chains: list[TriangleData], parameter_names: list[str], labels: list[str] | None = None, truths: dict[str, float] = dict(), engine: str = 'getdist', label: str = '')

Corner (triangle) plot of one or more MCMC chains.

A plot whose only trace is a TriangleTrace is drawn by a triangle engine (getdist, chainconsumer, anesthetic) that manages its own figure, so it cannot be a panel of a multi-panel figure. Only the matplotlib backend supports it.

Attributes:

Name Type Description
chains list[TriangleData]

The chains, aligned to parameter_names.

parameter_names list[str]

Parameters to plot.

labels list[str] | None

Axis labels per parameter. None uses the names.

truths dict[str, float]

Reference values to mark, by parameter name.

engine str

Registered triangle engine name.

label str

Unused; present for a uniform trace interface.

TextTrace dataclass

TextTrace(x: float, y: float, text: str, ha: TextAlign = 'left', va: TextBaseline = 'bottom', offset: tuple[float, float] = (0.0, 0.0), color: str | None = None, fontsize: float | None = None, label: str = '', style: dict[str, Any] = dict())

Text placed at a data point of a 2D panel. Never in the legend.

Attributes:

Name Type Description
x float

Anchor x, in data coordinates.

y float

Anchor y, in data coordinates.

text str

The text; may contain LaTeX, formatted as the panel's labels are.

ha TextAlign

Horizontal anchor: "left" puts the text's left edge at the point.

va TextBaseline

Vertical anchor: "bottom" puts the text's baseline at the point.

offset tuple[float, float]

Shift (right, up) in points from the anchor. Backends without point offsets (plotly) approximate it with their own padding.

color str | None

Text colour. None uses the style's text colour.

fontsize float | None

Font size in points. None uses the backend default.

label str

Always empty: present so every trace type has one.

style dict[str, Any]

Extra matplotlib keyword arguments for Axes.annotate.

split_mpl_style

split_mpl_style(style: Mapping[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]

Map known matplotlib keyword arguments onto typed :class:Trace fields.

Returns (typed, passthrough): typed can be splatted into Trace(...); everything else, including values with no backend-neutral equivalent (e.g. ls="-." or marker="^"), stays in passthrough for Trace.style.

Layout

SecondaryAxisSpec dataclass

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

Secondary axis (a top x-axis or a right y-axis), backend-agnostic.

Used as :attr:PlotSpec.secondary_x_axis or :attr:PlotSpec.secondary_y_axis. The primary axes' mirrored ticks on that side are hidden so the two don't overlap.

Attributes:

Name Type Description
forward Callable[[NDArray[Any]], NDArray[Any]]

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

inverse Callable[[NDArray[Any]], NDArray[Any]]

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, style: Style | None = None, sharex: bool = False, sharey: bool = False, latex_labels: bool = False, colorbar: ColorbarSpec | None = None, hspace: float | None = None, wspace: float | None = None, layout_engine: LayoutEngine | 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.

style Style | None

Visual style of the figure; each panel's own style is layered on top.

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.

colorbar ColorbarSpec | None

One colour scale shared by every panel (colour-coded line panels), drawn as a single bar. None lets each panel use its own.

hspace / wspace

Spacing between rows / columns (backend units).

layout_engine LayoutEngine | None

How matplotlib arranges the figure. None uses "constrained", or fixed spacing ("none") when hspace or wspace is set.

Secondary axis helpers

multipole_axis

multipole_axis(chi: float, label: str = '$\\ell$') -> 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.

'$\\ell$'
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()

Styles

Style dataclass

Style(font_family: str | None = None, font_size: float | None = None, label_size: float | None = None, title_size: float | None = None, tick_size: float | None = None, background: str | None = None, foreground: str | None = None, palette: tuple[str, ...] | None = None, linewidth: float | None = None, grid: bool | None = None, legend_frame: bool | None = None, backend_options: Mapping[str, Mapping[str, Any]] = dict())

Immutable, partial visual style applied by every backend.

Attributes:

Name Type Description
font_family str | None

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

font_size float | None

Base font size in points.

label_size float | None

Axis-label font size in points (defaults to font_size).

title_size float | None

Title font size in points.

tick_size float | None

Tick-label font size in points.

background str | None

Figure and axes background colour. "none" is transparent (blends with dark slides/notebooks).

foreground str | None

Colour of axes, ticks, labels and text.

palette tuple[str, ...] | None

Hex colours cycled across traces.

linewidth float | None

Default line width in points.

grid bool | None

Draw a background grid.

legend_frame bool | None

Draw a frame around legends.

backend_options Mapping[str, Mapping[str, Any]]

Backend-specific settings keyed by backend name, e.g. {"matplotlib": {"axes.spines.top": False}, "plotly": {"hovermode": "x"}}. matplotlib/ultraplot entries are rcParams; plotly entries are layout properties; altair entries are top-level Vega-Lite config.

Attributes

is_empty property
is_empty: bool

True if no field is set (backends then leave their defaults alone).

Methods:

merge
merge(other: Style | None) -> Style

Copy of this style with the set fields of other laid on top.

backend_options are merged per backend, so layers can each add keys.

options
options(backend: str) -> Mapping[str, Any]

The backend_options entry for backend (empty if none).

DEFAULT module-attribute

DEFAULT = Style(font_family='serif', font_size=10, background='white', foreground='black', palette=DEFAULT_PALETTE, linewidth=1.5, grid=False, legend_frame=False, backend_options={'matplotlib': {'font.serif': ['CMU Serif', 'Computer Modern Roman', 'Latin Modern Roman', 'DejaVu Serif'], 'mathtext.fontset': 'cm', 'axes.formatter.use_mathtext': True, 'xtick.direction': 'in', 'ytick.direction': 'in', 'xtick.top': True, 'ytick.right': True, 'xtick.minor.visible': True, 'ytick.minor.visible': True}})

Default style of every plot: Computer Modern text and math, FiveThirtyEight palette, boxed axes with inward major and minor ticks on all four sides.

It is the base of the global style; :func:cplots.set_style layers on top of it.

DEFAULT_PALETTE module-attribute

DEFAULT_PALETTE: tuple[str, ...] = ('#008fd5', '#fc4f30', '#e5ae38', '#6d904f', '#8b8b8b', '#810f7c')

Default trace colours (matplotlib's fivethirtyeight cycle). Also used where cplots needs explicit colours and no style sets a palette.

DEFAULT_COLORMAP module-attribute

DEFAULT_COLORMAP: str = 'magma'

Colormap of colour-mapped plots (XYZColored, PhasePortrait, colourbars) when none is given.

PUBLICATION module-attribute

PUBLICATION = Style(font_family='serif', font_size=11, background='white', palette=DEFAULT_PALETTE)

Publication-quality style: serif font, white background, default palette.

DARK module-attribute

DARK = Style(font_family='sans-serif', font_size=12, background='none', foreground='white', palette=('#4cc9f0', '#f72585', '#7209b7', '#E81FCA', '#00ca7d'), backend_options={'matplotlib': {'legend.facecolor': 'none'}})

Dark style: transparent background, white axes and text, high-contrast neon palette.

style

style(style: Style | None = None, /, **fields: Any) -> Generator[None, None, None]

Layer a style over the active one within a block.

Takes a :class:~cplots.Style, individual style fields, or both (fields win). Nested blocks merge, so an inner style(font_size=9) keeps the outer palette::

with cplots.style(cplots.DARK):
    with cplots.style(font_size=9):
        plot.show()

set_style

set_style(style: Style | None = None, /, *, base: Style | None = DEFAULT, **fields: Any) -> None

Set the process-wide style, layered on base.

By default the style sits on top of :data:cplots.DEFAULT, so unset fields keep the cplots look, and set_style(None) resets to DEFAULT. Pass base=None to start from the backends' own defaults instead::

cplots.set_style(font_size=9)                # DEFAULT with smaller text
cplots.set_style(base=None)                  # plain matplotlib/plotly look

resolve_style

resolve_style(*layers: Style | None) -> Style

The effective style: global, then context, then layers in order (later wins).

PaperFormat

Bases: NamedTuple

Figure size (inches) and base font size (points) of a journal format.

PAPER_FORMATS module-attribute

PAPER_FORMATS: dict[str, PaperFormat] = {'PRD': PaperFormat((3.375, 2.5), 10), 'PRD-2col': PaperFormat((6.95, 5.0), 10), 'MNRAS': PaperFormat((3.3, 2.5), 10), 'A4': PaperFormat((6.3, 4.7), 10)}

Journal format name to :class:PaperFormat. Apply one with plot.paper(name).

LegendSpec dataclass

LegendSpec(show: bool = True, loc: LegendLoc = 'best', ncol: int = 1, frame: bool | None = None, outside: bool = False, title: str = '')

Legend of a panel.

Attributes:

Name Type Description
show bool

Draw the legend. False hides it even when traces are labelled.

loc LegendLoc

Position inside the axes (or the side outside it with outside).

ncol int

Number of columns.

frame bool | None

Draw a frame. None uses the style/backend default.

outside bool

Place the legend outside the axes, on the right.

title str

Legend title.

TickSpec dataclass

TickSpec(values: tuple[float, ...] | None = None, labels: tuple[str, ...] | None = None, count: int | None = None, minor: bool | None = None, format: str | None = None)

Ticks of one axis; None fields keep the backend's choice.

Attributes:

Name Type Description
values tuple[float, ...] | None

Tick positions, in data units.

labels tuple[str, ...] | None

Text at each of values (same length).

count int | None

Approximate number of ticks, when values is not given.

minor bool | None

Draw (True) or hide (False) minor ticks.

format str | None

Tick-label format spec understood by both Python's format() and d3-format, e.g. ".2f", ".1e" or ".0%".

Layout composition

Row

Row(*children: _Formattable, widths: Sequence[float] | None = None)

Bases: _Node

Plots and figures side by side; a | b | c builds one.

Parameters:

Name Type Description Default
*children _Formattable

Plots or figures, left to right.

()
widths Sequence[float] | None

Relative width of each child (default: equal).

None

Col

Col(*children: _Formattable, heights: Sequence[float] | None = None)

Bases: _Node

Plots and figures stacked top to bottom; a / b / c builds one.

Parameters:

Name Type Description Default
*children _Formattable

Plots or figures, top to bottom.

()
heights Sequence[float] | None

Relative height of each child (default: equal).

None

Backend capabilities

UnsupportedFeatureWarning

Bases: UserWarning

A backend cannot render a requested presentation feature and ignores it.

FEATURES module-attribute

FEATURES: dict[str, str] = {'limits': 'explicit axis limits', 'equal_aspect': 'equal aspect ratio', 'secondary_x_axis': 'a secondary x-axis', 'secondary_y_axis': 'a secondary y-axis', 'scale.symlog': 'symlog axis scale', 'legend': 'legend settings', 'legend.outside': 'a legend outside the axes', 'grid': 'grid settings', 'ticks': 'tick settings', 'ticks.minor': 'minor tick settings', 'style.fonts': 'style fonts', 'style.foreground': 'a style foreground colour', 'style.linewidth': 'a style line width', 'style.legend_frame': 'a style legend frame', 'rowspan': 'panels spanning rows', 'colspan': 'panels spanning columns', 'ratios': 'unequal column widths / row heights', 'sharing': 'shared axes', 'spacing': 'panel spacing (hspace/wspace)'}

requested_features

requested_features(spec: PlotSpec | FigureSpec) -> set[str]

The presentation features spec uses (names from :data:FEATURES).

Data containers

PlotData dataclass

PlotData()

Marker base for all typed plot data containers.

XYData dataclass

XYData(x: NDArray[Any], y: NDArray[Any], x_label: str = '', y_label: str = '', uncertainties: NDArray[Any] | None = None)

Bases: PlotData

PKData dataclass

PKData(x: NDArray[Any], y: NDArray[Any], x_label: str = '', y_label: str = '', uncertainties: NDArray[Any] | None = None, redshift: float = 0.0)

Bases: XYData

ClData dataclass

ClData(x: NDArray[Any], y: NDArray[Any], x_label: str = '', y_label: str = '', uncertainties: NDArray[Any] | None = None)

Bases: XYData

BackgroundData dataclass

BackgroundData(redshift: NDArray[Any], quantities: dict[str, NDArray[Any]], labels: dict[str, str] = dict(), units: dict[str, str] = dict(), source: str = '', x_label: str = '$z$')

Bases: PlotData

TriangleData dataclass

TriangleData(samples: NDArray[Any], parameter_names: list[str], weights: NDArray[Any] | None = None, truths: dict[str, float] = dict(), labels: list[str] | None = None, label: str = '', color: str | None = None, ranges: dict[str, tuple[float | None, float | None]] = dict())

Bases: PlotData

PosteriorBandsData dataclass

PosteriorBandsData(z: NDArray[Any], samples: NDArray[Any], weights: NDArray[Any] | None = None, x_obs: NDArray[Any] | None = None, y_obs: NDArray[Any] | None = None, y_err: NDArray[Any] | None = None, x_label: str = '$z$', y_label: str = '')

Bases: PlotData

Predictive posterior samples of an observable y evaluated on a grid z.

Attributes:

Name Type Description
z NDArray[Any]

Redshift (or other x-axis) grid, shape (N_z,).

samples NDArray[Any]

Observable values for each MCMC sample, shape (N_samples, N_z).

weights NDArray[Any] | None

Importance weights for each sample, shape (N_samples,). None means uniform weights (standard MCMC chains).

x_obs NDArray[Any] | None

Observed data x-values, shape (N_obs,).

y_obs NDArray[Any] | None

Observed data y-values, shape (N_obs,).

y_err NDArray[Any] | None

Observed data uncertainties. Shape (N_obs,) for symmetric or (2, N_obs) for asymmetric [lower, upper] error bars.

x_label str

X-axis label.

y_label str

Y-axis label.

XYZData dataclass

XYZData()

Bases: PlotData

Marker type for XYZColored plots.

VectorFieldData dataclass

VectorFieldData(axes: tuple[NDArray[Any], ...], components: tuple[NDArray[Any], ...], labels: tuple[str, ...] = ())

Bases: PlotData

A vector field sampled on a regular grid.

Attributes:

Name Type Description
axes tuple[NDArray[Any], ...]

Strictly increasing 1-D coordinate arrays, one per dimension.

components tuple[NDArray[Any], ...]

One array per dimension with shape tuple(len(a) for a in axes) in indexing="ij" order.

labels tuple[str, ...]

Axis labels, one per dimension.

TrajectoryData dataclass

TrajectoryData(curves: tuple[NDArray[Any], ...], values: tuple[NDArray[Any], ...] | None = None, value_label: str = '', labels: tuple[str, ...] = ())

Bases: PlotData

Precomputed curves in phase space.

Attributes:

Name Type Description
curves tuple[NDArray[Any], ...]

One (N_i, d) array of vertices per curve.

values tuple[NDArray[Any], ...] | None

Optional per-vertex scalar for each curve, used for colouring.

value_label str

Name of the scalar (colourbar label).

labels tuple[str, ...]

Axis labels, one per dimension.

Dynamics

trace_streamlines

trace_streamlines(f: VectorField, bounds: Bounds, seeds: SeedStrategy | ArrayLike, *, direction: Literal['forward', 'backward', 'both'] = 'both', arclength: float | None = None, resolution: int = 200, method: str = 'auto', speed_eps: float = 1e-08, blowup: float = 100000000.0, rtol: float = 1e-06, atol: float = 1e-09, min_points: int = 2) -> list[Streamline]

Integrate streamlines of the autonomous system dx/dt = f(x).

Parameters:

Name Type Description Default
f VectorField

Vector field f(x) -> array_like mapping a point of shape (d,) to a vector of shape (d,). Close over any parameters yourself.

required
bounds Bounds

Box [(lo, hi), ...] that clips the curves; its length is d.

required
seeds SeedStrategy | ArrayLike

A seed strategy from :mod:cplots.dynamics.seeds or an explicit (N, d) array of starting points.

required
direction Literal['forward', 'backward', 'both']

Integrate with the flow, against it, or both.

'both'
arclength float | None

Maximum arclength per direction. Default: half the box diagonal, which keeps spirals and closed orbits from winding densely.

None
resolution int

Vertices per box diagonal, setting the output step.

200
method str

"auto" (RK45 with SciPy, else RK4), "RK4" (built-in, fixed step) or any SciPy solve_ivp method ("RK45", "DOP853", "Radau", "LSODA" ...) for stiff systems.

'auto'
speed_eps float

|f| below this counts as a stagnation point.

1e-08
blowup float

Stop when any coordinate exceeds this magnitude.

100000000.0
rtol float

SciPy solver relative tolerance.

1e-06
atol float

SciPy solver absolute tolerance.

1e-09
min_points int

Curves with fewer vertices (e.g. seeds on a fixed point or outside the box) are dropped.

2

Returns:

Name Type Description
One list[Streamline]

class:Streamline per surviving seed, in seed order.

Raises:

Type Description
ImportError

If a SciPy method is requested but SciPy is not installed.

Warns:

Type Description
RuntimeWarning

If f raised an arithmetic or value error somewhere; those curves end with status "failed". Other exceptions propagate.

Streamline dataclass

Streamline(points: NDArray[float64], arclength: NDArray[float64], speed: NDArray[float64], seed: NDArray[float64], end_status: tuple[Status | None, Status | None])

One integrated curve through a seed point.

Attributes:

Name Type Description
points NDArray[float64]

Vertices ordered along the flow, shape (N, d).

arclength NDArray[float64]

Signed arclength of each vertex from the seed, shape (N,).

speed NDArray[float64]

|f(x)| at each vertex, shape (N,).

seed NDArray[float64]

Starting point, shape (d,).

end_status tuple[Status | None, Status | None]

Why integration stopped as (backward, forward); None for a direction that was not integrated. Values are "length" (budget reached), "bounds" (left the box), "stagnant" (reached a near-zero-speed point), "blowup", "failed" (solver or vector field error) or "spaced" (cut short by :func:~cplots.dynamics.even_streamlines to keep curves apart).

GridField

GridField(axes: Sequence[ArrayLike], components: Sequence[ArrayLike])

Callable f(x) -> vector interpolating components sampled on a regular grid.

Parameters:

Name Type Description Default
axes Sequence[ArrayLike]

Strictly increasing 1-D coordinate arrays, one per dimension.

required
components Sequence[ArrayLike]

One array per dimension, each of shape tuple(len(a) for a in axes) using indexing="ij" order. Points outside the grid return NaN.

required

Methods:

__call__
__call__(x: NDArray[float64]) -> npt.NDArray[np.float64]

Interpolate at one point of shape (d,) or many of shape (d, N).

even_streamlines

even_streamlines(f: VectorField, bounds: Bounds, *, separation: float = 0.03, test_ratio: float = 0.5, start: ArrayLike | None = None, direction: Literal['forward', 'backward', 'both'] = 'both', arclength: float | None = None, resolution: int = 200, method: str = 'RK4', max_curves: int = 2000) -> list[Streamline]

Streamlines of a 2D system spread evenly over a box.

Parameters:

Name Type Description Default
f VectorField

Vector field f(x) -> (2,).

required
bounds Bounds

[(x_lo, x_hi), (y_lo, y_hi)].

required
separation float

Target distance between neighbouring curves, as a fraction of the box diagonal. Smaller values give more curves.

0.03
test_ratio float

A curve stops when closer than test_ratio * separation to another; 0.5 is the standard choice, larger values leave bigger gaps.

0.5
start ArrayLike | None

First seed point(s), shape (2,) or (N, 2). Default: the box centre (jittered if that is an equilibrium).

None
direction Literal['forward', 'backward', 'both']

Passed to :func:~cplots.dynamics.trace_streamlines. With a single direction the curves start at their seeds, so coverage is one-sided.

'both'
arclength float | None

Integration budget per direction before spacing cuts the curve (default: twice the box diagonal).

None
resolution int

Minimum vertices per box diagonal; raised automatically so that vertices are at most separation * test_ratio / 2 apart.

200
method str

Integrator, see :func:~cplots.dynamics.trace_streamlines. The default fixed-step "RK4" is fast and accurate enough for display. SciPy's adaptive methods are far slower here (tens of times) because each curve is integrated to its full budget before spacing cuts it.

'RK4'
max_curves int

Safety cap on the number of curves.

2000

Returns:

Type Description
list[Streamline]

Streamlines whose cut ends have status "spaced".

Raises:

Type Description
ValueError

For non-2D bounds or out-of-range separation / test_ratio.

nullclines

Nullclines of a planar system: the curves where one component of f vanishes.

x' = f_x(x, y) is zero on the first nullcline (trajectories cross it vertically) and y' = f_y(x, y) on the second (they cross it horizontally); equilibria sit where the two meet. The zero-level curves are extracted with a numpy marching-squares pass and chained into polylines.

Classes

Nullcline dataclass
Nullcline(component: int, curves: list[NDArray[float64]])

Zero-level set of one component of the vector field.

Attributes:

Name Type Description
component int

Index of the component that vanishes (0 for x' = 0, 1 for y' = 0).

curves list[NDArray[float64]]

Polylines of shape (N, 2); closed curves repeat their first point.

Functions:

nullclines
nullclines(f: VectorField, bounds: Bounds, *, resolution: int = 200) -> list[Nullcline]

Compute both nullclines of a 2D system inside a box.

Parameters:

Name Type Description Default
f VectorField

Vector field f(x) -> (2,). A vectorised call with x of shape (2, N) is tried first for speed, with a point-by-point fallback.

required
bounds Bounds

[(x_lo, x_hi), (y_lo, y_hi)].

required
resolution int

Grid points per axis.

200

Returns:

Type Description
list[Nullcline]

[Nullcline(0, ...), Nullcline(1, ...)]. Curves only appear where the

list[Nullcline]

component changes sign: a tangential zero such as f = x**2 is missed, and cells

list[Nullcline]

touching non-finite values are skipped.

Nullcline dataclass

Nullcline(component: int, curves: list[NDArray[float64]])

Zero-level set of one component of the vector field.

Attributes:

Name Type Description
component int

Index of the component that vanishes (0 for x' = 0, 1 for y' = 0).

curves list[NDArray[float64]]

Polylines of shape (N, 2); closed curves repeat their first point.

find_fixed_points

find_fixed_points(f: VectorField, bounds: Bounds, *, starts: SeedStrategy | ArrayLike | None = None, jac: Jacobian | None = None, tol: float = 1e-09, merge_tol: float = 0.001, max_iter: int = 100, classify_tol: float = 0.001) -> list[FixedPoint]

Find the equilibria of dx/dt = f(x) inside a box and classify them.

Damped Newton iterations are started from many points; converged roots inside bounds are merged and sorted. Equilibria that no start converges to are missed, so use a finer starts grid for systems with many of them.

Parameters:

Name Type Description Default
f VectorField

Vector field f(x) -> (d,).

required
bounds Bounds

Search box [(lo, hi), ...] (2 or 3 intervals typically).

required
starts SeedStrategy | ArrayLike | None

Starting points, a seed strategy or an (N, d) array. Default: a 7 x 7 grid in 2D, 5 x 5 x 5 in 3D, covering the whole box.

None
jac Jacobian | None

Analytic Jacobian J(x) -> (d, d); finite differences if omitted.

None
tol float

Convergence threshold on |f(x)|.

1e-09
merge_tol float

Roots closer than this fraction of the box diagonal are one point. Loose on purpose: degenerate roots are approached only linearly, so different starts stop at slightly different distances from them.

0.001
max_iter int

Newton iteration limit per start.

100
classify_tol float

Relative threshold on the real parts for the classification.

0.001

Returns:

Type Description
list[FixedPoint]

class:FixedPoint objects ordered by position (lexicographically).

FixedPoint dataclass

FixedPoint(point: NDArray[float64], eigenvalues: NDArray[complex128], kind: str)

An equilibrium f(x) = 0 together with its linear stability.

Attributes:

Name Type Description
point NDArray[float64]

Location, shape (d,).

eigenvalues NDArray[complex128]

Eigenvalues of the Jacobian there, shape (d,).

kind str

One of :data:KINDS.

Attributes

stable property
stable: bool

True for linearly stable points (all eigenvalues with negative real part).

Methods:

describe
describe() -> str

Short text with the kind and eigenvalues, e.g. for hover labels.

classify

classify(eigenvalues: ArrayLike, *, tol: float = 0.001) -> str

Classify an equilibrium by the eigenvalues of its Jacobian.

tol is relative to the largest eigenvalue magnitude (at least 1): real parts within it of zero count as zero. It is deliberately loose, because Newton converges only linearly to degenerate roots and leaves a small residual eigenvalue. Returns one of :data:KINDS.

seeds

Seed-point strategies for streamline integration.

A seed strategy is any callable (bounds) -> (N, d) array. The factories below return such callables, so they compose with PhasePortrait(seeds=...) and user code can pass a plain function or an explicit (N, d) array.

Functions:

grid
grid(*n: int, shrink: float = 0.9) -> SeedStrategy

Regular grid of n[0] x n[1] [x n[2]] seeds inside the box.

Parameters:

Name Type Description Default
*n int

Number of points along each axis (one per dimension of the box).

()
shrink float

Fraction of each extent that the grid covers, in (0, 1].

0.9
random
random(n: int, *, seed: int | None = None, shrink: float = 0.9) -> SeedStrategy

n uniformly random seeds inside the box (reproducible via seed).

line
line(p0: Sequence[float], p1: Sequence[float], n: int) -> SeedStrategy

n seeds evenly spaced on the segment from p0 to p1.

sphere
sphere(center: Sequence[float], radius: float, n: int) -> SeedStrategy

n near-uniform seeds on a sphere (Fibonacci lattice); 3D boxes only.

box_shell
box_shell(n: int = 3, *, shrink: float = 0.9) -> SeedStrategy

Seeds on the six faces of the (shrunken) box, an n x n grid per face; 3D only.

as_seed_array
as_seed_array(seeds: SeedStrategy | ArrayLike, bounds: Bounds) -> npt.NDArray[np.float64]

Resolve a strategy or explicit array into a validated (N, d) array.

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

as_observables

as_observables(obj: Any) -> Observables

Wrap a computed solver result in its :class:Observables adapter.

Recognises classy.Class, camb.CAMBdata and eft4py's BackgroundGrid / BackgroundSolution; an Observables is returned unchanged. Register adapters for other codes with @cplots.as_observables.register(ResultType).

Raises:

Type Description
TypeError

If no adapter is registered for type(obj).

Observables

Bases: ABC

Base for cosmological solver adapters (CLASS, CAMB, custom codes).

Every output method is optional and raises :class:NotImplementedError unless the subclass provides it, so a background-only code is a valid adapter. :meth:supports reports which outputs a subclass implements.

Background. :meth:background is a template: it resolves quantity names, converts units and builds labels. A subclass only says where the numbers come from, by overriding one hook:

  • :meth:_background_table for codes that precompute a table on their own redshift grid (CLASS);
  • :meth:_evaluate_background (plus :meth:available_background) for codes that evaluate on any redshift grid (CAMB).

Overriding :meth:background itself remains supported.

Example::

import numpy as np
import cplots
from cplots import Observables
from cplots.core.observables import BackgroundTable

class MyCode(Observables):
    source = "MyCode"

    def __init__(self, result):
        self._result = result

    def _background_table(self) -> BackgroundTable:
        return BackgroundTable(
            z=self._result.z,
            columns={"H": (self._result.H, "1/Mpc")},
        )

out = MyCode(result)
cplots.BackgroundEvolution(out.background(quantities=["H"])).show()

Methods:

supports classmethod
supports(output: str) -> bool

Whether this adapter implements output ("background", "pk", …).

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

Extract background cosmological evolution.

Parameters:

Name Type Description Default
quantities Sequence[str] | None

Quantity names to extract. Defaults to :attr:default_background_quantities.

None
labels Mapping[str, str] | None

Display labels keyed by quantity name, overriding the auto-generated unit-aware ones.

None
units Mapping[str, str] | None

Requested output units keyed by quantity name, e.g. {"H": "km/s/Mpc"}. Defaults to each code's native unit.

None
z ArrayLike | None

Redshift grid. Evaluator codes evaluate on it (each has its own default); table codes interpolate their table onto it (default: the native table).

None

Returns:

Type Description
BackgroundData

class:~cplots.core.data.BackgroundData.

Raises:

Type Description
KeyError

If a requested quantity is not available.

ValueError

If an unsupported unit conversion is requested, or z leaves the range of a table code's table.

NotImplementedError

If the adapter provides no background.

available_background
available_background() -> tuple[str, ...]

Names :meth:background accepts.

Table codes get this from their table; evaluator codes must override it.

pk
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).

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

Extract CMB angular power spectra, keyed by spectrum name ("tt", …).

Parameters:

Name Type Description Default
**kwargs Any

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

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

Extract the primordial scalar power spectrum.

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

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

BackgroundTable dataclass

BackgroundTable(z: NDArray[Any], columns: Mapping[str, Column])

A solver's precomputed background table.

Attributes:

Name Type Description
z NDArray[Any]

Redshift grid shared by every column.

columns Mapping[str, Column]

Quantity name → (values, native_unit).

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:

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:

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).

Eft4pyOutput

Eft4pyOutput(result: Any)

Bases: Observables

Adapter for an eft4py background solve.

Wraps an eft4py BackgroundGrid (from ScipyBackground.solve or JaxBackground.solve) or a BackgroundSolution. eft4py exports its grid in hi_class format (BackgroundGrid.to_hiclass()), so quantity names, units and conventions match :class:~cplots.ClassOutput on hi_class output, which makes eft4py-vs-hi_class overlays direct. eft4py is never imported by cplots.

Background only: pk and cl are not provided. Points where the solve failed (ok=False, e.g. a failed JAX solve) are masked to NaN with a warning. Passing z= to :meth:background resamples; with a BackgroundSolution its exact Hermite evaluators are used where available.

Example::

import cplots
from eft4py import ScipyBackground, frozen_field

bg = ScipyBackground(model, [V], ic=frozen_field(10.0))
theta = bg.shoot([guess], cosmo, index=0)
grid = bg.solve(theta, cosmo, ln_a_grid)

out = cplots.as_observables(grid)          # -> Eft4pyOutput
cplots.BackgroundEvolution(out.background(quantities=["w_de", "alpha_M"])).show()

class_background_table

class_background_table(bg: Mapping[str, Any], extra_units: Mapping[str, str] | None = None) -> BackgroundTable

Build a :class:BackgroundTable from a CLASS-format background dict.

Every raw key is a column (unit from extra_units, else none). Canonical quantities are added on top when their source columns exist: H, the distances, tau, a, rho_m/rho_r (summed over species), rho_de/p_de, w_de, Omega_de, M_star_sq, the alphas and cT2.

Quantities

Quantity dataclass

Quantity(name: str, label: str, dimension: str)

A canonical observable.

Attributes:

Name Type Description
name str

Canonical key, e.g. "H".

label str

Display text without the unit, e.g. r"$d_L$".

dimension str

Physical dimension; selects the unit-conversion table.

register_quantity

register_quantity(quantity: Quantity) -> None

Register (or replace) a canonical quantity.

get_quantity

get_quantity(name: str) -> Quantity | None

Return the registered quantity for name, or None if unknown.

convert_units

convert_units(name: str, values: NDArray[Any], from_unit: str, to_unit: str) -> npt.NDArray[Any]

Convert values of quantity name between units.

Raises:

Type Description
ValueError

If no conversion is registered for the quantity's dimension.

quantity_label

quantity_label(name: str, unit: str) -> str

Display label for name in unit, e.g. "H [km/s/Mpc]".