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). None selects the built-in default constraints; an empty list requests an unconstrained fit.

    constraints can be passed at construction time or assigned before calling fit:

    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 profiles C from X and St.

  • solver_St ('lstsq' | 'nnls' | 'pnnls', optional, default: 'lstsq') – Solver used to estimate spectral profiles St from X and C.

  • 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_start is True, the existing fitted model attributes is used to initialize the new model in a subsequent call to fit.

  • 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.

See also

fit

Fit the MCRALS model on X.

transform

Apply dimensionality reduction.

fit_transform

Fit the model and apply dimensionality reduction.

Notes

Three dimensionless stopping diagnostics are evaluated after each ALS iteration: reconstruction_error measures the current relative reconstruction error, residual_change measures the relative change in residual standard deviation since the preceding iteration, and profile_change measures the scale/sign-invariant relative change of the resolved factor profiles. Convergence is reached as soon as any enabled tolerance is satisfied. By default, only tol_residual_change=1e-3 is 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 C0 or St0, the individual value units of the resolved factors are undefined. In that case C and St remain 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_blocks carries block-specific physical metadata; the heterogeneous concatenated St is 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

C

The final accepted concentration profiles.

C_blocks

Concentration profiles split by experiment (block).

C_constrained

Final accepted concentration profiles.

C_constrained_list

Final accepted concentration profiles by ALS iteration.

C_ls_list

Unconstrained concentration least-squares solutions by ALS iteration.

St

The final accepted spectral profiles.

St_blocks

Spectral profiles split by experiment (block).

St_constrained_list

Final accepted spectral profiles by ALS iteration.

St_ls

The last spectral profiles obtained by least-square optimization, before constraints.

St_ls_list

Unconstrained spectral least-squares solutions by ALS iteration.

X

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

Y

The Y input.

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 None for simple 2D data.

closureConc

Defines the concentration profiles subjected to closure constraint.

closureMethod

The method used to enforce closure (Omidikia et al. [2018]).

closureTarget

The value of the sum of concentrations profiles subjected to closure.

components

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

config

traitlets.config.Config object.

constraints

Public constraint objects for MCR-ALS.

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 getConc and C[:,hardConc].

getConc

An external function that provide len(hardConc) concentration profiles.

getSpec

An external function that will provide len(hardSpec) concentration profiles.

getSt_to_St_idx

Correspondence between the indexes of the spectra returned by getSpec and St.

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 log output.

max_iter

Maximum number of ALS iteration.

maxdiv

Maximum number of successive non-converging iterations.

monoDecConc

Monotonic decrease constraint on concentrations.

monoDecTol

Tolerance parameter for monotonic decrease.

monoIncConc

Monotonic increase constraint on concentrations.

monoIncTol

Tolerance parameter for monotonic increase.

n_components

Number of components that were fitted.

name

Object name

nonnegConc

Non-negativity constraint on concentrations.

nonnegSpec

Non-negativity constraint on spectra.

normSpec

Defines whether the spectral profiles should be normalized.

result

AnalysisResult object wrapping the fitted MCRALS estimator.

solverConc

Solver used to get C from X and St.

solverSpec

Solver used to get St from X and C.

solver_C

Solver used to get C from X and St.

solver_St

Solver used to get St from X and C.

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.

tol_reconstruction_error

Tolerance on the relative reconstruction error norm(X - C @ St) / norm(X).

tol_residual_change

Relative tolerance on the change in residual standard deviation.

unimodConc

Unimodality constraint on concentrations.

unimodConcMod

Method to apply unimodality.

unimodConcTol

Tolerance parameter for unimodality.

unimodSpec

Unimodality constraint on Spectra.

unimodSpecMod

Method used to apply unimodality.

unimodSpecTol

Tolerance parameter for unimodality.

warm_start

Whether to reuse the previous solution on the next fit call.

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 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,Β 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.

C is 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 with St it satisfies C @ 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. C preserves 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 C0 supplies the title and units, or the units are derived from calibrated St0 as X.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 an NDDataset carrying the original observation coordinates and title where available. For plain array inputs, blocks are returned as numpy.ndarray.

