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    53799.0
#> Cell2         Cell2      Batch1   Group2    69214.5
#> Cell3         Cell3      Batch1   Group2    70920.8
#> Cell4         Cell4      Batch1   Group9    85231.9
#> Cell5         Cell5      Batch1   Group5    55341.5
#> ...             ...         ...      ...        ...
#> Cell496     Cell496      Batch2   Group3    37877.8
#> Cell497     Cell497      Batch2   Group6    55826.7
#> Cell498     Cell498      Batch2   Group3    62103.2
#> Cell499     Cell499      Batch2   Group3    61255.5
#> Cell500     Cell500      Batch2   Group5    42898.0

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.009   0.001   0.500 
#> Time of initialization
#>    user  system elapsed 
#>   0.087   0.026   1.108
#> Iteration 1
#> penalized log-likelihood = -1291209.5786204
#> Time of dispersion optimization
#>    user  system elapsed 
#>   1.041   0.028   1.071
#> after optimize dispersion = -1056095.53217835
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000  13.389
#> after right optimization= -1055341.53417614
#> after orthogonalization = -1055341.51221892
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.001   9.995
#> after left optimization= -1055037.94020666
#> after orthogonalization = -1055037.93708389
#> Iteration 2
#> penalized log-likelihood = -1055037.93708389
#> Time of dispersion optimization
#>    user  system elapsed 
#>   1.121   0.023   1.143
#> after optimize dispersion = -1055031.43200029
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.002  10.405
#> after right optimization= -1054997.34883149
#> after orthogonalization = -1054997.34563283
#> Time of left optimization
#>    user  system elapsed 
#>   0.002   0.000   6.227
#> after left optimization= -1054983.60230926
#> after orthogonalization = -1054983.60220288

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.011   0.001   0.335 
#> Time of initialization
#>    user  system elapsed 
#>   0.089   0.005   0.469
#> Iteration 1
#> penalized log-likelihood = -1291209.57862275
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.614   0.011   0.626
#> after optimize dispersion = -1056095.53570237
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.001   5.658
#> after right optimization= -1055341.53688087
#> after orthogonalization = -1055341.51492419
#> Time of left optimization
#>    user  system elapsed 
#>   0.003   0.001   8.171
#> after left optimization= -1055037.94145785
#> after orthogonalization = -1055037.93832815
#> Iteration 2
#> penalized log-likelihood = -1055037.93832815
#> Time of dispersion optimization
#>    user  system elapsed 
#>   1.125   0.041   1.165
#> after optimize dispersion = -1055031.432556
#> Time of right optimization
#>    user  system elapsed 
#>   0.003   0.000   6.048
#> after right optimization= -1054997.30629077
#> after orthogonalization = -1054997.30311218
#> Time of left optimization
#>    user  system elapsed 
#>   0.003   0.000   2.996
#> after left optimization= -1054983.52625053
#> after orthogonalization = -1054983.52612913

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.014   0.011   0.327 
#> Time of initialization
#>    user  system elapsed 
#>   0.108   0.003   0.498
#> Iteration 1
#> penalized log-likelihood = -1291209.57865268
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.678   0.029   0.708
#> after optimize dispersion = -1056095.53924303
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.001   4.060
#> after right optimization= -1055341.54013768
#> after orthogonalization = -1055341.51817134
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   3.627
#> after left optimization= -1055037.94762916
#> after orthogonalization = -1055037.94450184
#> Iteration 2
#> penalized log-likelihood = -1055037.94450184
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.229   0.008   0.237
#> after optimize dispersion = -1055033.36758201
#> Time of right optimization
#>    user  system elapsed 
#>   0.000   0.002   0.758
#> after right optimization= -1055027.94183335
#> after orthogonalization = -1055027.94124435
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.001   0.384
#> after left optimization= -1055027.66538295
#> after orthogonalization = -1055027.66533086

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.010   0.003   0.314 
#> Time of initialization
#>    user  system elapsed 
#>   0.095   0.028   0.503
#> Iteration 1
#> penalized log-likelihood = -1291209.57858537
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.615   0.019   0.635
#> after optimize dispersion = -1056095.538293
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.000   3.552
#> after right optimization= -1055341.53869466
#> after orthogonalization = -1055341.51673539
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   3.381
#> after left optimization= -1055037.94354829
#> after orthogonalization = -1055037.94042566
#> Iteration 2
#> penalized log-likelihood = -1055037.94042566
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.052   0.002   0.500
#> after optimize dispersion = -1050799.16649387
#> Time of right optimization
#>    user  system elapsed 
#>   0.000   0.001   0.666
#> after right optimization= -1050787.4785615
#> after orthogonalization = -1050787.46118876
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   0.672
#> after left optimization= -1050751.90015608
#> after orthogonalization = -1050751.8991314
#> Iteration 3
#> penalized log-likelihood = -1050751.8991314
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.051   0.001   0.217
#> after optimize dispersion = -1050751.90968268
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000   0.597
#> after right optimization= -1050746.9963357
#> after orthogonalization = -1050746.99605029
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   0.639
#> after left optimization= -1050714.4161027
#> after orthogonalization = -1050714.41471349

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.8817229

