PeakVI: Analyzing scATACseq data#

PeakVI is used for analyzing scATACseq data. This tutorial walks through how to read, set-up and train the model, accessing and visualizing the latent space, and differential accessibility. We use the 5kPBMC sample dataset from 10X but these steps can be easily adjusted for other datasets.

Note

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

!pip install --quiet scvi-colab
from scvi_colab import install

install()
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

import os
import tempfile
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pooch
import scanpy as sc
import scvi
import torch
scvi.settings.seed = 0
print("Last run with scvi-tools version:", scvi.__version__)
Last run with scvi-tools version: 1.1.0

Note

You can modify save_dir below to change where the data files for this tutorial are saved.

sc.set_figure_params(figsize=(4, 4), frameon=False)
torch.set_float32_matmul_precision("high")
save_dir = tempfile.TemporaryDirectory()

%config InlineBackend.print_figure_kwargs={"facecolor" : "w"}
%config InlineBackend.figure_format="retina"

Download and preprocess data#

First we need to download the sample data - we will use the pooch package to do this.

def download_data(save_path: str, fname: str = "atac_pbmc_5k") -> str:
    """Download the data files."""
    data_paths = pooch.retrieve(
        url="https://cf.10xgenomics.com/samples/cell-atac/1.2.0/atac_pbmc_5k_nextgem/atac_pbmc_5k_nextgem_filtered_peak_bc_matrix.tar.gz",
        known_hash="78e536a1508108fa5bd3b411a7484809c011f3403800369b20db05bdbfeb2284",
        fname=fname,
        path=save_path,
        processor=pooch.Untar(),
        progressbar=True,
    )
    return str(Path(data_paths[0]).parent)
data_path = download_data(save_dir.name)

PeakVI expects as input an AnnData object with a cell-by-region matrix. There are various pipelines that handle preprocessing of scATACseq to obtain this matrix from the sequencing data. If the data was generated by 10X genomics, this matrix is among the standard outputs of CellRanger. Other pipelines, like SnapATAC and ArchR, also generate similar matrices.

In the case of 10X data, PeakVI has a special reader function scvi.data.read_10x_atac that reads the files and creates an AnnData object, demonstrated below. For conveniece, we also demonstrate how to initialize an AnnData object from scratch.

Throughout this tutorial, we use sample scATACseq data from 10X of 5K PBMCs.

adata = scvi.data.read_10x_atac(data_path)
adata
AnnData object with n_obs × n_vars = 4585 × 115554
    obs: 'batch_id'
    var: 'chr', 'start', 'end'

We can use Scanpy to handle, filter, and manipulate the data. In our case, we might want to filter out peaks that are rarely detected, to make the model train faster:

print("# regions before filtering:", adata.shape[-1])

# compute the threshold: 5% of the cells
min_cells = int(adata.shape[0] * 0.05)
# in-place filtering of regions
sc.pp.filter_genes(adata, min_cells=min_cells)

print("# regions after filtering:", adata.shape[-1])
# regions before filtering: 115554
# regions after filtering: 33142

Set up, train, save, and load the model#

We can now set up the AnnData object with PeakVI, which will ensure everything the model needs is in place for training.

This is also the stage where we can condition the model on additional covariates, which encourages the model to remove the impact of those covariates from the learned latent space. Our sample data is a single batch, so we won’t demonstrate this directly, but it can be done simply by setting the batch_key argument to the annotation to be used as a batch covariate (must be a valid key in adata.obs) .

scvi.model.PEAKVI.setup_anndata(adata)

We can now create a PeakVI model object and train it!

Important

The default max_epochs is set to 500, but in practice PeakVI stops early once the model converges (we quantify convergence with the model’s validation reconstruction loss). This is especially the case for larger datasets, which require fewer training epochs to converge since each epoch lets the model view more data.

This means that the estimated training runtime is usually an overestimate of the actual runtime. For the data used in this tutorial, it typically converges with around half of max_epochs!

