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 2472, Sat Sep 19 06:10:48 2009 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    .sparseDiagonal <- function(n, x = rep.int(1,n), uplo = "U", shape = "t") {
36        stopifnot(n == (n. <- as.integer(n)), (n <- n.) >= 0)
37        if((lx <- length(x)) == 1) x <- rep.int(x, n)
38        else if(lx != n) stop("length(x) must be 1 or n")
39        stopifnot(is.character(shape), nchar(shape) == 1,
40                  any(shape == c("t","s","g"))) # triangular / symmetric / general
41        kind <-
42            if(is.double(x)) "d"
43            else if(is.logical(x)) "l"
44            else { ## for now
45                storage.mode(x) <- "double"
46                "d"
47            }
48        ii <- if(n) 0:(n - 1L) else integer(0)
49        if(shape == "g")
50            new(paste0(kind, "gCMatrix"), Dim = c(n,n),
51                x = x, i = ii, p = 0:n)
52        else new(paste0(kind, shape, "CMatrix"), Dim = c(n,n), uplo = uplo,
53                 x = x, i = ii, p = 0:n)
54    }
55    
56    ## Pkg 'spdep' had (relatively slow) versions of this as_dsCMatrix_I()
57    .symDiagonal <- function(n, x = rep.int(1,n), uplo = "U")
58        .sparseDiagonal(n, x, uplo, shape = "s")
59    
60    ## instead of   diagU2N(as(Diagonal(n), "CsparseMatrix")), diag = "N" in any case:
61    .trDiagonal <- function(n, x = rep.int(1,n), uplo = "U")
62        .sparseDiagonal(n, x, uplo, shape = "t")
63    
64    
65  ### 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.
66  ### 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
67  ### 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
68  ### who posted his bdiag() function written in December 1995.  ### who posted his bdiag() function written in December 1995.
69    if(FALSE)##--- no longer used:
70  bdiag <- function(...) {  .bdiag <- function(lst) {
71      if(nargs() == 0) return(new("dgCMatrix"))      ### block-diagonal matrix [a dgTMatrix] from list of matrices
72      ## else :      stopifnot(is.list(lst), length(lst) >= 1)
73      mlist <- if (nargs() == 1) as.list(...) else list(...)      dims <- sapply(lst, dim, USE.NAMES=FALSE)
     dims <- sapply(mlist, dim)  
74      ## make sure we had all matrices:      ## make sure we had all matrices:
75      if(!(is.matrix(dims) && nrow(dims) == 2))      if(!(is.matrix(dims) && nrow(dims) == 2))
76          stop("some arguments are not matrices")          stop("some arguments are not matrices")
77      csdim <- rbind(rep.int(0:0, 2),      csdim <- rbind(rep.int(0L, 2),
78                     apply(sapply(mlist, dim), 1, cumsum))                     apply(dims, 1, cumsum))
79      ret <- new("dgTMatrix", Dim = as.integer(csdim[nrow(csdim),]))      r <- new("dgTMatrix")
80        r@Dim <- as.integer(csdim[nrow(csdim),])
81      add1 <- matrix(1:0, 2,2)      add1 <- matrix(1:0, 2,2)
82      for(i in seq_along(mlist)) {      for(i in seq_along(lst)) {
83          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])
84          if(is.null(dim(indx))) ## non-square matrix          if(is.null(dim(indx))) ## non-square matrix
85              ret[indx[[1]],indx[[2]]] <- mlist[[i]]              r[indx[[1]],indx[[2]]] <- lst[[i]]
86          else ## square matrix          else ## square matrix
87              ret[indx[,1],indx[,2]] <- mlist[[i]]              r[indx[,1], indx[,2]] <- lst[[i]]
88        }
89        r
90    }
91    ## expand(<mer>) needed something like bdiag() for lower-triangular
92    ## (Tsparse) Matrices; hence Doug Bates provided a much more efficient
93    ##  implementation for those; now extended and generalized:
94    .bdiag <- function(lst) {
95        ## block-diagonal matrix [a dgTMatrix] from list of matrices
96        stopifnot(is.list(lst), (nl <- length(lst)) >= 1)
97    
98        Tlst <- lapply(lapply(lst, Matrix:::as_Csp2), # includes "diagU2N"
99                       as, "TsparseMatrix")
100        if(nl == 1) return(Tlst[[1]])
101        ## else
102        i_off <- c(0L, cumsum(sapply(Tlst, nrow)))
103        j_off <- c(0L, cumsum(sapply(Tlst, ncol)))
104    
105        clss <- sapply(Tlst, class)
106        knds <- substr(clss, 2, 2)
107        sym  <- knds == "s" # symmetric ones
108        tri  <- knds == "t" # triangular ones
109        use.n <- any(is.n <- substr(clss,1,1) == "n")
110        if(use.n && !(use.n <- all(is.n)))
111            Tlst[is.n] <- lapply(Tlst[is.n], as, "lMatrix")
112        if(all(sym)) { ## result should be *symmetric*
113            uplos <- sapply(Tlst, slot, "uplo") ## either "U" or "L"
114            tLU <- table(uplos)# of length 1 or 2 ..
115            if(length(tLU) == 1) { ## all "U" or all "L"
116                useU <- uplos[1] == "U"
117            } else { ## length(tLU) == 2, counting "L" and "U"
118                useU <- diff(tLU) >= 0
119                if(useU && (hasL <- tLU[1] > 0))
120                    Tlst[hasL] <- lapply(Tlst[hasL], t)
121                else if(!useU && (hasU <- tLU[2] > 0))
122                    Tlst[hasU] <- lapply(Tlst[hasU], t)
123            }
124            if(use.n) { ## return nsparseMatrix :
125                r <- new("nsTMatrix")
126            } else {
127                r <- new("dsTMatrix")
128                r@x <- unlist(lapply(Tlst, slot, "x"))
129      }      }
130      ## slightly debatable if we really should return Csparse.. :          r@uplo <- if(useU) "U" else "L"
     as(ret, "CsparseMatrix")  
131  }  }
132        else if(all(tri) && { ULs <- sapply(Tlst, slot, "uplo")##  "U" or "L"
133                              all(ULs[1L] == ULs[-1L]) } ## all upper or all lower
134           ){ ## *triangular* result
135    
136  diag2T <- function(from) {          if(use.n) { ## return nsparseMatrix :
137      i <- if(from@diag == "U") integer(0) else seq_len(from@Dim[1]) - 1:1              r <- new("ntTMatrix")
138      new(paste(.M.kind(from), "tTMatrix", sep=''),          } else {
139                r <- new("dtTMatrix")
140                r@x <- unlist(lapply(Tlst, slot, "x"))
141            }
142            r@uplo <- ULs[1L]
143        }
144        else {
145            if(any(sym))
146                Tlst[sym] <- lapply(Tlst[sym], as, "generalMatrix")
147            if(use.n) { ## return nsparseMatrix :
148                r <- new("ngTMatrix")
149            } else {
150                r <- new("dgTMatrix")
151                r@x <- unlist(lapply(Tlst, slot, "x"))
152            }
153        }
154        r@Dim <- c(i_off[nl+1], j_off[nl + 1])
155        r@i <- unlist(lapply(1:nl, function(k) Tlst[[k]]@i + i_off[k]))
156        r@j <- unlist(lapply(1:nl, function(k) Tlst[[k]]@j + j_off[k]))
157        r
158    }
159    
160    bdiag <- function(...) {
161        if((nA <- nargs()) == 0) return(new("dgCMatrix"))
162        if(nA == 1 && !is.list(...))
163            return(as(..., "CsparseMatrix"))
164        alis <- if(nA == 1 && is.list(..1)) ..1 else list(...)
165        if(length(alis) == 1)
166            return(as(alis[[1]], "CsparseMatrix"))
167    
168        ## else : two or more arguments
169        as(.bdiag(alis), "CsparseMatrix")
170    }
171    
172    
173    .diag2tT <- function(from, uplo = "U", kind = .M.kind(from)) {
174        ## to triangular Tsparse
175        i <- if(from@diag == "U") integer(0) else seq_len(from@Dim[1]) - 1L
176        new(paste(kind, "tTMatrix", sep=''),
177          diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,          diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,
178            uplo = uplo,
179          x = from@x, # <- ok for diag = "U" and "N" (!)          x = from@x, # <- ok for diag = "U" and "N" (!)
180          i = i, j = i)          i = i, j = i)
181  }  }
182    
183  setAs("diagonalMatrix", "triangularMatrix", diag2T)  .diag2sT <- function(from, uplo = "U", kind = .M.kind(from)) {
184  setAs("diagonalMatrix", "sparseMatrix", diag2T)      ## to symmetric Tsparse
185        n <- from@Dim[1]
186        i <- seq_len(n) - 1L
187        new(paste(kind, "sTMatrix", sep=''),
188            Dim = from@Dim, Dimnames = from@Dimnames,
189            i = i, j = i, uplo = uplo,
190            x = if(from@diag == "N") from@x else ## "U"-diag
191            rep.int(switch(kind,
192                           "d" = 1.,
193                           "l" =,
194                           "n" = TRUE,
195                           ## otherwise
196                           stop("'", kind,"' kind not yet implemented")), n))
197    }
198    
199    ## diagonal -> triangular,  upper / lower depending on "partner":
200    diag2tT.u <- function(d, x, kind = .M.kind(d))
201        .diag2tT(d, uplo = if(is(x,"triangularMatrix")) x@uplo else "U", kind)
202    
203    ## diagonal -> sparse {triangular OR symmetric} (upper / lower) depending on "partner":
204    diag2Tsmart <- function(d, x, kind = .M.kind(d)) {
205        clx <- getClassDef(class(x))
206        if(extends(clx, "symmetricMatrix"))
207            .diag2sT(d, uplo = x@uplo, kind)
208        else
209            .diag2tT(d, uplo = if(extends(clx,"triangularMatrix")) x@uplo else "U", kind)
210    }
211    
212    
213    ## In order to evade method dispatch ambiguity warnings,
214    ## and because we can save a .M.kind() call, we use this explicit
215    ## "hack"  instead of signature  x = "diagonalMatrix" :
216    ##
217    ## ddi*:
218    diag2tT <- function(from) .diag2tT(from, "U", "d")
219    setAs("ddiMatrix", "triangularMatrix", diag2tT)
220    ##_no_longer_ setAs("ddiMatrix", "sparseMatrix", diag2tT)
221    ## needed too (otherwise <dense> -> Tsparse is taken):
222    setAs("ddiMatrix", "TsparseMatrix", diag2tT)
223    setAs("ddiMatrix", "CsparseMatrix",
224          function(from) as(.diag2tT(from, "U", "d"), "CsparseMatrix"))
225    setAs("ddiMatrix", "symmetricMatrix",
226          function(from) .diag2sT(from, "U", "d"))
227    ##
228    ## ldi*:
229    diag2tT <- function(from) .diag2tT(from, "U", "l")
230    setAs("ldiMatrix", "triangularMatrix", diag2tT)
231    ##_no_longer_ setAs("ldiMatrix", "sparseMatrix", diag2tT)
232  ## needed too (otherwise <dense> -> Tsparse is taken):  ## needed too (otherwise <dense> -> Tsparse is taken):
233  setAs("diagonalMatrix", "TsparseMatrix", diag2T)  setAs("ldiMatrix", "TsparseMatrix", diag2tT)
234  ## is better than this:  setAs("ldiMatrix", "CsparseMatrix",
235  ## setAs("diagonalMatrix", "sparseMatrix",        function(from) as(.diag2tT(from, "U", "l"), "CsparseMatrix"))
236  ##       function(from)  setAs("ldiMatrix", "symmetricMatrix",
237  ##        as(from, if(is(from, "dMatrix")) "dgCMatrix" else "lgCMatrix"))        function(from) .diag2sT(from, "U", "l"))
 setAs("diagonalMatrix", "CsparseMatrix",  
       function(from) as(diag2T(from), "CsparseMatrix"))  
