Skip to content

fitting

Modules:

Name Description
engine_base
fitter
minimizers
multi_fitter
reshaping

Data reshaping and fit-function wrapping shared by Fitter and Sampler.

sampler

Bayesian MCMC sampling — the Sampler class and persistence helpers.

samplers

Classes

Modules

engine_base

Classes:

Name Description
EngineBase

Base for all evaluation engines: minimizers and samplers.

Classes

EngineBase(obj, fit_function)

Base for all evaluation engines: minimizers and samplers.

An engine binds an EasyScience object and a fit function, and repeatedly evaluates the function while writing values back into the object's Parameter instances. EngineBase owns this shared system: the parameter cache, the Parameter-writing wrapped fit function, and value restore on failure. It deliberately declares no abstract methods: the interfaces are defined on its subclasses (MinimizerBase.fit, DreamSampler.run).

Methods:

Name Description
validate_arrays

Validate the (x, y, weights) arrays handed to an engine.

evaluate

Evaluate the fit function for values of x.

Methods:
validate_arrays(x, y, weights) staticmethod

Validate the (x, y, weights) arrays handed to an engine.

Parameters:

Name Type Description Default
x np.ndarray

Independent variable array.

required
y np.ndarray

Dependent variable array.

required
weights np.ndarray

Weight array.

required

Raises:

Type Description
ValueError

If any array is non-numeric, the shapes disagree, x or y contain NaN or infinite values, or the weights are non-finite or non-positive.

evaluate(x, parameters=None, **kwargs)

Evaluate the fit function for values of x.

Parameters used are either the latest or user supplied. If the parameters are user supplied, it must be in a dictionary of {'parameter_name': parameter_value,...}.

Parameters:

Name Type Description Default
x np.ndarray

X values for which the fit function will be evaluated.

required
parameters dict[str, float] | None

Dictionary of parameters which will be used in the fit function. They must be in a dictionary of {'parameter_name': parameter_value,...}. By default, None.

None
**kwargs

Additional arguments.

{}

Returns:

Type Description
np.ndarray

Y values calculated at points x for a set of parameters.

Raises:

Type Description
TypeError

If parameters is not a dictionary.

fitter

Classes:

Name Description
Fitter

Fitter is a class which makes it possible to undertake fitting

Classes

Fitter(fit_object, fit_function)

Fitter is a class which makes it possible to undertake fitting utilizing one of the supported minimizers.

Methods:

Name Description
initialize

Set the model and callable.

switch_minimizer

Switch minimizer and initialize.

Attributes:

Name Type Description
available_minimizers List[Minimizers]

Get a list of the available fitting minimizers.

minimizer MinimizerBase

Get the current fitting minimizer object.

tolerance float

Get the tolerance for the minimizer.

max_evaluations int

Get the maximal number of evaluations for the minimizer.

fit_function Callable

Get the raw fit function that the optimizer will call.

fit_object object

Get the EasyScience object used as a model.

fit Callable

Property which wraps the current fit function from the

Attributes
available_minimizers property

Get a list of the available fitting minimizers.

Returns:

Type Description
List[Minimizers]

List of available fitting minimizers.

minimizer property

Get the current fitting minimizer object.

Returns:

Type Description
MinimizerBase
tolerance property writable

Get the tolerance for the minimizer.

Returns:

Type Description
float

Tolerance for the minimizer.

max_evaluations property writable

Get the maximal number of evaluations for the minimizer.

Returns:

Type Description
int

Maximal number of steps for the minimizer.

fit_function property writable

Get the raw fit function that the optimizer will call.

Returns:

Type Description
Callable

Raw fit function.

fit_object property writable

Get the EasyScience object used as a model.

For a Fitter this is not one of the supplied fit objects but a read-only, indexable and iterable aggregate.

Returns:

Type Description
object

EasyScience model object.

fit property

Property which wraps the current fit function from the fitting interface.

This property return a wrapped fit function which converts the input data into the correct shape for the optimizer, wraps the fit function to re-constitute the independent variables and once the fit is completed, reshape the inputs to those expected.

Methods:
initialize(fit_object, fit_function)

Set the model and callable.

Parameters:

Name Type Description Default
fit_object object

The EasyScience model object.

required
fit_function Callable

The function to be optimized against.

required
switch_minimizer(minimizer_enum)

Switch minimizer and initialize.

Parameters:

Name Type Description Default
minimizer_enum Minimizers

The enum of the minimizer to create and instantiate.

required

Raises:

Type Description
TypeError

If minimizer_enum is not a Minimizers member.

Functions:

minimizers

Modules:

Name Description
bumps_utils
minimizer_base
minimizer_bumps
minimizer_dfo
minimizer_lmfit
utils

Classes

Modules

bumps_utils

Modules:

Name Description
eval_counter
problem

BUMPS problem construction shared by the Bumps minimizer and

progress_monitor
Classes
Functions:
Modules
eval_counter

Classes:

Name Description
EvalCounter

Wrap a callable so the number of invocations is recorded on

Classes
EvalCounter(fn)

Wrap a callable so the number of invocations is recorded on count.

Used by the BUMPS minimizer to count objective-function evaluations for cross-backend consistency with LMFit (nfev) and DFO-LS (nf).

problem

BUMPS problem construction shared by the Bumps minimizer and DreamSampler.

These are free functions rather than Bumps methods so that any :class:~easyscience.fitting.engine_base.EngineBase: a minimizer or a sampler, can build a BUMPS Curve/FitProblem without inheriting from the minimizer.

Functions:

Name Description
to_bumps_parameter

Convert an EasyScience Parameter to a prefixed BumpsParameter.

build_curve_problem

Build a BUMPS FitProblem around an engine's wrapped fit function.

parameter_names

Return the problem's parameter names with the prefix stripped.

parameter_snapshot

Snapshot the problem's parameter values as {name: value}.

Classes Functions:
to_bumps_parameter(par)

Convert an EasyScience Parameter to a prefixed BumpsParameter.

