Generated banner for Scvi Tools
Generated logo for Scvi Tools

Scvi Tools

AnthropicOfficialPublished by Anthropic

  • Skill
  • Tool integration
  • Data and AI
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Deep learning for single-cell analysis using scvi-tools. This skill should be used when users need (1) data integration and batch correction with scVI/scANVI, (2) ATAC-seq analysis with PeakVI, (3) CITE-seq multi-modal analysis with totalVI, (4) multiome RNA+ATAC analysis with MultiVI, (5) spatial transcriptomics deconvolution with DestVI, (6) label transfer and reference mapping with scANVI/scArches, (7) RNA velocity with veloVI, or (8) any deep learning-based single-cell method. Triggers include mentions of scVI, scANVI, totalVI, PeakVI, MultiVI, DestVI, veloVI, sysVI, scArches, variational autoencoder, VAE, batch correction, data integration, multi-modal, CITE-seq, multiome, reference mapping, latent space.
— the description by Anthropic

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/anthropics/scvi-tools/download
  2. Unzip 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

  1. Identify the appropriate workflow from the model/workflow tables below

  2. Read the corresponding reference file for detailed steps and code

  3. Use scripts in scripts/ to avoid rewriting common code

  4. For installation or GPU issues, consult references/environment_setup.md

  5. For 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 TypeModelPrimary Use Case
scRNA-seqscVIUnsupervised integration, DE, imputation
scRNA-seq + labelsscANVILabel transfer, semi-supervised integration
CITE-seq (RNA+protein)totalVIMulti-modal integration, protein denoising
scATAC-seqPeakVIChromatin accessibility analysis
Multiome (RNA+ATAC)MultiVIJoint modality analysis
Spatial + scRNA referenceDestVICell type deconvolution
RNA velocityveloVITranscriptional dynamics
Cross-technologysysVISystem-level batch correction

Workflow Reference Files

WorkflowReference FileDescription
Environment Setupreferences/environment_setup.mdInstallation, GPU, version info
Data Preparationreferences/data_preparation.mdFormatting data for any model
scRNA Integrationreferences/scrna_integration.mdscVI/scANVI batch correction
ATAC-seq Analysisreferences/atac_peakvi.mdPeakVI for accessibility
CITE-seq Analysisreferences/citeseq_totalvi.mdtotalVI for protein+RNA
Multiome Analysisreferences/multiome_multivi.mdMultiVI for RNA+ATAC
Spatial Deconvolutionreferences/spatial_deconvolution.mdDestVI spatial analysis
Label Transferreferences/label_transfer.mdscANVI reference mapping
scArches Mappingreferences/scarches_mapping.mdQuery-to-reference mapping
Batch Correctionreferences/batch_correction_sysvi.mdAdvanced batch methods
RNA Velocityreferences/rna_velocity_velovi.mdveloVI dynamics
Troubleshootingreferences/troubleshooting.mdCommon issues and solutions

CLI Scripts

Modular scripts for common workflows. Chain together or modify as needed.

Pipeline Scripts
ScriptPurposeUsage
prepare_data.pyQC, filter, HVG selectionpython scripts/prepare_data.py raw.h5ad prepared.h5ad --batch-key batch
train_model.pyTrain any scvi-tools modelpython scripts/train_model.py prepared.h5ad results/ --model scvi
cluster_embed.pyNeighbors, UMAP, Leidenpython scripts/cluster_embed.py adata.h5ad results/
differential_expression.pyDE analysispython scripts/differential_expression.py model/ adata.h5ad de.csv --groupby leiden
transfer_labels.pyLabel transfer with scANVIpython scripts/transfer_labels.py ref_model/ query.h5ad results/
integrate_datasets.pyMulti-dataset integrationpython scripts/integrate_datasets.py results/ data1.h5ad data2.h5ad
validate_adata.pyCheck data compatibilitypython 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 leiden
Python Utilities

The scripts/model_utils.py provides importable functions for custom workflows:

FunctionPurpose
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

  1. 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")
  2. 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()
  3. 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

references/scrna_integration.md

scRNA-seq Integration with scVI and scANVI

This reference covers batch correction and dataset integration using scVI (unsupervised) and scANVI (semi-supervised with cell type labels).

Overview

Single-cell datasets often have batch effects from:

  • Different donors/patients

  • Different experimental batches

  • Different technologies (10x v2 vs v3)

  • Different studies

scVI and scANVI learn a shared latent space where batch effects are removed while biological variation is preserved.

When to Use Which Model

ModelUse WhenLabels Needed
scVINo labels available, exploratory analysisNo
scANVIHave partial/full labels, want better preservationYes (partial OK)

scVI Integration Workflow

Step 1: Prepare Data
import scvi
import scanpy as sc

