Communitygithub.com

scvelo

利用 scVelo 进行 RNA 速率分析。从未剪接/已剪接 mRNA 动力学推断细胞状态转换、估计轨迹方向、计算潜在时间,并在单细胞 RNA-seq 数据中识别驱动基因。补充 Scanpy/scVI-tools 的轨迹推断能力。

scvelo 是什么?

scVelo 是用于单细胞 RNA-seq 数据 RNA 速率分析的主流 Python 包。它通过建模 mRNA 剪接动力学来推断细胞状态转换,利用未剪接(前体 mRNA)与已剪接(成熟 mRNA)丰度的比例判断每个细胞中基因是上调还是下调,从而在不依赖时间序列数据的情况下重建发育轨迹并识别细胞命运决策点。 该技能支持在 Scanpy 流程中无缝集成,兼容来自 STARsolo、kallisto|bustools、velocyto 和 alevin-fry 等工具的剪接/未剪接计数矩阵,通常存储在 AnnData 对象中。 用户可灵活选择随机模型(快速探索)或动力学模型(更准确、产量级),并执行潜在时间估计、驱动基因识别、速度箭头/流线图、PAGA 轨迹图等下游分析,输出的基因水平参数(如转录率、剪接率、降解率)对理解细胞分化过程至关重要。 该技能适用于发育生物学、细胞命运预测和轨迹推断,要求对数据质量、邻居选择参数和模型输出进行审慎验证。

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

在你喜欢的 AI 中提问

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

文档

scVelo — RNA 速率分析

概述

scVelo 是用于单细胞 RNA-seq 数据 RNA 速率分析的主要 Python 包。它通过建模 mRNA 剪接动力学来推断细胞状态转换——利用未剪接(前体 mRNA)与已剪接(成熟 mRNA)丰度的比例判断每个细胞中基因是上调还是下调。这使得无需时间序列数据即可重建发育轨迹并识别细胞命运决策。

安装: uv pip install scvelo

关键资源:

何时使用本技能

在以下情况下使用 scVelo:

  • 从快照数据推断轨迹:确定细胞分化的方向
  • 细胞命运预测:识别祖细胞及其下游命运
  • 驱动基因识别:找到动力学最能解释观察到的轨迹的基因
  • 发育生物学:模拟造血、神经发生、上皮-间质转化
  • 潜在时间估计:根据剪接动力学对细胞进行伪时间排序
  • 补充 Scanpy:为 UMAP 嵌入添加方向性信息

前提条件

scVelo 需要同时包含未剪接和已剪接 RNA 的计数矩阵。这些由以下工具生成:

  1. STARsolo 或 kallisto|bustools(使用 lamanno 模式)
  2. velocyto CLI:velocyto run10x / velocyto run
  3. alevin-fry / simpleaf(输出剪接/未剪接结果)

数据存储在 AnnData 对象中,包含 layers["spliced"] 和 layers["unspliced"]。

标准 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')

# 加载数据(包含剪接/未剪接层的 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 参数,也不再进行 log 变换,
# 因此 log 步骤和 HVG 选择需要来自 Scanpy。
scv.pp.filter_and_normalize(
    adata,
    min_shared_counts=20    # 剪接+未剪接中的最小计数
)
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 速率(随机模型)"
)

4. 速率估计——动力学模型(推荐)

动力学模型拟合完整的剪接动力学,精度更高:

# 恢复动力学(计算密集型;约 10-30 分钟处理 10K 细胞)
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='潜在时间'
)

# 识别按潜在时间排序的 top 基因
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' 层以及 UMAP 在 obsm 中的 AnnData
        n_top_genes: 用于速率的 top HVG 数量
        mode: 'stochastic'(快速)或 'dynamical'(精确)
        n_jobs: 动力学模型的并行任务数

    Returns:
        添加了速率信息的已处理 AnnData
    """
    scv.settings.verbosity = 2

    # 1. 预处理(scVelo 0.3 已将 log/HVG 从 filter_and_normalize 中移除)
    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 上的二维速率向量
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慢高出版级质量;识别驱动基因

最佳实践

  • 从随机模式开始进行探索;最终分析时切换到动力学模式
  • 需要良好的未剪接读数覆盖:短读长(< 100 bp)可能导致内含子覆盖不足
  • 最少 2,000 个细胞:细胞数更少时 RNA 速率噪音较大
  • 速率应具有一致性:箭头应遵循已知生物学规律;随机性表明存在问题
  • k-NN 带宽很重要:邻居太少 → 速率噪音大;太多 → 过度平滑
  • 合理性检查:根细胞(祖细胞)的标记基因应具有高的未剪接/已剪接比率
  • 动力学模型需要清晰的动力学状态:最适合清晰的分化过程

故障排除

问题解决方案
缺少未剪接层重新运行 velocyto 或使用 STARsolo 的 --soloFeatures Gene Velocyto
极少的速率基因降低 min_shared_counts;检查测序深度
箭头看起来随机尝试不同的 n_neighbors 或速率模型
动力学模型内存错误设置 n_jobs=1;减少 n_top_genes
处处为负速率检查剪接/未剪接层是否互换

附加资源

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.

相关技能