bio-imaging-mass-cytometry-spatial-analysis
Spatial analysis of cell neighborhoods and interactions in IMC data. Covers neighbor graphs, spatial statistics, and interaction testing. Use when analyzing spatial relationships between cell types, testing for neighborhood enrichment, or identifying cell-cell interaction patterns in imaging mass cytometry data.
Best use case
bio-imaging-mass-cytometry-spatial-analysis is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Spatial analysis of cell neighborhoods and interactions in IMC data. Covers neighbor graphs, spatial statistics, and interaction testing. Use when analyzing spatial relationships between cell types, testing for neighborhood enrichment, or identifying cell-cell interaction patterns in imaging mass cytometry data.
Teams using bio-imaging-mass-cytometry-spatial-analysis 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-imaging-mass-cytometry-spatial-analysis/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How bio-imaging-mass-cytometry-spatial-analysis Compares
| Feature / Agent | bio-imaging-mass-cytometry-spatial-analysis | 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?
Spatial analysis of cell neighborhoods and interactions in IMC data. Covers neighbor graphs, spatial statistics, and interaction testing. Use when analyzing spatial relationships between cell types, testing for neighborhood enrichment, or identifying cell-cell interaction patterns in imaging mass cytometry data.
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
Best AI Skills for ChatGPT
Find the best AI skills to adapt into ChatGPT workflows for research, writing, summarization, planning, and repeatable assistant tasks.
AI Agent for Product Research
Browse AI agent skills for product research, competitive analysis, customer discovery, and structured product decision support.
AI Agent for SaaS Idea Validation
Use AI agent skills for SaaS idea validation, market research, customer discovery, competitor analysis, and documenting startup hypotheses.
SKILL.md Source
## Version Compatibility
Reference examples tested with: anndata 0.10+, matplotlib 3.8+, numpy 1.26+, pandas 2.2+, scanpy 1.10+, 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 Analysis for IMC
**"Analyze spatial cell interactions in my IMC data"** → Build spatial neighborhood graphs, test for cell-cell interaction enrichment, and identify spatial domains from multiplexed imaging data.
- Python: `squidpy.gr.spatial_neighbors()`, `squidpy.gr.nhood_enrichment()`
## Build Spatial Graph
```python
import squidpy as sq
import anndata as ad
# Load phenotyped data
adata = ad.read_h5ad('imc_phenotyped.h5ad')
# Ensure spatial coordinates are set
# adata.obsm['spatial'] should contain (x, y) coordinates
# Build spatial neighbor graph
sq.gr.spatial_neighbors(adata, coord_type='generic', delaunay=True)
# Or by distance
sq.gr.spatial_neighbors(adata, coord_type='generic', radius=50) # 50 pixels
print(f'Built graph with {adata.obsp["spatial_connectivities"].nnz} edges')
```
## Neighborhood Enrichment
```python
# Test if cell types are enriched near each other
sq.gr.nhood_enrichment(adata, cluster_key='cell_type')
# Visualize
sq.pl.nhood_enrichment(adata, cluster_key='cell_type', save='nhood_enrichment.png')
# Get z-scores
zscore = adata.uns['cell_type_nhood_enrichment']['zscore']
# Positive: enriched, Negative: depleted
```
## Co-occurrence Analysis
```python
# Analyze co-occurrence of cell types at multiple distances
sq.gr.co_occurrence(adata, cluster_key='cell_type')
# Plot
sq.pl.co_occurrence(adata, cluster_key='cell_type', save='co_occurrence.png')
```
## Ripley's Statistics
```python
# Ripley's L function for spatial clustering
sq.gr.ripley(adata, cluster_key='cell_type', mode='L')
# Plot
sq.pl.ripley(adata, cluster_key='cell_type', save='ripley.png')
# Interpretation:
# L(r) > r: clustering at distance r
# L(r) < r: dispersion at distance r
# L(r) = r: random distribution
```
## Cell-Cell Interaction
```python
# Permutation test for interactions
sq.gr.interaction_matrix(adata, cluster_key='cell_type', normalized=True)
# Get interaction matrix
interaction = adata.uns['cell_type_interactions']
```
## Custom Neighborhood Analysis
**Goal:** Characterize the local cellular microenvironment around each cell by quantifying the cell type composition of its spatial neighbors.
**Approach:** Multiply the spatial connectivity matrix by a one-hot encoding of cell types, then normalize each row to produce fractional neighborhood composition vectors per cell.
```python
import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix
def neighborhood_composition(adata, cluster_key='cell_type'):
'''Calculate cell type composition of each cell's neighborhood'''
# Get connectivity matrix
conn = adata.obsp['spatial_connectivities']
cell_types = adata.obs[cluster_key]
type_categories = cell_types.cat.categories
# One-hot encode cell types
type_onehot = pd.get_dummies(cell_types).values
# Neighborhood composition = connectivity * one-hot
nhood_composition = conn @ type_onehot
# Normalize to fractions
nhood_sum = np.array(nhood_composition.sum(axis=1)).flatten()
nhood_sum[nhood_sum == 0] = 1 # Avoid division by zero
nhood_frac = nhood_composition / nhood_sum[:, np.newaxis]
# Add to adata
for i, ct in enumerate(type_categories):
adata.obs[f'nhood_frac_{ct}'] = nhood_frac[:, i]
return nhood_frac
nhood_frac = neighborhood_composition(adata)
```
## Spatial Clustering
```python
# Leiden clustering on spatial + expression
# Weight spatial vs molecular information
# Combined graph
sq.gr.spatial_neighbors(adata, coord_type='generic', radius=30)
# Run spatial Leiden
sc.tl.leiden(adata, adjacency=adata.obsp['spatial_connectivities'],
resolution=0.5, key_added='spatial_cluster')
```
## Interaction Hotspots
```python
def find_interaction_hotspots(adata, type1, type2, cluster_key='cell_type', radius=50):
'''Find regions with high interaction between two cell types'''
# Get cells of each type
mask1 = adata.obs[cluster_key] == type1
mask2 = adata.obs[cluster_key] == type2
spatial = adata.obsm['spatial']
# For each type1 cell, count nearby type2 cells
from scipy.spatial import cKDTree
tree2 = cKDTree(spatial[mask2])
interaction_scores = np.zeros(mask1.sum())
for i, (x, y) in enumerate(spatial[mask1]):
neighbors = tree2.query_ball_point([x, y], r=radius)
interaction_scores[i] = len(neighbors)
return interaction_scores
cd8_tumor_interactions = find_interaction_hotspots(adata, 'CD8 T cell', 'Tumor', radius=30)
```
## Visualize Spatial Patterns
```python
import matplotlib.pyplot as plt
# Spatial plot by cell type
sq.pl.spatial_scatter(adata, color='cell_type', size=3, save='spatial_celltypes.png')
# Multiple markers
sq.pl.spatial_scatter(adata, color=['CD8', 'CD4', 'CD68'], size=2, save='spatial_markers.png')
# Highlight specific interaction
fig, ax = plt.subplots(figsize=(10, 10))
spatial = adata.obsm['spatial']
# Background: all cells gray
ax.scatter(spatial[:, 0], spatial[:, 1], c='lightgray', s=1, alpha=0.5)
# Highlight: CD8 and Tumor
for ct, color in [('CD8 T cell', 'red'), ('Tumor', 'blue')]:
mask = adata.obs['cell_type'] == ct
ax.scatter(spatial[mask, 0], spatial[mask, 1], c=color, s=5, label=ct)
ax.legend()
ax.set_aspect('equal')
plt.savefig('cd8_tumor_spatial.png', dpi=150)
```
## Statistical Testing
```python
from scipy import stats
def spatial_association_test(adata, type1, type2, cluster_key='cell_type', n_perm=1000):
'''Permutation test for spatial association between cell types'''
# Observed interaction count
sq.gr.nhood_enrichment(adata, cluster_key=cluster_key)
obs_zscore = adata.uns[f'{cluster_key}_nhood_enrichment']['zscore']
idx1 = list(adata.obs[cluster_key].cat.categories).index(type1)
idx2 = list(adata.obs[cluster_key].cat.categories).index(type2)
observed = obs_zscore[idx1, idx2]
# The z-score is already normalized, so we can use it directly
# p-value from z-score
pvalue = 2 * (1 - stats.norm.cdf(abs(observed)))
return {'zscore': observed, 'pvalue': pvalue}
result = spatial_association_test(adata, 'CD8 T cell', 'Tumor')
print(f"CD8-Tumor association: z={result['zscore']:.2f}, p={result['pvalue']:.4f}")
```
## Export Results
```python
# Save spatial analysis results
adata.write('imc_spatial_analyzed.h5ad')
# Export neighborhood enrichment
nhood_df = pd.DataFrame(
adata.uns['cell_type_nhood_enrichment']['zscore'],
index=adata.obs['cell_type'].cat.categories,
columns=adata.obs['cell_type'].cat.categories
)
nhood_df.to_csv('neighborhood_enrichment.csv')
```
## Related Skills
- phenotyping - Assign cell types first
- spatial-transcriptomics/spatial-statistics - Similar spatial methods
- single-cell/cell-communication - Interaction conceptsRelated Skills
tooluniverse-variant-analysis
Production-ready VCF processing, variant annotation, mutation analysis, and structural variant (SV/CNV) interpretation for bioinformatics questions. Parses VCF files (streaming, large files), classifies mutation types (missense, nonsense, synonymous, frameshift, splice, intronic, intergenic) and structural variants (deletions, duplications, inversions, translocations), applies VAF/depth/quality/consequence filters, annotates with ClinVar/dbSNP/gnomAD/CADD via ToolUniverse, interprets SV/CNV clinical significance using ClinGen dosage sensitivity scores, computes variant statistics, and generates reports. Solves questions like "What fraction of variants with VAF < 0.3 are missense?", "How many non-reference variants remain after filtering intronic/intergenic?", "What is the pathogenicity of this deletion affecting BRCA1?", or "Which dosage-sensitive genes overlap this CNV?". Use when processing VCF files, annotating variants, filtering by VAF/depth/consequence, classifying mutations, interpreting structural variants, assessing CNV pathogenicity, comparing cohorts, or answering variant analysis questions.
tooluniverse-structural-variant-analysis
Comprehensive structural variant (SV) analysis skill for clinical genomics. Classifies SVs (deletions, duplications, inversions, translocations), assesses pathogenicity using ACMG-adapted criteria, evaluates gene disruption and dosage sensitivity, and provides clinical interpretation with evidence grading. Use when analyzing CNVs, large deletions/duplications, chromosomal rearrangements, or any structural variants requiring clinical interpretation.
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.
tooluniverse-proteomics-analysis
Analyze mass spectrometry proteomics data including protein quantification, differential expression, post-translational modifications (PTMs), and protein-protein interactions. Processes MaxQuant, Spectronaut, DIA-NN, and other MS platform outputs. Performs normalization, statistical analysis, pathway enrichment, and integration with transcriptomics. Use when analyzing proteomics data, comparing protein abundance between conditions, identifying PTM changes, studying protein complexes, integrating protein and RNA data, discovering protein biomarkers, or conducting quantitative proteomics experiments.
protein-interaction-network-analysis
Analyze protein-protein interaction networks using STRING, BioGRID, and SASBDB databases. Maps protein identifiers, retrieves interaction networks with confidence scores, performs functional enrichment analysis (GO/KEGG/Reactome), and optionally includes structural data. No API key required for core functionality (STRING). Use when analyzing protein networks, discovering interaction partners, identifying functional modules, or studying protein complexes.
tooluniverse-metabolomics-analysis
Analyze metabolomics data including metabolite identification, quantification, pathway analysis, and metabolic flux. Processes LC-MS, GC-MS, NMR data from targeted and untargeted experiments. Performs normalization, statistical analysis, pathway enrichment, metabolite-enzyme integration, and biomarker discovery. Use when analyzing metabolomics datasets, identifying differential metabolites, studying metabolic pathways, integrating with transcriptomics/proteomics, discovering metabolic biomarkers, performing flux balance analysis, or characterizing metabolic phenotypes in disease, drug response, or physiological conditions.
tooluniverse-immune-repertoire-analysis
Comprehensive immune repertoire analysis for T-cell and B-cell receptor sequencing data. Analyze TCR/BCR repertoires to assess clonality, diversity, V(D)J gene usage, CDR3 characteristics, convergence, and predict epitope specificity. Integrate with single-cell data for clonotype-phenotype associations. Use for adaptive immune response profiling, cancer immunotherapy research, vaccine response assessment, autoimmune disease studies, or repertoire diversity analysis in immunology research.
tooluniverse-image-analysis
Production-ready microscopy image analysis and quantitative imaging data skill for colony morphometry, cell counting, fluorescence quantification, and statistical analysis of imaging-derived measurements. Processes ImageJ/CellProfiler output (area, circularity, intensity, cell counts), performs Dunnett's test, Cohen's d effect size, power analysis, Shapiro-Wilk normality tests, two-way ANOVA, polynomial regression, natural spline regression with confidence intervals, and comparative morphometry. Supports CSV/TSV measurement tables, multi-channel fluorescence data, colony swarming assays, and neuron counting datasets. Use when analyzing microscopy measurement data, colony area/circularity, cell count statistics, swarming assays, co-culture ratio optimization, or answering questions about imaging-derived quantitative data.
tooluniverse-crispr-screen-analysis
Comprehensive CRISPR screen analysis for functional genomics. Analyze pooled or arrayed CRISPR screens (knockout, activation, interference) to identify essential genes, synthetic lethal interactions, and drug targets. Perform sgRNA count processing, gene-level scoring (MAGeCK, BAGEL), quality control, pathway enrichment, and drug target prioritization. Use for CRISPR screen analysis, gene essentiality studies, synthetic lethality detection, functional genomics, drug target validation, or identifying genetic vulnerabilities.
statistical-analysis
Statistical analysis toolkit. Hypothesis tests (t-test, ANOVA, chi-square), regression, correlation, Bayesian stats, power analysis, assumption checks, APA reporting, for academic research.
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.