# SCM Repository

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

# Diff of /pkg/R/Matrix.R

revision 1673, Mon Nov 6 20:54:26 2006 UTC revision 2256, Fri Sep 5 16:23:39 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:  ## Most of these work; this is a last resort:
14  setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:  setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:
15        function(from) .bail.out.2("coerce", class(from), class(to)))        function(from) .bail.out.2("coerce", class(from), class(to)))
# Line 27  Line 31
32  setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)  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:  ## 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  ## "base" has an isSymmetric() S3-generic since R 2.3.0  ## "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))

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, forceCheck = FALSE)            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) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
140
141      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
142        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")))      if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
145          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
146        sM <- FALSE
147      doDN <- TRUE      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(!forceCheck && ((sparse && sM) || (!sparse && !sM)))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
153              return(data)              return(data)
# Line 101  Line 161
161          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
162              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
163              if(is.null(sparse)) sparse1 <- sparse <- TRUE              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!              ## will be sparse: do NOT construct full matrix!
167              data <- new(if(is.numeric(data)) "dgTMatrix" else              data <- new(paste(if(is.numeric(data)) "d" else
168                          if(is.logical(data)) "lgTMatrix" else                                if(is.logical(data)) "l" else
169                          stop("invalid 'data'"),                          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)),                          Dim = as.integer(c(nrow,ncol)),
173                          Dimnames = if(is.null(dimnames)) list(NULL,NULL)                          Dimnames = if(is.null(dimnames)) list(NULL,NULL)
174                          else dimnames)                          else dimnames)
175          } else { ## normal case          } 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)
dimnames(data) <- dimnames
184          }          }
185          doDN <- FALSE          doDN <- FALSE
186      }      } 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))      if (doDN && !is.null(dimnames))
191          dimnames(data) <- dimnames          dimnames(data) <- dimnames
# Line 126  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)
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 && !isTRUE(sparse1))          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))
if(sparse) {
if(isSym) "sCMatrix" else
if(isTri) "tCMatrix" else "gCMatrix"
} else { ## dense
if(isSym) "syMatrix" else
if(isTri) "trMatrix" else "geMatrix"
}, sep="")
221          }          }
222        }
223
224        if(isTri && !is(data, "triangularMatrix")) {
225            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      ## Now coerce and return      data
as(data, cl)
231  }  }
232
233  ## Methods for operations where one argument is numeric  ## Methods for operations where one argument is numeric
# Line 169  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(matrix(x, nrow = 1, byrow=TRUE), 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(as.matrix(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,  ## The as.matrix() promotion seems illogical to MM,
260  ## but is according to help(tcrossprod, package = "base") :  ## but is according to help(tcrossprod, package = "base") :
261  setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),  setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
262            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
263  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
264            function(x, y = NULL)  callGeneric(as.matrix(x), y))            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 optimal  ## maybe not 100% optimal, but elegant:
271  setMethod("solve", signature(a = "Matrix", b = "missing"),  setMethod("solve", signature(a = "Matrix", b = "missing"),
272            function(a, b, ...) solve(a, Diagonal(nrow(a))))            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)))
## when no sub-class method is found, bail out
276  setMethod("solve", signature(a = "Matrix", b = "matrix"),  setMethod("solve", signature(a = "Matrix", b = "matrix"),
277            function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))            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    setMethod("solve", signature(a = "Matrix", b = "diagonalMatrix"),
282              function(a, b, ...) callGeneric(a, as(b,"CsparseMatrix")))
283
284    ## when no sub-class method is found, bail out
285    setMethod("solve", signature(a = "Matrix", b = "ANY"),
286              function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
287    setMethod("solve", signature(a = "ANY", b = "Matrix"),
288              function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
289
290  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
291  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),            .local.bail.out = function (x, y)
function (x, y)
292            stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',            stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
293                          class(x), class(y))))                          class(x), class(y)))
294
295    setMethod("%*%", signature(x = "ANY", y = "Matrix"), .local.bail.out)
296    setMethod("%*%", signature(x = "Matrix", y = "ANY"), .local.bail.out)
297
298
299  setMethod("crossprod", signature(x = "Matrix", y = "ANY"),  setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
300            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
# Line 211  Line 306
306            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
307
308  ## cheap fallbacks  ## cheap fallbacks
309  setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),  setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
310            function(x, y = NULL) t(x) %*% y)            function(x, y = NULL) t(x) %*% y)
311  setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
312              function(x, y = NULL) t(x) %*% y)
313    setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
314              function(x, y = NULL) x %*% t(y))
315    setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
316            function(x, y = NULL) x %*% t(y))            function(x, y = NULL) x %*% t(y))
317
318  ## There are special sparse methods; this is a "fall back":  ## There are special sparse methods; this is a "fall back":
319  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
320                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
321            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
322                  if(is(X, "sparseMatrix"))
323                      warning("using slow kronecker() method")
324                X <- as(X, "matrix") ; Matrix(callGeneric()) })                X <- as(X, "matrix") ; Matrix(callGeneric()) })
325
326  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
327                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
328            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
329                  if(is(Y, "sparseMatrix"))
330                      warning("using slow kronecker() method")
331                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
332
333
334    setMethod("determinant", signature(x = "Matrix", logarithm = "missing"),
335              function(x, logarithm, ...)
336              determinant(x, logarithm = TRUE, ...))
337
338    if(FALSE) { ## This is desired "in theory" - but gives
339        ## "The following object(s) are masked from package:base :   det
340    ## base::det() calls [base::]determinant();
341    ## our det() should call our determinant() :
342    det <- base::det
343    environment(det) <- environment()## == as.environment("Matrix")
344    }
345
346  ## FIXME: All of these should never be called  ## FIXME: All of these should never be called
347  setMethod("chol", signature(x = "Matrix"),  setMethod("chol", signature(x = "Matrix"),
348            function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))            function(x, pivot, ...) .bail.out.1(.Generic, class(x)))
349  setMethod("determinant", signature(x = "Matrix"),  setMethod("determinant", signature(x = "Matrix", logarithm = "logical"),
350            function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))            function(x, logarithm, ...)
351              determinant(as(x,"dMatrix"), logarithm=logarithm, ...))
352
353  setMethod("diag", signature(x = "Matrix"),  setMethod("diag", signature(x = "Matrix"),
354            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
355  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
356            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
357
358  ## Group Methods  setMethod("norm", signature(x = "Matrix", type = "character"),
359  setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)            function(x, type, ...) .bail.out.1(.Generic, class(x)))
360  ## "fallback":  setMethod("rcond", signature(x = "Matrix", norm = "character"),
361  setMethod("-", signature(e1 = "Matrix", e2 = "missing"),            function(x, norm, ...) .bail.out.1(.Generic, class(x)))
362            function(e1) {
363                warning("inefficient method used for \"- e1\"")
364                0-e1  ## for all :
365    setMethod("norm", signature(x = "ANY", type = "missing"),
366              function(x, type, ...) norm(x, type = "O", ...))
367    setMethod("rcond", signature(x = "ANY", norm = "missing"),
368              function(x, norm, ...) rcond(x, norm = "O", ...))
369
370
371
372
373    ## We want to use all.equal.numeric() *and* make sure that uses
374    ## not just base::as.vector but the generic with our methods:
375    all.equal_num <- base::all.equal.numeric ## from <R>/src/library/base/R/all.equal.R
376    environment(all.equal_num) <- environment()## == as.environment("Matrix")
377
378    all.equal_Mat <- function(target, current, check.attributes = TRUE, ...)
379    {
380        msg <- attr.all_Mat(target, current, check.attributes=check.attributes, ...)
381        if(is.list(msg)) return(msg[[1]])
382        ## else
383        r <- all.equal_num(as.vector(target), as.vector(current),
384                           check.attributes=check.attributes, ...)
385        if(is.null(msg) && (r.ok <- isTRUE(r))) TRUE else c(msg, if(!r.ok) r)
386    }
387    ## The all.equal() methods for dense matrices (and fallback):
388    setMethod("all.equal", c(target = "Matrix", current = "Matrix"),
389              all.equal_Mat)
390    setMethod("all.equal", c(target = "Matrix", current = "ANY"),
391              all.equal_Mat)
392    setMethod("all.equal", c(target = "ANY", current = "Matrix"),
393              all.equal_Mat)
394    ## -> ./sparseMatrix.R, ./sparseVector.R  have specific methods
395
396
397
398    ## MM: More or less "Cut & paste" from
399    ## --- diff.default() from  R/src/library/base/R/diff.R :
400    setMethod("diff", signature(x = "Matrix"),
401              function(x, lag = 1, differences = 1, ...) {
402                  if (length(lag) > 1 || length(differences) > 1 ||
403                      lag < 1 || differences < 1)
404                      stop("'lag' and 'differences' must be integers >= 1")
405                  xlen <- nrow(x)
406                  if (lag * differences >= xlen)
407                      return(x[,FALSE][0])  # empty of proper mode
408
409                  i1 <- -1:-lag
410                  for (i in 1:differences)
411                      x <- x[i1, , drop = FALSE] -
412                          x[-nrow(x):-(nrow(x)-lag+1), , drop = FALSE]
413                  x
414            })            })
415
416  ## old-style matrices are made into new ones  setMethod("image", "Matrix",
417  setMethod("Ops", signature(e1 = "Matrix", e2 = "matrix"),            function(x, ...) { # coercing to sparse is not inefficient,
418            function(e1, e2) callGeneric(e1, Matrix(e2)))                ##               since we need 'i' and 'j' for levelplot()
419  ##          callGeneric(e1, Matrix(e2, sparse=is(e1,"sparseMatrix"))))                x <- as(as(x, "sparseMatrix"), "dMatrix")
420  setMethod("Ops", signature(e1 = "matrix", e2 = "Matrix"),                callGeneric()
function(e1, e2) callGeneric(Matrix(e1), e2))

## bail-outs -- on highest possible level, hence "Ops", not "Compare"/"Arith" :
setMethod("Ops", signature(e1 = "Matrix", e2 = "Matrix"),
function(e1, e2) {
d <- dimCheck(e1,e2)
.bail.out.2(.Generic, class(e1), class(e2))
421            })            })
setMethod("Ops", signature(e1 = "Matrix", e2 = "ANY"),
function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
setMethod("Ops", signature(e1 = "ANY", e2 = "Matrix"),
function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
422
423
424    ## Group Methods
425
426    ## For all  non-dMatrix objects, and note that  "all" and "any" have their own
427    setMethod("Summary", signature(x = "Matrix", na.rm = "ANY"),
428              function(x, ..., na.rm)
429              callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm))
430
431    Summary.l <- function(x, ..., na.rm) { ## must be method directly
432        r <- callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm)
433        if(!is.infinite(r) && .Generic %in% c("max", "min", "range", "sum"))
434            as.integer(r) else r
435    }
436    setMethod("Summary", signature(x = "lMatrix", na.rm = "ANY"), Summary.l)
437    setMethod("Summary", signature(x = "nMatrix", na.rm = "ANY"), Summary.l)
438    setMethod("Summary", signature(x = "pMatrix", na.rm = "ANY"), Summary.l)
439
440    ## Further, see ./Ops.R
441    ##                ~~~~~
442
443
444  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
445  ###  ###
# Line 278  Line 452
452  ## "x[]":  ## "x[]":
453  setMethod("[", signature(x = "Matrix",  setMethod("[", signature(x = "Matrix",
454                           i = "missing", j = "missing", drop = "ANY"),                           i = "missing", j = "missing", drop = "ANY"),
455            function (x, i, j, drop) x)            function (x, i, j, ..., drop) x)
456
457  ## missing 'drop' --> 'drop = TRUE'  ## missing 'drop' --> 'drop = TRUE'
458  ##                     -----------  ##                     -----------
459  ## select rows  ## select rows __ or __ vector indexing:
460  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
461                           drop = "missing"),                           drop = "missing"),
462            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, ..., drop) {
463                  if(nargs() == 2) { ## e.g. M[0] , M[TRUE],  M[1:2]
464                      if(any(as.logical(i)) || prod(dim(x)) == 0)
465                          ## FIXME: for *large sparse*, use sparseVector !
466                          as.vector(x)[i]
467                      else ## save memory (for large sparse M):
468                          as.vector(x[1,1])[FALSE]
469                  } else {
470                      callGeneric(x, i=i, , drop=TRUE)
471                      ##                  ^^
472                  }
473              })
474
475  ## select columns  ## select columns
476  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
477                           drop = "missing"),                           drop = "missing"),
478            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))            function(x,i,j, ..., drop) callGeneric(x, j=j, drop= TRUE))
479  setMethod("[", signature(x = "Matrix", i = "index", j = "index",  setMethod("[", signature(x = "Matrix", i = "index", j = "index",
480                           drop = "missing"),                           drop = "missing"),
481            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))
482
483  ## bail out if any of (i,j,drop) is "non-sense"  ## bail out if any of (i,j,drop) is "non-sense"
484  setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),  setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
485            function(x,i,j, drop)            function(x,i,j, ..., drop)
486            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
487
488  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
489  ## The following is *both* for    M [ <logical>   ]  ## The following is *both* for    M [ <logical>   ]
490  ##                 and also for   M [ <logical> , ]  ##                 and also for   M [ <logical> , ]
491  .M.sub.i.logical <- function (x, i, j, drop)  .M.sub.i.logical <- function (x, i, j, ..., drop)
492  {  {
493      nA <- nargs()      nA <- nargs()
494      if(nA == 2) { ##  M [ M >= 7 ]      if(nA == 2) { ##  M [ M >= 7 ]
495          ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient          ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
496          as(x, geClass(x))@x[as.vector(i)]          if(is(x, "sparseMatrix"))
497                message("<sparse>[ <logic> ] : .M.sub.i.logical() maybe inefficient")
498            toC <- geClass(x)
499            if(canCoerce(x, toC)) as(x, toC)@x[as.vector(i)]
500            else as(as(as(x, "generalMatrix"), "denseMatrix"), toC)@x[as.vector(i)]
501          ## -> error when lengths don't match          ## -> error when lengths don't match
502      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
503          stop("not-yet-implemented 'Matrix' subsetting") ## FIXME          stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
504
505      } else stop("nargs() = ", nA,      } else stop("nargs() = ", nA,
506                  " should never happen; please report.")                  ".  Extraneous illegal arguments inside '[ .. ]' (i.logical)?")
507  }  }
508  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
509                           drop = "ANY"),                           drop = "ANY"),
# Line 323  Line 513
513            .M.sub.i.logical)            .M.sub.i.logical)
514
515
516  ## A[ ij ]  where ij is (i,j) 2-column matrix :  subset.ij <- function(x, ij) {
517  .M.sub.i.2col <- function (x, i, j, drop)      m <- nrow(ij)
518        if(m > 3) {
519            cld <- getClassDef(class(x))
520            sym.x <- extends(cld, "symmetricMatrix")
521            if(sym.x) {
522                W <- if(x@uplo == "U") # stored only [i,j] with i <= j
523                    ij[,1] > ij[,2] else ij[,1] < ij[,2]
524                if(any(W))
525                    ij[W,] <- ij[W, 2:1]
526            }
527            if(extends(cld, "sparseMatrix")) {
528                ## do something smarter:
529                di <- dim(x)
530                if(!extends(cld, "CsparseMatrix")) {
531                    x <- as(x, "CsparseMatrix") # simpler; our standard
532                    cld <- getClassDef(class(x))
533                }
534                tri.x <- extends(cld, "triangularMatrix")
535                if(tri.x) {
536                    ## need these for the 'x' slot in any case
537                    if (x@diag == "U") x <- .Call(Csparse_diagU2N, x)
538                    ## slightly more efficient than non0.i() or non0ind():
539                    ij.x <- .Call(compressed_non_0_ij, x, isC=TRUE)
540                } else { ## symmetric / general : for symmetric, only "existing"b
541                    ij.x <- non0.i(x, cld)
542                }
543
544                mi <- match(.Call(m_encodeInd, ij.x,          di),
545                            .Call(m_encodeInd, ij -1L, di), nomatch=0)
546                mmi <- mi != 0
547                ## Result:
548                ans <- vector(mode = .type.kind[.M.kindC(cld)], length = m)
549                ## those that are *not* zero:
550                ans[mi[mmi]] <-
551                    if(extends(cld, "nsparseMatrix")) TRUE else x@x[mmi]
552                ans
553
554            } else { ## non-sparse : dense
555                ##---- NEVER happens:  'denseMatrix' has its own setMethod(.) !
556                message("m[ <ij-matrix> ]: inefficiently indexing single elements")
557                i1 <- ij[,1]
558                i2 <- ij[,2]
559                ## very inefficient for large m
560                unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
561            }
562        } else { # 1 <= m <= 3
563            i1 <- ij[,1]
564            i2 <- ij[,2]
565            unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
566        }
567    }
568
569    ## A[ ij ]  where ij is (i,j) 2-column matrix -- but also when that is logical mat!
570    .M.sub.i.2col <- function (x, i, j, ..., drop)
571  {  {
572      nA <- nargs()      nA <- nargs()
573      if(nA == 2) { ##  M [ cbind(ii,jj) ]      if(nA == 2) { ##  M [ cbind(ii,jj) ] or M [ <logical matrix> ]
574          if(!is.integer(nc <- ncol(i)))          if(!is.integer(nc <- ncol(i)))
575              stop("'i' has no integer column number",              stop(".M.sub.i.2col(): 'i' has no integer column number;\n",
576                   " should never happen; please report")                   " should never happen; please report")
577          if(is.logical(i))          if(is.logical(i))
578              return(.M.sub.i.logical(x,i,j,drop))              return(.M.sub.i.logical(x, i=i)) # call with 2 args!
579          else if(!is.numeric(i) || nc != 2)          else if(!is.numeric(i) || nc != 2)
580              stop("such indexing must be by logical or 2-column numeric matrix")              stop("such indexing must be by logical or 2-column numeric matrix")
581          m <- nrow(i)          m <- nrow(i)
582          if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))          if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
583          ## else          ## else
584          i1 <- i[,1]          subset.ij(x, i)
i2 <- i[,2]
## potentially inefficient -- FIXME --
unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
585
586      } else stop("nargs() = ", nA, " should never happen; please report.")      } else stop("nargs() = ", nA,
587                    ".  Extraneous illegal arguments inside '[ .. ]' (i.2col)?")
588  }  }
589  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
590            .M.sub.i.2col)            .M.sub.i.2col)
# Line 356  Line 597
597                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
598            function (x, value) {            function (x, value) {
599                ## Fails for 'nMatrix' ... FIXME : make sure have method there                ## Fails for 'nMatrix' ... FIXME : make sure have method there
600                x@x <- value                x@x <- rep(value, length = length(x@x))
601                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
602                x                x
603            })            })
604
605  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
606  .M.repl.i.2col <- function (x, i, j, value)  ## ----------------
607    ## The cheap general method --- FIXME: provide special ones; done for Tsparse..
608    ## NOTE:  need '...' below such that setMethod() does
609    ##        not use .local() such that nargs() will work correctly:
610    .M.repl.i.2col <- function (x, i, j, ..., value)
611  {  {
612      nA <- nargs()      nA <- nargs()
613      if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value      if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value  or M [ Lmat ] <- value
614          if(!is.integer(nc <- ncol(i)))          if(!is.integer(nc <- ncol(i)))
615              stop("'i' has no integer column number",              stop(".M.repl.i.2col(): 'i' has no integer column number;\n",
616                   " should never happen; please report")                   " should never happen; please report")
617          if(is.logical(i)) {          else if(!is.numeric(i) || nc != 2)
i <- c(i) # drop "matrix"
return( callNextMethod() )
} else if(!is.numeric(i) || nc != 2)
618              stop("such indexing must be by logical or 2-column numeric matrix")              stop("such indexing must be by logical or 2-column numeric matrix")
619            if(is.logical(i)) {
620                message(".M.repl.i.2col(): drop 'matrix' case ...")
621                ## c(i) : drop "matrix" to logical vector
622                return( callGeneric(x, i=c(i), value=value) )
623            }
624            if(!is.integer(i)) storage.mode(i) <- "integer"
625            if(any(i < 0))
626                stop("negative values are not allowed in a matrix subscript")
627            if(any(is.na(i)))
628                stop("NAs are not allowed in subscripted assignments")
629            if(any(i0 <- (i == 0))) # remove them
630                i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
631            ## now have integer i >= 1
632          m <- nrow(i)          m <- nrow(i)
633          mod.x <- .type.kind[.M.kind(x)]          ## mod.x <- .type.kind[.M.kind(x)]
634          if(length(value) > 0 && m %% length(value) != 0)          if(length(value) > 0 && m %% length(value) != 0)
635              warning("number of items to replace is not a multiple of replacement length")              warning("number of items to replace is not a multiple of replacement length")
636          ## recycle:          ## recycle:
637          value <- rep(value, length = m)          value <- rep(value, length = m)
638          i1 <- i[,1]          i1 <- i[,1]
639          i2 <- i[,2]          i2 <- i[,2]
640            if(m > 2)
641                message("m[ <ij-matrix> ] <- v: inefficiently treating single elements")
642          ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)          ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
643          for(k in seq_len(m))          for(k in seq_len(m))
644              x[i1[k], i2[k]] <- value[k]              x[i1[k], i2[k]] <- value[k]
x
645
646      } else stop("nargs() = ", nA, " should never happen; please report.")          x
647        } else stop("nargs() = ", nA,
648                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
649  }  }
650
651  setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
652                                  value = "replValue"),                                  value = "replValue"),
653            .M.repl.i.2col)            .M.repl.i.2col)
654
655    ## Three catch-all methods ... would be very inefficient for sparse*
656    ## --> extra methods in ./sparseMatrix.R
657    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
658                                    value = "Matrix"),
659                     function (x, i, j, ..., value)
660                     callGeneric(x=x, , j=j, value = as.vector(value)))
661
662    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
663                                    value = "Matrix"),
664                     function (x, i, j, ..., value)
665                     callGeneric(x=x, i=i, , value = as.vector(value)))
666
667  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
668                                  value = "Matrix"),                                  value = "Matrix"),
669                   function (x, i, j, value)                   function (x, i, j, ..., value)
670                   callGeneric(x=x, i=i, j=j, value = as.vector(value)))                   callGeneric(x=x, i=i, j=j, value = as.vector(value)))
671
672
673    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
674                                    value = "matrix"),
675                     function (x, i, j, ..., value)
676                     callGeneric(x=x, , j=j, value = c(value)))
677
678    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
679                                    value = "matrix"),
680                     function (x, i, j, ..., value)
681                     callGeneric(x=x, i=i, , value = c(value)))
682
683  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
684                                  value = "matrix"),                                  value = "matrix"),
685                   function (x, i, j, value)                   function (x, i, j, value)
# Line 412  Line 694
694                                 class(value),class(x)))                                 class(value),class(x)))
695                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
696            })            })

## 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.1673 changed lines Added in v.2256