model = scvi.model.PEAKVI(adata)
model.train()
Epoch 274/500:  55%|█████▍    | 274/500 [01:57<01:36,  2.33it/s, v_num=1, train_loss_step=1.14e+7, train_loss_epoch=2.01e+8]
Monitored metric reconstruction_loss_validation did not improve in the last 50 records. Best score: 13018.062. Signaling Trainer to stop.

Since training a model can take a while, we recommend saving the trained model after training, just in case.

model_dir = os.path.join(save_dir.name, "peakvi_pbmc")
model.save(model_dir, overwrite=True)

We can then load the model later, which require providing an AnnData object that is structured similarly to the one used for training (or, in most cases, the same one):

model = scvi.model.PEAKVI.load(model_dir, adata=adata)
INFO     File /tmp/tmpgce9lagt/peakvi_pbmc/model.pt already downloaded                                             

Visualizing and analyzing the latent space#

We can now use the trained model to visualize, cluster, and analyze the data. We first extract the latent representation from the model, and save it back into our AnnData object:

PEAKVI_LATENT_KEY = "X_peakvi"

latent = model.get_latent_representation()
adata.obsm[PEAKVI_LATENT_KEY] = latent
latent.shape
(4585, 13)

We can now use Scanpy to cluster and visualize our latent space:

PEAKVI_CLUSTERS_KEY = "clusters_peakvi"

# compute the k-nearest-neighbor graph that is used in both clustering and umap algorithms
sc.pp.neighbors(adata, use_rep=PEAKVI_LATENT_KEY)
# compute the umap
sc.tl.umap(adata, min_dist=0.2)
# cluster the space (we use a lower resolution to get fewer clusters than the default)
sc.tl.leiden(adata, key_added=PEAKVI_CLUSTERS_KEY, resolution=0.2)
sc.pl.umap(adata, color=PEAKVI_CLUSTERS_KEY)
../../../_images/7f2e21d7a653d859b5fec03623c7e641e1fbd0904895382013970152cf45893b.png

Differential accessibility#

Finally, we can use PeakVI to identify regions that are differentially accessible. There are many different ways to run this analysis, but the simplest is comparing one cluster against all others, or comparing two clusters to each other. In the first case we’ll be looking for marker-regions, so we’ll mostly want a one-sided test (the significant regions will only be the ones preferentially accessible in our target cluster). In the second case we’ll use a two-sided test to find regions that are differentially accessible, regardless of direction.

We demonstrate both of these next, and do this in two different ways: (1) more convenient but less flexible: using an existing factor to group the cells, and then comparing groups. (2) more flexible: using cell indices directly.

Important

If the data includes multiple batches, we encourage setting batch_correction=True so the model will sample from multiple batches when computing the differential signal. We do this below despite the data only having a single batch, as a demonstration.

# (1.1) using a known factor to compare two clusters
## two-sided is True by default, but included here for emphasis
da_res11 = model.differential_accessibility(
    groupby=PEAKVI_CLUSTERS_KEY, group1="3", group2="0", two_sided=True
)

# (1.2) using a known factor to compare a cluster against all other clusters
## if we only provide group1, group2 is all other cells by default
da_res12 = model.differential_accessibility(
    groupby=PEAKVI_CLUSTERS_KEY, group1="3", two_sided=False
)

# (2.1) using indices to compare two clusters
## we can use boolean masks or integer indices for the `idx1` and `idx2` arguments
da_res21 = model.differential_accessibility(
    idx1=adata.obs[PEAKVI_CLUSTERS_KEY] == "3",
    idx2=adata.obs[PEAKVI_CLUSTERS_KEY] == "0",
    two_sided=True,
)
# (2.2) using indices to compare a cluster against all other clusters
## if we don't provide idx2, it uses all other cells as the contrast
da_res22 = model.differential_accessibility(
    idx1=np.where(adata.obs[PEAKVI_CLUSTERS_KEY] == "3"),
    two_sided=False,
)

