ResolVI to address noise and biases in spatial transcriptomics#

In this tutorial, we go through the steps of training resolVI for correction in cellular-resolved spatial transcriptomics. This addresses erroneous co-expression pattern after cellular segmentation as well as unspecific background in these technologies. We highly recommend to optimize cell segmentation before running resolVI as a better cell segmentation will also yield better downstream results and both steps are complementary.

Plan for this tutorial:

  1. Loading the data

  2. Training an unsupervised and (semi-)supervised resolVI model

  3. Visualizing the latent space

  4. Transfer mapping.

  5. Generating corrected counts and perform DE analysis

Note

Running the following cell will install tutorial dependencies on Google Colab only. It will have no effect on environments other than Google Colab.

import sys

if "google.colab" in sys.modules:
    !pip install --quiet scvi-colab
    from scvi_colab import install

    install(for_tutorials=False)
    !pip install --quiet "scviva-tools[tutorials]"
    !pip install --quiet decoupler
    !pip install --quiet adjustText
import os
import tempfile

import decoupler as dc
import matplotlib.pyplot as plt
import numpy as np
import scanpy as sc
import scvi
import scviva
from scviva.model import ResolVI
HAS_RSC = False
try:
    import cupy as cp
    import rapids_singlecell as rsc

    # rapids_singlecell can be importable without a usable GPU (e.g. a CPU runtime on Google Colab)
    HAS_RSC = cp.cuda.runtime.getDeviceCount() > 0
except Exception:  # ImportError, or a CUDA error when no GPU/driver is present
    HAS_RSC = False

if HAS_RSC:
    print("RAPIDS SingleCell is installed and a GPU is available, using rapids_singlecell")
else:
    print("RAPIDS SingleCell (or a GPU) is not available, falling back to scanpy")
RAPIDS SingleCell is installed and a GPU is available, using rapids_singlecell
sc.set_figure_params(figsize=(4, 4))
save_dir = tempfile.TemporaryDirectory()
%config InlineBackend.print_figure_kwargs={'facecolor' : "w"}
%config InlineBackend.figure_format='retina'

scviva.settings.seed = 0
print("Last run with scviva-tools version:", scviva.__version__)
Last run with scviva-tools version: 0.1.8
scvi.settings.seed = 0
print("Last run with scvi-tools version:", scvi.__version__)
Last run with scvi-tools version: 1.5.1

Data Loading#

For the purposes of this notebook, we will be loading a Xenium dataset of a mouse brain. We will use the left hemisphere for model training and the right hemisphere for transfer mapping. The data was originally labeled using Leiden clustering of an optimized segmentation using the ProSeg algorithm, which is a scalable algorithm for transcriptome-informed segmentation.

adata_path = os.path.join(save_dir.name, "tutorial_xenium_brain.h5ad")
adata = sc.read(
    adata_path, backup_url="https://exampledata.scverse.org/scvi-tools/tutorial_xenium_brain.h5ad"
)
adata
AnnData object with n_obs × n_vars = 130604 × 248
    obs: 'x_centroid', 'y_centroid', 'transcript_counts', 'control_probe_counts', 'control_codeword_counts', 'total_counts', 'cell_area', 'nucleus_area', 'fov', 'predicted_celltype'
    var: 'gene_ids', 'feature_types', 'genome'
    uns: 'log1p'
    obsm: 'X_resolvi_transferred', 'X_spatial', 'X_umap_transferred'
    layers: 'counts', None (.X)

We computed a UMAP after transfering labels using the ProSeg segmented dataset and the UMAP serves as ground truth.

