Skip to content

Evaluation API

What you have What you can evaluate Use
An experimental image and its fitted reconstruction How closely the fit reproduces the measured signal and where it leaves structured errors reconstruction_error_maps(), residual PCA, and residual correlations
Two fits or a set of reference spectra on the same detector grid How similar the component spectra are and which rows correspond compare_spectra() and match_components()
A simulation with known spectra and abundance maps How accurately the fit recovers the true spectra and abundances, in addition to how well it fits the image evaluate_factors() and concentration_error_maps()

Experimental images: assess the fit without ground truth

On a typical experimental image, you have the measured detector signal but do not know the true contribution of each fluorophore at each pixel. You can check where the model fits poorly and compare spectra across fits. Even a close fit can come from different combinations of spectra and abundances. These checks cannot tell you the true abundance error.

Locate unexplained signal in space and across channels

Pass observed and reconstructed arrays with identical shapes, the same channel order and intensity units, and channels last. The residual is observed minus reconstructed. Positive values indicate underestimated signal. RMS measures the mismatch in the input intensity units, while relative L2 is dimensionless. Use relative_valid to find pixels where the observed signal was strong enough for a relative error to be reported.

import matplotlib.pyplot as plt

from lumic.evaluation import reconstruction_error_maps, residual_pca_from_residuals

# observed and predicted are Y × X × C arrays on the same detector grid.
errors = reconstruction_error_maps(observed, predicted)
pca = residual_pca_from_residuals(errors.residuals, n_components=2)

fig, (ax_error, ax_scores, ax_loading) = plt.subplots(1, 3, figsize=(10, 3))
rms = ax_error.imshow(errors.rms)
ax_error.set_title("Residual RMS")
fig.colorbar(rms, ax=ax_error, label="Detector intensity")

pc1_scores = pca.scores[..., 0]
limit = abs(pc1_scores).max() or 1.0
scores = ax_scores.imshow(pc1_scores, cmap="RdBu_r", vmin=-limit, vmax=limit)
ax_scores.set_title(f"PC1 scores ({pca.explained_variance_ratio[0]:.1%})")
fig.colorbar(scores, ax=ax_scores, label="Detector intensity")

ax_loading.plot(pca.loadings[0])
ax_loading.axhline(0, color="gray", linewidth=1)
ax_loading.set(xlabel="Detector channel index", ylabel="PC1 loading")
fig.tight_layout()

errors.rms shows where the model leaves a large error. The score map shows where a particular residual pattern is strong, and the matching loading shows which channels make up that pattern. Plot the loading against wavelength coordinates when they are available. The percentage in the score panel describes the fraction of centered residual variance explained by PC1. Inspect other PCs as well.

A spatially coherent score map paired with a structured loading can suggest a missing component, especially if the pattern recurs in another acquisition. Background, detector artifacts, or a mismatched reference spectrum can also leave structured residuals. PCA loadings can have both signs and are directions of variation. Use the pattern to decide what to inspect or test in a follow-up fit.

PCA removes the mean before fitting. Inspect pca.mean_residual separately for a systematic channel offset. residual_neighbor_correlation() summarizes similarity between adjacent pixels in a 2D image, while residual_spectral_correlation() maps correlation between consecutive channels within each pixel. The same checks also work on simulated data, including noisy simulations. See the evaluation walkthrough for the plots and a controlled missing-component example.

reconstruction_error_maps(observed, reconstructed, *, min_signal=0.0)

Describe unexplained signal in real or simulated spectral images.

Parameters:

Name Type Description Default
observed (array - like, shape(..., channels))

Measured image and fitted prediction in identical intensity units. Pixels may be flattened or spatial; channels are always the last axis. For flattened factors, the prediction is C @ S. Signed finite data are allowed, including offset-corrected measurements.

required
reconstructed (array - like, shape(..., channels))

Measured image and fitted prediction in identical intensity units. Pixels may be flattened or spatial; channels are always the last axis. For flattened factors, the prediction is C @ S. Signed finite data are allowed, including offset-corrected measurements.

required
min_signal float

Minimum measured spectral L2 norm for reporting relative error, in input intensity units. Pixels at or below this threshold are masked.

0

Returns:

Type Description
ReconstructionErrorMaps

