Read quality in tissue context
A low-count spot can cover damaged tissue, a sparse anatomical region, or only the edge of the section. The count distribution cannot distinguish those explanations by itself. Quality review therefore starts with the image and maps each measurement back to its position before removing observations. All measurements here belong to one section from one mouse.
The main analysis retains every valid provider-selected tissue spot. Missing coordinates, duplicate identifiers, invalid counts, or zero totals stop the example because they break the calculation. Distribution tails receive review flags, but those flags do not become exclusions. This rule is fixed before expression clusters or spatial statistics are calculated.
Use a declared denominator
Section titled “Use a declared denominator”The mitochondrial fraction divides counts from genes whose stored mouse symbol
starts with mt- by all UMI counts in that spot. The exported table preserves
each mitochondrial feature identifier. This is a fraction of captured counts,
not the fraction of mitochondria or a direct estimate of cell viability.
The diagnostic flags use the lowest one percent of spot totals, the lowest one percent of detected-gene counts, and the highest one percent of mitochondrial fractions. Both languages use linear quantiles. These are review aids for this section, not universal acceptance thresholds.
source("/shared/spatial_utils.R")data <- ReadSection()counts <- data$countstotals <- colSums(counts)detected <- colSums(counts > 0)mitochondrial <- startsWith(data$features$symbol, "mt-")fraction <- colSums(counts[mitochondrial, , drop = FALSE]) / totalsstopifnot(all(totals > 0), all(is.finite(fraction)))low_counts <- totals < quantile(totals, 0.01, type = 7)low_genes <- detected < quantile(detected, 0.01, type = 7)high_mito <- fraction > quantile(fraction, 0.99, type = 7)quality <- data.frame( barcode = data$barcodes, umi = totals, genes = detected, mitochondrial_fraction = fraction, low_counts = as.integer(low_counts), low_genes = as.integer(low_genes), high_mito = as.integer(high_mito), retained = 1L, exclusion_reason = "none")dir.create("outputs", showWarnings = FALSE)write.table(quality, "outputs/quality_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)write.table(data$features[mitochondrial, ], "outputs/mitochondrial_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)png("outputs/quality_r.png", width = 1500, height = 1250, res = 150)par(mfrow = c(2, 2), mar = c(4, 4, 3, 1))hist(totals, breaks = 30, col = "#168080", border = "white", main = "Captured UMI counts", xlab = "UMIs per tissue spot")plot(totals, detected, pch = 16, cex = 0.45, col = "#16808080", xlab = "UMIs per tissue spot", ylab = "Detected genes", main = "Depth and detection")DrawSpatial(data, log10(totals), "log10 UMI counts")DrawSpatial(data, 100 * fraction, "Mitochondrial count percentage")invisible(dev.off())WriteMetrics(list(spots = ncol(counts), genes = nrow(counts), mitochondrial_genes = sum(mitochondrial), median_umi = median(totals), median_genes = median(detected), flagged = sum(low_counts | low_genes | high_mito), excluded = 0))cat(sprintf("The review retains all %d valid tissue spots.\n", ncol(counts)))cat(sprintf("The mitochondrial set contains %d feature identifiers.\n", sum(mitochondrial)))cat(sprintf("The distribution flags identify %d spots for review.\n", sum(low_counts | low_genes | high_mito)))The review retains all 2695 valid tissue spots.The mitochondrial set contains 13 feature identifiers.The distribution flags identify 56 spots for review.
All valid tissue spots remain in the distributions and overlays. The image circles use the supplied diameter and the low resolution coordinate scale.
import sysfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
sys.path.insert(0, "/shared")import spatial_utils as spatial
data = spatial.read_section()counts = data["counts"]totals = np.asarray(counts.sum(axis=0)).ravel()detected = np.diff(counts.indptr)mitochondrial = data["features"]["symbol"].str.startswith("mt-").to_numpy()fraction = np.asarray(counts[mitochondrial].sum(axis=0)).ravel() / totalsassert np.all(totals > 0) and np.isfinite(fraction).all()low_counts = totals < np.quantile(totals, 0.01, method="linear")low_genes = detected < np.quantile(detected, 0.01, method="linear")high_mito = fraction > np.quantile(fraction, 0.99, method="linear")quality = pd.DataFrame(dict( barcode=data["barcodes"], umi=totals, genes=detected, mitochondrial_fraction=fraction, low_counts=low_counts.astype(int), low_genes=low_genes.astype(int), high_mito=high_mito.astype(int), retained=1, exclusion_reason="none",))reference = pd.read_csv("outputs/quality_r.tsv", sep="\t")assert reference["barcode"].tolist() == quality["barcode"].tolist()columns = ["umi", "genes", "low_counts", "low_genes", "high_mito", "retained"]np.testing.assert_array_equal(reference[columns], quality[columns])np.testing.assert_allclose(reference["mitochondrial_fraction"], fraction, atol=1e-8, rtol=0)Path("outputs").mkdir(exist_ok=True)quality.to_csv("outputs/quality_python.tsv", sep="\t", index=False)data["features"].loc[mitochondrial].to_csv( "outputs/mitochondrial_python.tsv", sep="\t", index=False,)fig, axes = plt.subplots(2, 2, figsize=(12, 10))axes[0, 0].hist(totals, bins=30, color="#168080", edgecolor="white")axes[0, 0].set(xlabel="UMIs per tissue spot", ylabel="Spots", title="Captured UMI counts")axes[0, 1].scatter(totals, detected, s=4, alpha=0.5, color="#168080")axes[0, 1].set(xlabel="UMIs per tissue spot", ylabel="Detected genes", title="Depth and detection")spatial.draw_spatial(axes[1, 0], data, np.log10(totals), "log10 UMI counts")spatial.draw_spatial(axes[1, 1], data, 100 * fraction, "Mitochondrial count percentage")fig.tight_layout()fig.savefig("outputs/quality_python.png", dpi=150, bbox_inches="tight")plt.close(fig)flagged = int(np.sum(low_counts | low_genes | high_mito))spatial.write_metrics(dict( spots=counts.shape[1], genes=counts.shape[0], mitochondrial_genes=int(mitochondrial.sum()), median_umi=float(np.median(totals)), median_genes=float(np.median(detected)), flagged=flagged, excluded=0,))print(f"The review retains all {counts.shape[1]} valid tissue spots.")print(f"The mitochondrial set contains {mitochondrial.sum()} feature IDs.")print(f"The distribution flags identify {flagged} spots for review.")The review retains all 2695 valid tissue spots.The mitochondrial set contains 13 feature IDs.The distribution flags identify 56 spots for review.
Every spot total, detected-gene count, and review flag agrees exactly between
languages. Mitochondrial fractions agree within 1e-8.
The background tissue images come from 10x Genomics under CC BY 4.0. The figures add quality overlays and axes. The example does not remove low-count anatomy, apply ambient RNA correction, or infer viability from mitochondrial counts.
The full valid set and the declared quality mask are identical here. This explicit choice makes later sensitivity limits visible: a different exclusion rule would change the expression universe, remove graph edges, and sometimes create new isolated spots. Rebuild and audit the graph after such a change.
Further reading
Section titled “Further reading”The 10x Genomics specimen record supplies the original filtered matrix and tissue image. The Space Ranger spatial output specification explains the tissue-position fields and image scale factors. Use these sources when checking whether an unusual count profile falls on tissue, an edge, or another anatomical region.