adata.obsm["X_umap"] = adata.obsm["X_umap_transferred"]
sc.pl.umap(adata, color="predicted_celltype")
sc.pl.spatial(adata, color="predicted_celltype", spot_size=30)
adata.obs["predicted_celltype"].value_counts()
predicted_celltype
Astrocytes                            17315
Oligodendrocyte                       14567
Fibroblast                            10070
Endothelial Cells                      9775
Inhibitory Neurons Hypothalamus        9284
Excitatory Neurons Amygdala            8640
Excitatory Neurons Thalamus            7947
Excitatory Neurons L5                  7004
Excitatory Neurons L2/3                6393
Inhibitory Neurons Putamen             5753
Inhibitory Neurons Cortical            5711
Excitatory Neurons L4                  5500
Excitatory Neurons L6                  5052
Microglia                              4141
Oligodendrocyte Precursor Cells        3872
Excitatory Neurons Dentate Gyrus       3283
Excitatory Neurons Cornu ammonis       2787
Ependymal Cells                        2202
Inhibitory Neurons Pallidum             658
Excitatory Neurons Amygdala medial      650
Name: count, dtype: int64

We use this dataset to set up a semisupervised and an unsupervised model in resolVI and train these. We split the dataset into right and left hemisphere to demonstrate query mapping.

adata.obs["hemisphere"] = ["right" if x > 5000 else "left" for x in adata.obsm["X_spatial"][:, 0]]
sc.pl.spatial(adata, color="hemisphere", spot_size=30)
ref_adata = adata[adata.obs["hemisphere"] == "left"].copy()
query_adata = adata[adata.obs["hemisphere"] == "right"].copy()

Train resolVI model#

As in the scANVI notebook, we need to register the AnnData object for use in resolVI. Namely, we can ignore the batch parameter because those cells don’t have much batch effect to begin with as they are derived from a single slice. However, we will give the celltype labels for resolVI to use. Setting up AnnData computes spatial neighbors within each batch. This step might take minutes for very large datasets. It is important that different slices are used as batch covariate.

# Drop any stale neighbors/config so setup_anndata always recomputes the spatial graph
# with the current _prepare_data (squared distances element-wise, rows sorted by distance).
ref_adata.uns.pop("_resolvi_prepare_data_config", None)
for key in ["index_neighbor", "distance_neighbor"]:
    ref_adata.obsm.pop(key, None)

ResolVI.setup_anndata(
    ref_adata,
    labels_key="predicted_celltype",
    layer="counts",
    prepare_data=True,
    prepare_data_kwargs={"spatial_rep": "X_spatial"},
)

# Verify neighbors were computed: valid indices and per-row ascending distances.
dist = ref_adata.obsm["distance_neighbor"]
idx = ref_adata.obsm["index_neighbor"]
print("prepare_data config:", ref_adata.uns["_resolvi_prepare_data_config"])
print("neighbors:", idx.shape, "max index < n_obs:", int(idx.max()) < ref_adata.n_obs)
print("distances sorted per row:", bool((np.diff(dist, axis=1) >= 0).all()))
Preparing data for training. This may take a while. RAPIDS SingleCell will be used if installed.
INFO     Generating sequential column names                                                                        
INFO     Generating sequential column names                                                                        
prepare_data config: {'batch_key': None, 'spatial_rep': 'X_spatial'}
neighbors: (66457, 10) max index < n_obs: True
distances sorted per row: True
supervised_resolvi = ResolVI(ref_adata, semisupervised=True)

We use here only 20 epochs to speed up running the tutorial. We would recommend using 100 epochs here.

supervised_resolvi.train(max_epochs=50)

Now we can predict the cell type labels using the trained model, and get the latent space. ResolVI uses pyro. Pyro stores parameters in a pyro_param_store. It is necessary that only a single model is used at a time, e.g. after query training only the query model is valid and the reference model gets overwritten.

ref_adata
AnnData object with n_obs × n_vars = 66457 × 248
    obs: 'x_centroid', 'y_centroid', 'transcript_counts', 'control_probe_counts', 'control_codeword_counts', 'total_counts', 'cell_area', 'nucleus_area', 'fov', 'predicted_celltype', 'hemisphere', '_indices', '_scvi_batch', '_scvi_ind_x', '_scvi_labels'
    var: 'gene_ids', 'feature_types', 'genome'
    uns: 'log1p', 'predicted_celltype_colors', 'hemisphere_colors', '_resolvi_prepare_data_config', '_scvi_uuid', '_scvi_manager_uuid'
    obsm: 'X_resolvi_transferred', 'X_spatial', 'X_umap_transferred', 'X_umap', 'index_neighbor', 'distance_neighbor'
    layers: 'counts', None (.X)
