agentleFS
shaoleishenshaoleishen/scrna-skills/skills/scrna-marker-genes/SKILL.md

scrna-marker-genes

Skill4 starsChanged 5 months agoMITView on GitHub

Marker gene detection and cell type annotation for scRNA-seq. Performs differential expression between clusters, identifies canonical markers, generates dotplots/heatmaps, and supports reference-based cell type annotation with CellTypist or manual marker matching.

  • Installs packages

The file

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    After clustering to identify what each cluster represents

    line 16
  2. Very specific:

    Always check if adata.X is sparse before operations.

    line 36
  3. Very specific:

    Use adata.raw for DEG testing — it contains the full gene space, not just HVGs

    line 37
  4. Very specific:

    Check pct_in vs pct_out — a good marker should be expressed in a high fraction of target cells and low in others

    line 39
  5. Very specific:

    Running DEG on HVG-subset data: If adata.raw is None, DEG will only test ~2000 genes, missing key markers like CD3D or CD79A

    line 44

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

Marker Gene Detection & Cell Type Annotation

When to Use

  • After clustering to identify what each cluster represents
  • Finding differentially expressed genes between cell populations
  • Annotating clusters with cell type labels
  • Generating publication-quality marker plots

Do NOT use when you need to:

  • 数据未聚类 → (use scrna-clustering-umap first)
  • 需要细胞通讯分析 → (use scrna-cell-communication)
  • 需要轨迹推断 → (use scrna-trajectory-inference)
  • 需要基因调控网络 → (use scrna-gene-regulatory-network)

Prerequisites

  • Python >= 3.10
  • Required packages: scanpy, anndata, numpy, pandas, matplotlib, seaborn
  • Optional: celltypist (automated cell type annotation)
  • Input: .h5ad file with cluster labels in adata.obs (e.g., "leiden") and adata.raw populated with full gene-space normalized data (output of scrna-clustering-umap)

Core Rules

  1. Always check if adata.X is sparse before operations; prefer sparse-compatible code
  2. Use adata.raw for DEG testing — it contains the full gene space, not just HVGs
  3. Filter markers by both pval_adj < 0.05 AND logfc > 0.5 to avoid noise
  4. Check pct_in vs pct_out — a good marker should be expressed in a high fraction of target cells and low in others
  5. Save intermediate results (marker tables, annotation scores) to avoid re-computation

Common Mistakes

  • Running DEG on HVG-subset data: If adata.raw is None, DEG will only test ~2000 genes, missing key markers like CD3D or CD79A
  • Using only logFC for ranking: A gene with high logFC but low expression percentage is a poor marker — always check pct_in
  • Gene name mismatch: Human genes are uppercase (CD3D), mouse genes are mixed case (Cd3d) — verify organism before annotation
  • Over-trusting automated annotation: CellTypist models are trained on specific tissues; always validate with known markers

Troubleshooting

问题原因解决方案
No significant markers foundClusters are not biologically meaningfulRe-cluster at different resolution; check UMAP for cluster separation
Genes not found in var_namesGene naming convention mismatchCheck organism: human=uppercase, mouse=mixed case
All clusters annotated as same typeResolution too high; clusters are sub-typesLower resolution or merge similar clusters before annotation
CellTypist ImportErrorPackage not installedpip install celltypist or use manual marker-based annotation

Output

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

{
  "skill": "scrna-marker-genes",
  "status": "success",
  "steps": ["load", "deg_analysis", "top_markers", "dotplot", "heatmap", "umap_markers", "annotation"],
  "result": {
    "output_h5ad": "path/to/annotated.h5ad",
    "n_cells": 5000,
    "n_clusters": 12,
    "n_significant_markers": 245,
    "marker_csv": "path/to/significant_markers.csv",
    "cluster_annotations": {"0": "CD4 T cells", "1": "B cells", "2": "Monocytes"},
    "dotplot_png": "path/to/marker_dotplot.png"
  }
}

Workflow

Step 1: Load Clustered Data

import scanpy as sc
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

adata = sc.read_h5ad("clustered.h5ad")
assert "leiden" in adata.obs.columns, "Cluster labels required"

# Use raw for DEG testing (full gene space)
if adata.raw is not None:
    adata_for_deg = adata.raw.to_adata()
else:
    adata_for_deg = adata

Step 2: Rank Genes Groups (DEG Analysis)

# Run rank_genes_groups on full gene space
sc.tl.rank_genes_groups(
    adata_for_deg,
    groupby="leiden",
    method="wilcoxon",
    pts=True,  # include fraction of expressing cells
    use_raw=False,
)

# Extract results to DataFrame
result = adata_for_deg.uns["rank_genes_groups"]
groups = result["names"].dtype.names

marker_df = pd.DataFrame()
for group in groups:
    df = pd.DataFrame({
        "cluster": group,
        "gene": result["names"][group],
        "logfc": result["logfoldchanges"][group],
        "pval": result["pvals"][group],
        "pval_adj": result["pvals_adj"][group],
        "score": result["scores"][group],
        "pct_in": result["pts"][group] if "pts" in result else None,
        "pct_out": result["pts_rest"][group] if "pts_rest" in result else None,
    })
    marker_df = pd.concat([marker_df, df])

