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.
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.- 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.
Notes
The current implementation supports only 1D fitting. Multi-dimensional datasets are not yet handled by
fit.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.**kwargs (dict) β Additional keyword arguments.
Attributes Summary
Return the X input dataset (eventually modified by the model).
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.
NDDatasetwith components in feature space (n_components, n_features).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 raw 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 the model with
Xand apply the dimensionality reduction onX.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([X,Β X_hat])Plot the input (
X), reconstructed (X_hat) and residuals.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).
- 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ο
NDDatasetwith components in feature space (n_components, n_features).See also
get_componentsRetrieve only the specified number of components.
- 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 raw solver Jacobian when the backend provides one.
- 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).
- fit_transform(X, Y=None, **kwargs)[source]ο
Fit the model with
Xand apply the dimensionality reduction onX.- Parameters:
X (
NDDatasetor 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. IfNone, all calculated components are returned.- Returns:
NDDatasetβ Dataset with shape (n_components, n_features)
- inverse_transform(X_transform=None, **kwargs)ο
Transform data back to its original space.
In other words, return an input
X_originalwhose reduce/transform would beX_transform.- Parameters:
X_transform (array-like of shape (n_observations, n_components), optional) β Reduced
Xdata, wheren_observationsis the number of observations andn_componentsis the number of components. IfX_transformis not provided, a transform ofXprovided infitis 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
reconstructAlias of inverse_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.
- plotmerit(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.
- 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.
- transform(X=None, **kwargs)ο
Apply dimensionality reduction to
X.- Parameters:
X (
NDDatasetor array-like of shape (n_observations, n_features), optional) β New data, where n_observations is the number of observations and n_features is the number of features. if not provided, the input dataset of thefitmethod will be used.**kwargs (keyword parameters, optional) β See Other 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 thefitprocess.
- 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
Processing NMR spectra (slicing, baseline correction, peak picking, peak fitting)
Processing NMR spectra (slicing, baseline correction, peak picking, peak fitting)