Communitygithub.com

scVelo — RNA速度解析

scVeloを用いたRNA速度解析。スプライシングされていないmRNAとスプライシングされたmRNAの動態から細胞状態遷移を推定し、軌道方向の推論、潜在時間の計算、シングルセルRNA-seqデータにおけるドライバー遺伝子の同定を行います。Scanpy/scVI-toolsを補完し、軌道推論を実現します。

scVelo — RNA速度解析 とは?

scVeloは、シングルセルRNA-seqデータにおけるRNA速度解析の主要なPythonパッケージです。スプライシングされていない(pre-mRNA)とスプライシングされた(成熟mRNA)の存在比に基づいてmRNAスプライシングの動態をモデル化し、各細胞で遺伝子がアップレギュレーションされているかダウンレギュレーションされているかを判断します。これにより、時間経過データを必要とせずに発生軌道の再構築や細胞運命決定の特定が可能になります。主な使用例としては、スナップショットデータからの軌道推論、細胞運命予測、ドライバー遺伝子の同定、発生生物学(造血、神経発生、上皮間葉転換など)、スプライシング動態に基づく潜在時間推定、UMAP埋め込みへの方向情報の追加が挙げられます。ワークフローは、Preprocessing(フィルタリング、正規化、モーメント計算)、速度推定(確率的モデルまたは動的モデル)、下流解析(潜在時間、ドライバー遺伝子、速度信頼性、PAGA軌道グラフ)から構成されます。動的モデルは完全なスプライシング動態を適合させ、高精度でドライバー遺伝子を特定するため、出版品質の解析に推奨されます。このスキルは、STARsolo、kallisto|bustools、velocyto、alevin-fryなどのツールで生成されたUnspliced/Splicedカウント行列を含むAnnDataオブジェクトと連携して動作します。

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

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

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

ドキュメント

scVelo — RNA速度解析 は何をしますか?

概要

scVeloは、シングルセルRNA-seqデータにおけるRNA速度解析のための主要なPythonパッケージです。スプライシングされていない(pre-mRNA)とスプライシングされた(成熟mRNA)の存在比を用いてmRNAスプライシングの動態をモデル化し、各細胞で遺伝子がアップレギュレーションされているかダウンレギュレーションされているかを判定することで、細胞状態遷移を推論します。これにより、時間経過データを必要とせずに発生軌道の再構築や細胞運命決定の特定が可能になります。

インストール: uv pip install scvelo

主要リソース:

このスキルを使用すべき場合

scVeloは以下のような場合に使用します:

  • スナップショットデータからの軌道推論: 細胞がどの方向に分化しているかを判定する
  • 細胞運命予測: 前駆細胞とその下流の運命を特定する
  • ドライバー遺伝子の同定: 観測された軌道を最もよく説明する動態を持つ遺伝子を見つける
  • 発生生物学: 造血、神経発生、上皮間葉転換をモデル化する
  • 潜在時間推定: スプライシング動態に基づく擬時間に沿って細胞を順序付ける
  • Scanpyの補完: UMAP埋め込みに方向情報を追加する

前提条件

scVeloには、Unspliced(未スプライシング)とSpliced(スプライシング済み)両方のRNAのカウント行列が必要です。これらは以下によって生成されます:

  1. STARsolo または kallisto|bustools(lamanno モード)
  2. velocyto CLI: velocyto run10x / velocyto run
  3. alevin-fry / simpleaf(Spliced/Unspliced出力)

データは layers["spliced"] と layers["unspliced"] を含む AnnData オブジェクトに格納されます。

標準的なRNA速度ワークフロー

1. セットアップとデータ読み込み

import scvelo as scv
import scanpy as sc
import numpy as np
import matplotlib.pyplot as plt

# 設定の構成
scv.settings.verbosity = 3       # 計算手順を表示
scv.settings.presenter_view = True
scv.settings.set_figure_params('scvelo')

# データの読み込み(Spliced/Unsplicedレイヤーを持つAnnData)
# オプションA: loomファイルから読み込み(velocyto出力)
adata = scv.read("cellranger_output.loom", cache=True)

# オプションB: velocytoのloomとScanpyで処理済みのAnnDataをマージ
adata_processed = sc.read_h5ad("processed.h5ad")  # UMAP、クラスタあり
adata_velocity = scv.read("velocyto.loom")
adata = scv.utils.merge(adata_processed, adata_velocity)

