agentleFS
shaoleishenshaoleishen/scrna-skills/skills/scrna-gene-regulatory-network/SKILL.md

scrna-gene-regulatory-network

Skill4 starsChanged 5 months agoMITView on GitHub

Gene regulatory network inference for scRNA-seq. Implements SCENIC-like pipeline: co-expression module detection, transcription factor enrichment (ctx), and regulon activity scoring (AUCell). Identifies master regulators and cell-type-specific regulatory programs.

The file

We split this skill into the rules it gives an agent

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

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Always use raw counts or log-normalized data for correlation computation — never use batch-corrected embeddings.

    line 36
  2. Distinctive:

    Missing TF genes: Check gene naming conventions (case sensitivity)

    line 356

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

Gene Regulatory Network Inference (SCENIC-like)

When to Use

  • Identifying master transcription factors driving cell identity
  • Discovering co-regulated gene modules
  • Understanding regulatory programs active in different cell types
  • Comparing GRN activity across conditions

Do NOT use when you need to:

  • 只需要差异表达 → (use scrna-marker-genes)
  • 需要蛋白互作网络 → (use string_database skill)
  • 需要完整 SCENIC 管线(含 motif 分析) → (use pySCENIC MCP server)
  • 数据未聚类/注释 → (use scrna-clustering-umap + scrna-marker-genes first)

Prerequisites

  • Python >= 3.10
  • Required packages: scanpy, anndata, numpy, pandas, scipy, matplotlib, ctxcore; optional: networkx
  • Input: h5ad file with raw counts or normalized expression; cell type annotations in obs recommended

Core Rules

  1. This skill provides a simplified co-expression-based GRN — for publication-quality results with motif enrichment, use the full pySCENIC pipeline.
  2. Always use raw counts or log-normalized data for correlation computation — never use batch-corrected embeddings.
  3. Expand the TF list with tissue-specific transcription factors for your biological system; the default list is generic.
  4. Filter regulons by cell-type specificity — TFs active in all cells are not informative for understanding cell identity.

Common Mistakes

  • Using batch-corrected expression: Batch correction distorts gene-gene correlations; use raw or normalized (non-integrated) expression.
  • Too few TFs in the list: The default TF list covers common factors only — always add tissue-specific TFs.
  • Interpreting correlation as causation: Co-expression does not imply direct regulation; this is a hypothesis-generating tool.

Troubleshooting

问题原因解决方案
Very few TFs foundTF genes not in expression matrixCheck gene naming (case, aliases); expand gene list
All regulons have similar scoresTF targets are non-specificIncrease corr_threshold; filter by cell-type specificity
Memory error on correlation matrixToo many genesReduce top_n to 3000 or fewer; process in chunks
Missing TF genesGene name mismatch (e.g., ESR1 vs Esr1)Standardize gene names to uppercase before analysis

Output

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

{
  "skill": "scrna-gene-regulatory-network",
  "status": "success",
  "steps": ["load_data", "coexpression_modules", "tf_target_detection", "regulon_scoring", "cell_type_regulons", "network_visualization", "save"],
  "result": {
    "input_file": "annotated.h5ad",
    "output_file": "grn_annotated.h5ad",
    "n_cells": 15000,
    "n_tfs_with_targets": 25,
    "n_regulons": 30,
    "top_regulons": ["SPI1_regulon", "CEBPA_regulon", "GATA1_regulon"],
    "regulon_activities_csv": "regulon_activities.csv",
    "tf_targets_csv": "tf_targets.csv",
    "plots": ["regulon_heatmap.png", "grn_network.png"]
  }
}

Workflow

Step 1: Load Data

import scanpy as sc
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import sparse

adata = sc.read_h5ad("annotated.h5ad")
print(f"Input: {adata.shape}")

# Need raw counts or normalized data
if adata.raw is not None:
    expr_matrix = adata.raw.X
    gene_names = adata.raw.var_names.tolist()
else:
    expr_matrix = adata.X
    gene_names = adata.var_names.tolist()

print(f"Genes: {len(gene_names)}")

Step 2: Co-expression Module Detection

def compute_gene_correlation(expr_matrix, gene_names, top_n=5000):
    """Compute gene-gene correlation matrix for top variable genes."""
    from scipy.stats import spearmanr

    # Select top variable genes for efficiency
    if sparse.issparse(expr_matrix):
        variances = np.array(expr_matrix.toarray()).var(axis=0)
    else:
        variances = expr_matrix.var(axis=0)

    top_idx = np.argsort(variances)[-top_n:]
    top_genes = [gene_names[i] for i in top_idx]

    if sparse.issparse(expr_matrix):
        expr_sub = expr_matrix[:, top_idx].toarray()
    else:
        expr_sub = expr_matrix[:, top_idx]

    # Compute correlation
    corr_matrix = np.corrcoef(expr_sub.T)
    return corr_matrix, top_genes

