Communitygithub.com

Scanpy:单细胞分析

标准单细胞RNA-seq分析流程。用于质量控制、标准化、降维(PCA/UMAP/t-SNE)、聚类、差异表达、可视化,以及将R友好的单细胞格式(如Seurat或SingleCellExperiment的RDS文件)转换为Scanpy所需的h5ad格式。最适合采用既定工作流程进行探索性单细胞RNA-seq分析。深度学习模型请使用scvi-tools;数据格式问题请使用anndata。

Scanpy:单细胞分析 是什么?

该技能提供基于Scanpy的完整单细胞RNA-seq分析流程,它是一个构建于AnnData之上的可扩展Python工具包。该技能的核心是一套可直接运行的CLI脚本,覆盖从数据加载、质量控制、标准化、降维到聚类、标记基因鉴定、细胞类型注释以及伪批量差异表达分析等所有标准步骤。这些脚本通过读取和写入h5ad格式文件以管道方式衔接,极大简化了分析流程。用户可根据需求选择一键式端到端管道(run_pipeline.py)或分步执行各个脚本以在阶段间进行迭代。该技能还包含全套参考文档,如标准工作流程、API参考和绘图指南,以及用于快速启动新项目的资产模板。建议在编写自定义Scanpy代码前优先使用这些脚本。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/scanpy

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Scanpy:单细胞分析 是做什么的?

概述

Scanpy是一个用于分析单细胞RNA-seq数据的可扩展Python工具包,构建于AnnData之上。应用此技能可完成完整的单细胞工作流程,包括质量控制、标准化、降维、聚类、标记基因鉴定、可视化和轨迹分析。当前稳定版本:scanpy 1.12.x(2026年1月)。

安装

需要Python 3.12+(scanpy 1.12已放弃对Python ≤3.11的支持)和anndata ≥0.10。

uv pip install "scanpy[leiden]"

[leiden]额外安装包会安装python-igraph和leidenalg,这是Leiden聚类所必需的。为重现环境,请固定版本:uv pip install "scanpy[leiden]==1.12.1"。

对于大型或超出核心内存的数据集,许多函数支持Dask数组(实验性):

uv pip install "scanpy[leiden]" dask

请参阅将dask与Scanpy配合使用教程。如需GPU加速的类似scanpy的操作,请使用独立的rapids-singlecell包。

如果输入是R原生的单细胞对象(.rds、.RData、Seurat或SingleCellExperiment),请先使用R工具将其转换为.h5ad,然后使用Scanpy加载。阅读references/r_interop.md以获取在macOS、Linux和Windows上由代理运行的安装和转换说明。

有关AnnData结构和I/O的详细信息,请使用anndata技能。有关概率模型和批次校正,请使用scvi-tools。

何时使用此技能

此技能应在以下情况使用:

  • 分析单细胞RNA-seq数据(.h5ad、10X、CSV格式)
  • 使用需要转换为.h5ad的R友好单细胞数据集(.rds、.RData、Seurat、SingleCellExperiment)
  • 对scRNA-seq数据集执行质量控制
  • 创建UMAP、t-SNE或PCA可视化
  • 识别细胞簇并寻找标记基因
  • 基于基因表达注释细胞类型
  • 进行轨迹推断或伪时间分析
  • 生成可用于发表的单细胞图

脚本工具包(优先使用这些脚本而非从头编写代码)

此技能在scripts/目录中捆绑了针对每个常见步骤的即用型CLI脚本。运行这些脚本,而非手动编写scanpy代码——它们能根据扩展名处理文件加载、图形设置、合理的默认值、原始计数保留和进度日志记录。每个脚本都读取和写入.h5ad,因此可以串联使用,并且每个都有其自己的--help。仅当任务未被脚本覆盖或需要异常定制时,才降级为编写scanpy代码。

所有脚本都使用共享的scripts/_common.py辅助模块(加载、保存、图形配置)——请将其与其他脚本放在一起。从技能目录运行或传递完整路径;图形默认保存到./figures/。

