fitting
Modules:
| Name | Description |
|---|---|
calculators |
|
fitter |
|
minimizers |
|
multi_fitter |
|
sampler |
Bayesian MCMC sampling — the |
Classes
Modules
calculators
Modules:
| Name | Description |
|---|---|
interface_factory |
|
Classes
Modules
interface_factory
Classes:
| Name | Description |
|---|---|
InterfaceFactoryTemplate |
This class allows for the creation and transference of interfaces. |
Classes
InterfaceFactoryTemplate(interface_list, *args, **kwargs)
This class allows for the creation and transference of interfaces.
Methods:
| Name | Description |
|---|---|
create |
Create an interface to a calculator from those initialized. |
switch |
Changes the current interface to a new interface. |
generate_bindings |
Automatically bind a |
return_name |
Return an interfaces name. |
Attributes:
| Name | Type | Description |
|---|---|---|
available_interfaces |
List[str]
|
Return all available interfaces. |
current_interface |
ABCMeta
|
Returns the constructor for the currently selected interface. |
current_interface_name |
str
|
Returns the constructor name for the currently selected |
fit_func |
Callable
|
Pass through to the underlying interfaces fitting function. |
available_interfaces
property
Return all available interfaces.
Returns:
| Type | Description |
|---|---|
List[str]
|
List of available interface names. |
current_interface
property
Returns the constructor for the currently selected interface.
Returns:
| Type | Description |
|---|---|
ABCMeta
|
Interface constructor. |
current_interface_name
property
Returns the constructor name for the currently selected interface.
Returns:
| Type | Description |
|---|---|
str
|
Interface constructor name. |
fit_func
property
Pass through to the underlying interfaces fitting function.
Returns:
| Type | Description |
|---|---|
Callable
|
Callable proxy to the underlying interface fit function. |
create(*args, interface_name=None, **kwargs)
Create an interface to a calculator from those initialized.
Interfaces can be selected by interface_name where
interface_name is one of obj.available_interfaces. This
interface can now be accessed by obj().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Positional arguments forwarded to the interface constructor. |
()
|
interface_name
|
str | None
|
Name of interface to be created. |
None
|
**kwargs
|
Any
|
Keyword arguments forwarded to the interface constructor. |
{}
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If no interfaces are available to instantiate. |
switch(new_interface, fitter=None)
Changes the current interface to a new interface.
The current interface is destroyed and all SerializerComponent parameters carried over to the new interface. i.e. pick up where you left off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_interface
|
str
|
Name of new interface to be created. |
required |
fitter
|
Optional[Type[Fitter]]
|
Fitting interface which contains the fitting object which may have bindings which will be updated. By default, None. |
None
|
Raises:
| Type | Description |
|---|---|
AttributeError
|
If |
generate_bindings(model, *args, ifun=None, **kwargs)
Automatically bind a Parameter to the corresponding
interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
Model whose linkable attributes should be bound. |
required |
*args
|
Any
|
Positional arguments reserved for interface-specific binding hooks. |
()
|
ifun
|
Any
|
Optional interface hook. By default, None. |
None
|
**kwargs
|
Any
|
Keyword arguments reserved for interface-specific binding hooks. |
{}
|
return_name(this_interface)
staticmethod
Return an interfaces name.
Modules
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 in the calculator interface. |
create |
Create the required minimizer. |
switch_minimizer |
Switch minimizer and initialize. |
mcmc_sample |
Run Bayesian MCMC sampling using the BUMPS DREAM sampler. |
Attributes:
| Name | Type | Description |
|---|---|---|
available_minimizers |
List[str]
|
Get a list of the names of 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 |
Attributes
available_minimizers
property
Get a list of the names of available fitting minimizers.
Returns:
| Type | Description |
|---|---|
List[str]
|
List of available fitting minimizers. |
minimizer
property
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.
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 in the calculator interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit_object
|
object
|
The EasyScience model object. |
required |
fit_function
|
Callable
|
The function to be optimized against. |
required |
create(minimizer_enum=DEFAULT_MINIMIZER)
Create the required minimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
minimizer_enum
|
Union[AvailableMinimizers, str]
|
The enum of the minimization engine to create. By default, DEFAULT_MINIMIZER. |
DEFAULT_MINIMIZER
|
switch_minimizer(minimizer_enum)
Switch minimizer and initialize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
minimizer_enum
|
Union[AvailableMinimizers, str]
|
The enum of the minimizer to create and instantiate. |
required |
mcmc_sample(x, y, weights, samples=10000, burn=2000, thin=10, population=None, vectorized=False, sampler_kwargs=None, progress_callback=None, abort_test=None)
Run Bayesian MCMC sampling using the BUMPS DREAM sampler.
Works with both a plain Fitter (single dataset) and a
MultiFitter (multiple datasets) via polymorphic dispatch:
_precompute_reshaping and _fit_function_wrapper are
resolved on the concrete subclass at call time, so multi-dataset
flattening is handled automatically when called on a
MultiFitter instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
np.ndarray
|
Independent variable array (or list of arrays for
|
required |
y
|
np.ndarray
|
Dependent variable array (or list of arrays for
|
required |
weights
|
np.ndarray
|
Weight array (or list of arrays for |
required |
samples
|
int
|
Number of retained DREAM samples requested from BUMPS. |
10000
|
burn
|
int
|
Burn-in steps to discard before collecting samples. |
2000
|
thin
|
int
|
Thinning interval — only every |
10
|
population
|
Optional[int]
|
BUMPS DREAM population count (number of parallel chains). |
None
|
vectorized
|
bool
|
When |
False
|
sampler_kwargs
|
Optional[dict]
|
Additional keyword arguments forwarded to the BUMPS DREAM sampler. |
None
|
progress_callback
|
Optional[Callable[[dict], Optional[bool]]]
|
Optional callback invoked at each DREAM generation. The
payload dict includes |
None
|
abort_test
|
Optional[Callable[[], bool]]
|
Optional callable that returns |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with keys |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
If the active minimizer is not a BUMPS instance. |
Modules
minimizers
Modules:
| Name | Description |
|---|---|
bumps_utils |
|
minimizer_base |
|
minimizer_bumps |
|
minimizer_dfo |
|
minimizer_lmfit |
|
utils |
|
Classes
Modules
bumps_utils
Modules:
| Name | Description |
|---|---|
eval_counter |
|
progress_monitor |
|
Classes:
| Name | Description |
|---|---|
EvalCounter |
Wrap a callable so the number of invocations is recorded on |
BumpsProgressMonitor |
BUMPS :class: |
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).
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.
Modules
eval_counter
Classes:
| Name | Description |
|---|---|
EvalCounter |
Wrap a callable so the number of invocations is recorded on |
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).
progress_monitor
Classes:
| Name | Description |
|---|---|
BumpsProgressMonitor |
BUMPS :class: |
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. |
evaluate |
Evaluate the fit function for values of x. |
convert_to_pars_obj |
Create an engine compatible container with the |
supported_methods |
Return a list of supported methods for the minimizer. |
all_methods |
Return a list of all available methods for the minimizer. |
convert_to_par_object |
Convert an |
fit(x, y, weights, model=None, parameters=None, 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 |
model
|
Callable | None
|
Optional Model which is being fitted to. By default, None. |
None
|
parameters
|
List[Parameter] | None
|
Optional parameters for the fit. By default, None. |
None
|
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], bool | None] | None
|
Optional progress callback. By default, None. |
None
|
**kwargs
|
Additional arguments for the fitting function. |
{}
|
Returns:
| Type | Description |
|---|---|
FitResults
|
Fit results. |
evaluate(x, minimizer_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 |
minimizer_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 |
convert_to_pars_obj(par_list=None)
abstractmethod
Create an engine compatible container with the Parameters
converted from the base object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
par_list
|
List[Parameter] | None
|
If only a single/selection of parameter is required. Specify as a list. By default, None. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Engine Parameters compatible object. |
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. |
convert_to_par_object(obj)
abstractmethod
staticmethod
Convert an EasyScience.variable.Parameter object to an
engine Parameter object.
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.ObjBase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
object
|
Object containing the |
required |
fit_function
|
Callable
|
Callable returning model y values for the supplied x values. |
required |
minimizer_enum
|
AvailableMinimizers | None
|
Selected BUMPS minimizer configuration. By default, None. |
None
|
Methods:
| Name | Description |
|---|---|
fit |
Perform a fit using the BUMPS engine. |
convert_to_pars_obj |
Create a container with the |
convert_to_par_object |
Convert an |
mcmc_sample |
Run Bayesian MCMC sampling using the BUMPS DREAM sampler. |
evaluate |
Evaluate the fit function for values of x. |
fit(x, y, weights, model=None, parameters=None, 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 |
model
|
Callable | None
|
Optional Model which is being fitted to. By default, None. |
None
|
parameters
|
list[Parameter] | None
|
Optional parameters for the fit. By default, None. |
None
|
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
|
None
|
progress_callback
|
Callable[[dict], bool | None] | None
|
Optional callback for progress updates. The payload field
|
None
|
abort_test
|
Callable[[], bool] | None
|
Optional callback that returns |
None
|
minimizer_kwargs
|
dict | None
|
Additional keyword arguments passed to the BUMPS minimizer. By default, None. |
None
|
engine_kwargs
|
dict | None
|
Additional engine keyword arguments. By default, None. |
None
|
**kwargs
|
Any
|
Additional keyword arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
FitResults
|
Fit results. |
Raises:
| Type | Description |
|---|---|
FitError
|
If the BUMPS fit fails. |
ValueError
|
If the input shapes or weights are invalid. |
convert_to_pars_obj(par_list=None)
Create a container with the Parameters converted from the
base object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
par_list
|
list[Parameter] | None
|
If only a single/selection of parameter is required. Specify as a list. By default, None. |
None
|
Returns:
| Type | Description |
|---|---|
list[BumpsParameter]
|
Bumps Parameters list. |
convert_to_par_object(obj)
staticmethod
Convert an EasyScience.variable.Parameter object to a bumps
Parameter object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Parameter
|
EasyScience parameter to convert. |
required |
Returns:
| Type | Description |
|---|---|
BumpsParameter
|
Bumps Parameter compatible object. |
mcmc_sample(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 current model and runs
the DREAM sampler. This is the public minimizer-level entry
point for Bayesian sampling; the higher-level
MultiFitter.mcmc_sample delegates to this method after
flattening multi-dataset arrays.
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. |
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 |
10000
|
burn
|
int
|
Burn-in generations to discard. BUMPS counts |
2000
|
thin
|
int
|
Thinning interval — only every |
10
|
population
|
int | None
|
BUMPS DREAM population count per parameter (number of parallel
chains): BUMPS creates |
None
|
resume_state
|
MCMCDraw | None
|
A BUMPS
The Resuming against different data is undefined behaviour (the chain's likelihood changes underneath it). |
None
|
sampler_kwargs
|
dict | None
|
Additional keyword arguments forwarded to
|
None
|
progress_callback
|
Callable[[dict], bool | None] | None
|
Optional callback for progress updates during sampling. The
payload dict includes |
None
|
abort_test
|
Callable[[], bool] | None
|
Optional callback that returns |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with keys |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input shapes or weights are invalid, if
|
FitError
|
If DREAM sampling was aborted by the user (via
|
Exception
|
Re-raised from DREAM fitting if any unexpected error occurs (parameter values are restored beforehand). |
evaluate(x, minimizer_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 |
minimizer_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 |
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 |
required |
fit_function
|
Callable
|
Callable returning model y values for the supplied x values. |
required |
minimizer_enum
|
AvailableMinimizers | None
|
Selected DFO minimizer configuration. By default, None. |
None
|
Methods:
| Name | Description |
|---|---|
fit |
Perform a fit using the DFO-ls engine. |
convert_to_pars_obj |
Required by interface but not needed for DFO-LS. |
convert_to_par_object |
Required by interface but not needed for DFO-LS. |
evaluate |
Evaluate the fit function for values of x. |
fit(x, y, weights, model=None, parameters=None, 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 |
model
|
Callable | None
|
Optional Model which is being fitted to. By default, None. |
None
|
parameters
|
List[Parameter] | None
|
Optional parameters for the fit. By default, None. |
None
|
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], bool | None] | None
|
Optional callback receiving normalized progress payloads. |
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. |
ValueError
|
If the input shapes, weights, or tolerance are invalid. |
convert_to_pars_obj(par_list=None)
Required by interface but not needed for DFO-LS.
convert_to_par_object(obj)
staticmethod
Required by interface but not needed for DFO-LS.
evaluate(x, minimizer_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 |
minimizer_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 |
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.ObjBase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
object
|
Object containing the |
required |
fit_function
|
Callable
|
Callable returning model y values for the supplied x values. |
required |
minimizer_enum
|
AvailableMinimizers | None
|
Selected LMFit minimizer configuration. By default, None. |
None
|
Methods:
| Name | Description |
|---|---|
fit |
Perform a fit using the lmfit engine. |
convert_to_pars_obj |
Create an lmfit compatible container with the |
convert_to_par_object |
Convert an EasyScience Parameter object to a lmfit Parameter |
evaluate |
Evaluate the fit function for values of x. |
fit(x, y, weights=None, model=None, parameters=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
|
model
|
LMModel | None
|
Optional Model which is being fitted to. By default, None. |
None
|
parameters
|
LMParameters | None
|
Optional parameters for the fit. 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], bool | None] | None
|
Optional callback receiving normalized progress payloads. |
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. |
ValueError
|
If the input shapes or weights are invalid. |
convert_to_pars_obj(parameters=None)
Create an lmfit compatible container with the Parameters
converted from the base object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
List[Parameter] | None
|
If only a single/selection of parameter is required. Specify as a list. By default, None. |
None
|
Returns:
| Type | Description |
|---|---|
LMParameters
|
Lmfit Parameters compatible object. |
convert_to_par_object(parameter)
staticmethod
Convert an EasyScience Parameter object to a lmfit Parameter object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameter
|
Parameter
|
EasyScience parameter to convert. |
required |
Returns:
| Type | Description |
|---|---|
LMParameter
|
Lmfit Parameter compatible object. |
evaluate(x, minimizer_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 |
minimizer_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 |
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 in the calculator interface. |
create |
Create the required minimizer. |
switch_minimizer |
Switch minimizer and initialize. |
mcmc_sample |
Run Bayesian MCMC sampling using the BUMPS DREAM sampler. |
Attributes:
| Name | Type | Description |
|---|---|---|
available_minimizers |
List[str]
|
Get a list of the names of 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 |
Attributes
available_minimizers
property
Get a list of the names of available fitting minimizers.
Returns:
| Type | Description |
|---|---|
List[str]
|
List of available fitting minimizers. |
minimizer
property
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.
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 in the calculator interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit_object
|
object
|
The EasyScience model object. |
required |
fit_function
|
Callable
|
The function to be optimized against. |
required |
create(minimizer_enum=DEFAULT_MINIMIZER)
Create the required minimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
minimizer_enum
|
Union[AvailableMinimizers, str]
|
The enum of the minimization engine to create. By default, DEFAULT_MINIMIZER. |
DEFAULT_MINIMIZER
|
switch_minimizer(minimizer_enum)
Switch minimizer and initialize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
minimizer_enum
|
Union[AvailableMinimizers, str]
|
The enum of the minimizer to create and instantiate. |
required |
mcmc_sample(x, y, weights, samples=10000, burn=2000, thin=10, population=None, vectorized=False, sampler_kwargs=None, progress_callback=None, abort_test=None)
Run Bayesian MCMC sampling using the BUMPS DREAM sampler.
Works with both a plain Fitter (single dataset) and a
MultiFitter (multiple datasets) via polymorphic dispatch:
_precompute_reshaping and _fit_function_wrapper are
resolved on the concrete subclass at call time, so multi-dataset
flattening is handled automatically when called on a
MultiFitter instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
np.ndarray
|
Independent variable array (or list of arrays for
|
required |
y
|
np.ndarray
|
Dependent variable array (or list of arrays for
|
required |
weights
|
np.ndarray
|
Weight array (or list of arrays for |
required |
samples
|
int
|
Number of retained DREAM samples requested from BUMPS. |
10000
|
burn
|
int
|
Burn-in steps to discard before collecting samples. |
2000
|
thin
|
int
|
Thinning interval — only every |
10
|
population
|
Optional[int]
|
BUMPS DREAM population count (number of parallel chains). |
None
|
vectorized
|
bool
|
When |
False
|
sampler_kwargs
|
Optional[dict]
|
Additional keyword arguments forwarded to the BUMPS DREAM sampler. |
None
|
progress_callback
|
Optional[Callable[[dict], Optional[bool]]]
|
Optional callback invoked at each DREAM generation. The
payload dict includes |
None
|
abort_test
|
Optional[Callable[[], bool]]
|
Optional callable that returns |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with keys |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
If the active minimizer is not a BUMPS instance. |
sampler
Bayesian MCMC sampling — the Sampler class and persistence helpers.
Classes:
| Name | Description |
|---|---|
SamplingResults |
Structured result of an MCMC sampling run (analogous to |
Sampler |
Bayesian MCMC sampler for one dataset, backed by a Fitter's BUMPS minimizer. |
Functions:
| Name | Description |
|---|---|
load_chain |
Reload a DREAM chain state saved by |
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 |
param_names |
list[str]
|
Parameter names (one per column of |
logp |
np.ndarray
|
Log-posterior values, shape |
state |
MCMCDraw
|
The raw BUMPS chain state, holding the full untrimmed chain. |
Methods:
| Name | Description |
|---|---|
to_legacy_dict |
Return the legacy dict shape produced by the deprecated |
Methods:
to_legacy_dict()
Return the legacy dict shape produced by the deprecated
mcmc_sample() APIs.
Sampler(fitter, x, y, weights=None, vectorized=False, sampler_kwargs=None)
Bayesian MCMC sampler for one dataset, backed by a Fitter's BUMPS minimizer.
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.
Construct directly with a configured Fitter (or MultiFitter) whose
minimizer has been switched to AvailableMinimizers.Bumps. Running a
fit first is not required — the Fitter supplies the model and the
minimizer, not a fit result, and sampling from the initial parameter values
works fine.
It is often worth fitting first anyway. DREAM seeds its whole starting
population inside a tiny ball around the parameters' current values
(BUMPS' default init='eps'), so sampling from fitted values starts the
chain in the right region and shortens the burn-in needed to reach the
typical set. From a poor initial guess, expect to burn for longer.
The sampler is BUMPS/DREAM-specific for now: the BUMPS check in _run()
is the seam where another backend would plug in.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fitter
|
Fitter
|
A configured |
required |
x
|
np.ndarray | list[np.ndarray]
|
Independent variable array (or list of arrays for |
required |
y
|
np.ndarray | list[np.ndarray]
|
Dependent variable array (or list of arrays for |
required |
weights
|
np.ndarray | list[np.ndarray | None] | None
|
Weight array (or list of arrays for |
None
|
vectorized
|
bool
|
When |
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
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
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(
fitter, 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 |
|---|---|
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 |
|---|---|---|
fitter |
Fitter
|
The Fitter supplying the model and minimizer (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 | None] | None
|
The bound weight data (read-only copy, or None). |
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
fitter
property
The Fitter supplying the model and minimizer (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, or None).
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:
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 |
10000
|
burn
|
int
|
Burn-in generations to discard before collecting samples. Note
BUMPS counts |
2000
|
thin
|
int
|
Thinning interval — only every |
10
|
population
|
int | None
|
DREAM population scale factor (not an absolute chain count):
BUMPS creates |
None
|
sampler_kwargs
|
dict | None
|
Additional keyword arguments forwarded to the BUMPS DREAM sampler (merged over the instance defaults). |
None
|
progress_callback
|
Callable[[dict], bool | None] | None
|
Optional callback invoked at each DREAM generation. The payload
dict includes |
None
|
abort_test
|
Callable[[], bool] | None
|
Optional callable that returns |
None
|
Returns:
| Type | Description |
|---|---|
SamplingResults
|
Structured sampling results (also stored on |
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 active minimizer is not a BUMPS instance.
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 |
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 |
None
|
sampler_kwargs
|
dict | None
|
Additional keyword arguments forwarded to the BUMPS DREAM sampler (merged over the instance defaults). |
None
|
progress_callback
|
Callable[[dict], bool | None] | None
|
Optional callback invoked at each DREAM generation. |
None
|
abort_test
|
Callable[[], bool] | None
|
Optional callable that returns |
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 |
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 a fitter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | os.PathLike
|
File path prefix. BUMPS appends its own suffixes. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
RuntimeError
|
If no chain state exists yet (call |
load_state(path, skip=0)
Load a previously saved chain into this sampler.
The sampler must be constructed with the same fitter 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 |
required |
skip
|
int
|
Discard the first |
0
|
Returns:
| Type | Description |
|---|---|
SamplingResults
|
The reloaded chain results (also stored on |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
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
fitter, 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 |
0
|
Returns:
| Type | Description |
|---|---|
tuple[MCMCDraw, list[str] | None, dict]
|
The reloaded BUMPS chain state, the parameter names (or |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |