diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 0000000..a6b1526 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2024-05-24 - Avoid Redundant Matrix Inversions in Formulaic Translations +**Learning:** Formulaic translation of statistical math into R code often leads to redundant matrix inversions (like computing `chol2inv(chol(A))` twice). This is an O(n^3) operation that causes unnecessary overhead. +**Action:** Always check for repeated identical calculations, especially expensive ones like matrix inversions or decompositions, and cache their results in variables to be reused. diff --git a/R/vuongtest.R b/R/vuongtest.R index 57c5f6b..1a1f040 100644 --- a/R/vuongtest.R +++ b/R/vuongtest.R @@ -271,10 +271,16 @@ calcLambda <- function(object1, object2, n, score1, score2, vc1, vc2) { AB2 <- calcAB(object2, n, score2, vc2) Bc <- calcBcross(AB1$sc, AB2$sc, n) - W <- cbind(rbind(-AB1$B %*% chol2inv(chol(AB1$A)), - t(Bc) %*% chol2inv(chol(AB1$A))), - rbind(-Bc %*% chol2inv(chol(AB2$A)), - AB2$B %*% chol2inv(chol(AB2$A)))) + ## Performance optimization: Cache redundant matrix inversions + ## Computing chol2inv(chol(A)) is an O(n^3) operation. Doing it once per + ## block instead of twice saves significant computation time for large matrices. + invA1 <- chol2inv(chol(AB1$A)) + invA2 <- chol2inv(chol(AB2$A)) + + W <- cbind(rbind(-AB1$B %*% invA1, + t(Bc) %*% invA1), + rbind(-Bc %*% invA2, + AB2$B %*% invA2)) lamstar <- eigen(W, only.values=TRUE)$values ## Discard imaginary part, as it only occurs for tiny eigenvalues?