Skip to content

Spatial deconvolution and reference checks

A spatial spot can contain several cell populations. Deconvolution compares its expression with reference profiles and estimates how much each profile contributes. The units matter: a population that contributes half the RNA need not account for half the cells.

This Python lesson fits nonnegative least squares to public mouse lymph node counts from the DestVI study. It first tests the fit on mixtures of cells from separate libraries, where the cell counts and captured RNA contributions are known. It then applies the same reference to measured tissue spots and plots their original coordinates. The model here is a transparent linear baseline; it does not run DestVI or model continuous states within a cell population.

Keep counts, libraries, and coordinates together

Section titled “Keep counts, libraries, and coordinates together”

Download the input archive and extract its files into inputs/. The archive contains sparse integer count matrices, cell metadata, spot metadata, shared gene names, and a source manifest. The preparation script records every extraction step and the two original file checksums.

The original matrices come from the scvi-tools lymph node tutorial. They represent the study’s mycobacterial stimulation and PBS conditions. The cell archive includes four library batches; these identifiers alone do not establish independent animals. The spatial archive contains three lymph nodes, MS-1, MS-2, and PBS. This is a separate specimen set from the mouse brain Visium example elsewhere in this section.

The extracted reference excludes cells flagged as doublets and retains at most 250 cells per broad family and library. B cells form one family; CD4, CD8, regulatory, and gamma delta T cells form another. Dendritic cells, macrophages, and monocytes form the myeloid family. NK cells remain separate. The counts retain their measured library sizes and use the genes present in both archives.

from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import nnls
from scipy.sparse import load_npz
output = Path("outputs")
output.mkdir(exist_ok=True)
cells = pd.read_csv("inputs/reference_cells.csv", index_col=0)
spots = pd.read_csv("inputs/spatial_spots.csv", index_col=0)
genes = pd.read_csv("inputs/genes.csv")["gene"].to_numpy()
counts = load_npz("inputs/reference_counts.npz")
tissue_counts = load_npz("inputs/spatial_counts.npz")
families = ["B", "T", "Myeloid", "NK"]
assert counts.shape == (len(cells), len(genes))
assert tissue_counts.shape == (len(spots), len(genes))
assert cells.index.is_unique and spots.index.is_unique
assert counts.min() >= 0 and tissue_counts.min() >= 0
library_size = np.asarray(counts.sum(axis=1)).ravel()
reference = cells["batch"].isin([0, 2]).to_numpy()
held_out = cells["batch"].isin([1, 3]).to_numpy()
assert np.all(reference != held_out)
print(f"Cells: {len(cells)}; shared genes: {len(genes)}")
print(f"Reference cells: {reference.sum()}; held-out cells: {held_out.sum()}")
print(spots["lymph_node"].value_counts().sort_index().to_string())
Cells: 2819; shared genes: 11757
Reference cells: 1443; held-out cells: 1376
lymph_node
MS-1 400
MS-2 323
PBS 369

A reference column is the pooled UMI count for a family, divided by that family’s total UMIs across all shared genes. Each column therefore sums to one. A mixture of these columns describes captured RNA contributions on this gene set, conditional on the reference profiles and comparable capture efficiency. It does not directly describe cell fractions or absolute RNA mass.

Feature selection also uses reference cells only. For each family, select the 40 genes with the highest expression ratio against the strongest other family, subject to a minimum abundance. Exclude mitochondrial and ribosomal genes from this selected panel. All shared genes still contribute to each library total. The four profiles must be linearly independent on the selected genes.

profiles = []
mean_sizes = []
reference_numbers = []
for family in families:
selected = reference & (cells["family"].to_numpy() == family)
pooled = np.asarray(counts[selected].sum(axis=0)).ravel()
profiles.append(pooled / pooled.sum())
mean_sizes.append(library_size[selected].mean())
reference_numbers.append(selected.sum())
signature = np.column_stack(profiles)
mean_sizes = np.array(mean_sizes)
assert np.allclose(signature.sum(axis=0), 1)
panel = set()
allowed = ~pd.Series(genes).str.match(r"^(mt-|Rpl|Rps)").to_numpy()
for column in range(len(families)):
others = np.delete(signature, column, axis=1).max(axis=1)
score = signature[:, column] / (others + 1e-6)
eligible = allowed & (signature[:, column] >= 1e-4)
positions = np.flatnonzero(eligible)
panel.update(positions[np.argsort(score[positions])[-40:]])
panel = np.array(sorted(panel))
design = signature[panel]
assert np.linalg.matrix_rank(design) == len(families)
reference_summary = pd.DataFrame({
"family": families, "cells": reference_numbers,
"mean_shared_gene_umis": mean_sizes,
})
reference_summary.to_csv(output / "reference_summary.csv", index=False)
pd.DataFrame(design, index=genes[panel], columns=families).to_csv(
output / "reference_signatures.csv", index_label="gene"
)
print(reference_summary.round(1).to_string(index=False))
print(f"Selected genes: {len(panel)}")
family cells mean_shared_gene_umis
B 500 5339.4
T 500 7725.8
Myeloid 404 10379.9
NK 39 8027.6
Selected genes: 160

