# 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.68822368 -1.3936384 -0.9065217  0.59705973 -1.1991963 -0.74184813
## [2,] -0.01911792 -1.2385333 -0.8869012 -1.62744841  1.6275772  0.62797273
## [3,]  1.19452692 -1.1414415  0.2726929  1.41265993 -1.5589486  0.06296977
## [4,]  0.76889985 -0.1159187  1.5394444  0.78473301  0.4309203  1.37913699
## [5,] -1.28017608 -1.4552560 -0.2827076 -0.43212041 -0.2466588 -0.00876254
## [6,] -0.29178666 -0.4826454  0.5117298  0.03836813  0.9124779 -2.37437121
##            [,7]        [,8]       [,9]       [,10]
## [1,] -0.4517361  1.58211401 -1.3211643 -0.60379602
## [2,]  1.5910932  0.07804622 -1.1639021 -0.18836866
## [3,]  1.1720867 -1.96767312  1.6900764  0.23458098
## [4,]  0.9313554  0.42210405 -0.9454156  0.77840870
## [5,] -0.5835726  0.19683738 -1.2185449  1.60605197
## [6,] -0.4385826 -0.02693251 -1.7756765  0.06465695
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.68822368 -1.39363841 -0.90652174   . -1.32116434 -0.60379602
## [2,] -0.01911792 -1.23853334 -0.88690115   . -1.16390206 -0.18836866
## [3,]  1.19452692 -1.14144147  0.27269290   .  1.69007645  0.23458098
## [4,]  0.76889985 -0.11591868  1.53944436   . -0.94541557  0.77840870
## [5,] -1.28017608 -1.45525602 -0.28270765   . -1.21854488  1.60605197
## [6,] -0.29178666 -0.48264544  0.51172982   . -1.77567648  0.06465695
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.68822368 -1.39363841 -0.90652174   . -1.32116434 -0.60379602
## [2,] -0.01911792 -1.23853334 -0.88690115   . -1.16390206 -0.18836866
## [3,]  1.19452692 -1.14144147  0.27269290   .  1.69007645  0.23458098
## [4,]  0.76889985 -0.11591868  1.53944436   . -0.94541557  0.77840870
## [5,] -1.28017608 -1.45525602 -0.28270765   . -1.21854488  1.60605197
## [6,] -0.29178666 -0.48264544  0.51172982   . -1.77567648  0.06465695

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.022   0.000   0.022
# The slower way with block processing.
da <- scale(DelayedArray(mat))
system.time(out2 <- da %*% blob)
##    user  system elapsed
##  30.949   9.553  40.549

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
##   9.720   0.316  10.037