ref_adata.obsm["resolvi_celltypes"] = supervised_resolvi.predict(
    ref_adata, num_samples=3, soft=True
)
ref_adata.obs["resolvi_predicted"] = ref_adata.obsm["resolvi_celltypes"].idxmax(axis=1)
ref_adata.obsm["X_resolVI"] = supervised_resolvi.get_latent_representation(ref_adata)

Again, we may visualize the latent space as well as the inferred labels

if HAS_RSC:
    rsc.pp.neighbors(ref_adata, use_rep="X_resolVI")
    rsc.tl.umap(ref_adata)
else:
    sc.pp.neighbors(ref_adata, use_rep="X_resolVI")
    sc.tl.umap(ref_adata)
ref_adata
AnnData object with n_obs × n_vars = 66457 × 248
    obs: 'x_centroid', 'y_centroid', 'transcript_counts', 'control_probe_counts', 'control_codeword_counts', 'total_counts', 'cell_area', 'nucleus_area', 'fov', 'predicted_celltype', 'hemisphere', '_indices', '_scvi_batch', '_scvi_ind_x', '_scvi_labels', 'resolvi_predicted'
    var: 'gene_ids', 'feature_types', 'genome'
    uns: 'log1p', 'predicted_celltype_colors', 'hemisphere_colors', '_resolvi_prepare_data_config', '_scvi_uuid', '_scvi_manager_uuid', 'neighbors', 'umap'
    obsm: 'X_resolvi_transferred', 'X_spatial', 'X_umap_transferred', 'X_umap', 'index_neighbor', 'distance_neighbor', 'resolvi_celltypes', 'X_resolVI'
    obsp: 'distances', 'connectivities'
    layers: 'counts', None (.X)
sc.pl.umap(ref_adata, color=["predicted_celltype", "resolvi_predicted"])
sc.pl.spatial(ref_adata, color=["predicted_celltype", "resolvi_predicted"], spot_size=30)

We can use the trained model to perform differential expression of two groups of cells. We compute here genes differentially expressed between neurons in two distinct layers. This uses a similar test to the scVI DE test. Please keep in mind this test doesn’t test for differences in the mean between two groups but tests for differences between random pairs of single cell.

de_result_importance = supervised_resolvi.differential_expression(
    ref_adata,
    groupby="resolvi_predicted",
    group1="Excitatory Neurons L6",
    group2="Excitatory Neurons L5",
    weights="importance",
    pseudocounts=1e-2,
    delta=0.05,
    filter_outlier_cells=True,
    mode="change",
    test_mode="three",
)
de_result_importance.head(5)
proba_de proba_not_de bayes_factor scale1 scale2 pseudocounts delta lfc_mean lfc_median lfc_std ... raw_mean1 raw_mean2 non_zeros_proportion1 non_zeros_proportion2 raw_normalized_mean1 raw_normalized_mean2 is_de_fdr_0.05 comparison group1 group2
Tle4 0.9942 0.0058 5.144079 0.029306 0.006448 0.01 0.05 2.401641 2.442760 0.907954 ... 7.884583 2.019634 0.979905 0.716971 258.171570 58.105282 True Excitatory Neurons L6 vs Excitatory Neurons L5 Excitatory Neurons L6 Excitatory Neurons L5
Gadd45a 0.9870 0.0130 4.329720 0.017413 0.003699 0.01 0.05 2.395836 2.374557 1.067081 ... 5.264003 1.187950 0.900709 0.518242 169.816788 32.559704 True Excitatory Neurons L6 vs Excitatory Neurons L5 Excitatory Neurons L6 Excitatory Neurons L5
Syt6 0.9844 0.0156 4.144761 0.013233 0.000827 0.01 0.05 4.610283 4.580660 2.051547 ... 3.391644 0.368435 0.797872 0.227750 109.637238 10.634214 True Excitatory Neurons L6 vs Excitatory Neurons L5 Excitatory Neurons L6 Excitatory Neurons L5
Foxp2 0.9790 0.0210 3.842009 0.012586 0.001282 0.01 0.05 3.800866 3.835156 1.753157 ... 3.197400 0.396904 0.815209 0.259812 102.546074 11.133417 True Excitatory Neurons L6 vs Excitatory Neurons L5 Excitatory Neurons L6 Excitatory Neurons L5
Nell1 0.9766 0.0234 3.731341 0.000794 0.006486 0.01 0.05 -2.921372 -3.004556 1.073292 ... 0.323485 2.658644 0.240347 0.647319 10.839521 68.947495 True Excitatory Neurons L6 vs Excitatory Neurons L5 Excitatory Neurons L6 Excitatory Neurons L5