# Filter significant markers
markers_sig = marker_df[
    (marker_df["pval_adj"] < 0.05) & (marker_df["logfc"] > 0.5)
].copy()

# Save all markers
marker_df.to_csv("all_markers.csv", index=False)
markers_sig.to_csv("significant_markers.csv", index=False)
print(f"Total significant markers: {len(markers_sig)}")

Step 3: Top Markers Per Cluster

# Get top N markers per cluster
top_n = 10
top_markers = (
    markers_sig.groupby("cluster")
    .apply(lambda x: x.nlargest(top_n, "score"))
    .reset_index(drop=True)
)

# Print summary
for cluster in sorted(adata.obs["leiden"].unique(), key=int):
    genes = top_markers[top_markers["cluster"] == cluster]["gene"].tolist()
    print(f"Cluster {cluster}: {', '.join(genes[:5])}")

Step 4: Dotplot of Top Markers

# Select top 5 markers per cluster for visualization
plot_genes = (
    top_markers.groupby("cluster")
    .head(5)["gene"]
    .unique()
    .tolist()
)

# Dotplot
sc.pl.dotplot(
    adata,
    var_names=plot_genes,
    groupby="leiden",
    standard_scale="var",
    dendrogram=True,
    save="_marker_dotplot.png",
)

Step 5: Heatmap of Top Markers

# Heatmap of top 10 markers per cluster
sc.pl.heatmap(
    adata,
    var_names=top_markers.groupby("cluster").head(10)["gene"].unique().tolist(),
    groupby="leiden",
    standard_scale="var",
    show_gene_labels=True,
    figsize=(16, 12),
    save="_marker_heatmap.png",
)

Step 6: UMAP with Marker Genes

# Plot top marker genes on UMAP
fig, axes = plt.subplots(2, 3, figsize=(18, 12))
top6_genes = top_markers.head(6)["gene"].tolist()
for i, gene in enumerate(top6_genes):
    r, c = divmod(i, 3)
    sc.pl.umap(adata, color=gene, ax=axes[r, c], show=False, title=gene)
plt.tight_layout()
plt.savefig("marker_genes_umap.png", dpi=150, bbox_inches="tight")
plt.close()

Step 7: Cell Type Annotation (Manual with Known Markers)

# Define marker dictionaries for common tissues
# Example: PBMC markers
marker_dict = {
    "T cells": ["CD3D", "CD3E", "CD2"],
    "CD4 T": ["CD4", "IL7R"],
    "CD8 T": ["CD8A", "CD8B"],
    "NK cells": ["GNLY", "NKG7", "KLRD1"],
    "B cells": ["CD79A", "MS4A1", "CD19"],
    "Monocytes": ["CD14", "LYZ", "CSF1R"],
    "DC": ["FCER1A", "CST3", "CLEC10A"],
    "Platelets": ["PPBP", "PF4"],
}

# Score each cluster for each cell type
from collections import defaultdict

cluster_scores = defaultdict(dict)
for ct, genes in marker_dict.items():
    available_genes = [g for g in genes if g in adata_for_deg.var_names]
    if not available_genes:
        continue
    sc.tl.score_genes(adata_for_deg, available_genes, score_name=f"score_{ct}")
    for cluster in adata.obs["leiden"].unique():
        mask = adata_for_deg.obs["leiden"] == cluster
        cluster_scores[cluster][ct] = adata_for_deg.obs.loc[mask, f"score_{ct}"].mean()

# Assign best match
score_df = pd.DataFrame(cluster_scores).T
score_df["assigned_type"] = score_df.idxmax(axis=1)
print("\nCluster annotations:")
print(score_df[["assigned_type"]])

Step 8: CellTypist Annotation (Automated)

try:
    import celltypist
    from celltypist import models

    # Load model (first run downloads it)
    model = models.Model.load(model="Immune_All_Low.pkl")

    # Predict
    predictions = celltypist.annotate(
        adata_for_deg,
        model=model,
        majority_voting=True,
    )
    adata.obs["celltypist_label"] = predictions.predicted_labels["majority_voting"]
    print("CellTypist annotations added")
except ImportError:
    print("Celltypist not available, using manual annotation only")

Step 9: Save Annotated Data

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

Common Tissue Markers

TissueKey Markers
PBMC/ImmuneCD3D (T), CD79A (B), CD14 (Mono), NKG7 (NK), PPBP (Platelet)
BrainGFAP (Astro), MBP (Oligo), SNAP25 (Neuron), CSF1R (Microglia)
LiverALB (Hepatocyte), PECAM1 (Endothelial), COL1A1 (Stellate), CD68 (Kupffer)
LungSFTPC (AT2), AGER (AT1), SCGB1A4 (Club), FOXJ1 (Ciliated)
KidneyNPHS1 (Podocyte), SLC12A3 (DCT), AQP2 (CD-PC), SLCO4C1 (PT)
HeartTNNT2 (Cardiomyocyte), PECAM1 (Endo), COL1A1 (Fibro), CD68 (Macro)

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.