# 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.01    0.00    0.01
system.time(rowSums(da))
##    user  system elapsed
##  20.166   7.648  27.814

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.0029809564 -0.0006456195  0.0037348976  0.0030665278  0.0021745640
##     [2,] -0.0029809564 -0.0006456195  0.0037348976  0.0030665278  0.0021745640
##     [3,] -0.0029809564 -0.0006456195  0.0037348976  0.0030665278  0.0021745640
##     [4,] -0.0029809564 -0.0006456195  0.0037348976  0.0030665278  0.0021745640
##     [5,] -0.0029809564 -0.0006456195  0.0037348976  0.0030665278  0.0021745640
##      ...             .             .             .             .             .
## [19996,] -0.0029809564 -0.0006456195  0.0037348976  0.0030665278  0.0021745640
## [19997,] -0.0029809564 -0.0006456195  0.0037348976 -0.9517324152  0.0021745640
## [19998,] -0.0029809564 -0.0006456195  0.0037348976  0.0030665278  0.0021745640
## [19999,] -0.0029809564 -0.0006456195  0.0037348976  0.0030665278  0.0021745640
## [20000,] -0.0029809564 -0.0006456195  0.0037348976  0.0030665278  0.0021745640
t(smat)
## <10000 x 20000> matrix of class ScaledMatrix and type "double":
##                   [,1]          [,2]          [,3] ...      [,19999]
##     [1,] -0.0029809564 -0.0029809564 -0.0029809564   . -0.0029809564
##     [2,] -0.0006456195 -0.0006456195 -0.0006456195   . -0.0006456195
##     [3,]  0.0037348976  0.0037348976  0.0037348976   .  0.0037348976
##     [4,]  0.0030665278  0.0030665278  0.0030665278   .  0.0030665278
##     [5,]  0.0021745640  0.0021745640  0.0021745640   .  0.0021745640
##      ...             .             .             .   .             .
##  [9996,]  -0.003123978  -0.003123978  -0.003123978   .  -0.003123978
##  [9997,]  -0.020145212  -0.020145212  -0.020145212   .  -0.020145212
##  [9998,]  -0.003486468  -0.003486468  -0.003486468   .  -0.003486468
##  [9999,]   0.008861400   0.008861400   0.008861400   .   0.008861400
## [10000,]  -0.004134874  -0.004134874  -0.004134874   .  -0.004134874
##               [,20000]
##     [1,] -0.0029809564
##     [2,] -0.0006456195
##     [3,]  0.0037348976
##     [4,]  0.0030665278
##     [5,]  0.0021745640
##      ...             .
##  [9996,]  -0.003123978
##  [9997,]  -0.020145212
##  [9998,]  -0.003486468
##  [9999,]   0.008861400
## [10000,]  -0.004134874
rownames(smat) <- paste0("GENE_", 1:20000)
smat
## <20000 x 10000> matrix of class ScaledMatrix and type "double":
##                     [,1]          [,2]          [,3] ...       [,9999]
##     GENE_1 -0.0029809564 -0.0006456195  0.0037348976   .   0.008861400
##     GENE_2 -0.0029809564 -0.0006456195  0.0037348976   .   0.008861400
##     GENE_3 -0.0029809564 -0.0006456195  0.0037348976   .   0.008861400
##     GENE_4 -0.0029809564 -0.0006456195  0.0037348976   .   0.008861400
##     GENE_5 -0.0029809564 -0.0006456195  0.0037348976   .   0.008861400
##        ...             .             .             .   .             .
## GENE_19996 -0.0029809564 -0.0006456195  0.0037348976   .   0.008861400
## GENE_19997 -0.0029809564 -0.0006456195  0.0037348976   .   0.008861400
## GENE_19998 -0.0029809564 -0.0006456195  0.0037348976   .   0.008861400
## GENE_19999 -0.0029809564 -0.0006456195  0.0037348976   .   0.008861400
## GENE_20000 -0.0029809564 -0.0006456195  0.0037348976   .   0.008861400
##                 [,10000]
##     GENE_1  -0.004134874
##     GENE_2  -0.004134874
##     GENE_3  -0.004134874
##     GENE_4  -0.004134874
##     GENE_5  -0.004134874
##        ...             .
## GENE_19996 -18.113334335
## GENE_19997  -0.004134874
## GENE_19998  -0.004134874
## GENE_19999  -0.004134874
## GENE_20000  -0.004134874

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 0.9970190 0.9993544 1.0037349   .   1.0088614   0.9958651
##     GENE_2 0.9970190 0.9993544 1.0037349   .   1.0088614   0.9958651
##     GENE_3 0.9970190 0.9993544 1.0037349   .   1.0088614   0.9958651
##     GENE_4 0.9970190 0.9993544 1.0037349   .   1.0088614   0.9958651
##     GENE_5 0.9970190 0.9993544 1.0037349   .   1.0088614   0.9958651
##        ...         .         .         .   .           .           .
## GENE_19996 0.9970190 0.9993544 1.0037349   .   1.0088614 -17.1133343
## GENE_19997 0.9970190 0.9993544 1.0037349   .   1.0088614   0.9958651
## GENE_19998 0.9970190 0.9993544 1.0037349   .   1.0088614   0.9958651
## GENE_19999 0.9970190 0.9993544 1.0037349   .   1.0088614   0.9958651
## GENE_20000 0.9970190 0.9993544 1.0037349   .   1.0088614   0.9958651

# 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.2.0 RC (2022-04-19 r82224)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.4 LTS
##
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.15-bioc/R/lib/libRblas.so
## LAPACK: /home/biocbuild/bbs-3.15-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
## [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] BiocSingular_1.12.0  ScaledMatrix_1.4.0   DelayedArray_0.22.0
##  [4] IRanges_2.30.0       S4Vectors_0.34.0     MatrixGenerics_1.8.0
##  [7] matrixStats_0.62.0   BiocGenerics_0.42.0  Matrix_1.4-1
## [10] BiocStyle_2.24.0
##
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.8.3              bslib_0.3.1
##  [3] compiler_4.2.0            BiocManager_1.30.17
##  [5] jquerylib_0.1.4           tools_4.2.0
##  [7] DelayedMatrixStats_1.18.0 digest_0.6.29
##  [9] jsonlite_1.8.0            evaluate_0.15
## [11] lattice_0.20-45           rlang_1.0.2
## [13] cli_3.3.0                 parallel_4.2.0
## [15] yaml_2.3.5                xfun_0.30
## [17] fastmap_1.1.0             stringr_1.4.0
## [19] knitr_1.38                sass_0.4.1
## [21] grid_4.2.0                R6_2.5.1
## [23] BiocParallel_1.30.0       rmarkdown_2.14
## [25] bookdown_0.26             irlba_2.3.5
## [27] magrittr_2.0.3            htmltools_0.5.2
## [29] sparseMatrixStats_1.8.0   rsvd_1.0.5
## [31] beachmat_2.12.0           stringi_1.7.6