Parameters:

Name Type Description Default
par Parameter

EasyScience parameter to convert.

required

Returns:

Type Description
BumpsParameter

Bumps Parameter compatible object, named PARAMETER_PREFIX + par.unique_name.

build_curve_problem(engine, x, y, weights)

Build a BUMPS FitProblem around an engine's wrapped fit function.

Wraps engine._generate_fit_function() in an :class:EvalCounter, converts the engine's cached parameters via :func:to_bumps_parameter, and assembles Curve(fit_func, x, y, dy=1/weights, **bumps_pars) into a FitProblem.

Parameters:

Name Type Description Default
engine EngineBase

The engine (minimizer or sampler) supplying the fit function and parameter cache.

required
x np.ndarray

Independent variable array.

required
y np.ndarray

Dependent variable array.

required
weights np.ndarray

Weight array; converted to dy = 1 / weights.

required

Returns:

Type Description
tuple[FitProblem, EvalCounter, Curve]

The assembled problem, the evaluation counter wrapping the fit function, and the Curve model itself. The Curve is returned because FitProblem.fitness is deprecated in current BUMPS.

parameter_names(problem)

Return the problem's parameter names with the prefix stripped.

Parameters:

Name Type Description Default
problem FitProblem

A BUMPS problem built by :func:build_curve_problem.

required

Returns:

Type Description
list[str]

Parameter names in problem order, without PARAMETER_PREFIX.

parameter_snapshot(problem, point)

Snapshot the problem's parameter values as {name: value}.

Parameters:

Name Type Description Default
problem FitProblem

A BUMPS problem built by :func:build_curve_problem.

required
point np.ndarray | None

Parameter values to report; when None the problem's current values (problem.getp()) are used.

required

Returns:

Type Description
dict

Mapping of prefix-stripped parameter names to float values.

progress_monitor

Classes:

Name Description
BumpsProgressMonitor

BUMPS :class:Monitor that forwards per-step progress information

Classes
BumpsProgressMonitor(problem, callback, payload_builder)

BUMPS :class:Monitor that forwards per-step progress information to a user-supplied callback.

The monitor delegates payload construction to payload_builder so the BUMPS minimizer can keep all backend-specific payload semantics in one place.

minimizer_base

Classes:

Name Description
MinimizerBase

This template class is the basis for all minimizer engines in

Classes
MinimizerBase(obj, fit_function, minimizer_enum)

This template class is the basis for all minimizer engines in EasyScience.

Methods:

Name Description
fit

Perform a fit using the engine.

supported_methods

Return a list of supported methods for the minimizer.

all_methods

Return a list of all available methods for the minimizer.

validate_arrays

Validate the (x, y, weights) arrays handed to an engine.

evaluate

Evaluate the fit function for values of x.

Methods:
fit(x, y, weights, method=None, tolerance=None, max_evaluations=None, progress_callback=None, **kwargs) abstractmethod

Perform a fit using the engine.

Parameters:

Name Type Description Default
x np.ndarray

Points to be calculated at.

required
y np.ndarray

Measured points.

required
weights np.ndarray

Weights for supplied measured points.

required
method str | None

Method for the minimizer to use. By default, None.

None
tolerance float | None

Requested convergence tolerance. By default, None.

None
max_evaluations int | None

Maximum number of objective evaluations. By default, None.

None
progress_callback Callable[[dict], None] | None

Optional progress callback. Its return value is ignored by every backend; use abort_test to stop a running fit. By default, None.

None
**kwargs

Additional arguments for the fitting function.

{}

Returns:

Type Description
FitResults

Fit results.

supported_methods() abstractmethod staticmethod

Return a list of supported methods for the minimizer.

Returns:

Type Description
List[str]

List of supported methods.

all_methods() abstractmethod staticmethod

Return a list of all available methods for the minimizer.

Returns:

Type Description
List[str]

List of all available methods.

validate_arrays(x, y, weights) staticmethod

Validate the (x, y, weights) arrays handed to an engine.

Parameters:

Name Type Description Default
x np.ndarray

Independent variable array.

required
y np.ndarray

Dependent variable array.

required
weights np.ndarray

Weight array.

required

Raises:

Type Description
ValueError

If any array is non-numeric, the shapes disagree, x or y contain NaN or infinite values, or the weights are non-finite or non-positive.

evaluate(x, parameters=None, **kwargs)

Evaluate the fit function for values of x.

Parameters used are either the latest or user supplied. If the parameters are user supplied, it must be in a dictionary of {'parameter_name': parameter_value,...}.

Parameters:

Name Type Description Default
x np.ndarray

X values for which the fit function will be evaluated.

required
parameters dict[str, float] | None

Dictionary of parameters which will be used in the fit function. They must be in a dictionary of {'parameter_name': parameter_value,...}. By default, None.

None
**kwargs

Additional arguments.

{}

Returns:

Type Description
np.ndarray

Y values calculated at points x for a set of parameters.

Raises:

Type Description
TypeError

If parameters is not a dictionary.

minimizer_bumps

Classes:

Name Description
Bumps

This is a wrapper to Bumps: https://bumps.readthedocs.io/ It allows

Classes
Bumps(obj, fit_function, minimizer_enum=None)

This is a wrapper to Bumps: https://bumps.readthedocs.io/ It allows for the Bumps fitting engine to use parameters declared in an easyscience.base_classes.ModelBase.

Parameters:

Name Type Description Default
obj object

Object containing the Parameter instances to fit.

required
fit_function Callable

Callable returning model y values for the supplied x values.

required
minimizer_enum Minimizers | None

Selected BUMPS minimizer configuration. By default, None.

None

Methods:

Name Description
fit

Perform a fit using the BUMPS engine.

validate_arrays

Validate the (x, y, weights) arrays handed to an engine.

evaluate

Evaluate the fit function for values of x.

Methods:
fit(x, y, weights, method=None, tolerance=None, max_evaluations=None, progress_callback=None, abort_test=None, minimizer_kwargs=None, engine_kwargs=None, **kwargs)