Only 39 reference cells supply the NK profile. Their limited representation can make this profile sensitive to the sampled cells and their states.

The mean library sizes provide a possible conversion from RNA contributions to cell fractions. They combine biology with capture efficiency and sequencing depth. The conversion assumes these family-specific means transfer to the mixture; the validation below tests that assumption for the held-out libraries. It cannot establish the same relationship in tissue.

Each pseudospot contains 20 measured cells from one held-out library. The composition varies across spots. Compositions that exceed a library’s available family pool are redrawn. Each selected cell contributes its original integer counts. A high-count cell therefore contributes more captured RNA than a low-count cell. Do not normalize individual cells before adding their counts.

Reference libraries never supply mixture cells. Cells can recur in different mixtures, so the mixtures are not independent biological replicates. Their purpose is to measure recovery error, not to test a treatment effect. This exercise also leaves the difference between dissociated cells and tissue capture untested.

rng = np.random.default_rng(20261114)
mixtures = []
cell_truth = []
rna_truth = []
membership = []
for mixture_id in range(160):
batch = [1, 3][mixture_id % 2]
proportions = rng.dirichlet(np.ones(len(families)))
pool_sizes = cells.loc[cells["batch"] == batch, "family"]
pool_sizes = pool_sizes.value_counts().reindex(families).to_numpy()
numbers = rng.multinomial(20, proportions)
while np.any(numbers > pool_sizes):
proportions = rng.dirichlet(np.ones(len(families)))
numbers = rng.multinomial(20, proportions)
selected_cells = []
family_rna = []
for family, number in zip(families, numbers):
pool = np.flatnonzero(
held_out & (cells["batch"].to_numpy() == batch)
& (cells["family"].to_numpy() == family)
)
chosen = rng.choice(pool, number, replace=False)
selected_cells.extend(chosen)
family_rna.append(library_size[chosen].sum())
for cell_position in chosen:
membership.append({
"mixture": mixture_id, "cell_id": cells.index[cell_position],
"family": family, "batch": batch,
})
mixtures.append(np.asarray(counts[selected_cells].sum(axis=0)).ravel())
cell_truth.append(numbers / numbers.sum())
rna_truth.append(np.array(family_rna) / np.sum(family_rna))
mixtures = np.array(mixtures)
cell_truth = np.array(cell_truth)
rna_truth = np.array(rna_truth)
pd.DataFrame(membership).to_csv(output / "mixture_membership.csv", index=False)
print(f"Mixtures: {len(mixtures)}; cells in each mixture: 20")
overlap = int((reference & held_out).sum())
print(f"Reference and mixture cells overlap: {overlap}")
Mixtures: 160; cells in each mixture: 20
Reference and mixture cells overlap: 0

Fit nonnegative contributions and check their units

Section titled “Fit nonnegative contributions and check their units”

For each spot, divide its selected-gene counts by its total across all shared genes. SciPy then minimizes the squared difference between this vector and a nonnegative combination of the reference columns. NNLS constrains coefficients to be nonnegative but does not require their sum to equal one. We retain that sum and the original fit residual, then normalize coefficients for display.

The residual below is the Euclidean error divided by the observed vector’s Euclidean norm, on the selected genes. A low residual describes agreement with these profiles on this panel. It does not prove that every population is present in the reference.

def fit_mixtures(matrix, basis, feature_positions):
"""Fit nonnegative RNA contributions to count rows.
Args:
matrix: Dense or sparse nonnegative counts for all shared genes.
basis: Selected gene by family reference matrix.
feature_positions: Positions of the selected genes in matrix.
Returns:
Normalized contributions, relative residuals, and coefficient sums.
Raises:
ValueError: A count row or its fitted contribution has zero total.
"""
contributions = []
residuals = []
totals = []
for row in matrix:
values = row.toarray().ravel() if hasattr(row, "toarray") else row
if values.sum() <= 0:
raise ValueError("A spot has zero shared-gene counts.")
target = values[feature_positions] / values.sum()
coefficients, residual = nnls(basis, target)
if coefficients.sum() <= 0 or np.linalg.norm(target) <= 0:
raise ValueError("A spot has no fitted contribution.")
contributions.append(coefficients / coefficients.sum())
residuals.append(residual / np.linalg.norm(target))
totals.append(coefficients.sum())
return np.array(contributions), np.array(residuals), np.array(totals)
rna_estimate, residual, coefficient_sum = fit_mixtures(
mixtures, design, panel
)
calibrated = rna_estimate / mean_sizes
calibrated = calibrated / calibrated.sum(axis=1, keepdims=True)
errors = pd.DataFrame({
"family": families,
"rna_mae": np.mean(np.abs(rna_estimate - rna_truth), axis=0),
"uncalibrated_cell_mae": np.mean(np.abs(rna_estimate - cell_truth), axis=0),
"calibrated_cell_mae": np.mean(np.abs(calibrated - cell_truth), axis=0),
})
errors.to_csv(output / "recovery_errors.csv", index=False)
print(errors.round(3).to_string(index=False))
print(f"Median relative residual: {np.median(residual):.3f}")
family rna_mae uncalibrated_cell_mae calibrated_cell_mae
B 0.054 0.087 0.067
T 0.086 0.095 0.088
Myeloid 0.124 0.147 0.129
NK 0.071 0.075 0.076
Median relative residual: 0.327

The first error column compares estimated and known captured RNA contributions. The second makes the common mistake of interpreting RNA weights as cell fractions. The third divides weights by reference mean library sizes before normalization. Calibration reduces cell-fraction error for B, T, and myeloid cells in this example, but slightly increases it for NK cells. Mean library sizes do not remove expression differences or count variation between individual cells.

Remove the myeloid column while keeping the same selected genes. This isolates the effect of an absent population from a change in feature selection. The fit must assign its signal to the remaining profiles or leave it in the residual. A missing column cannot receive a nonzero estimated contribution.

retained = [0, 1, 3]
reduced, reduced_residual, _ = fit_mixtures(
mixtures, design[:, retained], panel
)
missing_estimate = np.zeros_like(rna_estimate)
missing_estimate[:, retained] = reduced
mismatch = pd.DataFrame({
"reference": ["complete", "myeloid omitted"],
"mean_rna_absolute_error": [
np.mean(np.abs(rna_estimate - rna_truth)),
np.mean(np.abs(missing_estimate - rna_truth)),
],
"median_relative_residual": [
np.median(residual), np.median(reduced_residual),
],
})
mismatch.to_csv(output / "reference_mismatch.csv", index=False)
records = []
for column, family in enumerate(families):
for row in range(len(mixtures)):
records.append({
"mixture": row, "family": family,
"true_rna": rna_truth[row, column],
"estimated_rna": rna_estimate[row, column],
"true_cells": cell_truth[row, column],
"calibrated_cells": calibrated[row, column],
"missing_reference_rna": missing_estimate[row, column],
})
pd.DataFrame(records).to_csv(output / "mixture_recovery.csv", index=False)
figure, axes = plt.subplots(2, 2, figsize=(9, 8), layout="constrained")
for column, axis in enumerate(axes.flat):
axis.scatter(rna_truth[:, column], rna_estimate[:, column],
s=15, alpha=0.55, label="Complete reference")
axis.scatter(rna_truth[:, column], missing_estimate[:, column],
s=12, alpha=0.4, label="Myeloid omitted")
axis.plot([0, 1], [0, 1], color="black", linewidth=1)
axis.set(xlim=(0, 1), ylim=(0, 1), title=families[column],
xlabel="Known captured RNA fraction",
ylabel="Estimated RNA contribution")
axes[0, 0].legend(fontsize=8)
figure.savefig(output / "deconvolution_validation.png", dpi=180)
plt.close(figure)
print(mismatch.round(3).to_string(index=False))
reference mean_rna_absolute_error median_relative_residual
complete 0.084 0.327
myeloid omitted 0.191 0.576

Known and estimated captured RNA contributions differ by family and reference completeness.

The mixture results include the known and estimated contributions for every mixture.

Removing myeloid profiles raises the mean absolute RNA error from 0.084 to 0.191. The scatterplots show where the missing contribution moves into other families.