脚本用途典型调用
run_pipeline.py一条命令完成完整工作流程:加载 → QC → 标准化 → HVG → PCA →(批次)→ UMAP → Leiden → 标记物python scripts/run_pipeline.py raw.h5ad -o processed.h5ad
inspect_data.py总结未知数据集(形状、obs/var、层、已计算内容、原始与标准化对比)python scripts/inspect_data.py data.h5ad
convert.py加载任何格式(10x目录/.h5、csv、loom、mtx)并写入.h5adpython scripts/convert.py 10x_dir/ -o data.h5ad
qc_analysis.pyQC度量、前后对比图、过滤、可选的Scrublet双胞体检测python scripts/qc_analysis.py raw.h5ad -o qc.h5ad --scrublet
preprocess.py标准化、log1p、HVG、可选缩放/回归(保留counts层 + raw)python scripts/preprocess.py qc.h5ad -o norm.h5ad
reduce_dimensions.pyPCA + 方差图、邻域、UMAP、可选的t-SNEpython scripts/reduce_dimensions.py norm.h5ad -o red.h5ad
batch_correct.py整合:harmony / bbknn / combatpython scripts/batch_correct.py red.h5ad -o int.h5ad --method harmony --batch-key sample
cluster.py以一个或多个分辨率进行Leiden(或louvain)聚类python scripts/cluster.py red.h5ad -o clu.h5ad --resolution 0.3 0.6 1.0
find_markers.pyrank_genes_groups + 每个组的CSV + 标记物图python scripts/find_markers.py clu.h5ad --groupby leiden -o clu.h5ad
annotate.py将簇 → 细胞类型从JSON/CSV映射;可选的标记物参考点图python scripts/annotate.py clu.h5ad -o ann.h5ad --mapping map.json
score_genes.py对基因签名(JSON)和/或细胞周期阶段进行评分python scripts/score_genes.py ann.h5ad -o scored.h5ad --gene-sets sigs.json
pseudobulk.py按样本×细胞类型聚合计数 → 用于pydeseq2的矩阵python scripts/pseudobulk.py ann.h5ad --by sample cell_type --out-prefix pb
subset.py按obs值或基因列表子集(可选择清除过时的嵌入)python scripts/subset.py ann.h5ad -o tcells.h5ad --obs cell_type --keep "T cells"
plot.py从处理后的对象生成umap/tsne/pca/violin/dotplot/heatmap等python scripts/plot.py ann.h5ad --kind dotplot --genes CD3D CD14 --groupby cell_type

一次命令端到端运行

# 计数 → 聚类、标记物注释的对象 + 图形 + 标记物CSV
python scripts/run_pipeline.py raw.h5ad -o processed.h5ad \
    --resolution 0.5 --n-top-genes 2000 --scrublet
# 带多样本整合:
python scripts/run_pipeline.py raw.h5ad -o processed.h5ad --batch-key sample --batch-method harmony
# 通过JSON重现参数(键镜像带有下划线的标志名称):
python scripts/run_pipeline.py raw.h5ad -o processed.h5ad --config params.json

逐步链式运行(当需要在阶段间检查/迭代时)

python scripts/qc_analysis.py        raw.h5ad  -o qc.h5ad   --scrublet
python scripts/preprocess.py         qc.h5ad   -o norm.h5ad --n-top-genes 2000
python scripts/reduce_dimensions.py  norm.h5ad -o red.h5ad  --n-pcs 40
python scripts/cluster.py            red.h5ad  -o clu.h5ad  --resolution 0.3 0.5 0.8
python scripts/find_markers.py       clu.h5ad  -o clu.h5ad  --groupby leiden --use-raw
# 检查结果/markers/*.csv,决定标签,写入映射JSON,然后:
python scripts/annotate.py           clu.h5ad  -o ann.h5ad  --mapping celltypes.json

以下部分记录了每个脚本执行的底层scanpy调用——当需要在脚本标志之外进行自定义时阅读它们。

快速开始

基本导入和设置

import scanpy as sc
import pandas as pd
import numpy as np

# 配置设置
sc.settings.verbosity = 3
sc.settings.set_figure_params(dpi=80, facecolor='white')
sc.settings.figdir = './figures/'
sc.settings.autosave = True  # 优先于每个图的save=(在scanpy 1.12中已弃用)

加载数据

# 从10X Genomics
adata = sc.read_10x_mtx('path/to/data/')
adata = sc.read_10x_h5('path/to/data.h5')

# 从h5ad(AnnData格式)
adata = sc.read_h5ad('path/to/data.h5ad')

# 从CSV
adata = sc.read_csv('path/to/data.csv')

对于R原生文件,请勿尝试直接在Python中解析Seurat .rds。请先转换:

# 请参阅references/r_interop.md以获取安装R和转换包的说明。
Rscript convert_rds_to_h5ad.R input.rds output.h5ad
adata = sc.read_h5ad('output.h5ad')

理解AnnData结构

AnnData对象是scanpy中的核心数据结构:

adata.X          # 表达矩阵(细胞 × 基因)
adata.obs        # 细胞元数据(DataFrame)
adata.var        # 基因元数据(DataFrame)
adata.uns        # 非结构化注释(dict)
adata.obsm       # 多维细胞数据(PCA, UMAP)
adata.raw        # 原始数据备份

# 访问细胞和基因名称
adata.obs_names  # 细胞条形码
adata.var_names  # 基因名称

标准分析工作流程

七个步骤,以及每个步骤中重要的参数和代码,位于 references/analysis_workflow.md:

  1. 质量控制 — 过滤细胞和基因;在选择阈值前检查线粒体比例和计数,不要直接复制默认值。
  2. 标准化和预处理 — 标准化、对数变换、选择高变基因,并保留 .raw 以备后续绘图。
  3. 降维 — PCA,然后构建邻域图,接着是UMAP。
  4. 聚类 — 根据问题选择分辨率进行Leiden聚类,而非使用默认值。
  5. 标记基因鉴定 — 每个簇的基因排序。
  6. 细胞类型注释 — 根据标记物将簇映射到细胞类型。
  7. 保存结果 — 写入注释后的 AnnData。