The blocks are copies of the relevant rows of the concatenated C matrix. 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 C value title and units. Experimental X value units are never copied directly: calibrated units come from C0 or are derived from X.units / St0.units. Coordinate metadata remain block-specific and come from the matching input dataset.

Returns:

tuple of numpy.ndarray or NDDataset – One element per block. For non-augmented data, a single-element tuple containing the full C array is returned.

C_constrained

Final accepted concentration profiles.

This compatibility output is synchronized with C after 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.storeIterations set 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.storeIterations set to True.

St

The final accepted spectral profiles.

St is 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 with C it satisfies C @ St β‰ˆ X (reconstruction of the input data).

For non-augmented and vertically augmented fits, St carries 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 St uses a generic feature index. Use St_blocks to obtain per-block spectral matrices with the original physical coordinates.

A calibrated St0 supplies value title and units, or units are derived from X.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_blocks is 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), St is common across blocks and this property returns a single-element tuple containing the full St matrix.

When the input datasets were NDDataset, each block is returned as an NDDataset carrying:

  • 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 St0 blocks, or units derived from the corresponding X block and calibrated C0.

For plain array inputs, blocks are returned as numpy.ndarray.

The blocks are copies of the relevant columns of the concatenated St matrix. Modifying a returned block does not affect the fitted estimator.

Returns:

tuple of numpy.ndarray or NDDataset – 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.storeIterations set 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.storeIterations set to True.

X

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

Y

The Y input.

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 None for simple 2D data.

Returns a read-only view of the _AugmentedStructure describing 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 the closureTarget

  • list of indexes: the corresponding profiles are constrained so that their weighted sum equals closureTarget.

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 closureTarget and \(C_L^{-1}\) is the left inverse of \(C\).

  • 'constantSum' normalize the sum of concentration profiles to closureTarget.

closureTarget

The value of the sum of concentrations profiles subjected to closure.

  • 'default': the total concentration is set to 1.0 for 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

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

Public constraint objects for MCR-ALS. None selects the built-in defaults; an empty sequence means unconstrained. Otherwise, provide a list or tuple of Constraint instances 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 getConc and C[:,hardConc].

  • 'default': the profiles correspond to those of C[:,hardConc]. This is equivalent to range(len(hardConc))

  • list of indexes or of None. For instance [2, 1, 0] indicates that the third profile returned by getC (index 2) corresponds to the 1st profile of C[:, hardConc], the 2nd returned profile (index 1) corresponds to second profile of C[:, 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) -> hardC

  • getConc(Ccurr, *argsGetConc, **kwargsGetConc) -> hardC, newArgsGetConc

  • getConc(Ccurr, *argsGetConc, **kwargsGetConc) -> hardC, newArgsGetConc, extraOutputGetConc

where:

  • Ccurr is the current C dataset,

  • argsGetConc are the parameters needed to completely specify the function.

  • hardC is a ndarray or NDDataset of shape (n_observations , len(hardConc),

  • newArgsGetConc are the updated parameters for the next iteration (can be None),

  • extraOutputGetConc can be any other relevant output to be kept in extraOutputGetConc attribute, a list of extraOutputGetConc at each MCR ALS iteration.

Note

getConc can 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) -> hardSt

  • getSpec(Stcurr, *argsGetSpec, **kwargsGetSpec) -> hardSt, newArgsGetSpec

  • getSpec(Stcurr, *argsGetSpec, **kwargsGetSpec) -> hardSt, newArgsGetSpec, extraOutputGetSpec