# レイヤーの確認
print(adata)
# obs × var: N × G
# layers: 'spliced', 'unspliced' (必須)
# obsm['X_umap'] (可視化に必須)

2. 前処理

# フィルタリングと正規化。scVelo 0.3以降、filter_and_normalize()は
# 遺伝子のフィルタリングと細胞ごとの正規化のみを行い、n_top_genesや
# 対数変換は行わないため、対数変換とHVG選択はScanpyで行います。
scv.pp.filter_and_normalize(
    adata,
    min_shared_counts=20    # Spliced+Unsplicedの最小カウント数
)
sc.pp.log1p(adata)
sc.pp.highly_variable_genes(adata, n_top_genes=2000, subset=True)

# 一次および二次モーメント(平均と分散)の計算
# knn_connectivitiesを先に計算する必要があります
sc.pp.neighbors(adata, n_neighbors=30, n_pcs=30)
scv.pp.moments(
    adata,
    n_pcs=30,
    n_neighbors=30
)

3. 速度推定 — 確率的モデル

確率的モデルは高速で、探索的分析に適しています:

# 確率的速度(高速、精度は低い)
scv.tl.velocity(adata, mode='stochastic')
scv.tl.velocity_graph(adata)

# 可視化
scv.pl.velocity_embedding_stream(
    adata,
    basis='umap',
    color='leiden',
    title="RNA Velocity (Stochastic)"
)

4. 速度推定 — 動的モデル(推奨)

動的モデルは完全なスプライシング動態を適合させ、より高精度です:

# 動態の復元(計算負荷が高い;10K細胞で約10~30分)
scv.tl.recover_dynamics(adata, n_jobs=4)

# 動的モデルからの速度計算
scv.tl.velocity(adata, mode='dynamical')
scv.tl.velocity_graph(adata)

5. 潜在時間

動的モデルにより、共有された潜在時間(擬時間)の計算が可能になります:

# 潜在時間の計算
scv.tl.latent_time(adata)

# UMAP上に潜在時間を可視化
scv.pl.scatter(
    adata,
    color='latent_time',
    color_map='gnuplot',
    size=80,
    title='Latent time'
)

# 潜在時間で順序付けられた上位遺伝子の特定
top_genes = adata.var['fit_likelihood'].sort_values(ascending=False).index[:300]
scv.pl.heatmap(
    adata,
    var_names=top_genes,
    sortby='latent_time',
    col_color='leiden',
    n_convolve=100
)

6. ドライバー遺伝子解析

# 速度適合度が最も高い遺伝子の特定
scv.tl.rank_velocity_genes(adata, groupby='leiden', min_corr=0.3)
df = scv.DataFrame(adata.uns['rank_velocity_genes']['names'])
print(df.head(10))

# 速度と一貫性
scv.tl.velocity_confidence(adata)
scv.pl.scatter(
    adata,
    c=['velocity_length', 'velocity_confidence'],
    cmap='coolwarm',
    perc=[5, 95]
)

# 特定遺伝子のフェーズポートレート
scv.pl.velocity(adata, ['Cpe', 'Gnao1', 'Ins2'],
               ncols=3, figsize=(16, 4))

7. 速度矢印と擬時間

# UMAP上の矢印プロット
scv.pl.velocity_embedding(
    adata,
    arrow_length=3,
    arrow_size=2,
    color='leiden',
    basis='umap'
)

# ストリームプロット(よりクリーンな可視化)
scv.pl.velocity_embedding_stream(
    adata,
    basis='umap',
    color='leiden',
    smooth=0.8,
    min_mass=4
)

# 速度擬時間(潜在時間の代替)
scv.tl.velocity_pseudotime(adata)
scv.pl.scatter(adata, color='velocity_pseudotime', cmap='gnuplot')

8. PAGA軌道グラフ

# 速度情報に基づくPAGAグラフ
scv.tl.paga(adata, groups='leiden')
df = scv.get_df(adata, 'paga/transitions_confidence', precision=2).T
df.style.background_gradient(cmap='Blues').format('{:.2g}')

