Skip to content

analysis

Modules:

Name Description
analysis
analysis1d
analysis_base
fit_binding
parameter_analysis
posterior

Bounds suggestions and posterior summaries for Bayesian sampling.

posterior_labels

Naming the columns of an MCMC chain.

posterior_sampling

Bayesian MCMC sampling for the Analysis classes, backed by the BUMPS DREAM sampler.

Classes:

Name Description
Analysis

For analysing two-dimensional data, i.e. intensity as function of energy and Q.

Analysis1d

For analysing one-dimensional data, i.e. intensity as function of energy for a single Q index.

FitBinding

Contract between dataset, model, and fit functions for ParameterAnalysis. A binding maps the

ParameterAnalysis

For analysing fitted parameters.

BoundsSuggestion

A proposed pair of bounds for a single parameter.

BoundsSuggestions

The result of :func:suggest_bounds_for_parameters, rendered as a table.

ParameterPosterior

The marginal posterior of a single parameter.

PosteriorSummary

Marginal posterior summaries for every sampled parameter, rendered as a table.

ParameterLabels

Readable labels and units for the columns of a chain.

MultiQPosteriorSampler

Posterior sampling for an Analysis covering several Q values.

PosteriorSampler

Draws samples from the posterior distribution of an Analysis' free parameters.

Classes

Analysis(display_name='MyAnalysis', unique_name=None, experiment=None, sample_model=None, instrument_model=None, convolution_settings=None, detailed_balance_settings=None, extra_parameters=None)

For analysing two-dimensional data, i.e. intensity as function of energy and Q.

Supports independent fits of each Q value and simultaneous fits of all Q.

Besides least-squares fitting with :meth:fit, the posterior distribution of the free parameters can be explored through :attr:bayesian; see :class:~easydynamics.analysis.posterior_sampling.MultiQPosteriorSampler.

Examples:

Fitting vanadium data for instrument calibration

The standard workflow builds a sample model, resolution model, background model, and instrument model, then combines them into an Analysis before fitting:

import pooch
import easydynamics as edyn

file_path = pooch.retrieve(
    url='https://github.com/easyscience/dynamics-lib/raw/refs/heads/master/docs/docs/tutorials/data/vanadium_data_example.h5',
    known_hash='16cc1b327c303feeb88fb9dda5390dc4880b62396b1793f98c6fef0b27c7b873',
)
experiment = edyn.Experiment('Vanadium')
experiment.load_hdf5(filename=file_path)

sample_model = edyn.SampleModel(components=edyn.DeltaFunction(area=1))
resolution_model = edyn.ResolutionModel(components=edyn.Gaussian(width=0.1))
background_model = edyn.BackgroundModel(components=edyn.Polynomial(coefficients=[0.001]))
instrument_model = edyn.InstrumentModel(
    resolution_model=resolution_model,
    background_model=background_model,
)

analysis = edyn.Analysis(
    display_name='Vanadium Analysis',
    experiment=experiment,
    sample_model=sample_model,
    instrument_model=instrument_model,
)
analysis.fit(fit_method='independent')
analysis.plot_data_and_model()

Inspecting fitted parameters and fitting a single Q first

Use Q_index to fit and plot a single Q slice before fitting all Q:

analysis.fit(fit_method='independent', Q_index=5)
analysis.plot_data_and_model(Q_index=5)

analysis.fit(fit_method='independent')
analysis.plot_parameters(names=['Gaussian width'])

Parameters:

Name Type Description Default
display_name str | None

Display name of the analysis.

'MyAnalysis'
unique_name str | None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
convolution_settings ConvolutionSettings | None

The settings for the convolution. If None, default settings will be used.

None
detailed_balance_settings DetailedBalanceSettings | None

The settings for detailed balance. If None, default settings will be used.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None

Methods:

Name Description
to_dict

Convert an EasyScience object into a full dictionary using

from_dict

Re-create an EasyScience object with DescriptorNumber attributes

__copy__

Return a copy of the object.

get_all_parameters

Get all Parameter objects as a list.

get_fittable_parameters

Get all parameters which can be fitted as a list.

get_free_parameters

Get all parameters which are currently free to be fitted as a

get_fit_parameters

This is an alias for get_free_parameters.

normalize_resolution

Normalize the resolution in the InstrumentModel to ensure that it integrates to 1.

get_parameters_near_bounds

Get a list of parameters that are near their bounds.

rebin

Rebin the experiment data along specified dimensions and update the analysis.

calculate

Calculate model data for a specific Q index.

fit

Fit the model to the experimental data.

plot_data_and_model

Plot the experimental data and the model prediction.

data_and_model_to_datagroup

Create a scipp DataGroup containing the experimental data, model calculation and optionally

parameters_to_dataset

Creates a scipp dataset with copies of the Parameters in the model.

plot_parameters

Plot fitted parameters as a function of Q.

fix_energy_offset

Fix the energy offset parameter(s) for a specific Q index, or for all Q indices if Q_index

free_energy_offset

Free the energy offset parameter(s) for a specific Q index, or for all Q indices if Q_index

get_all_variables

Get all variables used in the analysis, across every Q index.

get_fit_functions

Get fit functions for all Q indices, which can be used for simultaneous fitting.

Attributes:

Name Type Description
unique_name str

Get the unique name of the object.

display_name str

Get a pretty display name.

name str

Get the name of the model.

x_unit str | sc.Unit | None

Get the unit of the x-axis.

y_unit str | sc.Unit | None

Get the unit of the model output.

convolution_settings ConvolutionSettings

Get the convolution settings for this Analysis.

extra_parameters list[Parameter]

Get the extra parameters included in this Analysis.

experiment Experiment

Get the Experiment associated with this Analysis.

sample_model SampleModel

Get the SampleModel associated with this Analysis.

instrument_model InstrumentModel

Get the InstrumentModel associated with this Analysis.

Q sc.Variable | None

Get the Q values from the associated Experiment, if available.

energy sc.Variable | None

Get the energy values from the associated Experiment, if available.

temperature Parameter | None

Get the temperature from the associated SampleModel, if available.

detailed_balance_settings DetailedBalanceSettings

Get the DetailedBalanceSettings of the SampleModel.

analysis_list list[Analysis1d]

Get the Analysis1d objects associated with this Analysis.

fitter MultiFitter

The EasyScience MultiFitter covering every Q index, built on first use.

bayesian MultiQPosteriorSampler

Bayesian posterior sampling for this Analysis, created on first use.

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.

name property writable

Get the name of the model.

Returns:

Type Description
str

The name of the model.

x_unit property writable

Get the unit of the x-axis.

Returns:

Type Description
str | sc.Unit | None

The unit of the x-axis.

y_unit property writable

Get the unit of the model output.

Returns:

Type Description
str | sc.Unit | None

The unit of the y-axis.

convolution_settings property writable

Get the convolution settings for this Analysis.

Returns:

Type Description
ConvolutionSettings

The convolution settings for this Analysis.

extra_parameters property writable

Get the extra parameters included in this Analysis.

Returns:

Type Description
list[Parameter]

The extra parameters included in this Analysis.

experiment property writable

Get the Experiment associated with this Analysis.

Returns:

Type Description
Experiment

The Experiment associated with this Analysis.

sample_model property writable

Get the SampleModel associated with this Analysis.

Returns:

Type Description
SampleModel

The SampleModel associated with this Analysis.

instrument_model property writable

Get the InstrumentModel associated with this Analysis.

Returns:

Type Description
InstrumentModel

The InstrumentModel associated with this Analysis.

Q property writable

Get the Q values from the associated Experiment, if available.

Returns:

Type Description
sc.Variable | None

The Q values from the associated Experiment, if available, and None if not.

energy property writable

Get the energy values from the associated Experiment, if available.

Returns:

Type Description
sc.Variable | None

The energy values from the associated Experiment, if available, and None if not.

temperature property writable

Get the temperature from the associated SampleModel, if available.

Returns:

Type Description
Parameter | None

The temperature from the associated SampleModel, if available, and None if not.

detailed_balance_settings property writable

Get the DetailedBalanceSettings of the SampleModel.

Returns:

Type Description
DetailedBalanceSettings

The DetailedBalanceSettings of the SampleModel.

analysis_list property writable

Get the Analysis1d objects associated with this Analysis.

Returns:

Type Description
list[Analysis1d]

A list of Analysis1d objects, one for each Q index.

fitter property

The EasyScience MultiFitter covering every Q index, built on first use.

Returns:

Type Description
MultiFitter

The cached MultiFitter.

bayesian property

Bayesian posterior sampling for this Analysis, created on first use.

Returns:

Type Description
MultiQPosteriorSampler

The sampler, which can run per Q index or over all of them at once.

Methods:

to_dict(skip=None)

Convert an EasyScience object into a full dictionary using SerializerBases generic convert_to_dict method.

Parameters:

Name Type Description Default
skip Optional[List[str]]

List of field names as strings to skip when forming the dictionary. By default, None.

None

Returns:

Type Description
Dict[str, Any]

Encoded object containing all information to reform an EasyScience object.

from_dict(obj_dict) classmethod

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

Parameters:

Name Type Description Default
obj_dict Dict[str, Any]

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

required

Returns:

Type Description
ModelBase

Reformed EasyScience object.

Raises:

Type Description
SyntaxError

If a deserialized parameter cannot be attached back to the class definition.

ValueError

If the input dictionary does not describe the expected class.

__copy__()

Return a copy of the object.

get_all_parameters()

Get all Parameter objects as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fittable_parameters()

Get all parameters which can be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_free_parameters()

Get all parameters which are currently free to be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fit_parameters()

This is an alias for get_free_parameters.

To be removed when fully moved to new base classes and minimizer can be changed.

normalize_resolution()

Normalize the resolution in the InstrumentModel to ensure that it integrates to 1.

This is important for accurate fitting and interpretation of the results.

get_parameters_near_bounds(rtol=1e-05, atol=1e-08)

Get a list of parameters that are near their bounds.

Parameters:

Name Type Description Default
rtol float

Relative tolerance for determining if a parameter is near its bound.

1e-5
atol float

Absolute tolerance for determining if a parameter is near its bound.

1e-8

Returns:

Type Description
list[Parameter]

A list of parameters that are near their bounds.

rebin(dimensions, confirm=False)

Rebin the experiment data along specified dimensions and update the analysis.

If Q values change (in count or magnitude), confirm=True is required. This clears Q from sample_model and instrument_model (including resolution and background sub-models) so they can accept the new Q values when the analysis list is next rebuilt.

Parameters:

Name Type Description Default
dimensions dict[str, int | sc.Variable]

A dictionary mapping dimension names to number of bins (int) or bin edges (sc.Variable).

required
confirm bool

Must be True when rebinning changes the Q values (count or magnitude), since this clears Q from all models. Raises ValueError otherwise.

False

Raises:

Type Description
ValueError

If rebinning changes Q and confirm is not True.

calculate(Q_index=None, energy=None)

Calculate model data for a specific Q index.

If Q_index is None, calculate for all Q indices and return a list of arrays.

Parameters:

Name Type Description Default
Q_index int | None

Index of the Q value to calculate for. If None, calculate for all Q values.

None
energy sc.Variable | None

The energy values to use for calculating the model. If None, uses the energy from the experiment.

None

Returns:

Type Description
list[np.ndarray] | np.ndarray

If Q_index is None, returns a list of numpy arrays, one for each Q index. If Q_index is an integer, returns a single numpy array for that Q index.

fit(fit_method='independent', Q_index=None)

Fit the model to the experimental data.

Parameters:

Name Type Description Default
fit_method str

Method to use for fitting. Options are "independent" (fit each Q index independently, one after the other) or "simultaneous" (fit all Q indices simultaneously).

'independent'
Q_index int | None

If fit_method is "independent", specify which Q index to fit. If None, fit all Q indices independently. Ignored if fit_method is "simultaneous".

None

Raises:

Type Description
ValueError

If fit_method is not "independent" or "simultaneous" or if there are no Q values available for fitting.

Returns:

Type Description
FitResults | list[FitResults]

A single FitResults when a specific Q index was fitted, and otherwise a list holding one FitResults per Q index. A simultaneous fit also reports per-Q results, since the underlying MultiFitter splits its combined result back up by dataset.

plot_data_and_model(Q_index=None, plot_components=True, add_background=True, plot_residuals=False, energy=None, **kwargs)

Plot the experimental data and the model prediction.

Optionally also plot the individual components of the model.

Uses Plopp for plotting: https://scipp.github.io/plopp/

Parameters:

Name Type Description Default
Q_index int | None

Index of the Q value to plot. If None, plot all Q values.

None
plot_components bool

Whether to plot the individual components.

True
add_background bool

Whether to add background components to the sample model components when plotting. Default is True.

True
plot_residuals bool

Whether to plot the residuals (data - model). Default is False.

False
energy sc.Variable | None

The energy values to use for calculating the model. If None, uses the energy from the experiment.

None
**kwargs dict[str, Any]

Additional keyword arguments passed to plopp for customizing the plot.

{}

Raises:

Type Description
ValueError

If Q_index is out of bounds, or if there is no data to plot, or if there are no Q values available for plotting.

RuntimeError

If not in a Jupyter notebook environment.

Returns:

Type Description
InteractiveFigure

A Plopp InteractiveFigure containing the plot of the data and model.

data_and_model_to_datagroup(energy=None, add_background=True, include_components=True, include_residuals=False)

Create a scipp DataGroup containing the experimental data, model calculation and optionally the individual components of the model.

Parameters:

Name Type Description Default
energy sc.Variable | None

The energy values to use for calculating the model. If None, uses the energy from the experiment.

None
add_background bool

Whether to add background components to the sample model components when creating the DataGroup.

True
include_components bool

Whether to include the individual components of the model in the DataGroup. If False, only the total model will be included.

True
include_residuals bool

Whether to include the residuals (data - model) in the DataGroup.

False

Raises:

Type Description
ValueError

If there is no data to include in the DataGroup, or if there are no Q values available for creating the DataGroup.

Returns:

Type Description
sc.DataGroup

A DataGroup containing the experimental data, model calculation, and optionally the individual components of the model.

parameters_to_dataset()

Creates a scipp dataset with copies of the Parameters in the model.

Ensures unit consistency across Q.

Raises:

Type Description
UnitError

If there are inconsistent units for the same parameter across different Q values.

ValueError

If duplicate parameter names exist for the same Q index.

Returns:

Type Description
sc.Dataset

A dataset where each entry is a parameter, with dimensions "Q" and values corresponding to the parameter values.

plot_parameters(names=None, **kwargs)

Plot fitted parameters as a function of Q.

Parameters:

Name Type Description Default
names str | list[str] | None

Name(s) of the parameter(s) to plot. If None, plots all parameters.

None
**kwargs dict[str, Any]

Additional keyword arguments passed to plopp.slicer for customizing the plot (e.g., title, linestyle, marker, color).

{}

Raises:

Type Description
TypeError

If names is not a string, list of strings, or None.

ValueError

If any of the specified parameter names are not found in the dataset.

Returns:

Type Description
InteractiveFigure

A Plopp InteractiveFigure containing the plot of the parameters.

fix_energy_offset(Q_index=None)

Fix the energy offset parameter(s) for a specific Q index, or for all Q indices if Q_index is None.

Parameters:

Name Type Description Default
Q_index int | None

Index of the Q value to fix the energy offset for. If None, fixes the energy offset for all Q values.

None
free_energy_offset(Q_index=None)

Free the energy offset parameter(s) for a specific Q index, or for all Q indices if Q_index is None.

Parameters:

Name Type Description Default
Q_index int | None

Index of the Q value to free the energy offset for. If None, frees the energy offset for all Q values.

None
get_all_variables()

Get all variables used in the analysis, across every Q index.

Overrides the easyscience fallback, which scans every attribute of the object and would therefore build the MultiFitter and the Sampler as side effects of merely listing variables (and fail outright on an empty analysis).

Returns:

Type Description
list[Parameter]

A list of all variables, including any extra parameters.

get_fit_functions()

Get fit functions for all Q indices, which can be used for simultaneous fitting.

Returns:

Type Description
list[callable]

A list of fit functions, one for each Q index.

Analysis1d(display_name='MyAnalysis', unique_name=None, experiment=None, sample_model=None, instrument_model=None, Q_index=None, convolution_settings=None, detailed_balance_settings=None, extra_parameters=None)

For analysing one-dimensional data, i.e. intensity as function of energy for a single Q index.

Is used primarily in the Analysis class, but can also be used on its own for simpler analyses.

Besides least-squares fitting with :meth:fit, the posterior distribution of the free parameters can be explored through :attr:bayesian; see :class:~easydynamics.analysis.posterior_sampling.PosteriorSampler.

Examples:

Fitting a single Q slice

Select a Q index with Q_index to fit only that slice of the dataset:

import pooch
import easydynamics as edyn

file_path = pooch.retrieve(
    url='https://github.com/easyscience/dynamics-lib/raw/refs/heads/master/docs/docs/tutorials/data/vanadium_data_example.h5',
    known_hash='16cc1b327c303feeb88fb9dda5390dc4880b62396b1793f98c6fef0b27c7b873',
)
experiment = edyn.Experiment('Vanadium')
experiment.load_hdf5(filename=file_path)

sample_model = edyn.SampleModel(components=edyn.DeltaFunction(area=1))
resolution_model = edyn.ResolutionModel(components=edyn.Gaussian(width=0.1))
background_model = edyn.BackgroundModel(components=edyn.Polynomial(coefficients=[0.001]))
instrument_model = edyn.InstrumentModel(
    resolution_model=resolution_model,
    background_model=background_model,
)

analysis = edyn.Analysis1d(
    display_name='Vanadium 1D Analysis',
    experiment=experiment,
    sample_model=sample_model,
    instrument_model=instrument_model,
    Q_index=5,
)
analysis.fit()
analysis.plot_data_and_model(plot_residuals=True)

Parameters:

Name Type Description Default
display_name str | None

Display name of the analysis.

'MyAnalysis'
unique_name str | None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
Q_index int | None

The Q index to analyze. If None, the analysis will not be able to calculate or fit until a Q index is set.

None
convolution_settings ConvolutionSettings | None

The settings for the convolution. If None, default settings will be used.

None
detailed_balance_settings DetailedBalanceSettings | None

The settings for detailed balance. If None, default settings will be used.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None

Methods:

Name Description
to_dict

Convert an EasyScience object into a full dictionary using

from_dict

Re-create an EasyScience object with DescriptorNumber attributes

__copy__

Return a copy of the object.

get_all_parameters

Get all Parameter objects as a list.

get_fittable_parameters

Get all parameters which can be fitted as a list.

get_free_parameters

Get all parameters which are currently free to be fitted as a

get_fit_parameters

This is an alias for get_free_parameters.

normalize_resolution

Normalize the resolution in the InstrumentModel to ensure that it integrates to 1.

get_parameters_near_bounds

Get a list of parameters that are near their bounds.

calculate

Calculate the model prediction for the chosen Q index.

fit

Fit the model to the experimental data for the chosen Q index.

as_fit_function

Return self._calculate as a fit function.

get_all_variables