da_res22.head()
DE...: 100%|██████████| 1/1 [00:03<00:00,  3.49s/it]
DE...: 100%|██████████| 1/1 [00:03<00:00,  3.49s/it]
DE...: 100%|██████████| 1/1 [00:03<00:00,  3.33s/it]
DE...: 100%|██████████| 1/1 [00:03<00:00,  3.37s/it]
prob_da is_da_fdr bayes_factor effect_size emp_effect est_prob1 est_prob2 emp_prob1 emp_prob2
chr2:232535623-232538141 1.0 True 18.420681 -0.882698 -0.561986 0.930892 0.048194 0.590308 0.028322
chr11:60222766-60223569 1.0 True 18.420681 -0.909804 -0.516749 0.928111 0.018306 0.526432 0.009683
chr22:22776937-22777587 1.0 True 18.420681 -0.686685 -0.349928 0.722180 0.035496 0.367841 0.017913
chr3:13151900-13153013 1.0 True 18.420681 -0.859640 -0.479738 0.904662 0.045022 0.506608 0.026870
chr3:122294823-122297353 1.0 True 18.420681 -0.739251 -0.416631 0.872822 0.133571 0.491189 0.074558

Note that da_res11 and da_res21 are equivalent, as are da_res12 and da_res22. The return value is a pandas DataFrame with the differential results and basic properties of the comparison:

prob_da in our case is the probability of cells from cluster 0 being more than 0.05 (the default minimal effect) more accessible than cells from the rest of the data.

is_da_fdr is a conservative classification (True/False) of whether a region is differential accessible. This is one way to threshold the results.

bayes_factor is a statistical significance score. It doesn’t have a commonly acceptable threshold (e.g 0.05 for p-values), bu we demonstrate below that it’s well calibrated to the effect size.

effect_size is the effect size, calculated as est_prob1 - est_prob2.

emp_effect is the empirical effect size, calculated as emp_prob1 - emp_prob2.

est_prob{1,2} are the estimated probabilities of accessibility in group1 and group2.

emp_prob{1,2} are the empirical probabilities of detection (how many cells in group X was the region detected in).

We can make sure the probability of DA is well calibrated, and look at the regions that are identified as differentially accessible:

plt.scatter(da_res22.effect_size, da_res22.prob_da, s=1)
plt.xlabel("effect size")
plt.ylabel("probability of DA")
plt.show()

da_res22.loc[da_res22.is_da_fdr].sort_values("prob_da", ascending=False).head(10)
../../../_images/585d57f3b8677f60bf06c3ea2c32c7f7bcbbc485a7601e5c32b2312671e95dc3.png
prob_da is_da_fdr bayes_factor effect_size emp_effect est_prob1 est_prob2 emp_prob1 emp_prob2
chr2:232535623-232538141 1.0 True 18.420681 -0.882698 -0.561986 0.930892 0.048194 0.590308 0.028322
chr16:67550946-67553518 1.0 True 18.420681 -0.746944 -0.377424 0.796463 0.049519 0.403084 0.025660
chr11:60222766-60223569 1.0 True 18.420681 -0.909804 -0.516749 0.928111 0.018306 0.526432 0.009683
chr5:55883388-55885472 1.0 True 18.420681 -0.755661 -0.427810 0.952137 0.196477 0.539648 0.111837
chr3:186733593-186735658 1.0 True 18.420681 -0.630135 -0.329764 0.692410 0.062275 0.361233 0.031469
chr8:28195531-28197587 1.0 True 18.420681 -0.846311 -0.540684 0.937371 0.091060 0.590308 0.049625
chr15:89199014-89200987 1.0 True 18.420681 -0.477286 -0.235269 0.534093 0.056807 0.264317 0.029049
chr4:2852856-2854873 1.0 True 18.420681 -0.532579 -0.268864 0.605137 0.072558 0.303965 0.035100
chr7:1062511-1064563 1.0 True 18.420681 -0.790935 -0.470831 0.824037 0.033101 0.488987 0.018155
chr19:17886105-17887874 1.0 True 18.420681 -0.640419 -0.321826 0.684176 0.043758 0.343612 0.021786

We can now examine these regions to understand what is happening in the data, using various different annotation and enrichment methods. For instance, chr11:60222766-60223569, one of the regions preferentially accessible in cluster 0, is the promoter region of MS4A1, also known as CD20, a known B-cell surface marker, indicating that cluster 0 are probably B-cells.