Debian Codegraph @

R/matrix-functions.R

raw
1
2 #---------------------------------------------
3 # matrix manipulation functions
4 #---------------------------------------------
5
6 sub_f <- function(x, fac, dim) {
7 function(f) switch(dim,
8 row = x[fac==f, ,drop=FALSE],
9 col = x[ ,fac==f, drop=FALSE],
10 both = x[fac==f, fac==f, drop=FALSE])
11 }
12
13 matrix_list <- function(x, fac, dim) {
14 if (is.vector(x)) {
15 if (dim != "both") stop(paste0("Object must be a matrix in order to subset by ",dim,"."))
16 x_list <- split(x, fac)
17 lapply(x_list, function(x) diag(x, nrow = length(x)))
18 } else {
19 lapply(levels(fac), sub_f(x, fac, dim))
20 }
21 }
22
23 # turn block-diagonal into regular matrix
24
25 unblock <- function(A, block = attr(A, "groups")) {
26
27 if (is.null(block)) block <- factor(rep(names(A), times = sapply(A, function(x) dim(x)[1])))
28 n <- length(block)
29 mat <- matrix(0, n, n)
30 for (i in levels(block)) {
31 index <- i == block
32 mat[index,index] <- A[[i]]
33 }
34 return(mat)
35 }
36
37 matrix_power <- function(x, p, symmetric = TRUE, tol = -12) {
38 eig <- eigen(x, symmetric = symmetric)
39 val_p <- with(eig, ifelse(values > 10^tol, values^p, 0))
40 with(eig, vectors %*% (val_p * t(vectors)))
41 }
42
43 chol_psd <- function(x) with(eigen(x, symmetric=TRUE), sqrt(pmax(values,0)) * t(vectors))
44
45
46 add_submatrices <- function(indices, small_mat, big_mat) {
47 levs <- levels(indices)
48 for (i in 1:length(levs)) {
49 ind <- levs[i] == indices
50 big_mat[ind,ind] <- small_mat[[i]] + big_mat[ind,ind]
51 }
52 big_mat
53 }
54
55 add_bdiag <- function(small_mats, big_mats, crosswalk) {
56 small_indices <- lapply(split(crosswalk[[1]], crosswalk[[2]]), droplevels)
57 big_indices <- unique(crosswalk)
58 big_indices <- big_indices[[2]][order(big_indices[[1]])]
59 small_mats <- split(small_mats, big_indices)
60 Map(add_submatrices, indices = small_indices, small_mat = small_mats, big_mat = big_mats)
61 }
62
63 nest_bdiag <- function(mats, crosswalk) {
64 small_indices <- lapply(split(crosswalk[[1]], crosswalk[[2]]), droplevels)
65 big_indices <- unique(crosswalk)
66 big_indices <- big_indices[[2]][order(big_indices[[1]])]
67 mat_groups <- split(mats, big_indices)
68 Map(unblock, A = mat_groups)
69 }
70