Skip to content

utils

Modules:

Name Description
dependency_functions

Functions for use in EasyScience dependency expressions.

detailed_balance
fit_target
plotting
posterior_plotting

Diagnostic plots for Bayesian posterior samples.

utils

Functions:

Name Description
detailed_balance_factor

Compute the detailed balance factor (DBF): $$ DBF(E, T) = E(n(E)+1)=\frac{E}{(1 - e^{-E /

slicerplot_with_residuals

Create a SlicerPlot with an additional subplot for residuals.

plot_corner

Plot marginal and pairwise posterior distributions.

plot_posterior_predictive

Plot the data against the credible band implied by the posterior.

plot_trace

Plot the chain trace of every sampled parameter.

Functions:

detailed_balance_factor(energy, temperature, energy_unit='meV', temperature_unit='K', divide_by_temperature=True)

Compute the detailed balance factor (DBF): $$ DBF(E, T) = E(n(E)+1)=\frac{E}{(1 - e^{-E / (k_B*T)})}}, $$ where \(n(E)\) is the Bose-Einstein distribution, \(E\) is the energy transfer, and \(T\) is the temperature. \(k_B\) is the Boltzmann constant. If divide_by_temperature is True, the result is normalized by \(k_B*T\) to have value 1 at \(E=0\).

Parameters:

Name Type Description Default
energy float | list | np.ndarray | sc.Variable | sc.DataArray

The energy transfer. If number, assumed to be in meV unless energy_unit is set. If a DataArray, its single coordinate is used as the energy axis.

required
temperature float | sc.Variable | Parameter

The temperature. Must be a single scalar value. If number, assumed to be in K unless temperature_unit is set.

required
energy_unit str | sc.Unit

Unit for energy if energy is given as a number or list.

'meV'
temperature_unit str | sc.Unit

Unit for temperature if temperature is given as a number.

'K'
divide_by_temperature bool

If True, divide the result by \(k_B*T\) to make it dimensionless and have value 1 at E=0. By default, True.

True

Raises:

Type Description
TypeError

If energy or temperature is not one of the accepted types, or if energy_unit or temperature_unit is not a string or scipp Unit, or if divide_by_temperature is not a boolean.

ValueError

If temperature is negative or is not a single scalar value, if energy is a list or numpy array with more than 1 dimension, or if energy is a scipp DataArray without exactly one coordinate.

UnitError

If the provided energy_unit or temperature_unit is invalid, or if the units of energy or temperature cannot be converted to the expected units.

ZeroDivisionError

If divide_by_temperature is True and temperature is zero.

Returns:

Type Description
np.ndarray

Detailed balance factor evaluated at the given energy and temperature.

Examples:

Basic usage

import easydynamics as edyn

dbf = edyn.detailed_balance_factor(1.0, 300)  # 1 meV at 300 K

Specifying units and disabling temperature normalisation

dbf = detailed_balance_factor(
    energy=[1.0, 2.0],
    temperature=300,
    energy_unit='microeV',
    temperature_unit='K',
    divide_by_temperature=False,
)

slicerplot_with_residuals(dg, *, residuals_key='Residuals', keep=None, operation='sum', **kwargs)

Create a SlicerPlot with an additional subplot for residuals.

This function is called internally by Analysis.plot_data_and_model and Analysis1d.plot_data_and_model. It can also be used directly with any sc.DataGroup that contains a residuals array.

Examples:

Plotting data, model, and residuals from a DataGroup

import scipp as sc
import easydynamics as edyn

dg = sc.DataGroup({
    'Data': my_data,
    'Model': my_model,
    'Residuals': my_residuals,
})
fig = edyn.slicerplot_with_residuals(dg, residuals_key='Residuals', keep='energy')

Parameters:

Name Type Description Default
dg sc.DataGroup

DataGroup containing the data to plot. Must include a key for residuals.

required
residuals_key str

Key in the DataGroup that contains the residuals data.

'Residuals'
keep list[str] | str | None

Dimensions to keep in the SlicerPlot. Passed to SlicerPlot.

None
operation str

Operation to apply when reducing the residuals data. Passed to SlicerPlot.

'sum'
**kwargs object

Additional keyword arguments passed to SlicerPlot.

{}

Returns:

Type Description
WidgetFigure

A figure containing the SlicerPlot and the residuals subplot.

Raises:

Type Description
TypeError

If dg is not a sc.DataGroup or if residuals_key is not a string.

ValueError

If residuals_key is not found in the DataGroup.

plot_corner(draws, names, units=None, title=None, bins=40, figsize=None)

Plot marginal and pairwise posterior distributions.

Diagonal panels show each parameter's marginal distribution. Off-diagonal panels show the joint distribution of a pair: a compact blob means the two are independent, while a narrow diagonal ridge means they are correlated and cannot be determined separately from this data.

Parameters:

Name Type Description Default
draws np.ndarray

Posterior draws, shape (n_draws, n_parameters).

required
names list[str]

One label per column of draws.

required
units list[str] | None

Unit of each column, appended to its label. Entries that are empty or dimensionless are skipped, since a bare "dimensionless" only adds clutter.

None
title str | None

Figure title.

None
bins int

Number of bins for the marginal histograms.

40
figsize tuple[float, float] | None

Figure size in inches. Defaults to a square that scales with the parameter count.

None

Returns:

Type Description
Figure

The matplotlib Figure.

Raises:

Type Description
ValueError

If draws is not two-dimensional or is empty, if names does not have one entry per column, or if any column contains non-finite values.

plot_posterior_predictive(x, y, predictions, y_err=None, title=None, credible_interval=68.0, xlabel=None, ylabel=None, figsize=(8.0, 5.0))

Plot the data against the credible band implied by the posterior.

The band shows where the model says the data should lie, given the posterior. If the data strays outside it systematically, the model is missing something that no amount of parameter tuning will fix.

Parameters:

Name Type Description Default
x np.ndarray

Independent variable of the data.

required
y np.ndarray

Observed values.

required
predictions np.ndarray

Model evaluations, shape (n_draws, len(x)), one row per posterior draw.

required
y_err np.ndarray | None

Standard deviation of the observed values, drawn as error bars when given.

None
title str | None

Figure title.

None
credible_interval float

Width of the credible band, as a percentage.

68.0
xlabel str | None

Label for the independent axis.

None
ylabel str | None

Label for the dependent axis.

None
figsize tuple[float, float]

Figure size in inches.

(8.0, 5.0)

Returns:

Type Description
Figure

The matplotlib Figure.

Raises:

Type Description
ValueError

If predictions is not two-dimensional with one column per point in x, or if credible_interval is not between 0 and 100.

plot_trace(draws, names, logp=None, units=None, title=None, figsize=None)

Plot the chain trace of every sampled parameter.

A converged chain looks like a "hairy caterpillar": noisy but stationary, with no drift or long excursions. A visible trend means the chain has not reached the typical set and needs a longer burn-in.

Parameters:

Name Type Description Default
draws np.ndarray

Posterior draws, shape (n_draws, n_parameters).

required
names list[str]

One label per column of draws.

required
logp np.ndarray | None

Log-posterior values, one per draw, plotted in an extra panel when given.

None
units list[str] | None

Unit of each column, appended to its label. Entries that are empty or dimensionless are skipped, since a bare "dimensionless" only adds clutter.

None
title str | None

Figure title.

None
figsize tuple[float, float] | None

Figure size in inches. Defaults to a height that scales with the number of panels.

None

Returns:

Type Description
Figure

The matplotlib Figure.

Raises:

Type Description
ValueError

If draws is not two-dimensional or is empty, if names does not have one entry per column, or if logp does not have one entry per draw.

Modules

dependency_functions

Functions for use in EasyScience dependency expressions.

Temporary: EasyScience cannot apply functions such as exp to a Parameter in a dependency expression yet. Delete this module, and its use in ModelBase, once it can.

Classes:

Name Description
DependencyFunction

A function that can be called on a Parameter in an EasyScience dependency expression.

Functions:

Name Description
create_dependency_functions

Create the functions to add to the dependency map of Parameter.make_dependent_on.

Classes

DependencyFunction(name, function, derivative)

A function that can be called on a Parameter in an EasyScience dependency expression.

Parameter.make_dependent_on only accepts DescriptorNumbers in its dependency map, and resolves the names in the expression from that map. A callable DescriptorNumber mapped to e.g. 'exp' is therefore what the expression calls, instead of the numpy function, which cannot handle a Parameter.

Parameters:

Name Type Description Default
name str

The name of the function.

required
function Callable[[float], float]

The function of a dimensionless number.

required
derivative Callable[[float], float]

The derivative of the function, used to propagate the variance.

required

Methods:

Name Description
__call__

Apply the function.

from_dict

Re-create an EasyScience object from a full encoded dictionary.

from_scipp

Create a DescriptorNumber from a scipp constant.

convert_unit

Convert the value from one unit system to another.

Attributes:

Name Type Description
unique_name str

Get the unique name of the object.

display_name str

Get a pretty display name.

description str

Get the description of the object.

url str

Get the url of the object.

value numbers.Number

Get the value.

full_value Variable

Get the value of self as a scipp scalar.

unit str

Get the unit.

variance float

Get the variance.

error float

The standard deviation for the parameter.

name str

Get the name of the model.

Attributes
unique_name property writable

Get the unique name of the object.

display_name property writable

Get a pretty display name.

Returns:

Type Description
str

The pretty display name.

description property writable

Get the description of the object.

Returns:

Type Description
str

Description of the object.

url property writable

Get the url of the object.

Returns:

Type Description
str

Url of the object.

value property writable

Get the value.

This should be usable for most cases. The full value can be obtained from obj.full_value.

Returns:

Type Description
numbers.Number

Value of self with unit.

full_value property writable

Get the value of self as a scipp scalar.

This is should be usable for most cases.

Returns:

Type Description
Variable

Value of self with unit.

unit property writable

Get the unit.

Returns:

Type Description
str

Unit as a string.

variance property writable

Get the variance.

Returns:

Type Description
float

Variance.

error property writable

The standard deviation for the parameter.

Returns:

Type Description
float

Error associated with parameter.

name property writable

Get the name of the model.

Returns:

Type Description
str

The name of the model.

Methods:
__call__(argument)

Apply the function.

Parameters:

Name Type Description Default
argument EasyScienceDescriptorNumber | Numeric

The argument of the function. A DescriptorNumber must have a unit that is convertible to dimensionless.

required

Returns:

Type Description
DescriptorNumber | float

The dimensionless function value, with the variance of a DescriptorNumber argument propagated to first order. A plain number gives a plain number.

from_dict(obj_dict) classmethod

Re-create an EasyScience object from a full encoded dictionary.

Parameters:

Name Type Description Default
obj_dict Dict[str, Any]

Dictionary containing the serialized contents (from to_dict) of an EasyScience object.

required

Returns:

Type Description
EasyBase

Reformed EasyScience object.

Raises:

Type Description
ValueError

If the input dictionary does not describe the expected class.

from_scipp(full_value, **kwargs) classmethod

Create a DescriptorNumber from a scipp constant.

Parameters:

Name Type Description Default
full_value Variable

Value of the descriptor as a scipp scalar.

required
**kwargs Any

Additional parameters for the descriptor.

{}

Returns:

Type Description
DescriptorNumber

DescriptorNumber.

Raises:

Type Description
TypeError

If full_value is not a scalar scipp Variable.

convert_unit(unit_str)

Convert the value from one unit system to another.

Parameters:

Name Type Description Default
unit_str str

New unit in string form.

required

Functions:

create_dependency_functions()

Create the functions to add to the dependency map of Parameter.make_dependent_on.

New objects are created on each call: make_dependent_on attaches the dependent Parameter as an observer of every mapped object, which must not accumulate on shared ones.

Returns:

Type Description
dict[str, DependencyFunction]

exp, sin, cos and sinc (the unnormalized sin(x)/x), keyed by name.

detailed_balance

Functions:

Name Description
detailed_balance_factor

Compute the detailed balance factor (DBF): $$ DBF(E, T) = E(n(E)+1)=\frac{E}{(1 - e^{-E /

Classes

Functions:

detailed_balance_factor(energy, temperature, energy_unit='meV', temperature_unit='K', divide_by_temperature=True)

Compute the detailed balance factor (DBF): $$ DBF(E, T) = E(n(E)+1)=\frac{E}{(1 - e^{-E / (k_B*T)})}}, $$ where \(n(E)\) is the Bose-Einstein distribution, \(E\) is the energy transfer, and \(T\) is the temperature. \(k_B\) is the Boltzmann constant. If divide_by_temperature is True, the result is normalized by \(k_B*T\) to have value 1 at \(E=0\).

Parameters:

Name Type Description Default
energy float | list | np.ndarray | sc.Variable | sc.DataArray

The energy transfer. If number, assumed to be in meV unless energy_unit is set. If a DataArray, its single coordinate is used as the energy axis.

required
temperature float | sc.Variable | Parameter

The temperature. Must be a single scalar value. If number, assumed to be in K unless temperature_unit is set.

required
energy_unit str | sc.Unit

Unit for energy if energy is given as a number or list.

'meV'
temperature_unit str | sc.Unit

Unit for temperature if temperature is given as a number.

'K'
divide_by_temperature bool

If True, divide the result by \(k_B*T\) to make it dimensionless and have value 1 at E=0. By default, True.

True

Raises:

Type Description
TypeError

If energy or temperature is not one of the accepted types, or if energy_unit or temperature_unit is not a string or scipp Unit, or if divide_by_temperature is not a boolean.

ValueError

If temperature is negative or is not a single scalar value, if energy is a list or numpy array with more than 1 dimension, or if energy is a scipp DataArray without exactly one coordinate.

UnitError

If the provided energy_unit or temperature_unit is invalid, or if the units of energy or temperature cannot be converted to the expected units.

ZeroDivisionError

If divide_by_temperature is True and temperature is zero.

Returns:

Type Description
np.ndarray

Detailed balance factor evaluated at the given energy and temperature.

Examples:

Basic usage

import easydynamics as edyn

dbf = edyn.detailed_balance_factor(1.0, 300)  # 1 meV at 300 K

Specifying units and disabling temperature normalisation

dbf = detailed_balance_factor(
    energy=[1.0, 2.0],
    temperature=300,
    energy_unit='microeV',
    temperature_unit='K',
    divide_by_temperature=False,
)

fit_target

Classes:

Name Description
FitTarget

One fittable prediction of a model, bound to a key in a parameters Dataset.

Classes

FitTarget(name, dataset_key, function, label, x_unit, y_unit) dataclass

One fittable prediction of a model, bound to a key in a parameters Dataset.

Models declare their predictions by returning FitTargets (see DiffusionModelBase.get_fit_targets), and FitBinding maps them onto the dataset keys they should be fitted against. Instances are immutable snapshots created on demand, so the units always reflect the model state at the time the targets are built.

Attributes:

Name Type Description
name str

The prediction's name (e.g. 'width', 'area', 'delta_area', 'value').

dataset_key str | None

The key in the parameters Dataset holding the data this prediction is fitted against. None when the prediction has no default key (component models); FitBinding supplies the key in that case.

function Callable

The fit function; called as function(x) with raw x values expressed in x_unit and returning raw values expressed in y_unit.

label str

Display label used for plots and results (e.g. 'DeltaLorentz width').

x_unit str | None

The unit function expects its input in, or None if no unit conversion applies.

y_unit str | None

The unit of function's output, or None if no unit conversion applies.

plotting

Functions:

Name Description
with_x_axis_dim

Make x_axis, computed from the Q coordinate, the dimension to plot against.

slicerplot_with_residuals

Create a SlicerPlot with an additional subplot for residuals.

relabel_lines

Rename the lines of a figure in its legend.

Functions:

with_x_axis_dim(data, x_axis)

Make x_axis, computed from the Q coordinate, the dimension to plot against.

Only the coordinate is transformed; the values at each Q are unchanged.

Parameters:

Name Type Description Default
data sc.Dataset

Dataset with a 1-D 'Q' coordinate. Its dimension need not be named 'Q'.

required
x_axis str

Name of the axis to plot against, one of the keys of Q_AXIS_TRANSFORMS.

required

Returns:

Type Description
sc.Dataset

A copy of data with the x_axis coordinate added and used as the dimension.

Raises:

Type Description
ValueError

If x_axis is not one of the supported axes.

slicerplot_with_residuals(dg, *, residuals_key='Residuals', keep=None, operation='sum', **kwargs)

Create a SlicerPlot with an additional subplot for residuals.

This function is called internally by Analysis.plot_data_and_model and Analysis1d.plot_data_and_model. It can also be used directly with any sc.DataGroup that contains a residuals array.

Examples:

Plotting data, model, and residuals from a DataGroup

import scipp as sc
import easydynamics as edyn

dg = sc.DataGroup({
    'Data': my_data,
    'Model': my_model,
    'Residuals': my_residuals,
})
fig = edyn.slicerplot_with_residuals(dg, residuals_key='Residuals', keep='energy')

Parameters:

Name Type Description Default
dg sc.DataGroup

DataGroup containing the data to plot. Must include a key for residuals.

required
residuals_key str

Key in the DataGroup that contains the residuals data.

'Residuals'
keep list[str] | str | None

Dimensions to keep in the SlicerPlot. Passed to SlicerPlot.

None
operation str

Operation to apply when reducing the residuals data. Passed to SlicerPlot.

'sum'
**kwargs object

Additional keyword arguments passed to SlicerPlot.

{}

Returns:

Type Description
WidgetFigure

A figure containing the SlicerPlot and the residuals subplot.

Raises:

Type Description
TypeError

If dg is not a sc.DataGroup or if residuals_key is not a string.

ValueError

If residuals_key is not found in the DataGroup.

relabel_lines(fig, labels)

Rename the lines of a figure in its legend.

Plopp labels each line by its DataGroup key, which must be unique, so lines whose label is a key in labels are renamed after plotting. A blank new label leaves the line out of the legend.

Parameters:

Name Type Description Default
fig WidgetFigure

The figure holding the lines to relabel.

required
labels dict[str, str]

The new label of each line, keyed by its current label.

required

posterior_plotting

Diagnostic plots for Bayesian posterior samples.

These take plain arrays rather than an Analysis, so they can be used on any chain, including one loaded from disk. The Analysis classes wrap them in convenience methods.

Each function closes its figure before returning it. Jupyter shows a returned figure as the result of the cell, and would show it a second time if pyplot still held it open. The returned figure can still be shown, changed and saved.

Functions:

Name Description
plot_trace

Plot the chain trace of every sampled parameter.

plot_corner

Plot marginal and pairwise posterior distributions.

plot_marginal

Plot the marginal posterior distribution of a single parameter.

plot_correlations

Plot the Pearson correlation matrix of the sampled parameters.

plot_posterior_predictive

Plot the data against the credible band implied by the posterior.

figures_with_slider

Show one pre-rendered figure at a time, with a slider choosing which one.

corner_with_slider

Show one corner plot at a time, with a slider choosing which chain to look at.

predictive_with_slider

Plot per-Q posterior-predictive bands behind a plopp Q slider.

Functions:

plot_trace(draws, names, logp=None, units=None, title=None, figsize=None)

Plot the chain trace of every sampled parameter.

A converged chain looks like a "hairy caterpillar": noisy but stationary, with no drift or long excursions. A visible trend means the chain has not reached the typical set and needs a longer burn-in.

Parameters:

Name Type Description Default
draws np.ndarray

Posterior draws, shape (n_draws, n_parameters).

required
names list[str]

One label per column of draws.

required
logp np.ndarray | None

Log-posterior values, one per draw, plotted in an extra panel when given.

None
units list[str] | None

Unit of each column, appended to its label. Entries that are empty or dimensionless are skipped, since a bare "dimensionless" only adds clutter.

None
title str | None

Figure title.

None
figsize tuple[float, float] | None

Figure size in inches. Defaults to a height that scales with the number of panels.

None

Returns:

Type Description
Figure

The matplotlib Figure.

Raises:

Type Description
ValueError

If draws is not two-dimensional or is empty, if names does not have one entry per column, or if logp does not have one entry per draw.

plot_corner(draws, names, units=None, title=None, bins=40, figsize=None)

Plot marginal and pairwise posterior distributions.

Diagonal panels show each parameter's marginal distribution. Off-diagonal panels show the joint distribution of a pair: a compact blob means the two are independent, while a narrow diagonal ridge means they are correlated and cannot be determined separately from this data.

Parameters:

Name Type Description Default
draws np.ndarray

Posterior draws, shape (n_draws, n_parameters).

required
names list[str]

One label per column of draws.

required
units list[str] | None

Unit of each column, appended to its label. Entries that are empty or dimensionless are skipped, since a bare "dimensionless" only adds clutter.

None
title str | None

Figure title.

None
bins int

Number of bins for the marginal histograms.

40
figsize tuple[float, float] | None

Figure size in inches. Defaults to a square that scales with the parameter count.

None

Returns:

Type Description
Figure

The matplotlib Figure.

Raises:

Type Description
ValueError

If draws is not two-dimensional or is empty, if names does not have one entry per column, or if any column contains non-finite values.

plot_marginal(values, name, unit=None, title=None, bins=40, figsize=(8.0, 5.0))

Plot the marginal posterior distribution of a single parameter.

Shows a density-normalized histogram of the parameter's draws, with the median and the 16th and 84th percentiles marked -- the same 68% credible interval the posterior summary reports.

Parameters:

Name Type Description Default
values np.ndarray

The parameter's posterior draws, one-dimensional.

required
name str

The label the parameter is reported under.

required
unit str | None

The parameter's unit, appended to the axis label. Empty or dimensionless units are skipped, since a bare "dimensionless" only adds clutter.

None
title str | None

Figure title.

None
bins int

Number of histogram bins.

40
figsize tuple[float, float]

Figure size in inches.

(8.0, 5.0)

Returns:

Type Description
Figure

The matplotlib Figure.

Raises:

Type Description
ValueError

If values is not one-dimensional, is empty, or contains non-finite entries.

plot_correlations(draws, names, title=None, figsize=None)

Plot the Pearson correlation matrix of the sampled parameters.

A strongly correlated pair (an entry near +1 or -1) cannot be determined separately from this data: the chain trades one off against the other. The matrix condenses what the off-diagonal panels of the corner plot show, one number per pair, which scales better to many parameters.

Correlations are dimensionless, so the labels carry no units. A constant column has no defined correlation with anything; its cells are shown greyed out and marked "n/a" rather than failing. A ValueError propagates from the input validation if draws is not two-dimensional or is empty, or if names does not have one entry per column.

Parameters:

Name Type Description Default
draws np.ndarray

Posterior draws, shape (n_draws, n_parameters).

required
names list[str]

One label per column of draws.

required
title str | None

Figure title.

None
figsize tuple[float, float] | None

Figure size in inches. Defaults to a square that scales with the parameter count, plus room for the colorbar.

None

Returns:

Type Description
Figure

The matplotlib Figure.

plot_posterior_predictive(x, y, predictions, y_err=None, title=None, credible_interval=68.0, xlabel=None, ylabel=None, figsize=(8.0, 5.0))

Plot the data against the credible band implied by the posterior.

The band shows where the model says the data should lie, given the posterior. If the data strays outside it systematically, the model is missing something that no amount of parameter tuning will fix.

Parameters:

Name Type Description Default
x np.ndarray

Independent variable of the data.

required
y np.ndarray

Observed values.

required
predictions np.ndarray

Model evaluations, shape (n_draws, len(x)), one row per posterior draw.

required
y_err np.ndarray | None

Standard deviation of the observed values, drawn as error bars when given.

None
title str | None

Figure title.

None
credible_interval float

Width of the credible band, as a percentage.

68.0
xlabel str | None

Label for the independent axis.

None
ylabel str | None

Label for the dependent axis.

None
figsize tuple[float, float]

Figure size in inches.

(8.0, 5.0)

Returns:

Type Description
Figure

The matplotlib Figure.

Raises:

Type Description
ValueError

If predictions is not two-dimensional with one column per point in x, or if credible_interval is not between 0 and 100.

figures_with_slider(figures, description='Q index')

Show one pre-rendered figure at a time, with a slider choosing which one.

Every figure is rendered to PNG bytes once, up front, and the slider callback only swaps the stored bytes into an image widget. Moving the slider therefore costs no matplotlib work at all, which keeps it as responsive as the plopp slider on the data plots; re-rendering a figure on every move is what made the previous slider feel sluggish.

The figures are closed after rendering, so no backend draws them a second time.

Parameters:

Name Type Description Default
figures dict[int, Figure]

Mapping of slider position to the matplotlib Figure shown there. Only these positions are offered, so the slider cannot land on an index with nothing to show.

required
description str

Label shown next to the slider.

'Q index'

Returns:

Type Description
VBox

An ipywidgets box holding the image and, under it, the slider.

Raises:

Type Description
ValueError

If no figures are given.

corner_with_slider(chains, title=None, **kwargs)

Show one corner plot at a time, with a slider choosing which chain to look at.

Chains sampled separately share no draws, so there is no joint distribution across them to plot. Stepping through them one at a time shows the correlations that were actually sampled, which is what a single combined figure could not do honestly. The figures are pre-rendered through :func:figures_with_slider, so the slider moves without re-drawing anything.

Parameters:

Name Type Description Default
chains dict[int, dict]

Mapping of index to a {'draws': ..., 'names': ..., 'units': ...} description of one chain. units is optional.

required
title str | None

Title prefix, extended with the selected index.

None
**kwargs dict[str, Any]

Forwarded to :func:plot_corner.

{}

Returns:

Type Description
VBox

An ipywidgets box holding the figure and the slider.

Raises:

Type Description
ValueError

If no chains are given.

predictive_with_slider(energy, q_values, y, lower, median, upper, y_variances=None, energy_unit=None, q_unit=None, ylabel=None, title=None, credible_interval=68.0, **kwargs)

Plot per-Q posterior-predictive bands behind a plopp Q slider.

Built on plopp.slicer over a scipp DataGroup with a Q dimension, so the figure looks and handles exactly like Analysis.plot_data_and_model: the data with its error bars, the model curves on top, and a Q slider underneath. Plopp draws no filled band for sliced data -- its only spread representation is variance-based error bars -- so the credible band is drawn as the posterior median with a dashed line along each band edge, labelled with the interval.

Rows are laid out on one common energy grid; where a Q has no point (masked or never measured), NaN leaves a gap in the lines rather than inventing a value.

Parameters:

Name Type Description Default
energy np.ndarray

The common energy grid, one column per point.

required
q_values np.ndarray

The Q value of each row, shown on the slider.

required
y np.ndarray

Observed values, shape (len(q_values), len(energy)), NaN where a Q has no point.

required
lower np.ndarray

Lower band edge per Q, same shape as y.

required
median np.ndarray

Posterior median prediction per Q, same shape as y.

required
upper np.ndarray

Upper band edge per Q, same shape as y.

required
y_variances np.ndarray | None

Variances of the observed values, drawn as error bars when given.

None
energy_unit str | None

Unit of the energy grid, shown on the horizontal axis.

None
q_unit str | None

Unit of the Q values, shown beside the slider.

None
ylabel str | None

Label for the dependent axis.

None
title str | None

Figure title.

None
credible_interval float

Width of the credible band the edges enclose, as a percentage, used in their labels.

68.0
**kwargs dict[str, Any]

Forwarded to plopp.slicer, overriding the style defaults.

{}

Returns:

Type Description
WidgetFigure

The plopp figure with its Q slider.

Raises:

Type Description
ValueError

If the arrays do not share the shape (len(q_values), len(energy)), or if credible_interval is not between 0 and 100.

utils

Functions:

Name Description
verify_Q_index

Verify that Q_index is a valid integer index into Q.

convert_units_with_rollback

Apply a sequence of unit conversions, rolling all of them back if any fails.

convert_value_unit

Convert a numeric value from one unit to another without mutating anything.

convert_parameter_unit

Convert a parameter to a new unit, keeping dependent parameters consistent.

energy_to_scipp

Convert a numpy energy array to a scipp Variable with dimension 'energy'.

prepare_x_for_evaluate

Validate x and extract its values, detected unit, and dimension name.

Classes

Functions:

verify_Q_index(Q_index, Q, allow_none=False)

Verify that Q_index is a valid integer index into Q.

When Q is None (e.g. no data has been loaded yet), only the type and sign of Q_index are checked; the upper-bound check is deferred until Q is available.

Parameters:

Name Type Description Default
Q_index int

Index to validate.

required
Q sc.Variable | None

The Q values (may be None if no data is loaded).

required
allow_none bool

Whether or not to allow Q_index to be None

False

Raises:

Type Description
TypeError

If Q_index is not an int (or not an int or None when allow_none=True). Booleans are rejected explicitly, since True would otherwise silently mean index 1.

IndexError

If Q_index is negative, or out of range when Q is available.

convert_units_with_rollback(conversions)

Apply a sequence of unit conversions, rolling all of them back if any fails.

Each item is (convert, new_unit, old_unit) where convert is a callable applying a unit (e.g. a bound convert_x_unit or a functools.partial around :func:convert_parameter_unit). The conversions are applied in order; if any raises, every item is converted back to its old unit best-effort (converting a not-yet-converted item back to its old unit is a no-op) and the original exception is re-raised.

Parameters:

Name Type Description Default
conversions list[tuple[Callable[[str | sc.Unit], None], str | sc.Unit, str | sc.Unit]]

The conversions to apply, each as (convert, new_unit, old_unit).

required

Raises:

Type Description
Exception

Whatever the failing conversion raised, after the rollback attempt.

convert_value_unit(value, from_unit, to_unit)

Convert a numeric value from one unit to another without mutating anything.

Returns the value unchanged when the two units compare equal as strings (the common no-conversion case, kept cheap for hot paths).

Parameters:

Name Type Description Default
value float

The value to convert.

required
from_unit str | sc.Unit

The unit the value is currently expressed in.

required
to_unit str | sc.Unit

The unit to convert the value to.

required

Returns:

Type Description
float

The value expressed in to_unit.

convert_parameter_unit(parameter, unit)

Convert a parameter to a new unit, keeping dependent parameters consistent.

Independent parameters are converted with convert_unit. Dependent parameters are converted with set_desired_unit, so the new unit survives later dependency-graph recomputations (a plain convert_unit would be reverted to the old desired unit the next time the dependency expression is re-evaluated).

Parameters:

Name Type Description Default
parameter Parameter

The parameter to convert.

required
unit str | sc.Unit

The unit to convert to.

required
energy_to_scipp(energy, unit)

Convert a numpy energy array to a scipp Variable with dimension 'energy'.

Parameters:

Name Type Description Default
energy np.ndarray

The energy array to be converted

required
unit str | sc.Unit

The unit of the energy

required

Returns:

Type Description
sc.Variable

Energy as sc.Variable.

prepare_x_for_evaluate(x, x_unit, component_name)

Validate x and extract its values, detected unit, and dimension name.

x is never converted. When x carries a unit, the caller is responsible for resolving parameter values to that unit via _resolve_param_value.

Parameters:

Name Type Description Default
x Numeric | list | np.ndarray | sc.Variable | sc.DataArray

Input x values to validate and extract.

required
x_unit str | sc.Unit | None

The unit of the model that will be evaluated. If None, no unit compatibility check is made.

required
component_name str

Name of the model, used in the error message when the units are incompatible.

required

Returns:

Type Description
tuple[np.ndarray, str | None, str]

x_values : np.ndarray of raw float values (no unit conversion) detected_unit : str unit of x if scipp input, else None dim : scipp dimension name if scipp input, else 'x'

Raises:

Type Description
UnitError

If x has a unit incompatible with x_unit.

ValueError

If x contains NaN or infinite values, or if a DataArray has more than one coordinate.