utils
Modules:
| Name | Description |
|---|---|
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 |
|---|---|
InteractiveFigure
|
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 |
required |
names
|
list[str]
|
One label per column of |
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 |
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 |
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 |
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 |
required |
names
|
list[str]
|
One label per column of |
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 |
Modules
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. |
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); |
function |
Callable
|
The fit function; called as |
label |
str
|
Display label used for plots and results (e.g. |
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 |
|---|---|
slicerplot_with_residuals |
Create a SlicerPlot with an additional subplot for residuals. |
Functions:
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 |
|---|---|
InteractiveFigure
|
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. |
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.
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 |
required |
names
|
list[str]
|
One label per column of |
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 |
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 |
required |
names
|
list[str]
|
One label per column of |
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 |
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 |
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 |
required |
names
|
list[str]
|
One label per column of |
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 |
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 |
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 |
required |
title
|
str | None
|
Title prefix, extended with the selected index. |
None
|
**kwargs
|
dict[str, Any]
|
Forwarded to :func: |
{}
|
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 |
required |
lower
|
np.ndarray
|
Lower band edge per Q, same shape as |
required |
median
|
np.ndarray
|
Posterior median prediction per Q, same shape as |
required |
upper
|
np.ndarray
|
Upper band edge per Q, same shape as |
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 |
{}
|
Returns:
| Type | Description |
|---|---|
InteractiveFigure
|
The plopp figure with its Q slider. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the arrays do not share the shape |
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'. |
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 |
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 |
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 |