Unmix a real experimental image (COS-7)
Use this notebook to unmix a spectral confocal image from the public COS-7 dataset. First fit the image with spectra selected from individual pixels. Then estimate starting spectra from the convex hull, refine them with MCR-ALS, and inspect the resulting abundance maps and reconstruction error.
Run your first notebook
- Download the notebook. Save
minimal_example.ipynbin a folder where you also want the output TIFFs. -
Create a Python 3.12 environment. If you don't already have Conda, install Miniforge, the conda-forge installer. Open a new terminal on macOS or Linux, or Miniforge Prompt on Windows. Use
cdto go to the folder containing the notebook, then run these commands one at a time.conda create -n lumic-notebooks -c conda-forge python=3.12 pip conda activate lumic-notebooks -
Install Lumic and start JupyterLab. The
examplesextra includes JupyterLab and the notebook dependencies. Run both commands in the same terminal withlumic-notebooksactive.python -m pip install "lumic[examples]==0.1.0" jupyter lab -
Open and run the notebook. JupyterLab opens in your browser. Double-click
minimal_example.ipynbin the file browser on the left. If asked to choose a kernel, select Python 3 (ipykernel) from this environment. The kernel is the Python process that runs the notebook. Select the first cell and press Shift + Enter to run it and move to the next, or use Run → Run All Cells to run the notebook from top to bottom.
The first run downloads the high-SNR mixed CZI (about 145 MB), and later runs
reuse it. To use your own acquisition, change IMAGE_PATH and choose reference
pixels for that image.
BioImage Archive S-BIAD4448

