# SCM Repository

[matrix] Diff of /pkg/R/diagMatrix.R
 [matrix] / pkg / R / diagMatrix.R

# Diff of /pkg/R/diagMatrix.R

revision 1331, Sat Jul 22 17:59:53 2006 UTC revision 1799, Sat Mar 24 14:54:00 2007 UTC
# Line 1  Line 1
1    #### All methods for "diagonalMatrix" and its subclasses,
2    ####  currently "ddiMatrix", "ldiMatrix"
3
4  ## Purpose: Constructor of diagonal matrices -- ~= diag() ,  ## Purpose: Constructor of diagonal matrices -- ~= diag() ,
5  ##          but *not* diag() extractor!  ##          but *not* diag() extractor!
6  Diagonal <- function(n, x = NULL)  Diagonal <- function(n, x = NULL)
# Line 10  Line 13
13          n <- as.integer(n)          n <- as.integer(n)
14      }      }
15
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)          stopifnot(length(x) == n)
20          if(is.logical(x))          if(is.logical(x))
21              cl <- "ldiMatrix"              cl <- "ldiMatrix"
22          else {          else if(is.numeric(x)) {
23              cl <- "ddiMatrix"              cl <- "ddiMatrix"
24              x <- as.numeric(x)              x <- as.numeric(x)
25          }          }
26            else if(is.complex(x)) {
27                cl <- "zdiMatrix"  # will not yet work
28            } else stop("'x' has invalid data type")
29          new(cl, Dim = c(n,n), diag = "N", x = x)          new(cl, Dim = c(n,n), diag = "N", x = x)
30      }      }
31  }  }
32
33  setAs("diagonalMatrix", "triangularMatrix",  ### This is modified from a post of Bert Gunter to R-help on  1 Sep 2005.
34        function(from) {  ### Bert's code built on a post by Andy Liaw who most probably was influenced
35            n <- from@Dim[1]  ### by earlier posts, notably one by Scott Chasalow on S-news, 16 Jan 2002
36            i <- seq(length = n)  ### who posted his bdiag() function written in December 1995.
37            x <- from@x
38            new(if(is.numeric(x)) "dtTMatrix" else "ltTMatrix",  bdiag <- function(...) {
39        if(nargs() == 0) return(new("dgCMatrix"))
40        ## else :
41        mlist <- if (nargs() == 1) as.list(...) else list(...)
42        dims <- sapply(mlist, dim)
43        ## make sure we had all matrices:
44        if(!(is.matrix(dims) && nrow(dims) == 2))
45            stop("some arguments are not matrices")
46        csdim <- rbind(rep.int(0:0, 2),
47                       apply(sapply(mlist, dim), 1, cumsum))
48        ret <- new("dgTMatrix", Dim = as.integer(csdim[nrow(csdim),]))
50        for(i in seq_along(mlist)) {
51            indx <- apply(csdim[i:(i+1),] + add1, 2, function(n) n[1]:n[2])
52            if(is.null(dim(indx))) ## non-square matrix
53                ret[indx[[1]],indx[[2]]] <- mlist[[i]]
54            else ## square matrix
55                ret[indx[,1],indx[,2]] <- mlist[[i]]
56        }
57        ## slightly debatable if we really should return Csparse.. :
58        as(ret, "CsparseMatrix")
59    }
60
61    diag2T <- function(from) {
62        i <- if(from@diag == "U") integer(0) else seq_len(from@Dim[1]) - 1:1
63        new(paste(.M.kind(from), "tTMatrix", sep=''),
64                diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,                diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,
65                x = x, i = i, j = i)          x = from@x, # <- ok for diag = "U" and "N" (!)
66            })          i = i, j = i)
67    }
68
69    setAs("diagonalMatrix", "triangularMatrix", diag2T)
70    setAs("diagonalMatrix", "sparseMatrix", diag2T)
71    ## is better than this:
72    ## setAs("diagonalMatrix", "sparseMatrix",
73    ##       function(from)
74    ##        as(from, if(is(from, "dMatrix")) "dgCMatrix" else "lgCMatrix"))
75    setAs("diagonalMatrix", "CsparseMatrix",
76          function(from) as(diag2T(from), "CsparseMatrix"))
77
78  setAs("diagonalMatrix", "matrix",  setAs("diagonalMatrix", "matrix",
79        function(from) {        function(from) {
# Line 42  Line 83
83                 nrow = n, ncol = n)                 nrow = n, ncol = n)
84        })        })
85
86  setAs("diagonalMatrix", "generalMatrix",  setAs("diagonalMatrix", "generalMatrix", # prefer sparse:
87        function(from) {        function(from) as(from, paste(.M.kind(from), "gCMatrix", sep='')))
88            x <- as(from, "matrix")
89            as(x,  .diag.x <- function(m) {
90               if(is.logical(x)) "lgeMatrix"      if(m@diag == "U")
91  ## Not yet:          rep.int(if(is.numeric(m@x)) 1. else TRUE,
92  ##              else if(is.complex(x)) "zgeMatrix"                  m@Dim[1])
93  ##              else if(is.integer(x)) "igeMatrix"      else m@x
94               else "dgeMatrix")  }
95        })
96    .diag.2N <- function(m) {
97        if(m@diag == "U") m@diag <- "N"
98        m
99    }
100
101    ## given the above, the following  4  coercions should be all unneeded;
102    ## we prefer triangular to general:
103  setAs("ddiMatrix", "dgTMatrix",  setAs("ddiMatrix", "dgTMatrix",
104        function(from) {        function(from) {
105              .Deprecated("as(, \"sparseMatrix\")")
106            n <- from@Dim[1]            n <- from@Dim[1]
107            i <- seq(length = n) - 1:1            i <- seq_len(n) - 1:1
108            new("dgTMatrix", i = i, j = i,            new("dgTMatrix", i = i, j = i, x = .diag.x(from),
x = if(from@diag == "U") rep(1,n) else from@x,
109                Dim = c(n,n), Dimnames = from@Dimnames) })                Dim = c(n,n), Dimnames = from@Dimnames) })
110
111  setAs("ddiMatrix", "dgCMatrix",  setAs("ddiMatrix", "dgCMatrix",
112        function(from) as(as(from, "dgTMatrix"), "dgCMatrix"))        function(from) as(as(from, "sparseMatrix"), "dgCMatrix"))
113
114  setAs("ldiMatrix", "lgTMatrix",  setAs("ldiMatrix", "lgTMatrix",
115        function(from) {        function(from) {
116              .Deprecated("as(, \"sparseMatrix\")")
117            n <- from@Dim[1]            n <- from@Dim[1]
118            i <- (if(from@diag == "U") seq(length = n) else which(from@x)) - 1:1            if(from@diag == "U") { # unit-diagonal
119            new("lgTMatrix", i = i, j = i,                x <- rep.int(TRUE, n)
120                  i <- seq_len(n) - 1:1
121              } else { # "normal"
122                  nz <- nz.NA(from@x, na. = TRUE)
123                  x <- from@x[nz]
124                  i <- which(nz) - 1:1
125              }
126              new("lgTMatrix", i = i, j = i, x = x,
127                Dim = c(n,n), Dimnames = from@Dimnames) })                Dim = c(n,n), Dimnames = from@Dimnames) })
128
129  setAs("ldiMatrix", "lgCMatrix",  setAs("ldiMatrix", "lgCMatrix",
130        function(from) as(as(from, "lgTMatrix"), "lgCMatrix"))        function(from) as(as(from, "lgTMatrix"), "lgCMatrix"))
131
setAs("diagonalMatrix", "sparseMatrix",
function(from)
as(from, if(is(from, "dMatrix")) "dgCMatrix" else "lgCMatrix"))
132
133    if(FALSE) # now have faster  "ddense" -> "dge"
134  setAs("ddiMatrix", "dgeMatrix",  setAs("ddiMatrix", "dgeMatrix",
135        function(from) as(as(from, "matrix"), "dgeMatrix"))        function(from) as(as(from, "matrix"), "dgeMatrix"))
136
# Line 95  Line 148
148                cl <- "ddiMatrix"                cl <- "ddiMatrix"
149                uni <- all(x == 1)                uni <- all(x == 1)
150                storage.mode(x) <- "double"                storage.mode(x) <- "double"
151            }            } ## TODO: complex
152            new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",            new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
153                x = if(uni) x[FALSE] else x)                x = if(uni) x[FALSE] else x)
154        })        })
# Line 120  Line 173
173                x = if(uni) x[FALSE] else x)                x = if(uni) x[FALSE] else x)
174        })        })
175
176
177    setMethod("diag", signature(x = "diagonalMatrix"),
178              function(x = 1, nrow, ncol = n) .diag.x(x))
179
180
181    subDiag <- function(x, i, j, drop) {
182        x <- as(x, "sparseMatrix")
183        x <- if(missing(i))
184            x[, j, drop=drop]
185        else if(missing(j))
186            x[i, , drop=drop]
187        else
188            x[i,j, drop=drop]
189        if(isDiagonal(x)) as(x, "diagonalMatrix") else x
190    }
191
192    setMethod("[", signature(x = "diagonalMatrix", i = "index",
193                             j = "index", drop = "logical"), subDiag)
194    setMethod("[", signature(x = "diagonalMatrix", i = "index",
195                            j = "missing", drop = "logical"),
196              function(x, i, drop) subDiag(x, i=i, drop=drop))
197    setMethod("[", signature(x = "diagonalMatrix", i = "missing",
198                             j = "index", drop = "logical"),
199              function(x, j, drop) subDiag(x, j=j, drop=drop))
200
201    ## When you assign to a diagonalMatrix, the result should be
202    ## diagonal or sparse ---
203    ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch
204    replDiag <- function(x, i, j, value) {
205        x <- as(x, "sparseMatrix")
206        if(missing(i))
207            x[, j] <- value
208        else if(missing(j))
209            x[i, ] <- value
210        else
211            x[i,j] <- value
212        if(isDiagonal(x)) as(x, "diagonalMatrix") else x
213    }
214
215    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
216                                    j = "index", value = "replValue"), replDiag)
217    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
218                                    j = "missing", value = "replValue"),
219                     function(x, i, value) replDiag(x, i=i, value=value))
220    setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",
221                                    j = "index", value = "replValue"),
222                     function(x, j, value) replDiag(x, j=j, value=value))
223
224
225  setMethod("t", signature(x = "diagonalMatrix"),  setMethod("t", signature(x = "diagonalMatrix"),
226            function(x) { x@Dimnames <- x@Dimnames[2:1] ; x })            function(x) { x@Dimnames <- x@Dimnames[2:1] ; x })
227
# Line 130  Line 232
232  setMethod("isSymmetric", signature(object = "diagonalMatrix"),  setMethod("isSymmetric", signature(object = "diagonalMatrix"),
233            function(object) TRUE)            function(object) TRUE)
234
235  setMethod("diag", signature(x = "diagonalMatrix"),  setMethod("chol", signature(x = "ddiMatrix"),# pivot = "ANY"
236            function(x = 1, nrow, ncol = n) {            function(x, pivot) {
237               if(x@diag == "U")                if(any(x@x < 0)) stop("chol() is undefined for diagonal matrix with negative entries")
238                   rep.int(if(is.logical(x@x)) TRUE else 1, x@Dim[1])                x@x <- sqrt(x@x)
239               else x@x                x
240            })            })
241    ## chol(L) is L for logical diagonal:
242    setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot) x)
243
244  setMethod("!", "ldiMatrix", function(e1) {  setMethod("!", "ldiMatrix", function(e1) {
245      if(e1@diag == "N")      if(e1@diag == "N")
# Line 144  Line 248
248          e1@diag <- "N"          e1@diag <- "N"
249          e1@x <- rep.int(FALSE, e1@Dim[1])          e1@x <- rep.int(FALSE, e1@Dim[1])
250      }      }
251      x      e1
252  })  })
253
254  ## Basic Matrix Multiplication {many more to add}  ## Basic Matrix Multiplication {many more to add}
255    ##       ---------------------
256  ## FIXME: extend this for 'ldi', i.e. do "diagonalMatrix"  ## Note that "ldi" logical are treated as numeric
257  diagdiagprod <- function(x, y) {  diagdiagprod <- function(x, y) {
258      if(any(dim(x) != dim(y))) stop("non-matching dimensions")      if(any(dim(x) != dim(y))) stop("non-matching dimensions")
259      if(x@diag != "U") {      if(x@diag != "U") {
260          if(y@diag != "U") x@x <- x@x * y@x          if(y@diag != "U") {
261                nx <- x@x * y@x
262                if(is.numeric(nx) && !is.numeric(x@x))
263                    x <- as(x, "dMatrix")
264                x@x <- as.numeric(nx)
265            }
266          return(x)          return(x)
267      } else ## x is unit diagonal      } else ## x is unit diagonal
268      return(y)      return(y)
269  }  }
270
271  setMethod("%*%", signature(x = "ddiMatrix", y = "ddiMatrix"),  setMethod("%*%", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
272            diagdiagprod, valueClass = "ddiMatrix")            diagdiagprod, valueClass = "ddiMatrix")
273
274  formals(diagdiagprod) <- alist(x=, y=NULL)  formals(diagdiagprod) <- alist(x=, y=x)
275  setMethod("crossprod", signature(x = "ddiMatrix", y = "ddiMatrix"),  setMethod("crossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
276            diagdiagprod, valueClass = "ddiMatrix")            diagdiagprod, valueClass = "ddiMatrix")
277  setMethod("tcrossprod", signature(x = "ddiMatrix", y = "ddiMatrix"),  setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
278              diagdiagprod, valueClass = "ddiMatrix")
279    setMethod("crossprod", signature(x = "diagonalMatrix", y = "missing"),
280              diagdiagprod, valueClass = "ddiMatrix")
281    setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "missing"),
282            diagdiagprod, valueClass = "ddiMatrix")            diagdiagprod, valueClass = "ddiMatrix")
283
284
# Line 182  Line 295
295  formals(diagmatprod) <- alist(x=, y=NULL)  formals(diagmatprod) <- alist(x=, y=NULL)
296  setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),  setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),
297            diagmatprod)            diagmatprod)
298    setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "matrix"),
299              diagmatprod)
300
301  diagdgeprod <- function(x, y) {  diagdgeprod <- function(x, y) {
302      dx <- dim(x)      dx <- dim(x)
# Line 202  Line 317
317                dx <- dim(x)                dx <- dim(x)
318                dy <- dim(y)                dy <- dim(y)
319                if(dx[2] != dy[1]) stop("non-matching dimensions")                if(dx[2] != dy[1]) stop("non-matching dimensions")
320                as(if(y@diag == "U") x else x * rep.int(y@x, dx[1]), "Matrix")                as(if(y@diag == "U") x else x * rep(y@x, each = dx[1]), "Matrix")
321            })            })
322
323  setMethod("%*%", signature(x = "dgeMatrix", y = "diagonalMatrix"),  setMethod("%*%", signature(x = "dgeMatrix", y = "diagonalMatrix"),
# Line 211  Line 326
326                dy <- dim(y)                dy <- dim(y)
327                if(dx[2] != dy[1]) stop("non-matching dimensions")                if(dx[2] != dy[1]) stop("non-matching dimensions")
328                if(y@diag == "N")                if(y@diag == "N")
329                    x@x <- x@x * rep.int(y@x, dx[1])                    x@x <- x@x * rep(y@x, each = dx[1])
330                x                x
331            })            })
332
# Line 228  Line 343
343  ##        function(x, y = NULL) {  ##        function(x, y = NULL) {
344  ##           })  ##           })
345
346    setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
347              function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })
348
349  ### ---------------- diagonal  o   sparse  -----------------------------  setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
350              function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })
351
352  ## These are cheap implementations via coercion  setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
353              function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })
354
355  ## FIXME?: In theory, this can be done *FASTER*, in some cases, via tapply1()  setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
356              function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })
357
358
359    ## FIXME?: In theory, this can be done *FASTER*, in some cases, via tapply1()
360  setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),  setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),
361            function(x, y) as(x, "sparseMatrix") %*% y)            function(x, y) as(x, "sparseMatrix") %*% y)
362    ## NB: The previous is *not* triggering for  "ddi" o "dgC" (= distance 3)
363    ##     since there's a "ddense" o "Csparse" at dist. 2 => triggers first.
364    ## ==> do this:
365    setMethod("%*%", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
366              function(x, y) as(x, "CsparseMatrix") %*% y)
367    setMethod("%*%", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
368              function(x, y) x %*% as(y, "CsparseMatrix"))
369    ## NB: this is *not* needed for Tsparse & Rsparse
370    ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*
371    ##       do indeed work by going through sparse (and *not* ddense)!
372
373  setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),  setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),
374            function(x, y) x %*% as(y, "sparseMatrix"))            function(x, y) x %*% as(y, "sparseMatrix"))
375
setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })
376
377  setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),  setMethod("solve", signature(a = "diagonalMatrix", b = "missing"),
378            function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })            function(a, b, ...) {
379                  a@x <- 1/ a@x
380                  a@Dimnames <- a@Dimnames[2:1]
381                  a
382              })
383
384    solveDiag <- function(a, b, ...) {
385        if((n <- a@Dim[1]) != nrow(b))
386            stop("incompatible matrix dimensions")
387        ## trivially invert a 'in place' and multiply:
388        a@x <- 1/ a@x
389        a@Dimnames <- a@Dimnames[2:1]
390        a %*% b
391    }
392    setMethod("solve", signature(a = "diagonalMatrix", b = "matrix"),
393              solveDiag)
394    setMethod("solve", signature(a = "diagonalMatrix", b = "Matrix"),
395              solveDiag)
396
setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })
397
setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })
398
399
400    ### ---------------- diagonal  o  sparse  -----------------------------
401
402
403    ## Use function for several signatures, in order to evade
404    ## ambiguous dispatch for "ddi", since there's also Arith(ddense., ddense.)
405    diagOdiag <- function(e1,e2) { # result should also be diagonal
406        r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"
407        if(is.numeric(r)) {
408            if(is.numeric(e2@x)) {
409                e2@x <- r; return(.diag.2N(e2)) }
410            if(!is.numeric(e1@x))
411                ## e.g. e1, e2 are logical;
412                e1 <- as(e1, "dMatrix")
413        }
414        else if(is.logical(r))
415            e1 <- as(e1, "lMatrix")
416        else stop("intermediate 'r' is of type", typeof(r))
417        e1@x <- r
418        .diag.2N(e1)
419    }
420
421    setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),
422              diagOdiag)
423    ## These two are just for method disambiguation:
424    setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "diagonalMatrix"),
425              diagOdiag)
426    setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ddiMatrix"),
427              diagOdiag)
428
429    ## For almost everything else, diag* shall be treated "as sparse" :
430    ## These are cheap implementations via coercion
431
432    ## for disambiguation
433    setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "sparseMatrix"),
434              function(e1,e2) callGeneric(as(e1, "sparseMatrix"), e2))
435    setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "diagonalMatrix"),
436              function(e1,e2) callGeneric(e1, as(e2, "sparseMatrix")))
437    ## in general:
438    setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ANY"),
439              function(e1,e2) callGeneric(as(e1,"sparseMatrix"), e2))
440    setMethod("Ops", signature(e1 = "ANY", e2 = "diagonalMatrix"),
441              function(e1,e2) callGeneric(e1, as(e2,"sparseMatrix")))
442
443
444
445  ## similar to prTriang() in ./Auxiliaries.R :  ## similar to prTriang() in ./Auxiliaries.R :
# Line 268  Line 454
454  }  }
455
456  setMethod("show", signature(object = "diagonalMatrix"),  setMethod("show", signature(object = "diagonalMatrix"),
457            function(object) prDiag(object))            function(object) {
458                  d <- dim(object)
459                  cl <- class(object)
460                  cat(sprintf('%d x %d diagonal matrix of class "%s"\n',
461                              d[1], d[2], cl))
462                  prDiag(object)
463              })

Legend:
 Removed from v.1331 changed lines Added in v.1799