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

scripts/differential_expression.py

#!/usr/bin/env python3
"""
Differential expression analysis using scvi-tools models.

Uses the trained model's differential_expression method which accounts
for batch effects and uses the generative model for inference.

Usage:
    python differential_expression.py model_dir/ adata.h5ad output.csv --groupby leiden
    python differential_expression.py model_dir/ adata.h5ad output.csv --groupby cell_type --group1 "T cells" --group2 "B cells"
"""

import argparse
import os
import sys


def run_de_analysis(
    model,
    adata,
    groupby,
    group1=None,
    group2=None,
    n_genes=None
):
    """
    Run differential expression analysis.

    Parameters
    ----------
    model : scvi model
        Trained model with differential_expression method
    adata : AnnData
        Data used for training
    groupby : str
        Column in obs to group by
    group1 : str, optional
        First group (if None, computes for all groups)
    group2 : str, optional
        Second group (rest if None)
    n_genes : int, optional
        Limit to top N genes per group

    Returns
    -------
    DataFrame with DE results
    """
    import pandas as pd

    if group1 is not None:
        # Specific comparison
        print(f"Comparing {group1} vs {group2 or 'rest'}...")
        de_results = model.differential_expression(
            groupby=groupby,
            group1=group1,
            group2=group2
        )

        # Add comparison info
        de_results["comparison"] = f"{group1}_vs_{group2 or 'rest'}"

    else:
        # All pairwise or one-vs-rest
        groups = adata.obs[groupby].unique()
        print(f"Computing DE for {len(groups)} groups...")

        all_results = []
        for group in groups:
            print(f"  Processing {group}...")
            try:
                de = model.differential_expression(
                    groupby=groupby,
                    group1=group
                )
                de["group"] = group
                all_results.append(de)
            except Exception as e:
                print(f"  Warning: Failed for {group}: {e}")

        de_results = pd.concat(all_results, ignore_index=False)

    # Filter to significant
    if "is_de_fdr_0.05" in de_results.columns:
        n_sig = de_results["is_de_fdr_0.05"].sum()
        print(f"Found {n_sig} significant DE genes (FDR < 0.05)")

    # Limit to top genes if requested
    if n_genes is not None and "lfc_mean" in de_results.columns:
        if "group" in de_results.columns:
            # Top N per group
            de_results = de_results.groupby("group").apply(
                lambda x: x.nlargest(n_genes, "lfc_mean")
            ).reset_index(drop=True)
        else:
            de_results = de_results.nlargest(n_genes, "lfc_mean")

    return de_results


def plot_volcano(de_results, output_path, group_name=None):
    """Create volcano plot of DE results."""
    import matplotlib.pyplot as plt
    import numpy as np

    if "lfc_mean" not in de_results.columns:
        print("Cannot create volcano plot: missing lfc_mean column")
        return

    fig, ax = plt.subplots(figsize=(8, 6))

    # Get values
    lfc = de_results["lfc_mean"].values
    if "bayes_factor" in de_results.columns:
        y_val = de_results["bayes_factor"].values
        y_label = "Bayes Factor"
    elif "proba_de" in de_results.columns:
        y_val = -np.log10(1 - de_results["proba_de"].values + 1e-10)
        y_label = "-log10(1 - P(DE))"
    else:
        y_val = np.ones(len(lfc))
        y_label = ""

    # Color by significance
    if "is_de_fdr_0.05" in de_results.columns:
        sig = de_results["is_de_fdr_0.05"].values
        colors = ["red" if s else "gray" for s in sig]
    else:
        colors = "gray"

    ax.scatter(lfc, y_val, c=colors, alpha=0.5, s=10)
    ax.axvline(0, color="black", linestyle="--", alpha=0.5)
    ax.set_xlabel("Log Fold Change")
    ax.set_ylabel(y_label)

    title = "Differential Expression"
    if group_name:
        title += f": {group_name}"
    ax.set_title(title)

    plt.tight_layout()
    plt.savefig(output_path, dpi=150, bbox_inches="tight")
    plt.close()
    print(f"Volcano plot saved to {output_path}")


def main():
    parser = argparse.ArgumentParser(
        description="Differential expression with scvi-tools",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
    # DE for all clusters (one-vs-rest)
    python differential_expression.py model/ adata.h5ad de_results.csv --groupby leiden

    # Specific comparison
    python differential_expression.py model/ adata.h5ad de_results.csv \\
        --groupby cell_type --group1 "T cells" --group2 "B cells"

    # Top 50 genes per cluster
    python differential_expression.py model/ adata.h5ad de_results.csv \\
        --groupby leiden --n-genes 50
        """
    )
    parser.add_argument("model_dir", help="Directory containing saved model")
    parser.add_argument("input", help="Input h5ad file (same as training)")
    parser.add_argument("output", help="Output CSV file for DE results")
    parser.add_argument("--groupby", required=True, help="Column to group by")
    parser.add_argument("--group1", help="First group for comparison")
    parser.add_argument("--group2", help="Second group (default: rest)")
    parser.add_argument("--n-genes", type=int, help="Limit to top N genes per group")
    parser.add_argument("--model-type", choices=["scvi", "scanvi", "totalvi"],
                        default="scvi", help="Model type (default: scvi)")
    parser.add_argument("--plot", action="store_true", help="Generate volcano plot")

    args = parser.parse_args()

    try:
        import scvi
        import scanpy as sc
    except ImportError:
        print("Error: scvi-tools and scanpy required")
        sys.exit(1)

    # Load data
    print(f"Loading {args.input}...")
    adata = sc.read_h5ad(args.input)

    # Load model
    print(f"Loading model from {args.model_dir}...")
    if args.model_type == "scvi":
        model = scvi.model.SCVI.load(args.model_dir, adata=adata)
    elif args.model_type == "scanvi":
        model = scvi.model.SCANVI.load(args.model_dir, adata=adata)
    elif args.model_type == "totalvi":
        model = scvi.model.TOTALVI.load(args.model_dir, adata=adata)

    # Run DE
    de_results = run_de_analysis(
        model,
        adata,
        groupby=args.groupby,
        group1=args.group1,
        group2=args.group2,
        n_genes=args.n_genes
    )

    # Save results
    de_results.to_csv(args.output)
    print(f"DE results saved to {args.output}")

    # Plot
    if args.plot:
        plot_path = args.output.replace(".csv", "_volcano.png")
        plot_volcano(de_results, plot_path, args.group1)

    print("\nDone!")


if __name__ == "__main__":
    main()

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