spectrochempy.Optimize

class Optimize(*, log_level='WARNING', warm_start=False, amplitude_mode='height', autoampl=False, autobase=False, callback_every=10, constraints=None, dry=False, max_fun_calls=0, max_iter=500, method='least_squares', script='')[source]

Non-linear curve fitting driven by the SpectroChemPy fitting DSL.

Optimize combines:

  • script-based model definition through script;

  • pre-fit validation through validate_script;

  • multiple public optimization-method families through method;

  • estimator-level access to raw solver artifacts such as jacobian;

  • grouped scientific outputs and diagnostics through result.

The current public method values are:

  • "least_squares"

  • "leastsq"

  • "simplex"

  • "basinhopping"

In current SpectroChemPy releases, "least_squares" is the clearest recommended entrypoint for ordinary local least-squares fitting. "leastsq" is still accepted as a public compatibility alias, but it currently uses the same least-squares backend family rather than defining a separate maintained fitting strategy of its own.

Least-squares-backed methods are the only ones that currently expose the retained Jacobian and the resulting uncertainty path on FitResult (covariance, standard errors, correlation, and confidence intervals).

Method selection

In current SpectroChemPy releases, the practical guidance is:

  • use "least_squares" as the default choice for ordinary local least-squares fitting;

  • treat "leastsq" mainly as a compatibility alias rather than as a separate maintained strategy;

  • use "simplex" when you explicitly want a derivative-free local search and can accept losing the least-squares uncertainty path;

  • reserve "basinhopping" for harder landscapes where a slower exploratory global-style search is justified.

The low-level SciPy least-squares backend variant (currently lm or trf) is still selected internally; users choose the high-level SpectroChemPy method, not the backend variant directly.

Notes

The current implementation supports only 1D fitting. Multi-dimensional datasets are not yet handled by fit.

Parameters
  • log_level (any of ["INFO", "DEBUG", "WARNING", "ERROR"], optional, default: "WARNING") – The log level at startup. It can be changed later on using the set_log_level method or by changing the log_level attribute.

  • warm_start (bool, optional, default: False) – Preserve the current estimator configuration instead of forcing a full reset to default configuration values during estimator reinitialization. This is a general estimator-state option shared with other SpectroChemPy analysis classes; it should not be interpreted as a dedicated Optimize solver-backend feature.

  • amplitude_mode (any value of ['area', 'height'], optional, default: 'height') – How line-shape amplitudes are interpreted during initialisation.

  • autoampl (bool, optional, default: False) – Whether to estimate initial amplitudes automatically during setup.

  • autobase (bool, optional, default: False) – Whether to estimate and apply a linear baseline correction automatically.

  • callback_every (int, optional, default: 10) – Number of iteration between each callback report. Used for printing or display intermediate results.

  • constraints (any value, optional, default: None) – Constraints.

  • dry (bool, optional, default: False) – If True, assemble the starting model without running the optimizer.

  • max_fun_calls (int, optional, default: 0) – Maximum number of function calls at each iteration.

  • max_iter (int, optional, default: 500) – Maximum number of fitting iteration.

  • method (any value of ['least_squares', 'leastsq', 'simplex', 'basinhopping'], optional, default: 'least_squares') – High-level optimization-method selector. β€˜least_squares’ is the preferred local least-squares entrypoint; β€˜leastsq’ is a compatibility alias using the same backend family; β€˜simplex’ uses a derivative-free local search; β€˜basinhopping’ uses a global-style exploratory search.

  • script (str, optional, default: '') – Script defining models and parameters for fitting.

Initialize the Optimize class with configuration parameters.

Parameters
  • log_level (str, optional) – Logging level, by default β€œWARNING”.

  • warm_start (bool, optional) – Preserve the current estimator configuration rather than resetting it to defaults during estimator reinitialization. This does not add any dedicated Optimize backend-specific warm-start strategy.

  • **kwargs (dict) – Additional keyword arguments.

Attributes Summary

X

Return the X input dataset (eventually modified by the model).

Y

The Y input.

amplitude_mode

How line-shape amplitudes are interpreted during initialisation.

autoampl

Whether to estimate initial amplitudes automatically during setup.

autobase

Whether to estimate and apply a linear baseline correction automatically.

callback_every

Number of iteration between each callback report.

components

NDDataset with components in feature space (n_components, n_features).

config

traitlets.config.Config object.

constraints

Constraints.

dry

If True, assemble the starting model without running the optimizer.

fp

A trait whose value must be an instance of a specified class.

jacobian

Return the retained raw solver Jacobian when the backend provides one.

log

Return log output.

max_fun_calls

Maximum number of function calls at each iteration.

max_iter

Maximum number of fitting iteration.

method

High-level optimization-method selector.

modeldata

An instance of a Python list.

n_components

Number of components that were fitted.

name

Object name

result

Return the Optimize fit result object.

script

Script defining models and parameters for fitting.

usermodels

User defined models.

