SCM

SCM Repository

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

Diff of /pkg/R/Matrix.R

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

revision 1455, Mon Aug 28 15:35:44 2006 UTC revision 2185, Sat Apr 26 20:33:16 2008 UTC
# Line 3  Line 3 
3    
4  ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)  ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)
5    
6  setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))  setAs("Matrix", "sparseMatrix", function(from) as(from, "CsparseMatrix"))
7    setAs("Matrix", "CsparseMatrix", function(from) as_Csparse(from))
8  setAs("Matrix", "denseMatrix",  function(from) as_dense(from))  setAs("Matrix", "denseMatrix",  function(from) as_dense(from))
9    
10    ## Maybe TODO:
11    ## setAs("Matrix", "nMatrix", function(from) ....)
12    
13    ## Most of these work; this is a last resort:
14    setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:
15          function(from) .bail.out.2("coerce", class(from), class(to)))
16    setAs(from = "matrix", to = "Matrix", function(from) Matrix(from))
17    
18  ## ## probably not needed eventually:  ## ## probably not needed eventually:
19  ## setAs(from = "ddenseMatrix", to = "matrix",  ## setAs(from = "ddenseMatrix", to = "matrix",
20  ##       function(from) {  ##       function(from) {
# Line 19  Line 28 
28  setMethod("as.array",  signature(x = "Matrix"), function(x) as(x, "matrix"))  setMethod("as.array",  signature(x = "Matrix"), function(x) as(x, "matrix"))
29    
30  ## head and tail apply to all Matrix objects for which subscripting is allowed:  ## head and tail apply to all Matrix objects for which subscripting is allowed:
31  ## if(paste(R.version$major, R.version$minor, sep=".") < "2.4") {  setMethod("head", signature(x = "Matrix"), utils::head.matrix)
32      setMethod("head", signature(x = "Matrix"), utils:::head.matrix)  setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
33      setMethod("tail", signature(x = "Matrix"), utils:::tail.matrix)  
34  ## } else { # R 2.4.0 and newer  setMethod("drop", signature(x = "Matrix"),
35  ##     setMethod("head", signature(x = "Matrix"), utils::head.matrix)            function(x) if(all(dim(x) != 1)) x else drop(as(x, "matrix")))
 ##     setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)  
 ## }  