5 rows × 22 columns

dc.pl.volcano(
    de_result_importance,
    x="lfc_mean",
    y="proba_not_de",
    thr_sign=0.1,
    thr_stat=0.4,
    top=30,
    figsize=(10, 10),
)
plt.show()

We can use the trained model to perform differential abundance of cell states in the neighborhood of two groups of cells. We find here that excitatory neurons in thalamus and cortex preferentially colocalize with themselves as well as adjacent layer neurons. This uses a similar test to the scVI DE test.

da = supervised_resolvi.differential_niche_abundance(
    groupby="resolvi_predicted",
    group1="Excitatory Neurons L4",
    group2="Excitatory Neurons Thalamus",
    neighbor_key="index_neighbor",
    test_mode="three",
    delta=0.05,
    pseudocounts=3e-2,
)
da.head(5)
proba_de proba_not_de bayes_factor scale1 scale2 pseudocounts delta lfc_mean lfc_median lfc_std lfc_min lfc_max is_de_fdr_0.05 comparison group1 group2
Excitatory Neurons Thalamus 1.0000 0.0000 18.420681 0.001544 0.598487 0.03 0.05 -11.729854 -12.503225 2.461239 -14.891913 -1.595258 True Excitatory Neurons L4 vs Excitatory Neurons Th... Excitatory Neurons L4 Excitatory Neurons Thalamus
Excitatory Neurons L4 0.9996 0.0004 7.823621 0.583093 0.001050 0.03 0.05 11.866110 12.244538 1.781026 -1.010016 14.993066 True Excitatory Neurons L4 vs Excitatory Neurons Th... Excitatory Neurons L4 Excitatory Neurons Thalamus
Excitatory Neurons L2/3 0.7734 0.2266 1.227610 0.053641 0.000162 0.03 0.05 7.262262 7.134897 3.396340 -6.988921 14.640425 False Excitatory Neurons L4 vs Excitatory Neurons Th... Excitatory Neurons L4 Excitatory Neurons Thalamus
Oligodendrocyte 0.6544 0.3456 0.638437 0.019676 0.073536 0.03 0.05 -5.469002 -5.992530 5.910371 -13.990974 11.463117 False Excitatory Neurons L4 vs Excitatory Neurons Th... Excitatory Neurons L4 Excitatory Neurons Thalamus
Astrocytes 0.6018 0.3982 0.412971 0.079472 0.128985 0.03 0.05 -2.296245 -0.998144 5.670868 -13.974169 13.143880 False Excitatory Neurons L4 vs Excitatory Neurons Th... Excitatory Neurons L4 Excitatory Neurons Thalamus
dc.pl.volcano(
    da,
    x="lfc_mean",
    y="proba_not_de",
    thr_sign=0.1,
    thr_stat=0.4,
    top=30,
    figsize=(10, 10),
)
plt.show()

