Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update scvi-tools

Timothy Kassiseffb57c5699c
diff --git a/docs/skills.md b/docs/skills.md
index 76da2388..a47a72c1 100644
--- a/docs/skills.md
+++ b/docs/skills.md
@@ -54,7 +54,7 @@
- **Pathway Enrichment** - Pathway and gene-set enrichment analysis on gene lists or ranked gene data, with result interpretation. Supports over-representation analysis (ORA via Enrichr/Fisher's exact/hypergeometric), preranked and standard Gene Set Enrichment Analysis (GSEA), and single-sample scoring (ssGSEA/GSVA) using gseapy and the official g:Profiler client. Covers gene-set libraries (GO Biological Process/Molecular Function/Cellular Component, KEGG, Reactome, WikiPathways, and MSigDB collections including Hallmark, C2 canonical pathways, C5 ontology, and C7 immune signatures), gene-ID mapping (Ensembl/Entrez to symbols via Biomart, g:Convert, or mygene) and organism handling, choice of the statistical background universe, multiple-testing correction (Benjamini-Hochberg FDR vs g:Profiler g:SCS vs Bonferroni), redundancy reduction (enrichment maps, leading-edge genes, term clustering), and publication-ready tables plus dotplots/bar plots/GSEA running-score plots. Includes a CLI helper (run_enrichment.py) that runs ORA or preranked GSEA end-to-end — automatically building the ranking metric from a DESeq2 results table — and writes a results table and dotplot. Cross-references PyDESeq2 and Scanpy upstream (sources of differentially expressed genes and cluster markers) and database-lookup/gget for gene-ID mapping and Reactome/KEGG/STRING APIs. Use cases: functional interpretation of differentially expressed genes, CRISPR-screen hits, and single-cell cluster markers; GO/KEGG/Reactome/WikiPathways enrichment; preranked GSEA from DESeq2 statistics; pathway activity scoring per sample or cell; and building defensible, reproducible enrichment analyses that avoid common pitfalls (gene-ID/organism mismatch, wrong background, thresholding before GSEA)
- **Scanpy** - Comprehensive Python toolkit for single-cell RNA-seq data analysis built on AnnData (scanpy 1.12.x; Python 3.12+). Provides end-to-end workflows for preprocessing (quality control, scrublet doublet detection, normalization, log transformation), dimensionality reduction (PCA, UMAP, t-SNE), Leiden clustering, marker gene identification, pseudobulk aggregation via `get.aggregate()`, trajectory inference (PAGA, diffusion maps), and visualization. Key features include: efficient handling of large datasets using sparse matrices and experimental Dask out-of-core support, integration with scvi-tools for advanced analysis, batch correction methods (ComBat), and publication-quality plotting. Optional GPU acceleration via rapids-singlecell. Use cases: single-cell RNA-seq analysis, cell-type identification, exploratory cluster markers, pseudobulk DE workflows (with pydeseq2), trajectory analysis, and comprehensive single-cell genomics workflows
- **scVelo** - RNA velocity analysis for estimating cell state transitions from unspliced/spliced mRNA dynamics. Infers trajectory directions, computes latent time, and identifies driver genes in single-cell RNA-seq data. Complements Scanpy/scVI-tools for trajectory inference, enabling the study of cellular differentiation dynamics and lineage decisions at single-cell resolution
-- **scvi-tools** - Probabilistic deep learning models for single-cell omics analysis. PyTorch-based framework providing variational autoencoders (VAEs) for dimensionality reduction, batch correction, differential expression, and data integration across modalities. Includes 25+ models: scVI/scANVI (RNA-seq integration and cell type annotation), totalVI (CITE-seq protein+RNA), MultiVI (multiome RNA+ATAC integration), PeakVI (ATAC-seq analysis), DestVI/Stereoscope/Tangram (spatial transcriptomics deconvolution), MethylVI (methylation), CytoVI (flow/mass cytometry), VeloVI (RNA velocity), contrastiveVI (perturbation studies), and Solo (doublet detection). Supports seamless integration with Scanpy/AnnData ecosystem, GPU acceleration, reference mapping (scArches), and probabilistic differential expression with uncertainty quantification
+- **scvi-tools** - Probabilistic deep learning models for single-cell omics analysis. PyTorch-based framework providing variational autoencoders (VAEs) for dimensionality reduction, batch correction, differential expression, and data integration across modalities. Includes 30+ models: scVI/scANVI (RNA-seq integration and cell type annotation), totalVI/totalANVI (CITE-seq protein+RNA), MultiVI (multiome RNA+ATAC integration), PeakVI (ATAC-seq analysis), DestVI/Stereoscope/Tangram (spatial transcriptomics deconvolution), MethylVI (methylation), CytoVI (flow/mass cytometry), VeloVI (RNA velocity), contrastiveVI (perturbation studies), and Solo (doublet detection). Supports seamless integration with Scanpy/AnnData ecosystem, GPU acceleration, reference mapping (scArches), and probabilistic differential expression with uncertainty quantification
- **scikit-bio** - Python library for bioinformatics providing data structures, algorithms, and parsers for biological sequence analysis. Built on NumPy, SciPy, and pandas. Key features include: sequence objects (DNA, RNA, protein sequences) with biological alphabet validation, sequence alignment algorithms (local, global, semiglobal), phylogenetic tree manipulation, diversity metrics (alpha diversity, beta diversity, phylogenetic diversity), distance metrics for sequences and communities, file format parsers (FASTA, FASTQ, QIIME formats, Newick), and statistical analysis tools. Provides scikit-learn compatible transformers for machine learning workflows. Supports efficient processing of large sequence datasets. Use cases: sequence analysis, microbial ecology (16S rRNA analysis), metagenomics, phylogenetic analysis, and bioinformatics research requiring sequence manipulation and diversity calculations
- **TileDB-VCF** - High-performance C++ library with Python and CLI interfaces for efficient storage and retrieval of genomic variant-call data using TileDB multidimensional sparse array technology. Enables scalable VCF/BCF ingestion with incremental sample addition, compressed storage, parallel queries across genomic regions and samples, and export capabilities for population genomics workflows. Key features include: memory-efficient queries, cloud storage integration (S3, Azure, GCS), and CLI tools for dataset creation, sample ingestion, data export, and statistics. Supports building variant databases for large cohorts, population-scale genomics studies, and association analysis. Use cases: population genomics databases, cohort studies, variant discovery workflows, genomic data warehousing, and scaling to enterprise-level analysis with TileDB-Cloud platform
- **Zarr** - Python library (Zarr-Python 3.x) implementing chunked, compressed N-dimensional arrays for local disk and cloud object storage (S3, GCS via fsspec). Supports Zarr format 2 and 3, `zarr.codecs` compression (Blosc, gzip, zstd), partial chunk reads, consolidated metadata, sharding, and integration with NumPy, Dask, and Xarray. Use for out-of-core arrays, cloud-native pipelines, and large scientific datasets (genomics, imaging, climate). Skill: `zarr-python`
diff --git a/skills/scvi-tools/SKILL.md b/skills/scvi-tools/SKILL.md
index c563baf5..b989d730 100644
--- a/skills/scvi-tools/SKILL.md
+++ b/skills/scvi-tools/SKILL.md
@@ -3,7 +3,7 @@ name: scvi-tools
description: Deep generative models for single-cell omics. Use when you need probabilistic batch correction (scVI), transfer learning, differential expression with uncertainty, or multi-modal integration (TOTALVI, MultiVI). Best for advanced modeling, batch effects, multimodal data. For standard analysis pipelines use scanpy.
license: BSD-3-Clause license
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -11,7 +11,9 @@ metadata:
## Overview
-scvi-tools is a comprehensive Python framework for probabilistic models in single-cell genomics. Built on PyTorch and PyTorch Lightning, it provides deep generative models using variational inference for analyzing diverse single-cell data modalities.
+scvi-tools is a comprehensive Python framework for probabilistic models in single-cell genomics. Built on PyTorch and PyTorch Lightning, it provides deep generative models using variational inference for analyzing diverse single-cell data modalities. Current stable release: **scvi-tools 1.4.3** (May 2026).
+
+**Model namespaces matter:** core models (scVI, scANVI, totalVI, MultiVI, PeakVI, AUTOZI, CondSCVI, DestVI, LinearSCVI, AmortizedLDA, JaxSCVI) live under `scvi.model`. Most other models (VeloVI, contrastiveVI, CellAssign, PoissonVI, scBasset, MrVI, MethylVI/MethylANVI, CytoVI, SysVI, Decipher, gimVI, scVIVA, ResolVI, Stereoscope, Solo, totalANVI, DIAGVI) live under `scvi.external`. The reference files specify the correct namespace per model.
## When to Use This Skill
@@ -46,8 +48,10 @@ Models for analyzing single-cell chromatin data. See `references/models-atac-seq
### 3. Multimodal & Multi-omics Integration
Joint analysis of multiple data types. See `references/models-multimodal.md` for:
- **totalVI**: CITE-seq protein and RNA joint modeling
-- **MultiVI**: Paired and unpaired multi-omic integration
+- **totalANVI**: Semi-supervised CITE-seq (totalVI with cell-type labels)
+- **MultiVI**: Paired and unpaired multi-omic integration (MuData-based)
- **MrVI**: Multi-resolution cross-sample analysis
+- **DIAGVI**: Diagonal integration of unpaired single-cell datasets (added in 1.4.3)
### 4. Spatial Transcriptomics
Spatially-resolved transcriptomics analysis. See `references/models-spatial.md` for:
@@ -171,12 +175,20 @@ See `references/theoretical-foundations.md` for detailed background on the mathe
## Installation
+Requires Python **3.12+** (scvi-tools 1.4 dropped older versions).
+
```bash
uv pip install scvi-tools
# For GPU support
-uv pip install scvi-tools[cuda]
+uv pip install "scvi-tools[cuda]"
```
+For reproducible environments, pin a version: `uv pip install scvi-tools==1.4.3`.
+
+**Compute backends:** training defaults to PyTorch (CPU/GPU/TPU). A JAX backend
+(`scvi.model.JaxSCVI`) and an experimental MLX backend for Apple silicon
+(`scvi.model.mlxSCVI`) are available for select models.
+
## Best Practices
1. **Use raw counts**: Always provide unnormalized count data to models
diff --git a/skills/scvi-tools/references/differential-expression.md b/skills/scvi-tools/references/differential-expression.md
index e7eaa2b9..729e7906 100644
--- a/skills/scvi-tools/references/differential-expression.md
+++ b/skills/scvi-tools/references/differential-expression.md
@@ -245,6 +245,22 @@ large_effect = de_results[
## Advanced Usage
+### Differential Abundance
+
+In addition to differential *expression*, models exposing the `VAEMixin` API
+provide `differential_abundance()` and `get_aggregated_posterior()` (added in
+v1.4.2) to test how cell-state abundance shifts between conditions in the
+learned latent space:
+
+```python
+# Compare the latent-space abundance of two conditions
+da = model.differential_abundance(
+ groupby="condition",
+ group1="disease",
+ group2="healthy",
+)
+```
+
### DE Within Specific Cells
```python
diff --git a/skills/scvi-tools/references/models-atac-seq.md b/skills/scvi-tools/references/models-atac-seq.md
index 37b2f59b..09af9f96 100644
--- a/skills/scvi-tools/references/models-atac-seq.md
+++ b/skills/scvi-tools/references/models-atac-seq.md
@@ -95,19 +95,19 @@ da_results = model.differential_accessibility(
- Fragment count matrix (cells × genomic regions)
- Count data (not binary)
-**Basic Usage**:
+**Basic Usage** (PoissonVI lives in `scvi.external`):
```python
-scvi.model.POISSONVI.setup_anndata(
+scvi.external.POISSONVI.setup_anndata(
adata,
batch_key="batch"
)
-model = scvi.model.POISSONVI(adata)
+model = scvi.external.POISSONVI(adata)
model.train()
# Get results
latent = model.get_latent_representation()
-accessibility = model.get_accessibility_estimates()
+accessibility = model.get_normalized_accessibility()
```
**Key Differences from PeakVI**:
@@ -143,27 +143,24 @@ accessibility = model.get_accessibility_estimates()
- Peak accessibility matrix
- Genome reference (for sequence extraction)
-**Basic Usage**:
+**Basic Usage** (scBasset lives in `scvi.external`):
```python
-# scBasset requires sequence information
-# First, extract sequences for peaks
-from scbasset import utils
-sequences = utils.fetch_sequences(adata, genome="hg38")
-
-# Setup and train
-scvi.model.SCBASSET.setup_anndata(
+# scBasset needs per-peak DNA sequences. Add them to the AnnData first;
+# this downloads the genome (once) and stores one-hot codes in adata.varm.
+scvi.data.add_dna_sequence(
adata,
- batch_key="batch"
+ genome_name="hg38",
+ install_genome=True,
)
-model = scvi.model.SCBASSET(adata, sequences=sequences)
+# Register the per-peak sequence code, then train
+scvi.external.SCBASSET.setup_anndata(adata, dna_code_key="dna_code")
+
+model = scvi.external.SCBASSET(adata)
model.train()
-# Get latent representation
+# Cell embeddings (low-dimensional latent representation)
latent = model.get_latent_representation()
-
-# Interpret model: which sequences/motifs are important
-importance_scores = model.get_feature_importance()
```
**Key Parameters**:
@@ -179,12 +176,16 @@ importance_scores = model.get_feature_importance()
- **Transfer learning**: Fine-tune on new datasets
**Interpretability Tools**:
-```python
-# Get importance scores for sequences
-importance = model.get_sequence_importance(region_indices=[0, 1, 2])
-# Predict accessibility for new sequences
-predictions = model.predict_accessibility(new_sequences)
+scBasset learns sequence-aware cell and peak embeddings. Transcription-factor
+activity is assessed by scoring motif sequences against the trained model rather
+than calling a single importance function. See the
+[scBasset user guide](https://docs.scvi-tools.org/en/stable/user_guide/models/scbasset.html)
+for the current motif-injection / TF-activity workflow.
+
+```python
+# Cell embeddings for clustering / visualization
+cell_embedding = model.get_latent_representation()
```
## Model Selection for ATAC-seq
@@ -275,14 +276,21 @@ model.save("peakvi_model")
For paired multimodal data (RNA+ATAC from same cells), use **MultiVI** instead:
```python
-# For 10x Multiome or similar paired data
-scvi.model.MULTIVI.setup_anndata(
- adata,
+from mudata import MuData
+
+# MultiVI is configured from a MuData object (setup_anndata was removed in v1.3)
+mdata = MuData({"rna": rna_adata, "atac": atac_adata})
+scvi.model.MULTIVI.setup_mudata(
+ mdata,
batch_key="sample",
- modality_key="modality" # "RNA" or "ATAC"
+ modalities={"rna_layer": "rna", "atac_layer": "atac"},
)
-model = scvi.model.MULTIVI(adata)
+model = scvi.model.MULTIVI(
+ mdata,
+ n_genes=rna_adata.n_vars,
+ n_regions=atac_adata.n_vars,
+)
model.train()
# Get joint latent space
diff --git a/skills/scvi-tools/references/models-multimodal.md b/skills/scvi-tools/references/models-multimodal.md
index 4cd3b71a..49303351 100644
--- a/skills/scvi-tools/references/models-multimodal.md
+++ b/skills/scvi-tools/references/models-multimodal.md
@@ -96,6 +96,39 @@ denoised_protein = model.get_normalized_expression(
4. Validate protein imputation with known markers
5. Check protein QC metrics before training
+## totalANVI (Semi-supervised CITE-seq)
+
+**Purpose**: The semi-supervised counterpart to totalVI -- joint RNA + protein
+modeling that also propagates cell-type labels (totalVI is to scVI as totalANVI
+is to scANVI). Lives in `scvi.external`.
+
+**When to Use**:
+- CITE-seq integration where some cells are labeled and you want annotation transfer
+- Query-to-reference mapping on CITE-seq data
+
+**Basic Usage**:
+```python
+scvi.external.TOTALANVI.setup_anndata(
+ adata,
+ protein_expression_obsm_key="protein_expression",
+ batch_key="batch",
+ labels_key="cell_type",
+ unlabeled_category="Unknown",
+)
+model = scvi.external.TOTALANVI(adata)
+model.train()
+predictions = model.predict() # cell-type predictions
+```
+
+## DIAGVI (Diagonal Integration of Unpaired Data)
+
+**Purpose**: Integrate unpaired single-cell datasets (diagonal integration --
+datasets that do not share the same feature space or paired cells). Added in
+scvi-tools 1.4.3; lives in `scvi.external`. Consult the
+[scvi-tools API](https://docs.scvi-tools.org/en/stable/api/index.html) for the
+current setup signature, then follow the standard
+`setup -> train -> get_latent_representation` workflow.
+
## MultiVI (Multi-modal Variational Inference)
**Purpose**: Integration of paired and unpaired multi-omic data (e.g., RNA + ATAC, paired and unpaired cells).
@@ -114,67 +147,73 @@ denoised_protein = model.get_normalized_expression(
- Cross-modality imputation tasks
**Data Requirements**:
-- AnnData with multiple modalities
-- Modality indicators (which measurements each cell has)
+- A `MuData` object with one modality per `.mod` (e.g. `"rna"`, `"atac"`, optional `"protein"`)
- Can handle:
- All cells with both modalities (fully paired)
- Mix of paired and unpaired cells
- Completely unpaired datasets
+> **Breaking change (v1.3):** `MULTIVI.setup_anndata` was removed. Configure the
+> model from a `MuData` object via `setup_mudata`. For a single concatenated
+> multiome matrix, split it into per-modality AnnData with
+> `scvi.data.organize_multiome_anndatas` first.
+
**Basic Usage**:
```python
-# Prepare data with modality information
-# adata.X should contain all features (genes + peaks)
-# adata.var["modality"] indicates "Gene" or "Peak"
-# adata.obs["modality"] indicates which modality each cell has
-
-scvi.model.MULTIVI.setup_anndata(
- adata,
+import scvi
+from mudata import MuData
+
+# rna_adata: gene-expression counts; atac_adata: peak/region counts.
+# For a concatenated multiome matrix, split it first:
+# rna_adata, atac_adata = scvi.data.organize_multiome_anndatas(
+# multiome_adata, rna_indices_end=n_genes
+# )
+mdata = MuData({"rna": rna_adata, "atac": atac_adata})
+
+# Configure from the MuData object (modalities maps model args -> mod keys)
+scvi.model.MULTIVI.setup_mudata(
+ mdata,
batch_key="batch",
- modality_key="modality" # Column indicating cell modality
+ modalities={"rna_layer": "rna", "atac_layer": "atac"},
)
-model = scvi.model.MULTIVI(adata)
+model = scvi.model.MULTIVI(
+ mdata,
+ n_genes=rna_adata.n_vars,
+ n_regions=atac_adata.n_vars,
+)
model.train()
# Get joint latent representation
-latent = model.get_latent_representation()
-
-# Impute missing modalities
-# E.g., predict ATAC for RNA-only cells
-imputed_accessibility = model.get_accessibility_estimates(
- indices=rna_only_indices
-)
+mdata.obsm["X_multiVI"] = model.get_latent_representation()
-# Get normalized expression/accessibility
+# Get normalized expression / accessibility
rna_normalized = model.get_normalized_expression()
atac_normalized = model.get_accessibility_estimates()
```
**Key Parameters**:
-- `n_genes`: Number of gene features
-- `n_regions`: Number of accessibility regions
+- `n_genes`: Number of gene features (required)
+- `n_regions`: Number of accessibility regions (required)
- `n_latent`: Latent dimensionality (default: 20)
-**Integration Scenarios**:
+**Integration Scenarios** (handled by how you build the MuData / organize inputs):
**Scenario 1: Fully Paired (10x Multiome)**:
```python
-# All cells have both RNA and ATAC
-# Single modality key: "paired"
-adata.obs["modality"] = "paired"
+# Every cell measured in both modalities -- the two .mod objects share obs_names
+mdata = MuData({"rna": rna_adata, "atac": atac_adata})
```
-**Scenario 2: Partially Paired**:
+**Scenario 2 & 3: Partially or Completely Unpaired**:
```python
-# Some cells have both, some RNA-only, some ATAC-only
-adata.obs["modality"] = ["RNA+ATAC", "RNA", "ATAC", ...]
-```
-
-**Scenario 3: Completely Unpaired**:
-```python
-# Separate RNA and ATAC experiments
-adata.obs["modality"] = ["RNA"] * n_rna + ["ATAC"] * n_atac
+# Combine a paired multiome matrix with RNA-only and/or ATAC-only experiments.
+# organize_multiome_anndatas pads missing features and tracks per-cell modality.
+joint = scvi.data.organize_multiome_anndatas(
+ multi_anndata=paired_multiome_adata, # cells with both modalities (or None)
+ rna_anndata=rna_only_adata, # expression-only cells (optional)
+ atac_anndata=atac_only_adata, # accessibility-only cells (optional)
+)
```
**Advanced Use Cases**:
@@ -194,9 +233,9 @@ expression_from_atac = model.get_normalized_expression(
**Modality-Specific Analysis**:
```python
-# Separate analysis per modality
-rna_subset = adata[adata.obs["modality"].str.contains("RNA")]
-atac_subset = adata[adata.obs["modality"].str.contains("ATAC")]
+# Each modality is accessible as its own AnnData on the MuData object
+rna_subset = mdata.mod["rna"]
+atac_subset = mdata.mod["atac"]
```
## MrVI (Multi-resolution Variational Inference)
@@ -218,50 +257,44 @@ atac_subset = adata[adata.obs["modality"].str.contains("ATAC")]
- Understanding inter-sample heterogeneity
- Multi-donor studies
-**Basic Usage**:
+**Basic Usage** (MrVI lives in `scvi.external`; the default backend is now PyTorch):
```python
-scvi.model.MRVI.setup_anndata(
+scvi.external.MRVI.setup_anndata(
adata,
- layer="counts",
batch_key="batch",
- sample_key="sample" # Critical: defines biological samples
+ sample_key="sample", # Critical: defines biological samples
)
-model = scvi.model.MRVI(adata, n_latent=10, n_latent_sample=5)
+model = scvi.external.MRVI(adata)
model.train()
-# Get representations
-shared_latent = model.get_latent_representation() # Shared across samples
-sample_specific = model.get_sample_specific_representation()
+# Cell-state (u) representation, shared across samples
+shared_latent = model.get_latent_representation()
-# Sample distance matrix
-sample_distances = model.get_sample_distances()
+# Per-cell, sample-resolved representation and sample-sample distances
+local_sample_repr = model.get_local_sample_representation()
+sample_distances = model.get_local_sample_distances()
```
**Key Parameters**:
-- `n_latent`: Dimensionality of shared latent space
-- `n_latent_sample`: Dimensionality of sample-specific space
-- `sample_key`: Column defining biological samples
+- `sample_key`: Column in `adata.obs` defining biological samples (required)
+- `batch_key`: Technical batch covariate
+- `n_latent` / `n_latent_u`: Dimensionalities of the cell-state and sample-aware latent spaces
**Analysis Workflow**:
```python
-# 1. Identify shared cell types across samples
-sc.pp.neighbors(adata, use_rep="X_MrVI_shared")
+# 1. Identify shared cell states across samples
+adata.obsm["X_MrVI"] = model.get_latent_representation()
+sc.pp.neighbors(adata, use_rep="X_MrVI")
sc.tl.umap(adata)
sc.tl.leiden(adata, key_added="shared_clusters")
-# 2. Analyze sample-specific variation
-sample_repr = model.get_sample_specific_representation()
-
-# 3. Compare samples
-distances = model.get_sample_distances()
+# 2. Sample-resolved representation and pairwise sample distances
+local_sample_repr = model.get_local_sample_representation()
+distances = model.get_local_sample_distances()
-# 4. Find sample-enriched genes
-de_results = model.differential_expression(
- groupby="sample",
- group1="Disease",
- group2="Healthy"
-)
+# 3. Test how a sample covariate shifts abundance / expression
+de_results = model.differential_abundance(sample_cov_keys=["condition"])
```
**Use Cases**:
diff --git a/skills/scvi-tools/references/models-scrna-seq.md b/skills/scvi-tools/references/models-scrna-seq.md
index 67cce686..057a7e30 100644
--- a/skills/scvi-tools/references/models-scrna-seq.md
+++ b/skills/scvi-tools/references/models-scrna-seq.md
@@ -153,9 +153,9 @@ import scvelo as scv
scv.pp.filter_and_normalize(adata)
scv.pp.moments(adata)
-# Train VeloVI
-scvi.model.VELOVI.setup_anndata(adata, spliced_layer="Ms", unspliced_layer="Mu")
-model = scvi.model.VELOVI(adata)
+# Train VeloVI (lives in scvi.external)
+scvi.external.VELOVI.setup_anndata(adata, spliced_layer="Ms", unspliced_layer="Mu")
+model = scvi.external.VELOVI(adata)
model.train()
# Get velocity estimates
@@ -179,25 +179,26 @@ velocities = model.get_velocity()
- Separating treatment effects from background variation
- Comparing control vs. perturbed conditions
-**Basic Usage**:
+**Basic Usage** (contrastiveVI lives in `scvi.external`):
```python
-scvi.model.CONTRASTIVEVI.setup_anndata(
- adata,
- layer="counts",
- batch_key="batch",
- categorical_covariate_keys=["condition"] # control vs treated
-)
+import numpy as np
+
+scvi.external.ContrastiveVI.setup_anndata(adata, layer="counts")
-model = scvi.model.CONTRASTIVEVI(
+model = scvi.external.ContrastiveVI(
adata,
- n_latent=10, # Shared variation
- n_latent_target=5 # Target-specific variation
+ n_background_latent=10, # Shared/background variation
+ n_salient_latent=10, # Target-specific (salient) variation
)
-model.train()
+
+# Train with explicit background (control) and target (perturbed) cell indices
+background_idx = np.where(adata.obs["condition"] == "control")[0]
+target_idx = np.where(adata.obs["condition"] == "treated")[0]
+model.train(background_indices=background_idx, target_indices=target_idx)
# Extract representations
-shared = model.get_latent_representation(representation="shared")
-target_specific = model.get_latent_representation(representation="target")
+background = model.get_latent_representation(representation_kind="background")
+salient = model.get_latent_representation(representation_kind="salient")
```
## CellAssign
@@ -224,8 +225,10 @@ marker_gene_mat = pd.DataFrame({
"B cells": [0, 0, 0, 1]
}, index=["CD3D", "CD4", "CD8A", "CD19"])
-scvi.model.CELLASSIGN.setup_anndata(adata, layer="counts")
-model = scvi.model.CELLASSIGN(adata, marker_gene_mat)
+# CellAssign lives in scvi.external and needs a size factor per cell
+adata.obs["size_factor"] = adata.X.sum(axis=1)
+scvi.external.CellAssign.setup_anndata(adata, size_factor_key="size_factor")
+model = scvi.external.CellAssign(adata, marker_gene_mat)
model.train()
predictions = model.predict()
@@ -281,15 +284,15 @@ adata.obs["doublet_score"] = doublet_scores
**Basic Usage**:
```python
-scvi.model.AMORTIZEDLDA.setup_anndata(adata, layer="counts")
-model = scvi.model.AMORTIZEDLDA(adata, n_topics=10)
+scvi.model.AmortizedLDA.setup_anndata(adata, layer="counts")
+model = scvi.model.AmortizedLDA(adata, n_topics=10)
model.train()
-# Get topic compositions per cell
+# Get topic compositions per cell (Monte Carlo estimate of topic proportions)
topic_proportions = model.get_latent_representation()
-# Get gene loadings per topic
-topic_gene_loadings = model.get_topic_distribution()
+# Get gene-by-topic loadings
+topic_gene_loadings = model.get_feature_by_topic()
```
## Model Selection Guidelines
diff --git a/skills/scvi-tools/references/models-spatial.md b/skills/scvi-tools/references/models-spatial.md
index 0d3e4d3e..de5ff398 100644
--- a/skills/scvi-tools/references/models-spatial.md
+++ b/skills/scvi-tools/references/models-spatial.md
@@ -25,41 +25,33 @@ This document covers models for analyzing spatially-resolved transcriptomics dat
- **Single-cell reference**: scRNA-seq with cell type annotations
- Both datasets should share genes
-**Basic Usage**:
+**Basic Usage** (DestVI requires a `CondSCVI` reference model, not plain `SCVI`):
```python
-import scvi
+from scvi.model import CondSCVI, DestVI
-# Step 1: Train scVI on single-cell reference
-scvi.model.SCVI.setup_anndata(sc_adata, layer="counts")
-sc_model = scvi.model.SCVI(sc_adata)
-sc_model.train()
+# Step 1: Train the single-cell LVM (CondSCVI) on the labeled reference
+CondSCVI.setup_anndata(sc_adata, layer="counts", labels_key="cell_type")
+sc_model = CondSCVI(sc_adata, weight_obs=False)
+sc_model.train(max_epochs=300)
-# Step 2: Setup spatial data
-scvi.model.DESTVI.setup_anndata(
- spatial_adata,
- layer="counts"
-)
-
-# Step 3: Train DestVI using reference
-model = scvi.model.DESTVI.from_rna_model(
- spatial_adata,
- sc_model,
- cell_type_key="cell_type" # Cell type labels in reference
-)
-model.train(max_epochs=2500)
+# Step 2: Set up the spatial data and build DestVI from the trained reference
+DestVI.setup_anndata(spatial_adata, layer="counts")
+st_model = DestVI.from_rna_model(spatial_adata, sc_model)
+st_model.train(max_epochs=2500)
-# Step 4: Get cell type proportions
-proportions = model.get_proportions()
+# Step 3: Get cell type proportions per spot
+proportions = st_model.get_proportions()
spatial_adata.obsm["proportions"] = proportions
-# Step 5: Get cell type-specific expression
+# Step 4: Get cell type-specific expression
# Expression of genes specific to each cell type at each spot
-ct_expression = model.get_scale_for_ct("T cells")
+ct_expression = st_model.get_scale_for_ct("T cells")
```
**Key Parameters**:
+- `weight_obs` (CondSCVI): downweight common cell types when training the reference
- `amortization`: Amortization strategy ("both", "latent", "proportion")
-- `n_latent`: Latent dimensionality (inherited from scVI model)
+- `n_latent`: Latent dimensionality (inherited from the CondSCVI reference)
**Outputs**:
- `get_proportions()`: Cell type proportions at each spot
@@ -103,29 +95,21 @@ for ct in cell_types:
- Deconvolving spatial data with reference
- Faster alternative for basic deconvolution
-**Basic Usage**:
+**Basic Usage** (Stereoscope is split into two `scvi.external` models):
```python
-scvi.model.STEREOSCOPE.setup_anndata(
- sc_adata,
- labels_key="cell_type",
- layer="counts"
-)
+from scvi.external import RNAStereoscope, SpatialStereoscope
-# Train on reference
-ref_model = scvi.model.STEREOSCOPE(sc_adata)
-ref_model.train()
+# Train the single-cell reference model
+RNAStereoscope.setup_anndata(sc_adata, labels_key="cell_type", layer="counts")
+sc_model = RNAStereoscope(sc_adata)
+sc_model.train(max_epochs=100)
-# Setup spatial data
-scvi.model.STEREOSCOPE.setup_anndata(spatial_adata, layer="counts")
+# Build the spatial model from the trained reference
+SpatialStereoscope.setup_anndata(spatial_adata, layer="counts")
+spatial_model = SpatialStereoscope.from_rna_model(spatial_adata, sc_model)
+spatial_model.train(max_epochs=2000)
-# Transfer to spatial
-spatial_model = scvi.model.STEREOSCOPE.from_reference_model(
- spatial_adata,
- ref_model
-)
-spatial_model.train()
-
-# Get proportions
+# Get cell-type proportions per spot
proportions = spatial_model.get_proportions()
```
@@ -150,6 +134,10 @@ proportions = spatial_model.get_proportions()
- Spatial transcriptomics data
- Shared genes between modalities
+> scvi-tools wraps the Tangram method as `scvi.external.Tangram`. The example
+> below uses the standalone `tangram-sc` package, whose helper functions
+> (annotation/gene projection) are convenient for downstream analysis.
+
**Basic Usage**:
```python
import tangram as tg
@@ -204,19 +192,16 @@ sc.pl.spatial(
**Basic Usage**:
```python
-# Combine datasets
-combined_adata = sc.concat([sc_adata, spatial_adata])
+# gimVI (scvi.external) jointly models a single-cell and a spatial dataset
+scvi.external.GIMVI.setup_anndata(sc_adata, layer="counts")
+scvi.external.GIMVI.setup_anndata(spatial_adata, layer="counts")
-scvi.model.GIMVI.setup_anndata(
- combined_adata,
- layer="counts"
-)
-
-model = scvi.model.GIMVI(combined_adata)
+model = scvi.external.GIMVI(sc_adata, spatial_adata)
model.train()
-# Impute genes in spatial data
-imputed = model.get_imputed_values(spatial_indices)
+# Per-dataset latent representations and imputed expression
+sc_latent, spatial_latent = model.get_latent_representation()
+_, imputed_spatial = model.get_imputed_values(normalized=True)
```
## scVIVA (Variation in Variational Autoencoders for Spatial)
@@ -239,24 +224,33 @@ imputed = model.get_imputed_values(spatial_indices)
- Spatial transcriptomics with coordinates
- Cell type annotations (optional)
-**Basic Usage**:
+**Basic Usage** (scVIVA lives in `scvi.external`):
```python
-scvi.model.SCVIVA.setup_anndata(
+# scVIVA jointly models each cell and its niche. Precompute neighborhood
+# composition / embeddings first, then register the resulting keys.
+scvi.external.SCVIVA.preprocess_anndata(
spatial_adata,
- layer="counts",
- spatial_key="spatial" # Coordinates in .obsm
+ sample_key="sample",
+ labels_key="cell_type",
+ cell_coordinates_key="spatial", # coordinates in .obsm
)
-model = scvi.model.SCVIVA(spatial_adata)
-model.train()
+scvi.external.SCVIVA.setup_anndata(
+ spatial_adata,
+ labels_key="cell_type",
+ sample_key="sample",
+)
-# Get environment representations
-env_latent = model.get_environment_representation()
+model = scvi.external.SCVIVA(spatial_adata)
+model.train()
-# Identify environment-associated genes
-env_genes = model.get_environment_specific_genes()
+# Latent representation capturing cell state in its spatial context
+spatial_adata.obsm["X_scVIVA"] = model.get_latent_representation()
```
+See the [scVIVA user guide](https://docs.scvi-tools.org/en/stable/user_guide/models/scviva.html)
+for the exact preprocessing keys and niche/environment outputs.
+
## ResolVI
**Purpose**: Addressing spatial transcriptomics noise through resolution-aware modeling.
@@ -273,19 +267,18 @@ env_genes = model.get_environment_specific_genes()
- Need denoising before analysis
- Improving data quality
-**Basic Usage**:
+**Basic Usage** (ResolVI lives in `scvi.external`):
```python
-scvi.model.RESOLVI.setup_anndata(
+scvi.external.RESOLVI.setup_anndata(
spatial_adata,
layer="counts",
- spatial_key="spatial"
)
-model = scvi.model.RESOLVI(spatial_adata)
+model = scvi.external.RESOLVI(spatial_adata)
model.train()
-# Get denoised expression
-denoised = model.get_denoised_expression()
+# Denoised / corrected expression
+denoised = model.get_normalized_expression()
```
## Model Selection for Spatial Transcriptomics
@@ -355,15 +348,17 @@ sc_adata = sc.read_h5ad("reference_scrna.h5ad")
sc.pp.filter_genes(sc_adata, min_cells=10)
sc.pp.highly_variable_genes(sc_adata, n_top_genes=4000)
-# Train scVI on reference
-scvi.model.SCVI.setup_anndata(
+# Train the CondSCVI reference model (labels_key carries cell types)
+from scvi.model import CondSCVI, DestVI
+
+CondSCVI.setup_anndata(
sc_adata,
layer="counts",
- batch_key="batch"
+ labels_key="cell_type",
)
-sc_model = scvi.model.SCVI(sc_adata)
-sc_model.train(max_epochs=400)
+sc_model = CondSCVI(sc_adata, weight_obs=False)
+sc_model.train(max_epochs=300)
# ===== Part 2: Load spatial data =====
spatial_adata = sc.read_visium("path/to/visium")
@@ -373,15 +368,14 @@ spatial_adata.var_names_make_unique()
sc.pp.filter_genes(spatial_adata, min_cells=10)
# ===== Part 3: Run DestVI =====
-scvi.model.DESTVI.setup_anndata(
+DestVI.setup_anndata(
spatial_adata,
layer="counts"
)
-destvi_model = scvi.model.DESTVI.from_rna_model(
+destvi_model = DestVI.from_rna_model(
spatial_adata,
sc_model,
- cell_type_key="cell_type"
)
destvi_model.train(max_epochs=2500)
diff --git a/skills/scvi-tools/references/models-specialized.md b/skills/scvi-tools/references/models-specialized.md
index b7917896..5cf4b8ee 100644
--- a/skills/scvi-tools/references/models-specialized.md
+++ b/skills/scvi-tools/references/models-specialized.md
@@ -29,13 +29,13 @@ This document covers models for specialized single-cell data modalities in scvi-
import scvi
# Setup methylation data
-scvi.model.METHYLVI.setup_anndata(
+scvi.external.METHYLVI.setup_anndata(
adata,
layer="methylation_counts", # Methylation data
batch_key="batch"
)
-model = scvi.model.METHYLVI(adata)
+model = scvi.external.METHYLVI(adata)
model.train()
# Get latent representation
@@ -50,7 +50,7 @@ normalized_meth = model.get_normalized_methylation()
**Basic Usage**:
```python
# Setup with cell type labels
-scvi.model.METHYLANVI.setup_anndata(
+scvi.external.METHYLANVI.setup_anndata(
adata,
layer="methylation_counts",
batch_key="batch",
@@ -58,7 +58,7 @@ scvi.model.METHYLANVI.setup_anndata(
unlabeled_category="Unknown"
)
-model = scvi.model.METHYLANVI(adata)
+model = scvi.external.METHYLANVI(adata)
model.train()
# Predict cell types
@@ -98,13 +98,13 @@ predictions = model.predict()
**Basic Usage**:
```python
-scvi.model.CYTOVI.setup_anndata(
+scvi.external.CYTOVI.setup_anndata(
adata,
protein_expression_obsm_key="protein_expression",
batch_key="batch"
)
-model = scvi.model.CYTOVI(adata)
+model = scvi.external.CYTOVI(adata)
model.train()
# Get batch-corrected representation
@@ -126,12 +126,12 @@ import scanpy as sc
adata = sc.read_h5ad("cytof_data.h5ad")
# 2. Train CytoVI
-scvi.model.CYTOVI.setup_anndata(
+scvi.external.CYTOVI.setup_anndata(
adata,
protein_expression_obsm_key="protein",
batch_key="experiment"
)
-model = scvi.model.CYTOVI(adata)
+model = scvi.external.CYTOVI(adata)
model.train()
# 3. Get batch-corrected values
@@ -163,13 +163,13 @@ sc.pl.umap(adata, color=["batch", "leiden"])
**Basic Usage**:
```python
-scvi.model.SYSVI.setup_anndata(
+scvi.external.SysVI.setup_anndata(
adata,
layer="counts",
batch_key="batch"
)
-model = scvi.model.SYSVI(adata)
+model = scvi.external.SysVI(adata)
model.train()
latent = model.get_latent_representation()
@@ -191,62 +191,25 @@ latent = model.get_latent_representation()
- Understanding cell state transitions
- Identifying branching points in development
-**Basic Usage**:
+**Basic Usage** (Decipher lives in `scvi.external`):
```python
-# Typically used after scVI for embeddings
-scvi_model = scvi.model.SCVI(adata)
-scvi_model.train()
-
-# Decipher for trajectory
-scvi.model.DECIPHER.setup_anndata(adata)
-decipher_model = scvi.model.DECIPHER(adata, scvi_model)
+# Decipher learns its own interpretable low-dimensional representation
+scvi.external.Decipher.setup_anndata(adata, layer="counts")
+decipher_model = scvi.external.Decipher(adata)
decipher_model.train()
-# Get pseudotime
-pseudotime = decipher_model.get_pseudotime()
-adata.obs["pseudotime"] = pseudotime
+# Interpretable Decipher representation for trajectory/structure analysis
+adata.obsm["X_decipher"] = decipher_model.get_latent_representation()
```
**Visualization**:
```python
import scanpy as sc
-# Plot pseudotime on UMAP
-sc.pl.umap(adata, color="pseudotime", cmap="viridis")
-
-# Gene expression along pseudotime
-sc.pl.scatter(adata, x="pseudotime", y="gene_of_interest")
-```
-
-## peRegLM (Peak Regulatory Linear Model)
-
-**Purpose**: Linking chromatin accessibility to gene expression for regulatory analysis.
-
-**Key Features**:
-- Links ATAC-seq peaks to gene expression
-- Identifies regulatory relationships
-- Works with paired multiome data
-
-**When to Use**:
-- Multiome data (RNA + ATAC from same cells)
-- Understanding gene regulation
-- Linking peaks to target genes
-- Regulatory network construction
-
-**Basic Usage**:
-```python
-# Requires paired RNA + ATAC data
-scvi.model.PEREGLM.setup_anndata(
- multiome_adata,
- rna_layer="counts",
- atac_layer="atac_counts"
-)
-
-model = scvi.model.PEREGLM(multiome_adata)
-model.train()
-
-# Get peak-gene links
-peak_gene_links = model.get_regulatory_links()
+# Build a neighborhood graph on the Decipher representation, then embed
+sc.pp.neighbors(adata, use_rep="X_decipher")
+sc.tl.umap(adata)
+sc.pl.umap(adata, color="cell_type")
```
## Model-Specific Best Practices
@@ -281,7 +244,7 @@ Many specialized models work well in combination:
**Methylation + Expression**:
```python
# Analyze separately, then integrate
-methylvi_model = scvi.model.METHYLVI(meth_adata)
+methylvi_model = scvi.external.METHYLVI(meth_adata)
scvi_model = scvi.model.SCVI(rna_adata)
# Integrate results at analysis level
@@ -291,7 +254,7 @@ scvi_model = scvi.model.SCVI(rna_adata)
**Cytometry + CITE-seq**:
```python
# CytoVI for flow/CyTOF
-cyto_model = scvi.model.CYTOVI(cyto_adata)
+cyto_model = scvi.external.CYTOVI(cyto_adata)
# totalVI for CITE-seq
cite_model = scvi.model.TOTALVI(cite_adata)
@@ -301,11 +264,16 @@ cite_model = scvi.model.TOTALVI(cite_adata)
**ATAC + RNA (Multiome)**:
```python
-# MultiVI for joint analysis
-multivi_model = scvi.model.MULTIVI(multiome_adata)
+from mudata import MuData
-# peRegLM for regulatory links
-pereglm_model = scvi.model.PEREGLM(multiome_adata)
+# MultiVI for joint analysis (configured from a MuData object; see models-multimodal.md)
+mdata = MuData({"rna": rna_adata, "atac": atac_adata})
+scvi.model.MULTIVI.setup_mudata(
+ mdata, modalities={"rna_layer": "rna", "atac_layer": "atac"}
+)
+multivi_model = scvi.model.MULTIVI(
+ mdata, n_genes=rna_adata.n_vars, n_regions=atac_adata.n_vars
+)
```
## Choosing Specialized Models
@@ -317,7 +285,6 @@ pereglm_model = scvi.model.PEREGLM(multiome_adata)
- Flow/CyTOF → CytoVI
- Trajectory → Decipher
- Multi-batch integration → SysVI
- - Regulatory links → peRegLM
2. **Do you have labels?**
- Yes → MethylANVI (methylation)
@@ -326,7 +293,6 @@ pereglm_model = scvi.model.PEREGLM(multiome_adata)
3. **What's your main goal?**
- Batch correction → CytoVI, SysVI
- Trajectory/pseudotime → Decipher
- - Peak-gene links → peRegLM
- Methylation patterns → MethylVI/ANVI
## Example: Complete Methylation Analysis
@@ -342,14 +308,14 @@ meth_adata = sc.read_h5ad("methylation_data.h5ad")
sc.pp.filter_genes(meth_adata, min_cells=10)
# 3. Setup MethylVI
-scvi.model.METHYLVI.setup_anndata(
+scvi.external.METHYLVI.setup_anndata(
meth_adata,
layer="methylation",
batch_key="batch"
)
# 4. Train model
-model = scvi.model.METHYLVI(meth_adata, n_latent=15)
+model = scvi.external.METHYLVI(meth_adata, n_latent=15)
model.train(max_epochs=400)
# 5. Get latent representation
@@ -386,11 +352,14 @@ solo.train()
doublets = solo.predict()
```
-**scArches** (reference mapping):
+**scArches** (reference mapping): scArches-style surgery is built into the
+core models via `ArchesMixin`, not a separate `SCARCHES` class. Train a
+reference model, then map a query with `load_query_data`:
```python
-from scvi.external import SCARCHES
-
-# For transfer learning and query-to-reference mapping
+# Reference model already trained and saved to "./reference_model"
+query_model = scvi.model.SCVI.load_query_data(query_adata, "./reference_model")
+query_model.train(max_epochs=200, plan_kwargs={"weight_decay": 0.0})
+query_latent = query_model.get_latent_representation()
```
These external tools extend scvi-tools functionality for specific use cases.
@@ -404,5 +373,4 @@ These external tools extend scvi-tools functionality for specific use cases.
| CytoVI | Cytometry | Batch correction | No |
| SysVI | scRNA-seq | Large-scale integration | No |
| Decipher | scRNA-seq | Trajectory inference | No |
-| peRegLM | Multiome | Peak-gene links | No |
| SOLO | scRNA-seq | Doublet detection | Semi |
diff --git a/skills/scvi-tools/references/workflows.md b/skills/scvi-tools/references/workflows.md
index d1fa86d1..42bd46ff 100644
--- a/skills/scvi-tools/references/workflows.md
+++ b/skills/scvi-tools/references/workflows.md
@@ -75,8 +75,8 @@ scvi.model.SCVI.setup_anndata(
continuous_covariate_keys=["percent_mito", "n_counts"]
)
-# Check registration
-adata.uns['_scvi']['summary_stats']
+# Check registration (inspect the AnnData setup recorded by the model)
+scvi.model.SCVI.view_anndata_setup(adata)
```
### 5. Model Training
@@ -106,6 +106,19 @@ train_history = model.history["elbo_train"]
val_history = model.history["elbo_validation"]
```
+To keep the best checkpoint during training, enable checkpointing (the legacy
+`SaveBestState` callback was removed in v1.3; use `scvi.train.SaveCheckpoint`):
+
+```python
+from scvi.train import SaveCheckpoint
+
+model.train(
+ max_epochs=400,
+ enable_checkpointing=True,
+ callbacks=[SaveCheckpoint(monitor="elbo_validation", load_best_on_end=True)],
+)
+```
+
### 6. Extract Results
```python