Note

This page was generated from data_loading.ipynb. Interactive online version: Colab badge. Some tutorial content may look better in light mode.

Data loading and preparation#

Here we walk through the necessary steps to get your data into ready for scvi-tools.

[ ]:
!pip install --quiet scvi-colab
from scvi_colab import install

install()
[1]:
import muon
import numpy as np
import scanpy as sc
import scvi

Loading data#

scvi-tools supports the AnnData data format, which also underlies Scanpy. AnnData is quite similar to other popular single cell objects like that of Seurat and SingleCellExperiment. In particular, it allows cell-level and feature-level metadata to coexist in the same data structure as the molecular counts.

It’s also now possible to automatically convert these R-based objects to AnnData within a Jupyter notebook. See the following tutorial for more information.

scvi-tools has a number of convenience methods for loading data from .csv, .loom, and .h5ad formats. To load outputs from Cell Ranger, please use Scanpy’s reading functionality.

Let us now download an AnnData object (.h5ad format) and load it using scvi-tools.

PBMC3k#

[2]:
!wget 'http://falexwolf.de/data/pbmc3k_raw.h5ad'
--2023-01-05 10:40:02--  http://falexwolf.de/data/pbmc3k_raw.h5ad
Resolving falexwolf.de (falexwolf.de)... 85.13.135.70
Connecting to falexwolf.de (falexwolf.de)|85.13.135.70|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://falexwolf.de/data/pbmc3k_raw.h5ad [following]
--2023-01-05 10:40:03--  https://falexwolf.de/data/pbmc3k_raw.h5ad
Connecting to falexwolf.de (falexwolf.de)|85.13.135.70|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 5855727 (5.6M)
Saving to: ‘pbmc3k_raw.h5ad’

pbmc3k_raw.h5ad     100%[===================>]   5.58M  3.39MB/s    in 1.6s

2023-01-05 10:40:05 (3.39 MB/s) - ‘pbmc3k_raw.h5ad’ saved [5855727/5855727]

[3]:
pbmc3k = scvi.data.read_h5ad("pbmc3k_raw.h5ad")
[4]:
pbmc3k
[4]:
AnnData object with n_obs × n_vars = 2700 × 32738
    var: 'gene_ids'

This is a fairly simple object, it just contains the count data and the ENSEMBL ids for the genes.

[5]:
pbmc3k.var.head()
[5]:
gene_ids
index
MIR1302-10 ENSG00000243485
FAM138A ENSG00000237613
OR4F5 ENSG00000186092
RP11-34P13.7 ENSG00000238009
RP11-34P13.8 ENSG00000239945

PBMC5k#

As another example, let’s download a dataset from 10x Genomics. This data was obtained from a CITE-seq experiment, so it also contains protein count data.

[6]:
!wget https://cf.10xgenomics.com/samples/cell-exp/3.0.2/5k_pbmc_protein_v3/5k_pbmc_protein_v3_filtered_feature_bc_matrix.h5
--2023-01-05 10:40:06--  https://cf.10xgenomics.com/samples/cell-exp/3.0.2/5k_pbmc_protein_v3/5k_pbmc_protein_v3_filtered_feature_bc_matrix.h5
Resolving cf.10xgenomics.com (cf.10xgenomics.com)... 104.18.1.173, 104.18.0.173, 2606:4700::6812:ad, ...
Connecting to cf.10xgenomics.com (cf.10xgenomics.com)|104.18.1.173|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 17129253 (16M) [binary/octet-stream]
Saving to: ‘5k_pbmc_protein_v3_filtered_feature_bc_matrix.h5’

5k_pbmc_protein_v3_ 100%[===================>]  16.33M  57.5MB/s    in 0.3s

2023-01-05 10:40:06 (57.5 MB/s) - ‘5k_pbmc_protein_v3_filtered_feature_bc_matrix.h5’ saved [17129253/17129253]

We load this data using muon, which will load a MuData object containing both the RNA and protein data.

[24]:
pbmc5k = muon.read_10x_h5(
    "5k_pbmc_protein_v3_filtered_feature_bc_matrix.h5",
)
/home/adam/miniconda3/envs/scvi-tools-dev/lib/python3.10/site-packages/anndata/_core/anndata.py:1830: UserWarning: Variable names are not unique. To make them unique, call `.var_names_make_unique`.
  utils.warn_names_duplicates("var")
/home/adam/miniconda3/envs/scvi-tools-dev/lib/python3.10/site-packages/mudata/_core/mudata.py:446: UserWarning: var_names are not unique. To make them unique, call `.var_names_make_unique`.
  warnings.warn(
/home/adam/miniconda3/envs/scvi-tools-dev/lib/python3.10/site-packages/mudata/_core/mudata.py:671: FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`
  data_mod.loc[:, colname] = col
/home/adam/miniconda3/envs/scvi-tools-dev/lib/python3.10/site-packages/mudata/_core/mudata.py:671: FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`
  data_mod.loc[:, colname] = col
/home/adam/miniconda3/envs/scvi-tools-dev/lib/python3.10/site-packages/mudata/_core/mudata.py:578: FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`
  data_mod.loc[:, colname] = col
[8]:
pbmc5k
[8]:
MuData object with n_obs × n_vars = 5247 × 33570
  var:      'gene_ids', 'feature_types', 'genome'
  2 modalities
    rna:    5247 x 33538
      var:  'gene_ids', 'feature_types', 'genome'
    prot:   5247 x 32
      var:  'gene_ids', 'feature_types', 'genome'

It’s often helpful to give the gene names unique names.

[9]:
pbmc5k.var_names_make_unique()

Concatenate the datasets#

[10]:
adata = pbmc5k.mod["rna"].concatenate(pbmc3k)
/home/adam/miniconda3/envs/scvi-tools-dev/lib/python3.10/site-packages/anndata/_core/anndata.py:1785: FutureWarning: X.dtype being converted to np.float32 from float64. In the next version of anndata (0.9) conversion will not be automatic. Pass dtype explicitly to avoid this warning. Pass `AnnData(X, dtype=X.dtype, ...)` to get the future behavour.
  [AnnData(sparse.csr_matrix(a.shape), obs=a.obs) for a in all_adatas],

Notice that the resulting AnnData has a batch key in .obs.

[11]:
adata.obs.sample(n=5)
[11]:
batch
GTAGCTAAGTTCATGC-1-0 0
CACTGAAAGACGGTCA-1-0 0
AAGGAATCAGTCGCAC-1-0 0
CCACTTGAGCGTTACT-1-0 0
GAGGGATGGGAAAT-1-1 1

Preprocessing the data#

It is common to remove outliers, and even perform feature selection before model fitting. We prefer the Scanpy preprocessing module at this stage.

[12]:
sc.pp.filter_genes(adata, min_counts=3)
sc.pp.filter_cells(adata, min_counts=3)

As it is popular to normalize the data for many methods, we can use Scanpy for this; however, it’s important to keep the count information intact for scvi-tools models.

[13]:
adata.layers["counts"] = adata.X.copy()

Now we can proceed with common normalization methods.

[14]:
sc.pp.normalize_total(adata)
sc.pp.log1p(adata)

We can store the normalized values in .raw to keep them safe in the event the anndata gets subsetted feature-wise.

[15]:
adata.raw = adata

Alternatively, we can create a new MuData object where the normalized data are another “modality”. This workflow is ideal going forward as .raw in AnnData has an akward interface.

We denote axis=-1 when creating the MuData object to denote that both the obs and var axes are aligned across modalities.

[16]:
mdata = muon.MuData({"rna": adata.copy(), "log_norm_rna": adata.copy()}, axis=-1)
# Now rna is count-based and log_norm_rna is log-normalized
mdata.mod["rna"].X = mdata.mod["rna"].layers["counts"]
del mdata.mod["rna"].raw
del mdata.mod["rna"].layers["counts"]
del mdata.mod["log_norm_rna"].layers["counts"]
mdata
/home/adam/miniconda3/envs/scvi-tools-dev/lib/python3.10/site-packages/mudata/_core/mudata.py:578: FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`
  data_mod.loc[:, colname] = col
/home/adam/miniconda3/envs/scvi-tools-dev/lib/python3.10/site-packages/mudata/_core/mudata.py:578: FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`
  data_mod.loc[:, colname] = col
[16]:
MuData object with n_obs × n_vars = 7947 × 14309
  2 modalities
    rna:    7947 x 14309
      obs:  'batch', 'n_counts'
      var:  'gene_ids-0', 'feature_types-0', 'genome-0', 'gene_ids-1', 'n_counts'
      uns:  'log1p'
    log_norm_rna:   7947 x 14309
      obs:  'batch', 'n_counts'
      var:  'gene_ids-0', 'feature_types-0', 'genome-0', 'gene_ids-1', 'n_counts'
      uns:  'log1p'

Register the data with scvi-tools#

Now that we have an AnnData object, we need to alert scvi-tools of all the interesting data in our object. For example, now that we have batches in our AnnData, we can alert the models that we’d like to perform batch correction. Also, because we have the count data in a layer, we can use the layer argument.

Normally, we set up the data right before using a model, thus we would call the setup_anndata method specific to that model. However, we are not using any particular model here since we are just demonstrating data usage and handling in this tutorial. We will use the SCVI model’s setup_anndata method here and in what follows for sake of example.

Basic case#

[17]:
scvi.model.SCVI.setup_anndata(adata, layer="counts", batch_key="batch")

CITE-seq case#

As PBMC5k is a CITE-seq dataset, we can use scvi-tools to register the protein abundance. Note that totalVI is the only current model that uses the protein abundance. The usage of registered items is model specific.

We have not preprocessed the pbmc5k object, which we do recommend. However, here we show how to setup this object for totalVI.

setup_mudata#

With CITE-seq data we can use a MuData or AnnData object. In the MuData case we use the modalities argument to specify which modality contains the RNA data and which contains the protein data. The None value of the layers indicates to use .X.

Therefore in the example below, the protein data will come from the "prot" modality’s .X, and likewise the RNA data will come from the "rna" modality’s .X.

[25]:
# totalVI requires dense protein data
pbmc5k.mod["prot"].X = np.asarray(pbmc5k.mod["prot"].X.A)
scvi.model.TOTALVI.setup_mudata(
    pbmc5k,
    protein_layer=None,
    rna_layer=None,
    modalities={"protein_layer": "prot", "rna_layer": "rna"},
)

setup_anndata#

[26]:
adata_pbm5k = pbmc5k.mod["rna"]
adata_pbm5k.obsm["prot"] = pbmc5k.mod["prot"].to_df()

scvi.model.TOTALVI.setup_anndata(
    adata_pbm5k,
    protein_expression_obsm_key="prot",
)
INFO     Using column names from columns of adata.obsm['prot']

Warning

After setup_anndata or setup_mudata has been run, the adata object should not be modified. The very next step in the workflow is to initialize and train the model of interest (e.g., scVI, totalVI). If you do modify the adata, it’s ok, just run setup_anndata or setup_mudata again – and then reinitialize the model.

Viewing the scvi-tools data setup#

[28]:
model = scvi.model.TOTALVI(adata_pbm5k)
model.view_anndata_setup(adata_pbm5k)
INFO     Computing empirical prior initialization for protein background.
Anndata setup with scvi-tools version 0.19.0.
Setup via `TOTALVI.setup_anndata` with arguments:
{
'protein_expression_obsm_key': 'prot',
'protein_names_uns_key': None,
'batch_key': None,
'layer': None,
'size_factor_key': None,
'categorical_covariate_keys': None,
'continuous_covariate_keys': None
}
         Summary Statistics         
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┓
┃     Summary Stat Key      Value ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━┩
│         n_batch             1   │
│         n_cells           5247  │
│ n_extra_categorical_covs    0   │
│ n_extra_continuous_covs     0   │
│         n_labels            1   │
│        n_proteins          32   │
│          n_vars           33538 │
└──────────────────────────┴───────┘
               Data Registry                
┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Registry Key     scvi-tools Location    ┃
┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│      X                 adata.X          │
│    batch      adata.obs['_scvi_batch']  │
│    labels     adata.obs['_scvi_labels'] │
│   proteins       adata.obsm['prot']     │
└──────────────┴───────────────────────────┘
                     labels State Registry                      
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓
┃      Source Location       Categories  scvi-tools Encoding ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩
│ adata.obs['_scvi_labels']      0                0          │
└───────────────────────────┴────────────┴─────────────────────┘
                     batch State Registry                      
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓
┃     Source Location       Categories  scvi-tools Encoding ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩
│ adata.obs['_scvi_batch']      0                0          │
└──────────────────────────┴────────────┴─────────────────────┘