knowledge-work-plugins 中的空间转录组解卷积实战基于 scvi-tools 的 DestVI 与 resolVI 完整指南【免费下载链接】knowledge-work-pluginsOpen source repository of plugins primarily intended for knowledge workers to use in Claude Cowork项目地址: https://gitcode.com/GitHub_Trending/kn/knowledge-work-plugins本文是 bio-research 技能包中 scvi-tools 技能的空间转录组分析参考文档references/spatial_deconvolution.md的深度展开系统讲解如何使用 scvi-tools 对 Visium 等空间转录组数据进行细胞类型解卷积与空间建模。读者将掌握 DestVI基于单细胞参考推断每个 spot 的细胞类型比例与 resolVI直接从空间数据学习空间感知表示与细胞类型分配两条完整工作流并学会结合仓库内 scripts 提供的 CLI 脚本进行工程化落地。空间转录组分析的两大方法DestVI 与 resolVI空间转录组技术如 Visium能够在确定的组织位置上捕获基因表达但多数平台的分辨率是多细胞级别的——每个 spot 内往往混合了多种细胞类型。要回答每个 spot 里有什么细胞、各占多少比例这类生物学问题就需要借助计算解卷积方法。scvi-tools 为此提供了两条互补的技术路线DestVIDeconvolution以带注释的单细胞参考数据为字典通过变分推断估计每个 spot 的细胞类型比例是经典的反卷积范式resolVI直接对空间数据本身建模学习考虑了空间上下文spatial context的基因表达模式并输出空间感知的细胞类型分配与潜在表示。在 scvi-tools 技能中空间解卷积对应的入口是 SKILL.md 中的references/spatial_deconvolution.md其决策树明确给出有空间数据且需要细胞类型解卷积时选择 DestVI对应 references/spatial_deconvolution.md。方法一览方法描述典型用途DestVI用于解卷积的变分推断方法估计每个 spot 的细胞类型比例resolVI空间基因表达模型学习空间感知的表示spatially-aware representationsCondSCVIDestVI 流程必需的参考模型在单细胞参考上训练作为 DestVI 的初始化环境准备与前置条件空间转录组分析需要 scvi-tools、scanpy 与 squidpy 协同工作。仓库的 references/environment_setup.md 给出了带空间分析支持的安装方式conda create -n scvi-spatial python3.10 conda activate scvi-spatial pip install scvi-tools scanpy squidpy核心依赖的最小版本要求为scvi-tools1.0.0、scanpy1.9.0、anndata0.9.0、torch2.0.0。注意 scvi-tools 1.x 与 0.x 的 API 差异0.x 使用scvi.data.setup_anndata(adata, ...)而当前 1.x API 必须使用scvi.model.XXX.setup_anndata(adata, ...)形式。代码中导入依赖并确认版本import scvi import scanpy as sc import squidpy as sq import numpy as np print(fscvi-tools version: {scvi.__version__})关键前提所有 scvi-tools 模型都要求整数原始计数raw counts不能使用归一化后的数据。仓库 scripts/validate_adata.py 中的validate_for_scvi()会专门检查数据是否包含整数、是否存在负值/NaN/Inf以及是否缺少counts层。建议在正式训练前先用该脚本做一次数据体检python scripts/validate_adata.py spatial.h5ad --layer counts --suggest此外数据准备统一推荐走 scripts/prepare_data.py它会自动完成 QC 过滤、原始计数入层adata.layers[counts]与 HVG 选择python scripts/prepare_data.py raw_spatial.h5ad prepared_spatial.h5ad --n-hvgs 2000Part 1DestVI 解卷积完整流程DestVI 的整体思路分三步加载空间数据 → 加载带注释的单细胞参考 → 先训练 CondSCVI 参考模型再用from_rna_model初始化并训练 DestVI。其中参考模型的作用相当于把单细胞数据编码为可供空间 spot 匹配的细胞类型特征空间。Step 1加载并 QC 空间数据使用 scanpy 的sc.read_visium读取 Space Ranger 的输出目录# Load Visium data adata_spatial sc.read_visium(spaceranger_output/) # Check structure print(fSpots: {adata_spatial.n_obs}) print(fGenes: {adata_spatial.n_vars}) print(fSpatial coordinates: {adata_spatial.obsm[spatial].shape}) # Basic QC sc.pp.calculate_qc_metrics(adata_spatial, inplaceTrue) adata_spatial adata_spatial[adata_spatial.obs[n_genes_by_counts] 200].copy() # Store counts adata_spatial.layers[counts] adata_spatial.X.copy()要点obsm[spatial]保存了 spot 的二维坐标供后续 squidpy 空间可视化使用必须先完成 QC 过滤再执行adata_spatial.layers[counts] adata_spatial.X.copy()确保counts层保存的是过滤后的原始整数计数。Step 2加载单细胞参考数据# Load reference single-cell data adata_sc sc.read_h5ad(reference_scrna.h5ad) # Requirements: # - Raw counts # - Cell type annotations print(fReference cells: {adata_sc.n_obs}) print(fCell types: {adata_sc.obs[cell_type].nunique()}) print(adata_sc.obs[cell_type].value_counts()) # Store counts adata_sc.layers[counts] adata_sc.X.copy()参考数据的硬性要求原始计数整数细胞类型注释列示例中为cell_type且应覆盖空间数据中预期的全部细胞类型——参考数据缺少某种类型将直接导致该类型在 spot 上的比例无法估计对应 NaN 比例见 Troubleshooting 一节。Step 3对齐基因Gene OverlapDestVI 要求参考数据与空间数据使用同一套基因feature。若两者来自不同批次或不同注释体系如 Ensembl ID vs Gene Symbol必须先取交集# DestVI requires gene overlap between reference and spatial common_genes adata_sc.var_names.intersection(adata_spatial.var_names) print(fCommon genes: {len(common_genes)}) adata_sc adata_sc[:, common_genes].copy() adata_spatial adata_spatial[:, common_genes].copy()仓库 references/troubleshooting.md 在 DestVI 小节中补充了量化标准common_genes应大于 1000否则解卷积效果通常不可靠。若交集过少应优先排查基因命名差异Ensembl ↔ Symbol 转换。Step 4训练参考模型CondSCVICondSCVI是条件变分自编码器以细胞类型为条件变量在单细胞数据上训练为 DestVI 提供参考特征空间# Train conditional scVI on reference data scvi.model.CondSCVI.setup_anndata( adata_sc, layercounts, labels_keycell_type ) sc_model scvi.model.CondSCVI( adata_sc, n_latent20 ) sc_model.train(max_epochs200) sc_model.history[elbo_train].plot()参数说明layercounts指定原始计数层labels_keycell_type细胞类型注释列n_latent20潜在空间维度影响参考特征的表达能力训练后可通过sc_model.history[elbo_train].plot()检查 ELBO 收敛曲线若曲线仍在下降可适当增加max_epochs。Step 5训练 DestVI利用DestVI.from_rna_model()将训练好的 CondSCVI 模型迁移为空间模型# Setup spatial data scvi.model.DestVI.setup_anndata( adata_spatial, layercounts ) # Train DestVI using reference model spatial_model scvi.model.DestVI.from_rna_model( adata_spatial, sc_model ) spatial_model.train(max_epochs500)这一设计的价值在于空间数据本身没有细胞类型注释DestVI 通过from_rna_model继承 CondSCVI 学到的细胞类型结构再在空间数据上做微调从而将单细胞知识投射到 spot 层面。Step 6获取细胞类型比例# Infer cell type proportions at each spot proportions spatial_model.get_proportions() # Add to adata for ct in adata_sc.obs[cell_type].unique(): adata_spatial.obs[fprop_{ct}] proportions[ct] # Visualize sq.pl.spatial_scatter( adata_spatial, color[fprop_{ct} for ct in adata_sc.obs[cell_type].unique()[:6]], ncols3 )get_proportions()返回每个 spot 上各细胞类型的比例矩阵随后将每种类型的比例写入adata_spatial.obs列名为prop_cell_type即可用 squidpy 的sq.pl.spatial_scatter将比例直接映射到组织切片的空间坐标上。Part 2resolVI 空间模型resolVI 是一种半监督方法semi-supervised它直接从空间数据学习细胞类型分配与空间感知表示可选地利用初始的细胞类型预测结果作为弱监督信号。需要特别注意的是resolVI 位于scvi.external而非scvi.model——scvi.external.RESOLVI是正确引用方式。Step 1准备空间数据resolVI 对特征数更敏感因此除 QC 与计数入层外还需做 HVG 选择4000 个高变基因# Load and preprocess adata sc.read_visium(spaceranger_output/) # QC sc.pp.calculate_qc_metrics(adata, inplaceTrue) adata adata[adata.obs[n_genes_by_counts] 200].copy() # Store counts adata.layers[counts] adata.X.copy() # HVG selection sc.pp.highly_variable_genes( adata, n_top_genes4000, flavorseurat_v3, layercounts ) adata adata[:, adata.var[highly_variable]].copy() # Optional: Get initial cell type predictions (e.g., from a reference) # adata.obs[predicted_celltype] ...flavorseurat_v3配合layercounts可直接在原始计数上做 HVG 选择该方法内部做归一化处理不会污染X。若需要初始细胞类型预测例如来自 DestVI 或其他标注工具的结果写入adata.obs[predicted_celltype]即可作为弱监督标签。Step 2Setup 与训练 resolVI# Setup for resolVI (note: scvi.external, not scvi.model) scvi.external.RESOLVI.setup_anndata( adata, labels_keypredicted_celltype, # Initial cell type predictions layercounts ) # Create model (semisupervisedTrue uses the labels) model scvi.external.RESOLVI(adata, semisupervisedTrue) # Train model.train(max_epochs50)无初始标签时可省略labels_key以纯无监督方式训练提供标签时务必设置semisupervisedTrue使模型利用这些弱监督信号max_epochs50是参考值resolVI 相比 DestVI 收敛更快。Step 3获取细胞类型预测# Get refined cell type predictions # softTrue returns probabilities, softFalse returns labels cell_type_probs model.predict(adata, num_samples3, softTrue) cell_type_labels model.predict(adata, num_samples3, softFalse) adata.obs[resolvi_celltype] cell_type_labels # Visualize sq.pl.spatial_scatter(adata, colorresolvi_celltype)predict的soft参数控制输出类型softTrue返回各类别概率softFalse返回硬标签num_samples为多次采样求平均的次数增大该值可提高预测稳定性。Step 4获取潜在表示并聚类# Get latent representation adata.obsm[X_resolVI] model.get_latent_representation(adata) # Cluster based on spatial representation sc.pp.neighbors(adata, use_repX_resolVI) sc.tl.umap(adata) sc.tl.leiden(adata, resolution0.5) # Visualize clusters spatially sq.pl.spatial_scatter(adata, colorleiden)resolVI 的潜在表示编码了空间上下文信息因此在其上做 Leiden 聚类可以划分出空间上有意义的区域niche。仓库 scripts/cluster_embed.py 提供了等价的命令行实现python scripts/cluster_embed.py adata.h5ad results/ --resolution 0.5其内部同样采用 neighbors UMAP Leiden 的标准流程。Step 5细胞类型间差异表达DE# DE between cell types using resolVI de_results model.differential_expression( adata, groupbyresolvi_celltype, group1T_cell, group2Tumor ) print(de_results.head(20))groupby指定分组列group1/group2指定要对比的两组细胞类型。结果 DataFrame 中包含 log fold change、FDR 等统计量可据此筛选两组间的标志性差异基因。Step 6生态位丰度分析Niche AbundanceresolVI 还支持统计不同细胞类型邻域niche在不同条件间的丰度差异这需要先构建空间邻接图# Analyze how cell type neighborhoods differ between conditions # Requires spatial neighbor graph sq.gr.spatial_neighbors(adata, coord_typegeneric) niche_results model.differential_niche_abundance( groupbyresolvi_celltype, group1T_cell, group2Tumor, neighbor_keyspatial_neighbors )注意sq.gr.spatial_neighbors生成的邻接图默认存储在adata.obsp[spatial_neighbors]neighbor_keyspatial_neighbors必须与之匹配。Step 7Query Mapping迁移到新数据resolVI 支持把训练好的模型迁移到新的空间样本query复用参考样本学到的表示# Map new spatial data to trained model query_adata sc.read_visium(new_sample/) query_adata.layers[counts] query_adata.X.copy() # Prepare and load query model.prepare_query_anndata(query_adata, reference_modelmodel) query_model model.load_query_data(query_adata, reference_modelmodel) # Fine-tune on query query_model.train(max_epochs20) # Get predictions for query query_labels query_model.predict(query_adata, num_samples3, softFalse)该流程与 scArches 的 query-to-reference 映射思想一脉相承参见仓库 references/scarches_mapping.md先用prepare_query_anndata对齐基因再load_query_data载入参考模型权重最后在 query 上短训练微调即可快速获得该样本的细胞类型预测。可视化比例、区域富集与细胞互作多类型空间比例图import matplotlib.pyplot as plt # Plot multiple cell type proportions cell_types [T_cell, Tumor, Fibroblast, Macrophage] fig, axes plt.subplots(2, 2, figsize(12, 12)) for ax, ct in zip(axes.flat, cell_types): sq.pl.spatial_scatter( adata_spatial, colorfprop_{ct}, axax, titlect, showFalse ) plt.tight_layout()区域富集热图先对空间数据做 Leiden 聚类划分区域再按区域聚合各细胞类型比例均值用热图直观展示哪个区域富集哪种细胞# Cluster spatial data sc.pp.neighbors(adata_spatial) sc.tl.leiden(adata_spatial, resolution0.5) # Compare proportions across regions import pandas as pd cell_types adata_sc.obs[cell_type].unique() prop_cols [fprop_{ct} for ct in cell_types] region_props adata_spatial.obs.groupby(leiden)[prop_cols].mean() print(region_props) # Heatmap import seaborn as sns plt.figure(figsize(10, 6)) sns.heatmap(region_props.T, annotTrue, cmapviridis) plt.title(Cell Type Proportions by Region)空间细胞类型共现分析利用prop_*列先构造主导细胞类型注释再用 squidpy 的共现co-occurrence分析考察不同细胞类型在空间上的亲和关系# Neighborhood enrichment using cell type assignments sq.gr.spatial_neighbors(adata_spatial) # Create dominant cell type annotation prop_cols [fprop_{ct} for ct in cell_types] adata_spatial.obs[dominant_type] adata_spatial.obs[prop_cols].idxmax(axis1) adata_spatial.obs[dominant_type] adata_spatial.obs[dominant_type].str.replace(prop_, ) # Co-occurrence analysis sq.gr.co_occurrence(adata_spatial, cluster_keydominant_type) sq.pl.co_occurrence(adata_spatial, cluster_keydominant_type)idxmax(axis1)取每个 spot 上比例最高的细胞类型作为该 spot 的主导类型共现分析即可揭示哪些主导类型倾向于在空间上相邻。完整 DestVI 管线函数将上述 DestVI 步骤封装为可复用函数返回带比例注释的AnnData与两个训练好的模型def deconvolve_spatial( adata_spatial, adata_ref, cell_type_keycell_type, n_latent20, max_epochs_ref200, max_epochs_spatial500 ): Perform spatial deconvolution using DestVI. Parameters ---------- adata_spatial : AnnData Spatial transcriptomics data adata_ref : AnnData Single-cell reference with cell type annotations cell_type_key : str Column in adata_ref.obs with cell type labels n_latent : int Latent dimensions max_epochs_ref : int Training epochs for reference model max_epochs_spatial : int Training epochs for spatial model Returns ------- AnnData with cell type proportions in obs import scvi # Get common genes common_genes adata_ref.var_names.intersection(adata_spatial.var_names) adata_ref adata_ref[:, common_genes].copy() adata_spatial adata_spatial[:, common_genes].copy() # Ensure counts are stored if counts not in adata_ref.layers: adata_ref.layers[counts] adata_ref.X.copy() if counts not in adata_spatial.layers: adata_spatial.layers[counts] adata_spatial.X.copy() # Train reference model scvi.model.CondSCVI.setup_anndata( adata_ref, layercounts, labels_keycell_type_key ) ref_model scvi.model.CondSCVI(adata_ref, n_latentn_latent) ref_model.train(max_epochsmax_epochs_ref) # Train spatial model scvi.model.DestVI.setup_anndata(adata_spatial, layercounts) spatial_model scvi.model.DestVI.from_rna_model( adata_spatial, ref_model ) spatial_model.train(max_epochsmax_epochs_spatial) # Get proportions proportions spatial_model.get_proportions() cell_types adata_ref.obs[cell_type_key].unique() for ct in cell_types: adata_spatial.obs[fprop_{ct}] proportions[ct] # Add dominant type prop_cols [fprop_{ct} for ct in cell_types] adata_spatial.obs[dominant_type] adata_spatial.obs[prop_cols].idxmax(axis1) adata_spatial.obs[dominant_type] adata_spatial.obs[dominant_type].str.replace(prop_, ) return adata_spatial, ref_model, spatial_model # Usage adata_spatial, ref_model, spatial_model deconvolve_spatial( adata_spatial, adata_sc, cell_type_keycell_type ) # Visualize sq.pl.spatial_scatter( adata_spatial, color[dominant_type, prop_T_cell, prop_Tumor], ncols3 )从工程化角度这条管线可以在上游直接复用仓库 scripts/prepare_data.py 对空间与参考数据做标准化准备QC 过滤、counts层写入、HVG 选择其prepare_data()函数会自动完成n_genes_by_counts 200的细胞过滤与counts层落盘与本函数形成无缝衔接。训练过程中可通过 scripts/model_utils.py 的plot_training_history()检查 CondSCVI 与 DestVI 的 ELBO/重构损失收敛情况用save_results()统一保存模型model.save()、处理后的AnnData与可视化图。Troubleshooting常见问题与解决方案问题原因解决方案共同基因太少Few common genes基因命名体系不同转换基因名Ensembl ↔ Symbol解卷积效果差Poor deconvolution参考数据不匹配使用组织匹配tissue-matched的参考数据所有 spot 都被判为同一类型过度平滑Over-smoothing调整模型参数检查参考数据多样性出现 NaN 比例NaN proportions参考数据缺少某些细胞类型确保参考数据包含所有预期细胞类型训练缓慢Training slow空间数据集过大减少max_epochs增大batch_size仓库 references/troubleshooting.md 针对 DestVI 提供了更细的排查步骤可作为上述表格的补充# 1. Check gene overlap common_genes adata_ref.var_names.intersection(adata_spatial.var_names) print(fCommon genes: {len(common_genes)}) # Should be 1000 # 2. Use tissue-matched reference # Reference should contain all cell types expected in spatial data # 3. Check reference quality print(adata_ref.obs[cell_type].value_counts())此外两个通用性高频问题值得留意X should contain integers数据被归一化导致。解决方式是使用layercountssetup_anndata中显式指定或从adata.raw恢复原始计数CUDA out of memoryGPU 显存不足。可依次尝试减小batch_size默认 128可降至 64、缩小模型n_latent、n_layers调小、降低 HVG 数量如 1500或调用torch.cuda.empty_cache()。关键参考文献Lopez et al. (2022) DestVI identifies continuums of cell types in spatial transcriptomics data本文对应的仓库原始参考文档bio-research/skills/scvi-tools/references/spatial_deconvolution.mdscvi-tools 技能入口与模型选型bio-research/skills/scvi-tools/SKILL.md数据准备规范bio-research/skills/scvi-tools/references/data_preparation.md环境安装与版本兼容性bio-research/skills/scvi-tools/references/environment_setup.md跨模型通用排障bio-research/skills/scvi-tools/references/troubleshooting.mdscvi-tools 官方空间转录组教程见原文档 Key References 一节【免费下载链接】knowledge-work-pluginsOpen source repository of plugins primarily intended for knowledge workers to use in Claude Cowork项目地址: https://gitcode.com/GitHub_Trending/kn/knowledge-work-plugins创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
阅读完成 · 觉得有帮助?