Resolvi

From swaruplab/operon · View interactive version

Resolvi is an AI agent skill from the GitHub repository swaruplab/operon. ResolVI — variational autoencoder for denoising imaging-based spatial transcriptomics (Xenium, MERFISH, CosMx). Removes ambient background and resolves wrong segmentation by jointly modeling true cell expression, mis-assigned neighbor counts, and unspecific background. Outputs a latent representatio

How to use this skill

Skill file

ResolVI: Resolving Single-Cell Resolution in Spatial Transcriptomics

Overview

ResolVI is a scvi-tools model that denoises imaging-based spatial transcriptomics (Xenium, MERFISH, CosMx, etc.) by jointly modeling three sources of observed counts in each cell:

| Component | Symbol | What it represents |

|---|---|---|

| α₀ | alpha_0 | True expression from this cell |

| α₁ | alpha_1 | Expression "leaked" from neighbor cells due to wrong segmentation |

| α₂ | alpha_2 | Unspecific ambient background |

The generative model uses a mixture-of-Gaussians prior over cell embeddings and weighted diffusion over the spatial neighbor graph to apportion observed counts among the three sources. The result is a per-cell latent representation that captures the true biological signal, plus denoised expression that strips off background and neighbor contamination.

Why this matters: imaging-based ST has three fundamental noise sources that bulk denoisers (CellBender for ambient, Scrublet for doublets) don't address well — segmentation errors smear transcripts across adjacent cells, and the cell's actual transcript count is conflated with neighbors. ResolVI is the model purpose-built for this.

When to Use This Skill

Not for:

Prerequisites

# Core install — scvi-tools includes RESOLVI in scvi.external
pip install scvi-tools

# Verify GPU detection
python -c "import torch; print('CUDA:', torch.cuda.is_available())"

Quick Start

import scanpy as sc
import scvi
import numpy as np

# ── 1. Load your spatial AnnData (Xenium / MERFISH / CosMx) ──────────────
adata = sc.read_h5ad("xenium_filtered.h5ad")
assert "spatial" in adata.obsm, "ResolVI requires adata.obsm['spatial']"
# adata.X should be RAW counts (not log-normalized). scvi-tools handles
# normalization internally via its negative-binomial likelihood.

# Cell-type labels — for semi-supervised mode, mark unlabelled as 'Unknown'.
# In unsupervised mode this column is just an unused placeholder.
adata.obs["celltype_resolvi"] = adata.obs["cell_type"].fillna("Unknown")

# ── 2. Setup AnnData for the RESOLVI model ───────────────────────────────
from scvi.external import RESOLVI

RESOLVI.setup_anndata(
    adata,
    layer            = None,                      # uses adata.X (raw counts)
    labels_key       = "celltype_resolvi",        # cell-type column (semi-supervised)
    batch_key        = "sample_id",                # optional, drop if single sample
    unlabeled_category = "Unknown",
)

# ── 3. Build the spatial neighbor graph ResolVI uses ─────────────────────
# (Skip if you already ran `sq.gr.spatial_neighbors` and have it in obsp.)
import squidpy as sq
sq.gr.spatial_neighbors(adata, coord_type="generic", n_neighs=20)

# ── 4. Train ─────────────────────────────────────────────────────────────
model = RESOLVI(
    adata,
    n_hidden    = 128,
    n_latent    = 20,
    n_layers    = 2,
    dropout_rate = 0.1,
    semisupervised = True,                         # use labels if available
)
model.train(
    max_epochs = 200,
    accelerator = "gpu", devices = 1,
    early_stopping = True,
)
# Save the trained model alongside the data
model.save("models/resolvi_xenium", save_anndata=False, overwrite=True)

Using the Trained Model

Latent representation → UMAP / clusters

adata.obsm["X_resolvi"] = model.get_latent_representation()

sc.pp.neighbors(adata, use_rep="X_resolvi")
sc.tl.umap(adata)
sc.tl.leiden(adata, resolution=0.5)
sc.pl.umap(adata, color=["leiden", "cell_type"])

The X_resolvi latent space is denoised — the same biology, with neighbor contamination and ambient stripped out. Clusters from this space typically look "cleaner" than clusters from raw counts.

Denoised expression

# Per-cell, per-gene estimate of TRUE expression (alpha_0 component)
denoised = model.get_normalized_expression(
    library_size = 1e4,
    return_mean  = True,                          # use posterior mean
)
# denoised is an AnnData / DataFrame depending on input — see the scvi-tools docs

# Compare to raw expression for a few marker genes:
sc.pl.umap(adata, color=["CD3D", "MS4A1", "CD14"], layer=None)       # raw
adata.layers["resolvi_denoised"] = denoised
sc.pl.umap(adata, color=["CD3D", "MS4A1", "CD14"], layer="resolvi_denoised")  # cleaned

A clean denoised UMAP will show CD3D confined to T cells, MS4A1 confined to B cells. If it still spreads across multiple clusters, ResolVI hasn't fully converged — run more epochs or check that the neighbor graph was built correctly.

Differential expression on denoised counts

de_df = model.differential_expression(
    groupby = "leiden",
    group1  = "0", group2 = "1",
    mode    = "vanilla",                          # or "change" for effect-size based
)
# Returns a per-gene DE table with proper posterior probabilities (LFC + Bayes factor)

Cell-type prediction (semi-supervised mode)

# Predicted label for every cell, including the original 'Unknown' set
preds = model.predict()
adata.obs["resolvi_predicted_celltype"] = preds

# Confidence per cell
probs = model.predict(soft=True)
adata.obs["resolvi_confidence"] = probs.max(axis=1)

If you trained with semisupervised=True and labels for ~10-30% of cells, predict() fills in the rest. Confidence scores let you flag uncertain calls for manual review.

Differential niche abundance

Are certain cell types over-represented in some spatial neighborhoods compared to others?

niche_df = model.differential_niche_abundance(
    groupby = "condition",                        # column with the conditions to compare
    group1  = "disease", group2 = "control",
)
# Returns log-fold-changes in per-niche cell-type abundance between conditions

This is the cleanest "which cell type changed where" analysis for spatial data — closer to ground truth than naive cell-counting because it uses the joint model's understanding of segmentation errors.

Key Parameters

Model setup

Training

Spatial graph (`sq.gr.spatial_neighbors`)

Best Practices

When ResolVI Output Looks Wrong

| Symptom | Likely cause | Fix |

|---|---|---|

| Denoised UMAP looks identical to raw | Model didn't converge | Bump max_epochs; check ELBO curve |

| Denoised UMAP has a totally different topology | Over-corrected, or neighbor graph is wrong | Inspect obsp["spatial_connectivities"] shape and connections; rebuild with sq.gr.spatial_neighbors |

| predict() returns 'Unknown' for everyone | Semi-supervised but no labels actually got registered | Confirm setup_anndata(labels_key=...) and that the column has values OTHER than the unlabeled category |

| OOM during training | Dataset too big for one GPU | Lower batch_size; use accelerator='gpu', devices=1 (multi-GPU not always faster) |

End-to-End Template

assets/resolvi_template.py — single parameterized script. Configure data path, label column, and batch column, then run end-to-end.

Convenience Scripts

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.