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  Group10    32973.6
#> Cell2         Cell2      Batch1  Group10    60399.9
#> Cell3         Cell3      Batch1  Group7     56891.4
#> Cell4         Cell4      Batch1  Group7     46519.1
#> Cell5         Cell5      Batch1  Group8     50676.9
#> ...             ...         ...      ...        ...
#> Cell496     Cell496      Batch2   Group1    38899.7
#> Cell497     Cell497      Batch2   Group4    61240.2
#> Cell498     Cell498      Batch2   Group5    61100.1
#> Cell499     Cell499      Batch2   Group6    51938.2
#> Cell500     Cell500      Batch2   Group8   102300.1

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.011   0.006   0.321 
#> Time of initialization
#>    user  system elapsed 
#>   0.036   0.004   0.607
#> Iteration 1
#> penalized log-likelihood = -1283492.23769893
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.609   0.019   0.629
#> after optimize dispersion = -1051525.92055732
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000   7.754
#> after right optimization= -1050724.15052482
#> after orthogonalization = -1050724.07733498
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000  11.021
#> after left optimization= -1050385.87522276
#> after orthogonalization = -1050385.85074569
#> Iteration 2
#> penalized log-likelihood = -1050385.85074569
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.653   0.055   1.726
#> after optimize dispersion = -1050378.43746481
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000   6.383
#> after right optimization= -1050343.40758485
#> after orthogonalization = -1050343.40382421
#> Time of left optimization
#>    user  system elapsed 
#>   0.000   0.000   6.166
#> after left optimization= -1050330.96856665
#> after orthogonalization = -1050330.9672864

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.010   0.008   0.818 
#> Time of initialization
#>    user  system elapsed 
#>   0.030   0.006   1.447
#> Iteration 1
#> penalized log-likelihood = -1283492.2377228
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.525   0.036   0.798
#> after optimize dispersion = -1051525.92063989
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000   3.676
#> after right optimization= -1050724.15052104
#> after orthogonalization = -1050724.07733049
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   3.727
#> after left optimization= -1050385.88016313
#> after orthogonalization = -1050385.85565129
#> Iteration 2
#> penalized log-likelihood = -1050385.85565129
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.723   0.029   0.760
#> after optimize dispersion = -1050378.44241594
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000   3.436
#> after right optimization= -1050343.41850035
#> after orthogonalization = -1050343.41473341
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   2.876
#> after left optimization= -1050330.94253407
#> after orthogonalization = -1050330.94123812

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.013   0.010   0.611 
#> Time of initialization
#>    user  system elapsed 
#>   0.042   0.004   0.648
#> Iteration 1
#> penalized log-likelihood = -1283492.23785342
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.818   0.048   1.169
#> after optimize dispersion = -1051525.92283972
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.001   6.960
#> after right optimization= -1050724.15192395
#> after orthogonalization = -1050724.07872237
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.001   6.965
#> after left optimization= -1050385.88113099
#> after orthogonalization = -1050385.85665671
#> Iteration 2
#> penalized log-likelihood = -1050385.85665671
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.394   0.262   0.872
#> after optimize dispersion = -1050379.79334569
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.000   1.424
#> after right optimization= -1050372.49027509
#> after orthogonalization = -1050372.48981255
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.001   0.637
#> after left optimization= -1050372.19036525
#> after orthogonalization = -1050372.19033123

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.013   0.009   0.388 
#> Time of initialization
#>    user  system elapsed 
#>   0.044   0.006   0.583
#> Iteration 1
#> penalized log-likelihood = -1283492.23769862
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.823   0.054   1.256
#> after optimize dispersion = -1051525.92067048
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.000   7.336
#> after right optimization= -1050724.15038944
#> after orthogonalization = -1050724.07719856
#> Time of left optimization
#>    user  system elapsed 
#>   0.002   0.001   6.916
#> after left optimization= -1050385.87777753
#> after orthogonalization = -1050385.8533001
#> Iteration 2
#> penalized log-likelihood = -1050385.8533001
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.075   0.002   1.076
#> after optimize dispersion = -1045512.47108279
#> Time of right optimization
#>    user  system elapsed 
#>   0.002   0.001   1.317
#> after right optimization= -1045505.57076525
#> after orthogonalization = -1045505.56966251
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.001   0.930
#> after left optimization= -1045461.84684645
#> after orthogonalization = -1045461.84577859
#> Iteration 3
#> penalized log-likelihood = -1045461.84577859
#> Time of dispersion optimization
#>    user  system elapsed 
#>   0.060   0.002   0.296
#> after optimize dispersion = -1045461.86831612
#> Time of right optimization
#>    user  system elapsed 
#>   0.001   0.000   0.735
#> after right optimization= -1045456.54902068
#> after orthogonalization = -1045456.54881381
#> Time of left optimization
#>    user  system elapsed 
#>   0.001   0.000   0.734
#> after left optimization= -1045422.64435999
#> after orthogonalization = -1045422.64372801

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] 1

Session Information

sessionInfo()
#> R version 4.4.1 (2024-06-14)
#> Platform: x86_64-apple-darwin20
#> Running under: macOS Monterey 12.7.6
#> 
#> Matrix products: default
#> BLAS:   /Library/Frameworks/R.framework/Versions/4.4-x86_64/Resources/lib/libRblas.0.dylib 
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.4-x86_64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0
#> 
#> locale:
#> [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#> 
#> time zone: America/New_York
#> tzcode source: internal
#> 
#> attached base packages:
#> [1] stats4    stats     graphics  grDevices utils     datasets  methods  
#> [8] base     
#> 
#> other attached packages:
#>  [1] NewWave_1.16.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.30.0             SingleCellExperiment_1.28.0
#>  [9] SummarizedExperiment_1.36.0 Biobase_2.66.0             
#> [11] GenomicRanges_1.58.0        GenomeInfoDb_1.42.0        
#> [13] IRanges_2.40.0              S4Vectors_0.44.0           
#> [15] BiocGenerics_0.52.0         MatrixGenerics_1.18.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.4.1            
#>  [7] generics_0.1.3          parallel_4.4.1          tibble_3.2.1           
#> [10] fansi_1.0.6             highr_0.11              pkgconfig_2.0.3        
#> [13] SharedObject_1.20.0     checkmate_2.3.2         lifecycle_1.0.4        
#> [16] GenomeInfoDbData_1.2.13 farver_2.1.2            compiler_4.4.1         
#> [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.40.0    
#> [28] DelayedArray_0.32.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.22.0     dplyr_1.1.4            
#> [37] labeling_0.4.3          fastmap_1.2.0           grid_4.4.1             
#> [40] colorspace_2.1-1        cli_3.6.3               SparseArray_1.6.0      
#> [43] magrittr_2.0.3          S4Arrays_1.6.0          utf8_1.2.4             
#> [46] withr_3.0.2             UCSC.utils_1.2.0        scales_1.3.0           
#> [49] backports_1.5.0         rmarkdown_2.28          XVector_0.46.0         
#> [52] httr_1.4.7              beachmat_2.22.0         ScaledMatrix_1.14.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.52.0