36    
37  ## slow "fall back" method {subclasses should have faster ones}:  ## slow "fall back" method {subclasses should have faster ones}:
38  setMethod("as.vector", signature(x = "Matrix", mode = "missing"),  setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
39            function(x) as.vector(as(x, "matrix")))            function(x, mode) as.vector(as(x, "matrix"), mode))
40    
41  ## mainly need these for "dMatrix" or "lMatrix" respectively, but why not general:  ## mainly need these for "dMatrix" or "lMatrix" respectively, but why not general:
42  setMethod("as.numeric", signature(x = "Matrix"),  setMethod("as.numeric", signature(x = "Matrix"),
# Line 37  Line 44 
44  setMethod("as.logical", signature(x = "Matrix"),  setMethod("as.logical", signature(x = "Matrix"),
45            function(x, ...) as.logical(as.vector(x)))            function(x, ...) as.logical(as.vector(x)))
46    
47    setMethod("mean", signature(x = "Matrix"),
48              function(x, trim = 0, ...) ## TODO: provide 'sparseMatrix method
49              if(is0(trim)) sum(x, ...) / length(x)
50              else mean(as.numeric(x), ...))
51    
52    setMethod("cov2cor", signature(V = "Matrix"),
53              function(V) { ## was as(cov2cor(as(V, "matrix")), "dpoMatrix"))
54                  r <- V
55                  p <- (d <- dim(V))[1]
56                  if(p != d[2]) stop("'V' is not a square matrix")
57                  Is <- sqrt(1/diag(V)) # diag( 1/sigma_i )
58                  if(any(!is.finite(Is)))
59                      warning("diag(.) had 0 or NA entries; non-finite result is doubtful")
60                  Is <- Diagonal(x = Is)
61                  r <- Is %*% V %*% Is
62                  r[cbind(1L:p,1L:p)] <- 1 # exact in diagonal
63                  as(forceSymmetric(r), "dpoMatrix")
64              })
65    
66  ## Note that isSymmetric is *not* exported  ## "base" has an isSymmetric() S3-generic since R 2.3.0
 ## but that "base" has an isSymmetric() S3-generic since R 2.3.0  
67  setMethod("isSymmetric", signature(object = "symmetricMatrix"),  setMethod("isSymmetric", signature(object = "symmetricMatrix"),
68            function(object,tol) TRUE)            function(object, ...) TRUE)
69  setMethod("isSymmetric", signature(object = "triangularMatrix"),  setMethod("isSymmetric", signature(object = "triangularMatrix"),
70            ## TRUE iff diagonal:            ## TRUE iff diagonal:
71            function(object,tol) isDiagonal(object))            function(object, ...) isDiagonal(object))
   
 if(paste(R.version$major, R.version$minor, sep=".") < "2.3")  
     ## need a "matrix" method as in R 2.3 and later  
     setMethod("isSymmetric", signature(object = "matrix"),  
               function(object, tol = 100*.Machine$double.eps, ...)  
           {  
               ## pretest: is it square?  
               d <- dim(object)  
               if(d[1] != d[2]) return(FALSE)  
               ## for `broken' all.equal in R <= 2.2.x:  
               dn <- dimnames(object)  
               if(!identical(dn[1], dn[2])) return(FALSE)  
               test <-  
                   if(is.complex(object))  
                       all.equal.numeric(object, Conj(t(object)), tol = tol, ...)  
                   else              # numeric, character, ..  
                       all.equal(object, t(object), tol = tol, ...)  
               isTRUE(test)  
           })  
   
   
 setMethod("isTriangular", signature(object = "triangularMatrix"),  
           function(object, ...) TRUE)  
72    
73  setMethod("isTriangular", signature(object = "matrix"), isTriMat)  setMethod("isTriangular", signature(object = "matrix"), isTriMat)
74    
75  setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)  setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
76    
77    ## The "catch all" methods -- far from optimal:
78    setMethod("symmpart", signature(x = "Matrix"),
79              function(x) as((x + t(x))/2, "symmetricMatrix"))
80    setMethod("skewpart", signature(x = "Matrix"),
81              function(x) (x - t(x))/2)
82    
83    ## FIXME: do this (similarly as for "ddense.." in C
84    setMethod("symmpart", signature(x = "matrix"), function(x) (x + t(x))/2)
85    setMethod("skewpart", signature(x = "matrix"), function(x) (x - t(x))/2)
86    
87    
88    
89    
90  setMethod("dim", signature(x = "Matrix"),  setMethod("dim", signature(x = "Matrix"),
91            function(x) x@Dim, valueClass = "integer")            function(x) x@Dim, valueClass = "integer")
92    
93    setMethod("length", "Matrix", function(x) prod(dim(x)))
94    
95  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
96    
97    
98  ## not exported but used more than once for "dimnames<-" method :  ## not exported but used more than once for "dimnames<-" method :
99  ## -- or do only once for all "Matrix" classes ??  ## -- or do only once for all "Matrix" classes ??
100  dimnamesGets <- function (x, value) {  dimnamesGets <- function (x, value) {
# Line 96  Line 113 
113  setMethod("unname", signature("Matrix", force="missing"),  setMethod("unname", signature("Matrix", force="missing"),
114            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
115    
116  Matrix <-  setMethod("all", signature(x = "Matrix"),
117      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,            function(x, ..., na.rm)
118                sparse = NULL, forceCheck = FALSE)            callGeneric(as(x, "lMatrix"), ..., na.rm=na.rm))
119    
120    setMethod("any", signature(x = "Matrix"),
121              function(x, ..., na.rm)
122              callGeneric(as(x, "lMatrix"), ..., na.rm=na.rm))
123    
124    ## NOTE:  "&" and "|"  are now in group "Logic" c "Ops" --> ./Ops.R
125    ##        "!" is in ./not.R
126    
127    
128    Matrix <- function (data = NA, nrow = 1, ncol = 1, byrow = FALSE,
129                        dimnames = NULL, sparse = NULL, forceCheck = FALSE)
130  {  {
131      sparseDefault <- function(m)      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
         prod(dim(m)) > 2*sum(as(m, "matrix") != 0)  
132    
133      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
134      if(is.null(sparse) && (i.M || is(data, "matrix")))      if(!i.M && inherits(data, "table")) # special treatment
135            class(data) <- "matrix" # "matrix" first for S4 dispatch
136        if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
137          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
138        sM <- FALSE
139      doDN <- TRUE      doDN <- TRUE
140      if (i.M && !forceCheck) {      if (i.M) {
141            if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
142                warning("'nrow', 'ncol', etc, are disregarded when 'data' is \"Matrix\" already")
143          sM <- is(data,"sparseMatrix")          sM <- is(data,"sparseMatrix")
144          if((sparse && sM) || (!sparse && !sM))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
145              return(data)              return(data)
146          ## else : convert  dense <-> sparse -> at end          ## else : convert  dense <-> sparse -> at end
147      }      }
# Line 119  Line 150 
150              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
151          else if (missing(ncol))          else if (missing(ncol))
152              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
153          if(length(data) == 1 && data == 0 && !identical(sparse,FALSE)) {          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
154              if(is.null(sparse)) sparse <- TRUE              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
155                if(is.null(sparse)) sparse1 <- sparse <- TRUE
156                i.M <- sM <- TRUE
157                isSym <- nrow == ncol
158              ## will be sparse: do NOT construct full matrix!              ## will be sparse: do NOT construct full matrix!
159              data <- new(if(is.numeric(data)) "dgTMatrix" else              data <- new(paste(if(is.numeric(data)) "d" else
160                          if(is.logical(data)) "lgTMatrix" else                                if(is.logical(data)) "l" else
161                          stop("invalid 'data'"),                          stop("invalid 'data'"),
162                                  if(isSym) "s" else "g", "CMatrix", sep=''),
163                            p = rep.int(0L, ncol+1L),
164                          Dim = as.integer(c(nrow,ncol)),                          Dim = as.integer(c(nrow,ncol)),
165                          Dimnames = if(is.null(dimnames)) list(NULL,NULL)                          Dimnames = if(is.null(dimnames)) list(NULL,NULL)
166                          else dimnames)                          else dimnames)
167          } else { ## normal case          } else { ## normal case - using .Internal() to avoid more copying
168                if(getRversion() >= "2.7.0")
169                    data <- .Internal(matrix(data, nrow, ncol, byrow, dimnames))
170                else {
171              data <- .Internal(matrix(data, nrow, ncol, byrow))              data <- .Internal(matrix(data, nrow, ncol, byrow))
172                    dimnames(data) <- dimnames
173                }
174              if(is.null(sparse))              if(is.null(sparse))
175                  sparse <- sparseDefault(data)                  sparse <- sparseDefault(data)
             dimnames(data) <- dimnames  
176          }          }
177          doDN <- FALSE          doDN <- FALSE
178      }      } else if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
179            warning("'nrow', 'ncol', etc, are disregarded for matrix 'data'")
180    
181      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
182      if (doDN && !is.null(dimnames))      if (doDN && !is.null(dimnames))
183          dimnames(data) <- dimnames          dimnames(data) <- dimnames
# Line 146  Line 188 
188          isTri <- isTriangular(data)          isTri <- isTriangular(data)
189      isDiag <- isSym # cannot be diagonal if it isn't symmetric      isDiag <- isSym # cannot be diagonal if it isn't symmetric
190      if(isDiag)      if(isDiag)
191          isDiag <- isDiagonal(data)          isDiag <- !isTRUE(sparse1) && isDiagonal(data)
192    
193  ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R      ## try to coerce ``via'' virtual classes
194        if(isDiag) { ## diagonal is preferred to sparse !
195      ## Find proper matrix class 'cl'          data <- as(data, "diagonalMatrix")
196      cl <-          isSym <- FALSE
197          if(isDiag)      } else if(sparse && !sM)
198              "diagonalMatrix" # -> will automatically check for type          data <- as(data, "sparseMatrix")
199          else {      else if(!sparse) {
200              ## consider it's type          if(i.M) { ## data is 'Matrix'
201              ctype <-              if(!is(data, "denseMatrix"))
202                  if(is(data,"Matrix")) class(data)                  data <- as(data, "denseMatrix")
203                  else {          } else { ## data is "matrix" (and result "dense" -> go via "general"
204                      if("complex" == (ctype <- typeof(data)))              ctype <- typeof(data)
205                          "z" else ctype              if (ctype == "complex")
                 }  
             ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"  
             if(ctype == "z")  
206                  stop("complex matrices not yet implemented in Matrix package")                  stop("complex matrices not yet implemented in Matrix package")
207              if(ctype == "i") {              if (ctype == "integer") ## integer Matrices not yet implemented
208                  warning("integer matrices not yet implemented in 'Matrix'; ",                  storage.mode(data) <- "double"
209                          "using 'double' ones'")              data <- new(paste(.M.kind(data), "geMatrix", sep=''),
210                  ctype <- "d"                          Dim = dim(data),
211              }                          Dimnames = .M.DN(data),
212              paste(ctype,                          x = c(data))
213                    if(sparse) {          }
                       if(isSym) "sCMatrix" else  
                       if(isTri) "tCMatrix" else "gCMatrix"  
                   } else { ## dense  
                       if(isSym) "syMatrix" else  
                       if(isTri) "trMatrix" else "geMatrix"  
                   }, sep="")  
214          }          }
215    
216      ## Now coerce and return      if(isTri && !is(data, "triangularMatrix")) {
217      as(data, cl)          data <- if(attr(isTri,"kind") == "L") tril(data) else triu(data)
218                                            #was as(data, "triangularMatrix")
219        } else if(isSym && !is(data, "symmetricMatrix"))
220            data <- forceSymmetric(data) #was as(data, "symmetricMatrix")
221    
222        data
223  }  }
224    
225  ## Methods for operations where one argument is numeric  ## Methods for operations where one argument is numeric
# Line 191  Line 229 
229    
230  setMethod("%*%", signature(x = "Matrix", y = "numeric"),  setMethod("%*%", signature(x = "Matrix", y = "numeric"),
231            function(x, y) callGeneric(x, as.matrix(y)))            function(x, y) callGeneric(x, as.matrix(y)))
   