Perform a fit using the BUMPS engine.

Parameters:

Name Type Description Default
x np.ndarray

Points to be calculated at.

required
y np.ndarray

Measured points.

required
weights np.ndarray

Weights for supplied measured points.

required
method str | None

Method for minimization. By default, None.

None
tolerance float | None

Requested optimizer tolerance. By default, None.

None
max_evaluations int | None

Maximum number of optimizer steps. Forwarded to BUMPS as its steps parameter. If None, the default value defined by the selected BUMPS fitter (fitclass.settings) is used. By default, None.

None
progress_callback Callable[[dict], None] | None

Optional callback for progress updates. The field iteration carries the BUMPS optimizer step index. The return value is ignored: use abort_test to stop a running fit. By default, None.

None
abort_test Callable[[], bool] | None

Optional callback that returns True to signal that the fit should be aborted. Called periodically during the BUMPS optimizer iteration loop, and once more after the optimizer returns in order to distinguish an aborted fit from a converged one, so it must be side-effect free. An aborted fit returns FitResults(success=False) rather than raising.

None
minimizer_kwargs dict | None

Additional keyword arguments passed to the BUMPS minimizer. The mapping is copied before use, so it is never mutated. By default, None.

None
engine_kwargs dict | None

Additional engine keyword arguments. By default, None.

None
**kwargs Any

Additional keyword arguments passed to FitDriver.

{}

Returns:

Type Description
FitResults

Fit results. FitResults.iterations is the number of BUMPS optimizer steps consumed (the last reported step index plus one), which is what max_evaluations tests against; it is not comparable to LMFit's nfev or DFO-LS' nf. The objective-call count is reported separately as FitResults.n_evaluations, which is the cross-backend consistent figure. Note that BUMPS derives the step index from whatever the selected fitter reports to its monitors, so the granularity of a "step" varies between fitters.

Raises:

Type Description
FitError

If the BUMPS fit raises. A fit that merely fails to converge is reported as FitResults(success=False) instead.

ValueError

If the input shapes or weights are invalid, or if progress_callback is not callable.

validate_arrays(x, y, weights) staticmethod

Validate the (x, y, weights) arrays handed to an engine.

Parameters:

Name Type Description Default
x np.ndarray

Independent variable array.

required
y np.ndarray

Dependent variable array.

required
weights np.ndarray

Weight array.

required

Raises:

Type Description
ValueError

If any array is non-numeric, the shapes disagree, x or y contain NaN or infinite values, or the weights are non-finite or non-positive.

evaluate(x, parameters=None, **kwargs)

Evaluate the fit function for values of x.

Parameters used are either the latest or user supplied. If the parameters are user supplied, it must be in a dictionary of {'parameter_name': parameter_value,...}.

Parameters:

Name Type Description Default
x np.ndarray

X values for which the fit function will be evaluated.

required
parameters dict[str, float] | None

Dictionary of parameters which will be used in the fit function. They must be in a dictionary of {'parameter_name': parameter_value,...}. By default, None.

None
**kwargs

Additional arguments.

{}

Returns:

Type Description
np.ndarray

Y values calculated at points x for a set of parameters.

Raises:

Type Description
TypeError

If parameters is not a dictionary.

Functions:
minimizer_dfo

Classes:

Name Description
DFOCallbackState

Snapshot of a DFO objective evaluation.

DFO

This is a wrapper to Derivative Free Optimisation for Least Square:

Classes
DFOCallbackState(evaluation, xk, residuals, objective, parameters, best_xk, best_objective, best_parameters, improved) dataclass

Snapshot of a DFO objective evaluation.

DFO(obj, fit_function, minimizer_enum=None)

This is a wrapper to Derivative Free Optimisation for Least Square: https://numericalalgorithmsgroup.github.io/dfols/.

Parameters:

Name Type Description Default
obj object

Object containing the Parameter instances to fit.

required
fit_function Callable

Callable returning model y values for the supplied x values.

required
minimizer_enum Minimizers | None

Selected DFO minimizer configuration. By default, None.

None

Methods:

Name Description
fit

Perform a fit using the DFO-ls engine.

validate_arrays

Validate the (x, y, weights) arrays handed to an engine.

evaluate

Evaluate the fit function for values of x.

Methods:
fit(x, y, weights, method=None, tolerance=None, max_evaluations=None, progress_callback=None, callback=None, **kwargs)

Perform a fit using the DFO-ls engine.

Parameters:

Name Type Description Default
x np.ndarray

Points to be calculated at.

required
y np.ndarray

Measured points.

required
weights np.ndarray

Weights for supplied measured points.

required
method str | None

Method for minimization. By default, None.

None
tolerance float | None

Requested optimizer tolerance. By default, None.

None
max_evaluations int | None

Maximum number of evaluations. By default, None.

None
progress_callback Callable[[dict], None] | None

Optional callback receiving normalized progress payloads. Its return value is ignored.

None
callback Callable[[DFOCallbackState], None] | None

Optional native DFO callback.

None
**kwargs

Additional arguments for the fitting function.

{}

Returns:

Type Description
FitResults

Fit results should be 1/sigma, where sigma is the standard deviation of the measurement. For unweighted least squares, these should be 1.

Raises:

Type Description
FitError

If the DFO fit fails.

validate_arrays(x, y, weights) staticmethod

Validate the (x, y, weights) arrays handed to an engine.

Parameters:

Name Type Description Default
x np.ndarray

Independent variable array.

required
y np.ndarray

Dependent variable array.

required
weights np.ndarray

Weight array.

required

Raises:

Type Description
ValueError

If any array is non-numeric, the shapes disagree, x or y contain NaN or infinite values, or the weights are non-finite or non-positive.

evaluate(x, parameters=None, **kwargs)

Evaluate the fit function for values of x.

Parameters used are either the latest or user supplied. If the parameters are user supplied, it must be in a dictionary of {'parameter_name': parameter_value,...}.

