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.
Optimizecombines: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
methodvalues 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
lmortrf) is still selected internally; users choose the high-level SpectroChemPymethod, not the backend variant directly.Notes
The script interface fits 1D spectra. Pass
peaksto 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 forsimulate_peaksand 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 theset_log_levelmethod or by changing thelog_levelattribute.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 dedicatedOptimizesolver-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
Optimizebackend-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 keysvalue,boundsandfixed. A varying width requires a strictly positive lower bound.**kwargs (dict) – Additional keyword arguments.
Attributes Summary
Return the fitted observations.
The
Yinput.How line-shape amplitudes are interpreted during initialisation.
Whether to estimate initial amplitudes automatically during setup.
Whether to estimate and apply a linear baseline correction automatically.
Number of iteration between each callback report.
Return fitted components, one dataset per peak in ND mode.
traitlets.config.Configobject.Constraints.
If True, assemble the starting model without running the optimizer.
A trait whose value must be an instance of a specified class.
Return the retained solver Jacobian when the backend provides one.
Return
logoutput.Maximum number of function calls at each iteration.
Maximum number of fitting iteration.
High-level optimization-method selector.
An instance of a Python list.
Number of components that were fitted.
Object name
Return the Optimize fit result object.
Script defining models and parameters for fitting.
User defined models.
Methods Summary
fit(X)Perform a non-linear optimization of the
Xdataset.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.
- 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.Configobject.
- 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_namesandresult.parameter_units.- Returns:
ndarray or None – Immutable Jacobian matrix for least-squares-backed methods. Returns
Nonefor backends that do not naturally expose a Jacobian, and for dry fits.
- log#
Return
logoutput.
- 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
Xdataset.- Parameters:
X (
NDDatasetor array-like of shape (n_observations, n_features)) – Training data.- Returns:
self – The fitted instance itself.
See also
fit_transformFit the model with an input dataset
Xand apply the dimensionality reduction onX.fit_reduceAlias of
fit_transform(Deprecated).
- 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
Xattribute is used for \(X`and :math:\)hat{X}`is computed by theinverse_transformmethod- Parameters:
X (
NDDataset, optional) – Original dataset. If is not provided (default), theXattribute is used and X_hat is computed usinginverse_transform.X_hat (
NDDataset, optional) – Inverse transformed dataset. ifXis provided,X_hatmust 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 (
intor'all', optional) – Number of lines to display. Default is'all'.**others (Other keywords parameters) – Parameters passed to the internal
plotmethod of theXdataset. Common options includecolor,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.
- set_params(**params)[source]#
Set configuration parameters on this estimator.
Returns
selfso 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.
- 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), validatesconstraints.script (str, optional) – Script used to resolve parameter names. If
None(default), uses the currently assignedscript.
- 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
ScriptErrorobjects 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