238    
239  setAs("diagonalMatrix", "matrix",  
240    setAs("diagonalMatrix", "nMatrix",
241        function(from) {        function(from) {
242            n <- from@Dim[1]            n <- from@Dim[1]
243            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
244                                       } else from@x,            new("ntTMatrix", i = i, j = i, diag = from@diag,
245                 nrow = n, ncol = n)                Dim = from@Dim, Dimnames = from@Dimnames)
246        })        })
247    
248  setAs("diagonalMatrix", "generalMatrix", # prefer sparse:  setAs("diagonalMatrix", "nsparseMatrix", function(from) as(from, "nMatrix"))
       function(from) as(from, paste(.M.kind(from), "gCMatrix", sep='')))  
249    
250  .diag.x <- function(m) {  ## Cheap fast substitute for diag() which *does* preserve the mode of x :
251      if(m@diag == "U")  mkDiag <- function(x, n) {
252          rep.int(if(is.numeric(m@x)) 1. else TRUE,      y <- matrix(as0(mod=mode(x)), n,n)
253                  m@Dim[1])      if (n > 0) y[1L + 0:(n - 1L) * (n + 1L)] <- x
254      else m@x      y
 }  
   
 .diag.2N <- function(m) {  
     if(m@diag == "U") m@diag <- "N"  
     m  
255  }  }
256    
257  ## given the above, the following  4  coercions should be all unneeded;  setAs("diagonalMatrix", "matrix",
 ## we prefer triangular to general:  
 setAs("ddiMatrix", "dgTMatrix",  
258        function(from) {        function(from) {
259            .Deprecated("as(, \"sparseMatrix\")")            ## want "ldiMatrix" -> <logical> "matrix" :
260            n <- from@Dim[1]            mkDiag(if(from@diag == "U") as1(from@x) else from@x,
261            i <- seq_len(n) - 1:1                   n = from@Dim[1])
262            new("dgTMatrix", i = i, j = i, x = .diag.x(from),        })
               Dim = c(n,n), Dimnames = from@Dimnames) })  