Get all variables used in the analysis.

plot_data_and_model

Plot the experimental data and the model prediction for the chosen Q index. Optionally also

data_and_model_to_datagroup

Create a scipp DataGroup containing the experimental data, model calculation, and

fix_energy_offset

Fix the energy offset parameter for the current Q index.

free_energy_offset

Free the energy offset parameter for the current Q index.

rebin

Rebin the experiment data along specified dimensions and update the analysis.

refresh_convolver

Refresh the pre-built Convolution object for the current Q index.

Attributes:

Name Type Description
unique_name str

Get the unique name of the object.

display_name str

Get a pretty display name.

name str

Get the name of the model.

x_unit str | sc.Unit | None

Get the unit of the x-axis.

y_unit str | sc.Unit | None

Get the unit of the model output.

convolution_settings ConvolutionSettings

Get the convolution settings for this Analysis.

extra_parameters list[Parameter]

Get the extra parameters included in this Analysis.

experiment Experiment

Get the Experiment associated with this Analysis.

sample_model SampleModel

Get the SampleModel associated with this Analysis.

instrument_model InstrumentModel

Get the InstrumentModel associated with this Analysis.

Q sc.Variable | None

Get the Q values from the associated Experiment, if available.

energy sc.Variable | None

Get the energy values from the associated Experiment, if available.

temperature Parameter | None

Get the temperature from the associated SampleModel, if available.

detailed_balance_settings DetailedBalanceSettings

Get the DetailedBalanceSettings of the SampleModel.

Q_index int | None

Get the Q index associated with this Analysis.

fitter EasyScienceFitter

The EasyScience Fitter used for fitting and sampling, built on first use.

bayesian PosteriorSampler

Bayesian posterior sampling for this Analysis, created on first use.

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.

name property writable

Get the name of the model.

Returns:

Type Description
str

The name of the model.

x_unit property writable

Get the unit of the x-axis.

Returns:

Type Description
str | sc.Unit | None

The unit of the x-axis.

y_unit property writable

Get the unit of the model output.

Returns:

Type Description
str | sc.Unit | None

The unit of the y-axis.

convolution_settings property writable

Get the convolution settings for this Analysis.

Returns:

Type Description
ConvolutionSettings

The convolution settings for this Analysis.

extra_parameters property writable

Get the extra parameters included in this Analysis.

Returns:

Type Description
list[Parameter]

The extra parameters included in this Analysis.

experiment property writable

Get the Experiment associated with this Analysis.

Returns:

Type Description
Experiment

The Experiment associated with this Analysis.

sample_model property writable

Get the SampleModel associated with this Analysis.

Returns:

Type Description
SampleModel

The SampleModel associated with this Analysis.

instrument_model property writable

Get the InstrumentModel associated with this Analysis.

Returns:

Type Description
InstrumentModel

The InstrumentModel associated with this Analysis.

Q property writable

Get the Q values from the associated Experiment, if available.

Returns:

Type Description
sc.Variable | None

The Q values from the associated Experiment, if available, and None if not.

energy property writable

Get the energy values from the associated Experiment, if available.

Returns:

Type Description
sc.Variable | None

The energy values from the associated Experiment, if available, and None if not.

temperature property writable

Get the temperature from the associated SampleModel, if available.

Returns:

Type Description
Parameter | None

The temperature from the associated SampleModel, if available, and None if not.

detailed_balance_settings property writable

Get the DetailedBalanceSettings of the SampleModel.

Returns:

Type Description
DetailedBalanceSettings

The DetailedBalanceSettings of the SampleModel.

Q_index property writable

Get the Q index associated with this Analysis.

Returns:

Type Description
int | None

The Q index associated with this Analysis.

fitter property

The EasyScience Fitter used for fitting and sampling, built on first use.

Exposed so the minimizer, tolerance, and maximum evaluation count can be configured directly, e.g. analysis.fitter.switch_minimizer(AvailableMinimizers.Bumps).

Returns:

Type Description
EasyScienceFitter

The cached Fitter.

bayesian property

Bayesian posterior sampling for this Analysis, created on first use.

Returns:

Type Description
PosteriorSampler

The sampler, which holds any chain that has been run.

Methods:

to_dict(skip=None)

Convert an EasyScience object into a full dictionary using SerializerBases generic convert_to_dict method.

Parameters:

Name Type Description Default
skip Optional[List[str]]

List of field names as strings to skip when forming the dictionary. By default, None.

None

Returns:

Type Description
Dict[str, Any]

Encoded object containing all information to reform an EasyScience object.

from_dict(obj_dict) classmethod

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

Parameters:

Name Type Description Default
obj_dict Dict[str, Any]

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

required

Returns:

Type Description
ModelBase

Reformed EasyScience object.

Raises:

Type Description
SyntaxError

If a deserialized parameter cannot be attached back to the class definition.

ValueError

If the input dictionary does not describe the expected class.

__copy__()

Return a copy of the object.

get_all_parameters()

Get all Parameter objects as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fittable_parameters()

Get all parameters which can be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_free_parameters()

Get all parameters which are currently free to be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fit_parameters()

This is an alias for get_free_parameters.

To be removed when fully moved to new base classes and minimizer can be changed.

normalize_resolution()

Normalize the resolution in the InstrumentModel to ensure that it integrates to 1.

This is important for accurate fitting and interpretation of the results.

get_parameters_near_bounds(rtol=1e-05, atol=1e-08)

Get a list of parameters that are near their bounds.

Parameters:

Name Type Description Default
rtol float

Relative tolerance for determining if a parameter is near its bound.

1e-5
atol float

Absolute tolerance for determining if a parameter is near its bound.

1e-8

Returns:

Type Description
list[Parameter]

A list of parameters that are near their bounds.

calculate(energy=None)

Calculate the model prediction for the chosen Q index.

Creates a new convolver before calculating without touching the stored convolver.

Parameters:

Name Type Description Default
energy sc.Variable | None

Optional energy grid to use for calculation. If None, the energy grid from the experiment is used.

None

Returns:

Type Description
np.ndarray

The calculated model prediction.

fit()

Fit the model to the experimental data for the chosen Q index.

The energy grid is fixed for the duration of the fit. Convolution objects are created once and reused during parameter optimization for performance reasons.

Raises:

Type Description
ValueError

If no experiment is associated with this Analysis.

Returns:

Type Description
FitResults

The result of the fit.

as_fit_function(_x=None, **kwargs)

Return self._calculate as a fit function.

The EasyScience fitter requires x as input, but self._calculate() already uses the correct energy from the experiment. So we ignore the x input and just return the calculated model.

Parameters:

Name Type Description Default
_x np.ndarray | sc.Variable | None

Ignored. The energy grid is taken from the experiment.

None
**kwargs dict[str, Any]

Ignored. Included for compatibility with the EasyScience fitter.

{}

Returns:

Type Description
callable

A function that can be used as a fit function in the EasyScience fitter, which returns the calculated model.

get_all_variables()

Get all variables used in the analysis.

Returns:

Type Description
list[DescriptorNumber]

A list of all variables.

plot_data_and_model(plot_components=True, add_background=True, plot_residuals=False, energy=None, **kwargs)

Plot the experimental data and the model prediction for the chosen Q index. Optionally also plot the individual components of the model.

Uses Plopp for plotting: https://scipp.github.io/plopp/

Parameters:

Name Type Description Default
plot_components bool

Whether to plot the individual components of the model.

True
add_background bool

Whether to add the background to the model prediction when plotting individual components.

True
plot_residuals bool

Whether to plot the residuals (data - model).

False
energy sc.Variable | None

Optional energy grid to use for plotting. If None, the energy grid from the experiment is used.

None
**kwargs dict[str, Any]

Keyword arguments to pass to the plotting function.

{}

Returns:

Type Description
InteractiveFigure

A plot of the data and model.

data_and_model_to_datagroup(energy=None, add_background=True, include_components=True, include_residuals=False)

Create a scipp DataGroup containing the experimental data, model calculation, and optionally the individual components.

Parameters:

Name Type Description Default
energy sc.Variable | None

Optional energy grid to use for the model calculation. If None, the energy grid from the experiment is used.

None
add_background bool

Whether to add the background to the model prediction when plotting individual components.

True
include_components bool

Whether to include the individual components of the model in the DataGroup. If True, the DataGroup will include a DataArray for each component with the component's display name as the key

True
include_residuals bool

Whether to include the residuals (data - model) in the DataGroup. If True, the DataGroup will include a DataArray with key 'Residuals' containing the residuals.

False

Raises:

Type Description
ValueError

If no data is available in the experiment to include in the DataGroup. If no Q values are available in the experiment to create the DataGroup. If Q_index is not set to create the DataGroup.

Returns:

Type Description
sc.DataGroup

A DataGroup containing the experimental data, model calculation, and optionally the individual components.

fix_energy_offset()

Fix the energy offset parameter for the current Q index.

free_energy_offset()

Free the energy offset parameter for the current Q index.

rebin(dimensions)

Rebin the experiment data along specified dimensions and update the analysis.

Parameters:

Name Type Description Default
dimensions dict[str, int | sc.Variable]

A dictionary mapping dimension names to number of bins (int) or bin edges (sc.Variable).

required
refresh_convolver(energy=None)

Refresh the pre-built Convolution object for the current Q index.

FitBinding(model, targets=None, display_name=None, unique_name=None)

Contract between dataset, model, and fit functions for ParameterAnalysis. A binding maps the model's fittable predictions (its FitTargets) onto keys of the parameters Dataset they should be fitted against.

Examples:

Fitting a component model to one parameter

Component models (e.g. a Polynomial) have a single prediction — their evaluate — so targets is simply the dataset key to fit against. The model's x_unit/y_unit declare the units its evaluate expects: here x is the dataset's Q coordinate and y the fitted parameter, so construct the model with matching units (or pass x_unit=None / y_unit=None to fit raw values):

import easydynamics as edyn

fit_func = edyn.Polynomial(
    coefficients=[3.7, -0.5],
    x_unit='1/angstrom',
    y_unit='meV',
    display_name='Straight line',
)
binding = edyn.FitBinding(model=fit_func, targets='Gaussian area')

Fitting a diffusion model with default dataset keys

Diffusion models declare their predictions ('area', 'width', and for DeltaLorentz also 'delta_area'). With targets=None all predictions are fitted against default dataset keys derived from the model's component names:

brownian = edyn.BrownianTranslationalDiffusion(
    diffusion_coefficient=2.4e-9,
    scale=0.5,
    lorentzian_name='Lorentzian',
)
binding = edyn.FitBinding(model=brownian)  # fits 'Lorentzian area' and 'Lorentzian width'

Selecting predictions or mapping them to custom dataset keys

Pass a list of prediction names, or a dict mapping prediction names to dataset keys:

binding = edyn.FitBinding(model=brownian, targets=['width'])

delta_lorentz = edyn.DeltaLorentz(A_0=0.5, lorentzian_width=0.1)
binding = edyn.FitBinding(
    model=delta_lorentz,
    targets={
        'width': 'Lorentzian width',
        'area': 'Lorentzian area',
        'delta_area': 'Elastic area',
    },
)

Validation raises TypeError if model or targets have an invalid type, and ValueError if targets names a prediction the model does not declare.

Parameters:

Name Type Description Default
model ModelComponent | ComponentCollection | DiffusionModelBase

The model to fit. This can be a single ModelComponent, a ComponentCollection, or a DiffusionModelBase.

required
targets str | list[str] | dict[str, str] | None

Which predictions of the model to fit, and against which dataset keys. For component models this must be a string: the dataset key to fit the model's evaluate against. For diffusion models: None fits all predictions against their default dataset keys; a string or list of strings selects predictions by name (default keys); a dict maps prediction names to custom dataset keys.

None
display_name str | None

An optional display name for the FitBinding. If None, the unique_name will be used. Default is None.

None
unique_name str | None

An optional unique name for the FitBinding. If None, a unique name will be generated. Default is None.

None

Methods:

Name Description
to_dict

Convert an EasyScience object into a full dictionary using

from_dict

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

__copy__

Return a copy of the object.

get_targets

Get the FitTargets this binding fits, with dataset keys resolved.

Attributes:

Name Type Description
unique_name str

Get the unique name of the object.

display_name str

Get a pretty display name.

name str

Get the name of the model.

model ModelComponent | ComponentCollection | DiffusionModelBase

The model to fit. This can be a single ModelComponent, a ComponentCollection, or a

targets str | list[str] | dict[str, str] | None

Which predictions of the model to fit, and against which dataset keys.

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.

name property writable

Get the name of the model.

Returns:

Type Description
str

The name of the model.

model property writable

The model to fit. This can be a single ModelComponent, a ComponentCollection, or a DiffusionModelBase.

Returns:

Type Description
ModelComponent | ComponentCollection | DiffusionModelBase

The model to fit.

targets property writable

Which predictions of the model to fit, and against which dataset keys.

Returns:

Type Description
str | list[str] | dict[str, str] | None

The targets specification (see __init__).

Methods:

to_dict(skip=None)

Convert an EasyScience object into a full dictionary using SerializerBases generic convert_to_dict method.

Parameters:

Name Type Description Default
skip Optional[List[str]]

List of field names as strings to skip when forming the dictionary. By default, None.

None

Returns:

Type Description
Dict[str, Any]

Encoded object containing all information to reform an EasyScience object.

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 SerializerDict) of an EasyScience object.

required

Returns:

Type Description
NewBase

Reformed EasyScience object.

Raises:

Type Description
ValueError

If the input dictionary does not describe the expected class.

__copy__()

Return a copy of the object.

get_targets()

Get the FitTargets this binding fits, with dataset keys resolved.

Targets are built from the model at call time, so their units and default dataset keys reflect the model's current state.

Returns:

Type Description
list[FitTarget]

The resolved fit targets.

ParameterAnalysis(parameters=None, bindings=None, display_name='ParameterAnalysis', unique_name=None)

For analysing fitted parameters.

Can be used to fit parameters to ModelComponents, ComponentCollections, or DiffusionModelBase objects, and to plot the parameters and fit results. The parameters to be analyzed can be provided as a sc.Dataset or directly as an Analysis object. Multiple parameters can be fitted simultaneously, and each binding maps its model's predictions onto the dataset keys they are fitted against (for diffusion models e.g. 'area', 'width', or 'delta_area').

Examples:

Fitting Lorentzian widths to a diffusion model

After a full Analysis fit, pass the Analysis directly and bind the model's predictions to dataset keys using a FitBinding:

import easydynamics as edyn

# analysis is an edyn.Analysis object with previously fitted parameters
diffusion_model = edyn.BrownianTranslationalDiffusion(diffusion_coefficient=2.4e-9, scale=0.5)
binding = edyn.FitBinding(
    model=diffusion_model,
    targets={'width': 'Lorentzian width'},
)

param_analysis = edyn.ParameterAnalysis(
    parameters=analysis,
    bindings=binding,
)
param_analysis.fit()
param_analysis.plot()

Fitting multiple parameters with separate bindings

Component models declare the units their evaluate expects: here the Polynomial's x is the dataset's Q coordinate and its y is the fitted parameter, so construct it with matching units (or pass x_unit=None / y_unit=None to fit raw values):

area_binding = edyn.FitBinding(
    model=edyn.Polynomial(coefficients=[0.5, 0.0], x_unit='1/angstrom', y_unit='meV'),
    targets='Lorentzian area',
)
param_analysis = edyn.ParameterAnalysis(
    parameters=analysis,
    bindings=[binding, area_binding],
)
param_analysis.fit()

Parameters:

Name Type Description Default
parameters sc.Dataset | Analysis | None

The parameters to analyze. Can be provided as a sc.Dataset or as an Analysis (in which case the parameters will be extracted from the Analysis).

None
bindings FitBinding | list[FitBinding] | None

The fit bindings to use for fitting the parameters. Can be a single FitBinding or a list of FitBindings. If None, no fit bindings are provided.

None
display_name str | None

Display name of the analysis.

'ParameterAnalysis'
unique_name str | None

Unique name of the analysis. If None, a unique name is automatically generated. By default, None.

None

Methods:

Name Description
to_dict

Convert an EasyScience object into a full dictionary using

from_dict

Re-create an EasyScience object with DescriptorNumber attributes

__copy__

Return a copy of the object.

get_all_parameters

Get all Parameter objects as a list.

get_fittable_parameters

Get all parameters which can be fitted as a list.

get_free_parameters

Get all parameters which are currently free to be fitted as a

get_fit_parameters

This is an alias for get_free_parameters.

fit

Fit the parameters using the specified fit functions and settings.

plot

Plot the parameters and fit results.

calculate_model_dataset

Evaluate all bindings into a sc.Dataset of model predictions.

append_binding

Append a FitBinding to the list of bindings for the parameter analysis.

clear_bindings

Clear all FitBindings from the list of bindings for the parameter analysis.

get_all_variables

Get all variables from the fit functions.

Attributes:

Name Type Description
unique_name str

Get the unique name of the object.

display_name str

Get a pretty display name.

name str

Get the name of the model.

x_unit str | sc.Unit | None

Get the unit of the x-axis.

y_unit str | sc.Unit | None

Get the unit of the model output.

parameters sc.Dataset | None

Get the parameters for the parameter analysis.

bindings list[FitBinding]

Get the fit bindings for the parameter analysis.

fitter MultiFitter

The EasyScience MultiFitter over the binding models, built on first use.

bayesian PosteriorSampler

Bayesian posterior sampling for this analysis, created on first use.

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.

name property writable

Get the name of the model.

Returns:

Type Description
str

The name of the model.

x_unit property writable

Get the unit of the x-axis.

Returns:

Type Description
str | sc.Unit | None

The unit of the x-axis.

y_unit property writable

Get the unit of the model output.

Returns:

Type Description
str | sc.Unit | None

The unit of the y-axis.

parameters property writable

Get the parameters for the parameter analysis.

Returns:

Type Description
sc.Dataset | None

The parameters for the parameter analysis.

bindings property writable

Get the fit bindings for the parameter analysis.

Returns:

Type Description
list[FitBinding]

The fit bindings for the parameter analysis.

fitter property

The EasyScience MultiFitter over the binding models, built on first use.

Returns:

Type Description
MultiFitter

The cached MultiFitter.

bayesian property

Bayesian posterior sampling for this analysis, created on first use.

Returns:

Type Description
PosteriorSampler

The sampler, which holds any chain that has been run.

Methods:

to_dict(skip=None)

Convert an EasyScience object into a full dictionary using SerializerBases generic convert_to_dict method.

Parameters:

Name Type Description Default
skip Optional[List[str]]

List of field names as strings to skip when forming the dictionary. By default, None.

None

Returns:

Type Description
Dict[str, Any]

Encoded object containing all information to reform an EasyScience object.

from_dict(obj_dict) classmethod

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

Parameters:

Name Type Description Default
obj_dict Dict[str, Any]

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

required

Returns:

Type Description
ModelBase

Reformed EasyScience object.

Raises:

Type Description
SyntaxError

If a deserialized parameter cannot be attached back to the class definition.

ValueError

If the input dictionary does not describe the expected class.

__copy__()

