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

revision 1805, Tue Mar 27 16:46:03 2007 UTC revision 2183, Thu Apr 24 10:58:51 2008 UTC
# Line 16  Line 16 
16      if(missing(x)) ## unit diagonal matrix      if(missing(x)) ## unit diagonal matrix
17          new("ddiMatrix", Dim = c(n,n), diag = "U")          new("ddiMatrix", Dim = c(n,n), diag = "U")
18      else {      else {
19          stopifnot(length(x) == n)          lx <- length(x)
20            stopifnot(lx == 1 || lx == n) # but keep 'x' short for now
21          if(is.logical(x))          if(is.logical(x))
22              cl <- "ldiMatrix"              cl <- "ldiMatrix"
23          else if(is.numeric(x)) {          else if(is.numeric(x)) {
# Line 26  Line 27 
27          else if(is.complex(x)) {          else if(is.complex(x)) {
28              cl <- "zdiMatrix"  # will not yet work              cl <- "zdiMatrix"  # will not yet work
29          } else stop("'x' has invalid data type")          } else stop("'x' has invalid data type")
30          new(cl, Dim = c(n,n), diag = "N", x = x)          new(cl, Dim = c(n,n), diag = "N",
31                x = if(lx == 1) rep.int(x,n) else x)
32      }      }
33  }  }
34    
35    ## Pkg 'spdep' had (relatively slow) versions of this as_dsCMatrix_I()
36    .symDiagonal <- function(n, x = rep.int(1,n), uplo = "U") {
37        stopifnot(n == (n. <- as.integer(n)), (n <- n.) >= 0)
38        if((lx <- length(x)) == 1) x <- rep.int(x, n)
39        else if(lx != n) stop("length(x) must be 1 or n")
40        cls <-
41            if(is.double(x)) "dsCMatrix"
42            else if(is.logical(x)) "lsCMatrix"
43            else { ## for now
44                storage.mode(x) <- "double"
45                "dsCMatrix"
46            }
47        new(cls, Dim = c(n,n), x = x, uplo = uplo,
48            i = if(n) 0:(n - 1L) else integer(0), p = 0:n)
49    }
50    
51  ### This is modified from a post of Bert Gunter to R-help on  1 Sep 2005.  ### This is modified from a post of Bert Gunter to R-help on  1 Sep 2005.
52  ### Bert's code built on a post by Andy Liaw who most probably was influenced  ### Bert's code built on a post by Andy Liaw who most probably was influenced
53  ### by earlier posts, notably one by Scott Chasalow on S-news, 16 Jan 2002  ### by earlier posts, notably one by Scott Chasalow on S-news, 16 Jan 2002
# Line 43  Line 61 
61      ## make sure we had all matrices:      ## make sure we had all matrices:
62      if(!(is.matrix(dims) && nrow(dims) == 2))      if(!(is.matrix(dims) && nrow(dims) == 2))
63          stop("some arguments are not matrices")          stop("some arguments are not matrices")
64      csdim <- rbind(rep.int(0:0, 2),      csdim <- rbind(rep.int(0L, 2),
65                     apply(sapply(mlist, dim), 1, cumsum))                     apply(sapply(mlist, dim), 1, cumsum))
66      ret <- new("dgTMatrix", Dim = as.integer(csdim[nrow(csdim),]))      ret <- new("dgTMatrix", Dim = as.integer(csdim[nrow(csdim),]))
67      add1 <- matrix(1:0, 2,2)      add1 <- matrix(1:0, 2,2)
# Line 58  Line 76 
76      as(ret, "CsparseMatrix")      as(ret, "CsparseMatrix")
77  }  }
78    
79  diag2T <- function(from) {  
80      i <- if(from@diag == "U") integer(0) else seq_len(from@Dim[1]) - 1:1  .diag2tT <- function(from, uplo = "U", kind = .M.kind(from)) {
81      new(paste(.M.kind(from), "tTMatrix", sep=''),      ## to triangular Tsparse
82        i <- if(from@diag == "U") integer(0) else seq_len(from@Dim[1]) - 1L
83        new(paste(kind, "tTMatrix", sep=''),
84          diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,          diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,
85            uplo = uplo,
86          x = from@x, # <- ok for diag = "U" and "N" (!)          x = from@x, # <- ok for diag = "U" and "N" (!)
87          i = i, j = i)          i = i, j = i)
88  }  }
89    
90  setAs("diagonalMatrix", "triangularMatrix", diag2T)  .diag2sT <- function(from, uplo = "U", kind = .M.kind(from)) {
91  setAs("diagonalMatrix", "sparseMatrix", diag2T)      ## to symmetric Tsparse
92        n <- from@Dim[1]
93        i <- seq_len(n) - 1L
94        new(paste(kind, "sTMatrix", sep=''),
95            Dim = from@Dim, Dimnames = from@Dimnames,
96            i = i, j = i, uplo = uplo,
97            x = if(from@diag == "N") from@x else ## "U"-diag
98            rep.int(switch(kind,
99                           "d" = 1.,
100                           "l" =,
101                           "n" = TRUE,
102                           ## otherwise
103                           stop("'", kind,"' kind not yet implemented")), n))
104    }
105    
106    ## diagonal -> triangular,  upper / lower depending on "partner":
107    diag2tT.u <- function(d, x, kind = .M.kind(d))
108        .diag2tT(d, uplo = if(is(x,"triangularMatrix")) x@uplo else "U", kind)
109    
110    ## diagonal -> sparse {triangular OR symmetric} (upper / lower) depending on "partner":
111    diag2Tsmart <- function(d, x, kind = .M.kind(d)) {
112        clx <- getClassDef(class(x))
113        if(extends(clx, "symmetricMatrix"))
114            .diag2sT(d, uplo = x@uplo, kind)
115        else
116            .diag2tT(d, uplo = if(extends(clx,"triangularMatrix")) x@uplo else "U", kind)
117    }
118    
119    
120    ## In order to evade method dispatch ambiguity warnings,
121    ## and because we can save a .M.kind() call, we use this explicit
122    ## "hack"  instead of signature  x = "diagonalMatrix" :
123    ##
124    ## ddi*:
125    diag2tT <- function(from) .diag2tT(from, "U", "d")
126    setAs("ddiMatrix", "triangularMatrix", diag2tT)
127    setAs("ddiMatrix", "sparseMatrix", diag2tT)
128    ## needed too (otherwise <dense> -> Tsparse is taken):
129    setAs("ddiMatrix", "TsparseMatrix", diag2tT)
130    setAs("ddiMatrix", "CsparseMatrix",
131          function(from) as(.diag2tT(from, "U", "d"), "CsparseMatrix"))
132    setAs("ddiMatrix", "symmetricMatrix",
133          function(from) .diag2sT(from, "U", "d"))
134    ##
135    ## ldi*:
136    diag2tT <- function(from) .diag2tT(from, "U", "l")
137    setAs("ldiMatrix", "triangularMatrix", diag2tT)
138    setAs("ldiMatrix", "sparseMatrix", diag2tT)
139  ## needed too (otherwise <dense> -> Tsparse is taken):  ## needed too (otherwise <dense> -> Tsparse is taken):
140  setAs("diagonalMatrix", "TsparseMatrix", diag2T)  setAs("ldiMatrix", "TsparseMatrix", diag2tT)
141  ## is better than this:  setAs("ldiMatrix", "CsparseMatrix",
142  ## setAs("diagonalMatrix", "sparseMatrix",        function(from) as(.diag2tT(from, "U", "l"), "CsparseMatrix"))
143  ##       function(from)  setAs("ldiMatrix", "symmetricMatrix",
144  ##        as(from, if(is(from, "dMatrix")) "dgCMatrix" else "lgCMatrix"))        function(from) .diag2sT(from, "U", "l"))
 setAs("diagonalMatrix", "CsparseMatrix",  
       function(from) as(diag2T(from), "CsparseMatrix"))  
