Communitygithub.com

scanpy

標準的な一細胞RNA-seq解析パイプライン。品質管理、正規化、次元削減(PCA/UMAP/t-SNE)、クラスタリング、差次的発現、可視化、およびSeuratやSingleCellExperimentなどのR向け一細胞形式をScanpy用のh5adに変換するために使用します。確立されたワークフローによる探索的scRNA-seq解析に最適です。深層学習モデルにはscvi-toolsを、データ形式に関する質問にはanndataを使用してください。

scanpy とは?

Scanpyは、AnnData上に構築された、一細胞RNA-seqデータを解析するためのスケーラブルなPythonツールキットです。このスキルは、品質管理、正規化、次元削減、クラスタリング、マーカー遺伝子同定、可視化、軌跡解析を含む完全な一細胞ワークフローを提供します。このスキルは主にClaude Code、Cursor、CodexなどのAIエージェント向けに設計されており、scanpyコードを一から書く代わりに実行できる、すぐに使えるCLIスクリプト一式をバンドルしています。このスキルは、`.h5ad`、10X Genomics形式、CSVなど、さまざまな入力形式をサポートし、SeuratやSingleCellExperimentなどのRオブジェクトをScanpyで使用する前に`.h5ad`に変換するためのガイダンスも含まれています。また、Leidenクラスタリングを推奨し、生カウントデータの保存やQCプロットの注意深い確認といったベストプラクティスを提供し、再現性のある解析のためにDaskやRとの相互運用性に関するリソースも含んでいます。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Scanpy: 一細胞解析

概要

Scanpyは、AnnData上に構築された、一細胞RNA-seqデータを解析するためのスケーラブルなPythonツールキットです。このスキルは、品質管理、正規化、次元削減、クラスタリング、マーカー遺伝子同定、可視化、軌跡解析を含む完全な一細胞ワークフローに適用します。現在の安定リリース: scanpy 1.12.x (2026年1月)。

インストール

Python 3.12+ (scanpy 1.12はPython ≤3.11をサポート終了) および anndata ≥0.10 が必要です。

uv pip install "scanpy[leiden]"

[leiden] extraは、Leidenクラスタリングに必要なpython-igraphとleidenalgをインストールします。再現可能な環境のためには、バージョンを固定してください: 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で読み込みます。エージェントがmacOS、Linux、Windowsでインストールと変換を実行する手順については、references/r_interop.mdを参照してください。

AnnDataの構造とI/Oの詳細については、anndataスキルを使用してください。確率的モデルとバッチ補正には、scvi-toolsを使用してください。

このスキルを使用するタイミング

このスキルは以下の場合に使用します:

  • 一細胞RNA-seqデータ (.h5ad, 10X, CSV形式) の解析
  • .h5adに変換する必要があるR向け一細胞データセット (.rds, .RData, Seurat, SingleCellExperiment) の操作
  • scRNA-seqデータセットの品質管理の実行
  • UMAP、t-SNE、またはPCA可視化の作成
  • 細胞クラスターの同定とマーカー遺伝子の発見
  • 遺伝子発現に基づく細胞型のアノテーション
  • 軌跡推定または疑似時間解析の実施
  • 出版品質の一細胞プロットの生成

スクリプトツールキット (ゼロからコードを書くよりもこれらを優先)

このスキルには、一般的な各ステップのための、すぐに実行可能なCLIスクリプトがscripts/にバンドルされています。scanpyコードを手書きする代わりにこれらを実行してください — 拡張子によるファイル読み込み、図の設定、適切なデフォルト値、生カウントの保存、進行状況のログ処理を行います。各スクリプトは.h5adを読み書きするため、連鎖させることができ、それぞれに--helpがあります。タスクがスクリプトでカバーされていない場合や、特殊なカスタマイズが必要な場合にのみ、scanpyコードを書くようにしてください。

すべてのスクリプトは共有のscripts/_common.pyヘルパー (読み込み、保存、図の設定) を使用します — これを他のスクリプトと一緒に配置してください。スキルディレクトリから実行するか、フルパスを渡してください。図はデフォルトで./figures/に出力されます。

スクリプト目的典型的な呼び出し
run_pipeline.py1コマンドでの完全ワークフロー: 読み込み → 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) を読み込み、.h5adを書き出すpython 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.pyLeiden (または louvain) を1つまたは複数の解像度で実行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.pyJSON/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.pyobs値または遺伝子リストでサブセット化 (オプションで古い埋め込みをクリア)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
# 結果/マーカー/*.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を直接解析しようとしないでください。最初に変換します:

# Rのインストールと変換パッケージについては references/r_interop.md を参照。
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  # 遺伝子名

標準解析ワークフロー

コードと各段階で重要なパラメータを含む7つのステップについては、 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. 設定を介してプロットを保存: プロット関数の非推奨のsave=の代わりにsc.settings.autosaveを使用
  11. Scanpyの前にRオブジェクトを変換: Rパッケージを使用してSeuratまたはSingleCellExperimentの.rdsファイルを.h5adに変換し、カウント、メタデータ、遺伝子識別子を保持

バンドルリソース

scripts/ (CLIツールキット)

ワークフロー全体をカバーする、.h5ad入力/.h5ad出力のスクリプトの構成可能なセットと、1コマンドのエンドツーエンドパイプライン。完全なテーブルと連鎖の例については、上記のスクリプトツールキットセクションを参照してください。各スクリプトには--helpがあります。ファイル:

  • _common.py — 他のスクリプトがインポートする共有の読み込み/保存/図ヘルパー (CLIではない)
  • run_pipeline.py — 1コマンドでの完全パイプライン (フラグまたは--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 用の遺伝子セットシグネチャ

追加リソース

関連スキル

  • anndata: AnnDataオブジェクトの構造、I/O、操作の詳細
  • scvi-tools: 深層確率モデル、バッチ補正、データセット統合
  • pydeseq2: 疑似バルク差次的発現解析

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.

関連スキル