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   Group9    41148.0
#> Cell2         Cell2      Batch1   Group9    66714.3
#> Cell3         Cell3      Batch1   Group5    62504.9
#> Cell4         Cell4      Batch1   Group8    59603.7
#> Cell5         Cell5      Batch1   Group4    58086.6
#> ...             ...         ...      ...        ...
#> Cell496     Cell496      Batch2  Group6     46561.2
#> Cell497     Cell497      Batch2  Group10    76505.4
#> Cell498     Cell498      Batch2  Group10    45492.5
#> Cell499     Cell499      Batch2  Group1     65893.1
#> Cell500     Cell500      Batch2  Group7     49821.5

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.

res <- newWave(data,X = "~Batch", K=10, verbose = TRUE)
#> Time of setup
#>    user  system elapsed 
#>   0.026   0.016   0.646 
#> Time of initialization
#>    user  system elapsed 
#>   0.053   0.007   1.530
#> Iteration 1
#> penalized log-likelihood = -1292288.91247789
#> Time of dispersion optimization
#>    user  system elapsed 
#>   1.021   0.012   1.149
#> after optimize dispersion = -1057929.18202539
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.000  13.033
#> after right optimization= -1057155.45887763
#> after orthogonalization = -1057155.43847607
#> Time of left optimization
#>    user  system elapsed 
#>   0.002   0.000   7.696
#> after left optimization= -1056843.69546086
#> after orthogonalization = -1056843.69146331
#> Iteration 2
#> penalized log-likelihood = -1056843.69146331
#> Time of dispersion optimization
#>    user  system elapsed 
#>   1.068   0.024   1.093
#> after optimize dispersion = -1056836.80251251
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.000   9.036
#> after right optimization= -1056802.42160777
#> after orthogonalization = -1056802.41542625
#> Time of left optimization
#>    user  system elapsed 
#>   0.002   0.000   6.855
#> after left optimization= -1056787.49186531
#> after orthogonalization = -1056787.49175891

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

res2 <- newWave(data,X = "~Batch", K=10, verbose = TRUE, children=2)
#> Time of setup
#>    user  system elapsed 
#>   0.008   0.005   3.342 
#> Time of initialization
#>    user  system elapsed 
#>   0.056   0.007   0.488
#> Iteration 1
#> penalized log-likelihood = -1292288.91249898
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.621   0.004   0.624
#> after optimize dispersion = -1057929.18098597
#> Time of right optimization
#>    user  system elapsed 
#>   0.000   0.004   4.362
#> after right optimization= -1057155.45841074
#> after orthogonalization = -1057155.43801115
#> Time of left optimization
#>    user  system elapsed 
#>   0.003   0.000   8.770
#> after left optimization= -1056843.65258861
#> after orthogonalization = -1056843.64858528
#> Iteration 2
#> penalized log-likelihood = -1056843.64858528
#> Time of dispersion optimization
#>    user  system elapsed 
#>   1.143   0.048   1.192
#> after optimize dispersion = -1056836.75833812
#> Time of right optimization
#>    user  system elapsed 
#>   0.000   0.003   5.774
#> after right optimization= -1056802.36902575
#> after orthogonalization = -1056802.36277531
#> Time of left optimization
#>    user  system elapsed 
#>   0.005   0.000   3.606
#> after left optimization= -1056787.51106295
#> after orthogonalization = -1056787.51096582

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:

res3 <- newWave(data,X = "~Batch", verbose = TRUE,K=10, children=2,
                n_gene_disp = 100, n_gene_par = 100, n_cell_par = 100)
#> Time of setup
#>    user  system elapsed 
#>   0.010   0.001   3.333 
#> Time of initialization
#>    user  system elapsed 
#>   0.052   0.011   0.484
#> Iteration 1
#> penalized log-likelihood = -1292288.91253175
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.684   0.016   0.700
#> after optimize dispersion = -1057929.18032952
#> Time of right optimization
#>    user  system elapsed 
#>   0.000   0.002   3.464
#> after right optimization= -1057155.45690456
#> after orthogonalization = -1057155.43650844
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   3.295
#> after left optimization= -1056843.65818083
#> after orthogonalization = -1056843.6541848
#> Iteration 2
#> penalized log-likelihood = -1056843.6541848
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.214   0.004   0.218
#> after optimize dispersion = -1056836.76527726
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000   0.634
#> after right optimization= -1056828.13286704
#> after orthogonalization = -1056828.13102052
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   0.405
#> after left optimization= -1056827.6007324
#> after orthogonalization = -1056827.60058347

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.007   0.004   3.331 
#> Time of initialization
#>    user  system elapsed 
#>   0.055   0.004   0.641
#> Iteration 1
#> penalized log-likelihood = -1292288.91249993
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.997   0.008   1.005
#> after optimize dispersion = -1057929.18062447
#> Time of right optimization
#>    user  system elapsed 
#>   0.000   0.003   5.919
#> after right optimization= -1057155.45808713
#> after orthogonalization = -1057155.43768878
#> Time of left optimization
#>    user  system elapsed 
#>   0.003   0.000   6.074
#> after left optimization= -1056843.65175863
#> after orthogonalization = -1056843.64776302
#> Iteration 2
#> penalized log-likelihood = -1056843.64776302
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.055   0.004   0.846
#> after optimize dispersion = -1052685.47269587
#> Time of right optimization
#>    user  system elapsed 
#>   0.003   0.000   1.056
#> after right optimization= -1052680.25946906
#> after orthogonalization = -1052680.25895262
#> Time of left optimization
#>    user  system elapsed 
#>   0.000   0.003   1.192
#> after left optimization= -1052636.28110785
#> after orthogonalization = -1052636.28039738
#> Iteration 3
#> penalized log-likelihood = -1052636.28039738
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.104   0.000   0.427
#> after optimize dispersion = -1052636.3041549
#> Time of right optimization
#>    user  system elapsed 
#>   0.003   0.000   0.932
#> after right optimization= -1052631.64353218
#> after orthogonalization = -1052631.64335994
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   0.627
#> after left optimization= -1052596.54196806
#> after orthogonalization = -1052596.54096366

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:

