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    81520.3
#> Cell2         Cell2      Batch1   Group8    53043.1
#> Cell3         Cell3      Batch1   Group3    48867.3
#> Cell4         Cell4      Batch1   Group3    63087.6
#> Cell5         Cell5      Batch1   Group4    64671.9
#> ...             ...         ...      ...        ...
#> Cell496     Cell496      Batch2   Group2    89687.0
#> Cell497     Cell497      Batch2   Group5    51284.5
#> Cell498     Cell498      Batch2   Group2    72541.6
#> Cell499     Cell499      Batch2   Group9    41821.2
#> Cell500     Cell500      Batch2   Group5    77733.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.012   0.008   0.272 
#> Time of initialization
#>    user  system elapsed 
#>   0.075   0.000   0.532
#> Iteration 1
#> penalized log-likelihood = -1294550.18439853
#> Time of dispersion optimization
#>    user  system elapsed 
#>   1.006   0.016   1.023
#> after optimize dispersion = -1059666.9937942
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.000   3.820
#> after right optimization= -1058904.1607334
#> after orthogonalization = -1058904.11269187
#> Time of left optimization
#>    user  system elapsed 
#>   0.000   0.002   3.196
#> after left optimization= -1058557.4389688
#> after orthogonalization = -1058557.43535423
#> Iteration 2
#> penalized log-likelihood = -1058557.43535423
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.047   0.004   0.547
#> after optimize dispersion = -1054542.01510891
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.000   0.615
#> after right optimization= -1054536.20004674
#> after orthogonalization = -1054536.19986668
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   0.664
#> after left optimization= -1054497.13872604
#> after orthogonalization = -1054497.13807506
#> Iteration 3
#> penalized log-likelihood = -1054497.13807506
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.062   0.000   0.257
#> after optimize dispersion = -1054497.15305862
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000   0.564
#> after right optimization= -1054488.90509888
#> after orthogonalization = -1054488.89897922
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   0.615
#> after left optimization= -1054460.58500094
#> after orthogonalization = -1054460.58382107

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.1 (2022-06-23)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Ubuntu 20.04.5 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.8.0               mclust_6.0.0               
#>  [3] ggplot2_3.3.6               Rtsne_0.16                 
#>  [5] irlba_2.3.5.1               Matrix_1.5-1               
#>  [7] splatter_1.22.0             SingleCellExperiment_1.20.0
#>  [9] SummarizedExperiment_1.28.0 Biobase_2.58.0             
#> [11] GenomicRanges_1.50.0        GenomeInfoDb_1.34.0        
#> [13] IRanges_2.32.0              S4Vectors_0.36.0           
#> [15] BiocGenerics_0.44.0         MatrixGenerics_1.10.0      
#> [17] matrixStats_0.62.0         
#> 
#> loaded via a namespace (and not attached):
#>  [1] rsvd_1.0.5             Rcpp_1.0.9             locfit_1.5-9.6        
#>  [4] lattice_0.20-45        assertthat_0.2.1       digest_0.6.30         
#>  [7] utf8_1.2.2             R6_2.5.1               backports_1.4.1       
#> [10] evaluate_0.17          highr_0.9              pillar_1.8.1          
#> [13] zlibbioc_1.44.0        rlang_1.0.6            jquerylib_0.1.4       
#> [16] checkmate_2.1.0        rmarkdown_2.17         labeling_0.4.2        
#> [19] BiocParallel_1.32.0    stringr_1.4.1          SharedObject_1.12.0   
#> [22] beachmat_2.14.0        RCurl_1.98-1.9         munsell_0.5.0         
#> [25] DelayedArray_0.24.0    BiocSingular_1.14.0    compiler_4.2.1        
#> [28] xfun_0.34              pkgconfig_2.0.3        htmltools_0.5.3       
#> [31] tidyselect_1.2.0       tibble_3.1.8           GenomeInfoDbData_1.2.9
#> [34] codetools_0.2-18       fansi_1.0.3            dplyr_1.0.10          
#> [37] withr_2.5.0            bitops_1.0-7           grid_4.2.1            
#> [40] jsonlite_1.8.3         gtable_0.3.1           lifecycle_1.0.3       
#> [43] DBI_1.1.3              magrittr_2.0.3         scales_1.2.1          
#> [46] ScaledMatrix_1.6.0     cli_3.4.1              stringi_1.7.8         
#> [49] cachem_1.0.6           farver_2.1.1           XVector_0.38.0        
#> [52] bslib_0.4.0            vctrs_0.5.0            generics_0.1.3        
#> [55] tools_4.2.1            glue_1.6.2             parallel_4.2.1        
#> [58] fastmap_1.1.0          yaml_2.3.6             colorspace_2.0-3      
#> [61] knitr_1.40             sass_0.4.2