Define neighbors on the capture lattice
A spatial neighbor is a geometric relation chosen by the analysis. Here two spots connect only when their native array positions share an immediate edge on the hexagonal capture lattice. Removing a spot does not create a replacement edge across its missing position, which preserves tissue gaps in the graph. The graph describes one section from one mouse donor.
For array position (row, col), the permitted offsets are (0, -2), (0, 2),
(-1, -1), (-1, 1), (1, -1), and (1, 1). The graph has no self edges.
Each undirected edge is stored once with its smaller matrix index first.
The quality review retains all valid tissue spots;
isolated positions remain visible here even though they cannot receive
row-normalized neighbor weights in the next lesson.
Construct and compare the edges
Section titled “Construct and compare the edges”R and Python derive the edge list independently from array coordinates.
Python also checks Squidpy’s current
spatial_neighbors_grid
function with one ring and six requested neighbors. The declared lattice
offsets remain the definition of the graph used for the statistics.
The neighbor label counts use the accepted Seurat fit from the expression lesson. Each undirected edge contributes two directed relations, one from each endpoint. These counts describe adjacent spot profiles, not cell contact or a signaling mechanism.
source("/shared/spatial_utils.R")data <- ReadSection()positions <- data$positionsn <- nrow(positions)offset_row <- c(0, 0, -1, -1, 1, 1)offset_col <- c(-2, 2, -1, 1, -1, 1)keys <- paste(positions$array_row, positions$array_col, sep = "_")stopifnot(!anyDuplicated(keys))source_index <- rep(seq_len(n), each = 6)neighbor_keys <- paste( rep(positions$array_row, each = 6) + rep(offset_row, n), rep(positions$array_col, each = 6) + rep(offset_col, n), sep = "_")target_index <- match(neighbor_keys, keys)keep <- !is.na(target_index) & source_index < target_indexedges <- data.frame(source = source_index[keep], target = target_index[keep])edges <- edges[order(edges$source, edges$target), ]adjacency <- sparseMatrix(i = c(edges$source, edges$target), j = c(edges$target, edges$source), x = 1, dims = c(n, n))stopifnot(all(diag(adjacency) == 0), isSymmetric(adjacency))degree <- rowSums(adjacency)graph <- igraph::graph_from_adjacency_matrix(adjacency, mode = "undirected")components <- igraph::components(graph)$noclusters <- read.delim("/fixtures/clusters_r.tsv", colClasses = "character")stopifnot(identical(clusters$barcode, data$barcodes))levels <- sort(unique(clusters$cluster))neighbors <- table(factor(clusters$cluster[edges$source], levels = levels), factor(clusters$cluster[edges$target], levels = levels))neighbors <- neighbors + t(neighbors)dir.create("outputs", showWarnings = FALSE)write.table(edges - 1L, "outputs/edges_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)write.table(data.frame(barcode = data$barcodes, degree = degree), "outputs/degrees_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)write.table(as.matrix(neighbors), "outputs/neighbors_r.tsv", sep = "\t", quote = FALSE, col.names = NA)png("outputs/graph_r.png", width = 1500, height = 700, res = 140)par(mfrow = c(1, 2), mar = c(6, 5, 3, 2))DrawSpatial(data, degree, "Immediate lattice edges and spot degrees")segments(positions$x[edges$source], positions$y[edges$source], positions$x[edges$target], positions$y[edges$target], col = "#33333350", lwd = 0.35)palette <- rev(hcl.colors(40, "Blues"))display <- t(as.matrix(neighbors))[, rev(seq_along(levels))]image(seq_along(levels), seq_along(levels), display, col = palette, axes = FALSE, xlab = "Neighbor Seurat cluster", ylab = "Source Seurat cluster", main = "Directed neighbor relations")axis(1, seq_along(levels), levels, las = 2, cex.axis = 0.65)axis(2, seq_along(levels), rev(levels), las = 2, cex.axis = 0.65)legend("bottomleft", paste(c(0, max(neighbors)), "relations"), fill = palette[c(1, 40)], bg = "white", cex = 0.7)invisible(dev.off())WriteMetrics(list(spots = n, edges = nrow(edges), isolated = sum(degree == 0), components = components))cat(sprintf("The graph contains %d undirected edges and %d components.\n", nrow(edges), components))cat(sprintf("The number of isolated tissue spots is %d.\n", sum(degree == 0)))print(data$barcodes[degree == 0])The graph contains 7828 undirected edges and 2 components.The number of isolated tissue spots is 1.[1] "TACTCGGCACGCCGGG-1"
The left panel retains isolated spots and colors each capture circle by its degree. The right panel counts directed relations, so each edge contributes twice.
import contextlibimport sys
import anndata as adimport matplotlib.pyplot as pltfrom matplotlib.collections import LineCollectionimport numpy as npimport pandas as pdfrom scipy import sparsefrom scipy.sparse.csgraph import connected_componentsimport squidpy as sq
sys.path.insert(0, "/shared")import spatial_utils as spatial
data = spatial.read_section()positions = data["positions"]array = positions[["array_row", "array_col"]].to_numpy()lookup = {tuple(position): index for index, position in enumerate(array)}assert len(lookup) == len(array)offsets = [(0, -2), (0, 2), (-1, -1), (-1, 1), (1, -1), (1, 1)]edge_list = []for source, (row, col) in enumerate(array): for row_offset, col_offset in offsets: target = lookup.get((row + row_offset, col + col_offset)) if target is not None and source < target: edge_list.append((source, target))edges = np.asarray(sorted(edge_list), dtype=int)reference = pd.read_csv("outputs/edges_r.tsv", sep="\t").to_numpy()np.testing.assert_array_equal(edges, reference)source = np.concatenate([edges[:, 0], edges[:, 1]])target = np.concatenate([edges[:, 1], edges[:, 0]])adjacency = sparse.csr_matrix((np.ones(len(source)), (source, target)), shape=(len(array), len(array)))assert adjacency.diagonal().sum() == 0assert (adjacency != adjacency.T).nnz == 0degree = np.asarray(adjacency.sum(axis=1)).ravel()degree_reference = pd.read_csv("outputs/degrees_r.tsv", sep="\t")assert degree_reference["barcode"].tolist() == data["barcodes"].tolist()np.testing.assert_array_equal(degree, degree_reference["degree"])components = connected_components(adjacency, directed=False)[0]grid = ad.AnnData(np.zeros((len(array), 1)))grid.obsm["spatial"] = np.column_stack([array[:, 1], array[:, 0] * np.sqrt(3)])with contextlib.redirect_stdout(sys.stderr): sq.gr.spatial_neighbors_grid(grid, n_neighs=6, n_rings=1, set_diag=False)squidpy_graph = grid.obsp["spatial_connectivities"]difference = int((squidpy_graph != adjacency).nnz)clusters = pd.read_csv("/fixtures/clusters_r.tsv", sep="\t", dtype=str)assert clusters["barcode"].tolist() == data["barcodes"].tolist()levels = sorted(clusters["cluster"].unique())labels = pd.Categorical(clusters["cluster"], categories=levels)neighbors = pd.crosstab(labels[source], labels[target], dropna=False)expected = pd.read_csv("outputs/neighbors_r.tsv", sep="\t", index_col=0)np.testing.assert_array_equal(neighbors.to_numpy(), expected.to_numpy())pd.DataFrame(edges, columns=["source", "target"]).to_csv( "outputs/edges_python.tsv", sep="\t", index=False,)pd.DataFrame(dict(barcode=data["barcodes"], degree=degree)).to_csv( "outputs/degrees_python.tsv", sep="\t", index=False,)neighbors.to_csv("outputs/neighbors_python.tsv", sep="\t")fig, axes = plt.subplots(1, 2, figsize=(12, 5))spatial.draw_spatial(axes[0], data, degree, "Immediate edges and spot degrees")xy = positions[["x", "y"]].to_numpy()axes[0].add_collection(LineCollection(xy[edges], colors="#33333350", linewidths=0.3))image = axes[1].imshow(neighbors.to_numpy(), cmap="Blues", aspect="auto")axes[1].set_xticks(range(len(levels)), levels)axes[1].set_yticks(range(len(levels)), levels)axes[1].set(xlabel="Neighbor Seurat cluster", ylabel="Source Seurat cluster", title="Directed neighbor relations")fig.colorbar(image, ax=axes[1], label="Relations")fig.tight_layout()fig.savefig("outputs/graph_python.png", dpi=160, bbox_inches="tight")plt.close(fig)spatial.write_metrics(dict(spots=len(array), edges=len(edges), isolated=int(np.sum(degree == 0)), components=int(components), grid_difference=difference))print(f"The graph contains {len(edges)} undirected edges " f"and {components} components.")print(f"The number of isolated tissue spots is {np.sum(degree == 0)}.")print(f"Squidpy differs at {difference} directed adjacency entries.")print(data["barcodes"][degree == 0].tolist())The graph contains 7828 undirected edges and 2 components.The number of isolated tissue spots is 1.Squidpy differs at 0 directed adjacency entries.['TACTCGGCACGCCGGG-1']
The Python calculation checks every ordered edge and every neighbor count against the R result. Geometric neighbors remain separate from the expression neighbors that created the cluster labels.
The background image is from 10x Genomics under CC BY 4.0. The figures add capture circles, edges, and axes. A large diagonal entry in the neighbor table can reflect broad expression domains and cluster size; it is not a test of cell interaction enrichment.
The autocorrelation lesson removes isolated spots only from the statistic. Their expression values and quality measurements remain available in the complete section.
The isolated barcode also receives a high mitochondrial fraction flag in the quality table. Its exclusion from Moran’s I follows the absence of lattice neighbors. The quality flag remains a separate diagnostic observation and does not establish cell viability.
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 grid neighbor reference explains the neighbor count and number of rings for a regular spatial lattice. It gives a comparison for the immediate hexagonal offsets used here.
The Space Ranger spatial output specification distinguishes array coordinates from image pixel coordinates. That distinction connects the graph calculation with the edges drawn over the tissue image.