latent <- reducedDim(res)

tsne_latent <- data.frame(Rtsne(latent)$Y)
tsne_latent$batch <- data$Batch
tsne_latent$group <- data$Group
ggplot(tsne_latent, aes(x=X1,y=X2,col=group, shape=batch))+ geom_point()

or for clustering:

cluster <- kmeans(latent, 10)

adjustedRandIndex(cluster$cluster, data$Group)
#> [1] 0.8681397

Session Information

sessionInfo()
#> R version 4.3.1 (2023-06-16)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Ubuntu 22.04.2 LTS
#> 
#> Matrix products: default
#> BLAS:   /home/biocbuild/bbs-3.17-bioc/R/lib/libRblas.so 
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
#> 
#> 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       
#> 
#> time zone: America/New_York
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats4    stats     graphics  grDevices utils     datasets  methods  
#> [8] base     
#> 
#> other attached packages:
#>  [1] NewWave_1.10.0              mclust_6.0.0               
#>  [3] ggplot2_3.4.2               Rtsne_0.16                 
#>  [5] irlba_2.3.5.1               Matrix_1.6-0               
#>  [7] splatter_1.24.0             SingleCellExperiment_1.22.0
#>  [9] SummarizedExperiment_1.30.2 Biobase_2.60.0             
#> [11] GenomicRanges_1.52.0        GenomeInfoDb_1.36.1        
#> [13] IRanges_2.34.1              S4Vectors_0.38.1           
#> [15] BiocGenerics_0.46.0         MatrixGenerics_1.12.3      
#> [17] matrixStats_1.0.0          
#> 
#> loaded via a namespace (and not attached):
#>  [1] gtable_0.3.3            xfun_0.40               bslib_0.5.1            
#>  [4] lattice_0.21-8          vctrs_0.6.3             tools_4.3.1            
#>  [7] bitops_1.0-7            generics_0.1.3          parallel_4.3.1         
#> [10] tibble_3.2.1            fansi_1.0.4             highr_0.10             
#> [13] pkgconfig_2.0.3         SharedObject_1.14.1     checkmate_2.2.0        
#> [16] lifecycle_1.0.3         GenomeInfoDbData_1.2.10 farver_2.1.1           
#> [19] compiler_4.3.1          munsell_0.5.0           codetools_0.2-19       
#> [22] htmltools_0.5.6         sass_0.4.7              RCurl_1.98-1.12        
#> [25] yaml_2.3.7              pillar_1.9.0            crayon_1.5.2           
#> [28] jquerylib_0.1.4         BiocParallel_1.34.2     DelayedArray_0.26.7    
#> [31] cachem_1.0.8            abind_1.4-5             rsvd_1.0.5             
#> [34] tidyselect_1.2.0        locfit_1.5-9.8          digest_0.6.33          
#> [37] BiocSingular_1.16.0     dplyr_1.1.2             labeling_0.4.2         
#> [40] fastmap_1.1.1           grid_4.3.1              colorspace_2.1-0       
#> [43] cli_3.6.1               magrittr_2.0.3          S4Arrays_1.0.5         
#> [46] utf8_1.2.3              withr_2.5.0             scales_1.2.1           
#> [49] backports_1.4.1         rmarkdown_2.23          XVector_0.40.0         
#> [52] beachmat_2.16.0         ScaledMatrix_1.8.1      evaluate_0.21          
#> [55] knitr_1.43              rlang_1.1.1             Rcpp_1.0.11            
#> [58] glue_1.6.2              jsonlite_1.8.7          R6_2.5.1               
#> [61] zlibbioc_1.46.0