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

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