263    
264  setAs("ddiMatrix", "dgCMatrix",  setMethod("as.vector", signature(x = "diagonalMatrix", mode="missing"),
265        function(from) as(as(from, "sparseMatrix"), "dgCMatrix"))            function(x, mode) {
266                  n <- x@Dim[1]
267                  mod.x <- mode(x@x)
268                  r <- vector(mod.x, length = n^2)
269                  if(n)
270                      r[1 + 0:(n - 1) * (n + 1)] <-
271                          if(x@diag == "U") as1(mod=mod.x) else x@x
272                  r
273              })
274    
275  setAs("ldiMatrix", "lgTMatrix",  setAs("diagonalMatrix", "generalMatrix", # prefer sparse:
276        function(from) {        function(from) as(as(from, "CsparseMatrix"), "generalMatrix"))
           .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) })  
277    
278  setAs("ldiMatrix", "lgCMatrix",  setAs("diagonalMatrix", "denseMatrix",
279        function(from) as(as(from, "lgTMatrix"), "lgCMatrix"))        function(from) as(as(from, "CsparseMatrix"), "denseMatrix"))
280    
281    .diag.x <- function(m) if(m@diag == "U") rep.int(as1(m@x), m@Dim[1]) else m@x
282    
283    .diag.2N <- function(m) {
284        if(m@diag == "U") m@diag <- "N"
285        m
286    }
287    
 if(FALSE) # now have faster  "ddense" -> "dge"  
288  setAs("ddiMatrix", "dgeMatrix",  setAs("ddiMatrix", "dgeMatrix",
289        function(from) as(as(from, "matrix"), "dgeMatrix"))        function(from) .Call(dup_mMatrix_as_dgeMatrix, from))
290    setAs("ddiMatrix", "ddenseMatrix",
291          function(from) as(as(from, "triangularMatrix"),"denseMatrix"))
292    setAs("ldiMatrix", "ldenseMatrix",
293          function(from) as(as(from, "triangularMatrix"),"denseMatrix"))
294    
295    
296  setAs("matrix", "diagonalMatrix",  setAs("matrix", "diagonalMatrix",
297        function(from) {        function(from) {
298            d <- dim(from)            d <- dim(from)
299            if(d[1] != (n <- d[2])) stop("non-square matrix")            if(d[1] != (n <- d[2])) stop("non-square matrix")
300            if(any(from[row(from) != col(from)] != 0))            if(any(from[row(from) != col(from)] != 0))
301                stop("has non-zero off-diagonal entries")                stop("matrix with non-zero off-diagonals cannot be coerced to diagonalMatrix")
302            x <- diag(from)            x <- diag(from)
303            if(is.logical(x)) {            if(is.logical(x)) {
304                cl <- "ldiMatrix"                cl <- "ldiMatrix"
305                uni <- all(x)                uni <- allTrue(x) ## uni := {is it unit-diagonal ?}
306            } else {            } else {
307                cl <- "ddiMatrix"                cl <- "ddiMatrix"
308                uni <- all(x == 1)                uni <- allTrue(x == 1)
309                storage.mode(x) <- "double"                storage.mode(x) <- "double"
310            } ## TODO: complex            } ## TODO: complex
311            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 322 
322            x <- diag(from)            x <- diag(from)
323            if(is.logical(x)) {            if(is.logical(x)) {
324                cl <- "ldiMatrix"                cl <- "ldiMatrix"
325                uni <- all(x)                uni <- allTrue(x)
326            } else {            } else {
327                cl <- "ddiMatrix"                cl <- "ddiMatrix"
328                uni <- all(x == 1)                uni <- allTrue(x == 1)
329                storage.mode(x) <- "double"                storage.mode(x) <- "double"
330            }            } ## TODO: complex
331            new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",            new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
332                x = if(uni) x[FALSE] else x)                x = if(uni) x[FALSE] else x)
333        })        })
334    
335    
336  setMethod("diag", signature(x = "diagonalMatrix"),  setMethod("diag", signature(x = "diagonalMatrix"),
337            function(x = 1, nrow, ncol = n) .diag.x(x))            function(x = 1, nrow, ncol) .diag.x(x))
   
