scrna-cell-communication
Skill4 starsChanged 5 months agoMITView on GitHub
Cell-cell communication analysis for scRNA-seq. Implements ligand-receptor interaction scoring using CellChat-like methodology, permutation testing, pathway-level aggregation, and network visualization. Works with annotated single-cell data.
In this repository8 other files it gives its agents.
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 2 are distinctive, and 3 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.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 16
After cell type annotation to discover intercellular signaling
- Very specific: line 34
Always check if adata.X is sparse before operations.
- Very specific: line 35
Use adata.raw for expression queries — it contains the full gene space for ligand/receptor lookup
- Distinctive: line 36
Verify ligand and receptor genes exist in the dataset before computing scores.
- Very specific: line 322
Add custom pairs to LR_DATABASE:
≈ “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.
Files
Cell-Cell Communication Analysis
When to Use
- After cell type annotation to discover intercellular signaling
- Identifying which cell types communicate most
- Finding active ligand-receptor pathways
- Comparing communication between conditions (e.g., tumor vs normal)
Do NOT use when you need to:
- 细胞类型未标注 → (use scrna-marker-genes first)
- 需要蛋白互作网络而非配体受体 → (use string_database skill)
- 分析空间邻近性而非表达通讯 → (use spatial-neighborhood-analysis)
Prerequisites
- Python >= 3.10
- Required packages:
scanpy,anndata,numpy,pandas,scipy,matplotlib,seaborn,networkx - Input:
.h5adfile with cell type annotations inadata.obs(e.g.,"cell_type","celltype") andadata.rawpopulated with normalized data (output of scrna-marker-genes)
Core Rules
- Always check if
adata.Xis sparse before operations; prefer sparse-compatible code - Use
adata.rawfor expression queries — it contains the full gene space for ligand/receptor lookup - Verify ligand and receptor genes exist in the dataset before computing scores; skip missing pairs silently
- Apply FDR correction when testing many LR pairs simultaneously to control false discovery rate
- Save intermediate results (per-pair scores, permutation null distributions) to avoid re-computation
Common Mistakes
- No cell type annotation: Communication analysis requires meaningful cell type labels — running on raw Leiden clusters produces uninterpretable results
- Using HVG-subset data: Ligand/receptor genes may not be in the HVG set; always use
adata.rawor full gene space - Too few permutations: 100 permutations is fast but noisy; use 500–1000 for publication-quality results
- Mouse data with human LR database: Gene names differ (mouse=Cd3d, human=CD3D) — convert to human orthologs or use mouse-specific database
Troubleshooting
| 问题 | 原因 | 解决方案 |
| No cell type column found | Missing annotation in adata.obs | Run scrna-marker-genes to annotate clusters first |
| No significant interactions | Cell types too few or genes not in dataset | Check gene names; increase n_perms; lower p-value threshold |
| All interactions significant | Insufficient permutations or no FDR correction | Increase n_perms to 500+; apply scipy.stats.false_discovery_control |
| Memory error | Too many permutations on large dataset | Reduce n_perms; process LR pairs in batches |
Output
写入 --output 指定的 JSON 文件:
{
"skill": "scrna-cell-communication",
"status": "success",
"steps": ["load", "define_lr_database", "compute_scores", "run_all_pairs", "network_viz", "heatmap", "top_pairs"],
"result": {
"n_cell_types": 5,
"n_significant_interactions": 38,
"results_csv": "path/to/communication_results.csv",
"network_png": "path/to/communication_network.png",
"heatmap_png": "path/to/communication_heatmap.png",
"top_pairs": [
{"pair": "CXCL12_CXCR4", "sender": "Fibroblast", "receiver": "T cell", "score": 0.85},
{"pair": "PDGFB_PDGFRb", "sender": "Endothelial", "receiver": "Fibroblast", "score": 0.72}
]
}
}Workflow
Step 1: Load Annotated Data
import scanpy as sc
import pandas as pd
import numpy as np
from scipy import sparse
from itertools import product
import matplotlib.pyplot as plt
import seaborn as sns
adata = sc.read_h5ad("annotated.h5ad")
# Identify cell type column (try common names)
ct_col = None
for col in ["cell_type", "celltype", "cell_type_coarse", "cell_type_fine", "leiden"]:
if col in adata.obs.columns:
ct_col = col
break
assert ct_col is not None, "No cell type column found"
print(f"Cell types: {adata.obs[ct_col].value_counts().to_dict()}")Step 2: Define Ligand-Receptor Database
# Core human ligand-receptor pairs (expandable)
LR_DATABASE = {
# Immune checkpoint
"PDCD1_CD274": ("PDCD1", "CD274"), # PD1-PDL1
"CTLA4_CD80": ("CTLA4", "CD80"), # CTLA4-B7
"LAG3_HLA-A": ("LAG3", "HLA-A"),
"TIGIT_PVR": ("TIGIT", "PVR"),
# Chemokine signaling
"CXCL12_CXCR4": ("CXCL12", "CXCR4"),
"CCL2_CCR2": ("CCL2", "CCR2"),
"CCL5_CCR5": ("CCL5", "CCR5"),
"CXCL1_CXCR2": ("CXCL1", "CXCR2"),
"CXCL8_CXCR1": ("CXCL8", "CXCR1"),
"CXCL9_CXCR3": ("CXCL9", "CXCR3"),
"CXCL10_CXCR3": ("CXCL10", "CXCR3"),
"CXCL13_CXCR5": ("CXCL13", "CXCR5"),
# Growth factors
"EGF_EGFR": ("EGF", "EGFR"),
"HBEGF_EGFR": ("HBEGF", "EGFR"),
"FGF1_FGFR1": ("FGF1", "FGFR1"),
"VEGFA_VEGFR1": ("VEGFA", "FLT1"),
"VEGFA_VEGFR2": ("VEGFA", "KDR"),
"PDGFA_PDGFRa": ("PDGFA", "PDGFRA"),
"PDGFB_PDGFRb": ("PDGFB", "PDGFRB"),
"HGF_MET": ("HGF", "MET"),
# Notch signaling
"DLL1_NOTCH1": ("DLL1", "NOTCH1"),
"DLL4_NOTCH1": ("DLL4", "NOTCH1"),
"JAG1_NOTCH1": ("JAG1", "NOTCH1"),
# TGF-beta
"TGFB1_TGFBR1": ("TGFB1", "TGFBR1"),
"TGFB1_TGFBR2": ("TGFB1", "TGFBR2"),
# Wnt signaling
"WNT3A_FZD5": ("WNT3A", "FZD5"),
"WNT5A_FZD5": ("WNT5A", "FZD5"),
# Other
"IL6_IL6R": ("IL6", "IL6R"),
"IL1B_IL1R1": ("IL1B", "IL1R1"),
"TNF_TNFRSF1A": ("TNF", "TNFRSF1A"),
"IFNG_IFNGR1": ("IFNG", "IFNGR1"),
"CSF1_CSF1R": ("CSF1", "CSF1R"),
"CSF2_CSF2R": ("CSF2", "CSF2R"),
"CD70_CD27": ("CD70", "CD27"),
"FASLG_FAS": ("FASLG", "FAS"),
"TRAIL_TNFRSF10A": ("TNFSF10", "TNFRSF10A"),
# Complement
"C3_C3AR1": ("C3", "C3AR1"),
"C3_CR1": ("C3", "CR1"),
# Collagen signaling
"COL1A1_ITGA1": ("COL1A1", "ITGA1"),
"COL4A1_ITGB1": ("COL4A1", "ITGB1"),
}Step 3: Compute Communication Scores
def compute_mean_expression(adata, gene, groupby, use_raw=True):
"""Compute mean expression of a gene per group."""
if gene not in (adata.raw.var_names if use_raw and adata.raw else adata.var_names):
return None
data = adata.raw if use_raw and adata.raw else adata
idx = list(data.var_names).index(gene)
if sparse.issparse(data.X):
expr = pd.Series(
np.array(data.X[:, idx].todense()).flatten(),
index=data.obs_names
)
else:
expr = pd.Series(data.X[:, idx], index=data.obs_names)
return expr.groupby(adata.obs[groupby]).mean()
def compute_communication_score(adata, ligand, receptor, groupby, n_perms=100):
"""Compute CellChat-like communication score with permutation test."""
cell_types = adata.obs[groupby].unique().tolist()
scores = pd.DataFrame(0.0, index=cell_types, columns=cell_types)
pvalues = pd.DataFrame(1.0, index=cell_types, columns=cell_types)
# Mean expression per cell type
lig_expr = compute_mean_expression(adata, ligand, groupby)
rec_expr = compute_mean_expression(adata, receptor, groupby)
if lig_expr is None or rec_expr is None:
return scores, pvalues
# Compute interaction scores (sender ligand * receiver receptor)
for sender, receiver in product(cell_types, cell_types):
score = lig_expr[sender] * rec_expr[receiver]
scores.loc[sender, receiver] = score
# Permutation test (shuffle cell labels)
if n_perms > 0:
perm_scores = np.zeros((n_perms, len(cell_types), len(cell_types)))
for i in range(n_perms):
perm_labels = adata.obs[groupby].sample(frac=1).values
perm_adata = adata.copy()
perm_adata.obs[groupby] = perm_labels
pl = compute_mean_expression(perm_adata, ligand, groupby)
pr = compute_mean_expression(perm_adata, receptor, groupby)
if pl is not None and pr is not None:
for si, sender in enumerate(cell_types):
for ri, receiver in enumerate(cell_types):
perm_scores[i, si, ri] = pl[sender] * pr[receiver]
for si, sender in enumerate(cell_types):
for ri, receiver in enumerate(cell_types):
pvalues.loc[sender, receiver] = (
(perm_scores[:, si, ri] >= scores.loc[sender, receiver]).sum() / n_perms
)
return scores, pvaluesStep 4: Run All Pairs
all_results = []
for pair_name, (ligand, receptor) in LR_DATABASE.items():
scores, pvals = compute_communication_score(adata, ligand, receptor, ct_col, n_perms=100)
# Record significant interactions
for sender in scores.index:
for receiver in scores.columns:
if scores.loc[sender, receiver] > 0 and pvals.loc[sender, receiver] < 0.05:
all_results.append({
"pair": pair_name,
"ligand": ligand,
"receptor": receptor,
"sender": sender,
"receiver": receiver,
"score": scores.loc[sender, receiver],
"pvalue": pvals.loc[sender, receiver],
})
results_df = pd.DataFrame(all_results)
if len(results_df) > 0:
results_df = results_df.sort_values("score", ascending=False)
results_df.to_csv("communication_results.csv", index=False)
print(f"Significant interactions: {len(results_df)}")
else:
print("No significant interactions found")Step 5: Network Visualization
import networkx as nx
if len(results_df) > 0:
# Aggregate scores per cell type pair
agg = results_df.groupby(["sender", "receiver"])["score"].sum().reset_index()
# Create network
G = nx.DiGraph()
for _, row in agg.iterrows():
G.add_edge(row["sender"], row["receiver"], weight=row["score"])
# Plot
fig, ax = plt.subplots(figsize=(10, 10))
pos = nx.spring_layout(G, k=2, seed=42)
weights = [G[u][v]["weight"] for u, v in G.edges()]
max_w = max(weights) if weights else 1
nx.draw_networkx_nodes(G, pos, node_size=2000, node_color="lightblue", ax=ax)
nx.draw_networkx_labels(G, pos, font_size=10, ax=ax)
nx.draw_networkx_edges(
G, pos,
width=[3 * w / max_w for w in weights],
edge_color="gray",
alpha=0.6,
arrows=True,
arrowsize=20,
ax=ax,
)
ax.set_title("Cell-Cell Communication Network")
plt.savefig("communication_network.png", dpi=150, bbox_inches="tight")
plt.close()Step 6: Heatmap of Communication Intensity
if len(results_df) > 0:
# Pivot table: sender x receiver, total score
pivot = results_df.pivot_table(
index="sender", columns="receiver", values="score", aggfunc="sum", fill_value=0
)
fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(pivot, annot=True, fmt=".2f", cmap="YlOrRd", ax=ax)
ax.set_title("Communication Intensity (Sender → Receiver)")
plt.savefig("communication_heatmap.png", dpi=150, bbox_inches="tight")
plt.close()Step 7: Top Interacting Pairs
if len(results_df) > 0:
# Top 20 interactions
top20 = results_df.head(20)
print("\nTop 20 ligand-receptor interactions:")
print(top20[["pair", "sender", "receiver", "score", "pvalue"]].to_string(index=False))Key Parameters
| Parameter | Default | Notes |
n_perms | 100 | Increase to 500-1000 for publication |
pvalue threshold | 0.05 | FDR correction recommended for many pairs |
score threshold | > 0 | Filter by score magnitude for top hits |
Extending the LR Database
Add custom pairs to LR_DATABASE:
LR_DATABASE["MY_PAIR"] = ("LIGAND_GENE", "RECEPTOR_GENE")Or load from CellChat/CellPhoneDB databases:
# Load CellChat database
cellchat_db = pd.read_csv("CellChatDB_human.csv")
for _, row in cellchat_db.iterrows():
LR_DATABASE[f"{row['ligand']}_{row['receptor']}"] = (row['ligand'], row['receptor'])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
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.