# Load datasets
adata1 = sc.read_h5ad("dataset1.h5ad")
adata2 = sc.read_h5ad("dataset2.h5ad")

# Add batch annotation
adata1.obs["batch"] = "batch1"
adata2.obs["batch"] = "batch2"

# Concatenate
adata = sc.concat([adata1, adata2], label="batch")

# Ensure we have raw counts
# If data is normalized, recover from .raw
if hasattr(adata, 'raw') and adata.raw is not None:
    adata = adata.raw.to_adata()

# Store counts
adata.layers["counts"] = adata.X.copy()
Step 2: HVG Selection Across Batches
# Select HVGs considering batch
sc.pp.highly_variable_genes(
    adata,
    n_top_genes=2000,
    flavor="seurat_v3",
    batch_key="batch",
    layer="counts"
)

# Subset to HVGs
adata = adata[:, adata.var["highly_variable"]].copy()
Step 3: Setup and Train scVI
# Register data with scVI
scvi.model.SCVI.setup_anndata(
    adata,
    layer="counts",
    batch_key="batch"
)

# Create model
model = scvi.model.SCVI(
    adata,
    n_latent=30,          # Latent dimensions
    n_layers=2,           # Encoder/decoder depth
    gene_likelihood="nb"  # negative binomial (or "zinb")
)

# Train
model.train(
    max_epochs=200,
    early_stopping=True,
    early_stopping_patience=10,
    batch_size=128
)

# Plot training history
model.history["elbo_train"].plot()
Step 4: Get Integrated Representation
# Get latent representation
adata.obsm["X_scVI"] = model.get_latent_representation()

# Use for clustering and visualization
sc.pp.neighbors(adata, use_rep="X_scVI", n_neighbors=15)
sc.tl.umap(adata)
sc.tl.leiden(adata, resolution=1.0)

# Visualize integration
sc.pl.umap(adata, color=["batch", "leiden"], ncols=2)
Step 5: Save Model
# Save model for later use
model.save("scvi_model/")

# Load model
model = scvi.model.SCVI.load("scvi_model/", adata=adata)

scANVI Integration Workflow

scANVI extends scVI with cell type labels for better biological preservation.

Step 1: Prepare Data with Labels
# Labels should be in adata.obs
# Use "Unknown" for unlabeled cells
print(adata.obs["cell_type"].value_counts())

# For partially labeled data
# Mark unlabeled cells
adata.obs["cell_type_scanvi"] = adata.obs["cell_type"].copy()
# adata.obs.loc[unlabeled_mask, "cell_type_scanvi"] = "Unknown"
Step 2: Option A - Train scANVI from Scratch
# Setup for scANVI
scvi.model.SCANVI.setup_anndata(
    adata,
    layer="counts",
    batch_key="batch",
    labels_key="cell_type"
)

# Create model
scanvi_model = scvi.model.SCANVI(
    adata,
    n_latent=30,
    n_layers=2
)

# Train
scanvi_model.train(max_epochs=200)
# First train scVI
scvi.model.SCVI.setup_anndata(adata, layer="counts", batch_key="batch")
scvi_model = scvi.model.SCVI(adata, n_latent=30)
scvi_model.train(max_epochs=200)

# Initialize scANVI from scVI
scanvi_model = scvi.model.SCANVI.from_scvi_model(
    scvi_model,
    labels_key="cell_type",
    unlabeled_category="Unknown"  # For partially labeled data
)

# Fine-tune scANVI (fewer epochs needed)
scanvi_model.train(max_epochs=50)
Step 3: Get Results
# Latent representation
adata.obsm["X_scANVI"] = scanvi_model.get_latent_representation()

# Predicted labels for unlabeled cells
predictions = scanvi_model.predict()
adata.obs["predicted_cell_type"] = predictions

# Prediction probabilities
soft_predictions = scanvi_model.predict(soft=True)

# Visualization
sc.pp.neighbors(adata, use_rep="X_scANVI")
sc.tl.umap(adata)
sc.pl.umap(adata, color=["batch", "cell_type", "predicted_cell_type"])

Comparing Integration Quality

Visual Assessment
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 3, figsize=(15, 4))

# Before integration (on PCA)
sc.pp.pca(adata)
sc.pl.pca(adata, color="batch", ax=axes[0], title="Before (PCA)", show=False)

# After scVI
sc.pp.neighbors(adata, use_rep="X_scVI")
sc.tl.umap(adata)
sc.pl.umap(adata, color="batch", ax=axes[1], title="After scVI", show=False)

# After scANVI
sc.pp.neighbors(adata, use_rep="X_scANVI")
sc.tl.umap(adata)
sc.pl.umap(adata, color="batch", ax=axes[2], title="After scANVI", show=False)