145    
146  setAs("diagonalMatrix", "matrix",  
147    setAs("diagonalMatrix", "nMatrix",
148        function(from) {        function(from) {
149            n <- from@Dim[1]            n <- from@Dim[1]
150            diag(x = if(from@diag == "U") { if(is.numeric(from@x)) 1. else TRUE            i <- if(from@diag == "U") integer(0) else which(isN0(from@x)) - 1L
151                                       } else from@x,            new("ntTMatrix", i = i, j = i, diag = from@diag,
152                 nrow = n, ncol = n)                Dim = from@Dim, Dimnames = from@Dimnames)
153          })
154    
155    
156    ## Cheap fast substitute for diag() which *does* preserve the mode of x :
157    mkDiag <- function(x, n) {
158        y <- matrix(as0(mod=mode(x)), n,n)
159        if (n > 0) y[1L + 0:(n - 1L) * (n + 1L)] <- x
160        y
161    }
162    
163    setAs("diagonalMatrix", "matrix",
164          function(from) {
165              ## want "ldiMatrix" -> <logical> "matrix" :
166              mkDiag(if(from@diag == "U") as1(from@x) else from@x,
167                     n = from@Dim[1])
168          })
169    
170    setMethod("as.vector", signature(x = "diagonalMatrix", mode="missing"),
171              function(x, mode) {
172                  n <- x@Dim[1]
173                  mod.x <- mode(x@x)
174                  r <- vector(mod.x, length = n^2)
175                  if(n)
176                      r[1 + 0:(n - 1) * (n + 1)] <-
177                          if(x@diag == "U") as1(mod=mod.x) else x@x
178                  r
179        })        })
180    
181  setAs("diagonalMatrix", "generalMatrix", # prefer sparse:  setAs("diagonalMatrix", "generalMatrix", # prefer sparse:
182        function(from) as(from, paste(.M.kind(from), "gCMatrix", sep='')))        function(from) as(as(from, "CsparseMatrix"), "generalMatrix"))
183    
184  .diag.x <- function(m) {  .diag.x <- function(m) {
185      if(m@diag == "U")      if(m@diag == "U")
186          rep.int(if(is.numeric(m@x)) 1. else TRUE,          rep.int(if(is.numeric(m@x)) 1. else TRUE, m@Dim[1])
                 m@Dim[1])  
187      else m@x      else m@x
188  }  }
189    
# Line 100  Line 192 
192      m      m
193  }  }
194    
195    if(FALSE) {
196  ## given the above, the following  4  coercions should be all unneeded;  ## given the above, the following  4  coercions should be all unneeded;
197  ## we prefer triangular to general:  ## we prefer triangular to general:
198  setAs("ddiMatrix", "dgTMatrix",  setAs("ddiMatrix", "dgTMatrix",
199        function(from) {        function(from) {
200            .Deprecated("as(, \"sparseMatrix\")")            .Deprecated("as(, \"sparseMatrix\")")
201            n <- from@Dim[1]            n <- from@Dim[1]
202            i <- seq_len(n) - 1:1            i <- seq_len(n) - 1L
203            new("dgTMatrix", i = i, j = i, x = .diag.x(from),            new("dgTMatrix", i = i, j = i, x = .diag.x(from),
204                Dim = c(n,n), Dimnames = from@Dimnames) })                Dim = c(n,n), Dimnames = from@Dimnames) })
205    
# Line 119  Line 212 
212            n <- from@Dim[1]            n <- from@Dim[1]
213            if(from@diag == "U") { # unit-diagonal            if(from@diag == "U") { # unit-diagonal
214                x <- rep.int(TRUE, n)                x <- rep.int(TRUE, n)
215                i <- seq_len(n) - 1:1                i <- seq_len(n) - 1L
216            } else { # "normal"            } else { # "normal"
217                nz <- nz.NA(from@x, na. = TRUE)                nz <- nz.NA(from@x, na. = TRUE)
218                x <- from@x[nz]                x <- from@x[nz]
219                i <- which(nz) - 1:1                i <- which(nz) - 1L
220            }            }
221            new("lgTMatrix", i = i, j = i, x = x,            new("lgTMatrix", i = i, j = i, x = x,
222                Dim = c(n,n), Dimnames = from@Dimnames) })                Dim = c(n,n), Dimnames = from@Dimnames) })
223    
224  setAs("ldiMatrix", "lgCMatrix",  setAs("ldiMatrix", "lgCMatrix",
225        function(from) as(as(from, "lgTMatrix"), "lgCMatrix"))        function(from) as(as(from, "lgTMatrix"), "lgCMatrix"))
226    }##{unused}
227    
   
 if(FALSE) # now have faster  "ddense" -> "dge"  