Return a copy of the object.

get_all_parameters()

Get all Parameter objects as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fittable_parameters()

Get all parameters which can be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_free_parameters()

Get all parameters which are currently free to be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fit_parameters()

This is an alias for get_free_parameters.

To be removed when fully moved to new base classes and minimizer can be changed.

fit()

Fit the parameters using the specified fit functions and settings.

A ValueError is raised if no parameters Dataset is provided, if no fit bindings are provided, or if a binding names a dataset key that is not in the parameters Dataset.

Returns:

Type Description
FitResults

The results of the fit

plot(names=None, **kwargs)

Plot the parameters and fit results.

Parameters:

Name Type Description Default
names str | list[str] | None

The names of the parameters to plot. If None, all parameters with bindings are plotted.

None
**kwargs dict[str, Any]

Additional keyword arguments to pass to the plotting function.

{}

Returns:

Type Description
InteractiveFigure

An interactive figure containing the plots of the parameters and fit results.

Raises:

Type Description
ValueError

If the units of the specified parameters are not consistent.

RuntimeError

If plot() is called outside of a Jupyter notebook environment.

calculate_model_dataset(bindings)

Evaluate all bindings into a sc.Dataset of model predictions.

Parameters:

Name Type Description Default
bindings list[FitBinding]

The bindings to evaluate.

required

Returns:

Type Description
sc.Dataset

A sc.Dataset containing the model predictions for all bindings.

Raises:

Type Description
ValueError

If any parameter name from the bindings is not found in the parameters Dataset.

TypeError

If bindings is not a list of FitBinding objects.

append_binding(binding)

Append a FitBinding to the list of bindings for the parameter analysis.

Parameters:

Name Type Description Default
binding FitBinding

The FitBinding to append.

required

Raises:

Type Description
TypeError

If binding is not a FitBinding object.

clear_bindings()

Clear all FitBindings from the list of bindings for the parameter analysis.

get_all_variables()

Get all variables from the fit functions.

Returns:

Type Description
list

A list of all variables from the fit functions.

BoundsSuggestion(parameter, label, suggested_min, suggested_max, reason) dataclass

A proposed pair of bounds for a single parameter.

Attributes:

Name Type Description
parameter Parameter

The parameter the suggestion applies to.

label str

The name the parameter is reported under. For a multi-Q analysis this is qualified by Q, since every Q holds an identically named copy of each parameter.

suggested_min float

The proposed lower bound. Equal to the parameter's current lower bound when that is already finite.

suggested_max float

The proposed upper bound. Equal to the parameter's current upper bound when that is already finite.

reason str

Empty when the suggestion is usable. Otherwise, why the parameter needs manual attention.

Attributes

needs_attention property

Whether this parameter could not be given a usable suggestion.

Returns:

Type Description
bool

True when no usable bounds could be derived and the user must set them by hand.

changes_bounds property

Whether applying this suggestion would actually change the parameter.

Returns:

Type Description
bool

True when either bound differs from the parameter's current bound.

BoundsSuggestions(suggestions)

The result of :func:suggest_bounds_for_parameters, rendered as a table.

This is advisory: nothing is changed until :meth:apply is called. Suggestions only ever fill in an infinite bound; a bound that is already finite is never widened or narrowed, so physical limits such as a non-negative area survive untouched.

Parameters:

Name Type Description Default
suggestions list[BoundsSuggestion]

The per-parameter suggestions.

required

Methods:

Name Description
apply

Set the suggested bounds on every parameter that has a usable suggestion.

__len__

Return the number of suggestions.

__iter__

Iterate over the suggestions.

Attributes:

Name Type Description
suggestions list[BoundsSuggestion]

All suggestions, including those needing manual attention.

needing_attention list[BoundsSuggestion]

The suggestions for which no usable bounds could be derived.

Attributes

suggestions property

All suggestions, including those needing manual attention.

Returns:

Type Description
list[BoundsSuggestion]

The per-parameter suggestions.

needing_attention property

The suggestions for which no usable bounds could be derived.

Returns:

Type Description
list[BoundsSuggestion]

Suggestions whose parameters must be bounded by hand.

Methods:

apply()

Set the suggested bounds on every parameter that has a usable suggestion.

Parameters needing manual attention are skipped rather than guessed at. A suggestion that is absurdly wide is still applied -- it is what the fit implied -- but warned about, since reading the table first is easy to skip in a script.

Returns:

Type Description
list[Parameter]

The parameters whose bounds were changed.

__len__()

Return the number of suggestions.

Returns:

Type Description
int

The number of suggestions.

__iter__()

Iterate over the suggestions.

Returns:

Type Description
iter

An iterator over the suggestions.

ParameterPosterior(name, unit, median, lower, upper, value) dataclass

The marginal posterior of a single parameter.

Attributes:

Name Type Description
name str

The parameter's name.

unit str

The parameter's unit, as a string.

median float

The 50th percentile of the marginal posterior.

lower float

The 16th percentile.

upper float

The 84th percentile.

value float

The parameter's current value, for comparison with the median.

Attributes

minus property

Distance from the median down to the 16th percentile.

Returns:

Type Description
float

The lower half of the 68% credible interval.

plus property

Distance from the median up to the 84th percentile.

Returns:

Type Description
float

The upper half of the 68% credible interval.

PosteriorSummary(entries)

Marginal posterior summaries for every sampled parameter, rendered as a table.

Parameters:

Name Type Description Default
entries list[ParameterPosterior]

One entry per sampled parameter.

required

Methods:

Name Description
__len__

Return the number of summarized parameters.

__iter__

Iterate over the entries.

__getitem__

Look up a parameter's summary by name.

Attributes:

Name Type Description
entries list[ParameterPosterior]

The per-parameter summaries.

Attributes

entries property

The per-parameter summaries.

Returns:

Type Description
list[ParameterPosterior]

One entry per sampled parameter.

Methods:

__len__()

Return the number of summarized parameters.

Returns:

Type Description
int

The number of entries.

__iter__()

Iterate over the entries.

Returns:

Type Description
iter

An iterator over the entries.

__getitem__(name)

Look up a parameter's summary by name.

Parameters:

Name Type Description Default
name str

The parameter name.

required

Returns:

Type Description
ParameterPosterior

The summary for that parameter.

Raises:

Type Description
KeyError

If no sampled parameter has that name.

ParameterLabels(parameters, qualify=None)

Readable labels and units for the columns of a chain.

Built once for a fixed set of parameters, so the name counts and lookups are computed a single time. Doing this per column instead is quadratic in the parameter count, which is seconds of work for an analysis with many Q values.

Parameters:

Name Type Description Default
parameters list[Parameter]

The parameters that can appear as columns.

required
qualify Callable[[Parameter], str | None] | None

Returns a qualifier for a parameter whose name is shared with another, for example its Q index. Only consulted when the bare name really is ambiguous, so an analysis with nothing to disambiguate keeps its short names. Returning None leaves the name unqualified.

None

Methods:

Name Description
label

Get the label a parameter is reported under.

name_map

Map each parameter's unique_name to its label.

resolve

Match each column of a chain to a parameter.

display_names

Get a readable label for each column of a chain.

units

Get the unit of each column of a chain.

Attributes:

Name Type Description
parameters list[Parameter]

The parameters these labels describe.

Attributes

parameters property

The parameters these labels describe.

Returns:

Type Description
list[Parameter]

The parameters given at construction.

Methods:

label(parameter)

Get the label a parameter is reported under.

Parameters:

Name Type Description Default
parameter Parameter

The parameter to label.

required

Returns:

Type Description
str

The parameter's name, qualified only where that name is shared with another parameter.

name_map()

Map each parameter's unique_name to its label.

Saved alongside a chain, because unique names are per-session: without this a reloaded chain cannot be matched back to any parameter. Where two parameters share a display label, the recorded labels carry a deterministic positional suffix (width [1], width [2]) so each column can be matched back to exactly one parameter.

Returns:

Type Description
dict[str, str]

Mapping of unique name to label, collision-free.

resolve(column_names, saved_labels=None)

Match each column of a chain to a parameter.

Columns are matched on unique_name first. That fails for a chain loaded from disk, where the saved labels are used instead.

Parameters:

Name Type Description Default
column_names list[str]

The sampler's name for each column.

required
saved_labels dict[str, str] | None

Mapping of unique name to label, as recorded when a chain was saved.

None

Returns:

Type Description
list[Parameter | None]

The parameter for each column, or None where no match could be made.

display_names(column_names, saved_labels=None)

Get a readable label for each column of a chain.

Parameters:

Name Type Description Default
column_names list[str]

The sampler's name for each column.

required
saved_labels dict[str, str] | None

Mapping of unique name to label, as recorded when a chain was saved.

None

Returns:

Type Description
list[str]

One label per column, falling back to the saved label and then to the raw column name.

units(column_names, saved_labels=None)

Get the unit of each column of a chain.

Parameters:

Name Type Description Default
column_names list[str]

The sampler's name for each column.

required
saved_labels dict[str, str] | None

Mapping of unique name to label, as recorded when a chain was saved.

None

Returns:

Type Description
list[str]

One unit per column, empty where no parameter could be matched.

MultiQPosteriorSampler(per_q, **kwargs)

Posterior sampling for an Analysis covering several Q values.

Reached as analysis.bayesian. Sampling can run either way round:

  • fit_method='independent' gives each Q index its own chain, which is cheaper and keeps the Q values from influencing one another.
  • fit_method='simultaneous' runs a single chain over every Q at once, which is what is needed when parameters are shared across Q, and costs considerably more: DREAM runs a number of chains proportional to the parameter count, and a simultaneous run has every Q's parameters in play together.

Results from independent runs stay on the per-Q samplers. This class gathers them where gathering is sound, and declines where it is not; see :meth:summary and :meth:plot_corner.

Parameters:

Name Type Description Default
per_q Callable[[], list]

Returns the per-Q Analysis objects, each exposing Q_index and its own bayesian.

required
**kwargs dict[str, Any]

Forwarded to :class:PosteriorSampler.

{}

Methods:

Name Description
invalidate

Mark the underlying Sampler as needing a rebuild.

suggest_bounds

Propose finite bounds for free parameters that still have an infinite one.

check_bounds

Verify that every free parameter has finite bounds.

load

Load a previously saved MCMC chain.

predictions

Evaluate the model once per posterior draw, restoring the parameters afterwards.

sample

Draw samples from the posterior, per Q index or over all of them at once.

extend

Continue the existing simultaneous chain with additional samples.

save

Save the simultaneous MCMC chain to disk.

summary

Summarize the posterior, gathering the per-Q chains when sampling was independent.

set_parameters_to_median

Set every sampled parameter to the median of its marginal posterior.

plot_corner

Plot the marginal and pairwise posterior distributions.

plot_trace

Plot the chain trace of each sampled parameter.

plot_marginal

Plot the marginal posterior distribution of a single sampled 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.

Attributes:

Name Type Description
sampler Sampler | None

The EasyScience Sampler holding the chain, or None before the first run.

results SamplingResults | None

The results of the most recent run, or None if there has not been one.

results_per_q list[SamplingResults | None] | None

The per-Q chains from independent sampling, or None if there are none.

Attributes

sampler property

The EasyScience Sampler holding the chain, or None before the first run.

Returns:

Type Description
Sampler | None

The cached Sampler.

results property

The results of the most recent run, or None if there has not been one.

Returns:

Type Description
SamplingResults | None

The most recent sampling results.

results_per_q property

The per-Q chains from independent sampling, or None if there are none.

A simultaneous run produces one chain covering every Q, which is on :attr:results.

Returns:

Type Description
list[SamplingResults | None] | None

One entry per Q index, None where that Q has not been sampled, or None overall if no Q index has been sampled.

Methods:

invalidate()

Mark the underlying Sampler as needing a rebuild.

Called by the Analysis when its data changes, since the Sampler binds its data at construction.

suggest_bounds(n_sigma=10.0, relative_pad=0.2, absolute_floor=None)

Propose finite bounds for free parameters that still have an infinite one.

Nothing changes until :meth:BoundsSuggestions.apply is called, so the proposal can be reviewed first. Bounds that are already finite are never widened or narrowed, so physical limits such as a non-negative area are left alone.

Because the bounds act as a uniform prior in DREAM, a generous width is the safe choice: too tight a bound truncates the posterior and understates the uncertainty.

Parameters:

Name Type Description Default
n_sigma float

How many standard deviations of the fitted uncertainty to allow on each side.

10.0
relative_pad float

Extra half-width as a fraction of the absolute parameter value, guarding against minimizers that report a zero or absurdly small uncertainty.

0.2
absolute_floor float | None

A minimum half-width in the parameter's own units, for when neither the uncertainty nor the value carries the natural scale.

None

Returns:

Type Description
BoundsSuggestions

The proposed bounds, which must be applied explicitly.

check_bounds()

Verify that every free parameter has finite bounds.

Raises:

Type Description
ValueError

If any free parameter has an infinite lower or upper bound, or finite bounds that enclose no range (min >= max).

load(path, skip=0)

Load a previously saved MCMC chain.

The loaded chain can be summarized, plotted, or continued with :meth:extend.

Parameters:

Name Type Description Default
path str | os.PathLike

The path prefix the chain was saved under.

required
skip int

Number of initial samples to skip when reading the chain.

0

Returns:

Type Description
SamplingResults

The loaded results, also stored on :attr:results.

predictions(n_draws=200)

Evaluate the model once per posterior draw, restoring the parameters afterwards.

Parameters:

Name Type Description Default
n_draws int

How many draws to evaluate, taken evenly across the chain.

200

Returns:

Type Description
np.ndarray

Model evaluations, shape (n_selected, len(x)).

sample(samples=10000, burn=2000, thin=10, fit_method='independent', Q_index=None, **sampler_options)

Draw samples from the posterior, per Q index or over all of them at once.

Parameters:

Name Type Description Default
samples int

Number of raw samples to draw across all chains, before thinning.

10000
burn int

Burn-in generations to discard before collecting samples.

2000
thin int

Thinning interval, which reduces autocorrelation between retained draws.

10
fit_method str

Either "independent" (a separate chain per Q index) or "simultaneous" (one chain over all Q indices at once).

'independent'
Q_index int | None

With fit_method='independent', sample only this Q index. Ignored when sampling simultaneously.

None
**sampler_options dict[str, Any]

Forwarded to the underlying sampler.

{}

Returns:

Type Description
SamplingResults | list[SamplingResults]

A single result when a specific Q index was sampled or when sampling simultaneously, and otherwise one result per Q index.

Raises:

Type Description
ValueError

If fit_method is not "independent" or "simultaneous", or there are no Q values.

Notes

An IndexError or TypeError propagates from the Q_index validation if Q_index is out of range or not an int.

extend(additional_samples=5000, thin=10, parameters=None, **sampler_options)

Continue the existing simultaneous chain with additional samples.

The chains from independent sampling live on the per-Q samplers, so each is extended there rather than here.

Parameters:

Name Type Description Default
additional_samples int

Number of additional samples to draw, in the same units as samples.

5000
thin int

Thinning interval for the retained draws.

10
parameters list[Parameter] | list[str] | None

The same restriction as in :meth:PosteriorSampler.extend.

None
**sampler_options dict[str, Any]

Forwarded to the EasyScience Sampler.

{}

Returns:

Type Description
SamplingResults

The sampling results for the full extended chain.

Raises:

Type Description
RuntimeError

If the latest sampling ran per Q index, so there is no simultaneous chain here to extend, or if there is no chain at all.

Notes

A ValueError propagates from the run guards if the model or data changed since the chain was started, or if this run's parameters differ from the ones the chain holds.

save(path)

Save the simultaneous MCMC chain to disk.

The chains from independent sampling live on the per-Q samplers, so each is saved there rather than here.

Parameters:

Name Type Description Default
path str | os.PathLike

Path prefix for the chain files.

required

Raises:

Type Description
RuntimeError

If the latest sampling ran per Q index -- there is then no simultaneous chain here to save -- or if there is no chain at all.

summary(labeller=None)

Summarize the posterior, gathering the per-Q chains when sampling was independent.

Every entry is a marginal distribution of one parameter, and a marginal is well defined within its own chain, so collecting them into one table is sound even though the chains are separate. Labels carry the Q index either way, so the table reads the same.

Parameters:

Name Type Description Default
labeller Callable[[Parameter], str] | None

Overrides the label a resolved column is reported under. The default is this analysis' own Q-qualified labels.

None

Returns:

Type Description
PosteriorSummary

One entry per sampled parameter, across every Q index that has been sampled.

set_parameters_to_median()

Set every sampled parameter to the median of its marginal posterior.

Applies the per-Q chains to their own Q when sampling was independent.

Returns:

Type Description
list[Parameter]

The parameters that were changed.

plot_corner(Q_index=None, **kwargs)

Plot the marginal and pairwise posterior distributions.

After independent sampling each Q has its own chain, and no draw pairs a parameter at one Q with a parameter at another, so there is no joint distribution across Q to plot. Rather than combine them into a figure showing correlations that came from how the sampling was run, this steps through the chains one at a time: pick one with Q_index, or leave it out in a notebook to get a slider.

Parameters:

Name Type Description Default
Q_index int | None

Which Q index to plot, when the chains are per-Q. If None, a slider is returned. Not used for a simultaneous chain, which already covers every Q.

None
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_corner.

{}

Returns:

Type Description
Figure | VBox

The matplotlib Figure, or an ipywidgets box with a Q slider.

Raises:

Type Description
RuntimeError

If a slider is asked for outside a notebook.

Notes

An IndexError or TypeError propagates from the Q_index validation if Q_index is out of range or not an int.

plot_trace(Q_index=None, **kwargs)

Plot the chain trace of each sampled parameter.

A simultaneous chain is one trace and is drawn directly. After independent sampling each Q index has its own chain, so the traces are stepped through one at a time: pick one with Q_index, or leave it out in a notebook to get a slider.

Parameters:

Name Type Description Default
Q_index int | None

Which Q index to plot, when the chains are per-Q. If None, a slider is returned. Not used for a simultaneous chain, which is a single trace already.

None
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_trace.

{}

Returns:

Type Description
Figure | VBox

The matplotlib Figure, or an ipywidgets box with a Q slider.

Notes

A RuntimeError propagates if a slider is asked for outside a notebook or nothing has been sampled yet, and an IndexError or TypeError from the Q_index validation if Q_index is out of range or not an int.

plot_marginal(parameter, Q_index=None, **kwargs)

Plot the marginal posterior distribution of a single sampled parameter.

A simultaneous chain holds every Q's parameters under Q-qualified labels, so the label picks the Q as well ('Gaussian width (Q_index=1)'). After independent sampling the chains are per-Q and the parameter goes by its plain label in each; pick a chain with Q_index, or leave it out in a notebook to step through the Q values with a slider.

Parameters:

Name Type Description Default
parameter Parameter | str

The parameter to plot, as a Parameter object or its label. On the slider path a Parameter object is resolved to its display name first, so the matching parameter of every Q is shown even though the object itself belongs to one Q.

required
Q_index int | None

