agentleFS
shaoleishenshaoleishen/scrna-skills/skills/scrna-clustering-umap/SKILL.md

scrna-clustering-umap

Skill4 starsChanged 5 months agoMITView on GitHub

scRNA-seq clustering and dimensionality reduction. Builds neighbor graphs, runs Leiden/Louvain clustering at multiple resolutions, computes UMAP embeddings, and generates diagnostic plots. Supports Harmony batch correction integration.

The file

We split this skill into the rules it gives an agent

6 rules. About 0 are common, 3 are distinctive, and 3 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.

  • 3

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    After QC/preprocessing (need PCA embeddings)

    line 16
  2. Very specific:

    Always check if adata.X is sparse before operations.

    line 37
  3. Very specific:

    Verify X_pca exists before running neighbors — clustering without PCA will fail or produce meaningless results

    line 38
  4. Distinctive:

    Run multi-resolution Leiden clustering (0.3–1.5) and compare.

    line 39
  5. Very specific:

    Clustering without PCA: Always assert "X_pca" in adata.obsm before starting

    line 45
  6. Distinctive:

    Ignoring batch effects: If UMAP shows batch-driven separation, run Harmony before clustering

    line 47

≈ “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

scRNA-seq Clustering & UMAP

When to Use

  • After QC/preprocessing (need PCA embeddings)
  • Identifying cell populations through unsupervised clustering
  • Visualizing high-dimensional data in 2D (UMAP/tSNE)
  • Finding optimal clustering resolution
  • Comparing multiple clustering results

Do NOT use when you need to:

  • 从原始计数开始预处理 → (use scrna-qc-preprocess first)
  • 需要批次校正 → (use scrna-batch-correction before clustering)
  • 需要差异表达分析 → (use scrna-marker-genes after clustering)
  • 分析空间域而非表达聚类 → (use spatial-neighborhood-analysis)

Prerequisites

  • Python >= 3.10
  • Required packages: scanpy, anndata, numpy, matplotlib, leidenalg
  • Optional: harmonypy (batch correction)
  • Input: .h5ad file with PCA embeddings in adata.obsm["X_pca"] (output of scrna-qc-preprocess)

Core Rules

  1. Always check if adata.X is sparse before operations; prefer sparse-compatible code
  2. Verify X_pca exists before running neighbors — clustering without PCA will fail or produce meaningless results
  3. Run multi-resolution Leiden clustering (0.3–1.5) and compare; single resolution may miss biology
  4. Set sc.settings.seed = 42 before UMAP for reproducibility
  5. Save intermediate results to avoid re-computation (neighbor graph is expensive on large datasets)

Common Mistakes

  • Clustering without PCA: Always assert "X_pca" in adata.obsm before starting
  • Using only one resolution: Different biological questions need different granularities — always explore multiple resolutions
  • Ignoring batch effects: If UMAP shows batch-driven separation, run Harmony before clustering
  • Non-reproducible UMAP: Forgetting to set random seed produces different layouts each run

Troubleshooting

问题原因解决方案
AssertionError: no X_pcaData not preprocessedRun scrna-qc-preprocess first
Too many clusters (>50)Resolution too highLower resolution to 0.3–0.5
UMAP shows batch-driven separationBatch effects not correctedRun Harmony integration before neighbors
Disconnected UMAP islandsOutlier cells or too few neighborsIncrease n_neighbors to 20–30, or filter outlier cells

Output

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

{
  "skill": "scrna-clustering-umap",
  "status": "success",
  "steps": ["load", "batch_correction", "neighbors", "leiden_clustering", "umap", "diagnostics"],
  "result": {
    "output_h5ad": "path/to/clustered.h5ad",
    "n_cells": 5000,
    "n_clusters": 12,
    "resolutions_tested": [0.3, 0.5, 0.8, 1.0, 1.5],
    "selected_resolution": 1.0,
    "umap_plot": "path/to/clustering_umap.png"
  }
}

Workflow

Step 1: Load Preprocessed Data

import scanpy as sc
import numpy as np
import matplotlib.pyplot as plt

