def fit_fluo_volume(
data,
energy_axis,
elements,
excitation_energy,
fwhm_keV=0.18,
background_order=2,
method="lstsq",
n_jobs=-1,
) -> dict[str, np.ndarray]:
"""
Fit fluorescence spectra for every pixel in a 3-D dataset.
Args:
data (np.ndarray): Full-spectrum dataset of shape ``(n_energy, n_y, n_x)``;
axis 0 is the energy dimension.
energy_axis (np.ndarray): Energy in keV for each channel, shape
``(n_energy,)``.
elements (list): Elements to fit, e.g. ``["Fe", "Cu", "Zn"]``.
excitation_energy (float): Incident beam energy in keV.
fwhm_keV (float, optional): Detector FWHM in keV (default 0.18).
background_order (int, optional): Polynomial degree for the background
model (default 2).
method (str, optional): Fitting strategy. ``"lstsq"`` solves all pixels
in a single batched ``np.linalg.lstsq`` call — very fast but
non-negativity is only enforced by clipping. ``"nnls"`` calls
``scipy.optimize.nnls`` per pixel (parallelised with ``joblib``) —
strictly non-negative but slower. Default ``"lstsq"``.
n_jobs (int, optional): Number of parallel workers for ``method="nnls"``
(``-1`` uses all CPUs). Ignored for ``method="lstsq"`` (default ``-1``).
Returns:
coeff_maps (dict): Mapping ``element -> np.ndarray`` of shape ``(n_y, n_x)``
with the fitted amplitude for each spatial pixel.
"""
n_energy, n_y, n_x = data.shape
n_pixels = n_y * n_x
A, labels = build_fit_matrix(
energy_axis, elements, excitation_energy, fwhm_keV, background_order
)
element_labels = [l for l in labels if not l.startswith("_bg")]
# Shape: (n_energy, n_pixels) — keeps memory contiguous for LAPACK
spectra = data.reshape(n_energy, n_pixels)
if method == "lstsq":
# Single batched solve: A (n_energy, n_comp) \ spectra (n_energy, n_pixels)
coeffs, _, _, _ = np.linalg.lstsq(A, spectra, rcond=None)
# coeffs: (n_comp, n_pixels) -> (n_pixels, n_comp)
coeffs = np.clip(coeffs.T, 0, None)
elif method == "nnls":
# spectra.T: (n_pixels, n_energy) for row-wise iteration
spectra_t = np.ascontiguousarray(spectra.T)
try:
from joblib import Parallel, delayed
results = Parallel(n_jobs=n_jobs)(
delayed(nnls)(A, spectra_t[i]) for i in range(n_pixels)
)
coeffs = np.array([r[0] for r in results])
except ImportError:
coeffs = np.array(
[nnls(A, spectra_t[i])[0] for i in tqdm(range(n_pixels))]
)
else:
raise ValueError(f"Unknown method '{method}'. Choose 'lstsq' or 'nnls'.")
coeff_maps = {
label: coeffs[:, j].reshape(n_y, n_x)
for j, label in enumerate(labels)
if label in element_labels
}
return coeff_maps