Parameters:

Name Type Description Default
x np.ndarray

X values for which the fit function will be evaluated.

required
parameters dict[str, float] | None

Dictionary of parameters which will be used in the fit function. They must be in a dictionary of {'parameter_name': parameter_value,...}. By default, None.

None
**kwargs

Additional arguments.

{}

Returns:

Type Description
np.ndarray

Y values calculated at points x for a set of parameters.

Raises:

Type Description
TypeError

If parameters is not a dictionary.

minimizer_lmfit

Classes:

Name Description
LMFit

This is a wrapper to the extended Levenberg-Marquardt Fit:

Classes
LMFit(obj, fit_function, minimizer_enum=None)

This is a wrapper to the extended Levenberg-Marquardt Fit: https://lmfit.github.io/lmfit-py/ It allows for the lmfit fitting engine to use parameters declared in an easyscience.base_classes.ModelBase.

Parameters:

Name Type Description Default
obj object

Object containing the Parameter instances to fit.

required
fit_function Callable

Callable returning model y values for the supplied x values.

required
minimizer_enum Minimizers | None

Selected LMFit minimizer configuration. By default, None.

None

Methods:

Name Description
fit

Perform a fit using the lmfit engine.

validate_arrays

Validate the (x, y, weights) arrays handed to an engine.

evaluate

Evaluate the fit function for values of x.

Methods:
fit(x, y, weights=None, method=None, tolerance=None, max_evaluations=None, progress_callback=None, minimizer_kwargs=None, engine_kwargs=None, **kwargs)

Perform a fit using the lmfit engine.

Parameters:

Name Type Description Default
x np.ndarray

Points to be calculated at.

required
y np.ndarray

Measured points.

required
weights np.ndarray

Weights for supplied measured points. By default, None.

None
method str | None

Minimizer method. By default, None.

None
tolerance float | None

Requested optimizer tolerance. By default, None.

None
max_evaluations int | None

Maximum number of function evaluations. By default, None.

None
progress_callback Callable[[dict], None] | None

Optional callback receiving normalized progress payloads. Its return value is ignored.

None
minimizer_kwargs dict | None

Additional keyword arguments passed to LMFit's minimizer. By default, None.

None
engine_kwargs dict | None

Additional engine keyword arguments. By default, None.

None
**kwargs

Additional arguments for the fitting function.

{}

Returns:

Type Description
FitResults

Fit results should be 1/sigma, where sigma is the standard deviation of the measurement. For unweighted least squares, these should be 1.

Raises:

Type Description
FitError

If the LMFit optimization fails.

validate_arrays(x, y, weights) staticmethod

Validate the (x, y, weights) arrays handed to an engine.

Parameters:

Name Type Description Default
x np.ndarray

Independent variable array.

required
y np.ndarray

Dependent variable array.

required
weights np.ndarray

Weight array.

required

Raises:

Type Description
ValueError

If any array is non-numeric, the shapes disagree, x or y contain NaN or infinite values, or the weights are non-finite or non-positive.

evaluate(x, parameters=None, **kwargs)

Evaluate the fit function for values of x.

Parameters used are either the latest or user supplied. If the parameters are user supplied, it must be in a dictionary of {'parameter_name': parameter_value,...}.

Parameters:

Name Type Description Default
x np.ndarray

X values for which the fit function will be evaluated.

required
parameters dict[str, float] | None

Dictionary of parameters which will be used in the fit function. They must be in a dictionary of {'parameter_name': parameter_value,...}. By default, None.

None
**kwargs

Additional arguments.

{}

Returns:

Type Description
np.ndarray

Y values calculated at points x for a set of parameters.

Raises:

Type Description
TypeError

If parameters is not a dictionary.

utils

Classes:

Name Description
FitResults

At the moment this is just a dummy way of unifying the returned fit

Classes
FitResults()

At the moment this is just a dummy way of unifying the returned fit parameters.

multi_fitter

Classes:

Name Description
MultiFitter

Extension of Fitter to enable multiple dataset/fit function fitting.

Classes

MultiFitter(fit_objects=None, fit_functions=None)

Extension of Fitter to enable multiple dataset/fit function fitting.

We can fit these types of data simultaneously: - Multiple models on multiple datasets.

The inherited fit wrapper from Fitter is used unchanged, including support for forwarding progress callbacks to the active minimizer.

Methods:

Name Description
initialize

Set the model and callable.

switch_minimizer

Switch minimizer and initialize.

Attributes:

Name Type Description
fit_functions list[Callable]

Get the per-dataset fit functions, in dataset order.

available_minimizers List[Minimizers]

Get a list of the available fitting minimizers.

minimizer MinimizerBase

Get the current fitting minimizer object.

tolerance float

Get the tolerance for the minimizer.

max_evaluations int

Get the maximal number of evaluations for the minimizer.

fit_function Callable

Get the raw fit function that the optimizer will call.

fit_object object

Get the EasyScience object used as a model.

fit Callable

Property which wraps the current fit function from the

Attributes
fit_functions property

Get the per-dataset fit functions, in dataset order.

Returns:

Type Description
list[Callable]

One fit function per dataset.

available_minimizers property

Get a list of the available fitting minimizers.

Returns:

Type Description
List[Minimizers]

List of available fitting minimizers.

minimizer property

Get the current fitting minimizer object.

Returns:

Type Description
MinimizerBase
tolerance property writable

Get the tolerance for the minimizer.

Returns:

Type Description
float

Tolerance for the minimizer.

max_evaluations property writable

Get the maximal number of evaluations for the minimizer.

Returns:

Type Description
int

Maximal number of steps for the minimizer.

fit_function property writable

Get the raw fit function that the optimizer will call.

Returns:

Type Description
Callable

Raw fit function.

fit_object property writable

Get the EasyScience object used as a model.

For a Fitter this is not one of the supplied fit objects but a read-only, indexable and iterable aggregate.