with:

  • Stcurr: the current value of St in the ALS loop,

  • *argsGetSpec and **kwargsGetSpec: the parameters needed to completely specify the function.

  • hardSt: ndarray or NDDataset of shape (n_observations, len(hardSpec),

  • newArgsGetSpec: updated parameters for the next ALS iteration (can be None),

  • extraOutputGetSpec: any other relevant output to be kept in extraOutputGetSpec attribute, a list of extraOutputGetSpec at each iterations.

Note

getSpec can 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 getSpec and St.

  • 'default': the indexes correspond to those of St. This is equivalent to range(len(hardSpec)).

  • list of indexes : corresponding indexes in St, i.e. [2, None, 0] indicates that the first returned profile corresponds to the third St profile (index 2), the 2nd returned profile does not correspond to any profile in St, the 3rd returned profile corresponds to the first St profile (index 0 ).

hardConc

Defines hard constraints on the concentration profiles.

  • []: no constraint is applied.

  • list of indexes: the corresponding profiles will set by getConc.

hardSpec

Defines hard constraints on the spectral profiles.

  • []: no constraint is applied.

  • list of indexes : the corresponding profiles will set by getSpec.

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 log output.

max_iter

Maximum number of ALS iteration.

maxdiv

Maximum number of successive non-converging iterations.

monoDecConc

Monotonic decrease constraint on concentrations.

  • []: no constraint is applied.

  • list of indexes: the corresponding profiles are considered to decrease monotonically, not the others. For instance [0, 2] indicates that profile #0 and #2 are decreasing while profile #1 can 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.

  • list of indexes: the corresponding profiles are considered to increase monotonically, not the others. For instance [0, 2] indicates that profile #0 and #2 are increasing while profile #1 can decrease.

monoIncTol

Tolerance parameter for monotonic increase.

Correction is applied only if C[i,j] < C[i-1,j] * monoIncTol along 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.

  • list of 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.

  • list of 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.

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

AnalysisResult object wrapping the fitted MCRALS estimator.

Returns:

AnalysisResult – Container with parameters, outputs, and diagnostics derived from the fitted estimator.

Raises:

NotFittedError – If the estimator has not been fitted yet.

solverConc

Solver used to get C from X and St.

  • 'lstsq': uses ordinary least squares with lstsq

  • 'nnls': non-negative least squares (nnls) are applied sequentially on all profiles

  • 'pnnls': bounded least squares constrains the component profiles indicated in nonnegConc to be non-negative while leaving other components unconstrained.

solverSpec

Solver used to get St from X and C.

  • 'lstsq': uses ordinary least squares with lstsq

  • 'nnls': non-negative least squares (nnls) are applied sequentially on all profiles

  • 'pnnls': bounded least squares constrains the component profiles indicated in nonnegSpec to be non-negative while leaving other components unconstrained.

solver_C

Solver used to get C from X and St.

solver_St

Solver used to get St from X and C.

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.

  • list of indexes: the corresponding profiles are considered unimodal, not the others. For instance [0, 2] indicates that profile #0 and #2 are unimodal while profile #1 can 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] * unimodConcTol on the decreasing branch of profile #j,

  • C[i,j] < C[i-1,j] * unimodConcTol on the increasing branch of profile #j.

unimodSpec

Unimodality constraint on Spectra.

  • []: all profiles can be multimodal.

  • 'all': all profiles are unimodal (equivalent to range(n_components)).

  • array of indexes : the corresponding profiles are considered unimodal, not the others. For instance [0, 2] indicates that profile #0 and #2 are unimodal while profile #1 can 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 than St[j, i-1] * unimodSpecTol on the decreasing branch of profile #j, or lower than St[j, i-1] * unimodSpecTol on the increasing branch of profile #j.

warm_start

Whether to reuse the previous solution on the next fit call.

Methods Documentation

fit(X, Y, augmentation=None)[source]

Fit the MCRALS model on an X dataset using initial concentration or spectra.

Parameters:
  • X (NDDataset or 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 and augmentation must 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, and St_blocks.

    Example:

    mcr.fit([X1, X2, X3], guess)
    
  • Y (array-like or list of array-like) – Initial concentration or spectra. Unit-bearing NDDataset guesses define the physical factor scale when no configured operation subsequently resets it. A (C0, St0) pair with units is checked for dimensional compatibility with X.

  • 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

transform

Apply dimensionality reduction.

fit_transform

Fit the model and apply dimensionality reduction.

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

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

Parameters:
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. 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)[source]

Transform data back to its original space.

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

Parameters:

X_transform (array-like of shape (n_observations, n_components), optional) – Reduced X data. 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.

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", 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.

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]

Return accepted concentrations with MCRALS factor metadata.

Parameters:
  • X (NDDataset or 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

MCR-ALS example (adapted from Jaumot et al. 2005)

MCR-ALS example (adapted from Jaumot et al. 2005)

MCR-ALS with kinetic constraints

MCR-ALS with kinetic constraints