常见的后续任务——发表级图形、轨迹推断、条件间伪批量差异表达、基因集评分和批次校正——都在同一文件中。另请参阅 references/standard_workflow.md 和 references/plotting_guide.md。

需要调整的关键参数

质量控制

  • min_genes:每个细胞的最小基因数(通常200-500)
  • min_cells:每个基因的最小细胞数(通常3-10)
  • pct_counts_mt:线粒体比例阈值(通常5-20%)

标准化

  • target_sum:每个细胞的目标计数(默认为1e4)

特征选择

  • n_top_genes:高变基因数量(通常2000-3000)
  • min_mean、max_mean、min_disp:HVG选择参数

降维

  • n_pcs:主成分数量(检查方差比图)
  • n_neighbors:邻居数量(通常10-30)

聚类

  • resolution:聚类粒度(0.4-1.2,越高簇越多)

常见陷阱和最佳实践

  1. 始终保存原始计数:在过滤基因前执行 adata.raw = adata
  2. 仔细检查QC图:根据数据集质量调整阈值
  3. 使用Leiden聚类:sc.tl.louvain 在scanpy 1.12中已弃用
  4. 尝试多个聚类分辨率:找到最佳粒度
  5. 验证细胞类型注释:使用多个标记基因
  6. 对基因表达图使用 use_raw=True:显示来自 .raw 的标准化计数
  7. 检查PCA方差比:确定最佳PC数量
  8. 保存中间结果:长工作流程可能中途失败
  9. 使用伪批量进行差异表达:不要将 rank_genes_groups 的p值视为条件间严格的差异表达
  10. 通过设置保存图:使用 sc.settings.autosave 替代绘图函数上已弃用的 save=
  11. 在Scanpy之前转换R对象:使用R包将Seurat或SingleCellExperiment .rds 文件转换为 .h5ad,保留计数、元数据和基因标识符

捆绑资源

scripts/(CLI工具包)

一套可组合的 .h5ad 输入/.h5ad 输出脚本,覆盖整个工作流程以及一个一键端到端管道。请参阅上方脚本工具包部分以获取完整表格和串联示例。每个脚本都有 --help。文件:

  • _common.py — 共享的加载/保存/图形辅助模块,由其他脚本导入(非CLI)
  • run_pipeline.py — 一条命令完成整个管道(标志或 --config JSON)
  • inspect_data.py、convert.py — 探索并加载/转换任何输入格式
  • qc_analysis.py、preprocess.py、reduce_dimensions.py、batch_correct.py、cluster.py — 管道步骤
  • find_markers.py、annotate.py、score_genes.py、pseudobulk.py — 标记物、注释、评分、DE准备
  • subset.py、plot.py — 按元数据/基因子集;生成任何标准图

在从头编写scanpy代码之前,默认使用这些脚本。

references/standard_workflow.md

完整的逐步工作流程,包含详细说明和代码示例,涵盖:

  • 数据加载和设置
  • 带可视化的质量控制
  • 标准化和缩放
  • 特征选择
  • 降维(PCA、UMAP、t-SNE)
  • 聚类(Leiden)
  • 双胞体检测(scrublet)和伪批量聚合
  • 标记基因鉴定
  • 细胞类型注释
  • 轨迹推断
  • 差异表达

当从头进行完整分析时,请阅读此参考文档。

references/api_reference.md

按模块组织的scanpy函数快速参考指南:

  • 读取/写入数据(sc.read_*、adata.write_*)
  • 预处理(sc.pp.*)
  • 工具(sc.tl.*)
  • 绘图(sc.pl.*)
  • AnnData结构和操作
  • 设置和实用工具

用于快速查找函数签名和常见参数。

references/plotting_guide.md

全面的可视化指南,包括:

  • 质量控制图
  • 降维可视化
  • 聚类可视化
  • 标记基因图(热图、点图、小提琴图)
  • 轨迹和伪时间图
  • 发表级自定义
  • 多面板图形
  • 调色板和样式

在创建发表级图形时参考此指南。

references/r_interop.md

代理运行手册,用于在macOS、Linux和Windows上安装R、安装CRAN/Bioconductor转换包、检查 .rds/.RData 输入、将Seurat或SingleCellExperiment对象转换为 .h5ad,并在Scanpy中验证结果。

assets/analysis_template.py

完整的分析模板,提供从数据加载到细胞类型注释的完整工作流程。为新分析复制并自定义此模板:

cp assets/analysis_template.py my_analysis.py
# 编辑参数并运行
python my_analysis.py

该模板包含所有标准步骤、可配置参数和有用的注释。

assets/ JSON模板

可编辑和传递的模板,因此您无需从头创建配置/映射:

  • assets/pipeline_config.json — 用于 run_pipeline.py --config 的参数集
  • assets/celltype_mapping.json — 用于 annotate.py --mapping 的簇 → 细胞类型映射
  • assets/gene_signatures.json — 用于 score_genes.py --gene-sets 的基因集签名

其他资源

贡献

此技能作为Scanpy生态系统的独立指南和维护。如需报告问题或提出改进建议,请查阅官方Scanpy仓库。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

相关技能