agentleFS
shaoleishenshaoleishen/scrna-skills/skills/spatial-neighborhood-analysis/SKILL.md

spatial-neighborhood-analysis

Skill4 starsChanged 5 months agoMITView on GitHub

Spatial transcriptomics neighborhood and domain analysis. Computes spatial neighbor graphs, identifies spatially variable genes, performs spatial clustering, analyzes cell type co-occurrence patterns, and generates spatial visualizations. Supports multiplex imaging (MIBI/IMC) and sequencing-based (Visium) data.

The file

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 3 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Always verify spatial coordinates exist in obsm["spatial"] before any analysis — auto-detect from obs columns if missing.

    line 36
  2. Distinctive:

    Mixing coordinate units: Ensure all coordinates are in the same unit (um preferred).

    line 43
  3. Distinctive:

    Ignoring multi-section data: If multiple FOVs/sections exist, add a section label and process each independently.

    line 45
  4. Very specific:

    No spatial coordinates: Check obs columns for coordinate names.

    line 298
  5. Distinctive:

    Scale mismatch: Ensure coordinates are in same units (μm preferred)

    line 300

≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Spatial Neighborhood & Domain Analysis

When to Use

  • Analyzing spatial transcriptomics data (Visium, MERFISH, MIBI, IMC, Xenium)
  • Identifying spatial domains and tissue regions
  • Finding spatially variable genes
  • Analyzing cell type co-occurrence and spatial patterns
  • Building cell-cell proximity networks in tissue context

Do NOT use when you need to:

  • 分析非空间单细胞数据 → (use scrna-clustering-umap)
  • 需要细胞类型反卷积 → (use cell2location MCP server)
  • 需要配体受体通讯分析 → (use scrna-cell-communication)
  • 数据没有空间坐标 → (use scrna-qc-preprocess + scrna-clustering-umap)

Prerequisites

  • Python >= 3.10
  • Required packages: scanpy, squidpy, numpy, pandas, scipy, matplotlib, seaborn
  • Input: h5ad file with spatial coordinates in obsm["spatial"] or coordinate columns in obs

Core Rules

  1. Always verify spatial coordinates exist in obsm["spatial"] before any analysis — auto-detect from obs columns if missing.
  2. Choose coord_type appropriately: "grid" for Visium, "generic" for multiplex imaging (MIBI/IMC/MERFISH/Xenium).
  3. Analyze each tissue section/ROI separately if multiple sections are present — do not mix spatial graphs across sections.
  4. Adjust n_neighs based on data density: 6 for sparse, 10-15 for dense single-cell resolution data.

Common Mistakes

  • Mixing coordinate units: Ensure all coordinates are in the same unit (um preferred); do not mix pixel and physical coordinates.
  • Using wrong coord_type: Visium spots form a regular grid — use coord_type="grid", not "generic".
  • Ignoring multi-section data: If multiple FOVs/sections exist, add a section label and process each independently.

Troubleshooting

问题原因解决方案
No spatial coordinates foundCoordinates not in standard locationCheck obs columns; manually set adata.obsm["spatial"]
Memory error on spatial graphToo many cellsSubsample cells or use radius instead of n_neighs
Moran's I gives all NaNConstant expression or zero varianceFilter lowly expressed genes before spatial autocorrelation test
Co-occurrence plot emptyToo few cells per typeMerge rare cell types or increase radius threshold

Output

写入 --output 指定的 JSON 文件:

{
  "skill": "spatial-neighborhood-analysis",
  "status": "success",
  "steps": ["load_data", "build_spatial_graph", "spatially_variable_genes", "spatial_clustering", "co_occurrence", "neighborhood_enrichment", "visualization", "save"],
  "result": {
    "input_file": "spatial.h5ad",
    "output_file": "spatial_analyzed.h5ad",
    "n_cells": 50000,
    "n_spatial_domains": 8,
    "n_spatially_variable_genes": 150,
    "spatial_coordinates_key": "obsm['spatial']",
    "coord_type": "generic",
    "plots": ["spatial_domains.png", "spatially_variable_genes.png", "co_occurrence.png", "neighborhood_enrichment.png", "cell_type_spatial_map.png"]
  }
}

Workflow

Step 1: Load Spatial Data

import scanpy as sc
import squidpy as sq
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import sparse

adata = sc.read_h5ad("spatial.h5ad")

# Identify spatial coordinates
# Method 1: stored in obsm['spatial'] (standard)
# Method 2: stored in obs columns (e.g., cell_x_um, cell_y_um)
if "spatial" not in adata.obsm:
    # Try common coordinate column names
    coord_candidates = [
        ("cell_x_um", "cell_y_um"),
        ("x", "y"),
        ("X_centroid", "Y_centroid"),
        ("spatial_x", "spatial_y"),
    ]
    for x_col, y_col in coord_candidates:
        if x_col in adata.obs.columns and y_col in adata.obs.columns:
            adata.obsm["spatial"] = adata.obs[[x_col, y_col]].values
            print(f"Using {x_col}, {y_col} as spatial coordinates")
            break

assert "spatial" in adata.obsm, "No spatial coordinates found"
print(f"Spatial data: {adata.shape}")
print(f"Coordinate range: x [{adata.obsm['spatial'][:, 0].min():.1f}, {adata.obsm['spatial'][:, 0].max():.1f}], "
      f"y [{adata.obsm['spatial'][:, 1].min():.1f}, {adata.obsm['spatial'][:, 1].max():.1f}]")

Step 2: Build Spatial Neighbor Graph

# Compute spatial neighbors using Delaunay triangulation or k-nearest
sq.gr.spatial_neighbors(
    adata,
    n_neighs=6,           # number of spatial neighbors
    coord_type="generic",  # use "grid" for Visium
    delaunay=True,         # Delaunay triangulation
)

