1 Overview

The ScaledMatrix provides yet another method of running scale() on a matrix. In other words, these three operations are equivalent:

mat <- matrix(rnorm(10000), ncol=10)

smat1 <- scale(mat)
head(smat1)
##            [,1]       [,2]        [,3]       [,4]        [,5]        [,6]
## [1,] -0.1517251  1.0349949 -1.32732119 -0.4432977 -0.60154642  0.67694598
## [2,] -0.1358044 -0.8561240  0.10679730 -1.3615843 -0.14157959  0.06345357
## [3,] -1.4477873 -0.4182674 -0.64749762 -0.2516685 -1.25553488 -1.31945908
## [4,]  1.3492174 -0.9712374 -1.01742538  0.5455477  0.07627055  1.14291067
## [5,] -0.3675949 -0.2256106 -0.02119701  0.8175813  1.77826132 -0.60920189
## [6,]  0.4464430 -0.6383643  0.73512719  0.2619150  0.50429168  0.12426879
##             [,7]        [,8]       [,9]       [,10]
## [1,] -0.16656395 -1.06251165  0.2214091  0.82819590
## [2,] -0.08388116  0.09918248 -0.6205001 -0.04615483
## [3,]  1.24177655 -1.63638699  0.4871656 -0.59383879
## [4,]  0.02244200  0.86962978 -0.0588651 -0.47976605
## [5,] -0.29321337  0.24568578  0.6893685 -1.30486977
## [6,] -1.21448927  0.70318234 -1.3202684 -1.29649899
library(DelayedArray)
smat2 <- scale(DelayedArray(mat))
head(smat2)
## <6 x 10> matrix of class DelayedMatrix and type "double":
##             [,1]        [,2]        [,3] ...        [,9]       [,10]
## [1,] -0.15172508  1.03499488 -1.32732119   .  0.22140914  0.82819590
## [2,] -0.13580445 -0.85612398  0.10679730   . -0.62050014 -0.04615483
## [3,] -1.44778734 -0.41826741 -0.64749762   .  0.48716559 -0.59383879
## [4,]  1.34921744 -0.97123742 -1.01742538   . -0.05886510 -0.47976605
## [5,] -0.36759495 -0.22561057 -0.02119701   .  0.68936851 -1.30486977
## [6,]  0.44644297 -0.63836434  0.73512719   . -1.32026841 -1.29649899
library(ScaledMatrix)
smat3 <- ScaledMatrix(mat, center=TRUE, scale=TRUE)
head(smat3)
## <6 x 10> matrix of class ScaledMatrix and type "double":
##             [,1]        [,2]        [,3] ...        [,9]       [,10]
## [1,] -0.15172508  1.03499488 -1.32732119   .  0.22140914  0.82819590
## [2,] -0.13580445 -0.85612398  0.10679730   . -0.62050014 -0.04615483
## [3,] -1.44778734 -0.41826741 -0.64749762   .  0.48716559 -0.59383879
## [4,]  1.34921744 -0.97123742 -1.01742538   . -0.05886510 -0.47976605
## [5,] -0.36759495 -0.22561057 -0.02119701   .  0.68936851 -1.30486977
## [6,]  0.44644297 -0.63836434  0.73512719   . -1.32026841 -1.29649899

The biggest difference lies in how they behave in downstream matrix operations.

  • smat1 is an ordinary matrix, with the scaled and centered values fully realized in memory. Nothing too unusual here.
  • smat2 is a DelayedMatrix and undergoes block processing whereby chunks are realized and operated on, one at a time. This sacrifices speed for greater memory efficiency by avoiding a copy of the entire matrix. In particular, it preserves the structure of the original mat, e.g., from a sparse or file-backed representation.
  • smat3 is a ScaledMatrix that refactors certain operations so that they can be applied to the original mat without any scaling or centering. This takes advantage of the original data structure to speed up matrix multiplication and row/column sums, albeit at the cost of numerical precision.

2 Matrix multiplication

Given an original matrix \(\mathbf{X}\) with \(n\) columns, a vector of column centers \(\mathbf{c}\) and a vector of column scaling values \(\mathbf{s}\), our scaled matrix can be written as:

\[ \mathbf{Y} = (\mathbf{X} - \mathbf{c} \cdot \mathbf{1}_n^T) \mathbf{S} \]

where \(\mathbf{S} = \text{diag}(s_1^{-1}, ..., s_n^{-1})\). If we wanted to right-multiply it with another matrix \(\mathbf{A}\), we would have:

\[ \mathbf{YA} = \mathbf{X}\mathbf{S}\mathbf{A} - \mathbf{c} \cdot \mathbf{1}_n^T \mathbf{S}\mathbf{A} \]

The right-most expression is simply the outer product of \(\mathbf{c}\) with the column sums of \(\mathbf{SA}\). More important is the fact that we can use the matrix multiplication operator for \(\mathbf{X}\) with \(\mathbf{SA}\), as this allows us to use highly efficient algorithms for certain data representations, e.g., sparse matrices.

