
Tooluniverse Spatial Transcriptomics
- 351 installs
- 1.6k repo stars
- Updated August 4, 2026
- mims-harvard/tooluniverse
tooluniverse-spatial-transcriptomics is a bioinformatics agent skill that analyzes spatially resolved gene expression maps to relate cell programs to tissue architecture, niches, and regional pathology for developers who
About
tooluniverse-spatial-transcriptomics is a ToolUniverse agent skill from mims-harvard/tooluniverse for spatial transcriptomics workflows. The skill guides developers through analyzing spatially resolved gene expression maps to connect cell programs with tissue architecture, microenvironment niches, and regional pathology in heterogeneous samples. It fits computational biology and translational research pipelines where spatial omics must be interpreted alongside histology and anatomical context. Developers reach for tooluniverse-spatial-transcriptomics when integrating spatial transcriptomics analysis into agent-assisted research code, notebooks, or reproducible pipelines that compare expression patterns across tissue regions.
- Spatial gene expression maps
- Tissue architecture context
- Niche and regional biology
- Beyond dissociated single-cell views
- ToolUniverse spatial omics access
Tooluniverse Spatial Transcriptomics by the numbers
- 351 all-time installs (skills.sh)
- +8 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #542 of 2,064 Data Science & ML skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mims-harvard/tooluniverse --skill tooluniverse-spatial-transcriptomicsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 351 |
|---|---|
| repo stars | ★ 1.6k |
| Last updated | August 4, 2026 |
| Repository | mims-harvard/tooluniverse ↗ |
How do you analyze spatial transcriptomics gene expression maps?
Analyze spatially resolved gene expression maps to relate cell programs to tissue architecture, niches, and regional pathology in complex samples.
Who is it for?
Developers and computational biologists building agent-assisted spatial omics analysis pipelines on heterogeneous tissue samples.
Skip if: Developers who only need bulk RNA-seq differential expression without spatial coordinates or tissue-context mapping.
When should I use this skill?
A developer asks to relate spatial gene expression to tissue architecture, niches, or regional pathology in complex samples.
What you get
Spatial expression maps linked to tissue architecture, niche assignments, and regional pathology summaries.
- tissue-region expression summaries
- niche and pathology linkage reports
Files
Spatial Transcriptomics Analysis
Comprehensive analysis of spatially-resolved transcriptomics data to understand gene expression patterns in tissue architecture context. Combines expression profiling with spatial coordinates to reveal tissue organization, cell-cell interactions, and spatially variable genes.
LOOK UP, DON'T GUESS
When uncertain about any scientific fact, SEARCH databases first rather than reasoning from memory. A database-verified answer is always more reliable than a guess.
When to Use This Skill
Triggers:
- User has spatial transcriptomics data (Visium, MERFISH, seqFISH, etc.)
- Questions about tissue architecture or spatial organization
- Spatial gene expression pattern analysis
- Cell-cell proximity or neighborhood analysis requests
- Tumor microenvironment spatial structure questions
- Integration of spatial with single-cell data
- Spatial domain identification
- Tissue morphology correlation with expression
Example Questions: 1. "Analyze this 10x Visium dataset to identify spatial domains" 2. "Which genes show spatially variable expression in this tissue?" 3. "Map the tumor microenvironment spatial organization" 4. "Find genes enriched at tissue boundaries" 5. "Identify cell-cell interactions based on spatial proximity" 6. "Integrate spatial transcriptomics with scRNA-seq annotations"
---
Core Capabilities
- Data Import: 10x Visium, MERFISH, seqFISH, Slide-seq, STARmap, Xenium formats
- Quality Control: Spot/cell QC, spatial alignment verification, tissue coverage
- Normalization: Spatial-aware normalization accounting for tissue heterogeneity
- Spatial Clustering: Identify spatial domains with similar expression profiles
- Spatial Variable Genes: Find genes with non-random spatial patterns
- Neighborhood Analysis: Cell-cell proximity, spatial neighborhoods, niche identification
- Integration: Merge with scRNA-seq for cell type mapping (Cell2location, Tangram, SPOTlight)
- Ligand-Receptor Spatial: Map cell communication in tissue context via OmniPath
Supported Platforms
- 10x Visium: 55um spots (~50 cells/spot), genome-wide, includes H&E image — most common
- MERFISH/seqFISH: Single-cell resolution, 100-10,000 targeted genes, imaging-based
- Slide-seq/V2: 10um beads, genome-wide — higher resolution than Visium
- Xenium: Single-cell/subcellular, 300+ targeted genes (10x platform)
---
Workflow Overview
Input: Spatial Transcriptomics Data + Tissue Image
|
v
Phase 1: Data Import & QC
|-- Load spatial coordinates + expression matrix
|-- Load tissue histology image
|-- Quality control per spot/cell (min 200 genes, 500 UMI, <20% MT)
|-- Align spatial coordinates to tissue
|
v
Phase 2: Preprocessing
|-- Normalization (spatial-aware methods)
|-- Highly variable gene selection (top 2000)
|-- Dimensionality reduction (PCA)
|-- Spatial lag smoothing (optional)
|
v
Phase 3: Spatial Clustering
|-- Build spatial neighbor graph (squidpy)
|-- Graph-based clustering with spatial constraints (Leiden)
|-- Annotate domains with marker genes (Wilcoxon)
|-- Visualize domains on tissue
|
v
Phase 4: Spatial Variable Genes
|-- Test spatial autocorrelation (Moran's I, Geary's C)
|-- Filter significant spatial genes (FDR < 0.05)
|-- Classify pattern types (gradient, hotspot, boundary, periodic)
|
v
Phase 5: Neighborhood Analysis
|-- Define spatial neighborhoods (k-NN, radius)
|-- Calculate neighborhood composition (squidpy nhood_enrichment)
|-- Identify interaction zones between domains
|
v
Phase 6: Integration with scRNA-seq
|-- Cell type deconvolution (Cell2location, Tangram, SPOTlight)
|-- Map cell types to spatial locations
|-- Validate with marker genes
|
v
Phase 7: Spatial Cell Communication
|-- Identify proximal cell type pairs
|-- Query ligand-receptor database (OmniPath)
|-- Score spatial interactions (squidpy ligrec)
|-- Map communication hotspots
|
v
Phase 8: Generate Spatial Report
|-- Tissue overview with domains
|-- Spatially variable genes
|-- Cell type spatial maps
|-- Interaction networks in tissue context---
Phase Summaries
Phase 1: Data Import & QC
Load platform-specific data (scanpy read_visium for Visium). Apply QC filters: min 200 genes/spot, min 500 UMI/spot, max 20% mitochondrial. Verify spatial alignment with tissue image overlay.
Phase 2: Preprocessing
Normalize to median total counts, log-transform, select top 2000 HVGs. Optional spatial smoothing via neighbor averaging (useful for noisy data but blurs boundaries).
Phase 3: Spatial Clustering
PCA (50 components) followed by spatial neighbor graph construction (squidpy). Leiden clustering with spatial constraints yields spatial domains. Find domain markers via Wilcoxon rank-sum test.
Phase 4: Spatially Variable Genes
Moran's I statistic tests spatial autocorrelation: I > 0 = clustering, I ~ 0 = random, I < 0 = checkerboard. Filter by FDR < 0.05. Classify patterns as gradient, hotspot, boundary, or periodic.
Phase 5: Neighborhood Analysis
Neighborhood enrichment analysis (squidpy) tests whether cell types/domains are co-localized beyond random expectation. Identify interaction zones at domain boundaries using k-NN spatial graphs.
Phase 6: scRNA-seq Integration
Cell type deconvolution maps single-cell annotations to spatial spots. Methods: Cell2location (recommended for Visium), Tangram, SPOTlight. Produces cell type fraction estimates per spot.
Phase 7: Spatial Cell Communication
Combine spatial proximity with ligand-receptor databases. Key ToolUniverse tools:
OmniPath_get_ligand_receptor_interactions— 14,000+ L-R pairs from CellPhoneDB, CellChatDB, etc. Usepartnersparam for specific genes.OmniPath_get_intercell_roles— classify proteins as ligand/receptor/ECM. Useproteinsparam.OmniPath_get_cell_communication_annotations— CellPhoneDB/CellChatDB pathway annotations. Useproteinsparam.OmniPath_get_signaling_interactions— intracellular signaling downstream of receptors.
Score interactions by co-expression of L-R pairs in proximal cells. Map hotspots where interaction scores peak.
Phase 7.5: Data Discovery & Gene Context (ToolUniverse API tools)
For dataset discovery and gene annotation (API-based, no local computation needed):
geo_search_datasets/OmicsDI_search_datasets/NCBI_SRA_search_runs— find spatial TX datasetsUniProt_get_function_by_accession— protein function for stroma/immune markersSTRING_get_network— protein interaction networks for key markerskegg_search_pathway/kegg_get_pathway_info— relevant metabolic/signaling pathwaysDGIdb_get_drug_gene_interactions— druggable targets in the spatial contextPubMed_search_articles— literature for spatial biology context
API tools vs. local computation: Phases 1-2 (data import, QC) and Phases 3-6 (clustering, SVGs, neighborhoods, deconvolution) require local Python with squidpy/scanpy. Phase 7 L-R databases and Phase 7.5 gene context use ToolUniverse API tools.
Phase 8: Report Generation
See report_template.md for full example output.
---
Integration with ToolUniverse Skills
tooluniverse-single-cell: scRNA-seq reference for deconvolution (Phase 6) and L-R database (Phase 7)tooluniverse-gene-enrichment: Pathway enrichment for spatial domain marker genes (Phase 3)tooluniverse-multi-omics-integration: Integration with other omics layers (Phase 8)
ToolUniverse Data Retrieval Tools
HuBMAP Spatial Atlas Tools
Use HuBMAP tools to discover published spatial biology datasets for reference, validation, or cross-study comparison.
Availability Note:HuBMAP_search_datasets,HuBMAP_list_organs, andHuBMAP_get_datasetmay not be registered in your ToolUniverse instance. Verify withtu.list_tools()before use. If unavailable, use OmicsDI (OmicsDI_search_datasets(query="spatial transcriptomics kidney")) or CELLxGENE (CELLxGENE_get_cell_metadata) as reliable alternatives for spatial dataset discovery.
HuBMAP_search_datasets: Search published datasets byorgan(code, e.g. "LK"=Left Kidney, "BR"=Brain),dataset_type,query,limitHuBMAP_list_organs: List all organs with codes and UBERON IDs (no required params)HuBMAP_get_dataset: Get detailed metadata for a specifichubmap_id(e.g. "HBM626.FHJD.938")
Organ codes: LK/RK=Kidney, LI=Large Intestine, SI=Small Intestine, HT=Heart, LV=Liver, LU=Lung, SP=Spleen, BR=Brain, PA=Pancreas, SK=Skin.
HuBMAP biospecimen + spatial-registration layer (Samples & Donors)
Below the dataset level, HuBMAP indexes the physical tissue Samples (anatomical blocks/sections/organs/suspensions) and the human Donors. Use these to inspect CCF/RUI spatial registration and donor demographics — context the dataset tools do not expose.
HuBMAP_search_samples: Find tissue Samples byorgan(2-letter code),sample_category("block"/"section"/"organ"/"suspension"),registered_only(only CCF/RUI-registered specimens),limit. Each result flagsspatially_registeredand links the parent donor.HuBMAP_get_sample: Full record for one Samplehubmap_id(e.g. "HBM658.BXNB.873"), including parsedrui_location— the CCFplacement_targetreference organ, x/y/zdimensions + units, andccf_annotations(UBERON/FMA structures the block overlaps).HuBMAP_search_donors: Find Donors bygroup_name(e.g. "Stanford") or free-textquery, with normalizeddemographics(age, sex, race, body_mass_index, cause_of_death) extracted from UMLS/SNOMED-coded metadata. Use to build demographically-matched tissue cohorts.
# Spatially-registered kidney blocks (carry CCF coordinates)
blocks = tu.tools.HuBMAP_search_samples(organ="LK", sample_category="block", registered_only=True, limit=5)
# Inspect the CCF spatial registration of one block
s = tu.tools.HuBMAP_get_sample(hubmap_id="HBM658.BXNB.873")
# s["data"]["rui_location"] -> {placement_target: ...VHMLung..., x/y/z_dimension, dimension_units, ccf_annotations:[UBERON...]}
# Demographically-matched donor cohort
donors = tu.tools.HuBMAP_search_donors(group_name="Stanford", limit=10)
# donors["data"]["donors"][i]["demographics"] -> {age, sex, race, body_mass_index, ...}When to use:
- Finding reference spatial datasets for a given organ/tissue
- Identifying available spatial assay types (Visium, CODEX, MERFISH) for a tissue
- Cross-referencing donor metadata (age, sex) for spatial datasets
- Retrieving DOI links for published spatial atlas datasets
Fallback if HuBMAP tools unavailable:
# Use OmicsDI for spatial dataset discovery
result = tu.tools.OmicsDI_search_datasets(query="spatial transcriptomics kidney Visium")
# Use CELLxGENE for cell-level expression context
result = tu.tools.CELLxGENE_get_cell_metadata(tissue="kidney")# Example: Find spatial datasets for kidney (if HuBMAP tools available)
result = tu.tools.HuBMAP_search_datasets(organ="LK", limit=5)
# Returns: {data: {total, returned, datasets: [{hubmap_id, title, dataset_type, organ, doi_url, ...}]}}
# Example: Get all available organs
organs = tu.tools.HuBMAP_list_organs()
# Returns: {data: {total, organs: [{code, term, organ_uberon, rui_supported}]}}---
Example Use Cases
Use Case 1: Tumor Microenvironment Mapping
Question: "Map the spatial organization of tumor, immune, and stromal cells" Workflow: Load Visium -> QC -> Spatial clustering -> Deconvolution -> Interaction zones -> L-R analysis -> Report
Use Case 2: Developmental Gradient Analysis
Question: "Identify spatial gene expression gradients in developing tissue" Workflow: Load spatial data -> SVG analysis -> Classify gradient patterns -> Map morphogens -> Correlate with cell fate -> Report
Use Case 3: Brain Region Identification
Question: "Automatically segment brain tissue into anatomical regions" Workflow: Load Visium brain -> High-resolution clustering -> Match to known regions -> Validate with Allen Brain Atlas -> Report
---
Quantified Minimums
- At least 500 spatial locations after QC
- Filter low-quality spots (min 200 genes, min 500 UMI, <20% MT) and verify alignment
- At least one spatial clustering method (graph-based with spatial constraints)
- Spatially variable genes tested with Moran's I or equivalent (FDR < 0.05)
- Spatial plots on tissue images for all major findings
- Report covers: domains, spatial genes, cell type maps, key interactions
---
Reasoning Framework
Starting Point: What Is the Spatial Question?
Spatial data adds location to expression. The key question: is the spatial pattern driven by cell type composition (trivial) or by spatially-regulated gene expression within the same cell type (interesting)? Deconvolution helps distinguish these.
Before interpreting any spatially variable gene (SVG), ask: 1. Does this gene simply mark a cell type that is spatially restricted? (e.g., a T-cell marker enriched in immune infiltrate zones — expected, not informative) 2. Or is the gene differentially expressed within the same cell type depending on its spatial position? (e.g., a fibroblast gene upregulated at the tumor-stroma boundary — spatially regulated, biologically interesting)
To distinguish these: (a) run deconvolution (Cell2location, Tangram) to get cell type fractions per spot; (b) regress SVG expression against cell type fraction; (c) if the spatial pattern persists after controlling for cell type composition, it reflects genuine spatial regulation. Always look up the gene's known biology before interpreting — check UniProt function and STRING interactions rather than guessing.
Evidence Grading
- T1: Validated by orthogonal method (IHC, smFISH, known anatomy) — e.g., spatial domain matches histology-confirmed tumor margin
- T2: Statistically significant, biologically consistent — SVG with Moran's I > 0.3 and FDR < 0.01 in expected tissue region
- T3: Computationally identified, awaiting validation — novel spatial domain from clustering with no histological correlate
- T4: Exploratory or artifact-prone — low-UMI edge spots, domains driven by batch effects
Interpretation Guidance
Spatial domains: Domains represent regions of coherent gene expression, often corresponding to tissue architecture (tumor core, stroma, immune infiltrate, necrosis). A domain is biologically meaningful when its marker genes align with known cell type signatures. Domains at tissue boundaries (e.g., tumor-stroma interface) are particularly informative for microenvironment studies.
Cell-cell proximity significance: Neighborhood enrichment z-scores > 2 indicate cell types co-localize more than expected by chance. Negative z-scores indicate spatial avoidance. Interpret in biological context: immune cell enrichment near tumor cells may indicate active immune response or immunosuppressive niche depending on the cell types involved (e.g., CD8+ T cells vs. Tregs).
Spatially variable genes (SVGs): Moran's I > 0.3 with FDR < 0.05 indicates strong spatial patterning. Classify SVGs by pattern: gradients (morphogen signaling, e.g., WNT along crypt-villus axis), hotspots (focal expression in immune aggregates), boundary genes (enriched at domain interfaces, e.g., epithelial-mesenchymal transition markers). SVGs with known spatial biology roles (e.g., tissue polarity genes) are higher confidence than novel candidates.
Synthesis Questions
A complete spatial transcriptomics report should answer: 1. What spatial domains were identified, and do they correspond to known tissue architecture? 2. Which genes show significant spatial variability, and what pattern types do they exhibit? 3. Are specific cell type pairs enriched or depleted in spatial proximity? 4. What ligand-receptor interactions are active at domain boundaries or cell-cell interfaces? 5. How do spatial findings compare to bulk or single-cell data from the same tissue type?
---
Programmatic Access (Beyond Tools)
When ToolUniverse tools return metadata but you need the actual expression matrices:
import scanpy as sc, pandas as pd, requests, io
# Load h5ad (most common format for spatial/single-cell)
adata = sc.read_h5ad("spatial_data.h5ad")
# Load 10X Visium output directory
adata = sc.read_visium("path/to/spaceranger_output/")
# Download from GEO supplementary files
geo_id = "GSE123456"
# Check for h5ad or MTX in supplementary files
url = f"https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc={geo_id}&targ=gsm&view=data"
# Load 10X MTX format (matrix + barcodes + features)
adata = sc.read_10x_mtx("filtered_feature_bc_matrix/", var_names="gene_symbols")
# HuBMAP data portal
# Search at https://portal.hubmapconsortium.org/search then download via globus or direct link
# Human Cell Atlas: https://data.humancellatlas.org/ — download h5ad/loom filesSee tooluniverse-data-wrangling skill for format cookbook and bulk download patterns.
---
Limitations
- Resolution: Visium spots contain multiple cells (not single-cell)
- Gene coverage: Imaging methods have limited gene panels
- 3D structure: Most platforms are 2D sections
- Tissue quality: Requires well-preserved tissue for imaging
- Computational: Large datasets require significant memory
- Reference dependency: Deconvolution quality depends on scRNA-seq reference
---
References
Methods:
- Squidpy: https://doi.org/10.1038/s41592-021-01358-2
- Cell2location: https://doi.org/10.1038/s41587-021-01139-4
- SpatialDE: https://doi.org/10.1038/nmeth.4636
Platforms:
- 10x Visium: https://www.10xgenomics.com/products/spatial-gene-expression
- MERFISH: https://doi.org/10.1126/science.aaa6090
- Slide-seq: https://doi.org/10.1126/science.aaw1219
---
Reference Files
- code_examples.md - Python code for all phases (scanpy, squidpy, cell2location)
- report_template.md - Full example report (breast cancer TME)
Spatial Transcriptomics Code Examples
Phase 1: Data Import & Quality Control
Data Loading (Visium)
def load_visium_data(data_dir):
"""
Load 10x Visium spatial transcriptomics data.
Expected structure:
data_dir/
├── filtered_feature_bc_matrix/
│ ├── barcodes.tsv.gz
│ ├── features.tsv.gz
│ └── matrix.mtx.gz
├── spatial/
│ ├── tissue_positions_list.csv
│ ├── scalefactors_json.json
│ └── tissue_hires_image.png
Returns: AnnData object with spatial coordinates
"""
import scanpy as sc
adata = sc.read_visium(data_dir)
return adataQuality Control
def spatial_qc(adata):
"""Quality control for spatial transcriptomics data."""
import scanpy as sc
sc.pp.calculate_qc_metrics(adata, inplace=True)
sc.pl.spatial(adata, color='n_genes_by_counts', title='Genes per Spot')
sc.pl.spatial(adata, color='total_counts', title='UMI Counts per Spot')
sc.pp.filter_cells(adata, min_genes=200)
sc.pp.filter_cells(adata, min_counts=500)
adata.var['mt'] = adata.var_names.str.startswith('MT-')
sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], inplace=True)
adata = adata[adata.obs['pct_counts_mt'] < 20].copy()
return adataSpatial Alignment Verification
def verify_spatial_alignment(adata):
"""Verify spatial coordinates align with tissue image."""
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10, 10))
img = adata.uns['spatial']['tissue_hires_image']
ax.imshow(img)
coords = adata.obsm['spatial']
ax.scatter(coords[:, 0], coords[:, 1], c='red', s=1, alpha=0.5)
ax.set_title('Spatial Alignment Verification')
plt.axis('off')Phase 2: Preprocessing & Normalization
Normalization
def normalize_spatial(adata):
"""Normalize spatial transcriptomics data."""
import scanpy as sc
sc.pp.filter_genes(adata, min_cells=3)
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
adata.raw = adata
return adataHighly Variable Genes
def select_hvg_spatial(adata):
"""Select highly variable genes for spatial analysis."""
import scanpy as sc
sc.pp.highly_variable_genes(adata, n_top_genes=2000)
return adataSpatial Smoothing
def spatial_smooth(adata, radius=2):
"""Smooth expression by averaging over spatial neighbors."""
from sklearn.neighbors import NearestNeighbors
coords = adata.obsm['spatial']
nn = NearestNeighbors(n_neighbors=radius, metric='euclidean')
nn.fit(coords)
distances, indices = nn.kneighbors(coords)
X_smooth = adata.X.copy()
for i in range(adata.n_obs):
neighbors = indices[i]
X_smooth[i] = adata.X[neighbors].mean(axis=0)
adata.layers['smoothed'] = X_smooth
return adataPhase 3: Spatial Clustering
def spatial_clustering(adata, n_neighbors=6):
"""Cluster spots into spatial domains using expression + spatial proximity."""
import scanpy as sc
import squidpy as sq
sc.pp.pca(adata, n_comps=50)
sq.gr.spatial_neighbors(adata, coord_type='generic', n_neighs=n_neighbors)
sc.tl.leiden(adata, resolution=1.0, key_added='spatial_domain')
sc.pl.spatial(adata, color='spatial_domain', title='Spatial Domains')
return adata
def find_domain_markers(adata):
"""Identify marker genes for each spatial domain."""
import scanpy as sc
sc.tl.rank_genes_groups(adata, groupby='spatial_domain', method='wilcoxon')
markers = sc.get.rank_genes_groups_df(adata, group=None)
return markersPhase 4: Spatially Variable Genes
def identify_spatial_genes(adata):
"""Test for spatial autocorrelation using Moran's I."""
import squidpy as sq
sq.gr.spatial_autocorr(adata, mode='moran', n_perms=100, n_jobs=-1)
spatial_genes = adata.uns['moranI'].sort_values('I', ascending=False)
sig_spatial = spatial_genes[spatial_genes['pval_norm_fdr_bh'] < 0.05]
return sig_spatial
def classify_spatial_patterns(adata, spatial_genes):
"""Classify types of spatial patterns: Gradient, Hotspot, Boundary, Periodic."""
patterns = {}
for gene in spatial_genes.index[:100]:
expr = adata[:, gene].X.toarray().flatten()
coords = adata.obsm['spatial']
pattern_type = detect_pattern_type(expr, coords)
patterns[gene] = pattern_type
return patternsPhase 5: Neighborhood Analysis
def analyze_neighborhoods(adata, radius=150):
"""Analyze spatial neighborhood composition."""
import squidpy as sq
sq.gr.nhood_enrichment(adata, cluster_key='spatial_domain')
sq.pl.nhood_enrichment(adata, cluster_key='spatial_domain')
return adata
def identify_interaction_zones(adata, domain_a, domain_b):
"""Find boundary regions between two spatial domains."""
from sklearn.neighbors import NearestNeighbors
spots_a = adata.obs['spatial_domain'] == domain_a
spots_b = adata.obs['spatial_domain'] == domain_b
coords = adata.obsm['spatial']
nn = NearestNeighbors(n_neighbors=6)
nn.fit(coords)
distances, indices = nn.kneighbors(coords)
interaction_spots = []
for i, spot_in_a in enumerate(spots_a):
if spot_in_a:
neighbors = indices[i]
if any(spots_b[neighbors]):
interaction_spots.append(i)
adata.obs['interaction_zone'] = False
adata.obs.loc[interaction_spots, 'interaction_zone'] = True
return adataPhase 6: Integration with Single-Cell RNA-seq
def deconvolve_cell_types(adata_spatial, adata_sc):
"""Predict cell type composition per spatial spot using cell2location."""
import cell2location
cell_type_signatures = extract_signatures(adata_sc)
mod = cell2location.models.Cell2location(
adata_spatial, cell_state_df=cell_type_signatures
)
mod.train(max_epochs=30000)
adata_spatial.obsm['cell_type_fractions'] = mod.get_cell_type_fractions()
return adata_spatial
def map_cell_types_spatial(adata):
"""Visualize cell type spatial distributions."""
import scanpy as sc
cell_types = adata.obsm['cell_type_fractions'].columns
for ct in cell_types:
sc.pl.spatial(
adata,
color=adata.obsm['cell_type_fractions'][ct],
title=f'{ct} Spatial Distribution'
)Phase 7: Spatial Cell Communication
def spatial_cell_communication(adata):
"""Identify cell-cell communication based on spatial proximity."""
import squidpy as sq
from tooluniverse import ToolUniverse
tu = ToolUniverse()
lr_pairs = tu.run_one_function({
"name": "OmniPath_get_ligand_receptor_interactions",
"arguments": {"partners": ""}
})
sq.gr.ligrec(
adata, n_perms=100, cluster_key='cell_type',
interactions=lr_pairs, copy=False
)
sq.pl.ligrec(adata, cluster_key='cell_type')
return adata
def map_communication_hotspots(adata, ligand, receptor):
"""Map spatial locations of specific L-R interactions."""
ligand_expr = adata[:, ligand].X.toarray().flatten()
receptor_expr = adata[:, receptor].X.toarray().flatten()
interaction_score = ligand_expr * receptor_expr
adata.obs[f'{ligand}_{receptor}_score'] = interaction_score
sc.pl.spatial(adata, color=f'{ligand}_{receptor}_score',
title=f'{ligand}-{receptor} Interaction Hotspots')Spatial Transcriptomics Report Template
Example Report: Breast Cancer Tumor Section
# Spatial Transcriptomics Analysis Report
## Dataset Summary
- **Platform**: 10x Visium
- **Tissue**: Breast cancer tumor section
- **Spots**: 3,562 (after QC filtering)
- **Genes**: 18,432 detected
- **Resolution**: 55um spot diameter (~50 cells/spot)
## Quality Control
- **Mean genes per spot**: 3,245
- **Mean UMI counts**: 12,543
- **Mitochondrial content**: 8.2% average
- **Tissue coverage**: 85% of capture area
## Spatial Domains Identified
- **7 distinct spatial domains** detected via graph-based clustering
- Domain 1: Tumor core (32% of tissue)
- Domain 2: Invasive margin (18%)
- Domain 3: Stromal region (25%)
- Domain 4: Immune infiltrate (12%)
- Domain 5: Necrotic region (8%)
- Domain 6: Normal epithelium (3%)
- Domain 7: Adipose tissue (2%)
## Top Marker Genes per Domain
### Domain 1 (Tumor Core)
- EPCAM, KRT19, MKI67, CCNB1, TOP2A (proliferative tumor)
### Domain 2 (Invasive Margin)
- VIM, FN1, MMP2, SNAI2 (EMT signature)
### Domain 4 (Immune Infiltrate)
- CD3D, CD8A, CD4, PTPRC (T cell enriched)
- CD68, CD14 (macrophage enriched)
## Spatially Variable Genes
- **456 genes with significant spatial patterns** (Moran's I, FDR < 0.05)
### Top 10 Spatial Genes
1. **MKI67** (I=0.82) - Hotspot pattern in tumor core
2. **CD8A** (I=0.78) - Gradient from margin to stroma
3. **VIM** (I=0.75) - Boundary enrichment at invasive margin
4. **COL1A1** (I=0.71) - Stromal-specific expression
5. **EPCAM** (I=0.69) - Tumor region pattern
## Cell Type Deconvolution
Integration with scRNA-seq reference (Bassez et al. 2021)
### Cell Type Spatial Distributions
- **Tumor cells**: Concentrated in core, sparse at margin
- **T cells**: Enriched at invasive margin and infiltrate zones
- **CAFs**: Stromal region and invasive margin
- **Macrophages**: Scattered, enriched near necrosis
- **B cells**: Lymphoid aggregates (2% of tissue)
### Tumor Microenvironment Composition
- Tumor core: 85% tumor cells, 10% CAFs, 5% immune
- Invasive margin: 45% tumor, 30% CAFs, 25% immune (T cell rich)
- Immune infiltrate: 70% T cells, 20% macrophages, 10% B cells
## Spatial Cell Communication
### Top L-R Interactions (Spatially Proximal)
1. **Tumor -> T cell**: CD274 (PD-L1) -> PDCD1 (PD-1)
- Hotspot: Invasive margin
- Interpretation: Immune checkpoint evasion
2. **CAF -> Tumor**: TGFB1 -> TGFBR2
- Hotspot: Stromal-tumor interface
- Interpretation: TGF-B-driven EMT
3. **Macrophage -> Tumor**: TNF -> TNFRSF1A
- Scattered across tumor
- Interpretation: Inflammatory signaling
### Interaction Zones
- **Tumor-Immune Interface**: 245 spots (7% of tissue)
- High expression: CXCL10, CXCL9 (chemokines)
- T cell recruitment and activation
- **Stromal-Tumor Interface**: 387 spots (11% of tissue)
- High expression: MMP2, MMP9 (matrix remodeling)
- Invasion-promoting niche
## Spatial Gradients
- **Hypoxia gradient**: HIF1A, VEGFA increase toward tumor core
- **Proliferation gradient**: MKI67, TOP2A decrease from core to margin
- **Immune gradient**: CD8A, GZMB peak at invasive margin
## Biological Interpretation
Spatial analysis reveals distinct tumor microenvironment organization:
1. **Tumor core**: Highly proliferative, hypoxic, immune-excluded
2. **Invasive margin**: Active EMT, high immune infiltration, checkpoint expression
3. **Stromal barrier**: CAF-rich, matrix remodeling, immunosuppressive signals
The invasive margin shows hallmarks of immune-tumor interaction with
PD-L1/PD-1 checkpoint engagement, suggesting potential for checkpoint
blockade therapy. CAF-mediated TGF-B signaling may drive EMT and therapy
resistance at tumor-stroma interface.
## Clinical Relevance
- **Checkpoint inhibitor response**: High immune infiltration at margin suggests potential
- **Resistance mechanisms**: CAF barrier and TGF-B signaling
- **Biomarkers**: Spatial arrangement of immune cells more predictive than bulk tumor metricsRelated skills
How it compares
Choose tooluniverse-spatial-transcriptomics over bulk RNA-seq skills when spatial coordinates and tissue architecture must drive interpretation.
FAQ
What does tooluniverse-spatial-transcriptomics analyze?
tooluniverse-spatial-transcriptomics analyzes spatially resolved gene expression maps to connect cell programs with tissue architecture, microenvironment niches, and regional pathology. Developers use the ToolUniverse skill when heterogeneous tissue samples need spatial context b
When should developers use spatial transcriptomics skills?
Developers should use tooluniverse-spatial-transcriptomics when spatial coordinates and tissue structure must inform gene expression interpretation. The skill targets complex samples where regional pathology and niche structure matter for downstream modeling.