Which Q index to plot, when the chains are per-Q. If None, a slider is returned. Not used for a simultaneous chain, whose labels carry the Q index already.

None
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_marginal.

{}

Returns:

Type Description
Figure | VBox

The matplotlib Figure, or an ipywidgets box with a Q slider.

Notes

A ValueError propagates if the parameter matches no sampled chain column, a RuntimeError if a slider is asked for outside a notebook or nothing has been sampled yet, and an IndexError or TypeError from the Q_index validation if Q_index is out of range or not an int.

plot_correlations(Q_index=None, **kwargs)

Plot the Pearson correlation matrix of the sampled parameters.

A simultaneous chain gives one matrix over every Q's parameters at once. After independent sampling no draw pairs one Q with another, so there is one matrix per chain: pick one with Q_index, or leave it out in a notebook to get a slider.

Parameters:

Name Type Description Default
Q_index int | None

Which Q index to plot, when the chains are per-Q. If None, a slider is returned. Not used for a simultaneous chain, which already covers every Q.

None
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_correlations.

{}

Returns:

Type Description
Figure | VBox

The matplotlib Figure, or an ipywidgets box with a Q slider.

Notes

A RuntimeError propagates if a slider is asked for outside a notebook or nothing has been sampled yet, and an IndexError or TypeError from the Q_index validation if Q_index is out of range or not an int.

plot_posterior_predictive(n_draws=200, credible_interval=68.0, Q_index=None, **kwargs)

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

After independent sampling each Q has its own chain, and its own band: pick one with Q_index for a single matplotlib figure, or leave it out in a notebook to get a plopp figure with a Q slider, looking and handling exactly like Analysis.plot_data_and_model. Plopp draws no filled band, so the slider view shows the posterior median with a dashed line along each band edge instead of a shaded band.

Parameters:

Name Type Description Default
n_draws int

How many posterior draws to evaluate the model for, per Q on the slider path. Each costs a full model evaluation.

200
credible_interval float

Width of the credible band, as a percentage.

68.0
Q_index int | None

Which Q index to plot, when the chains are per-Q. If None, a slider is returned.

None
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_posterior_predictive for a single figure, or to :func:easydynamics.utils.posterior_plotting.predictive_with_slider for the slider.

{}

Returns:

Type Description
Figure | InteractiveFigure

The matplotlib Figure for one Q, or the plopp figure with a Q slider.

Raises:

Type Description
ValueError

If n_draws is not a positive integer, or credible_interval is out of range.

Notes

A NotImplementedError propagates when the latest chain is simultaneous: it binds every dataset at once, and no per-Q chain exists for Q_index to pick out. A RuntimeError propagates if a slider is asked for outside a notebook or nothing has been sampled yet, and an IndexError or TypeError from the Q_index validation if Q_index is out of range or not an int.

PosteriorSampler(analysis, sampling_data, chain_parameters, parameter_labels, prepare=None)

Draws samples from the posterior distribution of an Analysis' free parameters.

Reached as analysis.bayesian. Sampling explores the whole posterior rather than reporting a single best-fit point, which is worth doing when parameters are correlated or their uncertainties are strongly non-Gaussian, both common in QENS.

Running a fit first is not required, but it helps: DREAM seeds its population in a small ball around the parameters' current values, so starting from fitted values shortens the burn-in.

The Analysis passes in everything that differs between the Analysis classes, so this class needs no knowledge of how any of them is built.

Parameters:

Name Type Description Default
analysis object

The Analysis being sampled, used for its display_name and its fitter.

required
sampling_data Callable[[], tuple]

Returns the (x, y, weights) to bind to the sampler. Each is an array, or a list of arrays for a multi-dataset fit.

required
chain_parameters Callable[[], list[Parameter]]

Returns the free parameters that will form the chain's columns.

required
parameter_labels Callable[[], ParameterLabels]

Returns labels for those parameters.

required
prepare Callable[[], None] | None

Brings any cached computation on the Analysis up to date before a run.

None

Notes

Every free parameter must have finite bounds before sampling, because in DREAM the bounds are the prior. :meth:suggest_bounds proposes bounds for any parameter still missing one.

Examples:

analysis.fit()
analysis.bayesian.suggest_bounds().apply()
analysis.bayesian.sample(samples=10000, burn=2000, thin=10)
analysis.bayesian.summary()

Methods:

Name Description
invalidate

Mark the underlying Sampler as needing a rebuild.

suggest_bounds

Propose finite bounds for free parameters that still have an infinite one.

check_bounds

Verify that every free parameter has finite bounds.

sample

Draw samples from the posterior distribution of the free parameters.

extend

Continue the existing chain with additional samples.

summary

Summarize the marginal posterior of each sampled parameter.

set_parameters_to_median

Set every sampled parameter to the median of its marginal posterior.

save

Save the MCMC chain to disk.

load

Load a previously saved MCMC chain.

plot_trace

Plot the chain trace of each sampled parameter.

plot_corner

Plot the marginal and pairwise posterior distributions.

plot_marginal

Plot the marginal posterior distribution of a single sampled 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.

predictions

Evaluate the model once per posterior draw, restoring the parameters afterwards.

Attributes:

Name Type Description
sampler Sampler | None

The EasyScience Sampler holding the chain, or None before the first run.

results SamplingResults | None

The results of the most recent run, or None if there has not been one.

Attributes

sampler property

The EasyScience Sampler holding the chain, or None before the first run.

Returns:

Type Description
Sampler | None

The cached Sampler.

results property

The results of the most recent run, or None if there has not been one.

Returns:

Type Description
SamplingResults | None

The most recent sampling results.

Methods:

invalidate()

Mark the underlying Sampler as needing a rebuild.

Called by the Analysis when its data changes, since the Sampler binds its data at construction.

suggest_bounds(n_sigma=10.0, relative_pad=0.2, absolute_floor=None)

Propose finite bounds for free parameters that still have an infinite one.

Nothing changes until :meth:BoundsSuggestions.apply is called, so the proposal can be reviewed first. Bounds that are already finite are never widened or narrowed, so physical limits such as a non-negative area are left alone.

Because the bounds act as a uniform prior in DREAM, a generous width is the safe choice: too tight a bound truncates the posterior and understates the uncertainty.

Parameters:

Name Type Description Default
n_sigma float

How many standard deviations of the fitted uncertainty to allow on each side.

10.0
relative_pad float

Extra half-width as a fraction of the absolute parameter value, guarding against minimizers that report a zero or absurdly small uncertainty.

0.2
absolute_floor float | None

A minimum half-width in the parameter's own units, for when neither the uncertainty nor the value carries the natural scale.

None

Returns:

Type Description
BoundsSuggestions

The proposed bounds, which must be applied explicitly.

check_bounds()

Verify that every free parameter has finite bounds.

Raises:

Type Description
ValueError

If any free parameter has an infinite lower or upper bound, or finite bounds that enclose no range (min >= max).

sample(samples=10000, burn=2000, thin=10, population=None, parameters=None, progress=False, **sampler_options)

Draw samples from the posterior distribution of the free parameters.

Starts a fresh chain, replacing any existing one; use :meth:extend to continue one. Parameter values are restored afterwards, so sampling never silently moves the model off its fitted values; use :meth:set_parameters_to_median to adopt the posterior.

Parameters:

Name Type Description Default
samples int

Number of raw samples to draw across all chains, before thinning. A guaranteed minimum rather than an exact count.

10000
burn int

Burn-in generations to discard before collecting samples.

2000
thin int

Thinning interval, which reduces autocorrelation between retained draws.

10
population int | None

DREAM population scale factor: BUMPS runs ceil(population * n_parameters) chains.

None
parameters list[Parameter] | list[str] | None

Restrict the chain to these parameters, given as Parameter objects or labels. All other free parameters are held fixed for the run. Holding a parameter fixed is not the same as marginalizing over it: the resulting intervals are conditional on those values and will be too narrow if the parameters are correlated. The default samples everything.

None
progress bool

Print a progress line, redrawn in place as the sampler advances and closed with a done marker when the run finishes. Off by default so scripted runs stay quiet; a progress_callback given in sampler_options takes precedence over it.

False
**sampler_options dict[str, Any]

Forwarded to the EasyScience Sampler, e.g. sampler_kwargs or progress_callback.

{}

Returns:

Type Description
SamplingResults

The sampling results, also stored on :attr:results.

Notes

Runs are not reproducible. BUMPS' DREAM sampler draws from NumPy's global random state and the underlying EasyScience Sampler exposes no seed control, so two identical calls return two different chains. Their summaries should nevertheless agree to well within the reported credible intervals; if they do not, the chain is too short to have converged.

extend(additional_samples=5000, thin=10, parameters=None, progress=False, **sampler_options)

Continue the existing chain with additional samples.

Parameters:

Name Type Description Default
additional_samples int

Number of additional samples to draw, in the same units as samples.

5000
thin int

Thinning interval for the retained draws.

10
parameters list[Parameter] | list[str] | None

The same restriction as in :meth:sample. It must leave the chain the same width, since BUMPS resumes from a stored chain whose columns are fixed.

None
progress bool

Print a progress line, redrawn in place as the sampler advances, as in :meth:sample.

False
**sampler_options dict[str, Any]

Forwarded to the EasyScience Sampler.

{}

Returns:

Type Description
SamplingResults

The sampling results for the full extended chain.

Raises:

Type Description
RuntimeError

If there is no chain to extend, or the previous run failed and left no results.

Notes

A ValueError propagates from the run guards if the model or data changed since the chain was started, or if this run's parameters differ from the ones the chain holds.

Like :meth:sample, extensions are not reproducible: the sampler draws from NumPy's global random state and exposes no seed control.

summary(labeller=None)

Summarize the marginal posterior of each sampled parameter.

Reports the median and the 68% credible interval under the parameter's own label and unit.

Parameters:

Name Type Description Default
labeller Callable[[Parameter], str] | None

Overrides the label a resolved column is reported under. Used by an Analysis covering several Q values, whose gathered table qualifies each name with its Q index. Columns that resolve to no parameter keep their usual fallback name.

None

Returns:

Type Description
PosteriorSummary

One entry per sampled parameter.

set_parameters_to_median()

Set every sampled parameter to the median of its marginal posterior.

The vector of marginal medians is not in general the highest-posterior point, and for strongly correlated parameters need not even be a good fit.

Returns:

Type Description
list[Parameter]

The parameters that were changed.

save(path)

Save the MCMC chain to disk.

Writes the BUMPS chain files plus a sidecar recording the column labels, because the unique names BUMPS stores are per-session and cannot be matched up again on their own.

Parameters:

Name Type Description Default
path str | os.PathLike

Path prefix for the chain files.

required

Raises:

Type Description
RuntimeError

If there is no chain to save.

load(path, skip=0)

Load a previously saved MCMC chain.

The loaded chain can be summarized, plotted, or continued with :meth:extend.

Parameters:

Name Type Description Default
path str | os.PathLike

The path prefix the chain was saved under.

required
skip int

Number of initial samples to skip when reading the chain.

0

Returns:

Type Description
SamplingResults

The loaded results, also stored on :attr:results.

plot_trace(**kwargs)

Plot the chain trace of each sampled parameter.

Parameters:

Name Type Description Default
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_trace.

{}

Returns:

Type Description
Figure

The matplotlib Figure.

plot_corner(**kwargs)

Plot the marginal and pairwise posterior distributions.

Parameters:

Name Type Description Default
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_corner.

{}

Returns:

Type Description
Figure

The matplotlib Figure.

plot_marginal(parameter, **kwargs)

Plot the marginal posterior distribution of a single sampled 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 :meth:summary reports.

Parameters:

Name Type Description Default
parameter Parameter | str

The parameter to plot, as a Parameter object or its label.

required
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_marginal.

{}

Returns:

Type Description
Figure

The matplotlib Figure.

plot_correlations(**kwargs)

Plot the Pearson correlation matrix of the sampled parameters.

A strongly correlated pair cannot be determined separately from this data. The matrix condenses what the off-diagonal panels of :meth:plot_corner show, one number per pair, which scales better to many parameters.

Parameters:

Name Type Description Default
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_correlations.

{}

Returns:

Type Description
Figure

The matplotlib Figure.

plot_posterior_predictive(n_draws=200, credible_interval=68.0, **kwargs)

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

Parameters:

Name Type Description Default
n_draws int

How many posterior draws to evaluate the model for. Each costs a full model evaluation.

200
credible_interval float

Width of the credible band, as a percentage.

68.0
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_posterior_predictive.

{}

Returns:

Type Description
Figure

The matplotlib Figure.

Raises:

Type Description
NotImplementedError

If this Analysis binds a list of datasets rather than a single one.

ValueError

If n_draws is not a positive integer.

predictions(n_draws=200)

Evaluate the model once per posterior draw, restoring the parameters afterwards.

Parameters:

Name Type Description Default
n_draws int

How many draws to evaluate, taken evenly across the chain.

200

Returns:

Type Description
np.ndarray

Model evaluations, shape (n_selected, len(x)).

Modules

analysis

Classes:

Name Description
Analysis

For analysing two-dimensional data, i.e. intensity as function of energy and Q.

Classes

Analysis(display_name='MyAnalysis', unique_name=None, experiment=None, sample_model=None, instrument_model=None, convolution_settings=None, detailed_balance_settings=None, extra_parameters=None)

For analysing two-dimensional data, i.e. intensity as function of energy and Q.

Supports independent fits of each Q value and simultaneous fits of all Q.

Besides least-squares fitting with :meth:fit, the posterior distribution of the free parameters can be explored through :attr:bayesian; see :class:~easydynamics.analysis.posterior_sampling.MultiQPosteriorSampler.

Examples:

Fitting vanadium data for instrument calibration

The standard workflow builds a sample model, resolution model, background model, and instrument model, then combines them into an Analysis before fitting:

import pooch
import easydynamics as edyn

file_path = pooch.retrieve(
    url='https://github.com/easyscience/dynamics-lib/raw/refs/heads/master/docs/docs/tutorials/data/vanadium_data_example.h5',
    known_hash='16cc1b327c303feeb88fb9dda5390dc4880b62396b1793f98c6fef0b27c7b873',
)
experiment = edyn.Experiment('Vanadium')
experiment.load_hdf5(filename=file_path)

sample_model = edyn.SampleModel(components=edyn.DeltaFunction(area=1))
resolution_model = edyn.ResolutionModel(components=edyn.Gaussian(width=0.1))
background_model = edyn.BackgroundModel(components=edyn.Polynomial(coefficients=[0.001]))
instrument_model = edyn.InstrumentModel(
    resolution_model=resolution_model,
    background_model=background_model,
)

analysis = edyn.Analysis(
    display_name='Vanadium Analysis',
    experiment=experiment,
    sample_model=sample_model,
    instrument_model=instrument_model,
)
analysis.fit(fit_method='independent')
analysis.plot_data_and_model()

Inspecting fitted parameters and fitting a single Q first

Use Q_index to fit and plot a single Q slice before fitting all Q:

analysis.fit(fit_method='independent', Q_index=5)
analysis.plot_data_and_model(Q_index=5)

analysis.fit(fit_method='independent')
analysis.plot_parameters(names=['Gaussian width'])

Parameters:

Name Type Description Default
display_name str | None

Display name of the analysis.

'MyAnalysis'
unique_name str | None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
convolution_settings ConvolutionSettings | None

The settings for the convolution. If None, default settings will be used.

None
detailed_balance_settings DetailedBalanceSettings | None

The settings for detailed balance. If None, default settings will be used.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None

Methods:

Name Description
rebin

Rebin the experiment data along specified dimensions and update the analysis.

calculate

Calculate model data for a specific Q index.

fit

Fit the model to the experimental data.

plot_data_and_model

Plot the experimental data and the model prediction.

data_and_model_to_datagroup

Create a scipp DataGroup containing the experimental data, model calculation and optionally

parameters_to_dataset

Creates a scipp dataset with copies of the Parameters in the model.

plot_parameters

Plot fitted parameters as a function of Q.

fix_energy_offset

Fix the energy offset parameter(s) for a specific Q index, or for all Q indices if Q_index

free_energy_offset

Free the energy offset parameter(s) for a specific Q index, or for all Q indices if Q_index

get_all_variables

Get all variables used in the analysis, across every Q index.

get_fit_functions

Get fit functions for all Q indices, which can be used for simultaneous fitting.

to_dict

Convert an EasyScience object into a full dictionary using

from_dict

Re-create an EasyScience object with DescriptorNumber attributes

__copy__

Return a copy of the object.

get_all_parameters

Get all Parameter objects as a list.

get_fittable_parameters

Get all parameters which can be fitted as a list.

get_free_parameters

Get all parameters which are currently free to be fitted as a

get_fit_parameters

This is an alias for get_free_parameters.

normalize_resolution

Normalize the resolution in the InstrumentModel to ensure that it integrates to 1.

get_parameters_near_bounds

Get a list of parameters that are near their bounds.

Attributes:

Name Type Description
analysis_list list[Analysis1d]

Get the Analysis1d objects associated with this Analysis.

fitter MultiFitter

The EasyScience MultiFitter covering every Q index, built on first use.

bayesian MultiQPosteriorSampler

Bayesian posterior sampling for this Analysis, created on first use.

unique_name str

Get the unique name of the object.

display_name str

Get a pretty display name.

name str

Get the name of the model.

x_unit str | sc.Unit | None

Get the unit of the x-axis.

y_unit str | sc.Unit | None

Get the unit of the model output.

convolution_settings ConvolutionSettings

Get the convolution settings for this Analysis.

extra_parameters list[Parameter]

Get the extra parameters included in this Analysis.

experiment Experiment

Get the Experiment associated with this Analysis.

sample_model SampleModel

Get the SampleModel associated with this Analysis.

instrument_model InstrumentModel

Get the InstrumentModel associated with this Analysis.

Q sc.Variable | None

Get the Q values from the associated Experiment, if available.

energy sc.Variable | None

Get the energy values from the associated Experiment, if available.

temperature Parameter | None

Get the temperature from the associated SampleModel, if available.

detailed_balance_settings DetailedBalanceSettings

Get the DetailedBalanceSettings of the SampleModel.

Attributes
analysis_list property writable

Get the Analysis1d objects associated with this Analysis.

Returns:

Type Description
list[Analysis1d]

A list of Analysis1d objects, one for each Q index.

fitter property

The EasyScience MultiFitter covering every Q index, built on first use.

Returns:

Type Description
MultiFitter

The cached MultiFitter.

bayesian property

Bayesian posterior sampling for this Analysis, created on first use.

Returns:

Type Description
MultiQPosteriorSampler

The sampler, which can run per Q index or over all of them at once.

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.

name property writable

Get the name of the model.

Returns:

Type Description
str

The name of the model.

x_unit property writable

Get the unit of the x-axis.

Returns:

Type Description
str | sc.Unit | None

The unit of the x-axis.

y_unit property writable

Get the unit of the model output.

Returns:

Type Description
str | sc.Unit | None

The unit of the y-axis.

convolution_settings property writable

Get the convolution settings for this Analysis.

Returns:

Type Description
ConvolutionSettings

The convolution settings for this Analysis.

extra_parameters property writable