338    
339  subDiag <- function(x, i, j, drop) {  subDiag <- function(x, i, j, ..., drop) {
340      x <- as(x, "sparseMatrix")      x <- as(x, "TsparseMatrix")
341      x <- if(missing(i))      x <- if(missing(i))
342          x[, j, drop=drop]          x[, j, drop=drop]
343      else if(missing(j))      else if(missing(j))
344          x[i, , drop=drop]          if(nargs() == 4) x[i, , drop=drop] else x[i, drop=drop]
345      else      else
346          x[i,j, drop=drop]          x[i,j, drop=drop]
347      if(isDiagonal(x)) as(x, "diagonalMatrix") else x      if(isS4(x) && isDiagonal(x)) as(x, "diagonalMatrix") else x
348  }  }
349    
350  setMethod("[", signature(x = "diagonalMatrix", i = "index",  setMethod("[", signature(x = "diagonalMatrix", i = "index",
351                           j = "index", drop = "logical"), subDiag)                           j = "index", drop = "logical"), subDiag)
352  setMethod("[", signature(x = "diagonalMatrix", i = "index",  setMethod("[", signature(x = "diagonalMatrix", i = "index",
353                          j = "missing", drop = "logical"),                          j = "missing", drop = "logical"),
354            function(x, i, drop) subDiag(x, i=i, drop=drop))            function(x, i, j, ..., drop) {
355                  na <- nargs()
356                  Matrix.msg("diag[i,m,l] : nargs()=", na, .M.level = 2)
357                  if(na == 4)
358                       subDiag(x, i=i, , drop=drop)
359                  else subDiag(x, i=i,   drop=drop)
360              })
361  setMethod("[", signature(x = "diagonalMatrix", i = "missing",  setMethod("[", signature(x = "diagonalMatrix", i = "missing",
362                           j = "index", drop = "logical"),                           j = "index", drop = "logical"),
363            function(x, j, drop) subDiag(x, j=j, drop=drop))            function(x, i, j, ..., drop) subDiag(x, j=j, drop=drop))
364    
365  ## When you assign to a diagonalMatrix, the result should be  ## When you assign to a diagonalMatrix, the result should be
366  ## diagonal or sparse ---  ## diagonal or sparse ---
367  ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch  ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch
368  replDiag <- function(x, i, j, value) {  ## Only(?) current bug:  x[i] <- value  is wrong when  i is *vector*
369      x <- as(x, "sparseMatrix")  replDiag <- function(x, i, j, ..., value) {
370        x <- as(x, "TsparseMatrix")
371      if(missing(i))      if(missing(i))
372          x[, j] <- value          x[, j] <- value
373      else if(missing(j))      else if(missing(j)) { ##  x[i , ] <- v  *OR*   x[i] <- v
374            na <- nargs()
375    ##         message("diagnosing replDiag() -- nargs()= ", na)
376            if(na == 4)
377          x[i, ] <- value          x[i, ] <- value
378      else          else if(na == 3)
379                x[i] <- value
380            else stop("Internal bug: nargs()=",na,"; please report")
381        } else
382          x[i,j] <- value          x[i,j] <- value
383      if(isDiagonal(x)) as(x, "diagonalMatrix") else x      if(isDiagonal(x)) as(x, "diagonalMatrix") else x
384  }  }
385    
386  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
387                                  j = "index", value = "replValue"), replDiag)                                  j = "index", value = "replValue"), replDiag)
388    
389  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
390                                  j = "missing", value = "replValue"),                                  j = "missing", value = "replValue"),
391                   function(x, i, value) replDiag(x, i=i, value=value))                   function(x,i,j, ..., value) {
392                         ## message("before replDiag() -- nargs()= ", nargs())
393                         if(nargs() == 3)
394                             replDiag(x, i=i, value=value)
395                         else ## nargs() == 4 :
396                             replDiag(x, i=i, , value=value)
397                     })
398    
399    setReplaceMethod("[", signature(x = "diagonalMatrix",
400                                    i = "matrix", # 2-col.matrix
401                                    j = "missing", value = "replValue"),
402                     function(x,i,j, ..., value) {
403                         if(ncol(i) == 2) {
404                             if(all((ii <- i[,1]) == i[,2])) { # replace in diagonal only
405                                 if(x@diag == "U") {
406                                     one <- as1(x@x)
407                                     if(any(value != one | is.na(value))) {
408                                         x@diag <- "N"
409                                         x@x <- rep.int(one, x@Dim[1])
410                                     }
411                                 }
412                                 x@x[ii] <- value
413                                 x
414                             } else { ## no longer diagonal, but remain sparse:
415                                 x <- as(x, "TsparseMatrix")
416                                 x[i] <- value
417                                 x
418                             }
419                         }
420                         else { # behave as "base R": use as if vector
421                             x <- as(x, "matrix")
422                             x[i] <- value
423                             Matrix(x)
424                         }
425                     })
426    
427  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",  setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",
428                                  j = "index", value = "replValue"),                                  j = "index", value = "replValue"),
429                   function(x, j, value) replDiag(x, j=j, value=value))                   function(x,i,j, ..., value) replDiag(x, j=j, value=value))
430    
431    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing", j = "index",
432                                    value = "sparseMatrix"),
433                     function (x, i, j, ..., value)
434                     callGeneric(x=x, , j=j, value = as(value, "sparseVector")))
435    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "missing",
436                                    value = "sparseMatrix"),
437                     function (x, i, j, ..., value)
438                     callGeneric(x=x, i=i, , value = as(value, "sparseVector")))
439    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "index",
440                                    value = "sparseMatrix"),
441                     function (x, i, j, ..., value)
442                     callGeneric(x=x, i=i, j=j, value = as(value, "sparseVector")))
443    
444    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing", j = "index",
445                                    value = "sparseVector"),
446                     replDiag)
447    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "missing",
448                                    value = "sparseVector"),
449                     replDiag)
450    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "index",
451                                    value = "sparseVector"),
452                     replDiag)
453    
454    
455  setMethod("t", signature(x = "diagonalMatrix"),  setMethod("t", signature(x = "diagonalMatrix"),
# Line 232  Line 460 
460  setMethod("isTriangular", signature(object = "diagonalMatrix"),  setMethod("isTriangular", signature(object = "diagonalMatrix"),
461            function(object) TRUE)            function(object) TRUE)
462  setMethod("isSymmetric", signature(object = "diagonalMatrix"),  setMethod("isSymmetric", signature(object = "diagonalMatrix"),
463            function(object) TRUE)            function(object, ...) TRUE)
464    
465  setMethod("chol", signature(x = "ddiMatrix"),# pivot = "ANY"  setMethod("symmpart", signature(x = "diagonalMatrix"), function(x) x)
466            function(x, pivot) {  setMethod("skewpart", signature(x = "diagonalMatrix"), setZero)
467                if(any(x@x < 0)) stop("chol() is undefined for diagonal matrix with negative entries")  
468    setMethod("chol", signature(x = "ddiMatrix"),
469              function(x, pivot, ...) {
470                  if(x@diag == "U") return(x)
471                  ## else
472                  if(any(x@x < 0))
473                      stop("chol() is undefined for diagonal matrix with negative entries")
474                x@x <- sqrt(x@x)                x@x <- sqrt(x@x)
475                x                x
476            })            })
477  ## chol(L) is L for logical diagonal:  ## chol(L) is L for logical diagonal:
478  setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot) x)  setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot, ...) x)
479    
480  setMethod("!", "ldiMatrix", function(e1) {  setMethod("determinant", signature(x = "diagonalMatrix", logarithm = "logical"),
481      if(e1@diag == "N")            function(x, logarithm, ...) mkDet(.diag.x(x), logarithm))
482          e1@x <- !e1@x  
483      else { ## "U"  setMethod("norm", signature(x = "diagonalMatrix", type = "character"),
484          e1@diag <- "N"            function(x, type, ...) {
485          e1@x <- rep.int(FALSE, e1@Dim[1])                if((n <- x@Dim[1]) == 0) return(0) # as for "sparseMatrix"
486                  type <- toupper(substr(type[1], 1, 1))
487                  isU <- (x@diag == "U") # unit-diagonal
488                  if(type == "F") sqrt(if(isU) n else sum(x@x^2))
489                  else { ## norm == "I","1","O","M" :
490                      if(isU) 1 else max(abs(x@x))
491      }      }
     e1  
492  })  })
493    
494    
495    
496  ## Basic Matrix Multiplication {many more to add}  ## Basic Matrix Multiplication {many more to add}
497  ##       ---------------------  ##       ---------------------
498  ## Note that "ldi" logical are treated as numeric  ## Note that "ldi" logical are treated as numeric
499  diagdiagprod <- function(x, y) {  diagdiagprod <- function(x, y) {
500      if(any(dim(x) != dim(y))) stop("non-matching dimensions")      n <- dimCheck(x,y)[1]
501      if(x@diag != "U") {      if(x@diag != "U") {
502          if(y@diag != "U") {          if(y@diag != "U") {
503              nx <- x@x * y@x              nx <- x@x * y@x
# Line 285  Line 525 
525    
526    
527  diagmatprod <- function(x, y) {  diagmatprod <- function(x, y) {
528        ## x is diagonalMatrix
529      dx <- dim(x)      dx <- dim(x)
530      dy <- dim(y)      dy <- dim(y)
531      if(dx[2] != dy[1]) stop("non-matching dimensions")      if(dx[2] != dy[1]) stop("non-matching dimensions")
532      n <- dx[1]      n <- dx[1]
533      as(if(x@diag == "U") y else x@x * y, "Matrix")      as(if(x@diag == "U") y else x@x * y, "Matrix")
534  }  }
   
535  setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),  setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),
536            diagmatprod)            diagmatprod)
537    ## sneaky .. :
538  formals(diagmatprod) <- alist(x=, y=NULL)  formals(diagmatprod) <- alist(x=, y=NULL)
539  setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),  setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),
540            diagmatprod)            diagmatprod)
 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "matrix"),  
           diagmatprod)  
