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.
Define the observations and the null
Section titled “Define the observations and the null”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") + 1Ln <- 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 > 0statistic_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)) %*% adjacencystopifnot(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")) + 1Lstopifnot(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 null histogram uses the same graph as the observed statistic. The red line
shows the observed P2ry12 value after isolated spots are excluded.
import contextlibimport sys
import anndata as adimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import sparsefrom statsmodels.stats.multitest import multipletestsimport squidpy as sq
sys.path.insert(0, "/shared")import spatial_utils as spatial
def moran_values(values, weights): """Calculate one Moran statistic per expression column.
Args: values: Position-by-gene numeric matrix. weights: Row-normalized spatial weight matrix.
Returns: One Moran statistic per gene. """ centered = values - values.mean(axis=0) denominator = np.sum(centered**2, axis=0) assert np.all(denominator > 0) numerator = np.sum(centered * (weights @ centered), axis=0) return len(values) / weights.sum() * numerator / denominator
data = spatial.read_section()edges = pd.read_csv("/fixtures/edges.tsv", sep="\t").to_numpy()source = np.concatenate([edges[:, 0], edges[:, 1]])target = np.concatenate([edges[:, 1], edges[:, 0]])n = len(data["barcodes"])adjacency = sparse.csr_matrix((np.ones(len(source)), (source, target)), shape=(n, n))degree = np.asarray(adjacency.sum(axis=1)).ravel()included = degree > 0statistic_spots = pd.read_csv("/fixtures/statistic_barcodes.tsv")expected_barcodes = data["barcodes"][included].tolist()assert statistic_spots["barcode"].tolist() == expected_barcodesadjacency = adjacency[included][:, included]weights = sparse.diags(1 / np.asarray(adjacency.sum(axis=1)).ravel())weights = (weights @ adjacency).tocsr()weight_reference = pd.read_csv("outputs/weights_r.tsv", sep="\t")row_index = weight_reference["i"] - 1col_index = weight_reference["j"] - 1expected_weights = sparse.csr_matrix( (weight_reference["x"], (row_index, col_index)), shape=weights.shape,)np.testing.assert_allclose((weights - expected_weights).data, 0, atol=1e-8, rtol=0)np.testing.assert_allclose(np.asarray(weights.sum(axis=1)).ravel(), 1, atol=1e-8, rtol=0)panel = spatial.panel_indices(data["features"])values = spatial.normalize_counts(data["counts"])[panel][:, included].Tvalues = values.toarray()permutations = np.loadtxt("/fixtures/permutations.tsv.gz", dtype=np.int32)assert permutations.shape == (999, len(values))observed = moran_values(values, weights)null = np.empty((len(permutations), len(panel)))for index, permutation in enumerate(permutations): np.testing.assert_array_equal(np.sort(permutation), np.arange(len(values))) null[index] = moran_values(values[permutation], weights)exceedances = np.sum(null >= observed, axis=0)p_value = (1 + exceedances) / (1 + len(permutations))results = data["features"].iloc[panel].copy()results["moran_i"] = observedresults["exceedances"] = exceedancesresults["p_value"] = p_valueresults["adjusted_p"] = multipletests(p_value, method="fdr_bh")[1]reference = pd.read_csv("outputs/moran_r.tsv", sep="\t")assert results["feature_id"].tolist() == reference["feature_id"].tolist()np.testing.assert_allclose(observed, reference["moran_i"], atol=1e-8, rtol=0)np.testing.assert_array_equal(exceedances, reference["exceedances"])np.testing.assert_allclose(p_value, reference["p_value"], atol=1e-8, rtol=0)np.testing.assert_allclose(results["adjusted_p"], reference["adjusted_p"], atol=1e-8, rtol=0)np.testing.assert_allclose(null, np.loadtxt("outputs/null_r.tsv"), atol=1e-8, rtol=0)check = ad.AnnData(values)check.var_names = results["feature_id"].tolist()check.obsp["spatial_connectivities"] = weightswith contextlib.redirect_stdout(sys.stderr): sq.gr.spatial_autocorr(check, genes=check.var_names, mode="moran", transformation=False, n_perms=None, n_jobs=1, show_progress_bar=False)squidpy_i = check.uns["moranI"].loc[check.var_names, "I"].to_numpy()np.testing.assert_allclose(observed, squidpy_i, atol=1e-8, rtol=0)results.to_csv("outputs/moran_python.tsv", sep="\t", index=False)np.savetxt("outputs/null_python.tsv", null, delimiter="\t")pd.DataFrame(dict(barcode=data["barcodes"][~included])).to_csv( "outputs/isolated_python.tsv", sep="\t", index=False,)fig, axes = plt.subplots(1, 2, figsize=(12, 5))axes[0].bar(results["symbol"], observed, color="#168080")axes[0].tick_params(axis="x", rotation=60)axes[0].set(ylabel="Moran's I", title="The fixed eight-gene panel")null_bins = np.linspace(null[:, 7].min(), max(null[:, 7].max(), observed[7]), 31)axes[1].hist(null[:, 7], bins=null_bins, color="#9ac9c2", edgecolor="white")axes[1].axvline(observed[7], color="#bd3b35", label="Observed P2ry12")axes[1].set(xlabel="Moran's I", ylabel="Permutations", title="P2ry12 under the permutation null")axes[1].legend()fig.tight_layout()fig.savefig("outputs/moran_python.png", dpi=160, bbox_inches="tight")plt.close(fig)spatial.write_metrics(dict(spots=len(values), genes=len(panel), permutations=len(null), moran_sum=float(observed.sum()), exceedances=int(exceedances.sum())))print(f"The statistic uses {len(values)} nonisolated spots " f"and {len(null)} permutations.")print(results[["symbol", "moran_i", "p_value", "adjusted_p"]].to_string( index=False, float_format="%.5f",))The statistic uses 2694 nonisolated spots and 999 permutations. symbol moran_i p_value adjusted_pSlc17a7 0.85385 0.00100 0.00114 Gad1 0.63430 0.00100 0.00114 Gad2 0.54907 0.00100 0.00114 Mbp 0.85407 0.00100 0.00114 Plp1 0.76073 0.00100 0.00114 Gfap 0.52031 0.00100 0.00114 Aqp4 0.28179 0.00100 0.00114 P2ry12 0.03056 0.00300 0.00300
Both implementations compare every permutation statistic and the exact exceedance counts. Squidpy checks the observed Moran values independently.
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.
Scientific references
Section titled “Scientific references”Palla and colleagues, 2022 describe Squidpy, a scalable Python library for spatial omics analysis.
Further reading
Section titled “Further reading”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.