Communitygithub.com

scanpy

標準的單細胞 RNA-seq 分析流程。適用於 QC、標準化、降維 (PCA/UMAP/t-SNE)、聚類、差異表現分析、視覺化,並可將 Seurat 或 SingleCellExperiment RDS 等 R 友善格式轉換為 Scanpy 適用的 h5ad 格式。最適合使用既定工作流程進行探索性的 scRNA-seq 分析。深度學習模型請使用 scvi-tools;數據格式問題請使用 anndata。

scanpy 是什麼?

此技能提供一個完整的單細胞 RNA-seq 分析管線,基於廣受使用的 Scanpy 套件。它不僅封裝了標準分析步驟(例如品質控制、標準化、降維、聚類和標記基因識別),還提供了一套可組合的命令列腳本,讓開發者能將常見任務串聯起來,並可處理 R 生態系格式。該技能支援多種啟動平台(Claude Code、Coder、Cursor),並透過結構化的參考文件和資產模板(JSON 配置、分析範本)來簡化工作流程。底層邏輯著重於實用性:首先使用腳本工具包來自動化處理,若需要高度自訂或進階分析(例如軌跡推斷、偽大量分析、批次校正)時才手動編寫 Scanpy 程式碼。此外,該技能也解決了 R 與 Python 互通性的常見痛點,提供轉換 Seurat 和 SingleCellExperiment 文件至 h5ad 的指引,確保從數據導入到格線類型注釋的流暢體驗。

相容平台~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 是一個基於 AnnData 的可擴展 Python 工具包,用於分析單細胞 RNA-seq 數據。使用此技能來完成完整的單細胞工作流程,包括品質控制、標準化、降維、聚類、標記基因識別、視覺化和軌跡分析。目前穩定版本: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、層、已計算內容、原始 vs 標準化)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/小提琴圖/點圖/熱圖等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: HVG 的數量(通常 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. 使用偽大量進行 DE:不要將 rank_genes_groups 的 p 值視為條件間嚴格的 DE
  10. 透過設定儲存圖表:使用 sc.settings.autosave 而非 plot 函數中已棄用的 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 的基因集標記

其他資源

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.

相關技能