541    
542  diagdgeprod <- function(x, y) {  diagGeprod <- function(x, y) {
543      dx <- dim(x)      dx <- dim(x)
544      dy <- dim(y)      dy <- dim(y)
545      if(dx[2] != dy[1]) stop("non-matching dimensions")      if(dx[2] != dy[1]) stop("non-matching dimensions")
# Line 308  Line 547 
547          y@x <- x@x * y@x          y@x <- x@x * y@x
548      y      y
549  }  }
550  setMethod("%*%", signature(x = "diagonalMatrix", y = "dgeMatrix"),  setMethod("%*%", signature(x= "diagonalMatrix", y= "dgeMatrix"), diagGeprod)
551            diagdgeprod, valueClass = "dgeMatrix")  setMethod("%*%", signature(x= "diagonalMatrix", y= "lgeMatrix"), diagGeprod)
552  formals(diagdgeprod) <- alist(x=, y=NULL)  formals(diagGeprod) <- alist(x=, y=NULL)
553  setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),  setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),
554            diagdgeprod, valueClass = "dgeMatrix")            diagGeprod, valueClass = "dgeMatrix")
555    setMethod("crossprod", signature(x = "diagonalMatrix", y = "lgeMatrix"),
556              diagGeprod)
557    
558  setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),  matdiagprod <- function(x, y) {
           function(x, y) {  
559                dx <- dim(x)                dx <- dim(x)
560                dy <- dim(y)                dy <- dim(y)
561                if(dx[2] != dy[1]) stop("non-matching dimensions")                if(dx[2] != dy[1]) stop("non-matching dimensions")
562                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]))
563            })  }
564    setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),
565              matdiagprod)
566    formals(matdiagprod) <- alist(x=, y=NULL)
567    setMethod("tcrossprod", signature(x = "matrix", y = "diagonalMatrix"),
568              matdiagprod)
569    
570  setMethod("%*%", signature(x = "dgeMatrix", y = "diagonalMatrix"),  gediagprod <- function(x, y) {
           function(x, y) {  
571                dx <- dim(x)                dx <- dim(x)
572                dy <- dim(y)                dy <- dim(y)
573                if(dx[2] != dy[1]) stop("non-matching dimensions")                if(dx[2] != dy[1]) stop("non-matching dimensions")
574                if(y@diag == "N")                if(y@diag == "N")
575                    x@x <- x@x * rep(y@x, each = dx[1])                    x@x <- x@x * rep(y@x, each = dx[1])
576                x                x
577            })  }
578    setMethod("%*%", signature(x= "dgeMatrix", y= "diagonalMatrix"), gediagprod)
579    setMethod("%*%", signature(x= "lgeMatrix", y= "diagonalMatrix"), gediagprod)
580    formals(gediagprod) <- alist(x=, y=NULL)
581    setMethod("tcrossprod", signature(x = "dgeMatrix", y = "diagonalMatrix"),
582              gediagprod)
583    setMethod("tcrossprod", signature(x = "lgeMatrix", y = "diagonalMatrix"),
584              gediagprod)
585    
586  ## crossprod {more of these}  ## crossprod {more of these}
587    
588  ## tcrossprod --- all are not yet there: do the dense ones here:  ## tcrossprod --- all are not yet there: do the dense ones here:
589    
590    setMethod("%*%", signature(x = "diagonalMatrix", y = "denseMatrix"),
591              function(x, y) if(x@diag == "U") y else x %*% as(y, "generalMatrix"))
592    setMethod("%*%", signature(x = "denseMatrix", y = "diagonalMatrix"),
593              function(x, y) if(y@diag == "U") x else as(x, "generalMatrix") %*% y)
594    
595    
596  ## FIXME:  ## FIXME:
597  ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),  ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),
598  ##        function(x, y = NULL) {  ##        function(x, y = NULL) {
599  ##           })  ##           })
600    
601  ## setMethod("tcrossprod", signature(x = "denseMatrix", y = "diagonalMatrix"),  Cspdiagprod <- function(x, y) {
602  ##        function(x, y = NULL) {      dx <- dim(x <- .Call(Csparse_diagU2N, x))
603  ##           })      dy <- dim(y)
604        if(dx[2] != dy[1]) stop("non-matching dimensions")
605        ind <- rep.int(seq_len(dx[2]), x@p[-1] - x@p[-dx[2]-1L])
606        if(y@diag == "N")
607            x@x <- x@x * y@x[ind]
608        x
609    }
610    
611    diagCspprod <- function(x, y) {
612        dx <- dim(x)
613        dy <- dim(y <- .Call(Csparse_diagU2N, y))
614        if(dx[2] != dy[1]) stop("non-matching dimensions")
615        if(x@diag == "N")
616            y@x <- y@x * x@x[y@i + 1L]
617        y
618    }
619    
620    setMethod("crossprod", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
621              function(x, y = NULL) diagCspprod(x, y))
622    
623  setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),  setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
624            function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })            function(x, y = NULL) diagCspprod(x, as(y, "CsparseMatrix")))
625    
626    ## Prefer calling diagCspprod to Cspdiagprod if going to transpose anyway
627    ##  x'y == (y'x)'
628    setMethod("crossprod", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
629              function(x, y = NULL) t(diagCspprod(y, x)))
630    
631  setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),  setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
632            function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })            function(x, y = NULL) t(diagCspprod(y, as(x, "Csparsematrix"))))
633    
634    setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
635              function(x, y = NULL) diagCspprod(x, t(y)))
636    
637  setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),  setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
638            function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })            function(x, y = NULL) diagCspprod(x, t(as(y, "CsparseMatrix"))))
639    
640    setMethod("tcrossprod", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
641              function(x, y = NULL) Cspdiagprod(x, y))
642    
643  setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),  setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
644            function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })            function(x, y = NULL) Cspdiagprod(as(x, "CsparseMatrix"), y))
645    
646    setMethod("%*%", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
647              function(x, y) diagCspprod(x, y))
648    
 ## FIXME?: In theory, this can be done *FASTER*, in some cases, via tapply1()  