We can also generate counts that are corrected for counts from neighboring cells wrongly assigned due to missegmentation as well as unspecific background. We use custom parameters for num_samples and and summary_fun to accelerate computation. “px_rate” of model_corrected generates corrected count data. “mixture_proportions” of model_residuals generates the amount of diffusion and background for each cell. Batch steps defines how many batches are accumulated before computing summary statistics. To increase the amount of correction, use lower quantiles instead of median.

import pandas as pd
samples_corr = supervised_resolvi.sample_posterior(
    model=supervised_resolvi.module.model_corrected,
    return_sites=["px_rate"],
    summary_fun={"post_sample_q50": np.median},
    num_samples=3,
    summary_frequency=30,
)
samples_corr = pd.DataFrame(samples_corr).T
samples = supervised_resolvi.sample_posterior(
    model=supervised_resolvi.module.model_residuals,
    return_sites=["mixture_proportions"],
    summary_fun={"post_sample_means": np.mean},
    num_samples=3,
    summary_frequency=100,
)
samples = pd.DataFrame(samples).T
ref_adata.obs[["true_proportion", "diffusion_proportion", "background_proportion"]] = samples.loc[
    "post_sample_means", "mixture_proportions"
]
sc.pl.umap(
    ref_adata,
    color=["total_counts", "true_proportion", "diffusion_proportion", "background_proportion"],
)
ref_adata.layers["generated_expression"] = samples_corr.loc["post_sample_q50", "px_rate"]
sc.pl.umap(ref_adata, color=["resolvi_predicted", "Slc17a6"], layer="counts", vmax="p98")
sc.pl.umap(
    ref_adata, color=["resolvi_predicted", "Slc17a6"], layer="generated_expression", vmax="p98"
)

Query transfer#

We can train the reference model on query data to reannotate this data. We rely on the observation names for non-amortized parameters in resolVI. It is important to make sure cells have unique names between query and reference dataset. We set the cell-type to unknown, so that resolVI needs to predict the celltype leveraging the reference model.

query_adata.obs["predicted_celltype"] = "unknown"
query_adata.obs_names = [f"query_{i}" for i in query_adata.obs_names]
supervised_resolvi.prepare_query_anndata(query_adata, reference_model=supervised_resolvi)
query_resolvi = supervised_resolvi.load_query_data(query_adata, reference_model=supervised_resolvi)
INFO     Found 100.0% reference vars in query data.
Preparing data for training. This may take a while. RAPIDS SingleCell will be used if installed.
query_resolvi.train(max_epochs=20)
Running transfer learning mode. Set lr to 0 and blocking variables.
query_adata.obs["resolvi_predicted"] = query_resolvi.predict(
    query_adata, num_samples=3, soft=False
)
query_adata.obsm["X_resolVI"] = query_resolvi.get_latent_representation(query_adata)

Again, we may visualize the latent space as well as the inferred labels

if HAS_RSC:
    rsc.pp.neighbors(query_adata, use_rep="X_resolVI")
    rsc.tl.umap(query_adata)
else:
    sc.pp.neighbors(query_adata, use_rep="X_resolVI")
    sc.tl.umap(query_adata)
sc.pl.umap(query_adata, color=["predicted_celltype", "resolvi_predicted"])
sc.pl.spatial(query_adata, color=["predicted_celltype", "resolvi_predicted"], spot_size=30)

We can now concatenate the datasets again and find good integration and accurate cell-type information.

import anndata as ad
full_adata = ad.concat(                                                                                                                                                                      
    {"reference": ref_adata, "query": query_adata},                                                                                                                                          
    label="source",                                                                                                                                                                          
    index_unique="-",                                                                                                                                                                        
    merge="same",                                                                                                                                                                            
)  
if HAS_RSC:
    rsc.pp.neighbors(full_adata, use_rep="X_resolVI")
    rsc.tl.umap(full_adata)
else:
    sc.pp.neighbors(full_adata, use_rep="X_resolVI")
    sc.tl.umap(full_adata)