228  setAs("ddiMatrix", "dgeMatrix",  setAs("ddiMatrix", "dgeMatrix",
229        function(from) as(as(from, "matrix"), "dgeMatrix"))        function(from) .Call(dup_mMatrix_as_dgeMatrix, from))
230    setAs("ddiMatrix", "ddenseMatrix",
231          function(from) as(as(from, "triangularMatrix"),"denseMatrix"))
232    setAs("ldiMatrix", "ldenseMatrix",
233          function(from) as(as(from, "triangularMatrix"),"denseMatrix"))
234    
235    
236  setAs("matrix", "diagonalMatrix",  setAs("matrix", "diagonalMatrix",
237        function(from) {        function(from) {
# Line 176  Line 273 
273        })        })
274    
275    
276  setMethod("diag", signature(x = "diagonalMatrix"),  ## In order to evade method dispatch ambiguity warnings,
277            function(x = 1, nrow, ncol = n) .diag.x(x))  ## we use this hack instead of signature  x = "diagonalMatrix" :
278    diCls <- names(getClass("diagonalMatrix")@subclasses)
279    for(cls in diCls) {
280        setMethod("diag", signature(x = cls),
281                  function(x = 1, nrow, ncol) .diag.x(x))
282    }
283    
284    
285  subDiag <- function(x, i, j, drop) {  subDiag <- function(x, i, j, ..., drop) {
286      x <- as(x, "sparseMatrix")      x <- as(x, "sparseMatrix")
287      x <- if(missing(i))      x <- if(missing(i))
288          x[, j, drop=drop]          x[, j, drop=drop]
# Line 188  Line 290 
290          x[i, , drop=drop]          x[i, , drop=drop]
291      else      else
292          x[i,j, drop=drop]          x[i,j, drop=drop]
293      if(isDiagonal(x)) as(x, "diagonalMatrix") else x      if(isS4(x) && isDiagonal(x)) as(x, "diagonalMatrix") else x
294  }  }
295    
296  setMethod("[", signature(x = "diagonalMatrix", i = "index",  setMethod("[", signature(x = "diagonalMatrix", i = "index",
297                           j = "index", drop = "logical"), subDiag)                           j = "index", drop = "logical"), subDiag)
298  setMethod("[", signature(x = "diagonalMatrix", i = "index",  setMethod("[", signature(x = "diagonalMatrix", i = "index",
299                          j = "missing", drop = "logical"),                          j = "missing", drop = "logical"),
300            function(x, i, drop) subDiag(x, i=i, drop=drop))            function(x, i, j, ..., drop) subDiag(x, i=i, drop=drop))
301  setMethod("[", signature(x = "diagonalMatrix", i = "missing",  setMethod("[", signature(x = "diagonalMatrix", i = "missing",
302                           j = "index", drop = "logical"),                           j = "index", drop = "logical"),
303            function(x, j, drop) subDiag(x, j=j, drop=drop))            function(x, i, j, ..., drop) subDiag(x, j=j, drop=drop))
304    
305  ## When you assign to a diagonalMatrix, the result should be  ## When you assign to a diagonalMatrix, the result should be
306  ## diagonal or sparse ---  ## diagonal or sparse ---
307  ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch  ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch
308  replDiag <- function(x, i, j, value) {  ## Only(?) current bug:  x[i] <- value  is wrong when  i is *vector*
309    replDiag <- function(x, i, j, ..., value) {
310      x <- as(x, "sparseMatrix")      x <- as(x, "sparseMatrix")
311      if(missing(i))      if(missing(i))
312          x[, j] <- value          x[, j] <- value
313      else if(missing(j))      else if(missing(j)) { ##  x[i , ] <- v  *OR*   x[i] <- v
314            na <- nargs()
315    ##         message("diagnosing replDiag() -- nargs()= ", na)
316            if(na == 4)
317          x[i, ] <- value          x[i, ] <- value
318      else          else if(na == 3)
319                x[i] <- value
320            else stop("Internal bug: nargs()=",na,"; please report")
321        } else
322          x[i,j] <- value          x[i,j] <- value
323      if(isDiagonal(x)) as(x, "diagonalMatrix") else x      if(isDiagonal(x)) as(x, "diagonalMatrix") else x
324  }  }
325    
326  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
327                                  j = "index", value = "replValue"), replDiag)                                  j = "index", value = "replValue"), replDiag)
328    
329  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
330                                  j = "missing", value = "replValue"),                                  j = "missing", value = "replValue"),
331                   function(x, i, value) replDiag(x, i=i, value=value))                   function(x,i,j, ..., value) {
332                         ## message("before replDiag() -- nargs()= ", nargs())
333                         if(nargs() == 3)
334                             replDiag(x, i=i, value=value)
335                         else ## nargs() == 4 :
336                             replDiag(x, i=i, , value=value)
337                     })
338    
339    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "matrix", # 2-col.matrix
340                                    j = "missing", value = "replValue"),
341                     function(x,i,j, ..., value) {
342                         if(ncol(i) == 2) {
343                             if(all((ii <- i[,1]) == i[,2])) { # replace in diagonal only
344                                 x@x[ii] <- value
345                                 x
346                             } else { ## no longer diagonal, but remain sparse:
347                                 x <- as(x, "sparseMatrix")
348                                 x[i] <- value
349                                 x
350                             }
351                         }
352                         else { # behave as "base R": use as if vector
353                             x <- as(x, "matrix")
354                             x[i] <- value
355                             Matrix(x)
356                         }
357                     })
358    
359  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",
360                                  j = "index", value = "replValue"),                                  j = "index", value = "replValue"),
361                   function(x, j, value) replDiag(x, j=j, value=value))                   function(x,i,j, ..., value) replDiag(x, j=j, value=value))
362    
363    
364  setMethod("t", signature(x = "diagonalMatrix"),  setMethod("t", signature(x = "diagonalMatrix"),
# Line 232  Line 369 
369  setMethod("isTriangular", signature(object = "diagonalMatrix"),  setMethod("isTriangular", signature(object = "diagonalMatrix"),
370            function(object) TRUE)            function(object) TRUE)
371  setMethod("isSymmetric", signature(object = "diagonalMatrix"),  setMethod("isSymmetric", signature(object = "diagonalMatrix"),
372            function(object) TRUE)            function(object, ...) TRUE)
373    
374  setMethod("chol", signature(x = "ddiMatrix"),# pivot = "ANY"  setMethod("symmpart", signature(x = "diagonalMatrix"), function(x) x)
375            function(x, pivot) {  setMethod("skewpart", signature(x = "diagonalMatrix"), setZero)
376                if(any(x@x < 0)) stop("chol() is undefined for diagonal matrix with negative entries")  
377    setMethod("chol", signature(x = "ddiMatrix"),
378              function(x, pivot, ...) {
379                  if(x@diag == "U") return(x)
380                  ## else
381                  if(any(x@x < 0))
382                      stop("chol() is undefined for diagonal matrix with negative entries")
383                x@x <- sqrt(x@x)                x@x <- sqrt(x@x)
384                x                x
385            })            })
386  ## chol(L) is L for logical diagonal:  ## chol(L) is L for logical diagonal:
387  setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot) x)  setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot, ...) x)
388    
389  setMethod("!", "ldiMatrix", function(e1) {  setMethod("determinant", signature(x = "diagonalMatrix", logarithm = "logical"),
390      if(e1@diag == "N")            function(x, logarithm, ...)
391          e1@x <- !e1@x            mkDet(if(x@diag == "U") rep.int(as1(x@x), x@Dim[1]) else x@x,
392      else { ## "U"                  logarithm))
393          e1@diag <- "N"  
394          e1@x <- rep.int(FALSE, e1@Dim[1])  setMethod("norm", signature(x = "diagonalMatrix", type = "character"),
395              function(x, type, ...) {
396                  if((n <- x@Dim[1]) == 0) return(0) # as for "sparseMatrix"
397                  type <- toupper(substr(type[1], 1, 1))
398                  isU <- (x@diag == "U") # unit-diagonal
399                  if(type == "F") sqrt(if(isU) n else sum(x@x^2))
400                  else { ## norm == "I","1","O","M" :
401                      if(isU) 1 else max(abs(x@x))
402      }      }
     e1  
403  })  })
404    
405    
406    
407  ## Basic Matrix Multiplication {many more to add}  ## Basic Matrix Multiplication {many more to add}
408  ##       ---------------------  ##       ---------------------
409  ## Note that "ldi" logical are treated as numeric  ## Note that "ldi" logical are treated as numeric
410  diagdiagprod <- function(x, y) {  diagdiagprod <- function(x, y) {
411      if(any(dim(x) != dim(y))) stop("non-matching dimensions")      n <- dimCheck(x,y)[1]
412      if(x@diag != "U") {      if(x@diag != "U") {
413          if(y@diag != "U") {          if(y@diag != "U") {
414              nx <- x@x * y@x              nx <- x@x * y@x
# Line 285  Line 436 
436    
437    
438  diagmatprod <- function(x, y) {  diagmatprod <- function(x, y) {
439        ## x is diagonalMatrix
440      dx <- dim(x)      dx <- dim(x)
441      dy <- dim(y)      dy <- dim(y)
442      if(dx[2] != dy[1]) stop("non-matching dimensions")      if(dx[2] != dy[1]) stop("non-matching dimensions")
443      n <- dx[1]      n <- dx[1]
444      as(if(x@diag == "U") y else x@x * y, "Matrix")      as(if(x@diag == "U") y else x@x * y, "Matrix")
445  }  }
   
446  setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),  setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),
447            diagmatprod)            diagmatprod)
448    ## sneaky .. :
449  formals(diagmatprod) <- alist(x=, y=NULL)  formals(diagmatprod) <- alist(x=, y=NULL)
450  setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),  setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),
451            diagmatprod)            diagmatprod)
 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "matrix"),  
           diagmatprod)  