Get the extra parameters included in this Analysis.

Returns:

Type Description
list[Parameter]

The extra parameters included in this Analysis.

experiment property writable

Get the Experiment associated with this Analysis.

Returns:

Type Description
Experiment

The Experiment associated with this Analysis.

sample_model property writable

Get the SampleModel associated with this Analysis.

Returns:

Type Description
SampleModel

The SampleModel associated with this Analysis.

instrument_model property writable

Get the InstrumentModel associated with this Analysis.

Returns:

Type Description
InstrumentModel

The InstrumentModel associated with this Analysis.

Q property writable

Get the Q values from the associated Experiment, if available.

Returns:

Type Description
sc.Variable | None

The Q values from the associated Experiment, if available, and None if not.

energy property writable

Get the energy values from the associated Experiment, if available.

Returns:

Type Description
sc.Variable | None

The energy values from the associated Experiment, if available, and None if not.

temperature property writable

Get the temperature from the associated SampleModel, if available.

Returns:

Type Description
Parameter | None

The temperature from the associated SampleModel, if available, and None if not.

detailed_balance_settings property writable

Get the DetailedBalanceSettings of the SampleModel.

Returns:

Type Description
DetailedBalanceSettings

The DetailedBalanceSettings of the SampleModel.

Methods:
rebin(dimensions, confirm=False)

Rebin the experiment data along specified dimensions and update the analysis.

If Q values change (in count or magnitude), confirm=True is required. This clears Q from sample_model and instrument_model (including resolution and background sub-models) so they can accept the new Q values when the analysis list is next rebuilt.

Parameters:

Name Type Description Default
dimensions dict[str, int | sc.Variable]

A dictionary mapping dimension names to number of bins (int) or bin edges (sc.Variable).

required
confirm bool

Must be True when rebinning changes the Q values (count or magnitude), since this clears Q from all models. Raises ValueError otherwise.

False

Raises:

Type Description
ValueError

If rebinning changes Q and confirm is not True.

calculate(Q_index=None, energy=None)

Calculate model data for a specific Q index.

If Q_index is None, calculate for all Q indices and return a list of arrays.

Parameters:

Name Type Description Default
Q_index int | None

Index of the Q value to calculate for. If None, calculate for all Q values.

None
energy sc.Variable | None

The energy values to use for calculating the model. If None, uses the energy from the experiment.

None

Returns:

Type Description
list[np.ndarray] | np.ndarray

If Q_index is None, returns a list of numpy arrays, one for each Q index. If Q_index is an integer, returns a single numpy array for that Q index.

fit(fit_method='independent', Q_index=None)

Fit the model to the experimental data.

Parameters:

Name Type Description Default
fit_method str

Method to use for fitting. Options are "independent" (fit each Q index independently, one after the other) or "simultaneous" (fit all Q indices simultaneously).

'independent'
Q_index int | None

If fit_method is "independent", specify which Q index to fit. If None, fit all Q indices independently. Ignored if fit_method is "simultaneous".

None

Raises:

Type Description
ValueError

If fit_method is not "independent" or "simultaneous" or if there are no Q values available for fitting.

Returns:

Type Description
FitResults | list[FitResults]

A single FitResults when a specific Q index was fitted, and otherwise a list holding one FitResults per Q index. A simultaneous fit also reports per-Q results, since the underlying MultiFitter splits its combined result back up by dataset.

plot_data_and_model(Q_index=None, plot_components=True, add_background=True, plot_residuals=False, energy=None, **kwargs)

Plot the experimental data and the model prediction.

Optionally also plot the individual components of the model.

Uses Plopp for plotting: https://scipp.github.io/plopp/

Parameters:

Name Type Description Default
Q_index int | None

Index of the Q value to plot. If None, plot all Q values.

None
plot_components bool

Whether to plot the individual components.

True
add_background bool

Whether to add background components to the sample model components when plotting. Default is True.

True
plot_residuals bool

Whether to plot the residuals (data - model). Default is False.

False
energy sc.Variable | None

The energy values to use for calculating the model. If None, uses the energy from the experiment.

None
**kwargs dict[str, Any]

Additional keyword arguments passed to plopp for customizing the plot.

{}

Raises:

Type Description
ValueError

If Q_index is out of bounds, or if there is no data to plot, or if there are no Q values available for plotting.

RuntimeError

If not in a Jupyter notebook environment.

Returns:

Type Description
InteractiveFigure

A Plopp InteractiveFigure containing the plot of the data and model.

data_and_model_to_datagroup(energy=None, add_background=True, include_components=True, include_residuals=False)

Create a scipp DataGroup containing the experimental data, model calculation and optionally the individual components of the model.

Parameters:

Name Type Description Default
energy sc.Variable | None

The energy values to use for calculating the model. If None, uses the energy from the experiment.

None
add_background bool

Whether to add background components to the sample model components when creating the DataGroup.

True
include_components bool

Whether to include the individual components of the model in the DataGroup. If False, only the total model will be included.

True
include_residuals bool

Whether to include the residuals (data - model) in the DataGroup.

False

Raises:

Type Description
ValueError

If there is no data to include in the DataGroup, or if there are no Q values available for creating the DataGroup.

Returns:

Type Description
sc.DataGroup

A DataGroup containing the experimental data, model calculation, and optionally the individual components of the model.

parameters_to_dataset()

Creates a scipp dataset with copies of the Parameters in the model.

Ensures unit consistency across Q.

Raises:

Type Description
UnitError

If there are inconsistent units for the same parameter across different Q values.

ValueError

If duplicate parameter names exist for the same Q index.

Returns:

Type Description
sc.Dataset

A dataset where each entry is a parameter, with dimensions "Q" and values corresponding to the parameter values.

plot_parameters(names=None, **kwargs)

Plot fitted parameters as a function of Q.

Parameters:

Name Type Description Default
names str | list[str] | None

Name(s) of the parameter(s) to plot. If None, plots all parameters.

None
**kwargs dict[str, Any]

Additional keyword arguments passed to plopp.slicer for customizing the plot (e.g., title, linestyle, marker, color).

{}

Raises:

Type Description
TypeError

If names is not a string, list of strings, or None.

ValueError

If any of the specified parameter names are not found in the dataset.

Returns:

Type Description
InteractiveFigure

A Plopp InteractiveFigure containing the plot of the parameters.

fix_energy_offset(Q_index=None)

Fix the energy offset parameter(s) for a specific Q index, or for all Q indices if Q_index is None.

Parameters:

Name Type Description Default
Q_index int | None

Index of the Q value to fix the energy offset for. If None, fixes the energy offset for all Q values.

None
free_energy_offset(Q_index=None)

Free the energy offset parameter(s) for a specific Q index, or for all Q indices if Q_index is None.

Parameters:

Name Type Description Default
Q_index int | None

Index of the Q value to free the energy offset for. If None, frees the energy offset for all Q values.

None
get_all_variables()

Get all variables used in the analysis, across every Q index.

Overrides the easyscience fallback, which scans every attribute of the object and would therefore build the MultiFitter and the Sampler as side effects of merely listing variables (and fail outright on an empty analysis).

Returns:

Type Description
list[Parameter]

A list of all variables, including any extra parameters.

get_fit_functions()

Get fit functions for all Q indices, which can be used for simultaneous fitting.

Returns:

Type Description
list[callable]

A list of fit functions, one for each Q index.

to_dict(skip=None)

Convert an EasyScience object into a full dictionary using SerializerBases generic convert_to_dict method.

Parameters:

Name Type Description Default
skip Optional[List[str]]

List of field names as strings to skip when forming the dictionary. By default, None.

None

Returns:

Type Description
Dict[str, Any]

Encoded object containing all information to reform an EasyScience object.

from_dict(obj_dict) classmethod

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

Parameters:

Name Type Description Default
obj_dict Dict[str, Any]

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

required

Returns:

Type Description
ModelBase

Reformed EasyScience object.

Raises:

Type Description
SyntaxError

If a deserialized parameter cannot be attached back to the class definition.

ValueError

If the input dictionary does not describe the expected class.

__copy__()

Return a copy of the object.

get_all_parameters()

Get all Parameter objects as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fittable_parameters()

Get all parameters which can be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_free_parameters()

Get all parameters which are currently free to be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fit_parameters()

This is an alias for get_free_parameters.

To be removed when fully moved to new base classes and minimizer can be changed.

normalize_resolution()

Normalize the resolution in the InstrumentModel to ensure that it integrates to 1.

This is important for accurate fitting and interpretation of the results.

get_parameters_near_bounds(rtol=1e-05, atol=1e-08)

Get a list of parameters that are near their bounds.

Parameters:

Name Type Description Default
rtol float

Relative tolerance for determining if a parameter is near its bound.

1e-5
atol float

Absolute tolerance for determining if a parameter is near its bound.

1e-8

Returns:

Type Description
list[Parameter]

A list of parameters that are near their bounds.

Functions:

analysis1d

Classes:

Name Description
Analysis1d

For analysing one-dimensional data, i.e. intensity as function of energy for a single Q index.

Classes

Analysis1d(display_name='MyAnalysis', unique_name=None, experiment=None, sample_model=None, instrument_model=None, Q_index=None, convolution_settings=None, detailed_balance_settings=None, extra_parameters=None)

For analysing one-dimensional data, i.e. intensity as function of energy for a single Q index.

Is used primarily in the Analysis class, but can also be used on its own for simpler analyses.

Besides least-squares fitting with :meth:fit, the posterior distribution of the free parameters can be explored through :attr:bayesian; see :class:~easydynamics.analysis.posterior_sampling.PosteriorSampler.

Examples:

Fitting a single Q slice

Select a Q index with Q_index to fit only that slice of the dataset:

import pooch
import easydynamics as edyn

file_path = pooch.retrieve(
    url='https://github.com/easyscience/dynamics-lib/raw/refs/heads/master/docs/docs/tutorials/data/vanadium_data_example.h5',
    known_hash='16cc1b327c303feeb88fb9dda5390dc4880b62396b1793f98c6fef0b27c7b873',
)
experiment = edyn.Experiment('Vanadium')
experiment.load_hdf5(filename=file_path)

sample_model = edyn.SampleModel(components=edyn.DeltaFunction(area=1))
resolution_model = edyn.ResolutionModel(components=edyn.Gaussian(width=0.1))
background_model = edyn.BackgroundModel(components=edyn.Polynomial(coefficients=[0.001]))
instrument_model = edyn.InstrumentModel(
    resolution_model=resolution_model,
    background_model=background_model,
)

analysis = edyn.Analysis1d(
    display_name='Vanadium 1D Analysis',
    experiment=experiment,
    sample_model=sample_model,
    instrument_model=instrument_model,
    Q_index=5,
)
analysis.fit()
analysis.plot_data_and_model(plot_residuals=True)

Parameters:

Name Type Description Default
display_name str | None

Display name of the analysis.

'MyAnalysis'
unique_name str | None

Unique name of the analysis. If None, a unique name is automatically generated.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
Q_index int | None

The Q index to analyze. If None, the analysis will not be able to calculate or fit until a Q index is set.

None
convolution_settings ConvolutionSettings | None

The settings for the convolution. If None, default settings will be used.

None
detailed_balance_settings DetailedBalanceSettings | None

The settings for detailed balance. If None, default settings will be used.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None

Methods:

Name Description
calculate

Calculate the model prediction for the chosen Q index.

fit

Fit the model to the experimental data for the chosen Q index.

as_fit_function

Return self._calculate as a fit function.

get_all_variables

Get all variables used in the analysis.

plot_data_and_model

Plot the experimental data and the model prediction for the chosen Q index. Optionally also

data_and_model_to_datagroup

Create a scipp DataGroup containing the experimental data, model calculation, and

fix_energy_offset

Fix the energy offset parameter for the current Q index.

free_energy_offset

Free the energy offset parameter for the current Q index.

rebin

Rebin the experiment data along specified dimensions and update the analysis.

refresh_convolver

Refresh the pre-built Convolution object for the current Q index.

to_dict

Convert an EasyScience object into a full dictionary using

from_dict

Re-create an EasyScience object with DescriptorNumber attributes

__copy__

Return a copy of the object.

get_all_parameters

Get all Parameter objects as a list.

get_fittable_parameters

Get all parameters which can be fitted as a list.

get_free_parameters

Get all parameters which are currently free to be fitted as a

get_fit_parameters

This is an alias for get_free_parameters.

normalize_resolution

Normalize the resolution in the InstrumentModel to ensure that it integrates to 1.

get_parameters_near_bounds

Get a list of parameters that are near their bounds.

Attributes:

Name Type Description
Q_index int | None

Get the Q index associated with this Analysis.

fitter EasyScienceFitter

The EasyScience Fitter used for fitting and sampling, built on first use.

bayesian PosteriorSampler

Bayesian posterior sampling for this Analysis, created on first use.

unique_name str

Get the unique name of the object.

display_name str

Get a pretty display name.

name str

Get the name of the model.

x_unit str | sc.Unit | None

Get the unit of the x-axis.

y_unit str | sc.Unit | None

Get the unit of the model output.

convolution_settings ConvolutionSettings

Get the convolution settings for this Analysis.

extra_parameters list[Parameter]

Get the extra parameters included in this Analysis.

experiment Experiment

Get the Experiment associated with this Analysis.

sample_model SampleModel

Get the SampleModel associated with this Analysis.

instrument_model InstrumentModel

Get the InstrumentModel associated with this Analysis.

Q sc.Variable | None

Get the Q values from the associated Experiment, if available.

energy sc.Variable | None

Get the energy values from the associated Experiment, if available.

temperature Parameter | None

Get the temperature from the associated SampleModel, if available.

detailed_balance_settings DetailedBalanceSettings

Get the DetailedBalanceSettings of the SampleModel.

Attributes
Q_index property writable

Get the Q index associated with this Analysis.

Returns:

Type Description
int | None

The Q index associated with this Analysis.

fitter property

The EasyScience Fitter used for fitting and sampling, built on first use.

Exposed so the minimizer, tolerance, and maximum evaluation count can be configured directly, e.g. analysis.fitter.switch_minimizer(AvailableMinimizers.Bumps).

Returns:

Type Description
EasyScienceFitter

The cached Fitter.

bayesian property

Bayesian posterior sampling for this Analysis, created on first use.

Returns:

Type Description
PosteriorSampler

The sampler, which holds any chain that has been run.

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.

name property writable

Get the name of the model.

Returns:

Type Description
str

The name of the model.

x_unit property writable

Get the unit of the x-axis.

Returns:

Type Description
str | sc.Unit | None

The unit of the x-axis.

y_unit property writable

Get the unit of the model output.

Returns:

Type Description
str | sc.Unit | None

The unit of the y-axis.

convolution_settings property writable

Get the convolution settings for this Analysis.

Returns:

Type Description
ConvolutionSettings

The convolution settings for this Analysis.

extra_parameters property writable

Get the extra parameters included in this Analysis.

Returns:

Type Description
list[Parameter]

The extra parameters included in this Analysis.

experiment property writable

Get the Experiment associated with this Analysis.

Returns:

Type Description
Experiment

The Experiment associated with this Analysis.

sample_model property writable

Get the SampleModel associated with this Analysis.

Returns:

Type Description
SampleModel

The SampleModel associated with this Analysis.

instrument_model property writable

Get the InstrumentModel associated with this Analysis.

Returns:

Type Description
InstrumentModel

The InstrumentModel associated with this Analysis.

Q property writable

Get the Q values from the associated Experiment, if available.

Returns:

Type Description
sc.Variable | None

The Q values from the associated Experiment, if available, and None if not.

energy property writable

Get the energy values from the associated Experiment, if available.

Returns:

Type Description
sc.Variable | None

The energy values from the associated Experiment, if available, and None if not.

temperature property writable

Get the temperature from the associated SampleModel, if available.

Returns:

Type Description
Parameter | None

The temperature from the associated SampleModel, if available, and None if not.

detailed_balance_settings property writable

Get the DetailedBalanceSettings of the SampleModel.

Returns:

Type Description
DetailedBalanceSettings

The DetailedBalanceSettings of the SampleModel.

Methods:
calculate(energy=None)

Calculate the model prediction for the chosen Q index.

Creates a new convolver before calculating without touching the stored convolver.

Parameters:

Name Type Description Default
energy sc.Variable | None

Optional energy grid to use for calculation. If None, the energy grid from the experiment is used.

None

Returns:

Type Description
np.ndarray

The calculated model prediction.

fit()

Fit the model to the experimental data for the chosen Q index.

The energy grid is fixed for the duration of the fit. Convolution objects are created once and reused during parameter optimization for performance reasons.

Raises:

Type Description
ValueError

If no experiment is associated with this Analysis.

Returns:

Type Description
FitResults

The result of the fit.

as_fit_function(_x=None, **kwargs)

Return self._calculate as a fit function.

The EasyScience fitter requires x as input, but self._calculate() already uses the correct energy from the experiment. So we ignore the x input and just return the calculated model.

Parameters:

Name Type Description Default
_x np.ndarray | sc.Variable | None

Ignored. The energy grid is taken from the experiment.

None
**kwargs dict[str, Any]

Ignored. Included for compatibility with the EasyScience fitter.

{}

Returns:

Type Description
callable

A function that can be used as a fit function in the EasyScience fitter, which returns the calculated model.

get_all_variables()

Get all variables used in the analysis.

Returns:

Type Description
list[DescriptorNumber]

A list of all variables.

plot_data_and_model(plot_components=True, add_background=True, plot_residuals=False, energy=None, **kwargs)

Plot the experimental data and the model prediction for the chosen Q index. Optionally also plot the individual components of the model.

Uses Plopp for plotting: https://scipp.github.io/plopp/

Parameters:

Name Type Description Default
plot_components bool

Whether to plot the individual components of the model.

True
add_background bool

Whether to add the background to the model prediction when plotting individual components.

True
plot_residuals bool

Whether to plot the residuals (data - model).

False
energy sc.Variable | None

Optional energy grid to use for plotting. If None, the energy grid from the experiment is used.

None
**kwargs dict[str, Any]

Keyword arguments to pass to the plotting function.

{}

Returns:

Type Description
InteractiveFigure

A plot of the data and model.

data_and_model_to_datagroup(energy=None, add_background=True, include_components=True, include_residuals=False)

Create a scipp DataGroup containing the experimental data, model calculation, and optionally the individual components.

Parameters:

Name Type Description Default
energy sc.Variable | None

Optional energy grid to use for the model calculation. If None, the energy grid from the experiment is used.

None
add_background bool

Whether to add the background to the model prediction when plotting individual components.

True
include_components bool

Whether to include the individual components of the model in the DataGroup. If True, the DataGroup will include a DataArray for each component with the component's display name as the key

True
include_residuals bool

Whether to include the residuals (data - model) in the DataGroup. If True, the DataGroup will include a DataArray with key 'Residuals' containing the residuals.

False

Raises:

Type Description
ValueError

If no data is available in the experiment to include in the DataGroup. If no Q values are available in the experiment to create the DataGroup. If Q_index is not set to create the DataGroup.

Returns:

Type Description
sc.DataGroup

