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

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

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