# 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 2005, Wed Jul 18 14:46:20 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    ## NOTE:  "&" and "|"  are now in group "Logic" c "Ops" --> ./Ops.R
96    ##        "!" is in ./not.R
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 101  Line 124
124          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
125              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
126              if(is.null(sparse)) sparse1 <- sparse <- TRUE              if(is.null(sparse)) sparse1 <- sparse <- TRUE
127                i.M <- sM <- TRUE
128              ## will be sparse: do NOT construct full matrix!              ## will be sparse: do NOT construct full matrix!
129              data <- new(if(is.numeric(data)) "dgTMatrix" else              data <- new(if(is.numeric(data)) "dgTMatrix" else
130                          if(is.logical(data)) "lgTMatrix" else                          if(is.logical(data)) "lgTMatrix" else
# Line 115  Line 139
139              dimnames(data) <- dimnames              dimnames(data) <- dimnames
140          }          }
141          doDN <- FALSE          doDN <- FALSE
142      }      } else if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
143            warning("'nrow', 'ncol', etc, are disregarded for matrix 'data'")
144
145      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
146      if (doDN && !is.null(dimnames))      if (doDN && !is.null(dimnames))
147          dimnames(data) <- dimnames          dimnames(data) <- dimnames
# Line 158  Line 184
184                    }, sep="")                    }, sep="")
185          }          }
186
187      ## Now coerce and return      ## Can we coerce and be done?
188        if(!canCoerce(data,cl)) { ## try to coerce ``via'' virtual classes
189            if(sparse && !sM)
190                data <- as(data, "sparseMatrix")
191            else if(!sparse && !is(data, "denseMatrix"))
192                data <- as(data, "denseMatrix")
193            if(isTri && !is(data, "triangularMatrix"))
194                data <- as(data, "triangularMatrix")
195            else if(isSym && !is(data, "symmetricMatrix"))
196                data <- as(data, "symmetricMatrix")
197        }
198        ## now coerce in any case .. maybe producing sensible error message:
199      as(data, cl)      as(data, cl)
200  }  }
201
# Line 194  Line 231
231  ## when no sub-class method is found, bail out  ## when no sub-class method is found, bail out
232  setMethod("solve", signature(a = "Matrix", b = "matrix"),  setMethod("solve", signature(a = "Matrix", b = "matrix"),
233            function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))            function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))
234    setMethod("solve", signature(a = "Matrix", b = "Matrix"),
235              function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
236
237  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
238  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 220  Line 259
259  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
260                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
261            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
262                  if(is(X, "sparseMatrix"))
263                      warning("using slow kronecker() method")
264                X <- as(X, "matrix") ; Matrix(callGeneric()) })                X <- as(X, "matrix") ; Matrix(callGeneric()) })
265
266  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
267                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
268            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
269                  if(is(Y, "sparseMatrix"))
270                      warning("using slow kronecker() method")
271                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
272
273
# Line 238  Line 282
282  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
283            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
284
285  ## Group Methods  setMethod("norm", signature(x = "Matrix", type = "character"),
286  setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)            function(x, type, ...) .bail.out.1(.Generic, class(x)))
287  ## "fallback":  setMethod("rcond", signature(x = "Matrix", type = "character"),
288  setMethod("-", signature(e1 = "Matrix", e2 = "missing"),            function(x, type, ...) .bail.out.1(.Generic, class(x)))
289            function(e1) {
290                warning("inefficient method used for \"- e1\"")
291                0-e1  ## for all :
292    setMethod("norm", signature(x = "ANY", type = "missing"),
293              function(x, type, ...) norm(x, type = "O", ...))
294    setMethod("rcond", signature(x = "ANY", type = "missing"),
295              function(x, type, ...) rcond(x, type = "O", ...))
296
297
298
299
300
301    ## MM: More or less "Cut & paste" from
302    ## --- diff.default() from  R/src/library/base/R/diff.R :
303    setMethod("diff", signature(x = "Matrix"),
304              function(x, lag = 1, differences = 1, ...) {
305                  if (length(lag) > 1 || length(differences) > 1 ||
306                      lag < 1 || differences < 1)
307                      stop("'lag' and 'differences' must be integers >= 1")
308                  xlen <- nrow(x)
309                  if (lag * differences >= xlen)
310                      return(x[,FALSE][0])  # empty of proper mode
311
312                  i1 <- -1:-lag
313                  for (i in 1:differences)
314                      x <- x[i1, , drop = FALSE] -
315                          x[-nrow(x):-(nrow(x)-lag+1), , drop = FALSE]
316                  x
317            })            })
318
319  ## old-style matrices are made into new ones  setMethod("image", "Matrix",
320  setMethod("Ops", signature(e1 = "Matrix", e2 = "matrix"),            function(x, ...) { # coercing to sparse is not inefficient,
321            function(e1, e2) callGeneric(e1, Matrix(e2)))                ##               since we need 'i' and 'j' for levelplot()
322  ##          callGeneric(e1, Matrix(e2, sparse=is(e1,"sparseMatrix"))))                x <- as(as(x, "sparseMatrix"), "dMatrix")
323  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))
324            })            })
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)))
325
326
327    ## Group Methods
328
329    ##-> see ./Ops.R
330    ##         ~~~~~
331    ## For all  non-dMatrix objects, and note that  "all" and "any" have their own
332    setMethod("Summary", signature(x = "Matrix", na.rm = "ANY"),
333              function(x, ..., na.rm)
334              callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm))
335
336
337  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
338  ###  ###
# Line 285  Line 352
352  ## select rows  ## select rows
353  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
354                           drop = "missing"),                           drop = "missing"),
355            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, drop) {
356                  if(nargs() == 1) { ## e.g. M[0] , M[TRUE],  M[1:2]
357                      if(any(i)) as.vector(x)[i] else as.vector(x[1,1])[FALSE]
358                  } else callGeneric(x, i=i, drop= TRUE)})
359
360  ## select columns  ## select columns
361  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
362                           drop = "missing"),                           drop = "missing"),
# Line 313  Line 384
384          stop("not-yet-implemented 'Matrix' subsetting") ## FIXME          stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
385
386      } else stop("nargs() = ", nA,      } else stop("nargs() = ", nA,
387                  " should never happen; please report.")                  ".  Extraneous illegal arguments inside '[ .. ]' ?")
388  }  }
389  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
390                           drop = "ANY"),                           drop = "ANY"),
# Line 343  Line 414
414          ## potentially inefficient -- FIXME --          ## potentially inefficient -- FIXME --
415          unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))          unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
416
417      } else stop("nargs() = ", nA, " should never happen; please report.")      } else stop("nargs() = ", nA,
418                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
419  }  }
420  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
421            .M.sub.i.2col)            .M.sub.i.2col)
# Line 356  Line 428
428                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
429            function (x, value) {            function (x, value) {
430                ## Fails for 'nMatrix' ... FIXME : make sure have method there                ## Fails for 'nMatrix' ... FIXME : make sure have method there
431                x@x <- value                x@x <- rep(value, length = length(x@x))
432                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
433                x                x
434            })            })
435
436  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
437    ## ----------------   The cheap general method --- FIXME: provide special ones
438  .M.repl.i.2col <- function (x, i, j, value)  .M.repl.i.2col <- function (x, i, j, value)
439  {  {
440      nA <- nargs()      nA <- nargs()
# Line 369  Line 442
442          if(!is.integer(nc <- ncol(i)))          if(!is.integer(nc <- ncol(i)))
443              stop("'i' has no integer column number",              stop("'i' has no integer column number",
444                   " should never happen; please report")                   " should never happen; please report")
445            else if(!is.numeric(i) || nc != 2)
446                stop("such indexing must be by logical or 2-column numeric matrix")
447          if(is.logical(i)) {          if(is.logical(i)) {
448                message(".M.repl.i.2col(): drop 'matrix' case ...")
449              i <- c(i) # drop "matrix"              i <- c(i) # drop "matrix"
450              return( callNextMethod() )              return( callNextMethod() )
451          } else if(!is.numeric(i) || nc != 2)          }
452              stop("such indexing must be by logical or 2-column numeric matrix")          if(!is.integer(i)) storage.mode(i) <- "integer"
453            if(any(i < 0))
454                stop("negative values are not allowed in a matrix subscript")
455            if(any(is.na(i)))
456                stop("NAs are not allowed in subscripted assignments")
457            if(any(i0 <- (i == 0))) # remove them
458                i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
459            ## now have integer i >= 1
460          m <- nrow(i)          m <- nrow(i)
461          mod.x <- .type.kind[.M.kind(x)]          ## mod.x <- .type.kind[.M.kind(x)]
462          if(length(value) > 0 && m %% length(value) != 0)          if(length(value) > 0 && m %% length(value) != 0)
463              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")
464          ## recycle:          ## recycle:
# Line 385  Line 468
468          ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)          ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
469          for(k in seq_len(m))          for(k in seq_len(m))
470              x[i1[k], i2[k]] <- value[k]              x[i1[k], i2[k]] <- value[k]
x
471
472      } else stop("nargs() = ", nA, " should never happen; please report.")          x
473        } else stop("nargs() = ", nA,
474                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
475  }  }
476
477  setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
478                                  value = "replValue"),                                  value = "replValue"),
479            .M.repl.i.2col)            .M.repl.i.2col)
# Line 396  Line 481
481
482  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
483                                  value = "Matrix"),                                  value = "Matrix"),
484                     function (x, i, j, value) {
485    ### *TEMPORARY* diagnostic output:
486    ##                  cat("<Matrix1>[i,j] <- <Matrix1>:\n<Matrix1> = x :")
487    ##                  str(x)
488    ##                  cat("<Matrix2> = value :")
489    ##                  str(value)
490    ##                  cat("i :"); if(!missing(i)) str(i) else cat("<missing>\n")
491    ##                  cat("j :"); if(!missing(j)) str(j) else cat("<missing>\n")
492
493                         callGeneric(x=x, i=i, j=j, value = as.vector(value))
494                     })
495    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
496                                    value = "Matrix"),
497                   function (x, i, j, value)                   function (x, i, j, value)
498                   callGeneric(x=x, i=i, j=j, value = as.vector(value)))                   callGeneric(x=x, i=i, j=j, value = as.vector(value)))
499
500  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
501                                  value = "matrix"),                                  value = "matrix"),
502                   function (x, i, j, value)                   function (x, i, j, value)
# Line 412  Line 511
511                                 class(value),class(x)))                                 class(value),class(x)))
512                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
513            })            })

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