spectrochempy.Optimize#

class Optimize(*, log_level='WARNING', warm_start=False, peaks=None, 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 script interface fits 1D spectra. Pass peaks to fit separable Gaussian or Lorentzian profiles jointly on a multidimensional grid. The ND fit uses unweighted residuals at finite, unmasked observations. Its result includes fitted peaks suitable for simulate_peaks and the parameter names and units in Jacobian column order. The local covariance is available for converged, full-rank fits with positive residual degrees of freedom and no active bounds.

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.

  • peaks (sequence of mappings, optional) – Enable ND fitting. Use the structure accepted by simulate_peaks, replacing each numerical value with an optional mapping with keys value, bounds and fixed. A varying width requires a strictly positive lower bound.

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

Attributes Summary

X

Return the fitted observations.

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

Return fitted components, one dataset per peak in ND mode.

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 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 and apply the legacy dimensionality reduction.

get_components([n_components])

Return all or the requested number of fitted components.

get_params([deep])

Get the configuration parameters of this estimator.

inverse_transform([X_transform])

Apply the legacy inverse transform.

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 the legacy dimensionality reduction.

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 fitted observations.

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#

Return fitted components, one dataset per peak in ND mode.

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 solver Jacobian when the backend provides one.

In ND mode, rows follow finite, unmasked observations in native C order. Columns follow the free parameters in physical magnitudes, as identified by result.parameter_names and result.parameter_units.

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 and apply the legacy dimensionality reduction.

get_components(n_components=None)[source]#

Return all or the requested number of fitted components.

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)[source]#

Apply the legacy inverse transform.

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`and :math:\)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)[source]#

Apply the legacy dimensionality reduction.

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

Fitting 1D dataset

Fitting 1D dataset

Fit overlapping peaks in a 2D spectrum

Fit overlapping peaks in a 2D spectrum