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

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