232  setMethod("%*%", signature(x = "numeric", y = "Matrix"),  setMethod("%*%", signature(x = "numeric", y = "Matrix"),
233            function(x, y) callGeneric(rbind(x), y))            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
234    
235    setMethod("%*%", signature(x = "Matrix", y = "matrix"),
236              function(x, y) callGeneric(x, Matrix(y)))
237    setMethod("%*%", signature(x = "matrix", y = "Matrix"),
238              function(x, y) callGeneric(Matrix(x), y))
239    
240    
241  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
242            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
243  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
244            function(x, y = NULL)  callGeneric(as.matrix(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
245    
246    setMethod("crossprod", signature(x = "Matrix", y = "matrix"),
247              function(x, y = NULL) callGeneric(x, Matrix(y)))
248    setMethod("crossprod", signature(x = "matrix", y = "Matrix"),
249              function(x, y = NULL) callGeneric(Matrix(x), y))
250    
251  ## The as.matrix() promotion seems illogical to MM,  ## The as.matrix() promotion seems illogical to MM,
252  ## but is according to help(tcrossprod, package = "base") :  ## but is according to help(tcrossprod, package = "base") :
253  setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),  setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
254            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
255  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
256            function(x, y = NULL)  callGeneric(as.matrix(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
257    setMethod("tcrossprod", signature(x = "Matrix", y = "matrix"),
258              function(x, y = NULL) callGeneric(x, Matrix(y)))
259    setMethod("tcrossprod", signature(x = "matrix", y = "Matrix"),
260              function(x, y = NULL) callGeneric(Matrix(x), y))
261    
262    ## maybe not 100% optimal, but elegant:
263    setMethod("solve", signature(a = "Matrix", b = "missing"),
264              function(a, b, ...) solve(a, Diagonal(nrow(a))))
265    
266  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
267            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, Matrix(b)))
268    setMethod("solve", signature(a = "Matrix", b = "matrix"),
269              function(a, b, ...) callGeneric(a, Matrix(b)))
270    setMethod("solve", signature(a = "matrix", b = "Matrix"),
271              function(a, b, ...) callGeneric(Matrix(a), b))
272    
273    ## when no sub-class method is found, bail out
274    setMethod("solve", signature(a = "Matrix", b = "Matrix"),
275              function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
276    
277  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
278  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 235  Line 299 
299  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
300                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
301            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
302                  if(is(X, "sparseMatrix"))
303                      warning("using slow kronecker() method")
304                X <- as(X, "matrix") ; Matrix(callGeneric()) })                X <- as(X, "matrix") ; Matrix(callGeneric()) })
305    
306  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
307                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
308            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
309                  if(is(Y, "sparseMatrix"))
310                      warning("using slow kronecker() method")
311                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
312    
313    
314    setMethod("determinant", signature(x = "Matrix", logarithm = "missing"),
315              function(x, logarithm, ...)
316              determinant(x, logarithm = TRUE, ...))
317    
318    if(FALSE) { ## This is desired "in theory" - but gives
319        ## "The following object(s) are masked from package:base :   det
320    ## base::det() calls [base::]determinant();
321    ## our det() should call our determinant() :
322    det <- base::det
323    environment(det) <- environment()## == as.environment("Matrix")
324    }
325    
326    ## FIXME: All of these should never be called
327    setMethod("chol", signature(x = "Matrix"),
328              function(x, pivot, ...) .bail.out.1(.Generic, class(x)))
329    setMethod("determinant", signature(x = "Matrix", logarithm = "logical"),
330              function(x, logarithm, ...)
331              determinant(as(x,"dMatrix"), logarithm=logarithm, ...))
332    
333  setMethod("diag", signature(x = "Matrix"),  setMethod("diag", signature(x = "Matrix"),
334            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
335  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
336            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
337    
338  ## Group Methods  setMethod("norm", signature(x = "Matrix", type = "character"),
339  setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)            function(x, type, ...) .bail.out.1(.Generic, class(x)))
340  ## "fallback":  setMethod("rcond", signature(x = "Matrix", norm = "character"),
341  setMethod("-", signature(e1 = "Matrix", e2 = "missing"),            function(x, norm, ...) .bail.out.1(.Generic, class(x)))
342            function(e1) {  
343                warning("inefficient method used for \"- e1\"")  
344                0-e1  ## for all :
345    setMethod("norm", signature(x = "ANY", type = "missing"),
346              function(x, type, ...) norm(x, type = "O", ...))
347    setMethod("rcond", signature(x = "ANY", norm = "missing"),
348              function(x, norm, ...) rcond(x, norm = "O", ...))
349    
350    
351    
352    
353    
354    ## MM: More or less "Cut & paste" from
355    ## --- diff.default() from  R/src/library/base/R/diff.R :
356    setMethod("diff", signature(x = "Matrix"),
357              function(x, lag = 1, differences = 1, ...) {
358                  if (length(lag) > 1 || length(differences) > 1 ||
359                      lag < 1 || differences < 1)
360                      stop("'lag' and 'differences' must be integers >= 1")
361                  xlen <- nrow(x)
362                  if (lag * differences >= xlen)
363                      return(x[,FALSE][0])  # empty of proper mode
364    
365                  i1 <- -1:-lag
366                  for (i in 1:differences)
367                      x <- x[i1, , drop = FALSE] -
368                          x[-nrow(x):-(nrow(x)-lag+1), , drop = FALSE]
369                  x
370            })            })
371    
372  ## bail-outs:  setMethod("image", "Matrix",
373  setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),            function(x, ...) { # coercing to sparse is not inefficient,
374            function(e1, e2) {                ##               since we need 'i' and 'j' for levelplot()
375                d <- dimCheck(e1,e2)                x <- as(as(x, "sparseMatrix"), "dMatrix")
376                .bail.out.2(.Generic, class(e1), class(e2))                callGeneric()
377            })            })
 setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),  
           function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))  
 setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),  
           function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))  
