SCM

SCM Repository

[matrix] Diff of /pkg/Matrix/R/diagMatrix.R
ViewVC logotype

Diff of /pkg/Matrix/R/diagMatrix.R

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

pkg/R/diagMatrix.R revision 1805, Tue Mar 27 16:46:03 2007 UTC pkg/Matrix/R/diagMatrix.R revision 3046, Mon Feb 16 14:40:37 2015 UTC
# Line 5  Line 5 
5  ##          but *not* diag() extractor!  ##          but *not* diag() extractor!
6  Diagonal <- function(n, x = NULL)  Diagonal <- function(n, x = NULL)
7  {  {
8      ## Allow  Diagonal(4)  and  Diagonal(x=1:5)      ## Allow  Diagonal(4), Diagonal(x=1:5), and  Diagonal(4, TRUE)
9      if(missing(n))      n <- if(missing(n)) length(x) else {
         n <- length(x)  
     else {  
10          stopifnot(length(n) == 1, n == as.integer(n), n >= 0)          stopifnot(length(n) == 1, n == as.integer(n), n >= 0)
11          n <- as.integer(n)          as.integer(n)
12      }      }
13    
14      if(missing(x)) ## unit diagonal matrix      if(missing(x)) ## unit diagonal matrix
15          new("ddiMatrix", Dim = c(n,n), diag = "U")          new("ddiMatrix", Dim = c(n,n), diag = "U")
16      else {      else {
17          stopifnot(length(x) == n)          lx <- length(x)
18            lx.1 <- lx == 1L
19            stopifnot(lx.1 || lx == n) # but keep 'x' short for now
20          if(is.logical(x))          if(is.logical(x))
21              cl <- "ldiMatrix"              cl <- "ldiMatrix"
22          else if(is.numeric(x)) {          else if(is.numeric(x)) {
# Line 26  Line 26 
26          else if(is.complex(x)) {          else if(is.complex(x)) {
27              cl <- "zdiMatrix"  # will not yet work              cl <- "zdiMatrix"  # will not yet work
28          } else stop("'x' has invalid data type")          } else stop("'x' has invalid data type")
29          new(cl, Dim = c(n,n), diag = "N", x = x)          if(lx.1 && !is.na(x) && x == 1) # cheap check for uni-diagonal..
30                new(cl, Dim = c(n,n), diag = "U")
31            else
32                new(cl, Dim = c(n,n), diag = "N",
33                    x = if(lx.1) rep.int(x,n) else x)
34      }      }
35  }  }
36    
37  ### This is modified from a post of Bert Gunter to R-help on  1 Sep 2005.  .sparseDiagonal <- function(n, x = 1, uplo = "U",
38  ### Bert's code built on a post by Andy Liaw who most probably was influenced                              shape = if(missing(cols)) "t" else "g",
39  ### by earlier posts, notably one by Scott Chasalow on S-news, 16 Jan 2002                              unitri, kind,
40  ### who posted his bdiag() function written in December 1995.                              cols = if(n) 0:(n - 1L) else integer(0))
41    {
42        stopifnot(n == (n. <- as.integer(n)), (n <- n.) >= 0)
43        if(!(mcols <- missing(cols)))
44            stopifnot(0 <= (cols <- as.integer(cols)), cols < n)
45        m <- length(cols)
46        if(missing(kind))
47            kind <-
48                if(is.double(x)) "d"
49                else if(is.logical(x)) "l"
50                else { ## for now
51                    storage.mode(x) <- "double"
52                    "d"
53                }
54        else stopifnot(any(kind == c("d","l","n")))
55        stopifnot(is.character(shape), nchar(shape) == 1,
56                  any(shape == c("t","s","g"))) # triangular / symmetric / general
57        if((missing(unitri) || unitri) && shape == "t" &&
58           (mcols || cols == 0:(n-1L)) &&
59           ((any(kind == c("l", "n")) && allTrue(x)) ||
60            (    kind == "d"          && allTrue(x == 1)))) { ## uni-triangular
61            new(paste0(kind,"tCMatrix"), Dim = c(n,n),
62                       uplo = uplo, diag = "U", p = rep.int(0L, n+1L))
63        }
64        else if(kind == "n") {
65            if(shape == "g")
66                new("ngCMatrix", Dim = c(n,m), i = cols, p = 0:m)
67            else new(paste0("n", shape, "CMatrix"), Dim = c(n,m), uplo = uplo,
68                     i = cols, p = 0:m)
69        }
70        else { ## kind != "n" -- have x slot :
71            if((lx <- length(x)) == 1) x <- rep.int(x, m)
72            else if(lx != m) stop("length(x) must be either 1 or #{cols}")
73            if(shape == "g")
74                new(paste0(kind, "gCMatrix"), Dim = c(n,m),
75                    x = x, i = cols, p = 0:m)
76            else new(paste0(kind, shape, "CMatrix"), Dim = c(n,m), uplo = uplo,
77                     x = x, i = cols, p = 0:m)
78        }
79    }
80    
81  bdiag <- function(...) {  ## Pkg 'spdep' had (relatively slow) versions of this as_dsCMatrix_I()
82      if(nargs() == 0) return(new("dgCMatrix"))  .symDiagonal <- function(n, x = rep.int(1,n), uplo = "U")
83      ## else :      .sparseDiagonal(n, x, uplo, shape = "s")
84      mlist <- if (nargs() == 1) as.list(...) else list(...)  
85      dims <- sapply(mlist, dim)  # instead of   diagU2N(as(Diagonal(n), "CsparseMatrix")), diag = "N" in any case:
86    .trDiagonal <- function(n, x = 1, uplo = "U", unitri=TRUE)
87        .sparseDiagonal(n, x, uplo, shape = "t", unitri=unitri)
88    
89    
90    ## This is modified from a post of Bert Gunter to R-help on  1 Sep 2005.
91    ## Bert's code built on a post by Andy Liaw who most probably was influenced
92    ## by earlier posts, notably one by Scott Chasalow on S-news, 16 Jan 2002
93    ## who posted his bdiag() function written in December 1995.
94    if(FALSE)##--- no longer used:
95    .bdiag <- function(lst) {
96        ## block-diagonal matrix [a dgTMatrix] from list of matrices
97        stopifnot(is.list(lst), length(lst) >= 1)
98        dims <- vapply(lst, dim, 1L, USE.NAMES=FALSE)
99      ## make sure we had all matrices:      ## make sure we had all matrices:
100      if(!(is.matrix(dims) && nrow(dims) == 2))      if(!(is.matrix(dims) && nrow(dims) == 2))
101          stop("some arguments are not matrices")          stop("some arguments are not matrices")
102      csdim <- rbind(rep.int(0:0, 2),      csdim <- rbind(rep.int(0L, 2),
103                     apply(sapply(mlist, dim), 1, cumsum))                     apply(dims, 1, cumsum))
104      ret <- new("dgTMatrix", Dim = as.integer(csdim[nrow(csdim),]))      r <- new("dgTMatrix")
105        r@Dim <- as.integer(csdim[nrow(csdim),])
106      add1 <- matrix(1:0, 2,2)      add1 <- matrix(1:0, 2,2)
107      for(i in seq_along(mlist)) {      for(i in seq_along(lst)) {
108          indx <- apply(csdim[i:(i+1),] + add1, 2, function(n) n[1]:n[2])          indx <- apply(csdim[i:(i+1),] + add1, 2, function(n) n[1]:n[2])
109          if(is.null(dim(indx))) ## non-square matrix          if(is.null(dim(indx))) ## non-square matrix
110              ret[indx[[1]],indx[[2]]] <- mlist[[i]]              r[indx[[1]],indx[[2]]] <- lst[[i]]
111          else ## square matrix          else ## square matrix
112              ret[indx[,1],indx[,2]] <- mlist[[i]]              r[indx[,1], indx[,2]] <- lst[[i]]
113        }
114        r
115    }
116    ## expand(<mer>) needed something like bdiag() for lower-triangular
117    ## (Tsparse) Matrices; hence Doug Bates provided a much more efficient
118    ##  implementation for those; now extended and generalized:
119    .bdiag <- function(lst) {
120        ## block-diagonal matrix [a dgTMatrix] from list of matrices
121        stopifnot(is.list(lst), (nl <- length(lst)) >= 1)
122    
123        Tlst <- lapply(lapply(lst, as_Csp2), # includes "diagU2N"
124                       as, "TsparseMatrix")
125        if(nl == 1) return(Tlst[[1]])
126        ## else
127        i_off <- c(0L, cumsum(vapply(Tlst, nrow, 1L)))
128        j_off <- c(0L, cumsum(vapply(Tlst, ncol, 1L)))
129    
130        clss <- vapply(Tlst, class, "")
131        typ <- substr(clss, 2, 2)
132        knd <- substr(clss, 1, 1)
133        sym <- typ == "s" # symmetric ones
134        tri <- typ == "t" # triangular ones
135        use.n <- any(is.n <- knd == "n")
136        if(use.n && !(use.n <- all(is.n))) {
137            Tlst[is.n] <- lapply(Tlst[is.n], as, "lMatrix")
138            knd [is.n] <- "l"
139        }
140        use.l <- !use.n && all(knd == "l")
141        if(all(sym)) { ## result should be *symmetric*
142            uplos <- vapply(Tlst, slot, ".", "uplo") ## either "U" or "L"
143            tLU <- table(uplos)# of length 1 or 2 ..
144            if(length(tLU) == 1) { ## all "U" or all "L"
145                useU <- uplos[1] == "U"
146            } else { ## length(tLU) == 2, counting "L" and "U"
147                useU <- diff(tLU) >= 0
148                if(useU && (hasL <- tLU[1] > 0))
149                    Tlst[hasL] <- lapply(Tlst[hasL], t)
150                else if(!useU && (hasU <- tLU[2] > 0))
151                    Tlst[hasU] <- lapply(Tlst[hasU], t)
152            }
153            if(use.n) { ## return nsparseMatrix :
154                r <- new("nsTMatrix")
155            } else {
156                r <- new(paste0(if(use.l) "l" else "d", "sTMatrix"))
157                r@x <- unlist(lapply(Tlst, slot, "x"))
158            }
159            r@uplo <- if(useU) "U" else "L"
160        }
161        else if(all(tri) && { ULs <- vapply(Tlst, slot, ".", "uplo")##  "U" or "L"
162                              all(ULs[1L] == ULs[-1L]) } ## all upper or all lower
163           ){ ## *triangular* result
164    
165            if(use.n) { ## return nsparseMatrix :
166                r <- new("ntTMatrix")
167            } else {
168                r <- new(paste0(if(use.l) "l" else "d", "tTMatrix"))
169                r@x <- unlist(lapply(Tlst, slot, "x"))
170            }
171            r@uplo <- ULs[1L]
172        }
173        else {
174            if(any(sym))
175                Tlst[sym] <- lapply(Tlst[sym], as, "generalMatrix")
176            if(use.n) { ## return nsparseMatrix :
177                r <- new("ngTMatrix")
178            } else {
179                r <- new(paste0(if(use.l) "l" else "d", "gTMatrix"))
180                r@x <- unlist(lapply(Tlst, slot, "x"))
181      }      }
     ## slightly debatable if we really should return Csparse.. :  
     as(ret, "CsparseMatrix")  
182  }  }
183        r@Dim <- c(i_off[nl+1], j_off[nl + 1])
184        r@i <- unlist(lapply(1:nl, function(k) Tlst[[k]]@i + i_off[k]))
185        r@j <- unlist(lapply(1:nl, function(k) Tlst[[k]]@j + j_off[k]))
186        r
187    }
188    
189    bdiag <- function(...) {
190        if((nA <- nargs()) == 0) return(new("dgCMatrix"))
191        if(nA == 1 && !is.list(...))
192            return(as(..., "CsparseMatrix"))
193        alis <- if(nA == 1 && is.list(..1)) ..1 else list(...)
194        if(length(alis) == 1)
195            return(as(alis[[1]], "CsparseMatrix"))
196    
197  diag2T <- function(from) {      ## else : two or more arguments
198      i <- if(from@diag == "U") integer(0) else seq_len(from@Dim[1]) - 1:1      as(.bdiag(alis), "CsparseMatrix")
199      new(paste(.M.kind(from), "tTMatrix", sep=''),  }
200    
201    setMethod("tril", "diagonalMatrix", function(x, k = 0, ...)
202        if(k >= 0) x else .setZero(x, paste0(.M.kind(x), "tCMatrix")))
203    
204    setMethod("triu", "diagonalMatrix", function(x, k = 0, ...)
205        if(k <= 0) x else  .setZero(x, paste0(.M.kind(x), "tCMatrix")))
206    
207    
208    
209    .diag2tT <- function(from, uplo = "U", kind = .M.kind(from)) {
210        ## to triangular Tsparse
211        i <- if(from@diag == "U") integer(0) else seq_len(from@Dim[1]) - 1L
212        new(paste0(kind, "tTMatrix"),
213          diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,          diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,
214            uplo = uplo,
215          x = from@x, # <- ok for diag = "U" and "N" (!)          x = from@x, # <- ok for diag = "U" and "N" (!)
216          i = i, j = i)          i = i, j = i)
217  }  }
218    
219  setAs("diagonalMatrix", "triangularMatrix", diag2T)  .diag2sT <- function(from, uplo = "U", kind = .M.kind(from)) {
220  setAs("diagonalMatrix", "sparseMatrix", diag2T)      ## to symmetric Tsparse
221        n <- from@Dim[1]
222        i <- seq_len(n) - 1L
223        new(paste0(kind, "sTMatrix"),
224            Dim = from@Dim, Dimnames = from@Dimnames,
225            i = i, j = i, uplo = uplo,
226            x = if(from@diag == "N") from@x else ## "U"-diag
227            rep.int(switch(kind,
228                           "d" = 1.,
229                           "l" =,
230                           "n" = TRUE,
231                           ## otherwise
232                           stop(gettextf("%s kind not yet implemented",
233                                         sQuote(kind)), domain=NA)),
234                    n))
235    }
236    
237    ## diagonal -> triangular,  upper / lower depending on "partner" 'x':
238    diag2tT.u <- function(d, x, kind = .M.kind(d))
239        .diag2tT(d, uplo = if(is(x,"triangularMatrix")) x@uplo else "U", kind)
240    
241    ## diagonal -> sparse {triangular OR symmetric} (upper / lower) depending on "partner":
242    diag2Tsmart <- function(d, x, kind = .M.kind(d)) {
243        clx <- getClassDef(class(x))
244        if(extends(clx, "symmetricMatrix"))
245            .diag2sT(d, uplo = x@uplo, kind)
246        else
247            .diag2tT(d, uplo = if(extends(clx,"triangularMatrix")) x@uplo else "U", kind)
248    }
249    
250    ## FIXME: should not be needed {when ddi* is dsparse* etc}:
251    setMethod("is.finite", signature(x = "diagonalMatrix"),
252              function(x) is.finite(.diag2tT(x)))
253    setMethod("is.infinite", signature(x = "diagonalMatrix"),
254              function(x) is.infinite(.diag2tT(x)))
255    
256    ## In order to evade method dispatch ambiguity warnings,
257    ## and because we can save a .M.kind() call, we use this explicit
258    ## "hack"  instead of signature  x = "diagonalMatrix" :
259    ##
260    ## ddi*:
261    di2tT <- function(from) .diag2tT(from, "U", "d")
262    setAs("ddiMatrix", "triangularMatrix", di2tT)
263    ##_no_longer_ setAs("ddiMatrix", "sparseMatrix", di2tT)
264    ## needed too (otherwise <dense> -> Tsparse is taken):
265    setAs("ddiMatrix", "TsparseMatrix", di2tT)
266    setAs("ddiMatrix", "dsparseMatrix", di2tT)
267    setAs("ddiMatrix", "CsparseMatrix",
268          function(from) as(.diag2tT(from, "U", "d"), "CsparseMatrix"))
269    setAs("ddiMatrix", "symmetricMatrix", function(from) .diag2sT(from, "U", "d"))
270    ##
271    ## ldi*:
272    di2tT <- function(from) .diag2tT(from, "U", "l")
273    setAs("ldiMatrix", "triangularMatrix", di2tT)
274    ##_no_longer_ setAs("ldiMatrix", "sparseMatrix", di2tT)
275  ## needed too (otherwise <dense> -> Tsparse is taken):  ## needed too (otherwise <dense> -> Tsparse is taken):
276  setAs("diagonalMatrix", "TsparseMatrix", diag2T)  setAs("ldiMatrix", "TsparseMatrix", di2tT)
277  ## is better than this:  setAs("ldiMatrix", "lsparseMatrix", di2tT)
278  ## setAs("diagonalMatrix", "sparseMatrix",  setAs("ldiMatrix", "CsparseMatrix",
279  ##       function(from)        function(from) as(.diag2tT(from, "U", "l"), "CsparseMatrix"))
280  ##        as(from, if(is(from, "dMatrix")) "dgCMatrix" else "lgCMatrix"))  setAs("ldiMatrix", "symmetricMatrix", function(from) .diag2sT(from, "U", "l"))
281  setAs("diagonalMatrix", "CsparseMatrix",  rm(di2tT)
       function(from) as(diag2T(from), "CsparseMatrix"))  
282    
283  setAs("diagonalMatrix", "matrix",  setAs("diagonalMatrix", "nMatrix",
284        function(from) {        function(from) {
285            n <- from@Dim[1]            i <- if(from@diag == "U") integer(0) else which(isN0(from@x)) - 1L
286            diag(x = if(from@diag == "U") { if(is.numeric(from@x)) 1. else TRUE            new("ntTMatrix", i = i, j = i, diag = from@diag,
287                                       } else from@x,                Dim = from@Dim, Dimnames = from@Dimnames)
                nrow = n, ncol = n)  
288        })        })
289    
290  setAs("diagonalMatrix", "generalMatrix", # prefer sparse:  setAs("diagonalMatrix", "nsparseMatrix", function(from) as(from, "nMatrix"))
       function(from) as(from, paste(.M.kind(from), "gCMatrix", sep='')))  
291    
292  .diag.x <- function(m) {  ##' A version of diag(x,n) which *does* preserve the mode of x, where diag() "fails"
293      if(m@diag == "U")  mkDiag <- function(x, n) {
294          rep.int(if(is.numeric(m@x)) 1. else TRUE,      y <- matrix(as0(mod=mode(x)), n,n)
295                  m@Dim[1])      if (n > 0) y[1L + 0:(n - 1L) * (n + 1)] <- x
296      else m@x      y
297  }  }
298    ## NB: diag(x,n) is really faster for n >= 20, and even more for large n
299    ## --> using diag() where possible, ==> .ddi2mat()
300    
301  .diag.2N <- function(m) {  .diag2mat <- function(from)
302      if(m@diag == "U") m@diag <- "N"      ## want "ldiMatrix" -> <logical> "matrix"  (but integer -> <double> for now)
303      m      mkDiag(if(from@diag == "U") as1(from@x) else from@x, n = from@Dim[1])
304  }  
305    .ddi2mat <- function(from)
306        base::diag(if(from@diag == "U") as1(from@x) else from@x, nrow = from@Dim[1])
307    
308    setAs("ddiMatrix", "matrix", .ddi2mat)
309    ## the non-ddi diagonalMatrix -- only "ldiMatrix" currently:
310    setAs("diagonalMatrix", "matrix", .diag2mat)
311    
312    setMethod("as.vector", signature(x = "diagonalMatrix", mode="missing"),
313              function(x, mode) {
314                  n <- x@Dim[1]
315                  mod.x <- mode(x@x)
316                  r <- vector(mod.x, length = n^2)
317                  if(n)
318                      r[1 + 0:(n - 1L) * (n + 1)] <-
319                          if(x@diag == "U") as1(mod=mod.x) else x@x
320                  r
321              })
322    
323  ## given the above, the following  4  coercions should be all unneeded;  setAs("diagonalMatrix", "generalMatrix", # prefer sparse:
324  ## we prefer triangular to general:        function(from) as(as(from, "CsparseMatrix"), "generalMatrix"))
 setAs("ddiMatrix", "dgTMatrix",  
       function(from) {  
           .Deprecated("as(, \"sparseMatrix\")")  
           n <- from@Dim[1]  
           i <- seq_len(n) - 1:1  
           new("dgTMatrix", i = i, j = i, x = .diag.x(from),  
               Dim = c(n,n), Dimnames = from@Dimnames) })  
325    
326  setAs("ddiMatrix", "dgCMatrix",  setAs("diagonalMatrix", "denseMatrix",
327        function(from) as(as(from, "sparseMatrix"), "dgCMatrix"))        function(from) as(as(from, "CsparseMatrix"), "denseMatrix"))
328    
329  setAs("ldiMatrix", "lgTMatrix",  ..diag.x <- function(m)                   rep.int(as1(m@x), m@Dim[1])
330        function(from) {  .diag.x  <- function(m) if(m@diag == "U") rep.int(as1(m@x), m@Dim[1]) else m@x
           .Deprecated("as(, \"sparseMatrix\")")  
           n <- from@Dim[1]  
           if(from@diag == "U") { # unit-diagonal  
               x <- rep.int(TRUE, n)  
               i <- seq_len(n) - 1:1  
           } else { # "normal"  
               nz <- nz.NA(from@x, na. = TRUE)  
               x <- from@x[nz]  
               i <- which(nz) - 1:1  
           }  
           new("lgTMatrix", i = i, j = i, x = x,  
               Dim = c(n,n), Dimnames = from@Dimnames) })  
   
 setAs("ldiMatrix", "lgCMatrix",  
       function(from) as(as(from, "lgTMatrix"), "lgCMatrix"))  
331    
332    .diag.2N <- function(m) {
333        if(m@diag == "U") m@diag <- "N"
334        m
335    }
336    
 if(FALSE) # now have faster  "ddense" -> "dge"  
337  setAs("ddiMatrix", "dgeMatrix",  setAs("ddiMatrix", "dgeMatrix",
338        function(from) as(as(from, "matrix"), "dgeMatrix"))        function(from) .Call(dup_mMatrix_as_dgeMatrix, from))
339    setAs("ddiMatrix", "ddenseMatrix",
340          function(from) as(as(from, "triangularMatrix"),"denseMatrix"))
341    setAs("ldiMatrix", "ldenseMatrix",
342          function(from) as(as(from, "triangularMatrix"),"denseMatrix"))
343    
344    
345  setAs("matrix", "diagonalMatrix",  setAs("matrix", "diagonalMatrix",
346        function(from) {        function(from) {
347            d <- dim(from)            d <- dim(from)
348            if(d[1] != (n <- d[2])) stop("non-square matrix")            if(d[1] != (n <- d[2])) stop("non-square matrix")
349            if(any(from[row(from) != col(from)] != 0))            if(any(from[row(from) != col(from)] != 0))
350                stop("has non-zero off-diagonal entries")                stop("matrix with non-zero off-diagonals cannot be coerced to \"diagonalMatrix\"")
351            x <- diag(from)            x <- diag(from)
352            if(is.logical(x)) {            if(is.logical(x)) {
353                cl <- "ldiMatrix"                cl <- "ldiMatrix"
354                uni <- all(x)                uni <- allTrue(x) ## uni := {is it unit-diagonal ?}
355            } else {            } else {
356                cl <- "ddiMatrix"                cl <- "ddiMatrix"
357                uni <- all(x == 1)                uni <- allTrue(x == 1)
358                storage.mode(x) <- "double"                storage.mode(x) <- "double"
359            } ## TODO: complex            } ## TODO: complex
360            new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",            new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
# Line 165  Line 371 
371            x <- diag(from)            x <- diag(from)
372            if(is.logical(x)) {            if(is.logical(x)) {
373                cl <- "ldiMatrix"                cl <- "ldiMatrix"
374                uni <- all(x)                uni <- allTrue(x)
375            } else {            } else {
376                cl <- "ddiMatrix"                cl <- "ddiMatrix"
377                uni <- all(x == 1)                uni <- allTrue(x == 1)
378                storage.mode(x) <- "double"                storage.mode(x) <- "double"
379            }            } ## TODO: complex
380            new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",            new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
381                x = if(uni) x[FALSE] else x)                x = if(uni) x[FALSE] else x)
382        })        })
383    
384    
385  setMethod("diag", signature(x = "diagonalMatrix"),  setMethod("diag", signature(x = "diagonalMatrix"),
386            function(x = 1, nrow, ncol = n) .diag.x(x))            function(x = 1, nrow, ncol) .diag.x(x))
   
387    
388  subDiag <- function(x, i, j, drop) {  subDiag <- function(x, i, j, ..., drop) {
389      x <- as(x, "sparseMatrix")      x <- as(x, "CsparseMatrix") ## << was "TsparseMatrix" (Csparse is faster now)
390      x <- if(missing(i))      x <- if(missing(i))
391          x[, j, drop=drop]          x[, j, drop=drop]
392      else if(missing(j))      else if(missing(j))
393          x[i, , drop=drop]          if(nargs() == 4) x[i, , drop=drop] else x[i, drop=drop]
394      else      else
395          x[i,j, drop=drop]          x[i,j, drop=drop]
396      if(isDiagonal(x)) as(x, "diagonalMatrix") else x      if(isS4(x) && isDiagonal(x)) as(x, "diagonalMatrix") else x
397  }  }
398    
399  setMethod("[", signature(x = "diagonalMatrix", i = "index",  setMethod("[", signature(x = "diagonalMatrix", i = "index",
400                           j = "index", drop = "logical"), subDiag)                           j = "index", drop = "logical"), subDiag)
401  setMethod("[", signature(x = "diagonalMatrix", i = "index",  setMethod("[", signature(x = "diagonalMatrix", i = "index",
402                          j = "missing", drop = "logical"),                          j = "missing", drop = "logical"),
403            function(x, i, drop) subDiag(x, i=i, drop=drop))            function(x, i, j, ..., drop) {
404                  na <- nargs()
405                  Matrix.msg("diag[i,m,l] : nargs()=", na, .M.level = 2)
406                  if(na == 4)
407                       subDiag(x, i=i, , drop=drop)
408                  else subDiag(x, i=i,   drop=drop)
409              })
410  setMethod("[", signature(x = "diagonalMatrix", i = "missing",  setMethod("[", signature(x = "diagonalMatrix", i = "missing",
411                           j = "index", drop = "logical"),                           j = "index", drop = "logical"),
412            function(x, j, drop) subDiag(x, j=j, drop=drop))            function(x, i, j, ..., drop) subDiag(x, j=j, drop=drop))
413    
414  ## When you assign to a diagonalMatrix, the result should be  ## When you assign to a diagonalMatrix, the result should be
415  ## diagonal or sparse ---  ## diagonal or sparse ---
416  ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch  ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch
417  replDiag <- function(x, i, j, value) {  ## Only(?) current bug:  x[i] <- value  is wrong when  i is *vector*
418      x <- as(x, "sparseMatrix")  replDiag <- function(x, i, j, ..., value) {
419        x <- as(x, "CsparseMatrix")# was "Tsparse.." till 2012-07
420      if(missing(i))      if(missing(i))
421          x[, j] <- value          x[, j] <- value
422      else if(missing(j))      else if(missing(j)) { ##  x[i , ] <- v  *OR*   x[i] <- v
423            na <- nargs()
424    ##         message("diagnosing replDiag() -- nargs()= ", na)
425            if(na == 4)
426          x[i, ] <- value          x[i, ] <- value
427      else          else if(na == 3)
428                x[i] <- value
429            else stop(gettextf("Internal bug: nargs()=%d; please report",
430                               na), domain=NA)
431        } else
432          x[i,j] <- value          x[i,j] <- value
433      if(isDiagonal(x)) as(x, "diagonalMatrix") else x      if(isDiagonal(x)) as(x, "diagonalMatrix") else x
434  }  }
435    
436  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
437                                  j = "index", value = "replValue"), replDiag)                                  j = "index", value = "replValue"), replDiag)
438    
439  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
440                                  j = "missing", value = "replValue"),                                  j = "missing", value = "replValue"),
441                   function(x, i, value) replDiag(x, i=i, value=value))                   function(x,i,j, ..., value) {
442                         ## message("before replDiag() -- nargs()= ", nargs())
443                         if(nargs() == 3)
444                             replDiag(x, i=i, value=value)
445                         else ## nargs() == 4 :
446                             replDiag(x, i=i, , value=value)
447                     })
448    
449  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",
450                                  j = "index", value = "replValue"),                                  j = "index", value = "replValue"),
451                   function(x, j, value) replDiag(x, j=j, value=value))                   function(x,i,j, ..., value) replDiag(x, j=j, value=value))
452    
453    ## x[] <- value :
454    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",
455                                    j = "missing", value = "ANY"),
456                     function(x,i,j, ..., value)
457                 {
458                  if(all0(value)) { # be faster
459                      r <- new(paste0(.M.kindC(getClassDef(class(x))),"tTMatrix"))# of all "0"
460                      r@Dim <- x@Dim
461                      r@Dimnames <- x@Dimnames
462                      r
463                  } else { ## typically non-sense: assigning to full sparseMatrix
464                      x[TRUE] <- value
465                      x
466                  }
467              })
468    
469    
470    setReplaceMethod("[", signature(x = "diagonalMatrix",
471                                    i = "matrix", # 2-col.matrix
472                                    j = "missing", value = "replValue"),
473                     function(x,i,j, ..., value) {
474                         if(ncol(i) == 2) {
475                             if(all((ii <- i[,1]) == i[,2])) { # replace in diagonal only
476                                 if(x@diag == "U") {
477                                     one <- as1(x@x)
478                                     if(any(value != one | is.na(value))) {
479                                         x@diag <- "N"
480                                         x@x <- rep.int(one, x@Dim[1])
481                                     } else return(x)
482                                 }
483                                 x@x[ii] <- value
484                                 x
485                             } else { ## no longer diagonal, but remain sparse:
486                                 x <- as(x, "TsparseMatrix")
487                                 x[i] <- value
488                                 x
489                             }
490                         }
491                         else { # behave as "base R": use as if vector
492                             x <- as(x, "matrix")
493                             x[i] <- value
494                             Matrix(x)
495                         }
496                     })
497    
498    
499    ## value = "sparseMatrix":
500    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing", j = "index",
501                                    value = "sparseMatrix"),
502                     function (x, i, j, ..., value)
503                     callGeneric(x=x, , j=j, value = as(value, "sparseVector")))
504    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "missing",
505                                    value = "sparseMatrix"),
506                     function (x, i, j, ..., value)
507                     callGeneric(x=x, i=i, , value = as(value, "sparseVector")))
508    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "index",
509                                    value = "sparseMatrix"),
510                     function (x, i, j, ..., value)
511                     callGeneric(x=x, i=i, j=j, value = as(value, "sparseVector")))
512    
513    ## value = "sparseVector":
514    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing", j = "index",
515                                    value = "sparseVector"),
516                     replDiag)
517    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "missing",
518                                    value = "sparseVector"),
519                     replDiag)
520    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "index",
521                                    value = "sparseVector"),
522                     replDiag)
523    
524    
525  setMethod("t", signature(x = "diagonalMatrix"),  setMethod("t", signature(x = "diagonalMatrix"),
526            function(x) { x@Dimnames <- x@Dimnames[2:1] ; x })            function(x) { x@Dimnames <- x@Dimnames[2:1] ; x })
527    
528  setMethod("isDiagonal", signature(object = "diagonalMatrix"),  setMethod("isDiagonal",   "diagonalMatrix", function(object) TRUE)
529            function(object) TRUE)  setMethod("isTriangular", "diagonalMatrix", function(object, upper=NA, ...) TRUE)
530  setMethod("isTriangular", signature(object = "diagonalMatrix"),  setMethod("isSymmetric",  "diagonalMatrix", function(object, ...) TRUE)
531            function(object) TRUE)  
532  setMethod("isSymmetric", signature(object = "diagonalMatrix"),  setMethod("symmpart", signature(x = "diagonalMatrix"), function(x) x)
533            function(object) TRUE)  setMethod("skewpart", signature(x = "diagonalMatrix"), function(x) .setZero(x))
534    
535  setMethod("chol", signature(x = "ddiMatrix"),# pivot = "ANY"  setMethod("chol", signature(x = "ddiMatrix"),
536            function(x, pivot) {            function(x, pivot, ...) {
537                if(any(x@x < 0)) stop("chol() is undefined for diagonal matrix with negative entries")                if(x@diag == "U") return(x)
538                  ## else
539                  if(any(x@x < 0))
540                      stop("chol() is undefined for diagonal matrix with negative entries")
541                x@x <- sqrt(x@x)                x@x <- sqrt(x@x)
542                x                x
543            })            })
544  ## chol(L) is L for logical diagonal:  ## chol(L) is L for logical diagonal:
545  setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot) x)  setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot, ...) x)
546    
547  setMethod("!", "ldiMatrix", function(e1) {  setMethod("determinant", signature(x = "diagonalMatrix", logarithm = "logical"),
548      if(e1@diag == "N")            function(x, logarithm, ...) mkDet(.diag.x(x), logarithm))
549          e1@x <- !e1@x  
550      else { ## "U"  setMethod("norm", signature(x = "diagonalMatrix", type = "character"),
551          e1@diag <- "N"            function(x, type, ...) {
552          e1@x <- rep.int(FALSE, e1@Dim[1])                if((n <- x@Dim[1]) == 0) return(0) # as for "sparseMatrix"
553                  type <- toupper(substr(type[1], 1, 1))
554                  isU <- (x@diag == "U") # unit-diagonal
555                  if(type == "F") sqrt(if(isU) n else sum(x@x^2))
556                  else { ## norm == "I","1","O","M" :
557                      if(isU) 1 else max(abs(x@x))
558      }      }
     e1  
559  })  })
560    
561    
562    
563  ## Basic Matrix Multiplication {many more to add}  ## Basic Matrix Multiplication {many more to add}
564  ##       ---------------------  ##       ---------------------
565  ## Note that "ldi" logical are treated as numeric  ## Note that "ldi" logical are treated as numeric
566  diagdiagprod <- function(x, y) {  diagdiagprod <- function(x, y) {
567      if(any(dim(x) != dim(y))) stop("non-matching dimensions")      dimCheck(x,y)
568      if(x@diag != "U") {      if(x@diag != "U") {
569          if(y@diag != "U") {          if(y@diag != "U") {
570              nx <- x@x * y@x              nx <- x@x * y@x
# Line 284  Line 591 
591            diagdiagprod, valueClass = "ddiMatrix")            diagdiagprod, valueClass = "ddiMatrix")
592    
593    
594    ## analogous to matdiagprod() below:
595  diagmatprod <- function(x, y) {  diagmatprod <- function(x, y) {
596      dx <- dim(x)      ## x is diagonalMatrix
597      dy <- dim(y)      if(x@Dim[2] != nrow(y)) stop("non-matching dimensions")
598      if(dx[2] != dy[1]) stop("non-matching dimensions")      Matrix(if(x@diag == "U") y else x@x * y)
     n <- dx[1]  
     as(if(x@diag == "U") y else x@x * y, "Matrix")  
599  }  }
   
600  setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),  setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),
601            diagmatprod)            diagmatprod)
602    ## sneaky .. :
603  formals(diagmatprod) <- alist(x=, y=NULL)  formals(diagmatprod) <- alist(x=, y=NULL)
604  setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),  setMethod("crossprod",  signature(x = "diagonalMatrix", y = "matrix"), diagmatprod)
           diagmatprod)  
 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "matrix"),  
           diagmatprod)  