library(Matrix)
mat <- rsparsematrix(20000, 10000, density=0.01)
smat <- ScaledMatrix(mat, center=TRUE, scale=TRUE)

blob <- matrix(runif(ncol(mat) * 5), ncol=5)
system.time(out <- smat %*% blob)
##    user  system elapsed 
##   0.033   0.000   0.034
# The slower way with block processing.
da <- scale(DelayedArray(mat))
system.time(out2 <- da %*% blob)
##    user  system elapsed 
##  28.573  10.188  41.447

The same logic applies for left-multiplication and cross-products. This allows us to easily speed up high-level operations involving matrix multiplication by just switching to a ScaledMatrix, e.g., in approximate PCA algorithms from the BiocSingular package.

library(BiocSingular)
set.seed(1000)
system.time(pcs <- runSVD(smat, k=10, BSPARAM=IrlbaParam()))
##    user  system elapsed 
##  12.546   0.272  12.820

3 Other utilities

Row and column sums are special cases of matrix multiplication and can be computed quickly:

system.time(rowSums(smat))
##    user  system elapsed 
##   0.009   0.000   0.009
system.time(rowSums(da))
##    user  system elapsed 
##  18.863   8.067  26.933

Subsetting, transposition and renaming of the dimensions are all supported without loss of the ScaledMatrix representation:

smat[,1:5]
## <20000 x 5> matrix of class ScaledMatrix and type "double":
##                  [,1]         [,2]         [,3]         [,4]         [,5]
##     [1,]  0.005552100 -0.012733326  0.005239519 -0.008289220 -0.002023485
##     [2,]  0.005552100 -0.012733326  0.005239519 -0.008289220 -0.002023485
##     [3,]  0.005552100 -0.012733326  0.005239519 -0.008289220 -0.002023485
##     [4,]  0.005552100 -0.012733326  0.005239519 -0.008289220 -0.002023485
##     [5,]  0.005552100 -0.012733326  0.005239519 10.287889608 -0.002023485
##      ...            .            .            .            .            .
## [19996,]  0.005552100 -0.012733326  0.005239519 -0.008289220 -0.002023485
## [19997,]  0.005552100 -0.012733326  0.005239519 -0.008289220 -0.002023485
## [19998,]  0.005552100 -0.012733326  0.005239519 -0.008289220 -0.002023485
## [19999,]  0.005552100 -0.012733326  0.005239519 -0.008289220 -0.002023485
## [20000,]  0.005552100 -0.012733326  0.005239519 -0.008289220 -0.002023485
t(smat)
## <10000 x 20000> matrix of class ScaledMatrix and type "double":
##                   [,1]          [,2]          [,3] ...      [,19999]
##     [1,]   0.005552100   0.005552100   0.005552100   .   0.005552100
##     [2,]  -0.012733326  -0.012733326  -0.012733326   .  -0.012733326
##     [3,]   0.005239519   0.005239519   0.005239519   .   0.005239519
##     [4,]  -0.008289220  -0.008289220  -0.008289220   .  -0.008289220
##     [5,]  -0.002023485  -0.002023485  -0.002023485   .  -0.002023485
##      ...             .             .             .   .             .
##  [9996,]  0.0053685656  0.0053685656  0.0053685656   .  0.0053685656
##  [9997,]  0.0074176537  0.0074176537  0.0074176537   .  0.0074176537
##  [9998,] -0.0097814994 -0.0097814994 -0.0097814994   . -0.0097814994
##  [9999,]  0.0001009669  0.0001009669  0.0001009669   .  0.0001009669
## [10000,] -0.0160924762 -0.0160924762 -0.0160924762   . -0.0160924762
##               [,20000]
##     [1,]   0.005552100
##     [2,]  -0.012733326
##     [3,]   0.005239519
##     [4,]  -0.008289220
##     [5,]  -0.002023485
##      ...             .
##  [9996,]  0.0053685656
##  [9997,]  0.0074176537
##  [9998,] -0.0097814994
##  [9999,]  0.0001009669
## [10000,] -0.0160924762
rownames(smat) <- paste0("GENE_", 1:20000)
smat
## <20000 x 10000> matrix of class ScaledMatrix and type "double":
##                    [,1]         [,2]         [,3] ...       [,9999]
##     GENE_1  0.005552100 -0.012733326  0.005239519   .  0.0001009669
##     GENE_2  0.005552100 -0.012733326  0.005239519   .  0.0001009669
##     GENE_3  0.005552100 -0.012733326  0.005239519   .  0.0001009669
##     GENE_4  0.005552100 -0.012733326  0.005239519   .  0.0001009669
##     GENE_5  0.005552100 -0.012733326  0.005239519   .  0.0001009669
##        ...            .            .            .   .             .
## GENE_19996  0.005552100 -0.012733326  0.005239519   .  0.0001009669
## GENE_19997  0.005552100 -0.012733326  0.005239519   .  0.0001009669
## GENE_19998  0.005552100 -0.012733326  0.005239519   .  0.0001009669
## GENE_19999  0.005552100 -0.012733326  0.005239519   .  0.0001009669
## GENE_20000  0.005552100 -0.012733326  0.005239519   .  0.0001009669
##                 [,10000]
##     GENE_1 -0.0160924762
##     GENE_2 -0.0160924762
##     GENE_3 -0.0160924762
##     GENE_4 -0.0160924762
##     GENE_5 -0.0160924762
##        ...             .
## GENE_19996 -0.0160924762
## GENE_19997 -0.0160924762
## GENE_19998 -0.0160924762
## GENE_19999 -0.0160924762
## GENE_20000 -0.0160924762