residuals = observed - reconstructed retains the input shape. Positive values identify underestimated signal, negative values overestimated signal. Inspect channels for wavelength-specific errors and spatial patterns such as missing background or omitted components. rms = sqrt(mean(residuals**2, axis=-1)) has the pixel shape and input intensity units; it locates the largest absolute mismatch. relative_l2 = norm(residuals) / norm(observed) is dimensionless and compares mismatch across brightness levels. It is NaN outside relative_valid; RMS remains available even for zero-signal pixels.

Limitations

No ground truth is required. These maps measure image fit, not correct identification of spectra or concentrations: different factors can yield the same image. They are not noise significance scores; bright regions can have larger RMS from shot noise alone, and relative errors at low signal need a scientifically appropriate threshold.

Examples:

>>> maps = reconstruction_error_maps([[3, 4]], [[0, 4]])
>>> maps.residuals.tolist()
[[3.0, 0.0]]
>>> maps.relative_l2.tolist()
[0.6]

ReconstructionErrorMaps dataclass

Channel residuals, pixel RMS, relative L2 error, and its validity mask.

residuals instance-attribute
rms instance-attribute
relative_l2 instance-attribute
relative_valid instance-attribute

residual_pca_from_residuals(residuals, *, n_components=6, spectral_axis=-1, batch_size=65536, return_scores=True)

Analyse precomputed SIGNED residuals; see residual_pca for full semantics.

Use when observed-minus-reconstructed residuals are already available. This avoids reconstructing or subtracting the images again. Use residual_pca when you instead have measured and reconstructed images, or residual_pca_from_factors when you have measured data and fitted C/S factors but have not allocated the reconstruction or residual cube. Do not pass absolute errors, squared errors or RMS maps: they have lost the spectral signs/shape this diagnostic needs. Layout, centring, result, memory options and interpretation limits match residual_pca.

ResidualPCAResult dataclass

Spectral directions and spatial amplitudes of unexplained variation.

mean_residual is a channel vector retained separately from centred PCA. loadings is (components, channels) with orthonormal rows. scores has the original spatial shape plus a final component axis, or is None when return_scores=False. Scores have signed detector-intensity units, not concentrations. explained_variance contains selected covariance eigenvalues (sample normalization, n_samples-1); eigenvalues includes all channel directions. Ratios use total centred variance, not residual RMS or original-image variance. covariance is (channels, channels).

Signs are fixed by making each loading's largest absolute entry positive. Signs remain a convention, and tied eigenvalues can rotate their bases. Independent results need not have corresponding PC numbers. Arrays are not made immutable by the frozen result container.

mean_residual instance-attribute
loadings instance-attribute
scores instance-attribute
explained_variance instance-attribute
explained_variance_ratio instance-attribute
eigenvalues instance-attribute
covariance instance-attribute
spatial_shape instance-attribute
n_samples instance-attribute

residual_neighbor_correlation(residuals, *, spectral_axis=-1, batch_size=65536)

Measure spatial structure in signed residuals from real or simulated images.

Parameters:

Name Type Description Default
residuals array, three axes

Observed minus reconstructed intensities, with two spatial axes and one spectral axis. Values must be finite; negative values are expected.

required
spectral_axis int

Channel axis; use 0 for a (channels, y, x) image.

-1
batch_size int

Maximum neighbor pairs processed together. No full pair array is built.

65536

Returns:

Type Description
float

Correlation in [-1, 1], pooling horizontal and vertical adjacent pairs, without diagonals or wrapping. Each endpoint population is centered separately per channel. The centered cross-product is divided by the product of endpoint norms, so channels with larger residual variance carry more weight. This is not a correlation of RMS maps. Returns NaN if there are no pairs or either endpoint has zero variance.

Notes

Positive values indicate neighboring pixels share signed spectral errors; negative values indicate alternation. Use alongside residual magnitude, mean bias and PCA maps to compare spatial structure across fits. Ground truth is unnecessary, but this is not a test for a missing fluorophore or statistical significance: PSF, detector noise and fitting can also induce correlations. Centering hides constant channel offsets. Near-zero residuals can have large correlations; callers choose a meaningful magnitude floor. Inputs are not modified. Moving a noncontiguous channel axis may copy data.

Examples:

>>> checker = 1 - 2 * (np.indices((4, 4)).sum(axis=0) % 2)
>>> residual_neighbor_correlation(checker[..., None])
-1.0

residual_spectral_correlation(residuals, *, spectral_axis=-1, batch_size=65536)

Map within-pixel structure across consecutive residual channels.