Methods Summary

fit(X)

Perform a non-linear optimization of the X dataset.

fit_transform(X[,Β Y])

Fit the model with X and apply the dimensionality reduction on X.

get_components([n_components])

Return the component's dataset: (selected n_components, n_features).

get_params([deep])

Get the configuration parameters of this estimator.

inverse_transform([X_transform])

Transform data back to its original space.

params([default])

Return current or default configuration values.

plot_merit([X,Β X_hat])

Plot the input (X), reconstructed (X_hat) and residuals.

plotmerit([replace,Β policy,Β X,Β X_hat])

Backward-compatible alias for plot_merit.

predict()

Return the fitted model.

reset()

Reset configuration parameters to their default values.

set_params(**params)

Set configuration parameters on this estimator.

to_dict()

Return config value in a dict form.

transform([X])

Apply dimensionality reduction to X.

validate_constraints([constraints,Β script])

Validate lightweight constraint specifications without running a fit.

validate_script([script])

Validate a fitting script without running an optimisation.

Attributes Documentation

X

Return the X input dataset (eventually modified by the model).

Y

The Y input.

amplitude_mode

How line-shape amplitudes are interpreted during initialisation.

autoampl

Whether to estimate initial amplitudes automatically during setup.

autobase

Whether to estimate and apply a linear baseline correction automatically.

callback_every

Number of iteration between each callback report. Used for printing or display intermediate results.

components

NDDataset with components in feature space (n_components, n_features).

See also

get_components

Retrieve only the specified number of components.

config

traitlets.config.Config object.

constraints

Constraints.

dry

If True, assemble the starting model without running the optimizer.

fp

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

jacobian

Return the retained raw solver Jacobian when the backend provides one.

Returns

ndarray or None – Immutable Jacobian matrix for least-squares-backed methods. Returns None for backends that do not naturally expose a Jacobian, and for dry fits.

log

Return log output.

max_fun_calls

Maximum number of function calls at each iteration.

max_iter

Maximum number of fitting iteration.

method

High-level optimization-method selector. β€˜least_squares’ is the preferred local least-squares entrypoint; β€˜leastsq’ is a compatibility alias using the same backend family; β€˜simplex’ uses a derivative-free local search; β€˜basinhopping’ uses a global-style exploratory search.

modeldata

An instance of a Python list.

n_components

Number of components that were fitted.

name

Object name

result

Return the Optimize fit result object.

Returns

FitResult – Result object containing fitted model outputs, solver diagnostics, and estimator parameters.

script

Script defining models and parameters for fitting.

usermodels

User defined models.

Methods Documentation

fit(X)[source]

Perform a non-linear optimization of the X dataset.

Parameters

X (NDDataset or array-like of shape (n_observations, n_features)) – Training data.

Returns

self – The fitted instance itself.

See also

fit_transform

Fit the model with an input dataset X and apply the dimensionality reduction on X.

fit_reduce

Alias of fit_transform (Deprecated).

fit_transform(X, Y=None, **kwargs)[source]

Fit the model with X and apply the dimensionality reduction on X.

Parameters
  • X (NDDataset or array-like of shape (n_observations, n_features)) – Training data.

  • Y (any) – Depends on the model.

  • **kwargs (keyword arguments, optional) – Additional keyword arguments passed to the underlying implementation.

Returns

NDDataset – Dataset with shape (n_observations, n_components).

Other Parameters

n_components (int, optional) – The number of components to use for the reduction.

get_components(n_components=None)

Return the component’s dataset: (selected n_components, n_features).

Parameters

n_components (int, optional, default: None) – The number of components to keep in the output dataset. If None, all calculated components are returned.

Returns

NDDataset – Dataset with shape (n_components, n_features)

get_params(deep=True)[source]

Get the configuration parameters of this estimator.

Parameters

deep (bool, optional, default:True) – Ignored. Present for compatibility with scikit-learn conventions.

Returns

dict – Mapping of parameter name -> current value.

inverse_transform(X_transform=None, **kwargs)

Transform data back to its original space.

In other words, return an input X_original whose reduce/transform would be X_transform.

Parameters
  • X_transform (array-like of shape (n_observations, n_components), optional) – Reduced X data, where n_observations is the number of observations and n_components is the number of components. If X_transform is not provided, a transform of X provided in fit is performed first.

  • **kwargs (keyword parameters, optional) – See Other Parameters.

Returns

NDDataset – Dataset with shape (n_observations, n_features).

Other Parameters

n_components (int, optional) – The number of components to use for the reconstruction.

See also

reconstruct

Alias of inverse_transform (Deprecated).

params(default=False)[source]

Return current or default configuration values.

Parameters

default (bool, optional, default: False) – If default is True, the default parameters are returned, else the current values.

Returns

dict – Current or default configuration values.

plot_merit(X=None, X_hat=None, **kwargs)[source]

Plot the input (X), reconstructed (X_hat) and residuals.