Other operations will cause the ScaledMatrix to collapse to the general DelayedMatrix representation, after which point block processing will be used.

smat + 1
## <20000 x 10000> matrix of class DelayedMatrix and type "double":
##                 [,1]      [,2]      [,3] ...   [,9999]  [,10000]
##     GENE_1 1.0055521 0.9872667 1.0052395   . 1.0001010 0.9839075
##     GENE_2 1.0055521 0.9872667 1.0052395   . 1.0001010 0.9839075
##     GENE_3 1.0055521 0.9872667 1.0052395   . 1.0001010 0.9839075
##     GENE_4 1.0055521 0.9872667 1.0052395   . 1.0001010 0.9839075
##     GENE_5 1.0055521 0.9872667 1.0052395   . 1.0001010 0.9839075
##        ...         .         .         .   .         .         .
## GENE_19996 1.0055521 0.9872667 1.0052395   . 1.0001010 0.9839075
## GENE_19997 1.0055521 0.9872667 1.0052395   . 1.0001010 0.9839075
## GENE_19998 1.0055521 0.9872667 1.0052395   . 1.0001010 0.9839075
## GENE_19999 1.0055521 0.9872667 1.0052395   . 1.0001010 0.9839075
## GENE_20000 1.0055521 0.9872667 1.0052395   . 1.0001010 0.9839075

4 Caveats

For most part, the implementation of the multiplication assumes that the \(\mathbf{A}\) matrix and the matrix product are small compared to \(\mathbf{X}\). It is also possible to multiply two ScaledMatrixes together if the underlying matrices have efficient operators for their product. However, if this is not the case, the ScaledMatrix offers little benefit for increased overhead.

It is also worth noting that this speed-up is not entirely free. The expression above involves subtracting two matrix with potentially large values, which runs the risk of catastrophic cancellation. The example below demonstrates how ScaledMatrix is more susceptible to loss of precision than a normal DelayedArray:

set.seed(1000)
mat <- matrix(rnorm(1000000), ncol=100000) 
big.mat <- mat + 1e12

# The 'correct' value, unaffected by numerical precision.
ref <- rowMeans(scale(mat))
head(ref)
## [1] -0.0025584703 -0.0008570664 -0.0019225335 -0.0001039903  0.0024761772
## [6]  0.0032943203
# The value from scale'ing a DelayedArray.
library(DelayedArray)
smat2 <- scale(DelayedArray(big.mat))
head(rowMeans(smat2))
## [1] -0.0025583534 -0.0008571123 -0.0019226040 -0.0001039539  0.0024761618
## [6]  0.0032943783
# The value from a ScaledMatrix.
library(ScaledMatrix)
smat3 <- ScaledMatrix(big.mat, center=TRUE, scale=TRUE)
head(rowMeans(smat3))
## [1] -0.00480  0.00848  0.00544 -0.00976 -0.01056  0.01520

In most practical applications, though, this does not seem to be a major concern, especially as most values (e.g., log-normalized expression matrices) lie close to zero anyway.

Session information

sessionInfo()
## R version 4.1.0 beta (2021-05-03 r80259)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.2 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.14-bioc/R/lib/libRblas.so
## LAPACK: /home/biocbuild/bbs-3.14-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] BiocSingular_1.9.0   ScaledMatrix_1.1.0   DelayedArray_0.19.0 
##  [4] IRanges_2.27.0       S4Vectors_0.31.0     MatrixGenerics_1.5.0
##  [7] matrixStats_0.58.0   BiocGenerics_0.39.0  Matrix_1.3-3        
## [10] BiocStyle_2.21.0    
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.6                bslib_0.2.5.1            
##  [3] compiler_4.1.0            BiocManager_1.30.15      
##  [5] jquerylib_0.1.4           tools_4.1.0              
##  [7] DelayedMatrixStats_1.15.0 digest_0.6.27            
##  [9] jsonlite_1.7.2            evaluate_0.14            
## [11] lattice_0.20-44           rlang_0.4.11             
## [13] yaml_2.2.1                xfun_0.23                
## [15] stringr_1.4.0             knitr_1.33               
## [17] sass_0.4.0                grid_4.1.0               
## [19] R6_2.5.0                  BiocParallel_1.27.0      
## [21] rmarkdown_2.8             bookdown_0.22            
## [23] irlba_2.3.3               magrittr_2.0.1           
## [25] htmltools_0.5.1.1         sparseMatrixStats_1.5.0  
## [27] rsvd_1.0.5                beachmat_2.9.0           
## [29] stringi_1.6.2