378    
379    
380    ## Group Methods
381    
382    ## For all  non-dMatrix objects, and note that  "all" and "any" have their own
383    setMethod("Summary", signature(x = "Matrix", na.rm = "ANY"),
384              function(x, ..., na.rm)
385              callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm))
386    
387    Summary.l <- function(x, ..., na.rm) { ## must be method directly
388        r <- callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm)
389        if(!is.infinite(r) && .Generic %in% c("max", "min", "range", "sum"))
390            as.integer(r) else r
391    }
392    setMethod("Summary", signature(x = "lMatrix", na.rm = "ANY"), Summary.l)
393    setMethod("Summary", signature(x = "nMatrix", na.rm = "ANY"), Summary.l)
394    setMethod("Summary", signature(x = "pMatrix", na.rm = "ANY"), Summary.l)
395    
396    ## Further, see ./Ops.R
397    ##                ~~~~~
398    
399    
400  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
401  ###  ###
# Line 280  Line 408 
408  ## "x[]":  ## "x[]":
409  setMethod("[", signature(x = "Matrix",  setMethod("[", signature(x = "Matrix",
410                           i = "missing", j = "missing", drop = "ANY"),                           i = "missing", j = "missing", drop = "ANY"),
411            function (x, i, j, drop) x)            function (x, i, j, ..., drop) x)
412    
413  ## missing 'drop' --> 'drop = TRUE'  ## missing 'drop' --> 'drop = TRUE'
414  ##                     -----------  ##                     -----------
415  ## select rows  ## select rows __ or __ vector indexing:
416  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
417                           drop = "missing"),                           drop = "missing"),
418            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, ..., drop) {
419                  if(nargs() == 2) { ## e.g. M[0] , M[TRUE],  M[1:2]
420                      if(any(as.logical(i)) || prod(dim(x)) == 0)
421                          ## FIXME: for *large sparse*, use sparseVector !
422                          as.vector(x)[i]
423                      else ## save memory (for large sparse M):
424                          as.vector(x[1,1])[FALSE]
425                  } else {
426                      callGeneric(x, i=i, , drop=TRUE)
427                      ##                  ^^
428                  }
429              })
430    
431  ## select columns  ## select columns
432  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
433                           drop = "missing"),                           drop = "missing"),
434            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))            function(x,i,j, ..., drop) callGeneric(x, j=j, drop= TRUE))
435  setMethod("[", signature(x = "Matrix", i = "index", j = "index",  setMethod("[", signature(x = "Matrix", i = "index", j = "index",
436                           drop = "missing"),                           drop = "missing"),
437            function(x,i,j, drop) callGeneric(x, i=i, j=j, drop= TRUE))            function(x,i,j, ..., drop) callGeneric(x, i=i, j=j, drop= TRUE))
438    
439  ## bail out if any of (i,j,drop) is "non-sense"  ## bail out if any of (i,j,drop) is "non-sense"
440  setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),  setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
441            function(x,i,j, drop)            function(x,i,j, ..., drop)
442            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
443    
444  ##  "logical *vector* indexing, such as  M [ M >= 10 ] :  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
445  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  ## The following is *both* for    M [ <logical>   ]
446                           drop = "ANY"),  ##                 and also for   M [ <logical> , ]
447            function (x, i, j, drop) {  .M.sub.i.logical <- function (x, i, j, ..., drop)
448                as(x, geClass(x))@x[as.vector(i)]  {
449        nA <- nargs()
450        if(nA == 2) { ##  M [ M >= 7 ]
451            ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
452            if(is(x, "sparseMatrix"))
453                message("<sparse>[ <logic> ] : .M.sub.i.logical() maybe inefficient")
454            toC <- geClass(x)
455            if(canCoerce(x, toC)) as(x, toC)@x[as.vector(i)]
456            else as(as(as(x, "generalMatrix"), "denseMatrix"), toC)@x[as.vector(i)]
457                ## -> error when lengths don't match                ## -> error when lengths don't match
458            })      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
459            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
460    
461  ## FIXME: The following is good for    M [ <logical>   ]      } else stop("nargs() = ", nA,
462  ##        *BUT* it also triggers for   M [ <logical> , ] where it is *WRONG*                  ".  Extraneous illegal arguments inside '[ .. ]' (i.logical)?")
463  ##       using nargs() does not help: it gives '3' for both cases  }
464  if(FALSE)  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
465                             drop = "ANY"),
466              .M.sub.i.logical)
467  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
468                           drop = "ANY"),                           drop = "ANY"),
469            function (x, i, j, drop) {            .M.sub.i.logical)
470                ## DEBUG  
471                cat("[(Matrix,i,..): nargs=", nargs(),"\n")  
472                as(x, geClass(x))@x[i] })  subset.ij <- function(x, ij) {
473        m <- nrow(ij)
474        if(m > 3) {
475            cld <- getClassDef(class(x))
476            sym.x <- extends(cld, "symmetricMatrix")
477            if(sym.x) {
478                W <- if(x@uplo == "U") # stored only [i,j] with i <= j
479                    ij[,1] > ij[,2] else ij[,1] < ij[,2]
480                if(any(W))
481                    ij[W,] <- ij[W, 2:1]
482            }
483            if(extends(cld, "sparseMatrix")) {
484                ## do something smarter:
485                nr <- nrow(x)
486                if(!extends(cld, "CsparseMatrix")) {
487                    x <- as(x, "CsparseMatrix") # simpler; our standard
488                    cld <- getClassDef(class(x))
489                }
490                tri.x <- extends(cld, "triangularMatrix")
491                if(tri.x) {
492                    ## need these for the 'x' slot in any case
493                    if (x@diag == "U") x <- .Call(Csparse_diagU2N, x)
494                    ## slightly more efficient than non0.i() or non0ind():
495                    ij.x <- .Call(compressed_non_0_ij, x, isC=TRUE)
496                } else { ## symmetric / general : for symmetric, only "existing"b
497                    ij.x <- non0.i(x, cld)
498                }
499    
500                mi <- match(encodeInd(ij.x,   nr),
501                            encodeInd(ij -1L, nr), nomatch=0)
502                mmi <- mi != 0
503                ## Result:
504                ans <- vector(mode = .type.kind[.M.kindC(cld)], length = m)
505                ## those that are *not* zero:
506                ans[mi[mmi]] <-
507                    if(extends(cld, "nsparseMatrix")) TRUE else x@x[mmi]
508                ans
509    
510            } else { ## non-sparse : dense
511                ##---- NEVER happens:  'denseMatrix' has its own setMethod(.) !
512                message("m[ <ij-matrix> ]: inefficiently indexing single elements")
513                i1 <- ij[,1]
514                i2 <- ij[,2]
515                ## very inefficient for large m
516                unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
517            }
518        } else { # 1 <= m <= 3
519            i1 <- ij[,1]
520            i2 <- ij[,2]
521            unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
522        }
523    }
524    
525  ## "FIXME:"  ## A[ ij ]  where ij is (i,j) 2-column matrix -- but also when that is logical mat!
526  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?  .M.sub.i.2col <- function (x, i, j, ..., drop)
527  ##  and                A[ LL ]  where LL is a logical *vector*  {
528  ## -> [.data.frame uses nargs() - can we do this in the *generic* ?      nA <- nargs()
529        if(nA == 2) { ##  M [ cbind(ii,jj) ] or M [ <logical matrix> ]
530            if(!is.integer(nc <- ncol(i)))
531                stop(".M.sub.i.2col(): 'i' has no integer column number;\n",
532                     "should never happen; please report")
533            if(is.logical(i))
534                return(.M.sub.i.logical(x, i=i)) # call with 2 args!
535            else if(!is.numeric(i) || nc != 2)
536                stop("such indexing must be by logical or 2-column numeric matrix")
537            m <- nrow(i)
538            if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
539            ## else
540            subset.ij(x, i)
541    
542        } else stop("nargs() = ", nA,
543                    ".  Extraneous illegal arguments inside '[ .. ]' (i.2col)?")
544    }
545    setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
546              .M.sub.i.2col)
547    
548    
549  ### "[<-" : -----------------  ### "[<-" : -----------------
# Line 333  Line 552 
552  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
553                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
554            function (x, value) {            function (x, value) {
555                x@x <- value                ## Fails for 'nMatrix' ... FIXME : make sure have method there
556                  x@x <- rep(value, length = length(x@x))
557                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
558                x                x
559            })            })
560    
561  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
562    ## ----------------
563    ## The cheap general method --- FIXME: provide special ones; done for Tsparse..
564    ## NOTE:  need '...' below such that setMethod() does
565    ##        not use .local() such that nargs() will work correctly:
566    .M.repl.i.2col <- function (x, i, j, ..., value)
567    {
568        nA <- nargs()
569        if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value  or M [ Lmat ] <- value
570            if(!is.integer(nc <- ncol(i)))
571                stop(".M.repl.i.2col(): 'i' has no integer column number;\n",
572                     "should never happen; please report")
573            else if(!is.numeric(i) || nc != 2)
574                stop("such indexing must be by logical or 2-column numeric matrix")
575            if(is.logical(i)) {
576                message(".M.repl.i.2col(): drop 'matrix' case ...")
577                ## c(i) : drop "matrix" to logical vector
578                return( callGeneric(x, i=c(i), value=value) )
579            }
580            if(!is.integer(i)) storage.mode(i) <- "integer"
581            if(any(i < 0))
582                stop("negative values are not allowed in a matrix subscript")
583            if(any(is.na(i)))
584                stop("NAs are not allowed in subscripted assignments")
585            if(any(i0 <- (i == 0))) # remove them
586                i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
587            ## now have integer i >= 1
588            m <- nrow(i)
589            ## mod.x <- .type.kind[.M.kind(x)]
590            if(length(value) > 0 && m %% length(value) != 0)
591                warning("number of items to replace is not a multiple of replacement length")
592            ## recycle:
593            value <- rep(value, length = m)
594            i1 <- i[,1]
595            i2 <- i[,2]
596            if(m > 2)
597                message("m[ <ij-matrix> ] <- v: inefficiently treating single elements")
598            ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
599            for(k in seq_len(m))
600                x[i1[k], i2[k]] <- value[k]
601    
602            x
603        } else stop("nargs() = ", nA,
604                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
605    }
606    
607    setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
608                                    value = "replValue"),
609              .M.repl.i.2col)
610    
611    
612    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
613                                    value = "Matrix"),
614                     function (x, i, j, ..., value)
615                     callGeneric(x=x, , j=j, value = as.vector(value)))
616    
617    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
618                                    value = "Matrix"),
619                     function (x, i, j, ..., value)
620                     callGeneric(x=x, i=i, , value = as.vector(value)))
621    
622    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
623                                    value = "Matrix"),
624                     function (x, i, j, ..., value)
625                     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
626    
627    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
628                                    value = "matrix"),
629                     function (x, i, j, ..., value)
630                     callGeneric(x=x, , j=j, value = c(value)))
631    
632    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
633                                    value = "matrix"),
634                     function (x, i, j, ..., value)
635                     callGeneric(x=x, i=i, , value = c(value)))
636    
637    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
638                                    value = "matrix"),
639                     function (x, i, j, value)
640                     callGeneric(x=x, i=i, j=j, value = c(value)))
641    
642  ## (ANY,ANY,ANY) is used when no `real method' is implemented :  ## (ANY,ANY,ANY) is used when no `real method' is implemented :
643  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
644                                  value = "ANY"),                                  value = "ANY"),
645            function (x, i, j, value) {            function (x, i, j, value) {
646                if(!is.atomic(value))                if(!is.atomic(value))
647                    stop("RHS 'value' must match matrix class ", class(x))                    stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
648                                   class(value),class(x)))
649                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
650            })            })
   
   
 ## The trivial methods :  
 setMethod("cbind2", signature(x = "Matrix", y = "NULL"),  
           function(x, y) x)  
 setMethod("cbind2", signature(x = "Matrix", y = "missing"),  
           function(x, y) x)  
 setMethod("cbind2", signature(x = "NULL", y="Matrix"),  
           function(x, y) x)  
   
 setMethod("rbind2", signature(x = "Matrix", y = "NULL"),  
           function(x, y) x)  
 setMethod("rbind2", signature(x = "Matrix", y = "missing"),  
           function(x, y) x)  
 setMethod("rbind2", signature(x = "NULL", y="Matrix"),  
           function(x, y) x)  
   
 ## Makes sure one gets x decent error message for the unimplemented cases:  
 setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),  
           function(x, y) {  
               rowCheck(x,y)  
               stop(gettextf("cbind2() method for (%s,%s) not-yet defined",  
                             class(x), class(y)))  
           })  
   
 ## Use a working fall back {particularly useful for sparse}:  
 ## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones  
 setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),  
           function(x, y) {  
               colCheck(x,y)  
               t(cbind2(t(x), t(y)))  
           })  

Legend:
Removed from v.1455  
changed lines
  Added in v.2185

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