corr_matrix, top_genes = compute_gene_correlation(expr_matrix, gene_names)
print(f"Correlation matrix: {corr_matrix.shape}")

Step 3: Define TF-Target Relationships

# Load known TF-target relationships (JASPAR/ENCODE-based)
# Simplified: use correlation-based approach
def find_tf_targets(corr_matrix, gene_names, tf_list, corr_threshold=0.15):
    """Find potential TF targets based on co-expression."""
    tf_targets = {}

    for tf in tf_list:
        if tf not in gene_names:
            continue
        tf_idx = gene_names.index(tf)
        tf_corr = corr_matrix[tf_idx]

        # Find genes correlated with this TF
        targets = []
        for i, (gene, corr) in enumerate(zip(gene_names, tf_corr)):
            if gene != tf and abs(corr) > corr_threshold:
                targets.append((gene, corr))

        if targets:
            tf_targets[tf] = sorted(targets, key=lambda x: abs(x[1]), reverse=True)

    return tf_targets

# Common human TFs (expandable)
COMMON_TFS = [
    "TP53", "MYC", "JUN", "FOS", "STAT3", "NFkB", "SPI1", "CEBPA", "CEBPB",
    "GATA1", "GATA2", "GATA3", "FOXP3", "TBX21", "BCL6", "IRF4", "IRF8",
    "PAX5", "EBF1", "RUNX1", "RUNX2", "SOX2", "SOX9", "SOX10", "NANOG",
    "POU5F1", "KLF4", "ETV1", "ETS1", "ETS2", "ERG", "FLI1",
    "HIF1A", "ARNT", "VHL", "NOTCH1", "NOTCH2", "WNT3A", "CTNNB1",
    "SMAD2", "SMAD3", "SMAD4", "TGFBR1", "TGFB1",
    "EGR1", "EGR2", "ATF3", "ATF4", "CREB1", "FOSL2", "JUND",
    "MAF", "MAFB", "BACH1", "NFE2", "NRF2", "KEAP1",
    "SNAI1", "SNAI2", "TWIST1", "ZEB1", "ZEB2",
    "RB1", "E2F1", "CDKN1A", "CDKN2A", "MDM2",
    "GLI1", "GLI2", "PTCH1", "SHH",
    "PPARG", "RXRA", "RARA", "VDR", "ESR1", "AR",
    "FOXO1", "FOXO3", "FOXO4", "FOXN1",
    "MITF", "PAX3", "PAX6", "DLX5", "HOXA9", "MEIS1",
]

tf_targets = find_tf_targets(corr_matrix, top_genes, COMMON_TFS)
print(f"TFs with targets: {len(tf_targets)}")
for tf, targets in list(tf_targets.items())[:5]:
    print(f"  {tf}: {len(targets)} targets")

Step 4: Regulon Activity Scoring (AUCell-like)

def compute_regulon_activity(adata, tf_targets, use_raw=True):
    """Compute regulon activity scores using AUCell-like approach."""
    data = adata.raw if use_raw and adata.raw else adata

    regulon_scores = {}
    for tf, targets in tf_targets.items():
        target_genes = [t[0] for t in targets[:50]]  # top 50 targets
        available = [g for g in target_genes if g in data.var_names]

        if len(available) < 5:
            continue

        # Compute enrichment score (mean expression of targets)
        if sparse.issparse(data.X):
            target_expr = data[:, available].X.toarray()
        else:
            target_expr = data[:, available].X

        # AUCell-like: rank-based enrichment
        from scipy.stats import rankdata
        ranks = np.apply_along_axis(rankdata, 0, target_expr)
        mean_rank = ranks.mean(axis=1)

        # Normalize to [0, 1]
        score = (mean_rank - mean_rank.min()) / (mean_rank.max() - mean_rank.min() + 1e-10)
        regulon_scores[f"{tf}_regulon"] = score

    return pd.DataFrame(regulon_scores, index=adata.obs_names)

regulon_activities = compute_regulon_activity(adata, tf_targets)
print(f"Regulon activities: {regulon_activities.shape}")

# Add to adata
for col in regulon_activities.columns:
    adata.obs[col] = regulon_activities[col]