Accept finite signed observed-minus-reconstructed residuals with at least two axes. spectral_axis defaults to the last axis; use 0 for CZI images. Return an array with that axis removed, containing each pixel's Pearson correlation between residual[:-1] and residual[1:]. Each vector is centered separately. Values lie in [-1, 1]; undefined correlations are NaN, including constant endpoint vectors or fewer than three channels. batch_size is a positive integer limiting temporary pixel arrays (default 65536).

This works on real and simulated data without ground truth. Positive values highlight spectrally smooth errors; negative values highlight alternating errors. Inspect maps alongside signed mean residuals, RMS and residual PCA to locate potentially unexplained spectral structure. It does not identify a species, establish correct factors or supply a significance threshold. Short spectra give noisy estimates; wavelength gaps/order, detector processing and fitting-induced noise correlations affect values. Constant spectral offsets are removed by centering, and this scale-free diagnostic cannot distinguish tiny errors from large ones. No wavelength interpolation, noise correction or magnitude floor is applied. Inputs are not modified; moving a noncontiguous channel axis may copy data.

Examples:

>>> residual_spectral_correlation([[0., 1., 2., 3.]])
array([1.])

Compare component spectra

Use two (K, C) matrices with the same component count and detector channels in the same order. match_components() returns estimated row indices in reference order. Use those indices to reorder estimated spectra and their paired abundance columns together. compare_spectra() reports changes in spectral shape after removing scale differences. Use match=False when rows already correspond and you want to preserve that pairing. Agreement with a previous fit or a reference spectrum tells you about spectral similarity. It cannot validate the abundance maps.

match_components(true_spectra, estimated_spectra)

Return estimated row indices in true-component order and their costs.

Matching minimizes summed squared Euclidean distance between unit-L2 spectral shapes. The first argument can also be a previous fit or blind starting spectra; its historical name does not require ground truth. Matching gives a correspondence, not proof of biological identity. A zero estimated spectrum is allowed and has unit distance from every nonzero true spectrum; a zero true spectrum cannot define a spectral identity.

compare_spectra(reference_spectra, estimated_spectra, *, match=True)

Measure spectral shape and channel changes relative to a reference.

Purpose

Use across fitting pools, sampling seeds, initializations or solver versions to identify which recovered signatures change most. With known true spectra these are recovery errors; with another fit or blind starts they measure change only. This function works without known abundances or ground truth.

Parameters and returns

Both arrays must be finite, nonnegative, and have the same nonempty shape (components, channels). With match=True, reference rows must be nonzero and estimated rows are matched by total squared unit-L2 distance. With match=False, rows are compared in their supplied order, allowing zero references; use this after alignment to a common reference so that trajectories keep the same component IDs.

Returns SpectralComparison. shape_distance is the Euclidean distance between unit-L2 rows (0 for identical shapes; sqrt(2) for orthogonal nonzero nonnegative shapes). max_channel_change is the largest absolute change in each unit-sum row, a fraction of total channel signal; multiplying by 100 gives percentage points. max_channel_index identifies that channel (first on a tie). Pure scaling causes no change in either metric. A zero row remains zero under normalization; its shape distance from a nonzero row is 1, a convention for absent signal rather than a defined shape.

Interpretation and limits

A small change establishes stability relative to this reference, not correctness. No confidence interval, noise significance, identity, or convergence guarantee is inferred. Scale/intensity differences are removed deliberately; inspect abundances separately. Similar components may have ambiguous assignments, and missing/extra components are not supported.

Examples:

Reordering and scaling alone do not constitute spectral change:

>>> change = compare_spectra([[1, 0], [0, 1]], [[0, 2], [3, 0]])
>>> change.shape_distance.tolist()
[0.0, 0.0]
>>> change.max_channel_change.tolist()
[0.0, 0.0]

For an already aligned trajectory, preserve its component IDs:

>>> change = compare_spectra([[1, 0]], [[1, 1]], match=False)
>>> change.max_channel_change.tolist()
[0.5]

SpectralComparison dataclass

Per-component differences after optional spectral row matching.

shape_distance uses unit-L2 spectra; max_channel_change and max_channel_index use unit-sum spectra. component_order indexes the original estimated rows. matching_costs are unit-L2 distances for the chosen pairing, even when row order is supplied directly.

component_order instance-attribute
matching_costs instance-attribute
shape_distance instance-attribute
max_channel_change instance-attribute
max_channel_index instance-attribute