Returns:

Type Description
object

EasyScience model object.

fit property

Property which wraps the current fit function from the fitting interface.

This property return a wrapped fit function which converts the input data into the correct shape for the optimizer, wraps the fit function to re-constitute the independent variables and once the fit is completed, reshape the inputs to those expected.

Methods:
initialize(fit_object, fit_function)

Set the model and callable.

Parameters:

Name Type Description Default
fit_object object

The EasyScience model object.

required
fit_function Callable

The function to be optimized against.

required
switch_minimizer(minimizer_enum)

Switch minimizer and initialize.

Parameters:

Name Type Description Default
minimizer_enum Minimizers

The enum of the minimizer to create and instantiate.

required

Raises:

Type Description
TypeError

If minimizer_enum is not a Minimizers member.

Functions:

reshaping

Data reshaping and fit-function wrapping shared by Fitter and Sampler.

Both fitting and sampling provide the engine witha flat 1-D y array and a dummy 1-D x index array, while the user's fit function is called with the real x. The helpers here do the translation in one place: reshape_dataset/inject_x do one dataset, reshape_datasets/inject_x_multi do a list of datasets.

Functions:

Name Description
reshape_dataset

Check the dimensions of the inputs and reshape if necessary.

reshape_datasets

Convert a list of X's and Y's to an acceptable shape for fitting.

inject_x

Wrap a fit function so it ignores the engine's dummy x and evaluates

inject_x_multi

Wrap one fit function per dataset into a single function whose output

Functions:

reshape_dataset(x, y, weights, vectorized)

Check the dimensions of the inputs and reshape if necessary.

Parameters:

Name Type Description Default
x np.ndarray

Independent points; 1-D, or ND with the coordinate components on the last axis.

required
y np.ndarray

Dependent points, one per observation.

required
weights np.ndarray | None

Optional weights for the fit.

required
vectorized bool

Whether x already stores vectorized coordinates.

required

Returns:

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

Dummy x index array for the engine, reshaped x values, flattened y values, flattened weights, and the shape of y (the dependent dimensions; its product is the number of observations, which the multi-dataset helpers use to slice the combined output).

Raises:

Type Description
ValueError

If the shapes of x and y are incompatible.

reshape_datasets(x, y, weights, vectorized)

Convert a list of X's and Y's to an acceptable shape for fitting.

Parameters:

Name Type Description Default
x list[np.ndarray]

List of independent variables.

required
y list[np.ndarray]

List of dependent variables.

required
weights list[np.ndarray] | None

Optional weights for each dataset.

required
vectorized bool

When True, each x array may be multi-dimensional (e.g. an (N, M, 2) grid for a 2D model) and is left as-is. When False (default), each x array is expected to be 1-D.

required

Returns:

Type Description
tuple[np.ndarray, list[np.ndarray], np.ndarray, np.ndarray | None, list[tuple[int, ...]]]

Dummy x index array for the engine, per-dataset reshaped x values, concatenated y values, concatenated weights, and the per-dataset dependent dimensions.

inject_x(fit_function, real_x=None, flatten=True)

Wrap a fit function so it ignores the engine's dummy x and evaluates on real_x instead, flattening the result if needed.

Parameters:

Name Type Description Default
fit_function Callable

The user's fit function.

required
real_x np.ndarray | None

Independent x values to be injected. By default, None.

None
flatten bool

Should the result be a flat 1D array? By default, True.

True

Returns:

Type Description
Callable

Wrapped optimizer function.

inject_x_multi(fit_functions, real_x, dims, flatten=True)

Wrap one fit function per dataset into a single function whose output is the concatenation of the per-dataset outputs.

Parameters:

Name Type Description Default
fit_functions list[Callable]

One fit function per dataset.

required
real_x list[np.ndarray]

One independent x array per dataset, injected into the matching fit function.

required
dims list[tuple[int, ...]]

Per-dataset dependent (y) shapes used to slice the combined output, as returned by reshape_datasets.

required
flatten bool

Should each per-dataset result be flattened? By default, True.

True

Returns:

Type Description
Callable

Wrapped optimizer function.

sampler

Bayesian MCMC sampling — the Sampler class and persistence helpers.

Classes:

Name Description
SamplingResults

Structured result of an MCMC sampling run (analogous to FitResults).

Sampler

Bayesian MCMC sampler for one dataset, backed by the BUMPS DREAM engine.

Functions:

Name Description
load_chain

Reload a DREAM chain state saved by Sampler.save.

Classes

SamplingResults(draws, param_names, logp, state) dataclass

Structured result of an MCMC sampling run (analogous to FitResults).

Attributes:

Name Type Description
draws np.ndarray

Posterior samples, shape (n_samples, n_params). For results from Sampler.sample()/Sampler.extend() this is a trimmed, outlier-filtered view of the chain, not the raw buffer, so it holds fewer rows than samples / thin — see the notes on Sampler.

param_names list[str]

Parameter names (one per column of draws).

logp np.ndarray

Log-posterior values, shape (n_samples,).

state MCMCDraw

The raw BUMPS chain state, holding the full untrimmed chain.

Sampler(fit_object, fit_function, x, y, weights, vectorized=False, sampler_kwargs=None)

Bayesian MCMC sampler for one dataset, backed by the BUMPS DREAM engine.

One Sampler instance represents one chain over one (x, y, weights) dataset. The data is bound at construction; sample() and extend() take no data arguments, so a chain can never be extended against different data (undefined behaviour in BUMPS). The bound data is a defensive, read-only copy of the caller's arrays, exposed via the x, y and weights properties — mutating the originals after construction has no effect on the sampler, and there are deliberately no setters: to sample different data, create a new Sampler.

Sampler is a parallel entry point to Fitter: it takes the same (fit_object, fit_function) pair plus the data.

Parameters:

Name Type Description Default
fit_object object

The EasyScience model object holding the Parameter instances to sample. For multiple datasets this is one object exposing all the parameters (for example an EasyList of models, or the fit_object of a MultiFitter).