The detector preview groups the measured channels into RGB. The fitted overlay shows three selected abundance maps from the four-component blind fit. The error map shows the mean squared residual per pixel. Its display scale ends at the 99th percentile so the brightest pixels do not obscure smaller errors. See Evaluate experimental data for ways to investigate these residuals.
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
import lumic
import skimage
Load one spectral image
In the Python 3.12 environment used by your Jupyter kernel, install Lumic and
the notebook dependencies with python -m pip install "lumic[examples]==0.1.0".
By default it downloads the high-SNR mixed COS-7 acquisition (about 145 MB) from
BioImage Archive S-BIAD4448.
Later runs reuse the local copy. The manual reference pixels below correspond
to this acquisition. To use your own data, set IMAGE_PATH in the next input
cell and choose new reference pixels in the RGB preview.
open_image inspects either CZI or OME-TIFF headers without decoding pixels.
Run the summary cell first, then the loading cell when ready. load_image
returns a SpectralImage; its default t=0, z=0 selects one plane, including
when those axes are absent. Both delegate to the existing format-specific
readers.
Why CYX here? This example currently inspects one two-dimensional plane:
RGB rendering now respects image axes, but manual reference spectra are picked
with mixData[:, y, x], and component plots expect KYX maps. The current
select_analysis_pixels helper also accepts a three-dimensional image.
These are notebook/helper limitations, not restrictions of SpectralImage,
UnfoldedImage or the numerical solvers. Those support other axis orders and
retained T/Z dimensions. A later update can separate a chosen display plane
from the full data used for fitting. image.slice(t=..., z=...) now copies a
selected plane and image.to_rgb() handles channel-image axis orders; the
remaining manual selection and analysis-pixel helper still need adaptation.
For now, select one T/Z plane and use CYX here.
The numerical functions continue receiving NumPy matrices.
from lumic.data import download_cos7_data
from lumic.io import open_image, load_image
# Leave IMAGE_PATH as None for the public COS-7 example.
IMAGE_PATH = None # Or set it to the path of your CZI or OME-TIFF.
TIME_POINT = 0
Z_SLICE = 0
if IMAGE_PATH is None:
pth, = download_cos7_data(snr="high", progress=True)
else:
pth = Path(IMAGE_PATH).expanduser()
print(f"Input image: {pth}")
Inspect before loading pixels
This cell reports the available image layout and detector metadata. It does not read pixels. A channel count does not establish the number of fluorophores; header support does not validate spectral interpretation or every pixel block.
with open_image(pth) as reader:
print(reader.summary())
Load the selected plane when ready
This is the first pixel-loading step. load_image selects the appropriate
reader, reads the requested T/Z plane and closes the file. The remaining
analysis receives the same SpectralImage/NumPy data as before.
image = load_image(pth, t=TIME_POINT, z=Z_SLICE)
if image.axes != "CYX":
raise ValueError(
f"This notebook's manual pixel selection and component plots currently require CYX; "
f"loaded {image.axes}. Select one T/Z plane. The numerical API supports other layouts."
)
# Keep the familiar NumPy alias for RGB rendering and manual pixel selection.
mixData = image.data
wave = image.wavelengths_nm
spectral_axis_label = "Wavelength (nm)"
if wave is None:
# Wavelengths are optional: use channel indices for plots when unavailable.
# This does not establish physical compatibility with external references.
wave = np.arange(mixData.shape[0])
spectral_axis_label = "Detector channel index"
print(f"Loaded {image.axes}, shape={image.data.shape}, kind={image.kind}")
Choose reference pixels in the RGB preview
The marked pixels provide three reference spectra, named by their preview colors. The collection stores their pixel coordinates, the source plane, and any wavelength coordinates and detector bands reported by the image. You can save the reference set as JSON and reload it for images acquired with the same detector channels in the same order.
rendering = image.to_rgb() # Channel-order preview; no component separation.
RGB_im = rendering.data # YXS: RGB samples last.
# Reference pixels selected by hand in the high-SNR COS-7 image (x, y).
reference_pixels = {
"blue": (1053, 897),
"green": (1074, 530),
"red": (228, 252),
}
plt.figure(figsize=(5, 5))
plt.title("RGB rendering of spec data")
plt.imshow(RGB_im)
plt.axis("off")
for color, (x, y) in reference_pixels.items():
plt.scatter(x, y, color=color, edgecolor="white")
# Each row is one reference spectrum, normalized to unit sum.
pixel_spectra = np.asarray([mixData[:, y, x] for x, y in reference_pixels.values()])
references = lumic.SpectrumCollection(
pixel_spectra / pixel_spectra.sum(axis=1, keepdims=True),
wavelengths_nm=image.wavelengths_nm,
detection_bands_nm=image.detection_bands_nm,
names=[f"{color} reference" for color in reference_pixels],
row_provenance=[{"x": x, "y": y} for x, y in reference_pixels.values()],
provenance={
"source_image": str(pth),
"time_point": TIME_POINT,
"z_slice": Z_SLICE,
"method": "manual pixel selection",
"normalization": "L1",
},
)
# Optional: save and reload the references before fitting.
# references.save_json("manual_references.json")
# references = lumic.SpectrumCollection.load_json("manual_references.json")
plt.figure(figsize=(8, 5))
plt.xlabel(spectral_axis_label)
plt.ylabel("Intensity")
plt.title("Reference spectra selected by hand")
for color, name, spectrum in zip(reference_pixels, references.names, references.values):
plt.plot(wave, spectrum, color=color, linestyle="solid", marker="o",
markerfacecolor="black", markersize=5, label=name)
plt.legend()
Spectral unmixing using non-negative constrains
from multiprocess import Pool
from functools import partial
# Unfold once: keep the layout object and pass only its matrix to solvers.
unfolded = image.unfold()
fData = unfolded.data
# Choose the sequential or parallel implementation.
go_slow = False
if go_slow:
fAbundance = lumic.positive_least_squares(mixed_data=fData,
components=references.values,
do_norm = "L1",
batch_size = 500,
verbose=True,
solver="auto")
else:
# Multi proc version of code for speed
nPools = 4
with Pool(nPools) as P:
ans = P.map(partial(lumic.positive_least_squares, components=references.values,
do_norm = "L1",
batch_size = 500,
verbose=False,
solver="auto",
),
np.array_split(fData,nPools))
fAbundance = np.vstack(ans)
manual_abundance_image = unfolded.fold_abundances(
fAbundance, component_names=references.names
)
abundance_maps = manual_abundance_image.data # KYX array for existing plots.
print(f"shape of abundance maps is: {abundance_maps.shape}")
from lumic.utils import norm8bit
IMmanual = np.zeros(abundance_maps.shape, dtype=np.uint8)
for idx in range(IMmanual.shape[0]):
IMmanual[idx,:,:] = norm8bit(abundance_maps[idx,:,:].squeeze())
plt.figure(figsize=(20, 10))
for idx in range(IMmanual.shape[0]):
ax = plt.subplot(1,IMmanual.shape[0],idx+1)
ax.set_title(f"abundance {idx}")
ax.imshow(IMmanual[idx,:,:].squeeze())
ax.axis('off')
RGB = np.dstack([IMmanual[2,:,:].squeeze(),
IMmanual[1,:,:].squeeze(),
IMmanual[0,:,:].squeeze()])
plt.figure(figsize=(10, 10))
plt.imshow(RGB)
plt.axis('off')
plt.title('manual')
convex hull to find most unique spectra
from lumic.utils import select_analysis_pixels
# User setting: discard pixels below this quantile of median channel intensity.
MEDIAN_INTENSITY_QUANTILE = 0.2
# Keep the original image unchanged; select rows only for the fitting pool.
# The helper also excludes nonfinite, negative and all-zero spectra.
retained = select_analysis_pixels(
image.data,
median_quantile=MEDIAN_INTENSITY_QUANTILE,
spectral_axis=image.axes.index("C"),
)
fData = unfolded.data # Full observation matrix remains available for unmixing.
subSet = fData[retained.indices] # Indices refer to the original unfolded rows.
print(f"Retained {len(retained.indices):,} of {len(fData):,} pixels for hull selection")
print(f"Median intensity threshold: {retained.median_threshold}")
print(f"Excluded pixels by reason: {retained.exclusion_counts}")
if len(retained.indices) == 0:
raise ValueError("No usable pixels remain for convex-hull selection; check the data and threshold.")
# 3 to 3
# careful here do not ask for large number of components, it breaks at the moment I must check convex hull options
princ_comp = 4
xReduced, hullIDX = lumic.essential_spectral_pixles(subSet, npc=princ_comp)
# hullIDX indexes subSet; map back to the full image's unfolded row indices.
hull_pixel_indices = retained.indices[hullIDX]
print(f"after convexhull with npc={princ_comp} the data is {xReduced.shape}")
nComponents = princ_comp
simSpec, _ = lumic.unique_profiles(xReduced.T, nComponents, 0.5)
for idx in range(simSpec.shape[0]):
plt.plot(wave,(simSpec[idx,:]/np.max(simSpec[idx,:]))+idx*1)
optimizing the spectra via mcr als
C, S, R, diagnostics = lumic.mcr_als(xReduced, simSpec, nIter = 500, normL="L2", tol_percent=0.01, return_diagnostics=True)
print(diagnostics)
#d = np.dot(C,S)
plt.figure(1)
plt.subplot(211)
plt.plot(R[:])
#ax = plt.gca()
#ax.set_xlim(2, 30)
plt.subplot(212)
for idx in range(S.shape[0]):
plt.plot(wave,(S[idx,:]/np.max(S[idx,:]))+idx*1)
plt.plot(wave,(simSpec[idx,:]/np.max(simSpec[idx,:]))+idx*1,'--')
# Multi proc version of code for speed
fData = unfolded.data
# L1 spectra make abundance values comparable as integrated channel contributions.
# Reuse these exact spectra for reconstruction; ALS returned S on an L2 scale.
fit_spectra = lumic.normalize_components(S, do_norm="L1")
nPools = 4
with Pool(nPools) as P:
ans = P.map(partial(lumic.positive_least_squares, components=fit_spectra,
do_norm = False,
batch_size = 500,
verbose=False,
solver="auto",
),
np.array_split(fData,nPools))
fAbOpt = np.vstack(ans)
optimized_abundance_image = unfolded.fold_abundances(fAbOpt)
ab_maps_opt = optimized_abundance_image.data # KYX; C was replaced with K.
print(f"shape of abundance maps is: {ab_maps_opt.shape}")
IM = np.zeros((S.shape[0],mixData.shape[1],mixData.shape[2]),dtype=np.uint8)
for idx in range(IM.shape[0]):
tmp_im = norm8bit(ab_maps_opt[idx,:,:].squeeze())
IM[idx,:,:] = tmp_im
skimage.io.imsave(f'basic_unmix_c{idx}.tif', tmp_im)
plt.figure(figsize=(20, 10))
for idx in range(IM.shape[0]):
ax = plt.subplot(1,IM.shape[0],idx+1)
ax.set_title(f"abundance {idx}")
ax.imshow(IM[idx,:,:].squeeze())
ax.axis('off')
from lumic.evaluation import reconstruction_error_maps
# Predict the detector signal with the same spectra used for the abundance fit.
predicted_signal = fAbOpt @ fit_spectra
reconstruction = unfolded.fold_spectra(predicted_signal)
# The diagnostic expects channels last; the reader returned CYX.
observed_yxc = np.moveaxis(image.data, 0, -1)
predicted_yxc = np.moveaxis(reconstruction.data, 0, -1)
errors = reconstruction_error_maps(observed_yxc, predicted_yxc)
# Preserve the existing MSE display/export (squared intensity units).
# A residual map is a diagnostic, not a component abundance image.
err_map = (errors.rms ** 2)[np.newaxis, ...] # (1, Y, X)
plt.figure(figsize=(10, 10))
plt.imshow(err_map[0])
plt.axis('off')
plt.title('Reconstruction error (mean squared residual)')
RGB = np.dstack([IM[0,:,:].squeeze(),
IM[3,:,:].squeeze(),
IM[2,:,:].squeeze()])
plt.figure(figsize=(10, 10))
plt.imshow(RGB)
plt.axis('off')
plt.title('opt')
skimage.io.imsave('basic_unmix.tif', RGB)
skimage.io.imsave('basic_error.tif', err_map)
plt.figure(figsize=(10, 10))
plt.imshow(IM[1,:,:].squeeze())
plt.axis('off')
plt.title('opt')