A DataGroup containing the experimental data, model calculation, and optionally the individual components.

fix_energy_offset()

Fix the energy offset parameter for the current Q index.

free_energy_offset()

Free the energy offset parameter for the current Q index.

rebin(dimensions)

Rebin the experiment data along specified dimensions and update the analysis.

Parameters:

Name Type Description Default
dimensions dict[str, int | sc.Variable]

A dictionary mapping dimension names to number of bins (int) or bin edges (sc.Variable).

required
refresh_convolver(energy=None)

Refresh the pre-built Convolution object for the current Q index.

to_dict(skip=None)

Convert an EasyScience object into a full dictionary using SerializerBases generic convert_to_dict method.

Parameters:

Name Type Description Default
skip Optional[List[str]]

List of field names as strings to skip when forming the dictionary. By default, None.

None

Returns:

Type Description
Dict[str, Any]

Encoded object containing all information to reform an EasyScience object.

from_dict(obj_dict) classmethod

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

Parameters:

Name Type Description Default
obj_dict Dict[str, Any]

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

required

Returns:

Type Description
ModelBase

Reformed EasyScience object.

Raises:

Type Description
SyntaxError

If a deserialized parameter cannot be attached back to the class definition.

ValueError

If the input dictionary does not describe the expected class.

__copy__()

Return a copy of the object.

get_all_parameters()

Get all Parameter objects as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fittable_parameters()

Get all parameters which can be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_free_parameters()

Get all parameters which are currently free to be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fit_parameters()

This is an alias for get_free_parameters.

To be removed when fully moved to new base classes and minimizer can be changed.

normalize_resolution()

Normalize the resolution in the InstrumentModel to ensure that it integrates to 1.

This is important for accurate fitting and interpretation of the results.

get_parameters_near_bounds(rtol=1e-05, atol=1e-08)

Get a list of parameters that are near their bounds.

Parameters:

Name Type Description Default
rtol float

Relative tolerance for determining if a parameter is near its bound.

1e-5
atol float

Absolute tolerance for determining if a parameter is near its bound.

1e-8

Returns:

Type Description
list[Parameter]

A list of parameters that are near their bounds.

Functions:

analysis_base

Classes:

Name Description
AnalysisBase

Base class for analysis in EasyDynamics.

Classes

AnalysisBase(display_name='MyAnalysis', unique_name=None, experiment=None, sample_model=None, instrument_model=None, convolution_settings=None, detailed_balance_settings=None, extra_parameters=None)

Base class for analysis in EasyDynamics.

This class is not meant to be used directly.

An Analysis consists of an Experiment, a SampleModel, and an InstrumentModel. The Experiment contains the data to be fitted, the SampleModel contains the model for the sample, and the InstrumentModel contains the model for the instrument, including background and resolution

Parameters:

Name Type Description Default
display_name str | None

Display name of the analysis.

'MyAnalysis'
unique_name str | None

Unique name of the analysis. If None, a unique name is automatically generated. By default, None.

None
experiment Experiment | None

The Experiment associated with this Analysis. If None, a default Experiment is created.

None
sample_model SampleModel | None

The SampleModel associated with this Analysis. If None, a default SampleModel is created.

None
instrument_model InstrumentModel | None

The InstrumentModel associated with this Analysis. If None, a default InstrumentModel is created.

None
convolution_settings ConvolutionSettings | None

The settings for the convolution. If None, default settings will be used.

None
detailed_balance_settings DetailedBalanceSettings | None

The settings for detailed balance. If None, default settings will be used.

None
extra_parameters Parameter | list[Parameter] | None

Extra parameters to be included in the analysis for advanced users. If None, no extra parameters are added.

None

Raises:

Type Description
TypeError

If experiment is not an Experiment or None or if sample_model is not a SampleModel or None or if instrument_model is not an InstrumentModel or None or if convolution_settings is not a ConvolutionSettings or None or if detailed_balance_settings is not a DetailedBalanceSettings or None or if extra_parameters is not a Parameter, a list of Parameters, or None.

Methods:

Name Description
normalize_resolution

Normalize the resolution in the InstrumentModel to ensure that it integrates to 1.

get_parameters_near_bounds

Get a list of parameters that are near their bounds.

to_dict

Convert an EasyScience object into a full dictionary using

from_dict

Re-create an EasyScience object with DescriptorNumber attributes

__copy__

Return a copy of the object.

get_all_variables

Get all Descriptor and Parameter objects as a list.

get_all_parameters

Get all Parameter objects as a list.

get_fittable_parameters

Get all parameters which can be fitted as a list.

get_free_parameters

Get all parameters which are currently free to be fitted as a

get_fit_parameters

This is an alias for get_free_parameters.

Attributes:

Name Type Description
experiment Experiment

Get the Experiment associated with this Analysis.

sample_model SampleModel

Get the SampleModel associated with this Analysis.

instrument_model InstrumentModel

Get the InstrumentModel associated with this Analysis.

Q sc.Variable | None

Get the Q values from the associated Experiment, if available.

energy sc.Variable | None

Get the energy values from the associated Experiment, if available.

temperature Parameter | None

Get the temperature from the associated SampleModel, if available.

convolution_settings ConvolutionSettings

Get the convolution settings for this Analysis.

detailed_balance_settings DetailedBalanceSettings

Get the DetailedBalanceSettings of the SampleModel.

extra_parameters list[Parameter]

Get the extra parameters included in this Analysis.

unique_name str

Get the unique name of the object.

display_name str

Get a pretty display name.

name str

Get the name of the model.

x_unit str | sc.Unit | None

Get the unit of the x-axis.

y_unit str | sc.Unit | None

Get the unit of the model output.

Attributes
experiment property writable

Get the Experiment associated with this Analysis.

Returns:

Type Description
Experiment

The Experiment associated with this Analysis.

sample_model property writable

Get the SampleModel associated with this Analysis.

Returns:

Type Description
SampleModel

The SampleModel associated with this Analysis.

instrument_model property writable

Get the InstrumentModel associated with this Analysis.

Returns:

Type Description
InstrumentModel

The InstrumentModel associated with this Analysis.

Q property writable

Get the Q values from the associated Experiment, if available.

Returns:

Type Description
sc.Variable | None

The Q values from the associated Experiment, if available, and None if not.

energy property writable

Get the energy values from the associated Experiment, if available.

Returns:

Type Description
sc.Variable | None

The energy values from the associated Experiment, if available, and None if not.

temperature property writable

Get the temperature from the associated SampleModel, if available.

Returns:

Type Description
Parameter | None

The temperature from the associated SampleModel, if available, and None if not.

convolution_settings property writable

Get the convolution settings for this Analysis.

Returns:

Type Description
ConvolutionSettings

The convolution settings for this Analysis.

detailed_balance_settings property writable

Get the DetailedBalanceSettings of the SampleModel.

Returns:

Type Description
DetailedBalanceSettings

The DetailedBalanceSettings of the SampleModel.

extra_parameters property writable

Get the extra parameters included in this Analysis.

Returns:

Type Description
list[Parameter]

The extra parameters included in this Analysis.

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.

name property writable

Get the name of the model.

Returns:

Type Description
str

The name of the model.

x_unit property writable

Get the unit of the x-axis.

Returns:

Type Description
str | sc.Unit | None

The unit of the x-axis.

y_unit property writable

Get the unit of the model output.

Returns:

Type Description
str | sc.Unit | None

The unit of the y-axis.

Methods:
normalize_resolution()

Normalize the resolution in the InstrumentModel to ensure that it integrates to 1.

This is important for accurate fitting and interpretation of the results.

get_parameters_near_bounds(rtol=1e-05, atol=1e-08)

Get a list of parameters that are near their bounds.

Parameters:

Name Type Description Default
rtol float

Relative tolerance for determining if a parameter is near its bound.

1e-5
atol float

Absolute tolerance for determining if a parameter is near its bound.

1e-8

Returns:

Type Description
list[Parameter]

A list of parameters that are near their bounds.

to_dict(skip=None)

Convert an EasyScience object into a full dictionary using SerializerBases generic convert_to_dict method.

Parameters:

Name Type Description Default
skip Optional[List[str]]

List of field names as strings to skip when forming the dictionary. By default, None.

None

Returns:

Type Description
Dict[str, Any]

Encoded object containing all information to reform an EasyScience object.

from_dict(obj_dict) classmethod

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

Parameters:

Name Type Description Default
obj_dict Dict[str, Any]

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

required

Returns:

Type Description
ModelBase

Reformed EasyScience object.

Raises:

Type Description
SyntaxError

If a deserialized parameter cannot be attached back to the class definition.

ValueError

If the input dictionary does not describe the expected class.

__copy__()

Return a copy of the object.

get_all_variables()

Get all Descriptor and Parameter objects as a list.

Returns:

Type Description
List[DescriptorBase]

List of Descriptor and Parameter objects.

get_all_parameters()

Get all Parameter objects as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fittable_parameters()

Get all parameters which can be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_free_parameters()

Get all parameters which are currently free to be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fit_parameters()

This is an alias for get_free_parameters.

To be removed when fully moved to new base classes and minimizer can be changed.

fit_binding

Classes:

Name Description
FitBinding

Contract between dataset, model, and fit functions for ParameterAnalysis. A binding maps the

Classes

FitBinding(model, targets=None, display_name=None, unique_name=None)

Contract between dataset, model, and fit functions for ParameterAnalysis. A binding maps the model's fittable predictions (its FitTargets) onto keys of the parameters Dataset they should be fitted against.

Examples:

Fitting a component model to one parameter

Component models (e.g. a Polynomial) have a single prediction — their evaluate — so targets is simply the dataset key to fit against. The model's x_unit/y_unit declare the units its evaluate expects: here x is the dataset's Q coordinate and y the fitted parameter, so construct the model with matching units (or pass x_unit=None / y_unit=None to fit raw values):

import easydynamics as edyn

fit_func = edyn.Polynomial(
    coefficients=[3.7, -0.5],
    x_unit='1/angstrom',
    y_unit='meV',
    display_name='Straight line',
)
binding = edyn.FitBinding(model=fit_func, targets='Gaussian area')

Fitting a diffusion model with default dataset keys

Diffusion models declare their predictions ('area', 'width', and for DeltaLorentz also 'delta_area'). With targets=None all predictions are fitted against default dataset keys derived from the model's component names:

brownian = edyn.BrownianTranslationalDiffusion(
    diffusion_coefficient=2.4e-9,
    scale=0.5,
    lorentzian_name='Lorentzian',
)
binding = edyn.FitBinding(model=brownian)  # fits 'Lorentzian area' and 'Lorentzian width'

Selecting predictions or mapping them to custom dataset keys

Pass a list of prediction names, or a dict mapping prediction names to dataset keys:

binding = edyn.FitBinding(model=brownian, targets=['width'])

delta_lorentz = edyn.DeltaLorentz(A_0=0.5, lorentzian_width=0.1)
binding = edyn.FitBinding(
    model=delta_lorentz,
    targets={
        'width': 'Lorentzian width',
        'area': 'Lorentzian area',
        'delta_area': 'Elastic area',
    },
)

Validation raises TypeError if model or targets have an invalid type, and ValueError if targets names a prediction the model does not declare.

Parameters:

Name Type Description Default
model ModelComponent | ComponentCollection | DiffusionModelBase

The model to fit. This can be a single ModelComponent, a ComponentCollection, or a DiffusionModelBase.

required
targets str | list[str] | dict[str, str] | None

Which predictions of the model to fit, and against which dataset keys. For component models this must be a string: the dataset key to fit the model's evaluate against. For diffusion models: None fits all predictions against their default dataset keys; a string or list of strings selects predictions by name (default keys); a dict maps prediction names to custom dataset keys.

None
display_name str | None

An optional display name for the FitBinding. If None, the unique_name will be used. Default is None.

None
unique_name str | None

An optional unique name for the FitBinding. If None, a unique name will be generated. Default is None.

None

Methods:

Name Description
get_targets

Get the FitTargets this binding fits, with dataset keys resolved.

to_dict

Convert an EasyScience object into a full dictionary using

from_dict

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

__copy__

Return a copy of the object.

Attributes:

Name Type Description
model ModelComponent | ComponentCollection | DiffusionModelBase

The model to fit. This can be a single ModelComponent, a ComponentCollection, or a

targets str | list[str] | dict[str, str] | None

Which predictions of the model to fit, and against which dataset keys.

unique_name str

Get the unique name of the object.

display_name str

Get a pretty display name.

name str

Get the name of the model.

Attributes
model property writable

The model to fit. This can be a single ModelComponent, a ComponentCollection, or a DiffusionModelBase.

Returns:

Type Description
ModelComponent | ComponentCollection | DiffusionModelBase

The model to fit.

targets property writable

Which predictions of the model to fit, and against which dataset keys.

Returns:

Type Description
str | list[str] | dict[str, str] | None

The targets specification (see __init__).

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.

name property writable

Get the name of the model.

Returns:

Type Description
str

The name of the model.

Methods:
get_targets()

Get the FitTargets this binding fits, with dataset keys resolved.

Targets are built from the model at call time, so their units and default dataset keys reflect the model's current state.

Returns:

Type Description
list[FitTarget]

The resolved fit targets.

to_dict(skip=None)

Convert an EasyScience object into a full dictionary using SerializerBases generic convert_to_dict method.

Parameters:

Name Type Description Default
skip Optional[List[str]]

List of field names as strings to skip when forming the dictionary. By default, None.

None

Returns:

Type Description
Dict[str, Any]

Encoded object containing all information to reform an EasyScience object.

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 SerializerDict) of an EasyScience object.

required

Returns:

Type Description
NewBase

Reformed EasyScience object.

Raises:

Type Description
ValueError

If the input dictionary does not describe the expected class.

__copy__()

Return a copy of the object.

parameter_analysis

Classes:

Name Description
ParameterAnalysis

For analysing fitted parameters.

Classes

ParameterAnalysis(parameters=None, bindings=None, display_name='ParameterAnalysis', unique_name=None)

For analysing fitted parameters.

Can be used to fit parameters to ModelComponents, ComponentCollections, or DiffusionModelBase objects, and to plot the parameters and fit results. The parameters to be analyzed can be provided as a sc.Dataset or directly as an Analysis object. Multiple parameters can be fitted simultaneously, and each binding maps its model's predictions onto the dataset keys they are fitted against (for diffusion models e.g. 'area', 'width', or 'delta_area').

Examples:

Fitting Lorentzian widths to a diffusion model

After a full Analysis fit, pass the Analysis directly and bind the model's predictions to dataset keys using a FitBinding:

import easydynamics as edyn

# analysis is an edyn.Analysis object with previously fitted parameters
diffusion_model = edyn.BrownianTranslationalDiffusion(diffusion_coefficient=2.4e-9, scale=0.5)
binding = edyn.FitBinding(
    model=diffusion_model,
    targets={'width': 'Lorentzian width'},
)

param_analysis = edyn.ParameterAnalysis(
    parameters=analysis,
    bindings=binding,
)
param_analysis.fit()
param_analysis.plot()

Fitting multiple parameters with separate bindings

Component models declare the units their evaluate expects: here the Polynomial's x is the dataset's Q coordinate and its y is the fitted parameter, so construct it with matching units (or pass x_unit=None / y_unit=None to fit raw values):

area_binding = edyn.FitBinding(
    model=edyn.Polynomial(coefficients=[0.5, 0.0], x_unit='1/angstrom', y_unit='meV'),
    targets='Lorentzian area',
)
param_analysis = edyn.ParameterAnalysis(
    parameters=analysis,
    bindings=[binding, area_binding],
)
param_analysis.fit()

Parameters:

Name Type Description Default
parameters sc.Dataset | Analysis | None

The parameters to analyze. Can be provided as a sc.Dataset or as an Analysis (in which case the parameters will be extracted from the Analysis).

None
bindings FitBinding | list[FitBinding] | None

The fit bindings to use for fitting the parameters. Can be a single FitBinding or a list of FitBindings. If None, no fit bindings are provided.

None
display_name str | None

Display name of the analysis.

'ParameterAnalysis'
unique_name str | None

Unique name of the analysis. If None, a unique name is automatically generated. By default, None.

None

Methods:

Name Description
fit

Fit the parameters using the specified fit functions and settings.

plot

Plot the parameters and fit results.

calculate_model_dataset

Evaluate all bindings into a sc.Dataset of model predictions.

append_binding

Append a FitBinding to the list of bindings for the parameter analysis.

clear_bindings

Clear all FitBindings from the list of bindings for the parameter analysis.

get_all_variables

Get all variables from the fit functions.

to_dict

Convert an EasyScience object into a full dictionary using

from_dict

Re-create an EasyScience object with DescriptorNumber attributes

__copy__

Return a copy of the object.

get_all_parameters

Get all Parameter objects as a list.

get_fittable_parameters

Get all parameters which can be fitted as a list.

get_free_parameters

Get all parameters which are currently free to be fitted as a

get_fit_parameters

This is an alias for get_free_parameters.

Attributes:

Name Type Description
parameters sc.Dataset | None

Get the parameters for the parameter analysis.

bindings list[FitBinding]

Get the fit bindings for the parameter analysis.

fitter MultiFitter

The EasyScience MultiFitter over the binding models, built on first use.

bayesian PosteriorSampler

Bayesian posterior sampling for this analysis, created on first use.

unique_name str

Get the unique name of the object.

display_name str

Get a pretty display name.

name str

Get the name of the model.

x_unit str | sc.Unit | None

Get the unit of the x-axis.

y_unit str | sc.Unit | None

Get the unit of the model output.

Attributes
parameters property writable

Get the parameters for the parameter analysis.

Returns:

Type Description
sc.Dataset | None

The parameters for the parameter analysis.

bindings property writable

Get the fit bindings for the parameter analysis.

Returns:

Type Description
list[FitBinding]

The fit bindings for the parameter analysis.

fitter property

The EasyScience MultiFitter over the binding models, built on first use.

Returns:

Type Description
MultiFitter

The cached MultiFitter.

bayesian property

Bayesian posterior sampling for this analysis, created on first use.

Returns:

Type Description
PosteriorSampler

The sampler, which holds any chain that has been run.

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.

name property writable

Get the name of the model.

Returns:

Type Description
str

The name of the model.

x_unit property writable

Get the unit of the x-axis.

Returns:

Type Description
str | sc.Unit | None

The unit of the x-axis.

y_unit property writable

Get the unit of the model output.

Returns:

Type Description
str | sc.Unit | None

The unit of the y-axis.

Methods:
fit()

Fit the parameters using the specified fit functions and settings.

A ValueError is raised if no parameters Dataset is provided, if no fit bindings are provided, or if a binding names a dataset key that is not in the parameters Dataset.

Returns:

Type Description
FitResults

The results of the fit

plot(names=None, **kwargs)

Plot the parameters and fit results.

Parameters:

Name Type Description Default
names str | list[str] | None

The names of the parameters to plot. If None, all parameters with bindings are plotted.

None
**kwargs dict[str, Any]

Additional keyword arguments to pass to the plotting function.

{}

Returns:

Type Description
InteractiveFigure