required
fit_function Callable | list[Callable]

The model function, or one per dataset when x, y and weights are lists of arrays.

required
x np.ndarray | list[np.ndarray]

Independent variable array (or list of arrays, one per dataset).

required
y np.ndarray | list[np.ndarray]

Dependent variable array (or list of arrays, one per dataset).

required
weights np.ndarray | list[np.ndarray]

Weight array (or list of arrays, one per dataset). Required: sampling has no default weighting, so a missing weight array is rejected here rather than deep inside the sampling engine.

required
vectorized bool

When True, each x array may be multi-dimensional (e.g. an (N, M, 2) grid for a 2D model) and is left as-is.

False
sampler_kwargs dict | None

Per-instance default keyword arguments forwarded to the BUMPS DREAM sampler on every run, merged with (and overridden by) per-call sampler_kwargs.

None

Raises:

Type Description
TypeError

If fit_object has no get_free_parameters, fit_function is not callable, any dataset in x/y/weights is not a numeric array (e.g. a string), or vectorized/sampler_kwargs have the wrong type.

ValueError

If fit_function, x, y and weights do not hold matching structures (all single, or lists of the same length), or any dataset is a scalar or empty array.

Notes

The retained draws are a trimmed view, not the whole chain. BUMPS' DREAM sampler defaults to trim=True: once sampling finishes it runs a convergence-based burn-point detector over the chain and returns only the portion after that point. state.draw() additionally drops chains flagged as outliers. So results.draws is usually smaller than the chain, and its length is not deterministic — the detector re-runs from scratch on every sample() and extend() call and may place the burn point differently each time. Read the count off the array; do not predict it.

Nor is the chain itself exactly samples / thin rows: samples is a guaranteed minimum, not an exact count. DREAM advances in blocks of 10 generations (one generation = one draw per chain) and only checks its stopping condition between blocks, so the raw chain length is samples rounded up to a multiple of 10 * n_chains.

The trimming is only a view — nothing is dropped from the buffer. To read the full untrimmed chain::

results = sampler.sample(samples=10000, burn=500, thin=2)
full = results.state.draw(portion=1.0, outliers=True)
full.points  # (n_chain_rows, n_params)
full.logp

To switch the automatic trimming off entirely, pass BUMPS' own trim option straight through sampler_kwargs; results.draws then holds the whole chain::

sampler = Sampler(
    parameter_container,
    model_function,
    x,
    y,
    weights=w,
    sampler_kwargs={'trim': False},
)

Note also that trimming does not survive a save()/load_state() round-trip: BUMPS does not persist the trim point, so a reloaded chain comes back untrimmed and load_state() reports more draws than the sample() call that created it. The chain itself is identical.

Methods:

Name Description
from_fitter

Build a Sampler from the model bound to an existing Fitter.

sample

Run fresh Bayesian MCMC sampling on the bound data.

extend

Continue the existing chain with additional samples.

save

Persist the chain state and metadata to disk.

load_state

Load a previously saved chain into this sampler.

Attributes:

Name Type Description
fit_object object

The EasyScience model object holding the sampled parameters (read-only).

fit_function Callable | list[Callable]

The model function, or list of them for multiple datasets (read-only).

x np.ndarray | list[np.ndarray]

The bound independent variable data (read-only copy).

y np.ndarray | list[np.ndarray]

The bound dependent variable data (read-only copy).

weights np.ndarray | list[np.ndarray]

The bound weight data (read-only copy).

state MCMCDraw | None

Raw BUMPS MCMCDraw state (None before first sample/load_state).

results SamplingResults | None

Results of the most recent sample/extend/load_state call.

draws np.ndarray | None

Posterior draws from the most recent run (or None).

param_names list[str] | None

Parameter names from the most recent run (or None).

logp np.ndarray | None

Log-posterior values from the most recent run (or None).

Attributes
fit_object property

The EasyScience model object holding the sampled parameters (read-only).

fit_function property

The model function, or list of them for multiple datasets (read-only).

x property

The bound independent variable data (read-only copy).

y property

The bound dependent variable data (read-only copy).

weights property

The bound weight data (read-only copy).

state property

Raw BUMPS MCMCDraw state (None before first sample/load_state).

results property

Results of the most recent sample/extend/load_state call.

draws property

Posterior draws from the most recent run (or None).

param_names property

Parameter names from the most recent run (or None).

logp property

Log-posterior values from the most recent run (or None).

Methods:
from_fitter(fitter, x, y, weights, vectorized=False, sampler_kwargs=None) classmethod

Build a Sampler from the model bound to an existing Fitter.

A convenience for the common fit-then-sample workflow: the sampler takes the fitter's fit_object and fit function(s) and is otherwise identical to one constructed directly. The fitter is not retained or modified. A MultiFitter yields a multi-dataset sampler, so x, y and weights must then be lists of arrays.

Parameters:

Name Type Description Default
fitter Fitter

A configured Fitter or MultiFitter. It does not need to have been fitted.

required
x np.ndarray | list[np.ndarray]

Independent variable array (or list of arrays, one per dataset).

required
y np.ndarray | list[np.ndarray]

Dependent variable array (or list of arrays, one per dataset).

required
weights np.ndarray | list[np.ndarray]

Weight array (or list of arrays, one per dataset).

required
vectorized bool

See Sampler.

False
sampler_kwargs dict | None

See Sampler.

None

Returns:

Type Description
Sampler

A sampler bound to the fitter's model and the given data.

sample(samples=10000, burn=2000, thin=10, population=None, sampler_kwargs=None, progress_callback=None, abort_test=None)

Run fresh Bayesian MCMC sampling on the bound data.

Calling sample() on a sampler that already holds a chain starts a fresh chain — the previous state and results are replaced. Use extend() to continue an existing chain.

Parameters:

Name Type Description Default
samples int

Number of raw samples to draw across all chains, before thinning. This is a guaranteed minimum, not an exact count: DREAM advances in blocks of 10 generations (one generation = one draw per chain) and stops at the first block boundary at or past samples.

10000
burn int

Burn-in generations to discard before collecting samples. Note BUMPS counts burn in generations while samples counts raw draws, so burn=500 discards 500 * n_chains raw samples.

2000
thin int

Thinning interval — only every thin-th generation is kept, which reduces autocorrelation between consecutive draws.

10
population int | None

DREAM population scale factor (not an absolute chain count): BUMPS creates ceil(population * n_parameters) parallel chains.

None
sampler_kwargs dict | None

Additional keyword arguments forwarded to the BUMPS DREAM sampler (merged over the instance defaults).

None
progress_callback Callable[[dict], None] | None

Optional callback invoked at each DREAM generation. The payload dict includes iteration and sampling: True. Any return value is ignored.

None
abort_test Callable[[], bool] | None

Optional callable that returns True to abort sampling early.

None

Returns:

Type Description
SamplingResults

Structured sampling results (also stored on results).

Notes

results.draws is a trimmed, outlier-filtered view of the chain, so it is usually smaller than the chain and its length is not predictable from samples/thin. See the Sampler class notes for how to read the full chain or switch trimming off.

Exceptions propagate from the sampling engine: ValueError if samples, burn, or thin are invalid, and RuntimeError if the bumps package is not installed.

extend(additional_samples=5000, thin=10, total_samples=None, sampler_kwargs=None, progress_callback=None, abort_test=None)

Continue the existing chain with additional samples.

DREAM stores draws in a fixed-size ring buffer sized to its samples parameter; this method does the ring-buffer arithmetic for you (samples = stored_generations * population + additional_samples) so no existing draws are dropped from the buffer, regardless of the thinning interval. Runs with burn=0 — re-burning a converged chain is usually a mistake, and BUMPS forces it to 0 on resume in any case. The DREAM population is recovered from the saved state and cannot be changed on extend.

Parameters:

Name Type Description Default
additional_samples int

Number of additional DREAM samples to draw, in the same units as samples in sample(). This grows the ring buffer by exactly additional_samples; how many of the new draws become visible in results.draws depends on the thinning interval and on BUMPS' automatic trimming (see Notes).

5000
thin int

Thinning interval for the retained draws.

10
total_samples int | None

Advanced: total retained samples requested from the ring buffer, overriding the additional_samples arithmetic. With total_samples=N, only the last N draws are retained.

None
sampler_kwargs dict | None

Additional keyword arguments forwarded to the BUMPS DREAM sampler (merged over the instance defaults).

None
progress_callback Callable[[dict], None] | None

Optional callback invoked at each DREAM generation. Any return value is ignored.

None
abort_test Callable[[], bool] | None

Optional callable that returns True to abort sampling early.

None

Returns:

Type Description
SamplingResults

Structured sampling results for the full (extended) chain.

Raises:

Type Description
RuntimeError

If there is no chain to extend (call sample() or load_state() first), or the bumps package is not installed.

Notes

results.draws will not grow by exactly additional_samples / thin. Two things get in the way, neither of them a re-applied burn-in: BUMPS re-runs its burn-point detector over the whole extended chain and re-trims the returned view (so the visible count can even shrink), and DREAM advances in blocks of 10 generations, so the raw growth is additional_samples rounded up to a multiple of 10 * n_chains (i.e. at least additional_samples / thin retained rows). To see the chain itself, compare results.state.draw(portion=1.0, outliers=True) before and after, or run with sampler_kwargs={'trim': False}. See the Sampler class notes.

save(path)

Persist the chain state and metadata to disk.

Writes the BUMPS native files (<path>-chain.mc.gz, <path>-point.mc.gz and <path>-stats.mc.gz) plus a <path>.params.json sidecar with the parameter names, the easyscience version, and a fingerprint of the bound data (verified with a warning on load_state()). Use load_chain to read the files back without the model.

Parameters:

Name Type Description Default
path str | os.PathLike

File path prefix. BUMPS appends its own suffixes.

required

Raises:

Type Description
TypeError

If path is not a str or os.PathLike.

RuntimeError

If no chain state exists yet (call sample() first).

load_state(path, skip=0)

Load a previously saved chain into this sampler.

The sampler must be constructed with the same model and data used to create the chain — extend() then continues the saved chain. If the sidecar carries a data fingerprint and it does not match this sampler's bound data, a warning is logged (extending a chain against different data is undefined behaviour).

Populates state and results (draws, log-posterior and parameter names) from the saved chain, so summaries and PosteriorResults.from_sampler() work without resampling.

Parameters:

Name Type Description Default
path str | os.PathLike

File path prefix used in save().

required
skip int

Discard the first skip saved generations on load. Useful for trimming additional burn-in without re-sampling.

0

Returns:

Type Description
SamplingResults

The reloaded chain results (also stored on results).

Raises:

Type Description
TypeError

If path is not a str or os.PathLike.

ValueError

If skip is not a non-negative integer.

Notes

BUMPS does not persist its automatic trim point, so a reloaded chain comes back untrimmed: this method reports more draws than the sample() call that wrote the file, even though the chain is identical. Use skip to discard leading generations explicitly. See the Sampler class notes.

Functions:

load_chain(path, skip=0)

Reload a DREAM chain state saved by Sampler.save.

This is the standalone reader: unlike Sampler.load_state it needs no model or data, so a saved chain can be inspected or post-processed on a machine that does not have the model. Parameter names are restored from the sidecar when available (schema versions 1 and 2), falling back to the state's labels with the minimizer prefix stripped.

Parameters:

Name Type Description Default
path str | os.PathLike

File path prefix used when saving.

required
skip int

Discard the first skip saved generations on load, forwarded to bumps.dream.state.load_state.

0

Returns:

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

The reloaded BUMPS chain state, the parameter names (or None if neither sidecar nor labels yielded them), and the raw sidecar dict (empty if absent/unreadable).