sc.pl.umap(full_adata, color=["source", "resolvi_predicted"])
sc.pl.spatial(full_adata, color=["source", "resolvi_predicted"], spot_size=30)

Benchmarking latent spaces with scib-metrics#

We compare the resolVI latent space (X_resolVI) against two baselines using scib-metrics:

  • PCA on log-normalized counts: an unintegrated baseline.

  • scVI: a non-spatial deep generative model with source (reference vs. query hemisphere) as batch covariate.

Bio-conservation metrics are computed against the ground-truth labels (the ProSeg-derived predicted_celltype). Batch-correction metrics measure how well the reference and query hemispheres mix. We don’t benchmark the other obsm entries: X_spatial holds coordinates, X_umap* are 2D visualizations, and index_neighbor/distance_neighbor are neighbor graphs, not embeddings.

PCA and scVI are fit on the full dataset, like resolVI. Only the metric computation, which scales poorly with cell count, runs on a random subsample of N_CELLS cells. Increase it once the runtime is acceptable.

from scib_metrics.benchmark import BatchCorrection, Benchmarker, BioConservation

# Query labels were masked as "unknown" before query mapping, so recover the ground truth.
expected_names = np.concatenate(
    [ref_adata.obs_names + "-reference", query_adata.obs_names + "-query"]
)
assert (full_adata.obs_names == expected_names).all()
full_adata.obs["celltype_true"] = pd.Categorical(
    np.concatenate(
        [
            ref_adata.obs["predicted_celltype"].astype(str).to_numpy(),
            adata.obs.loc[adata.obs["hemisphere"] == "right", "predicted_celltype"]
            .astype(str)
            .to_numpy(),
        ]
    )
)

Compute the PCA baseline on log-normalized counts of the full dataset.

full_adata.X = full_adata.layers["counts"].copy()
sc.pp.normalize_total(full_adata)
sc.pp.log1p(full_adata)
sc.pp.pca(full_adata, n_comps=30)

Train scVI on the full dataset with source as batch covariate.

scvi.model.SCVI.setup_anndata(full_adata, layer="counts", batch_key="source")
scvi_model = scvi.model.SCVI(full_adata, n_latent=10)
scvi_model.train(max_epochs=100)
full_adata.obsm["X_scVI"] = scvi_model.get_latent_representation()

Subsample cells for the metric computation only.

N_CELLS = 10_000  # increase once runtime is acceptable

# Keep cell types present in both hemispheres; batch metrics like BRAS need >1 batch per label.
shared = set(full_adata.obs.loc[full_adata.obs["source"] == "reference", "celltype_true"]) & set(
    full_adata.obs.loc[full_adata.obs["source"] == "query", "celltype_true"]
)
bench_adata = full_adata[full_adata.obs["celltype_true"].isin(shared)]

rng = np.random.default_rng(0)
idx = rng.choice(bench_adata.n_obs, size=min(N_CELLS, bench_adata.n_obs), replace=False)
bench_adata = bench_adata[np.sort(idx)].copy()
bench_adata.obs["celltype_true"] = bench_adata.obs["celltype_true"].cat.remove_unused_categories()
bench_adata.obs["source"].value_counts()
source
reference    5069
query        4931
Name: count, dtype: int64
bm = Benchmarker(
    bench_adata,
    batch_key="source",
    label_key="celltype_true",
    embedding_obsm_keys=["X_pca", "X_scVI", "X_resolVI"],
    pre_integrated_embedding_obsm_key="X_pca",
    bio_conservation_metrics=BioConservation(),
    batch_correction_metrics=BatchCorrection(),
    n_jobs=-1,
    solver="full",  # "arpack" fails with cuML PCA when rapids_singlecell is installed
)
bm.benchmark()
bm.plot_results_table(min_max_scale=False)
../_images/60c3f5d634937a771f6bd984b9499f90e82bf96ba12cd50819383eeaad70d3d8.png
<plottable.table.Table at 0x722c04e91fd0>
import gc

gc.collect()
import torch

torch.cuda.empty_cache()