An interactive figure containing the plots of the parameters and fit results.

Raises:

Type Description
ValueError

If the units of the specified parameters are not consistent.

RuntimeError

If plot() is called outside of a Jupyter notebook environment.

calculate_model_dataset(bindings)

Evaluate all bindings into a sc.Dataset of model predictions.

Parameters:

Name Type Description Default
bindings list[FitBinding]

The bindings to evaluate.

required

Returns:

Type Description
sc.Dataset

A sc.Dataset containing the model predictions for all bindings.

Raises:

Type Description
ValueError

If any parameter name from the bindings is not found in the parameters Dataset.

TypeError

If bindings is not a list of FitBinding objects.

append_binding(binding)

Append a FitBinding to the list of bindings for the parameter analysis.

Parameters:

Name Type Description Default
binding FitBinding

The FitBinding to append.

required

Raises:

Type Description
TypeError

If binding is not a FitBinding object.

clear_bindings()

Clear all FitBindings from the list of bindings for the parameter analysis.

get_all_variables()

Get all variables from the fit functions.

Returns:

Type Description
list

A list of all variables from the fit functions.

to_dict(skip=None)

Convert an EasyScience object into a full dictionary using SerializerBases generic convert_to_dict method.

Parameters:

Name Type Description Default
skip Optional[List[str]]

List of field names as strings to skip when forming the dictionary. By default, None.

None

Returns:

Type Description
Dict[str, Any]

Encoded object containing all information to reform an EasyScience object.

from_dict(obj_dict) classmethod

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

Parameters:

Name Type Description Default
obj_dict Dict[str, Any]

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

required

Returns:

Type Description
ModelBase

Reformed EasyScience object.

Raises:

Type Description
SyntaxError

If a deserialized parameter cannot be attached back to the class definition.

ValueError

If the input dictionary does not describe the expected class.

__copy__()

Return a copy of the object.

get_all_parameters()

Get all Parameter objects as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fittable_parameters()

Get all parameters which can be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_free_parameters()

Get all parameters which are currently free to be fitted as a list.

Returns:

Type Description
List[Parameter]

List of Parameter objects.

get_fit_parameters()

This is an alias for get_free_parameters.

To be removed when fully moved to new base classes and minimizer can be changed.

Functions:

posterior

Bounds suggestions and posterior summaries for Bayesian sampling.

The helpers here are deliberately free of any Analysis or Fitter machinery: they operate on plain Parameter objects and on the (n_draws, n_parameters) array produced by the sampler, so they can be unit-tested on their own and reused by every Analysis class.

Classes:

Name Description
BoundsSuggestion

A proposed pair of bounds for a single parameter.

BoundsSuggestions

The result of :func:suggest_bounds_for_parameters, rendered as a table.

ParameterPosterior

The marginal posterior of a single parameter.

PosteriorSummary

Marginal posterior summaries for every sampled parameter, rendered as a table.

Functions:

Name Description
suggest_bounds_for_parameters

Propose finite bounds for parameters that currently have an infinite one.

unbounded_parameters

Find parameters with a non-finite lower or upper bound.

degenerate_parameters

Find parameters whose finite bounds enclose no range at all.

parameters_at_bounds

Find parameters whose posterior has piled up against one of its bounds.

summarize_draws

Summarize posterior draws under caller-supplied labels.

Classes

BoundsSuggestion(parameter, label, suggested_min, suggested_max, reason) dataclass

A proposed pair of bounds for a single parameter.

Attributes:

Name Type Description
parameter Parameter

The parameter the suggestion applies to.

label str

The name the parameter is reported under. For a multi-Q analysis this is qualified by Q, since every Q holds an identically named copy of each parameter.

suggested_min float

The proposed lower bound. Equal to the parameter's current lower bound when that is already finite.

suggested_max float

The proposed upper bound. Equal to the parameter's current upper bound when that is already finite.

reason str

Empty when the suggestion is usable. Otherwise, why the parameter needs manual attention.

Attributes
needs_attention property

Whether this parameter could not be given a usable suggestion.

Returns:

Type Description
bool

True when no usable bounds could be derived and the user must set them by hand.

changes_bounds property

Whether applying this suggestion would actually change the parameter.

Returns:

Type Description
bool

True when either bound differs from the parameter's current bound.

BoundsSuggestions(suggestions)

The result of :func:suggest_bounds_for_parameters, rendered as a table.

This is advisory: nothing is changed until :meth:apply is called. Suggestions only ever fill in an infinite bound; a bound that is already finite is never widened or narrowed, so physical limits such as a non-negative area survive untouched.

Parameters:

Name Type Description Default
suggestions list[BoundsSuggestion]

The per-parameter suggestions.

required

Methods:

Name Description
apply

Set the suggested bounds on every parameter that has a usable suggestion.

__len__

Return the number of suggestions.

__iter__

Iterate over the suggestions.

Attributes:

Name Type Description
suggestions list[BoundsSuggestion]

All suggestions, including those needing manual attention.

needing_attention list[BoundsSuggestion]

The suggestions for which no usable bounds could be derived.

Attributes
suggestions property

All suggestions, including those needing manual attention.

Returns:

Type Description
list[BoundsSuggestion]

The per-parameter suggestions.

needing_attention property

The suggestions for which no usable bounds could be derived.

Returns:

Type Description
list[BoundsSuggestion]

Suggestions whose parameters must be bounded by hand.

Methods:
apply()

Set the suggested bounds on every parameter that has a usable suggestion.

Parameters needing manual attention are skipped rather than guessed at. A suggestion that is absurdly wide is still applied -- it is what the fit implied -- but warned about, since reading the table first is easy to skip in a script.

Returns:

Type Description
list[Parameter]

The parameters whose bounds were changed.

__len__()

Return the number of suggestions.

Returns:

Type Description
int

The number of suggestions.

__iter__()

Iterate over the suggestions.

Returns:

Type Description
iter

An iterator over the suggestions.

ParameterPosterior(name, unit, median, lower, upper, value) dataclass

The marginal posterior of a single parameter.

Attributes:

Name Type Description
name str

The parameter's name.

unit str

The parameter's unit, as a string.

median float

The 50th percentile of the marginal posterior.

lower float

The 16th percentile.

upper float

The 84th percentile.

value float

The parameter's current value, for comparison with the median.

Attributes
minus property

Distance from the median down to the 16th percentile.

Returns:

Type Description
float

The lower half of the 68% credible interval.

plus property

Distance from the median up to the 84th percentile.

Returns:

Type Description
float

The upper half of the 68% credible interval.

PosteriorSummary(entries)

Marginal posterior summaries for every sampled parameter, rendered as a table.

Parameters:

Name Type Description Default
entries list[ParameterPosterior]

One entry per sampled parameter.

required

Methods:

Name Description
__len__

Return the number of summarized parameters.

__iter__

Iterate over the entries.

__getitem__

Look up a parameter's summary by name.

Attributes:

Name Type Description
entries list[ParameterPosterior]

The per-parameter summaries.

Attributes
entries property

The per-parameter summaries.

Returns:

Type Description
list[ParameterPosterior]

One entry per sampled parameter.

Methods:
__len__()

Return the number of summarized parameters.

Returns:

Type Description
int

The number of entries.

__iter__()

Iterate over the entries.

Returns:

Type Description
iter

An iterator over the entries.

__getitem__(name)

Look up a parameter's summary by name.

Parameters:

Name Type Description Default
name str

The parameter name.

required

Returns:

Type Description
ParameterPosterior

The summary for that parameter.

Raises:

Type Description
KeyError

If no sampled parameter has that name.

Functions:

suggest_bounds_for_parameters(parameters, labels=None, n_sigma=10.0, relative_pad=0.2, absolute_floor=None)

Propose finite bounds for parameters that currently have an infinite one.

The half-width of a proposed bound is n_sigma * error + relative_pad * abs(value), floored at absolute_floor when one is given. The relative_pad term matters because least-squares minimizers sometimes report a zero or absurdly small uncertainty; without it such a parameter would be given a zero-width bound. When the half-width still comes out as zero or non-finite, the parameter is flagged for manual attention rather than given an invented scale.

In BUMPS' DREAM sampler the bounds act as a uniform prior, so a generous width is the safe choice: too narrow a bound truncates the posterior and understates the uncertainty. Hence the deliberately loose n_sigma default.

A TypeError is raised if any of the three settings is not a number, and a ValueError if any is negative.

Parameters:

Name Type Description Default
parameters list[Parameter]

The parameters to propose bounds for.

required
labels list[str] | None

The name to report each parameter under, one per parameter. Defaults to the parameters' own names, which is ambiguous when several share a name, as the per-Q copies of a multi-Q analysis do.

None
n_sigma float

How many standard deviations of the parameter's fitted uncertainty to allow on each side.

10.0
relative_pad float

Extra half-width as a fraction of the absolute parameter value, guarding against artificially small uncertainties.

0.2
absolute_floor float | None

A minimum half-width, in the parameter's own units. Use it when the natural scale is known but neither the uncertainty nor the value carries it.

None

Returns:

Type Description
BoundsSuggestions

The proposed bounds, which must be applied explicitly.

unbounded_parameters(parameters)

Find parameters with a non-finite lower or upper bound.

Parameters:

Name Type Description Default
parameters list[Parameter]

The parameters to check.

required

Returns:

Type Description
list[Parameter]

Those parameters that have at least one infinite bound.

degenerate_parameters(parameters)

Find parameters whose finite bounds enclose no range at all.

A zero-width range (min >= max) gives DREAM nothing to explore: as the prior it has zero volume, and letting it through surfaces only as NaNs deep inside the sampler, far from the cause.

Parameters:

Name Type Description Default
parameters list[Parameter]

The parameters to check.

required

Returns:

Type Description
list[Parameter]

Those parameters whose bounds are both finite with min >= max.

parameters_at_bounds(draws, parameters_by_column)

Find parameters whose posterior has piled up against one of its bounds.

A chain that spends much of its time hard against a bound is a sign that the bound, rather than the data, is setting the credible interval. That happens when a bound is too tight, and also when two parameters are degenerate and the pair drifts until it is stopped by a bound.

Parameters:

Name Type Description Default
draws np.ndarray

Posterior draws, shape (n_draws, n_parameters).

required
parameters_by_column list[Parameter | None]

The parameter for each column of draws, or None where no parameter could be matched.

required

Returns:

Type Description
dict[str, float]

Mapping of the parameter's unique_name -- name is not used as the key because two same-named parameters would collide -- to the fraction of draws sitting in the outer BOUND_EDGE_FRACTION of its allowed range, for those parameters where that fraction exceeds BOUND_OCCUPANCY_THRESHOLD. The caller resolves the unique names back to readable labels where the result is reported.

summarize_draws(draws, labels, parameters_by_column)

Summarize posterior draws under caller-supplied labels.

The sampler labels its columns with each parameter's unique_name (Parameter_4 and the like), which is not what a user recognises, so the caller supplies readable labels instead. A plain parameter name is enough for a single dataset, but a multi-Q analysis holds one copy of each parameter per Q, all sharing a name, so those labels have to be qualified by Q.

Parameters:

Name Type Description Default
draws np.ndarray

Posterior draws, shape (n_draws, n_parameters).

required
labels list[str]

The label to report each column under, one per column.

required
parameters_by_column list[Parameter | None]

The parameter for each column of draws, or None where none could be matched.

required

Returns:

Type Description
PosteriorSummary

One entry per column of draws, in column order.

posterior_labels

Naming the columns of an MCMC chain.

The sampler labels its columns with each parameter's unique_name -- Parameter_4 and the like -- which is not what a user recognises, and which is handed out per session so it does not survive a saved chain either. This turns those columns back into readable labels.

Classes:

Name Description
ParameterLabels

Readable labels and units for the columns of a chain.

Classes

ParameterLabels(parameters, qualify=None)

Readable labels and units for the columns of a chain.

Built once for a fixed set of parameters, so the name counts and lookups are computed a single time. Doing this per column instead is quadratic in the parameter count, which is seconds of work for an analysis with many Q values.

Parameters:

Name Type Description Default
parameters list[Parameter]

The parameters that can appear as columns.

required
qualify Callable[[Parameter], str | None] | None

Returns a qualifier for a parameter whose name is shared with another, for example its Q index. Only consulted when the bare name really is ambiguous, so an analysis with nothing to disambiguate keeps its short names. Returning None leaves the name unqualified.

None

Methods:

Name Description
label

Get the label a parameter is reported under.

name_map

Map each parameter's unique_name to its label.

resolve

Match each column of a chain to a parameter.

display_names

Get a readable label for each column of a chain.

units

Get the unit of each column of a chain.

Attributes:

Name Type Description
parameters list[Parameter]

The parameters these labels describe.

Attributes
parameters property

The parameters these labels describe.

Returns:

Type Description
list[Parameter]

The parameters given at construction.

Methods:
label(parameter)

Get the label a parameter is reported under.

Parameters:

Name Type Description Default
parameter Parameter

The parameter to label.

required

Returns:

Type Description
str

The parameter's name, qualified only where that name is shared with another parameter.

name_map()

Map each parameter's unique_name to its label.

Saved alongside a chain, because unique names are per-session: without this a reloaded chain cannot be matched back to any parameter. Where two parameters share a display label, the recorded labels carry a deterministic positional suffix (width [1], width [2]) so each column can be matched back to exactly one parameter.

Returns:

Type Description
dict[str, str]

Mapping of unique name to label, collision-free.

resolve(column_names, saved_labels=None)

Match each column of a chain to a parameter.

Columns are matched on unique_name first. That fails for a chain loaded from disk, where the saved labels are used instead.

Parameters:

Name Type Description Default
column_names list[str]

The sampler's name for each column.

required
saved_labels dict[str, str] | None

Mapping of unique name to label, as recorded when a chain was saved.

None

Returns:

Type Description
list[Parameter | None]

The parameter for each column, or None where no match could be made.

display_names(column_names, saved_labels=None)

Get a readable label for each column of a chain.

Parameters:

Name Type Description Default
column_names list[str]

The sampler's name for each column.

required
saved_labels dict[str, str] | None

Mapping of unique name to label, as recorded when a chain was saved.

None

Returns:

Type Description
list[str]

One label per column, falling back to the saved label and then to the raw column name.

units(column_names, saved_labels=None)

Get the unit of each column of a chain.

Parameters:

Name Type Description Default
column_names list[str]

The sampler's name for each column.

required
saved_labels dict[str, str] | None

Mapping of unique name to label, as recorded when a chain was saved.

None

Returns:

Type Description
list[str]

One unit per column, empty where no parameter could be matched.

posterior_sampling

Bayesian MCMC sampling for the Analysis classes, backed by the BUMPS DREAM sampler.

The sampler is composed into an Analysis rather than inherited by it: an Analysis exposes one bayesian property, and everything to do with sampling lives here instead of being mixed into three classes. Labelling lives in :mod:easydynamics.analysis.posterior_labels and the figures in :mod:easydynamics.utils.posterior_plotting; this module only runs chains.

Classes:

Name Description
PosteriorSampler

Draws samples from the posterior distribution of an Analysis' free parameters.

MultiQPosteriorSampler

Posterior sampling for an Analysis covering several Q values.

Classes

PosteriorSampler(analysis, sampling_data, chain_parameters, parameter_labels, prepare=None)

Draws samples from the posterior distribution of an Analysis' free parameters.

Reached as analysis.bayesian. Sampling explores the whole posterior rather than reporting a single best-fit point, which is worth doing when parameters are correlated or their uncertainties are strongly non-Gaussian, both common in QENS.

Running a fit first is not required, but it helps: DREAM seeds its population in a small ball around the parameters' current values, so starting from fitted values shortens the burn-in.

The Analysis passes in everything that differs between the Analysis classes, so this class needs no knowledge of how any of them is built.

Parameters:

Name Type Description Default
analysis object

The Analysis being sampled, used for its display_name and its fitter.

required
sampling_data Callable[[], tuple]

Returns the (x, y, weights) to bind to the sampler. Each is an array, or a list of arrays for a multi-dataset fit.

required
chain_parameters Callable[[], list[Parameter]]

Returns the free parameters that will form the chain's columns.

required
parameter_labels Callable[[], ParameterLabels]

Returns labels for those parameters.

required
prepare Callable[[], None] | None

Brings any cached computation on the Analysis up to date before a run.

None

Notes

Every free parameter must have finite bounds before sampling, because in DREAM the bounds are the prior. :meth:suggest_bounds proposes bounds for any parameter still missing one.

Examples:

analysis.fit()
analysis.bayesian.suggest_bounds().apply()
analysis.bayesian.sample(samples=10000, burn=2000, thin=10)
analysis.bayesian.summary()

Methods:

Name Description
invalidate

Mark the underlying Sampler as needing a rebuild.

suggest_bounds

Propose finite bounds for free parameters that still have an infinite one.

check_bounds

Verify that every free parameter has finite bounds.

sample

Draw samples from the posterior distribution of the free parameters.

extend

Continue the existing chain with additional samples.

summary

Summarize the marginal posterior of each sampled parameter.

set_parameters_to_median

Set every sampled parameter to the median of its marginal posterior.

save

Save the MCMC chain to disk.

load

Load a previously saved MCMC chain.

plot_trace

Plot the chain trace of each sampled parameter.

plot_corner

Plot the marginal and pairwise posterior distributions.

plot_marginal

Plot the marginal posterior distribution of a single sampled 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.

predictions

Evaluate the model once per posterior draw, restoring the parameters afterwards.

Attributes:

Name Type Description
sampler Sampler | None

The EasyScience Sampler holding the chain, or None before the first run.

results SamplingResults | None

The results of the most recent run, or None if there has not been one.

Attributes
sampler property

The EasyScience Sampler holding the chain, or None before the first run.

Returns:

Type Description
Sampler | None

The cached Sampler.

results property

The results of the most recent run, or None if there has not been one.

Returns:

Type Description
SamplingResults | None

The most recent sampling results.

Methods:
invalidate()

Mark the underlying Sampler as needing a rebuild.

Called by the Analysis when its data changes, since the Sampler binds its data at construction.

suggest_bounds(n_sigma=10.0, relative_pad=0.2, absolute_floor=None)

Propose finite bounds for free parameters that still have an infinite one.

Nothing changes until :meth:BoundsSuggestions.apply is called, so the proposal can be reviewed first. Bounds that are already finite are never widened or narrowed, so physical limits such as a non-negative area are left alone.

Because the bounds act as a uniform prior in DREAM, a generous width is the safe choice: too tight a bound truncates the posterior and understates the uncertainty.

Parameters:

Name Type Description Default
n_sigma float

How many standard deviations of the fitted uncertainty to allow on each side.

10.0
relative_pad float

Extra half-width as a fraction of the absolute parameter value, guarding against minimizers that report a zero or absurdly small uncertainty.

0.2
absolute_floor float | None

A minimum half-width in the parameter's own units, for when neither the uncertainty nor the value carries the natural scale.

None

Returns:

Type Description
BoundsSuggestions

The proposed bounds, which must be applied explicitly.

check_bounds()

Verify that every free parameter has finite bounds.

Raises:

Type Description
ValueError

