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  Group6     66699.8
#> Cell2         Cell2      Batch1  Group10    63777.1
#> Cell3         Cell3      Batch1  Group9     72411.0
#> Cell4         Cell4      Batch1  Group9     65963.6
#> Cell5         Cell5      Batch1  Group4     59865.8
#> ...             ...         ...      ...        ...
#> Cell496     Cell496      Batch2   Group6    70034.5
#> Cell497     Cell497      Batch2   Group3    71317.1
#> Cell498     Cell498      Batch2   Group6    57982.1
#> Cell499     Cell499      Batch2   Group8    66628.5
#> Cell500     Cell500      Batch2   Group9    52442.7

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.016   0.000   0.262 
#> Time of initialization
#>    user  system elapsed 
#>   0.056   0.000   0.428
#> Iteration 1
#> penalized log-likelihood = -1282183.42762887
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.580   0.012   0.592
#> after optimize dispersion = -1049675.99910903
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.000   3.206
#> after right optimization= -1048923.60474809
#> after orthogonalization = -1048923.56166836
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   2.995
#> after left optimization= -1048425.08372778
#> after orthogonalization = -1048425.07624055
#> Iteration 2
#> penalized log-likelihood = -1048425.07624055
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.045   0.000   0.530
#> after optimize dispersion = -1043854.38373288
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000   0.614
#> after right optimization= -1043844.45836944
#> after orthogonalization = -1043844.45717141
#> Time of left optimization
#>    user  system elapsed 
#>   0.002   0.000   0.630
#> after left optimization= -1043800.19595581
#> after orthogonalization = -1043800.19495874
#> Iteration 3
#> penalized log-likelihood = -1043800.19495874
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.058   0.000   0.303
#> after optimize dispersion = -1043800.21859133
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.000   0.588
#> after right optimization= -1043787.83622426
#> after orthogonalization = -1043787.82001762
#> Time of left optimization
#>    user  system elapsed 
#>   0.002   0.000   0.604
#> after left optimization= -1043756.32740591
#> after orthogonalization = -1043756.32606715

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.1.0 (2021-05-18)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Ubuntu 20.04.2 LTS
#> 
#> Matrix products: default
#> BLAS:   /home/biocbuild/bbs-3.13-bioc/R/lib/libRblas.so
#> LAPACK: /home/biocbuild/bbs-3.13-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] parallel  stats4    stats     graphics  grDevices utils     datasets 
#> [8] methods   base     
#> 
#> other attached packages:
#>  [1] NewWave_1.2.0               mclust_5.4.7               
#>  [3] ggplot2_3.3.3               Rtsne_0.15                 
#>  [5] irlba_2.3.3                 Matrix_1.3-3               
#>  [7] splatter_1.16.0             SingleCellExperiment_1.14.0
#>  [9] SummarizedExperiment_1.22.0 Biobase_2.52.0             
#> [11] GenomicRanges_1.44.0        GenomeInfoDb_1.28.0        
#> [13] IRanges_2.26.0              S4Vectors_0.30.0           
#> [15] BiocGenerics_0.38.0         MatrixGenerics_1.4.0       
#> [17] matrixStats_0.58.0         
#> 
#> loaded via a namespace (and not attached):
#>  [1] rsvd_1.0.5             Rcpp_1.0.6             locfit_1.5-9.4        
#>  [4] lattice_0.20-44        assertthat_0.2.1       digest_0.6.27         
#>  [7] utf8_1.2.1             R6_2.5.0               backports_1.2.1       
#> [10] evaluate_0.14          highr_0.9              pillar_1.6.1          
#> [13] zlibbioc_1.38.0        rlang_0.4.11           jquerylib_0.1.4       
#> [16] checkmate_2.0.0        rmarkdown_2.8          labeling_0.4.2        
#> [19] BiocParallel_1.26.0    stringr_1.4.0          SharedObject_1.6.0    
#> [22] beachmat_2.8.0         RCurl_1.98-1.3         munsell_0.5.0         
#> [25] DelayedArray_0.18.0    BiocSingular_1.8.0     compiler_4.1.0        
#> [28] xfun_0.23              pkgconfig_2.0.3        htmltools_0.5.1.1     
#> [31] tidyselect_1.1.1       tibble_3.1.2           GenomeInfoDbData_1.2.6
#> [34] fansi_0.4.2            crayon_1.4.1           dplyr_1.0.6           
#> [37] withr_2.4.2            bitops_1.0-7           grid_4.1.0            
#> [40] jsonlite_1.7.2         gtable_0.3.0           lifecycle_1.0.0       
#> [43] DBI_1.1.1              magrittr_2.0.1         scales_1.1.1          
#> [46] ScaledMatrix_1.0.0     stringi_1.6.2          farver_2.1.0          
#> [49] XVector_0.32.0         bslib_0.2.5.1          ellipsis_0.3.2        
#> [52] generics_0.1.0         vctrs_0.3.8            tools_4.1.0           
#> [55] glue_1.4.2             purrr_0.3.4            yaml_2.2.1            
#> [58] colorspace_2.0-1       knitr_1.33             sass_0.4.0