Session Information

sessionInfo()
#> R Under development (unstable) (2024-10-21 r87258)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.1 LTS
#> 
#> Matrix products: default
#> BLAS:   /home/biocbuild/bbs-3.21-bioc/R/lib/libRblas.so 
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.12.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.17.0              mclust_6.1.1               
#>  [3] ggplot2_3.5.1               Rtsne_0.17                 
#>  [5] irlba_2.3.5.1               Matrix_1.7-1               
#>  [7] splatter_1.31.0             SingleCellExperiment_1.29.0
#>  [9] SummarizedExperiment_1.37.0 Biobase_2.67.0             
#> [11] GenomicRanges_1.59.0        GenomeInfoDb_1.43.0        
#> [13] IRanges_2.41.0              S4Vectors_0.45.0           
#> [15] BiocGenerics_0.53.0         MatrixGenerics_1.19.0      
#> [17] matrixStats_1.4.1          
#> 
#> loaded via a namespace (and not attached):
#>  [1] gtable_0.3.6            xfun_0.48               bslib_0.8.0            
#>  [4] lattice_0.22-6          vctrs_0.6.5             tools_4.5.0            
#>  [7] generics_0.1.3          parallel_4.5.0          tibble_3.2.1           
#> [10] fansi_1.0.6             highr_0.11              pkgconfig_2.0.3        
#> [13] SharedObject_1.21.0     checkmate_2.3.2         lifecycle_1.0.4        
#> [16] GenomeInfoDbData_1.2.13 farver_2.1.2            compiler_4.5.0         
#> [19] munsell_0.5.1           codetools_0.2-20        htmltools_0.5.8.1      
#> [22] sass_0.4.9              yaml_2.3.10             pillar_1.9.0           
#> [25] crayon_1.5.3            jquerylib_0.1.4         BiocParallel_1.41.0    
#> [28] DelayedArray_0.33.0     cachem_1.1.0            abind_1.4-8            
#> [31] rsvd_1.0.5              tidyselect_1.2.1        locfit_1.5-9.10        
#> [34] digest_0.6.37           BiocSingular_1.23.0     dplyr_1.1.4            
#> [37] labeling_0.4.3          fastmap_1.2.0           grid_4.5.0             
#> [40] colorspace_2.1-1        cli_3.6.3               SparseArray_1.7.0      
#> [43] magrittr_2.0.3          S4Arrays_1.7.0          utf8_1.2.4             
#> [46] withr_3.0.2             UCSC.utils_1.3.0        scales_1.3.0           
#> [49] backports_1.5.0         rmarkdown_2.28          XVector_0.47.0         
#> [52] httr_1.4.7              beachmat_2.23.0         ScaledMatrix_1.15.0    
#> [55] evaluate_1.0.1          knitr_1.48              rlang_1.1.4            
#> [58] Rcpp_1.0.13             glue_1.8.0              jsonlite_1.8.9         
#> [61] R6_2.5.1                zlibbioc_1.53.0