649  setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),  setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),
650            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)!  
651    
652  setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),  setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),
653            function(x, y) x %*% as(y, "sparseMatrix"))            function(x, y) Cspdiagprod(as(x, "CsparseMatrix"), y))
654    
655    setMethod("%*%", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
656              function(x, y) Cspdiagprod(x, y))
657    
658    ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*
659    ##       do indeed work by going through sparse (and *not* ddense)!
660    
661  setMethod("solve", signature(a = "diagonalMatrix", b = "missing"),  setMethod("solve", signature(a = "diagonalMatrix", b = "missing"),
662            function(a, b, ...) {            function(a, b, ...) {
# Line 396  Line 678 
678  setMethod("solve", signature(a = "diagonalMatrix", b = "Matrix"),  setMethod("solve", signature(a = "diagonalMatrix", b = "Matrix"),
679            solveDiag)            solveDiag)
680    
681    ## Schur()  ---> ./eigen.R
682    
683    
684    
685  ### ---------------- diagonal  o  sparse  -----------------------------  ###---------------- <Ops> (<Arith>, <Logic>, <Compare> ) ----------------------
   
686    
687  ## Use function for several signatures, in order to evade  ## Use function for several signatures, in order to evade
688  ## ambiguous dispatch for "ddi", since there's also Arith(ddense., ddense.)  ## ambiguous dispatch for "ddi", since there's also Arith(ddense., ddense.)
689  diagOdiag <- function(e1,e2) { # result should also be diagonal  diagOdiag <- function(e1,e2) {
690        ## result should also be diagonal _ if possible _
691      r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"      r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"
692        ## Check what happens with non-diagonals, i.e. (0 o 0), (FALSE o 0), ...:
693        r00 <- callGeneric(if(is.numeric(e1@x)) 0 else FALSE,
694                           if(is.numeric(e2@x)) 0 else FALSE)
695        if(is0(r00)) { ##  r00 == 0 or FALSE --- result *is* diagonal
696      if(is.numeric(r)) {      if(is.numeric(r)) {
697          if(is.numeric(e2@x)) {          if(is.numeric(e2@x)) {
698              e2@x <- r; return(.diag.2N(e2)) }              e2@x <- r; return(.diag.2N(e2)) }
# Line 419  Line 706 
706      e1@x <- r      e1@x <- r
707      .diag.2N(e1)      .diag.2N(e1)
708  }  }
709        else { ## result not diagonal, but at least symmetric:
710            isNum <- (is.numeric(r) || is.numeric(r00))
711            isLog <- (is.logical(r) || is.logical(r00))
712    
713            Matrix.msg("exploding   <diag>  o  <diag>  into dense matrix")
714            d <- e1@Dim
715            n <- d[1]
716            stopifnot(length(r) == n)
717            xx <- as.vector(matrix(rbind(r, matrix(r00,n,n)), n,n))
718            newcl <-
719                paste(if(isNum) "d" else if(isLog) {
720                    if(!any(is.na(r)) && !any(is.na(r00))) "n" else "l"
721                } else stop("not yet implemented .. please report")
722                      ,
723                      "syMatrix", sep='')
724    
725            new(newcl, Dim = e1@Dim, Dimnames = e1@Dimnames, x = xx)
726        }
727    }
728    
729    ### This would be *the* way, but we get tons of "ambiguous method dispatch"
730    ## we use this hack instead of signature  x = "diagonalMatrix" :
731    diCls <- names(getClass("diagonalMatrix")@subclasses)
732    if(FALSE) {
733  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),
734            diagOdiag)            diagOdiag)
735  ## These two are just for method disambiguation:  } else { ## These are just for method disambiguation:
736  setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "diagonalMatrix"),      for(c1 in diCls)
737            diagOdiag)          for(c2 in diCls)
738  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ddiMatrix"),              setMethod("Ops", signature(e1 = c1, e2 = c2), diagOdiag)
739            diagOdiag)  }
740    
741    ## FIXME:    diagonal  o  triangular  |-->  triangular
742    ## -----     diagonal  o  symmetric   |-->  symmetric
743    ##    {also when other is sparse: do these "here" --
744    ##     before conversion to sparse, since that loses "diagonality"}
745    
746  ## For almost everything else, diag* shall be treated "as sparse" :  ## For almost everything else, diag* shall be treated "as sparse" :
747  ## These are cheap implementations via coercion  ## These are cheap implementations via coercion
748    
749  ## for disambiguation  ## For disambiguation --- define this for "sparseMatrix" , then for "ANY";
750  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "sparseMatrix"),  ## and because we can save an .M.kind() call, we use this explicit
751            function(e1,e2) callGeneric(as(e1, "sparseMatrix"), e2))  ## "hack" for all diagonalMatrix *subclasses* instead of just "diagonalMatrix" :
752  setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "diagonalMatrix"),  ##
753            function(e1,e2) callGeneric(e1, as(e2, "sparseMatrix")))  ## ddi*:
754  ## in general:  setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "sparseMatrix"),
755  setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ANY"),            function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2))
756            function(e1,e2) callGeneric(as(e1,"sparseMatrix"), e2))  setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ddiMatrix"),
757  setMethod("Ops", signature(e1 = "ANY", e2 = "diagonalMatrix"),            function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "d")))
758            function(e1,e2) callGeneric(e1, as(e2,"sparseMatrix")))  ## ldi*
759    setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "sparseMatrix"),
760              function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2))
761    setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ldiMatrix"),
762              function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "l")))
763    
764    ## Ops:  Arith  --> numeric : "dMatrix"
765    ##       Compare --> logical
766    ##       Logic   --> logical: "lMatrix"
767    
768    ##  other = "numeric" : stay diagonal if possible
769    ## ddi*: Arith: result numeric, potentially ddiMatrix
770    setMethod("Arith", signature(e1 = "ddiMatrix", e2 = "numeric"),
771              function(e1,e2) {
772                  n <- e1@Dim[1]; nsq <- n^2
773                  f0 <- callGeneric(0, 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(1, 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+1L)*(0:(n-1L))]
783                      return(e1)
784                  }
785                  callGeneric(diag2tT.u(e1,e2, "d"), e2)
786              })
787    
788    setMethod("Arith", signature(e1 = "numeric", e2 = "ddiMatrix"),
789              function(e1,e2) {
790                  n <- e2@Dim[1]; nsq <- n^2
791                  f0 <- callGeneric(e1, 0)
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, 1)) != 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+1L)*(0:(n-1L))]
801                      return(e2)
802                  }
803                  callGeneric(e1, diag2tT.u(e2,e1, "d"))
804              })
805    
806    ## ldi* Arith --> result numeric, potentially ddiMatrix
807    setMethod("Arith", signature(e1 = "ldiMatrix", e2 = "numeric"),
808              function(e1,e2) {
809                  n <- e1@Dim[1]; nsq <- n^2
810                  f0 <- callGeneric(0, e2)
811                  if(all(is0(f0))) { # remain diagonal
812                      L1 <- (le <- length(e2)) == 1L
813                      if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
814                      if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
815                          e1@diag <- "N"
816                          if(L1) r <- rep.int(r, n)
817                      } else
818                          r <- callGeneric(e1@x, e2)
819                      e1 <- copyClass(e1, "ddiMatrix", c("diag", "Dim", "Dimnames"))
820                      e1@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
821                      return(e1)
822                  }
823                  callGeneric(diag2tT.u(e1,e2, "d"), e2)
824              })
825    
826    setMethod("Arith", signature(e1 = "numeric", e2 = "ldiMatrix"),
827              function(e1,e2) {
828                  n <- e2@Dim[1]; nsq <- n^2
829                  f0 <- callGeneric(e1, 0)
830                  if(all(is0(f0))) { # remain diagonal
831                      L1 <- (le <- length(e1)) == 1L
832                      if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
833                      if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
834                          e2@diag <- "N"
835                          if(L1) r <- rep.int(r, n)
836                      } else
837                          r <- callGeneric(e1, e2@x)
838                      e2 <- copyClass(e2, "ddiMatrix", c("diag", "Dim", "Dimnames"))
839                      e2@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
840                      return(e2)
841                  }
842                  callGeneric(e1, diag2tT.u(e2,e1, "d"))
843              })
844    
845    ## ddi*: for "Ops" without Arith --> result logical, potentially ldi
846    setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "numeric"),
847              function(e1,e2) {
848                  n <- e1@Dim[1]; nsq <- n^2
849                  f0 <- callGeneric(0, e2)
850                  if(all(is0(f0))) { # remain diagonal
851                      L1 <- (le <- length(e2)) == 1L
852                      if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
853                      if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
854                          e1@diag <- "N"
855                          if(L1) r <- rep.int(r, n)
856                      } else
857                          r <- callGeneric(e1@x, e2)
858                      e1 <- copyClass(e1, "ldiMatrix", c("diag", "Dim", "Dimnames"))
859                      e1@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
860                      return(e1)
861                  }
862                  callGeneric(diag2tT.u(e1,e2, "l"), e2)
863              })
864    
865    setMethod("Ops", signature(e1 = "numeric", e2 = "ddiMatrix"),
866              function(e1,e2) {
867                  n <- e2@Dim[1]; nsq <- n^2
868                  f0 <- callGeneric(e1, 0)
869                  if(all(is0(f0))) { # remain diagonal
870                      L1 <- (le <- length(e1)) == 1L
871                      if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
872                      if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
873                          e2@diag <- "N"
874                          if(L1) r <- rep.int(r, n)
875                      } else
876                          r <- callGeneric(e1, e2@x)
877                      e2 <- copyClass(e2, "ldiMatrix", c("diag", "Dim", "Dimnames"))
878                      e2@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
879                      return(e2)
880                  }
881                  callGeneric(e1, diag2tT.u(e2,e1, "l"))
882              })
883    
884    ## ldi*: for "Ops" without Arith --> result logical, potentially ldi
885    setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "numeric"),
886              function(e1,e2) {
887                  n <- e1@Dim[1]; nsq <- n^2
888                  f0 <- callGeneric(FALSE, e2)
889                  if(all(is0(f0))) { # remain diagonal
890                      L1 <- (le <- length(e2)) == 1L
891                      if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
892                      if(e1@diag == "U" && any((r <- callGeneric(TRUE, e2)) != 1)) {
893                          e1@diag <- "N"
894                          if(L1) r <- rep.int(r, n)
895                      } else
896                          r <- callGeneric(e1@x, e2)
897                      e1@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
898                      return(e1)
899                  }
900                  callGeneric(diag2tT.u(e1,e2, "l"), e2)
901              })
902    
903    setMethod("Ops", signature(e1 = "numeric", e2 = "ldiMatrix"),
904              function(e1,e2) {
905                  n <- e2@Dim[1]; nsq <- n^2
906                  f0 <- callGeneric(e1, FALSE)
907                  if(all(is0(f0))) { # remain diagonal
908                      L1 <- (le <- length(e1)) == 1L
909                      if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
910                      if(e2@diag == "U" && any((r <- callGeneric(e1, TRUE)) != 1)) {
911                          e2@diag <- "N"
912                          if(L1) r <- rep.int(r, n)
913                      } else
914                          r <- callGeneric(e1, e2@x)
915                      e2@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
916                      return(e2)
917                  }
918                  callGeneric(e1, diag2tT.u(e2,e1, "l"))
919              })
920    
921    
922    
923    ## Not {"sparseMatrix", "numeric} :  {"denseMatrix", "matrix", ... }
924    for(other in c("ANY", "Matrix", "dMatrix")) {
925        ## ddi*:
926        setMethod("Ops", signature(e1 = "ddiMatrix", e2 = other),
927                  function(e1,e2) callGeneric(diag2tT.u(e1,e2, "d"), e2))
928        setMethod("Ops", signature(e1 = other, e2 = "ddiMatrix"),
929                  function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "d")))
930        ## ldi*:
931        setMethod("Ops", signature(e1 = "ldiMatrix", e2 = other),
932                  function(e1,e2) callGeneric(diag2tT.u(e1,e2, "l"), e2))
933        setMethod("Ops", signature(e1 = other, e2 = "ldiMatrix"),
934                  function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "l")))
935    }
936    
937    ## Direct subclasses of "denseMatrix": currently ddenseMatrix, ldense... :
938    dense.subCl <- local({ dM.scl <- getClass("denseMatrix")@subclasses
939                           names(dM.scl)[sapply(dM.scl, slot, "distance") == 1] })
940    for(DI in diCls) {
941        for(c2 in c(dense.subCl, "Matrix")) {
942            for(Fun in c("*", "^", "&")) {
943                setMethod(Fun, signature(e1 = DI, e2 = c2),
944                          function(e1,e2) callGeneric(e1, Diagonal(x = diag(e2))))
945                setMethod(Fun, signature(e1 = c2, e2 = DI),
946                          function(e1,e2) callGeneric(Diagonal(x = diag(e1)), e2))
947            }
948            ## NB: This arguably implicitly uses  0/0 :== 0  to keep diagonality
949            for(Fun in c("%%", "%/%", "/")) {
950                setMethod(Fun, signature(e1 = DI, e2 = c2),
951                          function(e1,e2) callGeneric(e1, Diagonal(x = diag(e2))))
952            }
953        }
954    }
955    
956    
957    ### "Summary" : "max"   "min"   "range" "prod"  "sum"   "any"   "all"
958    ### ----------   the last 4: separately here
959    for(cl in diCls) {
960    setMethod("any", cl,
961              function (x, ..., na.rm) {
962                  if(any(x@Dim == 0)) FALSE
963                  else if(x@diag == "U") TRUE else any(x@x, ..., na.rm = na.rm)
964              })
965    setMethod("all",  cl, function (x, ..., na.rm) {
966        n <- x@Dim[1]
967        if(n >= 2) FALSE
968        else if(n == 0 || x@diag == "U") TRUE
969        else all(x@x, ..., na.rm = na.rm)
970    })
971    setMethod("prod", cl, function (x, ..., na.rm) {
972        n <- x@Dim[1]
973        if(n >= 2) 0
974        else if(n == 0 || x@diag == "U") 1
975        else ## n == 1, diag = "N" :
976            prod(x@x, ..., na.rm = na.rm)
977    })
978    
979    setMethod("sum", cl,
980              function(x, ..., na.rm) {
981                  r <- sum(x@x, ..., na.rm = na.rm)# double or integer, correctly
982                  if(x@diag == "U" && !is.na(r)) r + x@Dim[1] else r
983              })
984    }
985    
986    ## The remaining ones are  max, min, range :
987    
988    setMethod("Summary", "ddiMatrix",
989              function(x, ..., na.rm) {
990                  if(any(x@Dim == 0)) callGeneric(numeric(0), ..., na.rm=na.rm)
991                  else if(x@diag == "U")
992                      callGeneric(x@x, 0, 1, ..., na.rm=na.rm)
993                  else callGeneric(x@x, 0, ..., na.rm=na.rm)
994              })
995    setMethod("Summary", "ldiMatrix",
996              function(x, ..., na.rm) {
997                  if(any(x@Dim == 0)) callGeneric(logical(0), ..., na.rm=na.rm)
998                  else if(x@diag == "U")
999                      callGeneric(x@x, FALSE, TRUE, ..., na.rm=na.rm)
1000                  else callGeneric(x@x, FALSE, ..., na.rm=na.rm)
1001              })
1002    
1003    
1004    
# Line 455  Line 1013 
1013      invisible(x)      invisible(x)
1014  }  }
1015    
1016    ## somewhat consistent with "print" for sparseMatrix :
1017    setMethod("print", signature(x = "diagonalMatrix"), prDiag)
1018    
1019  setMethod("show", signature(object = "diagonalMatrix"),  setMethod("show", signature(object = "diagonalMatrix"),
1020            function(object) {            function(object) {
1021                d <- dim(object)                d <- dim(object)
1022                cl <- class(object)                cl <- class(object)
1023                cat(sprintf('%d x %d diagonal matrix of class "%s"\n',                cat(sprintf('%d x %d diagonal matrix of class "%s"',
1024                            d[1], d[2], cl))                            d[1], d[2], cl))
1025                  if(d[1] < 50) {
1026                      cat("\n")
1027                prDiag(object)                prDiag(object)
1028                  } else {
1029                      cat(", with diagonal entries\n")
1030                      show(diag(object))
1031                      invisible(object)
1032                  }
1033            })            })

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

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