spectrochempy.MCRALSο
- class MCRALS(*args, constraints=None, solver_C='lstsq', solver_St='lstsq', max_iter=50, tol_residual_change=0.001, tol_reconstruction_error=None, tol_profile_change=None, maxdiv=5, warm_start=False, log_level=30)[source]ο
Multivariate Curve Resolution Alternating Least Squares (MCRALS).
MCR-ALS (
Multivariate Curve Resolution Alternating Least Squares) resolveβs a set (or several sets) of spectra \(X\) of an evolving mixture (or a set of mixtures) into the spectra \(S^t\) of βpureβ species and their concentration profiles \(C\).In terms of matrix equation:
\[X = C.S^t + E\]where \(E\) is the matrix of residuals.
- Parameters:
constraints (list of
Constraint, optional, default:None) β Public constraint objects describing scientific prior knowledge about the concentration ("C") or spectral ("St") profiles. When provided, each element must be an instance of a public constraint class (e.g.,NonNegative,Unimodal,Closure,Monotonic,ModelProfile).Noneselects the built-in default constraints; an empty list requests an unconstrained fit.constraintscan be passed at construction time or assigned before callingfit:from spectrochempy.analysis import constraints as mc mcr = MCRALS() mcr.constraints = [ mc.NonNegative("C"), mc.Closure("C"), ] mcr.fit(X, guess)
Added in version 0.7.0.
solver_C (
'lstsq'|'nnls'|'pnnls', optional, default:'lstsq') β Solver used to estimate concentration profilesCfromXandSt.solver_St (
'lstsq'|'nnls'|'pnnls', optional, default:'lstsq') β Solver used to estimate spectral profilesStfromXandC.max_iter (
int, optional, default:50) β Maximum number of ALS iteration.tol_residual_change (
float, optional, default:0.001) β Relative tolerance on the change in residual standard deviation. The dimensionless value is abs(sigma_k - sigma_(k-1)) / sigma_(k-1); 1e-3 therefore means 0.1%. Set to None to disable this stopping criterion.tol_reconstruction_error (
float, optional, default:None) β Tolerance on the relative reconstruction error norm(X - C @ St) / norm(X). This dimensionless stopping criterion is disabled when set to None.tol_profile_change (
float, optional, default:None) β Relative tolerance on the change of the resolved C and St profiles between successive iterations. Factor pairs are first normalized to remove their arbitrary reciprocal scale and sign; the larger relative Frobenius change of C and St is used. This dimensionless criterion is disabled when set to None.maxdiv (
int, optional, default:5) β Maximum number of successive non-converging iterations.warm_start (
bool, optional, default:False) β When fitting repeatedly on the same dataset, but for multiple parameter values (such as to find the value maximizing performance), reuse the solution of the previous call to fit and add more components (if available) in a sequential manner.When
warm_startisTrue, the existing fitted model attributes is used to initialize the new model in a subsequent call tofit.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.
See also
fitFit the MCRALS model on X.
transformApply dimensionality reduction.
fit_transformFit the model and apply dimensionality reduction.
Notes
Three dimensionless stopping diagnostics are evaluated after each ALS iteration:
reconstruction_errormeasures the current relative reconstruction error,residual_changemeasures the relative change in residual standard deviation since the preceding iteration, andprofile_changemeasures the scale/sign-invariant relative change of the resolved factor profiles. Convergence is reached as soon as any enabled tolerance is satisfied. By default, onlytol_residual_change=1e-3is enabled.With
log_level="INFO", these three diagnostics are printed using the same relative, dimensionless convention as their tolerances. The final message identifies the stopping diagnostic, its value, and its tolerance.The bilinear model has an intrinsic scale ambiguity: without a calibrated, unit-bearing initial
C0orSt0, the individual value units of the resolved factors are undefined. In that caseCandStremain unitless and use conservative titles. A calibrated initial factor fixes the scale convention, allowing the complementary units to be derived from[X] = [C][St].Operations that explicitly reset or exchange factor scale β spectral normalization, closure, and model/hard profile replacement β clear the resolved factor units. For horizontal augmentation,
St_blockscarries block-specific physical metadata; the heterogeneous concatenatedStis deliberately unitless with a neutral title.Initialize the BaseConfigurable class.
- Parameters:
log_level (int, optional) β The log level at startup. Default is logging.WARNING.
**kwargs (dict) β Additional keyword arguments for configuration.
Attributes Summary
The final accepted concentration profiles.
Concentration profiles split by experiment (block).
Final accepted concentration profiles.
Final accepted concentration profiles by ALS iteration.
Unconstrained concentration least-squares solutions by ALS iteration.
The final accepted spectral profiles.
Spectral profiles split by experiment (block).
Final accepted spectral profiles by ALS iteration.
The last spectral profiles obtained by least-square optimization, before constraints.
Unconstrained spectral least-squares solutions by ALS iteration.
Return the X input dataset (eventually modified by the model).
The
Yinput.Supplementary positional arguments passed to the external function.
Supplementary positional arguments passed to the external function.
The internal augmented data structure, or
Nonefor simple 2D data.Defines the concentration profiles subjected to closure constraint.
The method used to enforce closure (Omidikia et al. [2018]).
The value of the sum of concentrations profiles subjected to closure.
NDDatasetwith components in feature space (n_components, n_features).traitlets.config.Configobject.Public constraint objects for MCR-ALS.
The extra outputs of the external function used to get concentrations.
The extra outputs of the external function used to get spectra.
Correspondence of the profiles returned by
getConcandC[:,hardConc].An external function that provide
len(hardConc)concentration profiles.An external function that will provide
len(hardSpec)concentration profiles.Correspondence between the indexes of the spectra returned by
getSpecandSt.Defines hard constraints on the concentration profiles.
Defines hard constraints on the spectral profiles.
Whether the fit was performed on augmented (multiset) data.
Supplementary keyword arguments passed to the external function.
Supplementary keyword arguments passed to the external function.
Return
logoutput.Maximum number of ALS iteration.
Maximum number of successive non-converging iterations.
Monotonic decrease constraint on concentrations.
Tolerance parameter for monotonic decrease.
Monotonic increase constraint on concentrations.
Tolerance parameter for monotonic increase.
Number of components that were fitted.
Object name
Non-negativity constraint on concentrations.
Non-negativity constraint on spectra.
Defines whether the spectral profiles should be normalized.
AnalysisResultobject wrapping the fitted MCRALS estimator.Whether to store the C and St generated at each iteration.
Deprecated alias for 100 * tol_residual_change (percent).
Relative tolerance on the change of the resolved C and St profiles between successive iterations.
Tolerance on the relative reconstruction error norm(X - C @ St) / norm(X).
Relative tolerance on the change in residual standard deviation.
Unimodality constraint on concentrations.
Method to apply unimodality.
Tolerance parameter for unimodality.
Unimodality constraint on Spectra.
Method used to apply unimodality.
Tolerance parameter for unimodality.
Whether to reuse the previous solution on the next
fitcall.Methods Summary
fit(X,Β Y[,Β augmentation])Fit the MCRALS model on an X dataset using initial concentration or spectra.
fit_transform(X,Β Y,Β **kwargs)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([replace,Β removed,Β X,Β X_hat])Backward-compatible alias for
plot_merit.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])Return accepted concentrations with MCRALS factor metadata.
Attributes Documentation
- Cο
The final accepted concentration profiles.
Cis the factor accepted in the last ALS iteration after applying the configured concentration constraint pipeline and joint spectral normalization. If no configured operation changes the least-squares estimate, it is accepted unchanged. Together withStit satisfiesC @ St β X(reconstruction of the input data), where the reconstruction fidelity depends on the active constraints.For non-augmented and vertically augmented fits, the observation axis (rows) carries the observation coordinate of the original input dataset.
For horizontally augmented fits, all blocks share the same observation axis.
Cpreserves this shared coordinate (e.g. temperature) on its observation dimension.The component axis (columns) carries component labels obtained from
_get_component_labels.Value metadata follow the MCRALS scale policy: a calibrated
C0supplies the title and units, or the units are derived from calibratedSt0asX.units / St0.units. Without a preserved calibrated scale, the title is"relative concentration"and units are absent.
- C_blocksο
Concentration profiles split by experiment (block).
For vertically augmented data, one block per input dataset is returned, each with its own observation coordinate and title.
For horizontally augmented data, a single block is returned (all blocks share the same concentration matrix
C).When the input datasets were
NDDataset, each block is returned as anNDDatasetcarrying the original observation coordinates and title where available. For plain array inputs, blocks are returned asnumpy.ndarray.The blocks are copies of the relevant rows of the concatenated
Cmatrix. Modifying a returned block does not affect the fitted estimator (unlike_outfit[0]which returns the internal array directly).Each dataset block carries the resolved
Cvalue title and units. ExperimentalXvalue units are never copied directly: calibrated units come fromC0or are derived fromX.units / St0.units. Coordinate metadata remain block-specific and come from the matching input dataset.- Returns:
tuple of
numpy.ndarrayorNDDatasetβ One element per block. For non-augmented data, a single-element tuple containing the fullCarray is returned.
- C_constrainedο
Final accepted concentration profiles.
This compatibility output is synchronized with
Cafter the configured concentration constraint pipeline, joint normalization, and final ComponentPresence enforcement.
- C_constrained_listο
Final accepted concentration profiles by ALS iteration.
Entries include the configured concentration constraint pipeline, joint normalization, and final ComponentPresence enforcement. They are independent snapshots and require
MCRALS.storeIterationsset to True.
- C_ls_listο
Unconstrained concentration least-squares solutions by ALS iteration.
Each entry is the unconstrained least-squares solution before concentration constraints and normalization. Entries are independent snapshots and require
MCRALS.storeIterationsset to True.
- Stο
The final accepted spectral profiles.
Stis the factor accepted in the last ALS iteration after applying the configured spectral constraint pipeline and normalization. If no configured operation changes the least-squares estimate, it is accepted unchanged. Together withCit satisfiesC @ St β X(reconstruction of the input data).For non-augmented and vertically augmented fits,
Stcarries the original spectral coordinate on its feature axis.For horizontally augmented fits, the spectral axis is the concatenation of all blocksβ feature axes. Because different blocks may have incompatible spectral coordinates (e.g. UV wavelength vs CD wavelength), the global
Stuses a generic feature index. UseSt_blocksto obtain per-block spectral matrices with the original physical coordinates.A calibrated
St0supplies value title and units, or units are derived fromX.units / C0.units. Without a preserved calibrated scale, units are absent. For horizontal augmentation the global concatenated factor is always unitless with the neutral title"concatenated spectral profiles";St_blocksis authoritative.
- St_blocksο
Spectral profiles split by experiment (block).
Only meaningful for horizontally augmented data where each block has its own spectral matrix. For vertically augmented data (and for non-augmented data),
Stis common across blocks and this property returns a single-element tuple containing the fullStmatrix.When the input datasets were
NDDataset, each block is returned as anNDDatasetcarrying:the spectral coordinate (e.g. wavelength) from the corresponding input block on its feature axis;
component labels on its component axis.
block-specific value title and units from calibrated
St0blocks, or units derived from the correspondingXblock and calibratedC0.
For plain array inputs, blocks are returned as
numpy.ndarray.The blocks are copies of the relevant columns of the concatenated
Stmatrix. Modifying a returned block does not affect the fitted estimator.- Returns:
tuple of
numpy.ndarrayorNDDatasetβ One element per block.
- St_constrained_listο
Final accepted spectral profiles by ALS iteration.
Entries include the configured spectral constraint pipeline and normalization. They are independent snapshots and require
MCRALS.storeIterationsset to True.
- St_lsο
The last spectral profiles obtained by least-square optimization, before constraints.
Spectra obtained after solving \(C_{\textrm{constrained}} \cdot St = X\) for \(St\).
- St_ls_listο
Unconstrained spectral least-squares solutions by ALS iteration.
Each entry precedes spectral constraints and normalization. Entries are independent snapshots and require
MCRALS.storeIterationsset to True.
- Xο
Return the X input dataset (eventually modified by the model).
- argsGetConcο
Supplementary positional arguments passed to the external function.
- argsGetSpecο
Supplementary positional arguments passed to the external function.
- augmented_structureο
The internal augmented data structure, or
Nonefor simple 2D data.Returns a read-only view of the
_AugmentedStructuredescribing the block structure of vertically-augmented datasets. Only available after fitting.
- closureConcο
Defines the concentration profiles subjected to closure constraint.
[]: no constraint is applied.'all': all profile are constrained so that their weighted sum equals theclosureTargetlistof indexes: the corresponding profiles are constrained so that their weighted sum equalsclosureTarget.
- closureMethodο
The method used to enforce closure (Omidikia et al. [2018]).
'scaling'recompute the concentration profiles using least squares:\[C \leftarrow C \cdot \textrm{diag} \left( C_L^{-1} c_t \right)\]where \(c_t\) is the vector given by
closureTargetand \(C_L^{-1}\) is the left inverse of \(C\).'constantSum'normalize the sum of concentration profiles toclosureTarget.
- closureTargetο
The value of the sum of concentrations profiles subjected to closure.
'default': the total concentration is set to1.0for all observations.array-like of size n_observations: the values of concentration for each observation. Hence,
np.ones(X.shape[0]) would be equivalent to'default'.
- 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ο
Public constraint objects for MCR-ALS.
Noneselects the built-in defaults; an empty sequence means unconstrained. Otherwise, provide a list or tuple ofConstraintinstances defining the scientific constraints for the fit.
- extraOutputGetConcο
The extra outputs of the external function used to get concentrations.
- extraOutputGetSpecο
The extra outputs of the external function used to get spectra.
- getC_to_C_idxο
Correspondence of the profiles returned by
getConcandC[:,hardConc].'default': the profiles correspond to those ofC[:,hardConc]. This is equivalent torange(len(hardConc))listof indexes or ofNone. For instance[2, 1, 0]indicates that the third profile returned bygetC(index2) corresponds to the 1st profile ofC[:, hardConc], the 2nd returned profile (index1) corresponds to second profile ofC[:, hardConc], etcβ¦
- getConcο
An external function that provide
len(hardConc)concentration profiles.It should be using one of the following syntax:
getConc(Ccurr, *argsGetConc, **kwargsGetConc) -> hardCgetConc(Ccurr, *argsGetConc, **kwargsGetConc) -> hardC, newArgsGetConcgetConc(Ccurr, *argsGetConc, **kwargsGetConc) -> hardC, newArgsGetConc, extraOutputGetConc
where:
Ccurris the currentCdataset,argsGetConcare the parameters needed to completely specify the function.hardCis andarrayorNDDatasetof shape (n_observations , len(hardConc),newArgsGetConcare the updated parameters for the next iteration (can beNone),extraOutputGetConccan be any other relevant output to be kept inextraOutputGetConcattribute, a list ofextraOutputGetConcat each MCR ALS iteration.
Note
getConccan be also a serialized function created using dill and base64 python libraries. Normally not used directly, it is here for internal process.
- getSpecο
An external function that will provide
len(hardSpec)concentration profiles.It should be using one of the following syntax:
getSpec(Stcurr, *argsGetSpec, **kwargsGetSpec) -> hardStgetSpec(Stcurr, *argsGetSpec, **kwargsGetSpec) -> hardSt, newArgsGetSpecgetSpec(Stcurr, *argsGetSpec, **kwargsGetSpec) -> hardSt, newArgsGetSpec, extraOutputGetSpec
with:
*argsGetSpecand**kwargsGetSpec: the parameters needed to completely specify the function.hardSt:ndarrayorNDDatasetof shape(n_observations, len(hardSpec),newArgsGetSpec: updated parameters for the next ALS iteration (can be None),extraOutputGetSpec: any other relevant output to be kept inextraOutputGetSpecattribute, a list ofextraOutputGetSpecat each iterations.
Note
getSpeccan be also a serialized function created using dill and base64 python libraries. Normally not used directly, it is here for internal process.
- getSt_to_St_idxο
Correspondence between the indexes of the spectra returned by
getSpecandSt.'default': the indexes correspond to those ofSt. This is equivalent torange(len(hardSpec)).listof indexes : corresponding indexes inSt, i.e.[2, None, 0]indicates that the first returned profile corresponds to the thirdStprofile (index2), the 2nd returned profile does not correspond to any profile inSt, the 3rd returned profile corresponds to the firstStprofile (index0).
- hardConcο
Defines hard constraints on the concentration profiles.
- hardSpecο
Defines hard constraints on the spectral profiles.
- is_augmentedο
Whether the fit was performed on augmented (multiset) data.
- kwargsGetConcο
Supplementary keyword arguments passed to the external function.
- kwargsGetSpecο
Supplementary keyword arguments passed to the external function.
- logο
Return
logoutput.
- maxdivο
Maximum number of successive non-converging iterations.
- monoDecConcο
Monotonic decrease constraint on concentrations.
[]: no constraint is applied.listof indexes: the corresponding profiles are considered to decrease monotonically, not the others. For instance[0, 2]indicates that profile#0and#2are decreasing while profile#1can increase.
- monoDecTolο
Tolerance parameter for monotonic decrease.
Correction is applied only if:
C[i,j] > C[i-1,j] * monoDecTol.
- monoIncConcο
Monotonic increase constraint on concentrations.
[]: no constraint is applied.listof indexes: the corresponding profiles are considered to increase monotonically, not the others. For instance[0, 2]indicates that profile#0and#2are increasing while profile#1can decrease.
- monoIncTolο
Tolerance parameter for monotonic increase.
Correction is applied only if
C[i,j] < C[i-1,j] * monoIncTolalong profile#j.
- n_componentsο
Number of components that were fitted.
- nameο
Object name
- nonnegConcο
Non-negativity constraint on concentrations.
'all': all concentrations profiles are considered non-negative.listof indexes: the corresponding profiles are considered non-negative, not the others. For instance[0, 2]indicates that profile #0 and #2 are non-negative while profile #1 can be negative.[]: all profiles can be negative.
- nonnegSpecο
Non-negativity constraint on spectra.
'all': all profiles are considered non-negative.listof indexes : the corresponding profiles are considered non-negative, not the others. For instance[0, 2]indicates that profile#0and#2are non-negative while profile#1can be negative.[]: all profiles can be negative.
- normSpecο
Defines whether the spectral profiles should be normalized.
None: no normalization is applied.'euclid': spectra are normalized with respect to their total area,'max': spectra are normalized with respect to their maximum value.
- resultο
AnalysisResultobject wrapping the fitted MCRALS estimator.- Returns:
AnalysisResult β Container with
parameters,outputs, anddiagnosticsderived from the fitted estimator.- Raises:
NotFittedError β If the estimator has not been fitted yet.
- solverConcο
Solver used to get
CfromXandSt.'lstsq': uses ordinary least squares withlstsq'nnls': non-negative least squares (nnls) are applied sequentially on all profiles'pnnls': bounded least squares constrains the component profiles indicated innonnegConcto be non-negative while leaving other components unconstrained.
- solverSpecο
Solver used to get
StfromXandC.'lstsq': uses ordinary least squares withlstsq'nnls': non-negative least squares (nnls) are applied sequentially on all profiles'pnnls': bounded least squares constrains the component profiles indicated innonnegSpecto be non-negative while leaving other components unconstrained.
- storeIterationsο
Whether to store the C and St generated at each iteration.
- tolο
Deprecated alias for 100 * tol_residual_change (percent).
- tol_profile_changeο
Relative tolerance on the change of the resolved C and St profiles between successive iterations. Factor pairs are first normalized to remove their arbitrary reciprocal scale and sign; the larger relative Frobenius change of C and St is used. This dimensionless criterion is disabled when set to None.
- tol_reconstruction_errorο
Tolerance on the relative reconstruction error norm(X - C @ St) / norm(X). This dimensionless stopping criterion is disabled when set to None.
- tol_residual_changeο
Relative tolerance on the change in residual standard deviation. The dimensionless value is abs(sigma_k - sigma_(k-1)) / sigma_(k-1); 1e-3 therefore means 0.1%. Set to None to disable this stopping criterion.
- unimodConcο
Unimodality constraint on concentrations.
'all': all concentrations profiles are considered unimodal.listof indexes: the corresponding profiles are considered unimodal, not the others. For instance[0, 2]indicates that profile#0and#2are unimodal while profile#1can be multimodal.[]: all profiles can be multimodal.
- unimodConcModο
Method to apply unimodality.
'strict': values deviating from unimodality are reset to the value of the previous point.'smooth': both values (deviating point and previous point) are modified to avoid steps in the concentration profile.
- unimodConcTolο
Tolerance parameter for unimodality.
Correction is applied only if:
C[i,j] > C[i-1,j] * unimodConcTolon the decreasing branch of profile#j,C[i,j] < C[i-1,j] * unimodConcTolon the increasing branch of profile#j.
- unimodSpecο
Unimodality constraint on Spectra.
[]: all profiles can be multimodal.'all': all profiles are unimodal (equivalent torange(n_components)).array of indexes : the corresponding profiles are considered unimodal, not the others. For instance
[0, 2]indicates that profile#0and#2are unimodal while profile#1can be multimodal.
- unimodSpecModο
Method used to apply unimodality.
'strict': values deviating from unimodality are reset to the value of the previous point.'smooth': both values (deviating point and previous point) are modified to avoid steps in the concentration profile.
- unimodSpecTolο
Tolerance parameter for unimodality.
Correction is applied only if the deviating point
St[j, i]is larger thanSt[j, i-1] * unimodSpecTolon the decreasing branch of profile#j, or lower thanSt[j, i-1] * unimodSpecTolon the increasing branch of profile#j.
- warm_startο
Whether to reuse the previous solution on the next
fitcall.
Methods Documentation
- fit(X, Y, augmentation=None)[source]ο
Fit the MCRALS model on an X dataset using initial concentration or spectra.
- Parameters:
X (
NDDatasetor array-like of shape (n_observations, n_features)) β Training data. For augmented (multiset) analysis, a list or tuple of datasets can be passed. The augmentation mode is inferred from the input shapes (vertical if all share columns, horizontal if all share rows). When all datasets have identical dimensions, an ambiguity error is raised andaugmentationmust be specified explicitly.Note
Passing a single dataset in a list:
mcr.fit([X], guess)
explicitly requests the augmented-dataset workflow and creates a single augmentation block.
Passing the dataset directly:
mcr.fit(X, guess)
uses the standard single-dataset workflow.
Both approaches produce equivalent numerical MCR-ALS results, but the first exposes augmentation-specific features such as
is_augmented,C_blocks, andSt_blocks.Example:
mcr.fit([X1, X2, X3], guess)
Y (array-like or list of array-like) β Initial concentration or spectra. Unit-bearing
NDDatasetguesses define the physical factor scale when no configured operation subsequently resets it. A(C0, St0)pair with units is checked for dimensional compatibility withX.augmentation (str, optional) β Force the augmentation mode when it cannot be inferred. One of
"vertical"or"horizontal".
- Returns:
self β The fitted instance itself.
See also
transformApply dimensionality reduction.
fit_transformFit the model and apply dimensionality reduction.
- fit_transform(X, Y, **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 (array-like or list of array-like) β Initial concentration or spectra.
- Returns:
NDDatasetβ Transformed data 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)[source]ο
Transform data back to its original space.
In other words, return an input
X_originalwhose reduce/transform would be X.- Parameters:
X_transform (array-like of shape (n_observations, n_components), optional) β Reduced
Xdata. If not provided, the transform of the fitted X is used.- Returns:
NDDatasetβ Dataset with shape (n_observations, n_features).- Other Parameters:
n_components (
int, optional) β The number of components to use for the reduction.
- 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", removed="0.12") 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.
- transform(X=None, **kwargs)[source]ο
Return accepted concentrations with MCRALS factor metadata.
- Parameters:
X (
NDDatasetor array-like, optional) β Input dataset. MCRALS returns the fitted concentration factor; coordinates are taken from the fitted input dataset.**kwargs β Additional transformation options handled by the base estimator.
- Returns:
NDDatasetβ Final accepted concentration profiles with resolved factor title, units, observation coordinate, and component labels.
Examples using spectrochempy.MCRALS