605    
606  diagdgeprod <- function(x, y) {  diagGeprod <- function(x, y) {
607      dx <- dim(x)      if(x@Dim[2] != y@Dim[1]) stop("non-matching dimensions")
     dy <- dim(y)  
     if(dx[2] != dy[1]) stop("non-matching dimensions")  
608      if(x@diag != "U")      if(x@diag != "U")
609          y@x <- x@x * y@x          y@x <- x@x * y@x
610      y      y
611  }  }
612  setMethod("%*%", signature(x = "diagonalMatrix", y = "dgeMatrix"),  setMethod("%*%", signature(x= "diagonalMatrix", y= "dgeMatrix"), diagGeprod)
613            diagdgeprod, valueClass = "dgeMatrix")  setMethod("%*%", signature(x= "diagonalMatrix", y= "lgeMatrix"), diagGeprod)
614  formals(diagdgeprod) <- alist(x=, y=NULL)  formals(diagGeprod) <- alist(x=, y=NULL)
615  setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),  setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),
616            diagdgeprod, valueClass = "dgeMatrix")            diagGeprod, valueClass = "dgeMatrix")
617    setMethod("crossprod", signature(x = "diagonalMatrix", y = "lgeMatrix"),
618              diagGeprod)
619    
620  setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),  ## analogous to diagmatprod() above:
621            function(x, y) {  matdiagprod <- function(x, y) {
622                dx <- dim(x)                dx <- dim(x)
623                dy <- dim(y)      if(dx[2] != y@Dim[1]) stop("non-matching dimensions")
624                if(dx[2] != dy[1]) stop("non-matching dimensions")      Matrix(if(y@diag == "U") x else x * rep(y@x, each = dx[1]))
625                as(if(y@diag == "U") x else x * rep(y@x, each = dx[1]), "Matrix")  }
626    setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"), matdiagprod)
627    formals(matdiagprod) <- alist(x=, y=NULL)
628    setMethod("tcrossprod",signature(x = "matrix", y = "diagonalMatrix"), matdiagprod)
629    setMethod("crossprod", signature(x = "matrix", y = "diagonalMatrix"),
630              function(x, y=NULL) {
631                  dx <- dim(x)
632                  if(dx[1] != y@Dim[1]) stop("non-matching dimensions")
633                  Matrix(t(rep.int(y@x, dx[2]) * x))
634            })            })
635    
636  setMethod("%*%", signature(x = "dgeMatrix", y = "diagonalMatrix"),  gediagprod <- function(x, y) {
           function(x, y) {  
637                dx <- dim(x)                dx <- dim(x)
638                dy <- dim(y)      if(dx[2] != y@Dim[1]) stop("non-matching dimensions")
               if(dx[2] != dy[1]) stop("non-matching dimensions")  
639                if(y@diag == "N")                if(y@diag == "N")
640                    x@x <- x@x * rep(y@x, each = dx[1])                    x@x <- x@x * rep(y@x, each = dx[1])
641                x                x
642            })  }
643    setMethod("%*%", signature(x= "dgeMatrix", y= "diagonalMatrix"), gediagprod)
644    setMethod("%*%", signature(x= "lgeMatrix", y= "diagonalMatrix"), gediagprod)
645    formals(gediagprod) <- alist(x=, y=NULL)
646    setMethod("tcrossprod", signature(x = "dgeMatrix", y = "diagonalMatrix"),
647              gediagprod)
648    setMethod("tcrossprod", signature(x = "lgeMatrix", y = "diagonalMatrix"),
649              gediagprod)
650    
651  ## crossprod {more of these}  ## crossprod {more of these}
652    
653  ## tcrossprod --- all are not yet there: do the dense ones here:  ## tcrossprod --- all are not yet there: do the dense ones here:
654    
655    setMethod("%*%", signature(x = "diagonalMatrix", y = "denseMatrix"),
656              function(x, y) if(x@diag == "U") y else x %*% as(y, "generalMatrix"))
657    setMethod("%*%", signature(x = "denseMatrix", y = "diagonalMatrix"),
658              function(x, y) if(y@diag == "U") x else as(x, "generalMatrix") %*% y)
659    
660    
661  ## FIXME:  ## FIXME:
662  ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),  ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),
663  ##        function(x, y = NULL) {  ##        function(x, y = NULL) {
664  ##           })  ##           })
665    
666  ## setMethod("tcrossprod", signature(x = "denseMatrix", y = "diagonalMatrix"),  ##' @param x CsparseMatrix
667  ##        function(x, y = NULL) {  ##' @param y diagonalMatrix
668  ##           })  ##' @return x %*% y
669    Cspdiagprod <- function(x, y) {
670        m <- ncol(x <- .Call(Csparse_diagU2N, x))
671        if(m != y@Dim[1]) stop("non-matching dimensions")
672        if(y@diag == "N") { ## otherwise: y == Diagonal(n) : multiplication is identity
673            if(!all(y@x[1L] == y@x[-1L]) && is(x, "symmetricMatrix"))
674                x <- as(x, "generalMatrix")
675            ind <- rep.int(seq_len(m), x@p[-1] - x@p[-m-1L])
676            x@x <- x@x * y@x[ind]
677            if(.hasSlot(x, "factors") && length(x@factors)) {# drop cashed ones
678                ## instead of dropping all factors, be smart about some
679                ## TODO ......
680                x@factors <- list()
681            }
682        }
683        x
684    }
685    
686    ##' @param x diagonalMatrix
687    ##' @param y CsparseMatrix
688    ##' @return x %*% y
689    diagCspprod <- function(x, y) {
690        y <- .Call(Csparse_diagU2N, y)
691        if(x@Dim[2] != y@Dim[1]) stop("non-matching dimensions")
692        if(x@diag == "N") {
693            if(!all(x@x[1L] == x@x[-1L]) && is(y, "symmetricMatrix"))
694                y <- as(y, "generalMatrix")
695            y@x <- y@x * x@x[y@i + 1L]
696            if(.hasSlot(y, "factors") && length(y@factors)) {
697         ## if(.hasSlot(y, "factors") && length(yf <- y@factors)) { ## -- TODO? --
698                ## instead of dropping all factors, be smart about some
699                ## keep <- character()
700                ## if(any(names(yf) == "LU")) { ## <- not easy: y = P'LUQ,  x y = xP'LUQ => LU ???
701                ##     keep <- "LU"
702                ## }
703                ## y@factors <- yf[keep]
704                y@factors <- list()
705            }
706        }
707        y
708    }
709    
710    setMethod("crossprod", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
711              function(x, y = NULL) diagCspprod(x, y))
712    
713  setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),  setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
714            function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })            function(x, y = NULL) diagCspprod(x, as(y, "CsparseMatrix")))
715    
716    ## Prefer calling diagCspprod to Cspdiagprod if going to transpose anyway
717    ##  x'y == (y'x)'
718    setMethod("crossprod", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
719              function(x, y = NULL) t(diagCspprod(y, x)))
720    
721  setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),  setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
722            function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })            function(x, y = NULL) t(diagCspprod(y, as(x, "Csparsematrix"))))
723    
724    setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
725              function(x, y = NULL) diagCspprod(x, t(y)))
726    
727  setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),  setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
728            function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })            function(x, y = NULL) diagCspprod(x, t(as(y, "CsparseMatrix"))))
729    
730    setMethod("tcrossprod", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
731              function(x, y = NULL) Cspdiagprod(x, y))
732    
733  setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),  setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
734            function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })            function(x, y = NULL) Cspdiagprod(as(x, "CsparseMatrix"), y))
735    
736    setMethod("%*%", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
737              function(x, y) diagCspprod(x, y))
738    
739    ## instead of "sparseMatrix", use: [RT]sparse.. ("closer" in method dispatch)
740    for(cl in c("TsparseMatrix", "RsparseMatrix")) {
741    
 ## FIXME?: In theory, this can be done *FASTER*, in some cases, via tapply1()  
742  setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),  setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),
743            function(x, y) as(x, "sparseMatrix") %*% y)            function(x, y) diagCspprod(as(x, "CsparseMatrix"), y))
 ## NB: The previous is *not* triggering for  "ddi" o "dgC" (= distance 3)  
 ##     since there's a "ddense" o "Csparse" at dist. 2 => triggers first.  
 ## ==> do this:  
 setMethod("%*%", signature(x = "diagonalMatrix", y = "CsparseMatrix"),  
           function(x, y) as(x, "CsparseMatrix") %*% y)  
 setMethod("%*%", signature(x = "CsparseMatrix", y = "diagonalMatrix"),  
           function(x, y) x %*% as(y, "CsparseMatrix"))  
 ## NB: this is *not* needed for Tsparse & Rsparse  
 ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*  
 ##       do indeed work by going through sparse (and *not* ddense)!  
