class HyperspectralNMF:
"""
High-level interface for NMF decomposition of a hyperspectral XRD-CT volume.
Reshapes the 3-D volume into a 2-D pixel-by-channel matrix, runs
scikit-learn NMF, and exposes the component maps, component spectra, and
per-pixel RMSE through :meth:`fit_data`. Results can be visualised with
:meth:`plot`.
Attributes:
vol (np.ndarray): Original ``(nx, ny, n_channels)`` volume passed at construction.
X (np.ndarray): Flattened 2-D representation of shape ``(nx*ny, n_channels)``
used as NMF input.
n_comp (int): Number of NMF components.
x_spectra (np.ndarray): Spectral axis values.
unit (str): Spectral axis label used in plots.
W_maps (np.ndarray): Per-component spatial intensity maps, shape ``(nx, ny, K)``.
Set after calling :meth:`fit_data`.
H (np.ndarray): Component spectra of shape ``(K, n_channels)``.
Set after calling :meth:`fit_data`.
X_rec (np.ndarray): Reconstructed data matrix ``W @ H``, shape
``(nx*ny, n_channels)``. Set after calling :meth:`fit_data`.
E_map (np.ndarray): Per-pixel RMSE of shape ``(nx, ny)``.
Set after calling :meth:`fit_data`.
model (sklearn.decomposition.NMF): Fitted scikit-learn NMF object.
Set after calling :meth:`fit_data`.
"""
def __init__(
self,
volume: np.ndarray,
n_components: int,
spectral_axis: np.ndarray,
unit_name="energy (keV)",
loss_function="frobenius", # "frobenius" or "kullback-leibler"
solver=None, # None -> pick default based on loss
init="nndsvdar",
max_iter=1000,
random_state=0,
l1_ratio=0.0,
alpha_W=0.0,
alpha_H=0.0,
clip_negative=True,
):
"""
Args:
volume (np.ndarray): 3-D array of shape ``(n_channels, nx, ny)``
containing the hyperspectral volume.
n_components (int): Number of NMF components (endmembers) to extract.
spectral_axis (np.ndarray): 1-D array of spectral axis values
(e.g. 2θ or energy), length ``n_channels``.
unit_name (str, optional): Label for the spectral axis used in plots
(default ``"energy (keV)"``).
loss_function (str, optional): NMF beta-loss: ``"frobenius"`` (default)
or ``"kullback-leibler"``.
solver (str or None, optional): NMF solver; ``None`` selects ``"cd"``
for Frobenius and ``"mu"`` for KL loss automatically.
init (str, optional): Initialisation strategy passed to
:class:`~sklearn.decomposition.NMF` (default ``"nndsvdar"``).
max_iter (int, optional): Maximum number of NMF iterations (default 1000).
random_state (int, optional): Random seed for reproducibility (default 0).
l1_ratio (float, optional): Elastic-net mixing parameter; 0 = pure L2,
1 = pure L1 (default 0.0).
alpha_W (float, optional): Regularisation strength applied to W
(default 0.0).
alpha_H (float, optional): Regularisation strength applied to H
(default 0.0).
clip_negative (bool, optional): If ``True``, negative values in the
input are clipped to zero before fitting (default ``True``).
"""
self.vol = volume
self.X = volume.transpose(1, 2, 0).reshape(
(volume.shape[1] * volume.shape[2], volume.shape[0])
)
self.map_shape = (volume.shape[1], volume.shape[2])
self.n_comp = n_components
# self.comp_map = np.empty((self.n_comp, self.map_shape[0], self.map_shape[1]), dtype=float)
self.x_spectra = spectral_axis
self.unit = unit_name
self.loss_function = loss_function
self.solver = solver
self.init = init
self.iter_max = max_iter
self.rand_state = random_state
self.l1ratio = l1_ratio
self.alphaW = alpha_W
self.alphaH = alpha_H
self.clip_negative = clip_negative
def fit_data(self) -> None:
"""
Fit the NMF model and store results as instance attributes.
After calling this method the following attributes are available:
- ``W_maps`` — ``(nx, ny, K)`` component intensity maps
- ``H`` — ``(K, n_channels)`` component spectra
- ``X_rec`` — ``(n_pixels, n_channels)`` reconstructed data matrix
- ``E_map`` — ``(nx, ny)`` per-pixel RMSE map
- ``model`` — fitted :class:`~sklearn.decomposition.NMF` object
"""
W_maps, H, X_rec, E_map, model = _nmf_sklearn_hyperspectral(
X=self.X, # (n_pixels, n_channels)
map_shape=self.map_shape, # (nx, ny) with nx*ny == n_pixels
n_components=self.n_comp,
wavelength=self.x_spectra, # (n_channels,)
unit_name=self.unit,
loss=self.loss_function, # "frobenius" or "kullback-leibler"
solver=self.solver, # None -> pick default based on loss
init=self.init,
max_iter=self.iter_max,
random_state=self.rand_state,
l1_ratio=self.l1ratio,
alpha_W=self.alphaW,
alpha_H=self.alphaH,
clip_negative=self.clip_negative,
show_progress=True,
)
self.W_maps = W_maps
self.H = H
self.X_rec = X_rec
self.E_map = E_map
self.model = model
def plot(
self,
normalize_spectra: bool = False,
titles=None,
figsize=(14, 7),
extent=None,
save=True,
) -> None:
"""
Visualise the NMF decomposition with component spectra and spatial maps.
Args:
normalize_spectra (bool, optional): If ``True``, normalise each component
spectrum to unit L2 norm before plotting (default ``False``).
titles (list or None, optional): Per-component subplot titles; defaults
to ``["Component 1", ...]``.
figsize (tuple, optional): Figure size in inches (default ``(14, 7)``).
extent (tuple or None, optional): ``(xmin, xmax, ymin, ymax)`` passed to
:func:`~matplotlib.pyplot.imshow` for physical axis scaling
(default ``None``).
save (bool, optional): If ``True``, save the figure to
``nmf_decomposition_<K>_components.png`` (default ``True``).
"""
_plot_nmf_panel(
W_maps=self.W_maps,
H=self.H,
E_map=self.E_map,
wavelength=self.x_spectra,
unit_name=self.unit,
normalize_spectra=normalize_spectra,
titles=titles,
figsize=figsize,
extent=extent,
save=save,
)