452    
453  diagdgeprod <- function(x, y) {  diagGeprod <- function(x, y) {
454      dx <- dim(x)      dx <- dim(x)
455      dy <- dim(y)      dy <- dim(y)
456      if(dx[2] != dy[1]) stop("non-matching dimensions")      if(dx[2] != dy[1]) stop("non-matching dimensions")
# Line 308  Line 458 
458          y@x <- x@x * y@x          y@x <- x@x * y@x
459      y      y
460  }  }
461  setMethod("%*%", signature(x = "diagonalMatrix", y = "dgeMatrix"),  setMethod("%*%", signature(x= "diagonalMatrix", y= "dgeMatrix"), diagGeprod)
462            diagdgeprod, valueClass = "dgeMatrix")  setMethod("%*%", signature(x= "diagonalMatrix", y= "lgeMatrix"), diagGeprod)
463  formals(diagdgeprod) <- alist(x=, y=NULL)  formals(diagGeprod) <- alist(x=, y=NULL)
464  setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),  setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),
465            diagdgeprod, valueClass = "dgeMatrix")            diagGeprod, valueClass = "dgeMatrix")
466    setMethod("crossprod", signature(x = "diagonalMatrix", y = "lgeMatrix"),
467              diagGeprod)
468    
469  setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),  matdiagprod <- function(x, y) {
           function(x, y) {  
470                dx <- dim(x)                dx <- dim(x)
471                dy <- dim(y)                dy <- dim(y)
472                if(dx[2] != dy[1]) stop("non-matching dimensions")                if(dx[2] != dy[1]) stop("non-matching dimensions")
473                as(if(y@diag == "U") x else x * rep(y@x, each = dx[1]), "Matrix")      Matrix(if(y@diag == "U") x else x * rep(y@x, each = dx[1]))
474            })  }
475    setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),
476              matdiagprod)
477    formals(matdiagprod) <- alist(x=, y=NULL)
478    setMethod("tcrossprod", signature(x = "matrix", y = "diagonalMatrix"),
479              matdiagprod)
480    
481  setMethod("%*%", signature(x = "dgeMatrix", y = "diagonalMatrix"),  gediagprod <- function(x, y) {
           function(x, y) {  
482                dx <- dim(x)                dx <- dim(x)
483                dy <- dim(y)                dy <- dim(y)
484                if(dx[2] != dy[1]) stop("non-matching dimensions")                if(dx[2] != dy[1]) stop("non-matching dimensions")
485                if(y@diag == "N")                if(y@diag == "N")
486                    x@x <- x@x * rep(y@x, each = dx[1])                    x@x <- x@x * rep(y@x, each = dx[1])
487                x                x
488            })  }
489    setMethod("%*%", signature(x= "dgeMatrix", y= "diagonalMatrix"), gediagprod)
490    setMethod("%*%", signature(x= "lgeMatrix", y= "diagonalMatrix"), gediagprod)
491    formals(gediagprod) <- alist(x=, y=NULL)
492    setMethod("tcrossprod", signature(x = "dgeMatrix", y = "diagonalMatrix"),
493              gediagprod)
494    setMethod("tcrossprod", signature(x = "lgeMatrix", y = "diagonalMatrix"),
495              gediagprod)
496    
497  ## crossprod {more of these}  ## crossprod {more of these}
498    
499  ## tcrossprod --- all are not yet there: do the dense ones here:  ## tcrossprod --- all are not yet there: do the dense ones here:
500    
501    setMethod("%*%", signature(x = "diagonalMatrix", y = "denseMatrix"),
502              function(x, y) if(x@diag == "U") y else x %*% as(y, "generalMatrix"))
503    setMethod("%*%", signature(x = "denseMatrix", y = "diagonalMatrix"),
504              function(x, y) if(y@diag == "U") x else as(x, "generalMatrix") %*% y)
505    
506    
507  ## FIXME:  ## FIXME:
508  ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),  ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),
509  ##        function(x, y = NULL) {  ##        function(x, y = NULL) {
# Line 346  Line 514 
514  ##           })  ##           })
515    
516  setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),  setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
517            function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })            function(x, y = NULL) crossprod(as(x, "sparseMatrix"), y))
518    
519  setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),  setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
520            function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })            function(x, y = NULL) crossprod(x, as(y, "sparseMatrix")))
521    
522  setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),  setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
523            function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })            function(x, y = NULL) tcrossprod(as(x, "sparseMatrix"), y))
524    
525  setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),  setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
526            function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })            function(x, y = NULL) tcrossprod(x, as(y, "sparseMatrix")))
527    
528    
529  ## FIXME?: In theory, this can be done *FASTER*, in some cases, via tapply1()  ## FIXME?: In theory, this can be done *FASTER*, in some cases, via tapply1()
530  setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),  setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),
531            function(x, y) as(x, "sparseMatrix") %*% y)            function(x, y) as(x, "sparseMatrix") %*% y)
532    setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),
533              function(x, y) x %*% as(y, "sparseMatrix"))
534  ## NB: The previous is *not* triggering for  "ddi" o "dgC" (= distance 3)  ## NB: The previous is *not* triggering for  "ddi" o "dgC" (= distance 3)
535  ##     since there's a "ddense" o "Csparse" at dist. 2 => triggers first.  ##     since there's a "ddense" o "Csparse" at dist. 2 => triggers first.
536  ## ==> do this:  ## ==> do this:
# Line 372  Line 542 
542  ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*  ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*
543  ##       do indeed work by going through sparse (and *not* ddense)!  ##       do indeed work by going through sparse (and *not* ddense)!
544    
 setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),  
           function(x, y) x %*% as(y, "sparseMatrix"))  