Raises:

Type Description
TypeError

If path is not a str or os.PathLike.

ValueError

If skip is not a non-negative integer.

Modules

samplers

Modules:

Name Description
sampler_bumps

The BUMPS DREAM MCMC engine — DreamSampler.

validation

Run-settings validation for the DREAM sampler.

Classes

Functions:

Modules

sampler_bumps

The BUMPS DREAM MCMC engine — DreamSampler.

Classes:

Name Description
DreamSampler

BUMPS DREAM MCMC engine. Runs and resumes chains for one

Classes
DreamSampler(obj, fit_function)

BUMPS DREAM MCMC engine. Runs and resumes chains for one (obj, fit_function) binding.

This is the minimizer-independent location of Bayesian sampling: it builds its own BUMPS FitProblem via the shared bumps_utils helpers, so sampling no longer requires the Fitter's active minimizer to be BUMPS, only an installed bumps package.

DreamSampler is internal. The public entry point is :class:easyscience.fitting.Sampler.

Parameters:

Name Type Description Default
obj object

Object containing the Parameter instances to sample.

required
fit_function Callable

Callable returning model y values for the supplied x values.

required

Methods:

Name Description
run

Run Bayesian MCMC sampling using the BUMPS DREAM sampler.

validate_arrays

Validate the (x, y, weights) arrays handed to an engine.

evaluate

Evaluate the fit function for values of x.

Methods:
run(x, y, weights, samples=10000, burn=2000, thin=10, population=None, resume_state=None, sampler_kwargs=None, progress_callback=None, abort_test=None)

Run Bayesian MCMC sampling using the BUMPS DREAM sampler.

Builds a BUMPS FitProblem from the bound object and fit function and runs the DREAM sampler. This is the engine-level entry point for Bayesian sampling; the public :class:~easyscience.fitting.Sampler delegates to this method after flattening its bound data.

Parameters:

Name Type Description Default
x np.ndarray

Flattened independent variable array.

required
y np.ndarray

Flattened dependent variable array.

required
weights np.ndarray

Flattened weight array. Sampling has no default weighting, so weights are required; Sampler enforces this at construction.

required
samples int

Number of raw samples to draw across all chains, before thinning. A guaranteed minimum, not an exact count: DREAM advances in blocks of 10 generations (one generation = one draw per chain) and stops at the first block boundary at or past samples.

10000
burn int

Burn-in generations to discard. BUMPS counts burn in generations while samples counts raw draws, so burn=500 discards 500 * n_chains raw samples.

2000
thin int

Thinning interval: only every thin-th generation is stored.

10
population int | None

BUMPS DREAM population count per parameter (number of parallel chains): BUMPS creates ceil(population * n_parameters) chains.

None
resume_state MCMCDraw | None

A BUMPS MCMCDraw state object from a previous run() call. When provided, DREAM continues the saved chain instead of starting cold. The population, parameter count, and parameter names must match the current model. Otherwise, a ValueError is raised.

samples must be the total number of raw samples, not an increment: to extend an existing chain of N raw samples by M, pass samples=N + M (DREAM keeps only the last samples draws in its buffer). The Sampler.extend helper computes this for you.

burn is forced to 0 on resume: a previously-converged chain is never re-burned.

The population and initializer parameters have no effect when resume_state is provided. They are determined by the saved state.

Resuming against different data is undefined behaviour (the chain's likelihood changes underneath it).

None
sampler_kwargs dict | None

Additional keyword arguments forwarded to bumps.fitters.fit.

None
progress_callback Callable[[dict], None] | None

Optional callback for progress updates during sampling. The payload dict includes iteration (DREAM generation number) and sampling: True. Any return value is ignored.

None
abort_test Callable[[], bool] | None

Optional callback that returns True to signal that sampling should be aborted. Called periodically during the DREAM sampling loop.

None

Returns:

Type Description
dict

Dictionary with keys 'draws', 'param_names', 'internal_bumps_object', and 'logp'.

Raises:

Type Description
ValueError

If the input shapes or weights are invalid, if progress_callback is not callable, or if resume_state is incompatible with the current model (parameter count, names/order, or population mismatch).

FitError

If DREAM sampling was aborted by the user (via abort_test).

Exception

Re-raised from DREAM fitting if any unexpected error occurs (parameter values are restored beforehand).

validate_arrays(x, y, weights) staticmethod

Validate the (x, y, weights) arrays handed to an engine.

Parameters:

Name Type Description Default
x np.ndarray

Independent variable array.

required
y np.ndarray

Dependent variable array.

required
weights np.ndarray

Weight array.

required

Raises:

Type Description
ValueError

If any array is non-numeric, the shapes disagree, x or y contain NaN or infinite values, or the weights are non-finite or non-positive.

evaluate(x, parameters=None, **kwargs)

Evaluate the fit function for values of x.

Parameters used are either the latest or user supplied. If the parameters are user supplied, it must be in a dictionary of {'parameter_name': parameter_value,...}.

Parameters:

Name Type Description Default
x np.ndarray

X values for which the fit function will be evaluated.

required
parameters dict[str, float] | None

Dictionary of parameters which will be used in the fit function. They must be in a dictionary of {'parameter_name': parameter_value,...}. By default, None.

None
**kwargs

Additional arguments.

{}

Returns:

Type Description
np.ndarray

Y values calculated at points x for a set of parameters.

Raises:

Type Description
TypeError

If parameters is not a dictionary.

Functions:
validation

Run-settings validation for the DREAM sampler.

Functions:

Name Description
validate_run_settings

Validate the DREAM run settings.

Functions:
validate_run_settings(samples, burn, thin)

Validate the DREAM run settings.

Parameters:

Name Type Description Default
samples int

Number of raw samples to draw; must be a positive integer.

required
burn int

Burn-in generations to discard; must be a non-negative integer.

required
thin int

Thinning interval; must be a positive integer.

required

Raises:

Type Description
ValueError

If any value is out of range or not an integer.