Scvi Tools
AnthropicOfficialPublished by Anthropic
- Skill
- Tool integration
- Data and AI
- Apache-2.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
scvi-tools provides a suite of probabilistic models designed for the analysis of single-cell data, including scRNA-seq, scATAC-seq, and multi-modal datasets. It leverages variational autoencoders to handle batch correction, data integration, label transfer, and dimensionality reduction. This skill serves as a guide for utilizing specific models like scVI, scANVI, totalVI, PeakVI, MultiVI, DestVI, and veloVI, offering standardized workflows, CLI scripts for pipeline automation, and best practices for data preparation and model training.
What it does
- Performs batch correction and data integration across different experimental conditions.
- Supports multi-modal analysis for CITE-seq and multiome (RNA+ATAC) data.
- Enables label transfer and reference mapping between query and reference datasets.
- Facilitates spatial transcriptomics deconvolution and RNA velocity estimation.
- Provides modular Python scripts for common analysis pipelines.
- Offers guidance on model selection based on specific data types and research goals.
When to use it
- When integrating multiple single-cell datasets with significant batch effects.
- When analyzing multi-modal data such as CITE-seq or joint RNA+ATAC profiles.
- When performing reference-based label transfer or query-to-reference mapping.
- When conducting deep learning-based dimensionality reduction for clustering and visualization.
- When working with spatial transcriptomics or RNA velocity data.
Advantages
- Standardized approach to complex single-cell deep learning workflows.
- Modular scripts allow for reproducible and scalable analysis pipelines.
- Comprehensive model selection guide for diverse genomic data types.
- Built-in support for advanced tasks like batch correction and multi-modal integration.
- Clear documentation on data preparation requirements for probabilistic models.
Usage examples
- “How do I integrate two scRNA-seq datasets using scVI?”
- The agent provides the workflow for preparing the AnnData objects, selecting highly variable genes, setting up the model with batch keys, and training the scVI model.
- “I have CITE-seq data, which model should I use?”
- The agent identifies totalVI as the appropriate model and directs the user to the corresponding reference file for multi-modal integration.
- “How can I map my new scRNA-seq query data to an existing reference?”
- The agent explains the use of scArches for query-to-reference mapping and provides the necessary steps to configure the model.
- “What are the requirements for input data before training a model?”
- The agent outlines the necessity of raw integer count data, the importance of highly variable gene selection, and how to correctly set up the AnnData object.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/anthropics/scvi-tools/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip scvi-tools.zip -d .agents/skills
Documentation by Anthropic
scvi-tools Deep Learning Skill
This skill provides guidance for deep learning-based single-cell analysis using scvi-tools, the leading framework for probabilistic models in single-cell genomics.
How to Use This Skill
Identify the appropriate workflow from the model/workflow tables below
Read the corresponding reference file for detailed steps and code
Use scripts in
scripts/to avoid rewriting common codeFor installation or GPU issues, consult
references/environment_setup.mdFor debugging, consult
references/troubleshooting.md
When to Use This Skill
When scvi-tools, scVI, scANVI, or related models are mentioned
When deep learning-based batch correction or integration is needed
When working with multi-modal data (CITE-seq, multiome)
When reference mapping or label transfer is required
When analyzing ATAC-seq or spatial transcriptomics data
When learning latent representations of single-cell data
Model Selection Guide
| Data Type | Model | Primary Use Case |
|---|---|---|
| scRNA-seq | scVI | Unsupervised integration, DE, imputation |
| scRNA-seq + labels | scANVI | Label transfer, semi-supervised integration |
| CITE-seq (RNA+protein) | totalVI | Multi-modal integration, protein denoising |
| scATAC-seq | PeakVI | Chromatin accessibility analysis |
| Multiome (RNA+ATAC) | MultiVI | Joint modality analysis |
| Spatial + scRNA reference | DestVI | Cell type deconvolution |
| RNA velocity | veloVI | Transcriptional dynamics |
| Cross-technology | sysVI | System-level batch correction |
Workflow Reference Files
| Workflow | Reference File | Description |
|---|---|---|
| Environment Setup | references/environment_setup.md | Installation, GPU, version info |
| Data Preparation | references/data_preparation.md | Formatting data for any model |
| scRNA Integration | references/scrna_integration.md | scVI/scANVI batch correction |
| ATAC-seq Analysis | references/atac_peakvi.md | PeakVI for accessibility |
| CITE-seq Analysis | references/citeseq_totalvi.md | totalVI for protein+RNA |
| Multiome Analysis | references/multiome_multivi.md | MultiVI for RNA+ATAC |
| Spatial Deconvolution | references/spatial_deconvolution.md | DestVI spatial analysis |
| Label Transfer | references/label_transfer.md | scANVI reference mapping |
| scArches Mapping | references/scarches_mapping.md | Query-to-reference mapping |
| Batch Correction | references/batch_correction_sysvi.md | Advanced batch methods |
| RNA Velocity | references/rna_velocity_velovi.md | veloVI dynamics |
| Troubleshooting | references/troubleshooting.md | Common issues and solutions |
CLI Scripts
Modular scripts for common workflows. Chain together or modify as needed.
Pipeline Scripts
| Script | Purpose | Usage |
|---|---|---|
prepare_data.py | QC, filter, HVG selection | python scripts/prepare_data.py raw.h5ad prepared.h5ad --batch-key batch |
train_model.py | Train any scvi-tools model | python scripts/train_model.py prepared.h5ad results/ --model scvi |
cluster_embed.py | Neighbors, UMAP, Leiden | python scripts/cluster_embed.py adata.h5ad results/ |
differential_expression.py | DE analysis | python scripts/differential_expression.py model/ adata.h5ad de.csv --groupby leiden |
transfer_labels.py | Label transfer with scANVI | python scripts/transfer_labels.py ref_model/ query.h5ad results/ |
integrate_datasets.py | Multi-dataset integration | python scripts/integrate_datasets.py results/ data1.h5ad data2.h5ad |
validate_adata.py | Check data compatibility | python scripts/validate_adata.py data.h5ad --batch-key batch |
Example Workflow
# 1. Validate input data
python scripts/validate_adata.py raw.h5ad --batch-key batch --suggest
# 2. Prepare data (QC, HVG selection)
python scripts/prepare_data.py raw.h5ad prepared.h5ad --batch-key batch --n-hvgs 2000
# 3. Train model
python scripts/train_model.py prepared.h5ad results/ --model scvi --batch-key batch
# 4. Cluster and visualize
python scripts/cluster_embed.py results/adata_trained.h5ad results/ --resolution 0.8
# 5. Differential expression
python scripts/differential_expression.py results/model results/adata_clustered.h5ad results/de.csv --groupby leidenPython Utilities
The scripts/model_utils.py provides importable functions for custom workflows:
| Function | Purpose |
|---|---|
prepare_adata() | Data preparation (QC, HVG, layer setup) |
train_scvi() | Train scVI or scANVI |
evaluate_integration() | Compute integration metrics |
get_marker_genes() | Extract DE markers |
save_results() | Save model, data, plots |
auto_select_model() | Suggest best model |
quick_clustering() | Neighbors + UMAP + Leiden |
Critical Requirements
Raw counts required: scvi-tools models require integer count data
adata.layers["counts"] = adata.X.copy() # Before normalization scvi.model.SCVI.setup_anndata(adata, layer="counts")HVG selection: Use 2000-4000 highly variable genes
sc.pp.highly_variable_genes(adata, n_top_genes=2000, batch_key="batch", layer="counts", flavor="seurat_v3") adata = adata[:, adata.var['highly_variable']].copy()Batch information: Specify batch_key for integration
scvi.model.SCVI.setup_anndata(adata, layer="counts", batch_key="batch")
Quick Decision Tree
Need to integrate scRNA-seq data?
├── Have cell type labels? → scANVI (references/label_transfer.md)
└── No labels? → scVI (references/scrna_integration.md)
Have multi-modal data?
├── CITE-seq (RNA + protein)? → totalVI (references/citeseq_totalvi.md)
├── Multiome (RNA + ATAC)? → MultiVI (references/multiome_multivi.md)
└── scATAC-seq only? → PeakVI (references/atac_peakvi.md)
Have spatial data?
└── Need cell type deconvolution? → DestVI (references/spatial_deconvolution.md)
Have pre-trained reference model?
└── Map query to reference? → scArches (references/scarches_mapping.md)
Need RNA velocity?
└── veloVI (references/rna_velocity_velovi.md)
Strong cross-technology batch effects?
└── sysVI (references/batch_correction_sysvi.md)Key Resources
Files
- ATTRIBUTION.mdAdded by AutoGineer932 B
- LICENSE.txt10.0 KiB
- SKILL.md7.2 KiB
- references/atac_peakvi.md9.3 KiB
- references/batch_correction_sysvi.md10.2 KiB
- references/citeseq_totalvi.md10.1 KiB
- references/data_preparation.md6.2 KiB
- references/environment_setup.md6.3 KiB
- references/label_transfer.md10.2 KiB
- references/multiome_multivi.md8.9 KiB
- references/rna_velocity_velovi.md8.6 KiB
- references/scarches_mapping.md10.8 KiB
- references/scrna_integration.md9.6 KiB
- references/spatial_deconvolution.md11.2 KiB
- references/troubleshooting.md10.8 KiB
- scripts/cluster_embed.pyScript6.3 KiB
- scripts/differential_expression.pyScript6.7 KiB
- scripts/integrate_datasets.pyScript6.9 KiB
- scripts/model_utils.pyScript17.0 KiB
- scripts/prepare_data.pyScript5.1 KiB
- scripts/train_model.pyScript11.3 KiB
- scripts/transfer_labels.pyScript7.2 KiB
- scripts/validate_adata.pyScript11.9 KiB
references/citeseq_totalvi.md
CITE-seq Analysis with totalVI
This reference covers multi-modal analysis of CITE-seq data (RNA + surface proteins) using totalVI.
Overview
CITE-seq combines:
scRNA-seq (transcriptome)
Protein surface markers (antibody-derived tags, ADT)
totalVI jointly models both modalities to:
Integrate across batches
Denoise protein signal
Learn joint latent representation
Enable cross-modal imputation
Prerequisites
import scvi
import scanpy as sc
import mudata as md
import numpy as np
import pandas as pd
print(f"scvi-tools version: {scvi.__version__}")Step 1: Load CITE-seq Data
From 10x Genomics (Cell Ranger)
# 10x outputs separate gene expression and feature barcoding
adata_rna = sc.read_10x_h5("filtered_feature_bc_matrix.h5", gex_only=False)
# Separate RNA and protein
adata_protein = adata_rna[:, adata_rna.var['feature_types'] == 'Antibody Capture'].copy()
adata_rna = adata_rna[:, adata_rna.var['feature_types'] == 'Gene Expression'].copy()
print(f"RNA: {adata_rna.shape}")
print(f"Protein: {adata_protein.shape}")From MuData
# If data is in MuData format
mdata = md.read_h5mu("cite_seq.h5mu")
adata_rna = mdata['rna'].copy()
adata_protein = mdata['protein'].copy()Combine into Single AnnData
# totalVI expects protein data in obsm
adata = adata_rna.copy()
# Add protein expression to obsm
adata.obsm["protein_expression"] = adata_protein.X.toarray() if hasattr(adata_protein.X, 'toarray') else adata_protein.X
# Store protein names
adata.uns["protein_names"] = list(adata_protein.var_names)Step 2: Quality Control
RNA QC
# Standard RNA QC
# Handle both human (MT-) and mouse (mt-, Mt-) mitochondrial genes
adata.var['mt'] = (
adata.var_names.str.startswith('MT-') |
adata.var_names.str.startswith('mt-') |
adata.var_names.str.startswith('Mt-')
)
sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], inplace=True)
# Filter cells
adata = adata[adata.obs['n_genes_by_counts'] > 200].copy()
adata = adata[adata.obs['pct_counts_mt'] < 20].copy()
# Filter genes
sc.pp.filter_genes(adata, min_cells=3)Protein QC
# Protein QC
protein_counts = adata.obsm["protein_expression"]
print(f"Protein counts per cell: min={protein_counts.sum(1).min():.0f}, max={protein_counts.sum(1).max():.0f}")
# Check for isotype controls
# Isotype controls should have low counts
protein_names = adata.uns["protein_names"]
for i, name in enumerate(protein_names):
if 'isotype' in name.lower() or 'control' in name.lower():
print(f"{name}: mean={protein_counts[:, i].mean():.1f}")Step 3: Data Preparation
Store Raw Counts
# Store RNA counts
adata.layers["counts"] = adata.X.copy()
# Protein must be raw ADT counts (NOT CLR-normalized)
# WARNING: If importing from Seurat, ensure you use raw counts, not CLR-normalized data
# Seurat's NormalizeData(normalization.method = "CLR") transforms counts - use the original assayHVG Selection for RNA
# Select HVGs for RNA
# Note: totalVI uses all proteins regardless of HVG
sc.pp.highly_variable_genes(
adata,
n_top_genes=4000, # Use more for CITE-seq
flavor="seurat_v3",
batch_key="batch" if "batch" in adata.obs else None,
layer="counts"
)
# Subset to HVGs
adata = adata[:, adata.var["highly_variable"]].copy()Step 4: Setup and Train totalVI
# Setup AnnData for totalVI
scvi.model.TOTALVI.setup_anndata(
adata,
layer="counts",
protein_expression_obsm_key="protein_expression",
batch_key="batch" # Optional
)
# Create model
model = scvi.model.TOTALVI(
adata,
n_latent=20,
latent_distribution="normal" # or "ln" for log-normal
)
# Train
model.train(
max_epochs=200,
early_stopping=True,
batch_size=128
)
# Check training
model.history['elbo_train'].plot()Step 5: Get Latent Representation
# Joint latent space
adata.obsm["X_totalVI"] = model.get_latent_representation()
# Clustering and visualization
sc.pp.neighbors(adata, use_rep="X_totalVI")
sc.tl.umap(adata)
sc.tl.leiden(adata, resolution=1.0)
sc.pl.umap(adata, color=['leiden', 'batch'])Step 6: Denoised Protein Expression
# Get denoised protein values
# This removes background noise from protein measurements
_, protein_denoised = model.get_normalized_expression(
return_mean=True,
transform_batch="batch1" # Optional: normalize to specific batch
)
# Add to adata
adata.obsm["protein_denoised"] = protein_denoised
# Visualize denoised proteins
protein_names = adata.uns["protein_names"]
for i, protein in enumerate(protein_names[:5]):
adata.obs[f"denoised_{protein}"] = protein_denoised[:, i]
sc.pl.umap(adata, color=[f"denoised_{p}" for p in protein_names[:5]])Step 7: Normalized RNA Expression
# Get normalized RNA expression
rna_normalized, _ = model.get_normalized_expression(
return_mean=True
)
# Store
adata.layers["totalVI_normalized"] = rna_normalizedStep 8: Differential Expression
RNA Differential Expression
# DE between clusters
de_rna = model.differential_expression(
groupby="leiden",
group1="0",
group2="1"
)
# Filter significant genes
de_sig = de_rna[
(de_rna['is_de_fdr_0.05']) &
(abs(de_rna['lfc_mean']) > 1)
]
print(f"Significant DE genes: {len(de_sig)}")Protein Differential Expression
# Protein DE
de_protein = model.differential_expression(
groupby="leiden",
group1="0",
group2="1",
mode="protein"
)
print(de_protein.head(20))Step 9: Visualization
Protein Expression on UMAP
# Denoised protein on UMAP
import matplotlib.pyplot as plt
proteins_to_plot = ["CD3", "CD4", "CD8", "CD19", "CD14"]
fig, axes = plt.subplots(1, len(proteins_to_plot), figsize=(4*len(proteins_to_plot), 4))
for ax, protein in zip(axes, proteins_to_plot):
idx = adata.uns["protein_names"].index(protein)
sc.pl.umap(
adata,
color=adata.obsm["protein_denoised"][:, idx],
ax=ax,
title=protein,
show=False
)
plt.tight_layout()Joint Heatmap
# Heatmap of top genes and proteins per cluster
sc.pl.dotplot(
adata,
var_names=de_sig.index[:20].tolist(),
groupby="leiden",
layer="totalVI_normalized"
)Step 10: Cell Type Annotation
# Use both RNA and protein markers for annotation
# RNA markers
rna_markers = {
'T cells': ['CD3D', 'CD3E'],
'CD4 T': ['CD4'],
'CD8 T': ['CD8A', 'CD8B'],
'B cells': ['CD19', 'MS4A1'],
'Monocytes': ['CD14', 'LYZ']
}
# Check denoised protein expression
for i, protein in enumerate(adata.uns["protein_names"]):
if any(m in protein for m in ['CD3', 'CD4', 'CD8', 'CD19', 'CD14']):
print(f"{protein}: cluster means")
for cluster in adata.obs['leiden'].unique():
mask = adata.obs['leiden'] == cluster
mean_expr = adata.obsm["protein_denoised"][mask, i].mean()
print(f" Cluster {cluster}: {mean_expr:.2f}")Complete Pipeline
def analyze_citeseq(
adata_rna,
adata_protein,
batch_key=None,
n_top_genes=4000,
n_latent=20
):
"""
Complete CITE-seq analysis with totalVI.
Parameters
----------
adata_rna : AnnData
RNA expression (raw counts)
adata_protein : AnnData
Protein expression (raw counts)
batch_key : str, optional
Batch column in obs
n_top_genes : int
Number of HVGs
n_latent : int
Latent dimensions
Returns
-------
Tuple of (processed AnnData, trained model)
"""
import scvi
import scanpy as sc
# Ensure same cells
common_cells = adata_rna.obs_names.intersection(adata_protein.obs_names)
adata = adata_rna[common_cells].copy()
adata_protein = adata_protein[common_cells].copy()
# Add protein to obsm
adata.obsm["protein_expression"] = adata_protein.X.toarray() if hasattr(adata_protein.X, 'toarray') else adata_protein.X
adata.uns["protein_names"] = list(adata_protein.var_names)
# RNA QC
# Handle both human (MT-) and mouse (mt-, Mt-) mitochondrial genes
adata.var['mt'] = (
adata.var_names.str.startswith('MT-') |
adata.var_names.str.startswith('mt-') |
adata.var_names.str.startswith('Mt-')
)
sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], inplace=True)
adata = adata[adata.obs['pct_counts_mt'] < 20].copy()
sc.pp.filter_genes(adata, min_cells=3)
# Store counts
adata.layers["counts"] = adata.X.copy()
# HVG selection
sc.pp.highly_variable_genes(
adata,
n_top_genes=n_top_genes,
flavor="seurat_v3",
batch_key=batch_key,
layer="counts"
)
adata = adata[:, adata.var["highly_variable"]].copy()
# Setup totalVI
scvi.model.TOTALVI.setup_anndata(
adata,
layer="counts",
protein_expression_obsm_key="protein_expression",
batch_key=batch_key
)
# Train
model = scvi.model.TOTALVI(adata, n_latent=n_latent)
model.train(max_epochs=200, early_stopping=True)
# Get representations
adata.obsm["X_totalVI"] = model.get_latent_representation()
rna_norm, protein_denoised = model.get_normalized_expression(return_mean=True)
adata.layers["totalVI_normalized"] = rna_norm
adata.obsm["protein_denoised"] = protein_denoised
# Clustering
sc.pp.neighbors(adata, use_rep="X_totalVI")
sc.tl.umap(adata)
sc.tl.leiden(adata)
return adata, model
# Usage
adata, model = analyze_citeseq(
adata_rna,
adata_protein,
batch_key="batch"
)
# Visualize
sc.pl.umap(adata, color=['leiden', 'batch'])Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
| Protein signal noisy | Background not removed | Use get_normalized_expression with denoising |
| Batch effects persist | Need batch_key | Ensure batch_key is specified |
| Memory error | Too many genes | Reduce n_top_genes |
| Poor protein clustering | Few proteins | Normal - totalVI uses RNA for structure |
Key References
Gayoso et al. (2021) "Joint probabilistic modeling of single-cell multi-omic data with totalVI"
Requirements and compatibility
Written for: Claude Code, Claude apps
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Anthropic
- Publisher
- Anthropic (Official)
- Source
- anthropics/knowledge-work-plugins · bio-research/skills/scvi-tools · commit e050c2e
- Licence
- Apache License 2.0 (redistribution allowed)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Anthropic or Anthropic.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download scvi-tools.zip