plt.tight_layout()
Quantitative Metrics (scib)
# pip install scib-metrics

from scib_metrics.benchmark import Benchmarker

bm = Benchmarker(
    adata,
    batch_key="batch",
    label_key="cell_type",
    embedding_obsm_keys=["X_pca", "X_scVI", "X_scANVI"]
)

bm.benchmark()
bm.plot_results_table()

Differential Expression

scVI provides differential expression that accounts for batch effects:

# DE between groups
de_results = model.differential_expression(
    groupby="cell_type",
    group1="T cells",
    group2="B cells"
)

# Filter significant
de_sig = de_results[
    (de_results["is_de_fdr_0.05"] == True) &
    (abs(de_results["lfc_mean"]) > 1)
]

print(de_sig.head(20))

Advanced: Multiple Categorical Covariates

# Include additional covariates beyond batch
scvi.model.SCVI.setup_anndata(
    adata,
    layer="counts",
    batch_key="batch",
    categorical_covariate_keys=["donor", "technology"]
)

model = scvi.model.SCVI(adata, n_latent=30)
model.train()

Training Tips

For Large Datasets (>100k cells)
model.train(
    max_epochs=100,      # Fewer epochs needed
    batch_size=256,      # Larger batches
    train_size=0.9,      # Less validation
    early_stopping=True
)
For Small Datasets (<10k cells)
model = scvi.model.SCVI(
    adata,
    n_latent=10,         # Smaller latent space
    n_layers=1,          # Simpler model
    dropout_rate=0.2     # More regularization
)

model.train(
    max_epochs=400,
    batch_size=64
)
Monitoring Training
# Check training curves
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(model.history["elbo_train"], label="Train")
ax.plot(model.history["elbo_validation"], label="Validation")
ax.set_xlabel("Epoch")
ax.set_ylabel("ELBO")
ax.legend()

# Should see convergence without overfitting

Complete Pipeline

def integrate_datasets(
    adatas,
    batch_key="batch",
    labels_key=None,
    n_top_genes=2000,
    n_latent=30
):
    """
    Integrate multiple scRNA-seq datasets.
    
    Parameters
    ----------
    adatas : dict
        Dictionary of {batch_name: AnnData}
    batch_key : str
        Key for batch annotation
    labels_key : str, optional
        Key for cell type labels (uses scANVI if provided)
    n_top_genes : int
        Number of HVGs
    n_latent : int
        Latent dimensions
        
    Returns
    -------
    AnnData with integrated representation
    """
    import scvi
    import scanpy as sc
    
    # Add batch labels and concatenate
    for batch_name, adata in adatas.items():
        adata.obs[batch_key] = batch_name
    
    adata = sc.concat(list(adatas.values()), label=batch_key)
    
    # 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()
    
    # Train model
    if labels_key and labels_key in adata.obs.columns:
        # Use scANVI
        scvi.model.SCVI.setup_anndata(adata, layer="counts", batch_key=batch_key)
        scvi_model = scvi.model.SCVI(adata, n_latent=n_latent)
        scvi_model.train(max_epochs=200)
        
        model = scvi.model.SCANVI.from_scvi_model(
            scvi_model,
            labels_key=labels_key,
            unlabeled_category="Unknown"
        )
        model.train(max_epochs=50)
        rep_key = "X_scANVI"
    else:
        # Use scVI
        scvi.model.SCVI.setup_anndata(adata, layer="counts", batch_key=batch_key)
        model = scvi.model.SCVI(adata, n_latent=n_latent)
        model.train(max_epochs=200)
        rep_key = "X_scVI"
    
    # Add representation
    adata.obsm[rep_key] = model.get_latent_representation()
    
    # Compute neighbors and UMAP
    sc.pp.neighbors(adata, use_rep=rep_key)
    sc.tl.umap(adata)
    sc.tl.leiden(adata)
    
    return adata, model

# Usage
adatas = {
    "study1": sc.read_h5ad("study1.h5ad"),
    "study2": sc.read_h5ad("study2.h5ad"),
    "study3": sc.read_h5ad("study3.h5ad")
}

adata_integrated, model = integrate_datasets(
    adatas,
    labels_key="cell_type"
)

sc.pl.umap(adata_integrated, color=["batch", "leiden", "cell_type"])

Troubleshooting

IssueCauseSolution
Batches not mixingToo few shared genesUse more HVGs, check gene overlap
Over-correctionBiological variation removedUse scANVI with labels
Training divergesLearning rate too highReduce lr, increase batch_size
NaN lossBad dataCheck for all-zero cells/genes
Memory errorToo many cellsReduce batch_size, use GPU

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.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download scvi-tools.zip