# 速度を用いたPAGAのプロット
scv.pl.paga(
    adata,
    basis='umap',
    size=50,
    alpha=0.1,
    min_edge_width=2,
    node_size_scale=1.5
)

完全なワークフロースクリプト

import scvelo as scv
import scanpy as sc

def run_rna_velocity(adata, n_top_genes=2000, mode='dynamical', n_jobs=4):
    """
    完全なRNA速度ワークフロー。

    Args:
        adata: 'spliced' および 'unspliced' レイヤー、obsmにUMAPを持つAnnData
        n_top_genes: 速度に使用する上位HVGの数
        mode: 'stochastic'(高速)または 'dynamical'(高精度)
        n_jobs: 動的モデル用の並列ジョブ数

    Returns:
        速度情報が追加された処理済みAnnData
    """
    scv.settings.verbosity = 2

    # 1. 前処理(scVelo 0.3ではfilter_and_normalizeから対数変換とHVG選択が削除されました)
    scv.pp.filter_and_normalize(adata, min_shared_counts=20)
    sc.pp.log1p(adata)
    sc.pp.highly_variable_genes(adata, n_top_genes=n_top_genes, subset=True)

    if 'neighbors' not in adata.uns:
        sc.pp.neighbors(adata, n_neighbors=30)

    scv.pp.moments(adata, n_pcs=30, n_neighbors=30)

    # 2. 速度推定
    if mode == 'dynamical':
        scv.tl.recover_dynamics(adata, n_jobs=n_jobs)

    scv.tl.velocity(adata, mode=mode)
    scv.tl.velocity_graph(adata)

    # 3. 下流解析
    if mode == 'dynamical':
        scv.tl.latent_time(adata)
        scv.tl.rank_velocity_genes(adata, groupby='leiden', min_corr=0.3)

    scv.tl.velocity_confidence(adata)
    scv.tl.velocity_pseudotime(adata)

    return adata

AnnDataの主要出力フィールド

ワークフロー実行後、以下のフィールドが追加されます:

場所キー説明
adata.layersvelocity細胞ごと・遺伝子ごとのRNA速度
adata.layersfit_t細胞ごと・遺伝子ごとの適合潜在時間
adata.obsmvelocity_umapUMAP上の2D速度ベクトル
adata.obsvelocity_pseudotime速度からの擬時間
adata.obslatent_time動的モデルからの潜在時間
adata.obsvelocity_length各細胞の速度
adata.obsvelocity_confidence各細胞の信頼度スコア
adata.varfit_likelihood遺伝子レベルのモデル適合品質
adata.varfit_alpha転写速度
adata.varfit_betaスプライシング速度
adata.varfit_gamma分解速度
adata.unsvelocity_graph細胞間遷移確率行列

速度モデルの比較

モデル速度精度使用すべき状況
stochastic高速中程度探索的分析;大規模データセット
deterministic中程度中程度単純な線形動態
dynamical低速高出版品質;ドライバー遺伝子の特定

ベストプラクティス

  • 探索的には確率的モードから開始し、最終解析では動的モデルに切り替える
  • Unsplicedリードの十分なカバレッジが必要:短いリード(< 100 bp)ではイントロンカバレッジが不足する可能性あり
  • 最低2,000細胞:RNA速度は細胞数が少ないとノイズが多くなる
  • 速度は一貫しているべき:矢印は既知の生物学に従うべきで、ランダム性は問題を示す
  • k-NN帯域幅に注意:近傍数が少なすぎるとノイズの多い速度、多すぎると過度に平滑化される
  • 健全性チェック:ルート細胞(前駆細胞)はマーカー遺伝子に対して高いUnspliced/Spliced比を示すべき
  • 動的モデルには異なる動態状態が必要:明確な分化プロセスに最も適している

トラブルシューティング

問題解決策
Unsplicedレイヤーがないvelocytoを再実行するか、--soloFeatures Gene Velocyto 付きでSTARsoloを使用する
速度遺伝子が非常に少ないmin_shared_counts を下げる;シーケンシング深度を確認する
矢印がランダムに見える異なる n_neighbors または速度モデルを試す
動的モデルでメモリエラーn_jobs=1 に設定;n_top_genes を減らす
どこでも負の速度Spliced/Unsplicedレイヤーが入れ替わっていないか確認する

追加リソース

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.

関連スキル