Normalize expression within a spot
Library normalization asks how a gene contributes to the captured transcript
pool within each spot. It divides that gene’s count by the spot total,
multiplies by 10,000, and applies log1p. The denominator can reflect capture
efficiency, tissue coverage, cell density, and cell composition, so the result
does not measure absolute expression per cell. The source contains one section
from one mouse donor.
The example uses all valid tissue spots retained in the
quality review. It preserves the original sparse count
matrix and creates a separate normalized matrix. The selected gene, Mbp, is
declared before the map is drawn and is not selected by a spatial test.
Apply the same arithmetic
Section titled “Apply the same arithmetic”For count c and positive spot total t, the transformation is
log1p(10000 * c / t). Zero counts remain zero. The examples keep feature
identifiers and barcode order fixed, then compare every stored normalized
value across languages within 1e-6.
source("/shared/spatial_utils.R")data <- ReadSection()counts <- data$countstotals <- colSums(counts)stopifnot(all(totals > 0))normalized <- counts %*% Diagonal(x = 10000 / totals)normalized@x <- log1p(normalized@x)stopifnot(all(counts@x == floor(counts@x)))stopifnot(identical(normalized@i, counts@i))stopifnot(identical(normalized@p, counts@p))marker <- which(data$features$symbol == "Mbp")stopifnot(length(marker) == 1)raw_marker <- as.numeric(counts[marker, ])relative_marker <- as.numeric(normalized[marker, ])dir.create("outputs", showWarnings = FALSE)writeBin(normalized@x, "outputs/normalized_r.bin", size = 8, endian = "little")write.table(data.frame(barcode = data$barcodes, raw = raw_marker, normalized = relative_marker), "outputs/marker_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)png("outputs/normalization_r.png", width = 1400, height = 650, res = 140)par(mfrow = c(1, 2), mar = c(4, 4, 3, 1))DrawSpatial(data, raw_marker, "Mbp captured UMI counts")DrawSpatial(data, relative_marker, "Mbp log1p counts per 10,000")invisible(dev.off())WriteMetrics(list(spots = ncol(counts), nonzero = length(normalized@x), count_sum = sum(counts), marker_sum = sum(relative_marker)))cat(sprintf("The transformation preserves %d original count entries.\n", length(counts@x)))cat(sprintf("The Mbp normalized sum is %.6f across the retained spots.\n", sum(relative_marker)))The transformation preserves 15850802 original count entries.The Mbp normalized sum is 8001.679653 across the retained spots.
Both maps retain the same capture circles and coordinates. Each map has its own color scale because counts and log-transformed relative expression have different units.
import sysfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import sparse
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()assert np.all(totals > 0)normalized = (counts @ sparse.diags(10000 / totals)).tocsc()normalized.sort_indices()normalized.data = np.log1p(normalized.data)np.testing.assert_array_equal(normalized.indices, counts.indices)np.testing.assert_array_equal(normalized.indptr, counts.indptr)assert np.all(counts.data == np.floor(counts.data))reference = np.fromfile("outputs/normalized_r.bin", dtype="<f8")np.testing.assert_allclose(normalized.data, reference, atol=1e-6, rtol=0)marker = np.flatnonzero(data["features"]["symbol"].eq("Mbp"))assert len(marker) == 1raw_marker = counts[marker].toarray().ravel()relative_marker = normalized[marker].toarray().ravel()Path("outputs").mkdir(exist_ok=True)normalized.data.astype("<f8").tofile("outputs/normalized_python.bin")pd.DataFrame(dict(barcode=data["barcodes"], raw=raw_marker, normalized=relative_marker)).to_csv( "outputs/marker_python.tsv", sep="\t", index=False,)fig, axes = plt.subplots(1, 2, figsize=(12, 5))spatial.draw_spatial(axes[0], data, raw_marker, "Mbp captured UMI counts")spatial.draw_spatial(axes[1], data, relative_marker, "Mbp log1p counts per 10,000")fig.tight_layout()fig.savefig("outputs/normalization_python.png", dpi=150, bbox_inches="tight")plt.close(fig)spatial.write_metrics(dict(spots=counts.shape[1], nonzero=normalized.nnz, count_sum=int(counts.sum()), marker_sum=float(relative_marker.sum())))print(f"The transformation preserves {counts.nnz} original count entries.")print(f"The Mbp normalized sum is {relative_marker.sum():.6f} " "across the retained spots.")The transformation preserves 15850802 original count entries.The Mbp normalized sum is 8001.679653 across the retained spots.
The Python calculation checks the full sparse value vector against the R result. The comparison includes every nonzero entry, not only the displayed marker or its total.
The tissue images come from 10x Genomics
under CC BY 4.0. These figures
add expression overlays. A normalized hotspot means that Mbp contributes
more strongly to the captured pool at that position; it does not count
oligodendrocytes or establish a change between mice.
The next lesson fits expression clusters without using spatial coordinates. That separation allows expression similarity and physical adjacency to be compared later.
Further reading
Section titled “Further reading”The Single-cell best practices normalization chapter explains library-size scaling and shifted logarithms. Compare its target-sum definitions with the fixed 10,000-UMI denominator used here.
The 10x Genomics specimen record identifies the spot-capture assay and archived section. That measurement context limits the biological interpretation of a normalized count.