bio-spatial-transcriptomics-spatial-neighbors
Build spatial neighbor graphs for spatial transcriptomics data using Squidpy. Compute k-nearest neighbors, Delaunay triangulation, and radius-based connectivity for downstream spatial analyses. Use when building spatial neighborhood graphs.
Best use case
bio-spatial-transcriptomics-spatial-neighbors is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Build spatial neighbor graphs for spatial transcriptomics data using Squidpy. Compute k-nearest neighbors, Delaunay triangulation, and radius-based connectivity for downstream spatial analyses. Use when building spatial neighborhood graphs.
Teams using bio-spatial-transcriptomics-spatial-neighbors should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/bio-spatial-transcriptomics-spatial-neighbors/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How bio-spatial-transcriptomics-spatial-neighbors Compares
| Feature / Agent | bio-spatial-transcriptomics-spatial-neighbors | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Build spatial neighbor graphs for spatial transcriptomics data using Squidpy. Compute k-nearest neighbors, Delaunay triangulation, and radius-based connectivity for downstream spatial analyses. Use when building spatial neighborhood graphs.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
SKILL.md Source
## Version Compatibility
Reference examples tested with: matplotlib 3.8+, numpy 1.26+, scanpy 1.10+, scikit-learn 1.4+, scipy 1.12+, squidpy 1.3+
Before using code patterns, verify installed versions match. If versions differ:
- Python: `pip show <package>` then `help(module.function)` to check signatures
If code throws ImportError, AttributeError, or TypeError, introspect the installed
package and adapt the example to match the actual API rather than retrying.
# Spatial Neighbor Graphs
**"Build a spatial neighborhood graph"** → Construct spatial connectivity graphs using k-nearest neighbors, Delaunay triangulation, or radius-based methods for downstream spatial statistics.
- Python: `squidpy.gr.spatial_neighbors(adata, coord_type='generic', n_neighs=6)`
Build spatial neighbor graphs for connectivity-based analyses.
## Required Imports
```python
import squidpy as sq
import scanpy as sc
import numpy as np
```
## Build K-Nearest Neighbors Graph
**Goal:** Construct a spatial KNN graph connecting each spot to its nearest spatial neighbors.
**Approach:** Use Squidpy's `spatial_neighbors` with k-nearest neighbors on coordinate distances.
```python
# Build spatial KNN graph
sq.gr.spatial_neighbors(adata, n_neighs=6, coord_type='generic')
# Check the graph
print(f"Connectivities shape: {adata.obsp['spatial_connectivities'].shape}")
print(f"Distances shape: {adata.obsp['spatial_distances'].shape}")
```
## Build Delaunay Triangulation Graph
```python
# Delaunay triangulation (natural neighbors)
sq.gr.spatial_neighbors(adata, delaunay=True, coord_type='generic')
```
## Radius-Based Neighbors
```python
# Connect all spots within a radius
sq.gr.spatial_neighbors(adata, radius=100, coord_type='generic')
```
## For Visium Data (Grid Structure)
```python
# For Visium hexagonal grid, use n_rings
sq.gr.spatial_neighbors(adata, n_rings=1, coord_type='grid') # 6 immediate neighbors
sq.gr.spatial_neighbors(adata, n_rings=2, coord_type='grid') # Extended neighborhood
```
## Access Neighbor Information
```python
# Get connectivities as sparse matrix
conn = adata.obsp['spatial_connectivities']
print(f'Edges in graph: {conn.nnz}')
print(f'Mean neighbors per spot: {conn.nnz / adata.n_obs:.1f}')
# Get distances
dist = adata.obsp['spatial_distances']
nonzero_dist = dist.data[dist.data > 0]
print(f'Mean neighbor distance: {nonzero_dist.mean():.1f}')
```
## Get Neighbors for a Specific Spot
```python
from scipy.sparse import csr_matrix
spot_idx = 0
conn = adata.obsp['spatial_connectivities']
# Get neighbor indices
neighbor_indices = conn[spot_idx].nonzero()[1]
print(f'Spot {spot_idx} has {len(neighbor_indices)} neighbors: {neighbor_indices}')
# Get distances to neighbors
dist = adata.obsp['spatial_distances']
neighbor_distances = dist[spot_idx, neighbor_indices].toarray().flatten()
print(f'Distances: {neighbor_distances}')
```
## Build Expression-Based Neighbors
```python
# Standard expression-based neighbors (for comparison)
sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30)
# Now adata has both:
# - adata.obsp['spatial_connectivities'] (spatial)
# - adata.obsp['connectivities'] (expression)
```
## Combine Spatial and Expression Neighbors
**Goal:** Create a unified neighbor graph that balances spatial proximity with expression similarity.
**Approach:** Build separate spatial and expression neighbor graphs, normalize each, then combine with a tunable weight parameter.
```python
# Build both graphs
sq.gr.spatial_neighbors(adata, n_neighs=6, coord_type='generic')
sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30)
# Weighted combination (manual)
alpha = 0.5 # Weight for spatial vs expression
spatial_conn = adata.obsp['spatial_connectivities']
expr_conn = adata.obsp['connectivities']
# Normalize and combine
from sklearn.preprocessing import normalize
spatial_norm = normalize(spatial_conn, norm='l1', axis=1)
expr_norm = normalize(expr_conn, norm='l1', axis=1)
combined = alpha * spatial_norm + (1 - alpha) * expr_norm
adata.obsp['combined_connectivities'] = combined
```
## Visualize Neighbor Graph
**Goal:** Display the spatial neighbor graph overlaid on tissue coordinates for visual inspection.
**Approach:** Draw edges between connected spots and scatter plot the spot positions.
```python
import matplotlib.pyplot as plt
# Get coordinates
coords = adata.obsm['spatial']
conn = adata.obsp['spatial_connectivities']
fig, ax = plt.subplots(figsize=(10, 10))
# Draw edges
rows, cols = conn.nonzero()
for i, j in zip(rows, cols):
if i < j: # Avoid drawing twice
ax.plot([coords[i, 0], coords[j, 0]], [coords[i, 1], coords[j, 1]], 'k-', alpha=0.1, linewidth=0.5)
# Draw nodes
ax.scatter(coords[:, 0], coords[:, 1], s=10, c='blue', alpha=0.5)
ax.set_aspect('equal')
plt.title('Spatial neighbor graph')
```
## Compute Graph Statistics
**Goal:** Calculate summary statistics of the spatial neighbor graph (nodes, edges, connectivity).
**Approach:** Convert the sparse connectivity matrix to a NetworkX graph and compute standard graph metrics.
```python
import networkx as nx
from scipy.sparse import csr_matrix
conn = adata.obsp['spatial_connectivities']
G = nx.from_scipy_sparse_array(conn)
print(f'Nodes: {G.number_of_nodes()}')
print(f'Edges: {G.number_of_edges()}')
print(f'Average degree: {2 * G.number_of_edges() / G.number_of_nodes():.2f}')
print(f'Connected components: {nx.number_connected_components(G)}')
```
## Store Multiple Neighbor Graphs
```python
# Store different neighborhood sizes
for n_neighs in [4, 6, 10]:
sq.gr.spatial_neighbors(adata, n_neighs=n_neighs, coord_type='generic')
adata.obsp[f'spatial_conn_{n_neighs}'] = adata.obsp['spatial_connectivities'].copy()
adata.obsp[f'spatial_dist_{n_neighs}'] = adata.obsp['spatial_distances'].copy()
```
## Related Skills
- spatial-statistics - Use neighbor graph for spatial statistics
- spatial-domains - Identify domains using spatial graph
- single-cell/clustering - Non-spatial neighbor graphsRelated Skills
tooluniverse-spatial-transcriptomics
Analyze spatial transcriptomics data to map gene expression in tissue architecture. Supports 10x Visium, MERFISH, seqFISH, Slide-seq, and imaging-based platforms. Performs spatial clustering, domain identification, cell-cell proximity analysis, spatial gene expression patterns, tissue architecture mapping, and integration with single-cell data. Use when analyzing spatial transcriptomics datasets, studying tissue organization, identifying spatial expression patterns, mapping cell-cell interactions in tissue context, characterizing tumor microenvironment spatial structure, or integrating spatial and single-cell RNA-seq data for comprehensive tissue analysis.
tooluniverse-spatial-omics-analysis
Computational analysis framework for spatial multi-omics data integration. Given spatially variable genes (SVGs), spatial domain annotations, tissue type, and disease context from spatial transcriptomics/proteomics experiments (10x Visium, MERFISH, DBiTplus, SLIDE-seq, etc.), performs comprehensive biological interpretation including pathway enrichment, cell-cell interaction inference, druggable target identification, immune microenvironment characterization, and multi-modal integration. Produces a detailed markdown report with Spatial Omics Integration Score (0-100), domain-by-domain characterization, and validation recommendations. Uses 70+ ToolUniverse tools across 9 analysis phases. Use when users ask about spatial transcriptomics analysis, spatial omics interpretation, tissue heterogeneity, spatial gene expression patterns, tumor microenvironment mapping, tissue zonation, or cell-cell communication from spatial data.
spatial-transcriptomics-tutorials-with-omicverse
Guide users through omicverse's spatial transcriptomics tutorials covering preprocessing, deconvolution, and downstream modelling workflows across Visium, Visium HD, Stereo-seq, and Slide-seq datasets.
single2spatial-spatial-mapping
Map scRNA-seq atlases onto spatial transcriptomics slides using omicverse's Single2Spatial workflow for deep-forest training, spot-level assessment, and marker visualisation.
bio-spatial-transcriptomics-spatial-visualization
Visualize spatial transcriptomics data using Squidpy and Scanpy. Create tissue plots with gene expression, clusters, and annotations overlaid on histology images. Use when visualizing spatial expression patterns.
bio-spatial-transcriptomics-spatial-statistics
Compute spatial statistics for spatial transcriptomics data using Squidpy. Calculate Moran's I, Geary's C, spatial autocorrelation, co-occurrence analysis, and neighborhood enrichment. Use when computing spatial autocorrelation or co-occurrence statistics.
bio-spatial-transcriptomics-spatial-proteomics
Analyzes spatial proteomics data from CODEX, IMC, and MIBI platforms including cell segmentation and protein colocalization. Use when working with multiplexed imaging data, analyzing protein spatial patterns, or integrating spatial proteomics with transcriptomics.
bio-spatial-transcriptomics-spatial-preprocessing
Quality control, filtering, normalization, and feature selection for spatial transcriptomics data. Calculate QC metrics, filter spots/cells, normalize counts, and identify highly variable genes. Use when filtering and normalizing spatial transcriptomics data.
bio-spatial-transcriptomics-spatial-multiomics
Analyze high-resolution spatial platforms like Slide-seq, Stereo-seq, and Visium HD. Use when working with subcellular resolution or high-density spatial data.
bio-spatial-transcriptomics-spatial-domains
Identify spatial domains and tissue regions in spatial transcriptomics data using Squidpy and Scanpy. Cluster spots considering both expression and spatial context to define anatomical regions. Use when identifying tissue domains or spatial regions.
bio-spatial-transcriptomics-spatial-deconvolution
Estimate cell type composition in spatial transcriptomics spots using reference-based deconvolution. Use cell2location, RCTD, SPOTlight, or Tangram to infer cell type proportions from scRNA-seq references. Use when estimating cell type composition in spatial spots.
bio-spatial-transcriptomics-spatial-data-io
Load spatial transcriptomics data from Visium, Xenium, MERFISH, Slide-seq, and other platforms using Squidpy and SpatialData. Read Space Ranger outputs, convert formats, and access spatial coordinates. Use when loading Visium, Xenium, MERFISH, or other spatial data.