744    
745  setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),  setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),
746            function(x, y) x %*% as(y, "sparseMatrix"))            function(x, y) Cspdiagprod(as(x, "CsparseMatrix"), y))
747    }
748    
749    setMethod("%*%", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
750              function(x, y) Cspdiagprod(x, y))
751    
752    ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*
753    ##       do indeed work by going through sparse (and *not* ddense)!
754    
755  setMethod("solve", signature(a = "diagonalMatrix", b = "missing"),  setMethod("solve", signature(a = "diagonalMatrix", b = "missing"),
756            function(a, b, ...) {            function(a, b, ...) {
# Line 384  Line 760 
760            })            })
761    
762  solveDiag <- function(a, b, ...) {  solveDiag <- function(a, b, ...) {
763      if((n <- a@Dim[1]) != nrow(b))      if(a@Dim[1] != nrow(b))
764          stop("incompatible matrix dimensions")          stop("incompatible matrix dimensions")
765      ## trivially invert a 'in place' and multiply:      ## trivially invert a 'in place' and multiply:
766      a@x <- 1/ a@x      a@x <- 1/ a@x
# Line 396  Line 772 
772  setMethod("solve", signature(a = "diagonalMatrix", b = "Matrix"),  setMethod("solve", signature(a = "diagonalMatrix", b = "Matrix"),
773            solveDiag)            solveDiag)
774    
775    ## Schur()  ---> ./eigen.R
776    
777    
778    
779  ### ---------------- diagonal  o  sparse  -----------------------------  ###---------------- <Ops> (<Arith>, <Logic>, <Compare> ) ----------------------
   
780    
781  ## Use function for several signatures, in order to evade  ## Use function for several signatures, in order to evade
782  ## ambiguous dispatch for "ddi", since there's also Arith(ddense., ddense.)  diagOdiag <- function(e1,e2) {
783  diagOdiag <- function(e1,e2) { # result should also be diagonal      ## result should also be diagonal _ if possible _
784      r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"      r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"
785      if(is.numeric(r)) {      ## Check what happens with non-diagonals, i.e. (0 o 0), (FALSE o 0), ...:
786        r00 <- callGeneric(if(is.numeric(e1@x)) 0 else FALSE,
787                           if(is.numeric(e2@x)) 0 else FALSE)
788        if(is0(r00)) { ##  r00 == 0 or FALSE --- result *is* diagonal
789            if(is.numeric(r)) { # "double" *or* "integer"
790          if(is.numeric(e2@x)) {          if(is.numeric(e2@x)) {
791              e2@x <- r; return(.diag.2N(e2)) }              e2@x <- r; return(.diag.2N(e2)) }
792          if(!is.numeric(e1@x))          if(!is.numeric(e1@x))
793              ## e.g. e1, e2 are logical;              ## e.g. e1, e2 are logical;
794              e1 <- as(e1, "dMatrix")              e1 <- as(e1, "dMatrix")
795                if(!is.double(r)) r <- as.double(r)
796      }      }
797      else if(is.logical(r))      else if(is.logical(r))
798          e1 <- as(e1, "lMatrix")          e1 <- as(e1, "lMatrix")
799      else stop("intermediate 'r' is of type", typeof(r))          else stop(gettextf("intermediate 'r' is of type %s",
800                               typeof(r)), domain=NA)
801      e1@x <- r      e1@x <- r
802      .diag.2N(e1)      .diag.2N(e1)
803  }  }
804        else { ## result not diagonal, but at least symmetric:
805            ## e.g., m == m
806            isNum <- (is.numeric(r) || is.numeric(r00))
807            isLog <- (is.logical(r) || is.logical(r00))
808            Matrix.msg("exploding <diag> o <diag> into dense matrix", .M.level = 2)
809            d <- e1@Dim
810            n <- d[1]
811            stopifnot(length(r) == n)
812            if(isNum && !is.double(r)) r <- as.double(r)
813            xx <- as.vector(matrix(rbind(r, matrix(r00,n,n)), n,n))
814            newcl <-
815                paste0(if(isNum) "d" else if(isLog) {
816                    if(!any(is.na(r)) && !any(is.na(r00))) "n" else "l"
817                } else stop("not yet implemented .. please report"), "syMatrix")
818    
819            new(newcl, Dim = e1@Dim, Dimnames = e1@Dimnames, x = xx)
820        }
821    }
822    
823    ### This would be *the* way, but we get tons of "ambiguous method dispatch"
824    ## we use this hack instead of signature  x = "diagonalMatrix" :
825    diCls <- names(getClass("diagonalMatrix")@subclasses)
826    if(FALSE) {
827  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),
828            diagOdiag)            diagOdiag)
829  ## These two are just for method disambiguation:  } else { ## These are just for method disambiguation:
830  setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "diagonalMatrix"),      for(c1 in diCls)
831            diagOdiag)          for(c2 in diCls)
832  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ddiMatrix"),              setMethod("Ops", signature(e1 = c1, e2 = c2), diagOdiag)
833            diagOdiag)  }
834    
835    ## diagonal  o  triangular  |-->  triangular
836    ## diagonal  o  symmetric   |-->  symmetric
837    ##    {also when other is sparse: do these "here" --
838    ##     before conversion to sparse, since that loses "diagonality"}
839    diagOtri <- function(e1,e2) {
840        ## result must be triangular
841        r <- callGeneric(d1 <- .diag.x(e1), diag(e2)) # error if not "compatible"
842        ## Check what happens with non-diagonals, i.e. (0 o 0), (FALSE o 0), ...:
843        e1.0 <- if(is.numeric(d1)) 0 else FALSE
844        r00 <- callGeneric(e1.0, if(.n2 <- is.numeric(e2[0])) 0 else FALSE)
845        if(is0(r00)) { ##  r00 == 0 or FALSE --- result *is* triangular
846            diag(e2) <- r
847            ## check what happens "in the triangle"
848            e2.2 <- if(.n2) 2 else TRUE
849            if(!callGeneric(e1.0, e2.2) == e2.2) { # values "in triangle" can change:
850                n <- dim(e2)[1L]
851                it <- indTri(n, upper = (e2@uplo == "U"))
852                e2[it] <- callGeneric(e1.0, e2[it])
853            }
854            e2
855        }
856        else { ## result not triangular ---> general
857            rr <- as(e2, "generalMatrix")
858            diag(rr) <- r
859            rr
860        }
861    }
862    
863    
864    setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "triangularMatrix"),
865              diagOtri)
866    ## For the reverse,  Ops == "Arith" | "Compare" | "Logic"
867    ##   'Arith'  :=  '"+"', '"-"', '"*"', '"^"', '"%%"', '"%/%"', '"/"'
868    setMethod("Arith", signature(e1 = "triangularMatrix", e2 = "diagonalMatrix"),
869              function(e1,e2)
870          { ## this must only trigger for *dense* e1
871              switch(.Generic,
872                     "+" = .Call(dtrMatrix_addDiag, as(e1,"dtrMatrix"),   .diag.x(e2)),
873                     "-" = .Call(dtrMatrix_addDiag, as(e1,"dtrMatrix"), - .diag.x(e2)),
874                     "*" = {
875                         n <- e2@Dim[1L]
876                         d2 <- if(e2@diag == "U") { # unit-diagonal
877                             d <- rep.int(as1(e2@x), n)
878                             e2@x <- d
879                             e2@diag <- "N"
880                             d
881                         } else e2@x
882                         e2@x <- diag(e1) * d2
883                         e2
884                     },
885                     "^" = { ## will be dense ( as  <ANY> ^ 0 == 1 ):
886                         e1 ^ as(e2, "denseMatrix")
887                     },
888                     ## otherwise:
889                     callGeneric(e1, diag2Tsmart(e2,e1)))
890    })
891    
892    ## Compare --> 'swap' (e.g.   e1 < e2   <==>  e2 > e1 ):
893    setMethod("Compare", signature(e1 = "triangularMatrix", e2 = "diagonalMatrix"),
894              .Cmp.swap)
895    ## '&' and "|'  are commutative:
896    setMethod("Logic", signature(e1 = "triangularMatrix", e2 = "diagonalMatrix"),
897              function(e1,e2) callGeneric(e2, e1))
898    
899  ## For almost everything else, diag* shall be treated "as sparse" :  ## For almost everything else, diag* shall be treated "as sparse" :
900  ## These are cheap implementations via coercion  ## These are cheap implementations via coercion
901    
902  ## for disambiguation  ## For disambiguation --- define this for "sparseMatrix" , then for "ANY";
903  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "sparseMatrix"),  ## and because we can save an .M.kind() call, we use this explicit
904            function(e1,e2) callGeneric(as(e1, "sparseMatrix"), e2))  ## "hack" for all diagonalMatrix *subclasses* instead of just "diagonalMatrix" :
905  setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "diagonalMatrix"),  ##
906            function(e1,e2) callGeneric(e1, as(e2, "sparseMatrix")))  ## ddi*:
907  ## in general:  setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "sparseMatrix"),
908  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ANY"),            function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2))
909            function(e1,e2) callGeneric(as(e1,"sparseMatrix"), e2))  setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ddiMatrix"),
910  setMethod("Ops", signature(e1 = "ANY", e2 = "diagonalMatrix"),            function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "d")))
911            function(e1,e2) callGeneric(e1, as(e2,"sparseMatrix")))  ## ldi*
912    setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "sparseMatrix"),
913              function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2))
914    setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ldiMatrix"),
915              function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "l")))
916    
917    ## Ops:  Arith  --> numeric : "dMatrix"
918    ##       Compare --> logical
919    ##       Logic   --> logical: "lMatrix"
920    
921    ## Other = "numeric" : stay diagonal if possible
922    ## ddi*: Arith: result numeric, potentially ddiMatrix
923    for(arg2 in c("numeric","logical"))
924    setMethod("Arith", signature(e1 = "ddiMatrix", e2 = arg2),
925              function(e1,e2) {
926                  n <- e1@Dim[1]
927                  f0 <- callGeneric(0, e2)
928                  if(all0(f0)) { # remain diagonal
929                      L1 <- (le <- length(e2)) == 1L
930                      if(e1@diag == "U") {
931                          if(any((r <- callGeneric(1, e2)) != 1)) {
932                              e1@diag <- "N"
933                              e1@x[seq_len(n)] <- r # possibly recycling r
934                          } ## else: result = e1  (is "U" diag)
935                      } else {
936                          r <- callGeneric(e1@x, e2)
937                          ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
938                          e1@x[] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
939                      }
940                      e1
941                  } else
942                      callGeneric(diag2tT.u(e1,e2, "d"), e2)
943              })
944    
945    for(arg1 in c("numeric","logical"))
946    setMethod("Arith", signature(e1 = arg1, e2 = "ddiMatrix"),
947              function(e1,e2) {
948                  n <- e2@Dim[1]
949                  f0 <- callGeneric(e1, 0)
950                  if(all0(f0)) { # remain diagonal
951                      L1 <- (le <- length(e1)) == 1L
952                      if(e2@diag == "U") {
953                          if(any((r <- callGeneric(e1, 1)) != 1)) {
954                              e2@diag <- "N"
955                              e2@x[seq_len(n)] <- r # possibly recycling r
956                          } ## else: result = e2  (is "U" diag)
957                      } else {
958                          r <- callGeneric(e1, e2@x)
959                          ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
960                          e2@x[] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
961                      }
962                      e2
963                  } else
964                      callGeneric(e1, diag2tT.u(e2,e1, "d"))
965              })
966    
967    ## ldi* Arith --> result numeric, potentially ddiMatrix
968    for(arg2 in c("numeric","logical"))
969    setMethod("Arith", signature(e1 = "ldiMatrix", e2 = arg2),
970              function(e1,e2) {
971                  n <- e1@Dim[1]
972                  f0 <- callGeneric(0, e2)
973                  if(all0(f0)) { # remain diagonal
974                      L1 <- (le <- length(e2)) == 1L
975                      E <- copyClass(e1, "ddiMatrix", c("diag", "Dim", "Dimnames"), check=FALSE)
976                      ## storage.mode(E@x) <- "double"
977                      if(e1@diag == "U") {
978                          if(any((r <- callGeneric(1, e2)) != 1)) {
979                              E@diag <- "N"
980                              E@x[seq_len(n)] <- r # possibly recycling r
981                          } ## else: result = E  (is "U" diag)
982                      } else {
983                          r <- callGeneric(e1@x, e2)
984                          ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
985                          E@x[seq_len(n)] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
986                      }
987                      E
988                  } else
989                      callGeneric(diag2tT.u(e1,e2, "l"), e2)
990              })
991    
992    for(arg1 in c("numeric","logical"))
993    setMethod("Arith", signature(e1 = arg1, e2 = "ldiMatrix"),
994              function(e1,e2) {
995                  n <- e2@Dim[1]
996                  f0 <- callGeneric(e1, 0)
997                  if(all0(f0)) { # remain diagonal
998                      L1 <- (le <- length(e1)) == 1L
999                      E <- copyClass(e2, "ddiMatrix", c("diag", "Dim", "Dimnames"), check=FALSE)
1000                      ## storage.mode(E@x) <- "double"
1001                      if(e2@diag == "U") {
1002                          if(any((r <- callGeneric(e1, 1)) != 1)) {
1003                              E@diag <- "N"
1004                              E@x[seq_len(n)] <- r # possibly recycling r
1005                          } ## else: result = E  (is "U" diag)
1006                      } else {
1007                          r <- callGeneric(e1, e2@x)
1008                          ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
1009                          E@x[seq_len(n)] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
1010                      }
1011                      E
1012                  } else
1013                      callGeneric(e1, diag2tT.u(e2,e1, "l"))
1014              })
1015    
1016    ## ddi*: for "Ops" without "Arith": <Compare> or <Logic> --> result logical, potentially ldi
1017    ##
1018    ## Note that  ("numeric", "ddiMatrix")  is simply swapped, e.g.,
1019    if(FALSE) {
1020        selectMethod("<", c("numeric","lMatrix"))# Compare
1021        selectMethod("&", c("numeric","lMatrix"))# Logic
1022    } ## so we don't need to define a method here :
1023    
1024    for(arg2 in c("numeric","logical"))
1025    setMethod("Ops", signature(e1 = "ddiMatrix", e2 = arg2),
1026              function(e1,e2) {
1027                  n <- e1@Dim[1]
1028                  f0 <- callGeneric(0, e2)
1029                  if(all0(f0)) { # remain diagonal
1030                      L1 <- (le <- length(e2)) == 1L
1031                      E <- copyClass(e1, "ldiMatrix", c("diag", "Dim", "Dimnames"), check=FALSE)
1032                      ## storage.mode(E@x) <- "logical"
1033                      if(e1@diag == "U") {
1034                          if(any((r <- callGeneric(1, e2)) != 1)) {
1035                              E@diag <- "N"
1036                              E@x[seq_len(n)] <- r # possibly recycling r
1037                          } ## else: result = E  (is "U" diag)
1038                      } else {
1039                          r <- callGeneric(e1@x, e2)
1040                          ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
1041                          E@x[seq_len(n)] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
1042                      }
1043                      E
1044                  } else
1045                      callGeneric(diag2tT.u(e1,e2, "d"), e2)
1046              })
1047    
1048    ## ldi*: for "Ops" without "Arith": <Compare> or <Logic> --> result logical, potentially ldi
1049    for(arg2 in c("numeric","logical"))
1050    setMethod("Ops", signature(e1 = "ldiMatrix", e2 = arg2),
1051              function(e1,e2) {
1052                  n <- e1@Dim[1]
1053                  f0 <- callGeneric(FALSE, e2)
1054                  if(all0(f0)) { # remain diagonal
1055                      L1 <- (le <- length(e2)) == 1L
1056    
1057                      if(e1@diag == "U") {
1058                          if(any((r <- callGeneric(TRUE, e2)) != 1)) {
1059                              e1@diag <- "N"
1060                              e1@x[seq_len(n)] <- r # possibly recycling r
1061                          } ## else: result = e1  (is "U" diag)
1062                      } else {
1063                          r <- callGeneric(e1@x, e2)
1064                          ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
1065                          e1@x[] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
1066                      }
1067                      e1
1068                  } else
1069                      callGeneric(diag2tT.u(e1,e2, "l"), e2)
1070              })
1071    
1072    
1073    ## Not {"sparseMatrix", "numeric} :  {"denseMatrix", "matrix", ... }
1074    for(other in c("ANY", "Matrix", "dMatrix")) {
1075        ## ddi*:
1076        setMethod("Ops", signature(e1 = "ddiMatrix", e2 = other),
1077                  function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2))
1078        setMethod("Ops", signature(e1 = other, e2 = "ddiMatrix"),
1079                  function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "d")))
1080        ## ldi*:
1081        setMethod("Ops", signature(e1 = "ldiMatrix", e2 = other),
1082                  function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2))
1083        setMethod("Ops", signature(e1 = other, e2 = "ldiMatrix"),
1084                  function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "l")))
1085    }
1086    
1087    ## Direct subclasses of "denseMatrix": currently ddenseMatrix, ldense... :
1088    dense.subCl <- local({ dM.scl <- getClass("denseMatrix")@subclasses
1089                           names(dM.scl)[vapply(dM.scl, slot, 0, "distance") == 1] })
1090    for(DI in diCls) {
1091        dMeth <- if(extends(DI, "dMatrix"))
1092            function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2)
1093        else # "lMatrix", the only other kind for now
1094            function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2)
1095        for(c2 in c(dense.subCl, "Matrix")) {
1096            for(Fun in c("*", "&")) {
1097                setMethod(Fun, signature(e1 = DI, e2 = c2),
1098                          function(e1,e2) callGeneric(e1, Diagonal(x = diag(e2))))
1099                setMethod(Fun, signature(e1 = c2, e2 = DI),
1100                          function(e1,e2) callGeneric(Diagonal(x = diag(e1)), e2))
1101            }
1102            setMethod("^", signature(e1 = c2, e2 = DI),
1103                      function(e1,e2) callGeneric(Diagonal(x = diag(e1)), e2))
1104            for(Fun in c("%%", "%/%", "/")) ## 0 <op> 0 |--> NaN  for these.
1105                setMethod(Fun, signature(e1 = DI, e2 = c2), dMeth)
1106        }
1107    }
1108    
1109    ## Group methods "Math", "Math2" in                     --> ./Math.R
1110    
1111    ### "Summary" : "max"   "min"   "range" "prod"  "sum"   "any"   "all"
1112    ### ----------   the last 4: separately here
1113    for(cl in diCls) {
1114    setMethod("any", cl,
1115              function (x, ..., na.rm) {
1116                  if(any(x@Dim == 0)) FALSE
1117                  else if(x@diag == "U") TRUE else any(x@x, ..., na.rm = na.rm)
1118              })
1119    setMethod("all",  cl, function (x, ..., na.rm) {
1120        n <- x@Dim[1]
1121        if(n >= 2) FALSE
1122        else if(n == 0 || x@diag == "U") TRUE
1123        else all(x@x, ..., na.rm = na.rm)
1124    })
1125    setMethod("prod", cl, function (x, ..., na.rm) {
1126        n <- x@Dim[1]
1127        if(n >= 2) 0
1128        else if(n == 0 || x@diag == "U") 1
1129        else ## n == 1, diag = "N" :
1130            prod(x@x, ..., na.rm = na.rm)
1131    })
1132    
1133    setMethod("sum", cl,
1134              function(x, ..., na.rm) {
1135                  r <- sum(x@x, ..., na.rm = na.rm)# double or integer, correctly
1136                  if(x@diag == "U" && !is.na(r)) r + x@Dim[1] else r
1137              })
1138    }
1139    
1140    ## The remaining ones are  max, min, range :
1141    
1142    setMethod("Summary", "ddiMatrix",
1143              function(x, ..., na.rm) {
1144                  if(any(x@Dim == 0)) callGeneric(numeric(0), ..., na.rm=na.rm)
1145                  else if(x@diag == "U")
1146                      callGeneric(x@x, 0, 1, ..., na.rm=na.rm)
1147                  else callGeneric(x@x, 0, ..., na.rm=na.rm)
1148              })
1149    setMethod("Summary", "ldiMatrix",
1150              function(x, ..., na.rm) {
1151                  if(any(x@Dim == 0)) callGeneric(logical(0), ..., na.rm=na.rm)
1152                  else if(x@diag == "U")
1153                      callGeneric(x@x, FALSE, TRUE, ..., na.rm=na.rm)
1154                  else callGeneric(x@x, FALSE, ..., na.rm=na.rm)
1155              })
1156    
1157    
1158    
# Line 455  Line 1167 
1167      invisible(x)      invisible(x)
1168  }  }
1169    
1170    ## somewhat consistent with "print" for sparseMatrix :
1171    setMethod("print", signature(x = "diagonalMatrix"), prDiag)
1172    
1173  setMethod("show", signature(object = "diagonalMatrix"),  setMethod("show", signature(object = "diagonalMatrix"),
1174            function(object) {            function(object) {
1175                d <- dim(object)                d <- dim(object)
1176                cl <- class(object)                cl <- class(object)
1177                cat(sprintf('%d x %d diagonal matrix of class "%s"\n',                cat(sprintf('%d x %d diagonal matrix of class "%s"',
1178                            d[1], d[2], cl))                            d[1], d[2], cl))
1179                  if(d[1] < 50) {
1180                      cat("\n")
1181                prDiag(object)                prDiag(object)
1182                  } else {
1183                      cat(", with diagonal entries\n")
1184                      show(diag(object))
1185                      invisible(object)
1186                  }
1187            })            })
1188    
1189    rm(arg1, arg2, other, DI, Fun, cl, c1, c2,
1190       dense.subCl, diCls)# not used elsewhere
1191    
1192    setMethod("summary", signature(object = "diagonalMatrix"),
1193              function(object, ...) {
1194                  d <- dim(object)
1195                  r <- summary(object@x, ...)
1196                  attr(r, "header") <-
1197                      sprintf('%d x %d diagonal Matrix of class "%s"',
1198                              d[1], d[2], class(object))
1199                  ## use ole' S3 technology for such a simple case
1200                  class(r) <- c("diagSummary", class(r))
1201                  r
1202              })
1203    
1204    print.diagSummary <- function (x, ...) {
1205        cat(attr(x, "header"),"\n")
1206        class(x) <- class(x)[-1]
1207        print(x, ...)
1208        invisible(x)
1209    }

Legend:
Removed from v.1805  
changed lines
  Added in v.3046

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge