Skip to content

Test a declared spatial pattern

Moran’s I compares expression differences between neighboring positions with the variation across the section. A positive value means that nearby spots tend to have similar values under the declared graph. The statistic describes the joint behavior of the expression transformation and the neighbor weights; it is not an intrinsic property of a gene. The observations come from one section from one mouse donor.

This example fixes eight genes before the statistic is calculated. The panel contains Slc17a7, Gad1, Gad2, Mbp, Plp1, Gfap, Aqp4, and P2ry12. Each symbol must resolve to one stable feature identifier. The marker lesson explains the biological references and the limits of their interpretation in mixed spots.

The calculation uses log1p counts per 10,000 UMIs from the complete quality mask. It excludes isolated spots from the statistic, then normalizes each remaining adjacency row to sum to one. Isolated spots remain in the expression and quality figures. The graph comes from the checked lattice construction.

The null shuffles expression values across the retained positions while the graph stays fixed. The preparation saves 999 permutation index rows with seed 20261031, and both languages use those same rows. The upper-tail p-value is (1 + exceedances) / 1000, including equality in the exceedance count. Its minimum possible value is 0.001. Benjamini-Hochberg correction covers exactly the eight declared genes, without selecting a smaller family after inspection.

source("/shared/spatial_utils.R")
#' Calculate Moran's I for each expression column.
#'
#' @param values A position-by-gene numeric matrix.
#' @param weights A row-normalized spatial weight matrix.
#' @return One Moran statistic per gene.
MoranValues <- function(values, weights) {
centered <- sweep(values, 2, colMeans(values), "-")
numerator <- colSums(centered * as.matrix(weights %*% centered))
denominator <- colSums(centered^2)
stopifnot(all(denominator > 0))
nrow(values) / sum(weights) * numerator / denominator
}
data <- ReadSection()
edges <- read.delim("/fixtures/edges.tsv") + 1L
n <- length(data$barcodes)
adjacency <- sparseMatrix(i = c(edges$source, edges$target),
j = c(edges$target, edges$source), x = 1,
dims = c(n, n))
degree <- rowSums(adjacency)
included <- degree > 0
statistic_spots <- read.delim("/fixtures/statistic_barcodes.tsv")
stopifnot(identical(statistic_spots$barcode, data$barcodes[included]))
adjacency <- adjacency[included, included]
weights <- Diagonal(x = 1 / rowSums(adjacency)) %*% adjacency
stopifnot(max(abs(rowSums(weights) - 1)) < 1e-8)
panel <- PanelIndices(data$features)
values <- t(as.matrix(NormalizeCounts(data$counts)[panel, included]))
permutations <- as.matrix(read.table(
gzfile("/fixtures/permutations.tsv.gz"), sep = "\t", colClasses = "integer"
)) + 1L
stopifnot(nrow(permutations) == 999, ncol(permutations) == nrow(values))
observed <- MoranValues(values, weights)
null <- matrix(NA_real_, nrow = nrow(permutations), ncol = length(panel))
for (index in seq_len(nrow(permutations))) {
permutation <- as.integer(permutations[index, ])
stopifnot(identical(sort(permutation), seq_len(nrow(values))))
null[index, ] <- MoranValues(values[permutation, ], weights)
}
exceedances <- colSums(sweep(null, 2, observed, ">="))
p_value <- (1 + exceedances) / (1 + nrow(permutations))
results <- data.frame(data$features[panel, ], moran_i = observed,
exceedances = exceedances, p_value = p_value,
adjusted_p = p.adjust(p_value, method = "BH"))
dir.create("outputs", showWarnings = FALSE)
write.table(results, "outputs/moran_r.tsv", sep = "\t", quote = FALSE,
row.names = FALSE)
write.table(null, "outputs/null_r.tsv", sep = "\t", quote = FALSE,
row.names = FALSE, col.names = FALSE)
write.table(summary(weights), "outputs/weights_r.tsv", sep = "\t",
quote = FALSE, row.names = FALSE)
write.table(data.frame(barcode = data$barcodes[!included]),
"outputs/isolated_r.tsv", sep = "\t", quote = FALSE,
row.names = FALSE)
png("outputs/moran_r.png", width = 1450, height = 650, res = 140)
par(mfrow = c(1, 2), mar = c(6, 4, 3, 1))
barplot(observed, names.arg = results$symbol, las = 2, col = "#168080",
ylab = "Moran's I", main = "The fixed eight-gene panel")
null_breaks <- seq(min(null[, 8]), max(c(null[, 8], observed[8])),
length.out = 31)
hist(null[, 8], breaks = null_breaks, col = "#9ac9c2", border = "white",
xlab = "Moran's I", main = "P2ry12 under the permutation null")
abline(v = observed[8], col = "#bd3b35", lwd = 2)
legend("topright", "Observed P2ry12", col = "#bd3b35", lwd = 2, bty = "n")
invisible(dev.off())
WriteMetrics(list(spots = nrow(values), genes = length(panel),
permutations = nrow(null), moran_sum = sum(observed),
exceedances = sum(exceedances)))
cat(sprintf("The statistic uses %d nonisolated spots and %d permutations.\n",
nrow(values), nrow(null)))
print(results[, c("symbol", "moran_i", "p_value", "adjusted_p")],
digits = 5, row.names = FALSE)
The statistic uses 2694 nonisolated spots and 999 permutations.
symbol moran_i p_value adjusted_p
Slc17a7 0.853848 0.001 0.0011429
Gad1 0.634304 0.001 0.0011429
Gad2 0.549071 0.001 0.0011429
Mbp 0.854067 0.001 0.0011429
Plp1 0.760733 0.001 0.0011429
Gfap 0.520312 0.001 0.0011429
Aqp4 0.281787 0.001 0.0011429
P2ry12 0.030564 0.003 0.0030000

The R figure shows Moran statistics for the fixed panel and the P2ry12 permutation null.

The null histogram uses the same graph as the observed statistic. The red line shows the observed P2ry12 value after isolated spots are excluded.

The Squidpy specification distinguishes analytic p-values from permutation p-values. Only the shared permutation calculation supplies the p-values shown here. The analytic values created during the Squidpy check are not the reported evidence.

P2ry12 has a smaller Moran value than Mbp even though both depart from the same random placement null. A low p-value does not make their spatial effects equal. The null panel displays P2ry12 so that the observed value and the permutation distribution remain visible on the same scale.

A small permutation p-value rejects a random placement of these expression values over this graph. Tissue anatomy makes that null restrictive, and nearby spots share biological structure. The result does not estimate a treatment effect, establish cell communication, or support a claim across independent mice.

Palla and colleagues, 2022 describe Squidpy, a scalable Python library for spatial omics analysis.

The Squidpy spatial autocorrelation reference distinguishes the observed statistic, analytic p-values, and permutation results. Check the weight transformation and permutation settings when comparing it with the shared permutations used here.

The R p-value adjustment reference explains BH correction across the eight declared gene hypotheses. The software documentation defines these operations; it does not increase the number of independent tissue donors.