Step 5: Cell-Type-Specific Regulons

ct_col = None
for col in ["cell_type", "celltype", "leiden", "cell_type_coarse"]:
    if col in adata.obs.columns:
        ct_col = col
        break

if ct_col:
    # Compute mean regulon activity per cell type
    ct_regulon = regulon_activities.groupby(adata.obs[ct_col]).mean()

    # Find top regulons per cell type
    print("\nTop regulons per cell type:")
    for ct in ct_regulon.index:
        top = ct_regulon.loc[ct].nlargest(5)
        print(f"  {ct}: {', '.join([f'{r}({v:.2f})' for r, v in top.items()])}")

    # Heatmap
    fig, ax = plt.subplots(figsize=(14, 8))
    # Select top regulons across all cell types
    top_regulons = ct_regulon.max().nlargest(30).index
    sns.heatmap(
        ct_regulon[top_regulons].T,
        cmap="YlOrRd",
        ax=ax,
        xticklabels=True,
        yticklabels=True,
    )
    ax.set_title("Regulon Activity by Cell Type")
    plt.savefig("regulon_heatmap.png", dpi=150, bbox_inches="tight")
    plt.close()

Step 6: GRN Network Visualization

import networkx as nx

# Build TF-target network for top regulons
G = nx.DiGraph()

# Select top regulons by activity
top_regulon_names = regulon_activities.max().nlargest(10).index

for regulon in top_regulon_names:
    tf = regulon.replace("_regulon", "")
    if tf not in tf_targets:
        continue

    targets = tf_targets[tf][:10]  # top 10 targets
    for target, corr in targets:
        G.add_edge(tf, target, weight=abs(corr))

# Plot
fig, ax = plt.subplots(figsize=(12, 12))
pos = nx.spring_layout(G, k=1.5, seed=42)

# Color TFs differently
tf_nodes = [n for n in G.nodes() if n in COMMON_TFS]
target_nodes = [n for n in G.nodes() if n not in COMMON_TFS]

nx.draw_networkx_nodes(G, pos, nodelist=tf_nodes, node_color="red",
                       node_size=300, ax=ax, label="TFs")
nx.draw_networkx_nodes(G, pos, nodelist=target_nodes, node_color="lightblue",
                       node_size=100, ax=ax, label="Targets")
nx.draw_networkx_labels(G, pos, font_size=7, ax=ax)
nx.draw_networkx_edges(G, pos, alpha=0.3, arrows=True, arrowsize=10, ax=ax)

ax.legend()
ax.set_title("Gene Regulatory Network")
plt.savefig("grn_network.png", dpi=150, bbox_inches="tight")
plt.close()

Step 7: Save Results

# Save regulon activities
regulon_activities.to_csv("regulon_activities.csv")

# Save TF-target relationships
tf_target_rows = []
for tf, targets in tf_targets.items():
    for gene, corr in targets[:20]:
        tf_target_rows.append({"tf": tf, "target": gene, "correlation": corr})
pd.DataFrame(tf_target_rows).to_csv("tf_targets.csv", index=False)

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

Extending the TF List

Add tissue-specific TFs:

# Liver-specific TFs
LIVER_TFS = ["HNF4A", "HNF1A", "HNF1B", "FOXA1", "FOXA2", "FOXA3", "CEBPA", "ATF5"]

# Brain-specific TFs
BRAIN_TFS = ["NEUROD1", "NEUROD2", "ASCL1", "OLIG2", "SOX2", "PAX6", "TBR1", "EMX1"]

Key Parameters

ParameterDefaultNotes
top_n genes5000More genes = more complete GRN but slower
corr_threshold0.15Lower = more targets; higher = stricter
top targets per TF50For regulon scoring

Advanced: Full SCENIC Pipeline

For production-quality GRN, use the full pySCENIC pipeline:

# Step 1: GRN inference
pyscenic grn expression.csv regulons.csv -o grn_output.csv

# Step 2: Regulon refinement (ctx)
pyscenic ctx grn_output.csv \
    --annotations_fname motif_annot.csv \
    --expression_mtx_fname expression.csv \
    -o ctx_output.csv

# Step 3: AUCell scoring
pyscenic aucell expression.csv ctx_output.csv \
    -o aucell_output.loom

Common Issues

  • Too few TFs found: Expand TF list or lower correlation threshold
  • Non-specific regulons: TFs active in all cells; filter by cell-type specificity
  • Memory issues: Process cell types separately; reduce gene count
  • Missing TF genes: Check gene naming conventions (case sensitivity)

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.