\(X\) and \(\hat{X}\) can be passed as arguments. If not, the X attribute is used for \(X\)hat{X}`is computed by the inverse_transform method

Parameters
  • X (NDDataset, optional) – Original dataset. If is not provided (default), the X attribute is used and X_hat is computed using inverse_transform.

  • X_hat (NDDataset, optional) – Inverse transformed dataset. if X is provided, X_hat must also be provided as compuyed externally.

Returns

Axes – Matplotlib subplot axe.

Other Parameters
  • exp_c (color, colormap, or list of colors, optional) – Color(s) for experimental spectra. - None: use unified semantic resolver (auto-detect categorical/sequential) - Single color: use for all experimental spectra - Colormap name/object: sample colors from colormap - List/tuple: use as explicit color cycle

  • calc_c (color, colormap, or list of colors, optional) – Color(s) for calculated spectra. - None: use default blue β€œ#2a6fbb” - Single color: use for all calculated spectra - Colormap name/object: sample colors from colormap - List/tuple: use as explicit color cycle

  • resid_c (color, colormap, or list of colors, optional) – Color(s) for residual spectra. - None: use default grey β€œ0.4” - Single color: use for all residual spectra - Colormap name/object: sample colors from colormap - List/tuple: use as explicit color cycle

  • exp_linestyle (str, optional) – Line style for experimental spectra. Default: β€œ-β€œ.

  • calc_linestyle (str, optional) – Line style for calculated spectra. Default: β€œβ€“β€œ.

  • resid_linestyle (str, optional) – Line style for residual spectra. Default: β€œ-β€œ.

  • exp_linewidth (float, optional) – Line width for experimental spectra. Default: 1.2.

  • calc_linewidth (float, optional) – Line width for calculated spectra. Default: 1.0.

  • resid_linewidth (float, optional) – Line width for residual spectra. Default: 1.0.

  • min_contrast (float, optional) – Minimum contrast ratio for sequential colormaps. Default: 1.5.

  • offset (float, optional, default: None) – Specify the separation (in percent) between the \(X\) , \(X_hat\) and \(E\).

  • nb_traces (int or 'all', optional) – Number of lines to display. Default is 'all'.

  • **others (Other keywords parameters) – Parameters passed to the internal plot method of the X dataset. Common options include color, linewidth, linestyle, alpha, and standard Matplotlib kwargs.

plotmerit(replace="plot_merit", policy=True, ) def plotmerit(self, X=None, X_hat=None, **kwargs)[source]

Backward-compatible alias for plot_merit. Deprecated.

Returns

Axes – Matplotlib axes containing the plot.

predict()[source]

Return the fitted model.

Returns

NDDataset – The fitted model.

reset()[source]

Reset configuration parameters to their default values.

set_params(**params)[source]

Set configuration parameters on this estimator.

Returns self so that calls can be chained.

Parameters

**params – Parameter names and values to update.

Returns

self – The estimator instance.

Raises

SpectroChemPyError – If a parameter name does not correspond to a configurable trait.

to_dict()[source]

Return config value in a dict form.

Returns

dict – A regular dictionary.

transform(X=None, **kwargs)

Apply dimensionality reduction to X.

Parameters
Returns

NDDataset – Dataset with shape (n_observations, n_components).

Other Parameters

n_components (int, optional) – The number of components to use for the reduction. If not given the number of components is eventually the one specified or determined in the fit process.

validate_constraints(constraints=None, script=None)[source]

Validate lightweight constraint specifications without running a fit.

This method currently validates:

  • the overall constraints container shape;

  • recognized constraint keys / types;

  • references to parameter names defined by the fitting script.

It does not guarantee that every accepted constraint is fully enforced by the current optimization backend. The present goal is to provide a stable validation surface before broader constraint execution semantics are expanded.

Parameters
  • constraints (dict or sequence of dict, optional) – Constraint specification(s) to validate. If None (default), validates constraints.

  • script (str, optional) – Script used to resolve parameter names. If None (default), uses the currently assigned script.

Returns

list of ConstraintError – Empty list when the constraint specification is valid.

validate_script(script=None)[source]

Validate a fitting script without running an optimisation.

Returns a list of ScriptError objects describing every problem found in the script. An empty list means the script is valid.

Parameters

script (str, optional) – The script to validate. If None (default), validates the currently assigned script.

Returns

list of ScriptError – Empty list when the script is valid.

Examples

>>> opt = scp.Optimize()
>>> errors = opt.validate_script(script)
>>> if errors:
...     for err in errors:
...         print(err)

Examples using spectrochempy.Optimize

Processing a 1D NMR spectrum

Processing a 1D NMR spectrum

Processing a saturation-recovery relaxation series

Processing a saturation-recovery relaxation series

Fitting 1D dataset

Fitting 1D dataset

Processing a 1D NMR spectrum

Processing a 1D NMR spectrum

Processing a saturation-recovery relaxation series

Processing a saturation-recovery relaxation series