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   Group1    73317.5
#> Cell2         Cell2      Batch1   Group8    62159.1
#> Cell3         Cell3      Batch1   Group1    68796.0
#> Cell4         Cell4      Batch1   Group3    60843.1
#> Cell5         Cell5      Batch1   Group8    90444.3
#> ...             ...         ...      ...        ...
#> Cell496     Cell496      Batch2  Group3     55401.0
#> Cell497     Cell497      Batch2  Group10    59985.3
#> Cell498     Cell498      Batch2  Group7     63211.7
#> Cell499     Cell499      Batch2  Group3     83457.7
#> Cell500     Cell500      Batch2  Group3     49164.6

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.015   0.000   0.488 
#> Time of initialization
#>    user  system elapsed 
#>   0.060   0.007   0.527
#> Iteration 1
#> penalized log-likelihood = -1287557.48561027
#> Time of dispersion optimization
#>    user  system elapsed 
#>   1.028   0.029   1.057
#> after optimize dispersion = -1054318.02830995
#> Time of right optimization
#>    user  system elapsed 
#>   0.003   0.000   6.563
#> after right optimization= -1053558.48750499
#> after orthogonalization = -1053558.445754
#> Time of left optimization
#>    user  system elapsed 
#>   0.003   0.000   6.023
#> after left optimization= -1053148.62099747
#> after orthogonalization = -1053148.61555489
#> Iteration 2
#> penalized log-likelihood = -1053148.61555489
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.086   0.000   0.789
#> after optimize dispersion = -1048715.75254501
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.000   0.935
#> after right optimization= -1048708.35482169
#> after orthogonalization = -1048708.35426999
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   1.477
#> after left optimization= -1048670.53822859
#> after orthogonalization = -1048670.53730918
#> Iteration 3
#> penalized log-likelihood = -1048670.53730918
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.083   0.012   0.391
#> after optimize dispersion = -1048670.55171668
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000   0.700
#> after right optimization= -1048663.69032073
#> after orthogonalization = -1048663.68955516
#> Time of left optimization
#>    user  system elapsed 
#>   0.002   0.000   0.734
#> after left optimization= -1048634.55429981
#> after orthogonalization = -1048634.55350515

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.2.0 RC (2022-04-21 r82226)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Ubuntu 20.04.4 LTS
#> 
#> Matrix products: default
#> BLAS:   /home/biocbuild/bbs-3.16-bioc/R/lib/libRblas.so
#> LAPACK: /home/biocbuild/bbs-3.16-bioc/R/lib/libRlapack.so
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_GB              LC_COLLATE=C              
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> attached base packages:
#> [1] stats4    stats     graphics  grDevices utils     datasets  methods  
#> [8] base     
#> 
#> other attached packages:
#>  [1] NewWave_1.7.0               mclust_5.4.9               
#>  [3] ggplot2_3.3.5               Rtsne_0.16                 
#>  [5] irlba_2.3.5                 Matrix_1.4-1               
#>  [7] splatter_1.21.0             SingleCellExperiment_1.19.0
#>  [9] SummarizedExperiment_1.27.0 Biobase_2.57.0             
#> [11] GenomicRanges_1.49.0        GenomeInfoDb_1.33.0        
#> [13] IRanges_2.31.0              S4Vectors_0.35.0           
#> [15] BiocGenerics_0.43.0         MatrixGenerics_1.9.0       
#> [17] matrixStats_0.62.0         
#> 
#> loaded via a namespace (and not attached):
#>  [1] sass_0.4.1             BiocSingular_1.13.0    jsonlite_1.8.0        
#>  [4] bslib_0.3.1            assertthat_0.2.1       highr_0.9             
#>  [7] GenomeInfoDbData_1.2.8 yaml_2.3.5             pillar_1.7.0          
#> [10] backports_1.4.1        lattice_0.20-45        glue_1.6.2            
#> [13] beachmat_2.13.0        SharedObject_1.11.0    digest_0.6.29         
#> [16] XVector_0.37.0         checkmate_2.1.0        colorspace_2.0-3      
#> [19] htmltools_0.5.2        pkgconfig_2.0.3        zlibbioc_1.43.0       
#> [22] purrr_0.3.4            scales_1.2.0           ScaledMatrix_1.5.0    
#> [25] BiocParallel_1.31.0    tibble_3.1.6           generics_0.1.2        
#> [28] farver_2.1.0           ellipsis_0.3.2         withr_2.5.0           
#> [31] cli_3.3.0              magrittr_2.0.3         crayon_1.5.1          
#> [34] evaluate_0.15          fansi_1.0.3            tools_4.2.0           
#> [37] lifecycle_1.0.1        stringr_1.4.0          munsell_0.5.0         
#> [40] locfit_1.5-9.5         DelayedArray_0.23.0    compiler_4.2.0        
#> [43] jquerylib_0.1.4        rsvd_1.0.5             rlang_1.0.2           
#> [46] grid_4.2.0             RCurl_1.98-1.6         bitops_1.0-7          
#> [49] labeling_0.4.2         rmarkdown_2.14         gtable_0.3.0          
#> [52] DBI_1.1.2              R6_2.5.1               knitr_1.38            
#> [55] dplyr_1.0.8            fastmap_1.1.0          utf8_1.2.2            
#> [58] stringi_1.7.6          parallel_4.2.0         Rcpp_1.0.8.3          
#> [61] vctrs_0.4.1            tidyselect_1.1.2       xfun_0.30