Simulated images: measure recovery against known truth

A simulation provides the component spectra and abundance maps that generated the clean detector signal. Keep those factors when adding noise so you can compare the fit against known truth. These recovery functions also apply to an experimental validation dataset if it supplies independent ground truth for both quantities.

evaluate_factors() summarizes recovery from flattened observations (N, C), abundance matrices (N, K), and spectra (K, C). concentration_error_maps() also accepts spatial abundance maps with components last. It returns signed and absolute errors in true component order and masks relative errors where the reference concentration is too small.

Both functions match estimated components to the reference shapes, then put spectra on a unit-sum scale and transfer the removed scale to their paired abundances. This preserves the predicted detector signal while making abundances comparable. For a detector image in count units, the aligned abundance scale is total detector counts per component. See Evaluate simulation recovery.

evaluate_factors(observed, true_abundances, true_spectra, estimated_abundances, estimated_spectra)

Measure image fit and factor recovery after scale and order alignment.

Inputs have shapes (pixels, channels), (pixels, components), and (components, channels). Relative abundance error is NaN for a true component with zero abundance; its count RMSE remains defined.

FactorEvaluation dataclass

Matched factors and errors for one fitted spectral image.

component_order instance-attribute

matching_costs instance-attribute

estimated_abundances instance-attribute

estimated_spectra instance-attribute

reconstruction_relative_l2 instance-attribute

spectral_relative_l2_per_component instance-attribute

spectral_relative_l2_global instance-attribute

max_channel_absolute instance-attribute

max_error_component_index instance-attribute

max_error_channel_index instance-attribute

abundance_rmse_per_component instance-attribute

abundance_rmse_global instance-attribute

abundance_relative_l2_per_component instance-attribute

abundance_relative_l2_global instance-attribute

concentration_error_maps(true_abundances, true_spectra, estimated_abundances, estimated_spectra, *, min_concentration=0.0)

Compare recovered concentrations with known truth after factor alignment.

Parameters:

Name Type Description Default
true_abundances (array - like, shape(..., components))

Nonnegative concentration maps with identical shapes and components on the last axis. Flattened pixel matrices are also accepted.

required
estimated_abundances (array - like, shape(..., components))

Nonnegative concentration maps with identical shapes and components on the last axis. Flattened pixel matrices are also accepted.

required
true_spectra (array - like, shape(components, channels))

Paired nonnegative spectra. True spectra must be nonzero. Components are matched using the same unit-L2 spectral assignment as evaluate_factors. Both sets of spectra are normalized to unit sum and their removed scales transferred to their paired abundances.

required
estimated_spectra (array - like, shape(components, channels))

Paired nonnegative spectra. True spectra must be nonzero. Components are matched using the same unit-L2 spectral assignment as evaluate_factors. Both sets of spectra are normalized to unit sum and their removed scales transferred to their paired abundances.

required
min_concentration float

Report relative error only where canonical true concentration is strictly greater than this nonnegative threshold.

0

Returns:

Type Description
ConcentrationErrorMaps

Maps retain the abundance shape in true-component order. signed = aligned_estimate - canonical_truth reveals overestimation (positive), underestimation (negative), and possible component leakage. absolute = abs(signed) locates recovery errors, including false positives where truth is zero. Both are in unit-sum-spectrum abundance units: total detector-channel counts when the image uses count units. relative = signed / canonical_truth is a dimensionless fractional error; multiply by 100 for percent. It is NaN outside relative_valid. component_order records the estimated indices selected by matching.

Limitations

Requires known ground-truth concentrations and spectra, normally from a simulation or independent validation. It cannot establish recovery accuracy on ordinary real images without those references. Matching compares the supplied components; it does not prove their identities or compensate for missing/extra components. Relative error is undefined for absent truth; inspect absolute errors there rather than treating masked pixels as zero. These maps are not uncertainty estimates or noise significance scores.

Examples:

>>> maps = concentration_error_maps([[2, 0]], [[1, 0], [0, 1]],
...                                 [[3, 1]], [[1, 0], [0, 1]])
>>> maps.signed.tolist()
[[1.0, 1.0]]
>>> maps.relative_valid.tolist()
[[True, False]]

ConcentrationErrorMaps dataclass

Aligned concentration errors and estimated indices in true order.

signed instance-attribute

absolute instance-attribute

relative instance-attribute

relative_valid instance-attribute

component_order instance-attribute