print(f"Spatial graph: {adata.obsp['spatial_connectivities'].shape}")
print(f"Non-zero edges: {adata.obsp['spatial_connectivities'].nnz}")

Step 3: Spatially Variable Gene Detection

# Moran's I test for spatial autocorrelation
sq.gr.spatial_autocorr(
    adata,
    mode="moran",
    n_perms=100,
    n_jobs=4,
)

# Top spatially variable genes
if "moranI" in adata.uns:
    moran_df = adata.uns["moranI"].sort_values("I", ascending=False)
    print("\nTop 20 spatially variable genes (Moran's I):")
    print(moran_df.head(20)[["I", "pval_norm"]].to_string())

    # Save results
    moran_df.to_csv("spatially_variable_genes.csv")

    # Plot top SVGs
    top_genes = moran_df.head(6).index.tolist()
    fig, axes = plt.subplots(2, 3, figsize=(18, 12))
    for i, gene in enumerate(top_genes):
        r, c = divmod(i, 3)
        sc.pl.spatial(adata, color=gene, ax=axes[r, c], show=False, title=gene)
    plt.tight_layout()
    plt.savefig("spatially_variable_genes.png", dpi=150, bbox_inches="tight")
    plt.close()

Step 4: Spatial Clustering (Domain Detection)

# Leiden clustering on spatial graph
sc.tl.leiden(
    adata,
    resolution=0.5,
    key_added="spatial_domain",
    adjacency=adata.obsp["spatial_connectivities"],
    flavor="igraph",
    n_iterations=2,
)

print(f"Spatial domains: {adata.obs['spatial_domain'].nunique()}")

# Visualize spatial domains
fig, axes = plt.subplots(1, 2, figsize=(16, 6))

# Spatial coordinates plot
coords = adata.obsm["spatial"]
scatter = axes[0].scatter(
    coords[:, 0], coords[:, 1],
    c=adata.obs["spatial_domain"].astype(int),
    cmap="tab20", s=1, alpha=0.7
)
axes[0].set_title("Spatial Domains")
axes[0].set_xlabel("X")
axes[0].set_ylabel("Y")

# Compare with cell types if available
ct_col = None
for col in ["cell_type", "celltype", "Classification", "cell_type_coarse"]:
    if col in adata.obs.columns:
        ct_col = col
        break

if ct_col:
    ct_codes = adata.obs[ct_col].astype("category").cat.codes
    axes[1].scatter(
        coords[:, 0], coords[:, 1],
        c=ct_codes, cmap="tab20", s=1, alpha=0.7
    )
    axes[1].set_title(f"Cell Types ({ct_col})")
    axes[1].set_xlabel("X")
    axes[1].set_ylabel("Y")

plt.tight_layout()
plt.savefig("spatial_domains.png", dpi=150, bbox_inches="tight")
plt.close()

Step 5: Cell Type Co-occurrence Analysis

if ct_col:
    # Compute co-occurrence scores
    sq.gr.co_occurrence(
        adata,
        cluster_key=ct_col,
    )

    # Plot co-occurrence
    sq.pl.co_occurrence(
        adata,
        cluster_key=ct_col,
        figsize=(10, 8),
        save="co_occurrence.png",
    )

Step 6: Neighborhood Enrichment Test

if ct_col:
    # Neighborhood enrichment (are cell types spatially associated?)
    sq.gr.nhood_enrichment(adata, cluster_key=ct_col)

    # Plot
    sq.pl.nhood_enrichment(
        adata,
        cluster_key=ct_col,
        figsize=(10, 8),
        save="neighborhood_enrichment.png",
    )

Step 7: Spatial Visualization

# Cell type spatial map
if ct_col:
    fig, ax = plt.subplots(figsize=(10, 10))
    ct_categories = adata.obs[ct_col].astype("category")
    colors = plt.cm.tab20(np.linspace(0, 1, len(ct_categories.cat.categories)))

    for i, ct in enumerate(ct_categories.cat.categories):
        mask = ct_categories == ct
        ax.scatter(
            coords[mask, 0], coords[mask, 1],
            c=[colors[i]], label=ct, s=1, alpha=0.7
        )
    ax.legend(markerscale=10, fontsize=8, bbox_to_anchor=(1.05, 1))
    ax.set_title("Cell Type Spatial Map")
    ax.set_xlabel("X (μm)")
    ax.set_ylabel("Y (μm)")
    plt.savefig("cell_type_spatial_map.png", dpi=150, bbox_inches="tight")
    plt.close()

Step 8: Save Results

adata.write_h5ad("spatial_analyzed.h5ad")
print(f"Saved: {adata.shape}")

Key Parameters

ParameterDefaultNotes
n_neighs6Increase for denser tissues; decrease for sparse
coord_type"generic"Use "grid" for Visium spots
resolution0.5Lower for broad domains; higher for fine regions
n_perms100Increase for publication quality

Data Type Specific Notes

Data Typecoord_typen_neighsNotes
Visium"grid"6Regular hexagonal grid
MERFISH"generic"10-15Dense single-cell
MIBI/IMC"generic"6-10Multiplex imaging
Xenium"generic"10-15In situ sequencing
Slide-seq"generic"15-20Sparse beads

Common Issues

  • No spatial coordinates: Check obs columns for coordinate names; set adata.obsm["spatial"]
  • Memory issues: Subsample cells or use sq.gr.spatial_neighbors with radius instead of n_neighs
  • Scale mismatch: Ensure coordinates are in same units (μm preferred)
  • ROI/section handling: Analyze each section separately, or add section label

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.