adata = sc.read_h5ad("preprocessed.h5ad")
assert "X_pca" in adata.obsm, "PCA embeddings required. Run QC preprocessing first."
print(f"Input: {adata.shape}, PCA dims: {adata.obsm['X_pca'].shape[1]}")

Step 2: Batch Correction (Optional)

# If multiple batches exist, run Harmony
if "batch" in adata.obs.columns and adata.obs["batch"].nunique() > 1:
    try:
        import harmonypy as hm
        sc.external.pp.harmony_integrate(adata, "batch", basis="X_pca", adjusted_basis="X_pca_harmony")
        use_embedding = "X_pca_harmony"
        print("Harmony correction applied")
    except ImportError:
        print("harmonypy not available, using uncorrected PCA")
        use_embedding = "X_pca"
else:
    use_embedding = "X_pca"

Step 3: Neighbor Graph Construction

# Compute neighbor graph
sc.pp.neighbors(
    adata,
    n_neighbors=15,
    n_pcs=30,
    use_rep=use_embedding,
    metric="euclidean",
)
print(f"Neighbor graph: {adata.obsp['connectivities'].shape}")

Step 4: Multi-Resolution Leiden Clustering

# Run Leiden at multiple resolutions
resolutions = [0.3, 0.5, 0.8, 1.0, 1.5]
for res in resolutions:
    key = f"leiden_{res}"
    sc.tl.leiden(adata, resolution=res, key_added=key, flavor="igraph", n_iterations=2)
    n_clusters = adata.obs[key].nunique()
    print(f"Resolution {res}: {n_clusters} clusters")

# Choose a resolution (default: 1.0, adjust based on biology)
adata.obs["leiden"] = adata.obs["leiden_1.0"]
print(f"Selected resolution 1.0: {adata.obs['leiden'].nunique()} clusters")

Step 5: UMAP Embedding

sc.tl.umap(adata, min_dist=0.3, spread=1.0)
print(f"UMAP shape: {adata.obsm['X_umap'].shape}")

Step 6: Diagnostic Plots

fig, axes = plt.subplots(2, 3, figsize=(18, 12))

# UMAP colored by cluster
sc.pl.umap(adata, color="leiden", ax=axes[0, 0], show=False, title="Leiden Clusters")

# UMAP colored by QC metrics
for i, col in enumerate(["n_genes_by_counts", "total_counts", "pct_counts_mt"]):
    if col in adata.obs.columns:
        r, c = divmod(i + 1, 3)
        sc.pl.umap(adata, color=col, ax=axes[r, c], show=False, title=col)

# Leiden resolution comparison
if "leiden_0.5" in adata.obs.columns:
    sc.pl.umap(adata, color="leiden_0.5", ax=axes[1, 1], show=False, title="Leiden 0.5")
if "leiden_1.5" in adata.obs.columns:
    sc.pl.umap(adata, color="leiden_1.5", ax=axes[1, 2], show=False, title="Leiden 1.5")

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

Step 7: Cluster Summary Statistics

# Summary per cluster
for cluster_key in ["leiden"]:
    summary = adata.obs.groupby(cluster_key).agg(
        n_cells=(cluster_key, "count"),
        mean_genes=("n_genes_by_counts", "mean"),
        mean_counts=("total_counts", "mean"),
        mean_mt=("pct_counts_mt", "mean"),
    ).round(2)
    print(f"\n{cluster_key} summary:")
    print(summary)

Step 8: Save Output

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

Choosing Clustering Resolution

ResolutionTypical Use
0.3-0.5Major cell types (5-10 clusters)
0.8-1.0Standard resolution (10-20 clusters)
1.0-1.5Cell subtypes (20-40 clusters)
1.5-2.0Fine-grained subpopulations (40+ clusters)

Key Parameters

ParameterDefaultNotes
n_neighbors15Lower = local structure; higher = global structure
n_pcs30Use elbow plot to determine; typically 20-50
min_dist (UMAP)0.3Lower = tighter clusters; higher = more spread
spread (UMAP)1.0Controls overall scale of embedding

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.