File: blockMM.R

package info (click to toggle)
r-cran-itertools 0.1-3-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 316 kB
  • sloc: makefile: 2
file content (71 lines) | stat: -rw-r--r-- 1,788 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
library(foreach)
library(itertools)

n <- 10777
nrowsx <- 959
ncolsy <- 101
chunks <- 80  # applied to "n"
xchunks <- 1  # applied to "nrowsx"
ychunks <- 1  # applied to "ncolsy"

x <- matrix(rnorm(nrowsx * n), nrow=nrowsx)
y <- matrix(rnorm(n * ncolsy), nrow=n)
expected <- x %*% y

actual <-
  foreach(ia=iarray(x, c(2,1), chunks=c(chunks,xchunks)),
          .combine='rbind') %:%
    foreach(a=ia, ib=iarray(y, c(2,1), chunks=c(ychunks,chunks)),
            .combine='+') %:%
      foreach(b=ib, .combine='cbind') %do% {
        a %*% b
      }
all.equal(actual, expected)

actual <-
  foreach(ib=iarray(y, c(1,2), chunks=c(chunks,ychunks)),
          .combine='cbind') %:%
    foreach(b=ib, ia=iarray(x, c(1,2), chunks=c(xchunks,chunks)),
            .combine='+') %:%
      foreach(a=ia, .combine='rbind') %do% {
        a %*% b
      }
all.equal(actual, expected)

actual <-
  foreach(bsub=iarray(y, 2, chunks=ychunks),
          .combine='cbind') %:%
    foreach(ia=iarray(x, c(2,1), chunks=c(chunks,xchunks)),
            .combine='rbind') %:%
      foreach(a=ia, b=iarray(bsub, 1, chunks=chunks),
              .combine='+') %do% {
        a %*% b
      }
all.equal(actual, expected)

iqseq <- function(n, ...) {
  i <- 0
  it <- idiv(n, ...)

  nextEl <- function() {
    j <- i + nextElem(it)
    val <- call(':', i + 1, j)
    i <<- j
    val
  }

  obj <- list(nextElem=nextEl)
  class(obj) <- c('abstractiter', 'iter')
  obj
}

actual <-
  foreach(bcols=iqseq(ncol(y), chunks=ychunks),
          .combine='cbind') %:%
    foreach(ia=iarray(x, c(2,1), chunks=c(chunks,xchunks)),
            .combine='rbind') %:%
      foreach(a=ia, b=iarray(y, 1, chunks=chunks, idx=list(TRUE, bcols)),
              .combine='+') %do% {
        a %*% b
      }
all.equal(actual, expected)