If any free parameter has an infinite lower or upper bound, or finite bounds that enclose no range (min >= max).

sample(samples=10000, burn=2000, thin=10, population=None, parameters=None, progress=False, **sampler_options)

Draw samples from the posterior distribution of the free parameters.

Starts a fresh chain, replacing any existing one; use :meth:extend to continue one. Parameter values are restored afterwards, so sampling never silently moves the model off its fitted values; use :meth:set_parameters_to_median to adopt the posterior.

Parameters:

Name Type Description Default
samples int

Number of raw samples to draw across all chains, before thinning. A guaranteed minimum rather than an exact count.

10000
burn int

Burn-in generations to discard before collecting samples.

2000
thin int

Thinning interval, which reduces autocorrelation between retained draws.

10
population int | None

DREAM population scale factor: BUMPS runs ceil(population * n_parameters) chains.

None
parameters list[Parameter] | list[str] | None

Restrict the chain to these parameters, given as Parameter objects or labels. All other free parameters are held fixed for the run. Holding a parameter fixed is not the same as marginalizing over it: the resulting intervals are conditional on those values and will be too narrow if the parameters are correlated. The default samples everything.

None
progress bool

Print a progress line, redrawn in place as the sampler advances and closed with a done marker when the run finishes. Off by default so scripted runs stay quiet; a progress_callback given in sampler_options takes precedence over it.

False
**sampler_options dict[str, Any]

Forwarded to the EasyScience Sampler, e.g. sampler_kwargs or progress_callback.

{}

Returns:

Type Description
SamplingResults

The sampling results, also stored on :attr:results.

Notes

Runs are not reproducible. BUMPS' DREAM sampler draws from NumPy's global random state and the underlying EasyScience Sampler exposes no seed control, so two identical calls return two different chains. Their summaries should nevertheless agree to well within the reported credible intervals; if they do not, the chain is too short to have converged.

extend(additional_samples=5000, thin=10, parameters=None, progress=False, **sampler_options)

Continue the existing chain with additional samples.

Parameters:

Name Type Description Default
additional_samples int

Number of additional samples to draw, in the same units as samples.

5000
thin int

Thinning interval for the retained draws.

10
parameters list[Parameter] | list[str] | None

The same restriction as in :meth:sample. It must leave the chain the same width, since BUMPS resumes from a stored chain whose columns are fixed.

None
progress bool

Print a progress line, redrawn in place as the sampler advances, as in :meth:sample.

False
**sampler_options dict[str, Any]

Forwarded to the EasyScience Sampler.

{}

Returns:

Type Description
SamplingResults

The sampling results for the full extended chain.

Raises:

Type Description
RuntimeError

If there is no chain to extend, or the previous run failed and left no results.

Notes

A ValueError propagates from the run guards if the model or data changed since the chain was started, or if this run's parameters differ from the ones the chain holds.

Like :meth:sample, extensions are not reproducible: the sampler draws from NumPy's global random state and exposes no seed control.

summary(labeller=None)

Summarize the marginal posterior of each sampled parameter.

Reports the median and the 68% credible interval under the parameter's own label and unit.

Parameters:

Name Type Description Default
labeller Callable[[Parameter], str] | None

Overrides the label a resolved column is reported under. Used by an Analysis covering several Q values, whose gathered table qualifies each name with its Q index. Columns that resolve to no parameter keep their usual fallback name.

None

Returns:

Type Description
PosteriorSummary

One entry per sampled parameter.

set_parameters_to_median()

Set every sampled parameter to the median of its marginal posterior.

The vector of marginal medians is not in general the highest-posterior point, and for strongly correlated parameters need not even be a good fit.

Returns:

Type Description
list[Parameter]

The parameters that were changed.

save(path)

Save the MCMC chain to disk.

Writes the BUMPS chain files plus a sidecar recording the column labels, because the unique names BUMPS stores are per-session and cannot be matched up again on their own.

Parameters:

Name Type Description Default
path str | os.PathLike

Path prefix for the chain files.

required

Raises:

Type Description
RuntimeError

If there is no chain to save.

load(path, skip=0)

Load a previously saved MCMC chain.

The loaded chain can be summarized, plotted, or continued with :meth:extend.

Parameters:

Name Type Description Default
path str | os.PathLike

The path prefix the chain was saved under.

required
skip int

Number of initial samples to skip when reading the chain.

0

Returns:

Type Description
SamplingResults

The loaded results, also stored on :attr:results.

plot_trace(**kwargs)

Plot the chain trace of each sampled parameter.

Parameters:

Name Type Description Default
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_trace.

{}

Returns:

Type Description
Figure

The matplotlib Figure.

plot_corner(**kwargs)

Plot the marginal and pairwise posterior distributions.

Parameters:

Name Type Description Default
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_corner.

{}

Returns:

Type Description
Figure

The matplotlib Figure.

plot_marginal(parameter, **kwargs)

Plot the marginal posterior distribution of a single sampled 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 :meth:summary reports.

Parameters:

Name Type Description Default
parameter Parameter | str

The parameter to plot, as a Parameter object or its label.

required
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_marginal.

{}

Returns:

Type Description
Figure

The matplotlib Figure.

plot_correlations(**kwargs)

Plot the Pearson correlation matrix of the sampled parameters.

A strongly correlated pair cannot be determined separately from this data. The matrix condenses what the off-diagonal panels of :meth:plot_corner show, one number per pair, which scales better to many parameters.

Parameters:

Name Type Description Default
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_correlations.

{}

Returns:

Type Description
Figure

The matplotlib Figure.

plot_posterior_predictive(n_draws=200, credible_interval=68.0, **kwargs)

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

Parameters:

Name Type Description Default
n_draws int

How many posterior draws to evaluate the model for. Each costs a full model evaluation.

200
credible_interval float

Width of the credible band, as a percentage.

68.0
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_posterior_predictive.

{}

Returns:

Type Description
Figure

The matplotlib Figure.

Raises:

Type Description
NotImplementedError

If this Analysis binds a list of datasets rather than a single one.

ValueError

If n_draws is not a positive integer.

predictions(n_draws=200)

Evaluate the model once per posterior draw, restoring the parameters afterwards.

Parameters:

Name Type Description Default
n_draws int

How many draws to evaluate, taken evenly across the chain.

200

Returns:

Type Description
np.ndarray

Model evaluations, shape (n_selected, len(x)).

MultiQPosteriorSampler(per_q, **kwargs)

Posterior sampling for an Analysis covering several Q values.

Reached as analysis.bayesian. Sampling can run either way round:

  • fit_method='independent' gives each Q index its own chain, which is cheaper and keeps the Q values from influencing one another.
  • fit_method='simultaneous' runs a single chain over every Q at once, which is what is needed when parameters are shared across Q, and costs considerably more: DREAM runs a number of chains proportional to the parameter count, and a simultaneous run has every Q's parameters in play together.

Results from independent runs stay on the per-Q samplers. This class gathers them where gathering is sound, and declines where it is not; see :meth:summary and :meth:plot_corner.

Parameters:

Name Type Description Default
per_q Callable[[], list]

Returns the per-Q Analysis objects, each exposing Q_index and its own bayesian.

required
**kwargs dict[str, Any]

Forwarded to :class:PosteriorSampler.

{}

Methods:

Name Description
sample

Draw samples from the posterior, per Q index or over all of them at once.

extend

Continue the existing simultaneous chain with additional samples.

save

Save the simultaneous MCMC chain to disk.

summary

Summarize the posterior, gathering the per-Q chains when sampling was independent.

set_parameters_to_median

Set every sampled parameter to the median of its marginal posterior.

plot_corner

Plot the marginal and pairwise posterior distributions.

plot_trace

Plot the chain trace of each sampled parameter.

plot_marginal

Plot the marginal posterior distribution of a single sampled 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.

invalidate

Mark the underlying Sampler as needing a rebuild.

suggest_bounds

Propose finite bounds for free parameters that still have an infinite one.

check_bounds

Verify that every free parameter has finite bounds.

load

Load a previously saved MCMC chain.

predictions

Evaluate the model once per posterior draw, restoring the parameters afterwards.

Attributes:

Name Type Description
results_per_q list[SamplingResults | None] | None

The per-Q chains from independent sampling, or None if there are none.

sampler Sampler | None

The EasyScience Sampler holding the chain, or None before the first run.

results SamplingResults | None

The results of the most recent run, or None if there has not been one.

Attributes
results_per_q property

The per-Q chains from independent sampling, or None if there are none.

A simultaneous run produces one chain covering every Q, which is on :attr:results.

Returns:

Type Description
list[SamplingResults | None] | None

One entry per Q index, None where that Q has not been sampled, or None overall if no Q index has been sampled.

sampler property

The EasyScience Sampler holding the chain, or None before the first run.

Returns:

Type Description
Sampler | None

The cached Sampler.

results property

The results of the most recent run, or None if there has not been one.

Returns:

Type Description
SamplingResults | None

The most recent sampling results.

Methods:
sample(samples=10000, burn=2000, thin=10, fit_method='independent', Q_index=None, **sampler_options)

Draw samples from the posterior, per Q index or over all of them at once.

Parameters:

Name Type Description Default
samples int

Number of raw samples to draw across all chains, before thinning.

10000
burn int

Burn-in generations to discard before collecting samples.

2000
thin int

Thinning interval, which reduces autocorrelation between retained draws.

10
fit_method str

Either "independent" (a separate chain per Q index) or "simultaneous" (one chain over all Q indices at once).

'independent'
Q_index int | None

With fit_method='independent', sample only this Q index. Ignored when sampling simultaneously.

None
**sampler_options dict[str, Any]

Forwarded to the underlying sampler.

{}

Returns:

Type Description
SamplingResults | list[SamplingResults]

A single result when a specific Q index was sampled or when sampling simultaneously, and otherwise one result per Q index.

Raises:

Type Description
ValueError

If fit_method is not "independent" or "simultaneous", or there are no Q values.

Notes

An IndexError or TypeError propagates from the Q_index validation if Q_index is out of range or not an int.

extend(additional_samples=5000, thin=10, parameters=None, **sampler_options)

Continue the existing simultaneous chain with additional samples.

The chains from independent sampling live on the per-Q samplers, so each is extended there rather than here.

Parameters:

Name Type Description Default
additional_samples int

Number of additional samples to draw, in the same units as samples.

5000
thin int

Thinning interval for the retained draws.

10
parameters list[Parameter] | list[str] | None

The same restriction as in :meth:PosteriorSampler.extend.

None
**sampler_options dict[str, Any]

Forwarded to the EasyScience Sampler.

{}

Returns:

Type Description
SamplingResults

The sampling results for the full extended chain.

Raises:

Type Description
RuntimeError

If the latest sampling ran per Q index, so there is no simultaneous chain here to extend, or if there is no chain at all.

Notes

A ValueError propagates from the run guards if the model or data changed since the chain was started, or if this run's parameters differ from the ones the chain holds.

save(path)

Save the simultaneous MCMC chain to disk.

The chains from independent sampling live on the per-Q samplers, so each is saved there rather than here.

Parameters:

Name Type Description Default
path str | os.PathLike

Path prefix for the chain files.

required

Raises:

Type Description
RuntimeError

If the latest sampling ran per Q index -- there is then no simultaneous chain here to save -- or if there is no chain at all.

summary(labeller=None)

Summarize the posterior, gathering the per-Q chains when sampling was independent.

Every entry is a marginal distribution of one parameter, and a marginal is well defined within its own chain, so collecting them into one table is sound even though the chains are separate. Labels carry the Q index either way, so the table reads the same.

Parameters:

Name Type Description Default
labeller Callable[[Parameter], str] | None

Overrides the label a resolved column is reported under. The default is this analysis' own Q-qualified labels.

None

Returns:

Type Description
PosteriorSummary

One entry per sampled parameter, across every Q index that has been sampled.

set_parameters_to_median()

Set every sampled parameter to the median of its marginal posterior.

Applies the per-Q chains to their own Q when sampling was independent.

Returns:

Type Description
list[Parameter]

The parameters that were changed.

plot_corner(Q_index=None, **kwargs)

Plot the marginal and pairwise posterior distributions.

After independent sampling each Q has its own chain, and no draw pairs a parameter at one Q with a parameter at another, so there is no joint distribution across Q to plot. Rather than combine them into a figure showing correlations that came from how the sampling was run, this steps through the chains one at a time: pick one with Q_index, or leave it out in a notebook to get a slider.

Parameters:

Name Type Description Default
Q_index int | None

Which Q index to plot, when the chains are per-Q. If None, a slider is returned. Not used for a simultaneous chain, which already covers every Q.

None
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_corner.

{}

Returns:

Type Description
Figure | VBox

The matplotlib Figure, or an ipywidgets box with a Q slider.

Raises:

Type Description
RuntimeError

If a slider is asked for outside a notebook.

Notes

An IndexError or TypeError propagates from the Q_index validation if Q_index is out of range or not an int.

plot_trace(Q_index=None, **kwargs)

Plot the chain trace of each sampled parameter.

A simultaneous chain is one trace and is drawn directly. After independent sampling each Q index has its own chain, so the traces are stepped through one at a time: pick one with Q_index, or leave it out in a notebook to get a slider.

Parameters:

Name Type Description Default
Q_index int | None

Which Q index to plot, when the chains are per-Q. If None, a slider is returned. Not used for a simultaneous chain, which is a single trace already.

None
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_trace.

{}

Returns:

Type Description
Figure | VBox

The matplotlib Figure, or an ipywidgets box with a Q slider.

Notes

A RuntimeError propagates if a slider is asked for outside a notebook or nothing has been sampled yet, and an IndexError or TypeError from the Q_index validation if Q_index is out of range or not an int.

plot_marginal(parameter, Q_index=None, **kwargs)

Plot the marginal posterior distribution of a single sampled parameter.

A simultaneous chain holds every Q's parameters under Q-qualified labels, so the label picks the Q as well ('Gaussian width (Q_index=1)'). After independent sampling the chains are per-Q and the parameter goes by its plain label in each; pick a chain with Q_index, or leave it out in a notebook to step through the Q values with a slider.

Parameters:

Name Type Description Default
parameter Parameter | str

The parameter to plot, as a Parameter object or its label. On the slider path a Parameter object is resolved to its display name first, so the matching parameter of every Q is shown even though the object itself belongs to one Q.

required
Q_index int | None

Which Q index to plot, when the chains are per-Q. If None, a slider is returned. Not used for a simultaneous chain, whose labels carry the Q index already.

None
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_marginal.

{}

Returns:

Type Description
Figure | VBox

The matplotlib Figure, or an ipywidgets box with a Q slider.

Notes

A ValueError propagates if the parameter matches no sampled chain column, a RuntimeError if a slider is asked for outside a notebook or nothing has been sampled yet, and an IndexError or TypeError from the Q_index validation if Q_index is out of range or not an int.

plot_correlations(Q_index=None, **kwargs)

Plot the Pearson correlation matrix of the sampled parameters.

A simultaneous chain gives one matrix over every Q's parameters at once. After independent sampling no draw pairs one Q with another, so there is one matrix per chain: pick one with Q_index, or leave it out in a notebook to get a slider.

Parameters:

Name Type Description Default
Q_index int | None

Which Q index to plot, when the chains are per-Q. If None, a slider is returned. Not used for a simultaneous chain, which already covers every Q.

None
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_correlations.

{}

Returns:

Type Description
Figure | VBox

The matplotlib Figure, or an ipywidgets box with a Q slider.

Notes

A RuntimeError propagates if a slider is asked for outside a notebook or nothing has been sampled yet, and an IndexError or TypeError from the Q_index validation if Q_index is out of range or not an int.

plot_posterior_predictive(n_draws=200, credible_interval=68.0, Q_index=None, **kwargs)

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

After independent sampling each Q has its own chain, and its own band: pick one with Q_index for a single matplotlib figure, or leave it out in a notebook to get a plopp figure with a Q slider, looking and handling exactly like Analysis.plot_data_and_model. Plopp draws no filled band, so the slider view shows the posterior median with a dashed line along each band edge instead of a shaded band.

Parameters:

Name Type Description Default
n_draws int

How many posterior draws to evaluate the model for, per Q on the slider path. Each costs a full model evaluation.

200
credible_interval float

Width of the credible band, as a percentage.

68.0
Q_index int | None

Which Q index to plot, when the chains are per-Q. If None, a slider is returned.

None
**kwargs dict[str, Any]

Forwarded to :func:easydynamics.utils.posterior_plotting.plot_posterior_predictive for a single figure, or to :func:easydynamics.utils.posterior_plotting.predictive_with_slider for the slider.

{}

Returns:

Type Description
Figure | InteractiveFigure

The matplotlib Figure for one Q, or the plopp figure with a Q slider.

Raises:

Type Description
ValueError

If n_draws is not a positive integer, or credible_interval is out of range.

Notes

A NotImplementedError propagates when the latest chain is simultaneous: it binds every dataset at once, and no per-Q chain exists for Q_index to pick out. A RuntimeError propagates if a slider is asked for outside a notebook or nothing has been sampled yet, and an IndexError or TypeError from the Q_index validation if Q_index is out of range or not an int.

invalidate()

Mark the underlying Sampler as needing a rebuild.

Called by the Analysis when its data changes, since the Sampler binds its data at construction.

suggest_bounds(n_sigma=10.0, relative_pad=0.2, absolute_floor=None)

Propose finite bounds for free parameters that still have an infinite one.

Nothing changes until :meth:BoundsSuggestions.apply is called, so the proposal can be reviewed first. Bounds that are already finite are never widened or narrowed, so physical limits such as a non-negative area are left alone.

Because the bounds act as a uniform prior in DREAM, a generous width is the safe choice: too tight a bound truncates the posterior and understates the uncertainty.

Parameters:

Name Type Description Default
n_sigma float

How many standard deviations of the fitted uncertainty to allow on each side.

10.0
relative_pad float

Extra half-width as a fraction of the absolute parameter value, guarding against minimizers that report a zero or absurdly small uncertainty.

0.2
absolute_floor float | None

A minimum half-width in the parameter's own units, for when neither the uncertainty nor the value carries the natural scale.

None

Returns:

Type Description
BoundsSuggestions

The proposed bounds, which must be applied explicitly.

check_bounds()

Verify that every free parameter has finite bounds.

Raises:

Type Description
ValueError

If any free parameter has an infinite lower or upper bound, or finite bounds that enclose no range (min >= max).

load(path, skip=0)

Load a previously saved MCMC chain.

The loaded chain can be summarized, plotted, or continued with :meth:extend.

Parameters:

Name Type Description Default
path str | os.PathLike

The path prefix the chain was saved under.

required
skip int

Number of initial samples to skip when reading the chain.

0

Returns:

Type Description
SamplingResults

The loaded results, also stored on :attr:results.

predictions(n_draws=200)

Evaluate the model once per posterior draw, restoring the parameters afterwards.

Parameters:

Name Type Description Default
n_draws int

How many draws to evaluate, taken evenly across the chain.

200

Returns:

Type Description
np.ndarray

Model evaluations, shape (n_selected, len(x)).

Functions: