Unmixing and spectral selection
Use positive_least_squares() when the component spectra are known. It
fits nonnegative abundances while holding those spectra fixed. Use
mcr_als() when you have starting spectra and want to refine them along
with the abundances. Neither function identifies fluorophores by name.
Array shapes and scale
| Array | Shape | Ordering |
|---|---|---|
| Observations | (N, C) |
One row per pixel or other observation |
| Component spectra | (K, C) |
One row per component, with the same detector channels and order as the observations |
| Abundances | (N, K) |
Same observation order as the input and same component order as the spectra |
image.unfold().data provides the observation matrix. For a
SpectrumCollection, use references.values as the component matrix after
checking that the detector grid matches the image. Save the exact basis and
its scale with the abundances if you want to reconstruct the fit later. See
Image containers and
Save images and spectra.
Fixed references and MCR-ALS
Normalize the references explicitly when you want to reuse or save the
effective basis. For example, normalize each reference to unit L1 norm,
then fit with do_norm=False to use those rows as supplied.
from lumic import normalize_components, positive_least_squares
unfolded = image.unfold()
basis = normalize_components(references.values, do_norm="L1")
abundances = positive_least_squares(unfolded.data, basis, do_norm=False)
maps = unfolded.fold_abundances(abundances, spectra=basis, normalization="L1")
With MCR-ALS, the returned abundances and spectra come from the same best iteration. If you refine on a subset of pixels, fit the resulting spectra against the full set of observations before folding the abundances. See Unmix a ternary image and Estimate unknown spectra.
positive_least_squares(mixed_data, components, do_norm=False, batch_size=1000, verbose=False, *, solver='nnls')
Fit nonnegative abundances with fixed component spectra.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mixed_data
|
ndarray
|
Observation matrix of shape (N, C), with one row per pixel or other observation and one column per detector channel. |
required |
components
|
ndarray
|
Reference spectra of shape (K, C), with one row per component. The detector channels must match the observations in count and order. |
required |
do_norm
|
(False, L1, L2)
|
False uses the reference rows at their supplied scale. "L1" or "L2" normalizes each nonzero reference row before fitting. The returned abundances correspond to the scale used in the fit. Use nonzero references when requesting normalization. |
False
|
batch_size
|
int
|
Maximum number of observations processed in a batch, default 1000. |
1000
|
verbose
|
bool
|
Show a progress bar when True. |
False
|
solver
|
(nnls, auto)
|
"nnls" uses the standard nonnegative least squares solver. "auto" tries a batched solver for up to six well-conditioned components and falls back to the standard path as needed. |
"nnls"
|
Returns:
| Name | Type | Description |
|---|---|---|
abundance |
ndarray
|
Shape (N, K), ordered like the input observations and component rows. |
Notes
When NNLS does not converge, the observations in that batch are retried individually with bounded variable least squares (BVLS). Rows that still fail contain NaN. A RuntimeWarning reports the fallback and identifies any unresolved observation indices.
mcr_als(mixData, in_estimates, nIter, normL, *, tol_percent=None, return_diagnostics=False, iteration_callback=None, solver='auto')
Fit nonnegative concentration and spectral factors by alternating least squares.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mixData
|
ndarray
|
Spectral data with pixels in rows and channels in columns. |
required |
in_estimates
|
ndarray
|
Initial spectra with components in rows and channels in columns. Initial concentration estimates are not yet supported. |
required |
nIter
|
int
|
Maximum number of alternating spectral and concentration updates. |
required |
normL
|
bool or str
|
False leaves spectra unscaled; "L1" or "L2" gives each spectrum unit norm. Concentrations are fitted against the spectra on that same scale. |
required |
tol_percent
|
float
|
Stop when a complete update improves relative lack of fit by no more than this percentage. None runs all nIter updates. A fit at numerical precision also stops. A worsening step never counts as convergence. |
None
|
return_diagnostics
|
bool
|
If True, return an additional MCRALSDiagnostics value. |
False
|
iteration_callback
|
callable
|
If provided, called with the number of completed updates after each iteration. This can be used to report progress without changing the fitting results. |
None
|
solver
|
str
|
"auto" batches small, well-conditioned nonnegative least-squares problems, falling back to the original solver when needed. "nnls" uses the original per-observation solver for comparison. Both solve the same constrained least-squares objective. If "auto" falls back because the component count exceeds the batch limit, print an informational message once at the start of the run. |
'auto'
|
Returns:
| Name | Type | Description |
|---|---|---|
out_C |
ndarray
|
Fitted concentrations, with pixels in rows and components in columns. |
out_S |
ndarray
|
Fitted spectra on the scale selected by normL. |
R_vector |
ndarray
|
Fractional lack of fit before the first update and after each completed update. The returned factors are from the best iteration, which may precede the last history entry. |
diagnostics |
(MCRALSDiagnostics, optional)
|
Stopping reason, updates completed, best iteration, and best fit. |
MCRALSDiagnostics
dataclass
Why MCR-ALS stopped and where its best paired factors were found.
stop_reason
instance-attribute
iterations_completed
instance-attribute
best_iteration
instance-attribute
best_relative_l2
instance-attribute
normalize_components(components, do_norm=False)
Normalize component rows, keeping rows with no signal at zero.
Select pixels and starting spectra
Use select_analysis_pixels() on a loaded 3D spectral plane to track the
pixels included in the analysis. Its indices map back to the original
spatial positions. To find starting spectra, pass the selected observations
to essential_spectral_pixels(), then transpose the candidate matrix
before passing it to unique_profiles().
from lumic import essential_spectral_pixels, select_analysis_pixels, unique_profiles
plane = image.slice()
pixels = plane.unfold().data
selection = select_analysis_pixels(plane.data, spectral_axis=plane.axes.index("C"))
candidates, candidate_indices = essential_spectral_pixels(
pixels[selection.indices], npc=3,
)
starts, _ = unique_profiles(candidates.T, nr=3, f=1.0)
candidate_indices indexes the selected rows. Use
selection.indices[candidate_indices] to get the corresponding original
pixel indices. The old spelling essential_spectral_pixles remains an alias
for existing code.
select_analysis_pixels(image, *, median_quantile=None, spectral_axis=0)
Select candidate pixels for analysis without changing the measured image.
Purpose
Use before convex-hull selection or other fitting-pool construction when original pixel locations must survive filtering. The result includes mask, original indices, threshold/settings and exclusion reasons. A faint pixel can be valid yet excluded from this analysis pool; selection does not erase it from the image or establish that it contains only noise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
array-like, 3D
|
Real numeric spectral image. Default layout is (channels, y, x); spectral_axis=-1 supports simulation images (y, x, channels). |
required |
median_quantile
|
float in [0, 1] or None
|
Optional percentile threshold on each pixel's median across channels. Calculate the threshold from finite, nonnegative pixels, including zeros, to retain the legacy median rule on valid nonnegative images. Exclude values strictly below it; ties remain. None disables this rule. Zero retains all otherwise usable pixels; one retains the maximum ties. |
None
|
spectral_axis
|
int
|
Axis containing spectral channels; other axes retain their order. |
0
|
Returns:
| Type | Description |
|---|---|
AnalysisPixelSelection
|
Original spatial mask/indices and disjoint exclusion reasons. Pixels with any nonfinite or negative value, or all-zero spectra, are excluded regardless of the optional median filter. If none are usable, return empty indices and an all-false mask; a hull/solver may require more data. |
Limitations
Excluding negative intensities assumes nonnegative unmixing, and may be inappropriate for signed offset-corrected measurements. This function does not repair invalid data, estimate noise, detect saturation, or normalize spectra. Full-image unmixing still needs its own input validation. Future rules can extend this selection interface without combining it with hull calculation. Low-intensity exclusion can discard meaningful minor species.
Examples:
>>> image = np.array([[[0, 1, 4]], [[0, 3, 6]]])
>>> retained = select_analysis_pixels(image, median_quantile=0.5)
>>> retained.indices.tolist()
[1, 2]
>>> retained.median_threshold
2.0
Use unfolded.data[retained.indices] when unfolded was created from
the same image with SpectralImage.unfold(). The result stores the
selection without copying the selected spectra.
AnalysisPixelSelection
dataclass
Traceable selection in the original image's spatial coordinates.
mask has the spatial image shape and indices indexes its C-order
flattening, equivalent to np.flatnonzero(mask). Move the spectral axis
last before flattening the measured spectra. exclusion_masks records
disjoint reasons: nonfinite input, negative intensity, zero signal, and
below-median threshold. These labels describe selection rules, not sample
identities or noise significance. Frozen fields do not make arrays immutable.
indices
instance-attribute
mask
instance-attribute
image_shape
instance-attribute
spectral_axis
instance-attribute
median_quantile
instance-attribute
median_threshold
instance-attribute
exclusion_masks
instance-attribute
exclusion_counts
property
Number of pixels excluded for each disjoint selection reason.
essential_spectral_pixels(mixed_data, npc=3)
Select candidate pixel spectra at the extremes of an SVD projection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mixed_data
|
ndarray
|
Spectral observations of shape (N, C), with pixels in rows and detector channels in columns. Each row must have a usable first SVD coordinate. |
required |
npc
|
int
|
Number of SVD components, default 3. Dividing the remaining coordinates by the first leaves a projection of dimension npc - 1. |
3
|
Returns:
| Name | Type | Description |
|---|---|---|
candidates |
ndarray
|
Original spectra of shape (number of candidates, C). In one projected dimension, the candidates are the two endpoints. |
indices |
ndarray
|
Row indices into mixed_data, in the same order as candidates. |
Notes
Candidate rows are useful starting points for blind unmixing. Hull membership does not establish that a spectrum comes from one component.
unique_profiles(d, nr, f)
Select distinct profiles from the columns of a data matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
ndarray
|
Matrix with one candidate profile per column. To select spectra,
pass the transpose of the candidates returned by
|
required |
nr
|
int
|
Number of profiles to select. |
required |
f
|
float
|
Noise offset as a percentage of the largest column mean. For example, f=1.0 adds an offset of 1 percent of that mean. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
profiles |
ndarray
|
Selected profiles as rows, with shape (nr, number of input rows). |
indices |
ndarray
|
Selected column indices into d, in the same order as profiles. |
Inspect spectral distinctness
spectral_uniqueness_map() scores how far each usable pixel lies from the
center of a fitted spectral projection. It does not select a component
basis or assign fluorophore identities. spectral_uniqueness_rgb() turns
those scores and directions into a display image and requires the
visualization extra. See Spectral uniqueness maps.
spectral_uniqueness_map(image, *, npc=3, spectral_axis=0, min_total_intensity=0.0, reference=None, random_state=0)
Score distance from the center of the convex-hull spectral space.
The mapping is the same as essential_spectral_pixels: fit an
uncentered TruncatedSVD to pixel spectra, divide each projected row by
its first coordinate, and retain coordinates 2 through npc. The score
is Euclidean distance from the mean point in that space. Computing a
hull or choosing component signatures is not required to score pixels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
ndarray
|
Nonempty 3D spectral image, default layout (channel, y, x). Use
|
required |
npc
|
int
|
Number of SVD components, as in the hull helper. The resulting space has npc-1 coordinates. Must be at least two and no larger than the channel count or retained pixel count when fitting a new projection. Ignored when a reference supplies an existing projection. |
3
|
spectral_axis
|
int
|
Channel axis. The other axes keep their order in the returned maps. |
0
|
min_total_intensity
|
float
|
Retain pixels whose summed signal is at least this nonnegative value. Zero-signal pixels are always excluded. Set a threshold appropriate to the acquisition so very faint pixels do not amplify noise. |
0.0
|
reference
|
SpectralUniquenessResult
|
Reuse both the SVD basis and center from a previous result. Images must use the same channel definitions and order. This keeps the coordinate system fixed across images or brightness changes. |
None
|
random_state
|
int
|
Seed for fitting TruncatedSVD; default zero gives repeatable mapping. |
0
|
Returns:
| Type | Description |
|---|---|
SpectralUniquenessResult
|
Distances, mask, intensity, projected coordinates, center, and basis. |
Notes
This is spectral distinctness relative to the retained population, not a purity probability. Uniform pure spectra have zero distance from their own center. Noise, background, and artifacts can also lie far from it.
First-coordinate normalization cancels a pixel's multiplicative intensity for a fixed basis. Refitting SVD after changing brightness or the retained population can change that basis and therefore the distances. Reuse a reference for controlled comparisons. Scores are raw distances, without per-image display rescaling, and depend on npc and the detector channels.
Negative/nonfinite spectra, nonfinite totals, insufficient signal, and near-zero first SVD coordinates are excluded rather than clipped. At least one usable projected pixel is required.
SpectralUniquenessResult
dataclass
A distance map and its fitted spectral coordinate system.
scores, valid_mask, and total_intensity have the image's spatial
shape. coordinates adds an axis of length npc-1. Excluded pixels have
NaN scores and coordinates. center_coordinates is the mean position
of retained pixels, unless a reference result supplies the center.
projection_components stores the SVD basis for later comparisons.
scores
instance-attribute
valid_mask
instance-attribute
total_intensity
instance-attribute
coordinates
instance-attribute
center_coordinates
instance-attribute
projection_components
instance-attribute
spectral_uniqueness_rgb(result, *, max_distance=None)
Color spectral direction by hue and full-space distance by brightness and saturation.
Use the first two retained coordinates relative to the spectral center for the angle, regardless of npc. With npc=2, negative and positive positions use cyan and red respectively. HSV brightness and saturation both increase with distance. Pixels at the center are black; excluded pixels are dark gray.
max_distance is the positive distance displayed at full brightness and saturation. By default use the largest retained score. Reuse an explicit scale along with a shared projection/center when comparing images. Larger distances are clipped for display only; numerical scores are unchanged.
In higher dimensions, directions outside the displayed plane cannot be distinguished by hue. When both displayed coordinates are effectively zero, show black because the displayed direction is undefined, even if the full-dimensional score is nonzero. Colors are projection directions, not fluorophore identities or physical emission colors.