Dimensionality reduction and batch effect removal using NewWave

Installation

First of all we need to install NewWave:

if(!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
BiocManager::install("NewWave")
suppressPackageStartupMessages(
  {library(SingleCellExperiment)
library(splatter)
library(irlba)
library(Rtsne)
library(ggplot2)
library(mclust)
library(NewWave)}
)

Introduction

NewWave is a new package that assumes a Negative Binomial distributions for dimensionality reduction and batch effect removal. In order to reduce the memory consumption it uses a PSOCK cluster combined with the R package SharedObject that allow to share a matrix between different cores without memory duplication. Thanks to that we can massively parallelize the estimation process with huge benefit in terms of time consumption. We can reduce even more the time consumption using some minibatch approaches on the different steps of the optimization.

I am going to show how to use NewWave with example data generated with Splatter.

params <- newSplatParams()
N=500
set.seed(1234)
data <- splatSimulateGroups(params,batchCells=c(N/2,N/2),
                           group.prob = rep(0.1,10),
                           de.prob = 0.2,
                           verbose = FALSE) 

Now we have a dataset with 500 cells and 10000 genes, I will use only the 500 most variable genes. NewWave takes as input raw data, not normalized.

set.seed(12359)
hvg <- rowVars(counts(data))
names(hvg) <- rownames(counts(data))
data <- data[names(sort(hvg,decreasing=TRUE))[1:500],]

As you can see there is a variable called batch in the colData section.

colData(data)
#> DataFrame with 500 rows and 4 columns
#>                Cell       Batch    Group ExpLibSize
#>         <character> <character> <factor>  <numeric>
#> Cell1         Cell1      Batch1   Group7    69394.7
#> Cell2         Cell2      Batch1   Group3    45269.2
#> Cell3         Cell3      Batch1   Group2    73107.6
#> Cell4         Cell4      Batch1   Group5    65459.4
#> Cell5         Cell5      Batch1   Group4    41577.9
#> ...             ...         ...      ...        ...
#> Cell496     Cell496      Batch2   Group9    61312.8
#> Cell497     Cell497      Batch2   Group2    53177.8
#> Cell498     Cell498      Batch2   Group9    71482.5
#> Cell499     Cell499      Batch2   Group5    84772.0
#> Cell500     Cell500      Batch2   Group1    53768.3

IMPORTANT: For batch effecr removal the batch variable must be a factor

data$Batch <- as.factor(data$Batch)

We also have a variable called Group that represent the cell type labels.

We can see the how the cells are distributed between group and batch

pca <- prcomp_irlba(t(counts(data)),n=10)
plot_data <-data.frame(Rtsne(pca$x)$Y)
plot_data$batch <- data$Batch
plot_data$group <- data$Group
ggplot(plot_data, aes(x=X1,y=X2,col=group, shape=batch))+ geom_point()

There is a clear batch effect between the cells.

Let’s try to correct it.

NewWave

I am going to show different implementation and the suggested way to use them with the given hardware.

Some advise:

Standard usage

This is the way to insert the batch variable, in the same manner can be inserted other cell-related variable and if you need some gene related variable those can be inserted in V.

In order to make it faster you can increase the number of cores using “children” parameter:

Commonwise dispersion and minibatch approaches

If you do not have an high number of cores to run newWave this is the fastest way to run. The optimization process is done by three process itereated until convercence.

Each of these three steps can be accelerated using mini batch, the number of observation is settled with these parameters:

Genewise dispersion mini-batch

If you have a lot of core disposable or you want to estimate a genewise dispersion parameter this is the fastes configuration:

res3 <- newWave(data,X = "~Batch", verbose = TRUE,K=10, children=2,
                n_gene_par = 100, n_cell_par = 100, commondispersion = FALSE)
#> Time of setup
#>    user  system elapsed 
#>    0.02    0.00    0.39 
#> Time of initialization
#>    user  system elapsed 
#>    0.03    0.00    0.36
#> Iteration 1
#> penalized log-likelihood = -1296222.94323569
#> Time of dispersion optimization
#>    user  system elapsed 
#>    1.34    0.02    1.36
#> after optimize dispersion = -1057891.92694735
#> Time of right optimization
#>    user  system elapsed 
#>    0.00    0.00    6.75
#> after right optimization= -1057166.14302671
#> after orthogonalization = -1057166.10650811
#> Time of left optimization
#>    user  system elapsed 
#>    0.00    0.00    6.16
#> after left optimization= -1056871.69622864
#> after orthogonalization = -1056871.69419875
#> Iteration 2
#> penalized log-likelihood = -1056871.69419875
#> Time of dispersion optimization
#>    user  system elapsed 
#>    0.09    0.01    0.97
#> after optimize dispersion = -1052841.91904145
#> Time of right optimization
#>    user  system elapsed 
#>     0.0     0.0     1.2
#> after right optimization= -1052835.38763942
#> after orthogonalization = -1052835.38643117
#> Time of left optimization
#>    user  system elapsed 
#>    0.00    0.00    1.23
#> after left optimization= -1052802.04375939
#> after orthogonalization = -1052802.04281488
#> Iteration 3
#> penalized log-likelihood = -1052802.04281488
#> Time of dispersion optimization
#>    user  system elapsed 
#>    0.11    0.00    0.44
#> after optimize dispersion = -1052802.05594918
#> Time of right optimization
#>    user  system elapsed 
#>    0.00    0.00    1.19
#> after right optimization= -1052796.66590452
#> after orthogonalization = -1052796.66518409
#> Time of left optimization
#>    user  system elapsed 
#>     0.0     0.0     1.2
#> after left optimization= -1052767.13238508
#> after orthogonalization = -1052767.1315722

NB: do not use n_gene_disp in this case, it will slower the computation.

Now I can use the latent dimension rapresentation for visualization purpose:

or for clustering:

Session Information

sessionInfo()
#> R version 4.0.3 (2020-10-10)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows Server 2012 R2 x64 (build 9600)
#> 
#> Matrix products: default
#> 
#> locale:
#> [1] LC_COLLATE=C                          
#> [2] LC_CTYPE=English_United States.1252   
#> [3] LC_MONETARY=English_United States.1252
#> [4] LC_NUMERIC=C                          
#> [5] LC_TIME=English_United States.1252    
#> 
#> attached base packages:
#> [1] parallel  stats4    stats     graphics  grDevices utils     datasets 
#> [8] methods   base     
#> 
#> other attached packages:
#>  [1] NewWave_1.0.2               SharedObject_1.4.0         
#>  [3] mclust_5.4.7                ggplot2_3.3.2              
#>  [5] Rtsne_0.15                  irlba_2.3.3                
#>  [7] Matrix_1.2-18               splatter_1.14.1            
#>  [9] SingleCellExperiment_1.12.0 SummarizedExperiment_1.20.0
#> [11] Biobase_2.50.0              GenomicRanges_1.42.0       
#> [13] GenomeInfoDb_1.26.2         IRanges_2.24.1             
#> [15] S4Vectors_0.28.1            BiocGenerics_0.36.0        
#> [17] MatrixGenerics_1.2.0        matrixStats_0.57.0         
#> 
#> loaded via a namespace (and not attached):
#>  [1] tidyselect_1.1.0       locfit_1.5-9.4         xfun_0.19             
#>  [4] beachmat_2.6.4         BiocSingular_1.6.0     purrr_0.3.4           
#>  [7] lattice_0.20-41        colorspace_2.0-0       vctrs_0.3.6           
#> [10] generics_0.1.0         htmltools_0.5.0        yaml_2.2.1            
#> [13] rlang_0.4.9            pillar_1.4.7           glue_1.4.2            
#> [16] withr_2.3.0            BiocParallel_1.24.1    GenomeInfoDbData_1.2.4
#> [19] lifecycle_0.2.0        stringr_1.4.0          zlibbioc_1.36.0       
#> [22] munsell_0.5.0          gtable_0.3.0           rsvd_1.0.3            
#> [25] evaluate_0.14          labeling_0.4.2         knitr_1.30            
#> [28] Rcpp_1.0.5             scales_1.1.1           backports_1.2.1       
#> [31] checkmate_2.0.0        DelayedArray_0.16.0    XVector_0.30.0        
#> [34] farver_2.0.3           digest_0.6.27          stringi_1.5.3         
#> [37] dplyr_1.0.2            grid_4.0.3             tools_4.0.3           
#> [40] bitops_1.0-6           magrittr_2.0.1         RCurl_1.98-1.2        
#> [43] tibble_3.0.4           crayon_1.3.4           pkgconfig_2.0.3       
#> [46] ellipsis_0.3.1         rmarkdown_2.6          R6_2.5.0              
#> [49] compiler_4.0.3