545    
546    
547  setMethod("solve", signature(a = "diagonalMatrix", b = "missing"),  setMethod("solve", signature(a = "diagonalMatrix", b = "missing"),
# Line 396  Line 564 
564  setMethod("solve", signature(a = "diagonalMatrix", b = "Matrix"),  setMethod("solve", signature(a = "diagonalMatrix", b = "Matrix"),
565            solveDiag)            solveDiag)
566    
567    ## Schur()  ---> ./eigen.R
568    
569    
570    
571  ### ---------------- diagonal  o  sparse  -----------------------------  ###---------------- <Ops> (<Arith>, <Logic>, <Compare> ) ----------------------
   
572    
573  ## Use function for several signatures, in order to evade  ## Use function for several signatures, in order to evade
574  ## ambiguous dispatch for "ddi", since there's also Arith(ddense., ddense.)  ## ambiguous dispatch for "ddi", since there's also Arith(ddense., ddense.)
575  diagOdiag <- function(e1,e2) { # result should also be diagonal  diagOdiag <- function(e1,e2) {
576        ## result should also be diagonal _ if possible _
577      r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"      r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"
578        ## Check what happens with non-diagonals, i.e. (0 o 0), (FALSE o 0), ...:
579        r00 <- callGeneric(if(is.numeric(e1@x)) 0 else FALSE,
580                           if(is.numeric(e2@x)) 0 else FALSE)
581        if(is0(r00)) { ##  r00 == 0 or FALSE --- result *is* diagonal
582      if(is.numeric(r)) {      if(is.numeric(r)) {
583          if(is.numeric(e2@x)) {          if(is.numeric(e2@x)) {
584              e2@x <- r; return(.diag.2N(e2)) }              e2@x <- r; return(.diag.2N(e2)) }
# Line 419  Line 592 
592      e1@x <- r      e1@x <- r
593      .diag.2N(e1)      .diag.2N(e1)
594  }  }
595        else { ## result not diagonal, but at least symmetric:
596            isNum <- (is.numeric(r) || is.numeric(r00))
597            isLog <- (is.logical(r) || is.logical(r00))
598    
599            if(getOption("verbose"))
600                message("exploding  <diag>  o  <diag>  into dense matrix")
601            d <- e1@Dim
602            n <- d[1]
603            stopifnot(length(r) == n)
604            xx <- as.vector(matrix(rbind(r, matrix(r00,n,n)), n,n))
605            newcl <-
606                paste(if(isNum) "d" else if(isLog) {
607                    if(!any(is.na(r)) && !any(is.na(r00))) "n" else "l"
608                } else stop("not yet implemented .. please report")
609                      ,
610                      "syMatrix", sep='')
611    
612            new(newcl, Dim = e1@Dim, Dimnames = e1@Dimnames, x = xx)
613        }
614    }
615    
616    ### This would be *the* way, but we get tons of "ambiguous method dispatch"
617    if(FALSE) {
618  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),
619            diagOdiag)            diagOdiag)
620  ## These two are just for method disambiguation:  } else { ## These are just for method disambiguation:
621  setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "diagonalMatrix"),      for(c1 in diCls)
622            diagOdiag)          for(c2 in diCls)
623  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ddiMatrix"),              setMethod("Ops", signature(e1 = c1, e2 = c2), diagOdiag)
624            diagOdiag)  }
625    
626    ## FIXME:    diagonal  o  triangular  |-->  triangular
627    ## -----     diagonal  o  symmetric   |-->  symmetric
628    ##    {also when other is sparse: do these "here" --
629    ##     before conversion to sparse, since that loses "diagonality"}
630    
631  ## For almost everything else, diag* shall be treated "as sparse" :  ## For almost everything else, diag* shall be treated "as sparse" :
632  ## These are cheap implementations via coercion  ## These are cheap implementations via coercion
633    
634  ## for disambiguation  ## For disambiguation --- define this for "sparseMatrix" , then for "ANY";
635  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "sparseMatrix"),  ## and because we can save an .M.kind() call, we use this explicit
636            function(e1,e2) callGeneric(as(e1, "sparseMatrix"), e2))  ## "hack" for all diagonalMatrix *subclasses* instead of just "diagonalMatrix" :
637  setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "diagonalMatrix"),  ##
638            function(e1,e2) callGeneric(e1, as(e2, "sparseMatrix")))  ## ddi*:
639  ## in general:  setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "sparseMatrix"),
640  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ANY"),            function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2))
641            function(e1,e2) callGeneric(as(e1,"sparseMatrix"), e2))  setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ddiMatrix"),
642  setMethod("Ops", signature(e1 = "ANY", e2 = "diagonalMatrix"),            function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "d")))
643            function(e1,e2) callGeneric(e1, as(e2,"sparseMatrix")))  ## ldi*
644    setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "sparseMatrix"),
645              function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2))
646    setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ldiMatrix"),
647              function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "l")))
648    
649    ## Ops:  Arith  --> numeric : "dMatrix"
650    ##       Compare --> logical
651    ##       Logic   --> logical: "lMatrix"
652    
653    ##  other = "numeric" : stay diagonal if possible
654    ## ddi*: Arith: result numeric, potentially ddiMatrix
655    setMethod("Arith", signature(e1 = "ddiMatrix", e2 = "numeric"),
656              function(e1,e2) {
657                  n <- e1@Dim[1]; nsq <- n*n
658                  f0 <- callGeneric(0, e2)
659                  if(all(is0(f0))) { # remain diagonal
660                      L1 <- (le <- length(e2)) == 1L
661                      if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
662                      if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
663                          e1@diag <- "N"
664                          if(L1) r <- rep.int(r, n)
665                      } else
666                          r <- callGeneric(e1@x, e2)
667                      e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
668                      return(e1)
669                  }
670                  callGeneric(diag2tT.u(e1,e2, "d"), e2)
671              })
672    
673    setMethod("Arith", signature(e1 = "numeric", e2 = "ddiMatrix"),
674              function(e1,e2) {
675                  n <- e2@Dim[1]; nsq <- n*n
676                  f0 <- callGeneric(e1, 0)
677                  if(all(is0(f0))) { # remain diagonal
678                      L1 <- (le <- length(e1)) == 1L
679                      if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
680                      if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
681                          e2@diag <- "N"
682                          if(L1) r <- rep.int(r, n)
683                      } else
684                          r <- callGeneric(e1, e2@x)
685                      e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
686                      return(e2)
687                  }
688                  callGeneric(e1, diag2tT.u(e2,e1, "d"))
689              })
690    
691    ## ldi* Arith --> result numeric, potentially ddiMatrix
692    setMethod("Arith", signature(e1 = "ldiMatrix", e2 = "numeric"),
693              function(e1,e2) {
694                  n <- e1@Dim[1]; nsq <- n*n
695                  f0 <- callGeneric(0, e2)
696                  if(all(is0(f0))) { # remain diagonal
697                      L1 <- (le <- length(e2)) == 1L
698                      if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
699                      if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
700                          e1@diag <- "N"
701                          if(L1) r <- rep.int(r, n)
702                      } else
703                          r <- callGeneric(e1@x, e2)
704                      e1 <- copyClass(e1, "ddiMatrix", c("diag", "Dim", "Dimnames"))
705                      e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
706                      return(e1)
707                  }
708                  callGeneric(diag2tT.u(e1,e2, "d"), e2)
709              })
710    
711    setMethod("Arith", signature(e1 = "numeric", e2 = "ldiMatrix"),
712              function(e1,e2) {
713                  n <- e2@Dim[1]; nsq <- n*n
714                  f0 <- callGeneric(e1, 0)
715                  if(all(is0(f0))) { # remain diagonal
716                      L1 <- (le <- length(e1)) == 1L
717                      if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
718                      if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
719                          e2@diag <- "N"
720                          if(L1) r <- rep.int(r, n)
721                      } else
722                          r <- callGeneric(e1, e2@x)
723                      e2 <- copyClass(e2, "ddiMatrix", c("diag", "Dim", "Dimnames"))
724                      e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
725                      return(e2)
726                  }
727                  callGeneric(e1, diag2tT.u(e2,e1, "d"))
728              })
729    
730    ## ddi*: for "Ops" without Arith --> result logical, potentially ldi
731    setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "numeric"),
732              function(e1,e2) {
733                  n <- e1@Dim[1]; nsq <- n*n
734                  f0 <- callGeneric(0, e2)
735                  if(all(is0(f0))) { # remain diagonal
736                      L1 <- (le <- length(e2)) == 1L
737                      if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
738                      if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
739                          e1@diag <- "N"
740                          if(L1) r <- rep.int(r, n)
741                      } else
742                          r <- callGeneric(e1@x, e2)
743                      e1 <- copyClass(e1, "ldiMatrix", c("diag", "Dim", "Dimnames"))
744                      e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
745                      return(e1)
746                  }
747                  callGeneric(diag2tT.u(e1,e2, "l"), e2)
748              })
749    
750    setMethod("Ops", signature(e1 = "numeric", e2 = "ddiMatrix"),
751              function(e1,e2) {
752                  n <- e2@Dim[1]; nsq <- n*n
753                  f0 <- callGeneric(e1, 0)
754                  if(all(is0(f0))) { # remain diagonal
755                      L1 <- (le <- length(e1)) == 1L
756                      if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
757                      if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
758                          e2@diag <- "N"
759                          if(L1) r <- rep.int(r, n)
760                      } else
761                          r <- callGeneric(e1, e2@x)
762                      e2 <- copyClass(e2, "ldiMatrix", c("diag", "Dim", "Dimnames"))
763                      e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
764                      return(e2)
765                  }
766                  callGeneric(e1, diag2tT.u(e2,e1, "l"))
767              })
768    
769    ## ldi*: for "Ops" without Arith --> result logical, potentially ldi
770    setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "numeric"),
771              function(e1,e2) {
772                  n <- e1@Dim[1]; nsq <- n*n
773                  f0 <- callGeneric(FALSE, e2)
774                  if(all(is0(f0))) { # remain diagonal
775                      L1 <- (le <- length(e2)) == 1L
776                      if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
777                      if(e1@diag == "U" && any((r <- callGeneric(TRUE, e2)) != 1)) {
778                          e1@diag <- "N"
779                          if(L1) r <- rep.int(r, n)
780                      } else
781                          r <- callGeneric(e1@x, e2)
782                      e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
783                      return(e1)
784                  }
785                  callGeneric(diag2tT.u(e1,e2, "l"), e2)
786              })
787    
788    setMethod("Ops", signature(e1 = "numeric", e2 = "ldiMatrix"),
789              function(e1,e2) {
790                  n <- e2@Dim[1]; nsq <- n*n
791                  f0 <- callGeneric(e1, FALSE)
792                  if(all(is0(f0))) { # remain diagonal
793                      L1 <- (le <- length(e1)) == 1L
794                      if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
795                      if(e2@diag == "U" && any((r <- callGeneric(e1, TRUE)) != 1)) {
796                          e2@diag <- "N"
797                          if(L1) r <- rep.int(r, n)
798                      } else
799                          r <- callGeneric(e1, e2@x)
800                      e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
801                      return(e2)
802                  }
803                  callGeneric(e1, diag2tT.u(e2,e1, "l"))
804              })
805    
806    
807    
808    ## Not {"sparseMatrix", "numeric} :  {"denseMatrix", "matrix", ... }
809    ## ddi*:
810    setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "ANY"),
811              function(e1,e2) callGeneric(diag2tT.u(e1,e2, "d"), e2))
812    setMethod("Ops", signature(e1 = "ANY", e2 = "ddiMatrix"),
813              function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "d")))
814    ## ldi*:
815    setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "ANY"),
816              function(e1,e2) callGeneric(diag2tT.u(e1,e2, "l"), e2))
817    setMethod("Ops", signature(e1 = "ANY", e2 = "ldiMatrix"),
818              function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "l")))
819    
820    ## This should *not* dispatch to <dense> methods (in ./Ops.R ), as
821    ##  FALSE & <anything> |-> FALSE : hence result should be diagonal:
822    for(cl in diCls) {
823        setMethod("&", signature(e1 = cl, e2 = "ANY"),
824                  function(e1,e2) e1 & as(e2,"Matrix"))
825        setMethod("&", signature(e1 = "ANY", e2 = cl),
826                  function(e1,e2) as(e1,"Matrix") & e2)
827        for(c2 in c("denseMatrix", "Matrix")) {
828            setMethod("&", signature(e1 = cl, e2 = c2),
829                      function(e1,e2) e1 & Diagonal(x = diag(e2)))
830            setMethod("&", signature(e1 = c2, e2 = cl),
831                      function(e1,e2) Diagonal(x = diag(e1)) & e2)
832        }
833    }
834    
835    
836    ### "Summary" : "max"   "min"   "range" "prod"  "sum"   "any"   "all"
837    ### ----------  any, all: separately here
838    for(cl in diCls) {
839    setMethod("any", cl,
840              function (x, ..., na.rm) {
841                  if(any(x@Dim == 0)) FALSE
842                  else if(x@diag == "U") TRUE else any(x@x, ..., na.rm = na.rm)
843              })
844    setMethod("all",  cl, function (x, ..., na.rm) any(x@Dim == 0))
845    setMethod("prod", cl, function (x, ..., na.rm) as.numeric(any(x@Dim == 0)))
846    
847    setMethod("sum", cl,
848              function(x, ..., na.rm) {
849                  r <- sum(x@x, ..., na.rm = na.rm)# double or integer, correctly
850                  if(x@diag == "U" && !is.na(r)) r + x@Dim[1] else r
851              })
852    }
853    
854    ## The remaining ones are  max, min, range :
855    
856    setMethod("Summary", "ddiMatrix",
857              function(x, ..., na.rm) {
858                  if(any(x@Dim == 0)) callGeneric(numeric(0), ..., na.rm=na.rm)
859                  else if(x@diag == "U")
860                      callGeneric(x@x, 0, 1, ..., na.rm=na.rm)
861                  else callGeneric(x@x, 0, ..., na.rm=na.rm)
862              })
863    setMethod("Summary", "ldiMatrix",
864              function(x, ..., na.rm) {
865                  if(any(x@Dim == 0)) callGeneric(logical(0), ..., na.rm=na.rm)
866                  else if(x@diag == "U")
867                      callGeneric(x@x, FALSE, TRUE, ..., na.rm=na.rm)
868                  else callGeneric(x@x, FALSE, ..., na.rm=na.rm)
869              })
870    
871    
872    

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

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