These mixtures test the supplied immune populations on separate libraries. They do not contain stromal or endothelial cells, which this reference lacks. A real spot with either population can receive misleading immune contributions, even when the four reported weights add to one. Inspect tissue markers and histology before deciding whether a reference covers a new specimen.

Apply the same reference to real tissue coordinates

Section titled “Apply the same reference to real tissue coordinates”

Use the same profiles and selected genes for the measured spots. Plot each lymph node separately because its pixel coordinates belong to its own image. The first figure shows the four estimated RNA contributions in MS-1. The second compares selected-gene residuals across the three lymph nodes on one color scale. Neither figure supplies independently measured cell fractions.

tissue_rna, tissue_residual, tissue_sum = fit_mixtures(
tissue_counts, design, panel
)
for column, family in enumerate(families):
spots[f"{family}_rna"] = tissue_rna[:, column]
spots["relative_residual"] = tissue_residual
spots["coefficient_sum"] = tissue_sum
spots.to_csv(output / "tissue_rna_contributions.csv", index_label="spot_id")
node = spots.loc[spots["lymph_node"] == "MS-1"]
figure, axes = plt.subplots(2, 2, figsize=(9, 8), layout="constrained")
for family, axis in zip(families, axes.flat):
plotted = axis.scatter(node["pixel_x"], node["pixel_y"],
c=node[f"{family}_rna"], s=24,
cmap="viridis", vmin=0, vmax=1)
axis.set(title=f"MS-1: {family}", xlabel="Image x pixel",
ylabel="Image y pixel", aspect="equal")
axis.invert_yaxis()
figure.colorbar(plotted, ax=axes.ravel().tolist(), shrink=0.6,
label="Reference-conditional RNA contribution")
figure.savefig(output / "deconvolution_tissue.png", dpi=180)
plt.close(figure)
figure, axes = plt.subplots(1, 3, figsize=(12, 4), layout="constrained")
for name, axis in zip(["MS-1", "MS-2", "PBS"], axes):
node = spots.loc[spots["lymph_node"] == name]
plotted = axis.scatter(node["pixel_x"], node["pixel_y"],
c=node["relative_residual"], s=14,
cmap="magma", vmin=0, vmax=1)
axis.set(title=name, xlabel="Image x pixel", ylabel="Image y pixel",
aspect="equal")
axis.invert_yaxis()
figure.colorbar(plotted, ax=axes.tolist(), shrink=0.7,
label="Selected-gene relative residual")
figure.savefig(output / "deconvolution_residuals.png", dpi=180)
plt.close(figure)
print(spots.groupby("lymph_node")[["relative_residual", "coefficient_sum"]]
.median().round(3).to_string())
relative_residual coefficient_sum
lymph_node
MS-1 0.555 1.167
MS-2 0.545 1.107
PBS 0.519 1.185

Four reference-conditional RNA contributions use the measured coordinates of the MS-1 lymph node.

Selected-gene fit residuals use a shared color scale across the three lymph node sections.

The tissue results retain every spot identifier, original coordinate, RNA contribution, and fit diagnostic for inspection with other tissue measurements.

The tissue median residuals exceed the pseudospot median. The measured tissue therefore fits these profiles less closely than the constructed mixtures. An estimated zero for NK contribution does not establish that NK cells are absent.

A high residual can reflect an absent population, a cell state missing from the reference, or a technology difference. It does not identify which explanation is correct. This fit has no spatial smoothing, so neighboring spots remain separate observations and the coordinates do not determine their estimates.

For another experiment, align species, gene identifiers, tissue, condition, and count scale before the fit. Include reference populations expected in the tissue and retain donor or library identifiers for validation. Preserve a matching spot-to-coordinate table, then examine independent marker staining or known anatomical regions. Those measurements address tissue validity; mixtures of dissociated cells cannot replace them.

Lopez and colleagues, 2022 describe DestVI and provide the lymph node reference and spatial measurements used here.

Lawson and Hanson, 1995 describe least squares methods, including the nonnegative solver used for this linear mixture model.

Virtanen and colleagues, 2020 describe SciPy 1.0 and its fundamental algorithms for scientific computing in Python.

The SciPy NNLS documentation states the nonnegative least squares objective and the returned residual. It helps distinguish this constraint from a requirement that coefficients sum to one.

The DestVI tutorial provides the two source matrices and demonstrates a model that allows continuous expression states. Use it to examine the additional assumptions beyond this linear baseline.

The study’s GEO record provides the experiment and sequencing records. Consult those records before treating library identifiers as animal identifiers or comparing experimental conditions.