# 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 1799, Sat Mar 24 14:54:00 2007 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) as.vector(as(x, "matrix")))
# Line 56  Line 63
63
64  setMethod("dim", signature(x = "Matrix"),  setMethod("dim", signature(x = "Matrix"),
65            function(x) x@Dim, valueClass = "integer")            function(x) x@Dim, valueClass = "integer")
66
67    setMethod("length", "Matrix", function(x) prod(dim(x)))
68
69  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
70
71
72  ## not exported but used more than once for "dimnames<-" method :  ## not exported but used more than once for "dimnames<-" method :
73  ## -- or do only once for all "Matrix" classes ??  ## -- or do only once for all "Matrix" classes ??
74  dimnamesGets <- function (x, value) {  dimnamesGets <- function (x, value) {
# Line 75  Line 87
87  setMethod("unname", signature("Matrix", force="missing"),  setMethod("unname", signature("Matrix", force="missing"),
88            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
89
90    setMethod("all", signature(x = "Matrix"),
91              function(x, ..., na.rm) { x <- as(x, "lMatrix"); callGeneric()})
92    setMethod("any", signature(x = "Matrix"),
93              function(x, ..., na.rm) { x <- as(x, "lMatrix"); callGeneric()})
94
95    setMethod("!", "Matrix", function(e1) !as(e1, "lMatrix"))
96
97
98
99  Matrix <-  Matrix <-
100      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
101                sparse = NULL, forceCheck = FALSE)                sparse = NULL, forceCheck = FALSE)
# Line 88  Line 109
109
110      doDN <- TRUE      doDN <- TRUE
111      if (i.M) {      if (i.M) {
112            if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
113                warning("'nrow', 'ncol', etc, are disregarded when 'data' is \"Matrix\" already")
114          sM <- is(data,"sparseMatrix")          sM <- is(data,"sparseMatrix")
115          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
116              return(data)              return(data)
# Line 115  Line 138
138              dimnames(data) <- dimnames              dimnames(data) <- dimnames
139          }          }
140          doDN <- FALSE          doDN <- FALSE
141      }      } else if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
142            warning("'nrow', 'ncol', etc, are disregarded for matrix 'data'")
143
144      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
145      if (doDN && !is.null(dimnames))      if (doDN && !is.null(dimnames))
146          dimnames(data) <- dimnames          dimnames(data) <- dimnames
# Line 194  Line 219
219  ## when no sub-class method is found, bail out  ## when no sub-class method is found, bail out
220  setMethod("solve", signature(a = "Matrix", b = "matrix"),  setMethod("solve", signature(a = "Matrix", b = "matrix"),
221            function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))            function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))
222    setMethod("solve", signature(a = "Matrix", b = "Matrix"),
223              function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
224
225  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
226  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 238  Line 265
265  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
266            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
267
268  ## Group Methods  setMethod("dim<-", signature(x = "Matrix", value = "ANY"),
269  setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)            function(x, value) {
270  ## "fallback":                if(!is.numeric(value) || length(value) != 2)
271  setMethod("-", signature(e1 = "Matrix", e2 = "missing"),                    stop("dim(.) value must be numeric of length 2")
272            function(e1) {                if(prod(dim(x)) != prod(value <- as.integer(value)))
273                warning("inefficient method used for \"- e1\"")                    stop("dimensions don't match the number of cells")
274                0-e1                clx <- class(x)
275                  if(substring(clx,2) == "geMatrix") {
276                      x@Dim <- value
277                      if(length(x@factors) > 0)
278                          x@factors <- list()
279                      x
280                  } else if(extends(clx, "denseMatrix")) {
281                      x <- as_geSimpl2(x, clx)
282                      dim(x) <- value
283                  } else { ## FIXME: this is very inefficient for large sparse x
284                      Matrix(as.vector(x), value[1], value[2])
285                  }
286            })            })
287
288  ## old-style matrices are made into new ones  ## MM: More or less "Cut & paste" from
289  setMethod("Ops", signature(e1 = "Matrix", e2 = "matrix"),  ## --- diff.default() from  R/src/library/base/R/diff.R :
290            function(e1, e2) callGeneric(e1, Matrix(e2)))  setMethod("diff", signature(x = "Matrix"),
291  ##          callGeneric(e1, Matrix(e2, sparse=is(e1,"sparseMatrix"))))            function(x, lag = 1, differences = 1, ...) {
292  setMethod("Ops", signature(e1 = "matrix", e2 = "Matrix"),                if (length(lag) > 1 || length(differences) > 1 ||
293            function(e1, e2) callGeneric(Matrix(e1), e2))                    lag < 1 || differences < 1)
294                      stop("'lag' and 'differences' must be integers >= 1")
295  ## bail-outs -- on highest possible level, hence "Ops", not "Compare"/"Arith" :                xlen <- nrow(x)
296  setMethod("Ops", signature(e1 = "Matrix", e2 = "Matrix"),                if (lag * differences >= xlen)
297            function(e1, e2) {                    return(x[,FALSE][0])  # empty of proper mode
298                d <- dimCheck(e1,e2)
299                .bail.out.2(.Generic, class(e1), class(e2))                i1 <- -1:-lag
300                  for (i in 1:differences)
301                      x <- x[i1, , drop = FALSE] -
302                          x[-nrow(x):-(nrow(x)-lag+1), , drop = FALSE]
303                  x
304            })            })
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)))
305
306
307    ## Group Methods
308
309    ##-> see ./Ops.R
310
311  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
312  ###  ###
# Line 285  Line 326
326  ## select rows  ## select rows
327  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
328                           drop = "missing"),                           drop = "missing"),
329            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, drop) {
330                  if(nargs() == 1) { ## e.g. M[0] , M[TRUE],  M[1:2]
331                      if(any(i)) as.vector(x)[i] else as.vector(x[1,1])[FALSE]
332                  } else callGeneric(x, i=i, drop= TRUE)})
333
334  ## select columns  ## select columns
335  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
336                           drop = "missing"),                           drop = "missing"),
# Line 313  Line 358
358          stop("not-yet-implemented 'Matrix' subsetting") ## FIXME          stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
359
360      } else stop("nargs() = ", nA,      } else stop("nargs() = ", nA,
361                  " should never happen; please report.")                  ".  Extraneous illegal arguments inside '[ .. ]' ?")
362  }  }
363  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
364                           drop = "ANY"),                           drop = "ANY"),
# Line 343  Line 388
388          ## potentially inefficient -- FIXME --          ## potentially inefficient -- FIXME --
389          unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))          unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
390
391      } else stop("nargs() = ", nA, " should never happen; please report.")      } else stop("nargs() = ", nA,
392                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
393  }  }
394  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
395            .M.sub.i.2col)            .M.sub.i.2col)
# Line 356  Line 402
402                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
403            function (x, value) {            function (x, value) {
404                ## Fails for 'nMatrix' ... FIXME : make sure have method there                ## Fails for 'nMatrix' ... FIXME : make sure have method there
405                x@x <- value                x@x <- rep(value, length = length(x@x))
406                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
407                x                x
408            })            })
409
410  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
411    ## ----------------   The cheap general method --- FIXME: provide special ones
412  .M.repl.i.2col <- function (x, i, j, value)  .M.repl.i.2col <- function (x, i, j, value)
413  {  {
414      nA <- nargs()      nA <- nargs()
# Line 369  Line 416
416          if(!is.integer(nc <- ncol(i)))          if(!is.integer(nc <- ncol(i)))
417              stop("'i' has no integer column number",              stop("'i' has no integer column number",
418                   " should never happen; please report")                   " should never happen; please report")
419            else if(!is.numeric(i) || nc != 2)
420                stop("such indexing must be by logical or 2-column numeric matrix")
421          if(is.logical(i)) {          if(is.logical(i)) {
422                message(".M.repl.i.2col(): drop 'matrix' case ...")
423              i <- c(i) # drop "matrix"              i <- c(i) # drop "matrix"
424              return( callNextMethod() )              return( callNextMethod() )
425          } else if(!is.numeric(i) || nc != 2)          }
426              stop("such indexing must be by logical or 2-column numeric matrix")          if(!is.integer(i)) storage.mode(i) <- "integer"
427            if(any(i < 0))
428                stop("negative values are not allowed in a matrix subscript")
429            if(any(is.na(i)))
430                stop("NAs are not allowed in subscripted assignments")
431            if(any(i0 <- (i == 0))) # remove them
432                i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
433            ## now have integer i >= 1
434          m <- nrow(i)          m <- nrow(i)
435          mod.x <- .type.kind[.M.kind(x)]          ## mod.x <- .type.kind[.M.kind(x)]
436          if(length(value) > 0 && m %% length(value) != 0)          if(length(value) > 0 && m %% length(value) != 0)
437              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")
438          ## recycle:          ## recycle:
# Line 385  Line 442
442          ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)          ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
443          for(k in seq_len(m))          for(k in seq_len(m))
444              x[i1[k], i2[k]] <- value[k]              x[i1[k], i2[k]] <- value[k]
x
445
446      } else stop("nargs() = ", nA, " should never happen; please report.")          x
447        } else stop("nargs() = ", nA,
448                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
449  }  }
450
451  setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
452                                  value = "replValue"),                                  value = "replValue"),
453            .M.repl.i.2col)            .M.repl.i.2col)
# Line 396  Line 455
455
456  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
457                                  value = "Matrix"),                                  value = "Matrix"),
458                     function (x, i, j, value) {
459    ### *TEMPORARY* diagnostic output:
460    ##                  cat("<Matrix1>[i,j] <- <Matrix1>:\n<Matrix1> = x :")
461    ##                  str(x)
462    ##                  cat("<Matrix2> = value :")
463    ##                  str(value)
464    ##                  cat("i :"); if(!missing(i)) str(i) else cat("<missing>\n")
465    ##                  cat("j :"); if(!missing(j)) str(j) else cat("<missing>\n")
466
467                         callGeneric(x=x, i=i, j=j, value = as.vector(value))
468                     })
469    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
470                                    value = "Matrix"),
471                   function (x, i, j, value)                   function (x, i, j, value)
472                   callGeneric(x=x, i=i, j=j, value = as.vector(value)))                   callGeneric(x=x, i=i, j=j, value = as.vector(value)))
473
474  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
475                                  value = "matrix"),                                  value = "matrix"),
476                   function (x, i, j, value)                   function (x, i, j, value)
# Line 412  Line 485
485                                 class(value),class(x)))                                 class(value),class(x)))
486                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
487            })            })

## 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.1799