# SCM Repository

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

# Diff of /pkg/R/Matrix.R

revision 1455, Mon Aug 28 15:35:44 2006 UTC revision 1747, Mon Jan 29 20:17:33 2007 UTC
# Line 6  Line 6
6  setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))  setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))
7  setAs("Matrix", "denseMatrix",  function(from) as_dense(from))  setAs("Matrix", "denseMatrix",  function(from) as_dense(from))
8
9    ## Most of these work; this is a last resort:
10    setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:
11          function(from) .bail.out.2("coerce", class(from), class(to)))
12    setAs(from = "matrix", to = "Matrix", function(from) Matrix(from))
13
14  ## ## probably not needed eventually:  ## ## probably not needed eventually:
15  ## setAs(from = "ddenseMatrix", to = "matrix",  ## setAs(from = "ddenseMatrix", to = "matrix",
16  ##       function(from) {  ##       function(from) {
# Line 19  Line 24
24  setMethod("as.array",  signature(x = "Matrix"), function(x) as(x, "matrix"))  setMethod("as.array",  signature(x = "Matrix"), function(x) as(x, "matrix"))
25
26  ## 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:
27  ## if(paste(R.version\$major, R.version\$minor, sep=".") < "2.4") {  setMethod("head", signature(x = "Matrix"), utils::head.matrix)
28      setMethod("head", signature(x = "Matrix"), utils:::head.matrix)  setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
setMethod("tail", signature(x = "Matrix"), utils:::tail.matrix)
## } else { # R 2.4.0 and newer
##     setMethod("head", signature(x = "Matrix"), utils::head.matrix)
##     setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
## }
29
30  ## slow "fall back" method {subclasses should have faster ones}:  ## slow "fall back" method {subclasses should have faster ones}:
31  setMethod("as.vector", signature(x = "Matrix", mode = "missing"),  setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
# Line 38  Line 38
38            function(x, ...) as.logical(as.vector(x)))            function(x, ...) as.logical(as.vector(x)))
39
40
41  ## 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
42  setMethod("isSymmetric", signature(object = "symmetricMatrix"),  setMethod("isSymmetric", signature(object = "symmetricMatrix"),
43            function(object,tol) TRUE)            function(object,tol) TRUE)
44  setMethod("isSymmetric", signature(object = "triangularMatrix"),  setMethod("isSymmetric", signature(object = "triangularMatrix"),
45            ## TRUE iff diagonal:            ## TRUE iff diagonal:
46            function(object,tol) isDiagonal(object))            function(object,tol) isDiagonal(object))
47
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)
})

48  setMethod("isTriangular", signature(object = "triangularMatrix"),  setMethod("isTriangular", signature(object = "triangularMatrix"),
49            function(object, ...) TRUE)            function(object, ...) TRUE)
50
# Line 77  Line 56
56
57  setMethod("dim", signature(x = "Matrix"),  setMethod("dim", signature(x = "Matrix"),
58            function(x) x@Dim, valueClass = "integer")            function(x) x@Dim, valueClass = "integer")
59
60    setMethod("length", "Matrix", function(x) prod(dim(x)))
61
62  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
63
64
65  ## not exported but used more than once for "dimnames<-" method :  ## not exported but used more than once for "dimnames<-" method :
66  ## -- or do only once for all "Matrix" classes ??  ## -- or do only once for all "Matrix" classes ??
67  dimnamesGets <- function (x, value) {  dimnamesGets <- function (x, value) {
# Line 96  Line 80
80  setMethod("unname", signature("Matrix", force="missing"),  setMethod("unname", signature("Matrix", force="missing"),
81            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
82
83    setMethod("all", signature(x = "Matrix"),
84              function(x, ..., na.rm) { x <- as(x, "lMatrix"); callGeneric()})
85    setMethod("any", signature(x = "Matrix"),
86              function(x, ..., na.rm) { x <- as(x, "lMatrix"); callGeneric()})
87
88    setMethod("!", "Matrix", function(e1) !as(e1, "lMatrix"))
89
90
91
92  Matrix <-  Matrix <-
93      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
94                sparse = NULL, forceCheck = FALSE)                sparse = NULL, forceCheck = FALSE)
95  {  {
96      sparseDefault <- function(m)      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
prod(dim(m)) > 2*sum(as(m, "matrix") != 0)
97
98      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
99      if(is.null(sparse) && (i.M || is(data, "matrix")))
100        if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
101          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
102
103      doDN <- TRUE      doDN <- TRUE
104      if (i.M && !forceCheck) {      if (i.M) {
105          sM <- is(data,"sparseMatrix")          sM <- is(data,"sparseMatrix")
106          if((sparse && sM) || (!sparse && !sM))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
107              return(data)              return(data)
108          ## else : convert  dense <-> sparse -> at end          ## else : convert  dense <-> sparse -> at end
109      }      }
# Line 119  Line 112
112              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
113          else if (missing(ncol))          else if (missing(ncol))
114              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
115          if(length(data) == 1 && data == 0 && !identical(sparse,FALSE)) {          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
116              if(is.null(sparse)) sparse <- TRUE              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
117                if(is.null(sparse)) sparse1 <- sparse <- TRUE
118              ## will be sparse: do NOT construct full matrix!              ## will be sparse: do NOT construct full matrix!
119              data <- new(if(is.numeric(data)) "dgTMatrix" else              data <- new(if(is.numeric(data)) "dgTMatrix" else
120                          if(is.logical(data)) "lgTMatrix" else                          if(is.logical(data)) "lgTMatrix" else
# Line 135  Line 129
129              dimnames(data) <- dimnames              dimnames(data) <- dimnames
130          }          }
131          doDN <- FALSE          doDN <- FALSE
132      }      } else if(!missing(nrow) || !missing(ncol))
133            warning("'nrow', 'ncol', etc, are disregarded for matrix 'data'")
134
135      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
136      if (doDN && !is.null(dimnames))      if (doDN && !is.null(dimnames))
137          dimnames(data) <- dimnames          dimnames(data) <- dimnames
# Line 148  Line 144
144      if(isDiag)      if(isDiag)
145          isDiag <- isDiagonal(data)          isDiag <- isDiagonal(data)
146
### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R

147      ## Find proper matrix class 'cl'      ## Find proper matrix class 'cl'
148      cl <-      cl <-
149          if(isDiag)          if(isDiag && !isTRUE(sparse1))
150              "diagonalMatrix" # -> will automatically check for type              "diagonalMatrix" # -> will automatically check for type
151          else {          else {
152              ## consider it's type              ## consider it's type
# Line 193  Line 187
187            function(x, y) callGeneric(x, as.matrix(y)))            function(x, y) callGeneric(x, as.matrix(y)))
188
189  setMethod("%*%", signature(x = "numeric", y = "Matrix"),  setMethod("%*%", signature(x = "numeric", y = "Matrix"),
190            function(x, y) callGeneric(rbind(x), y))            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
191
192  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
193            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
# Line 207  Line 201
201  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
202            function(x, y = NULL)  callGeneric(as.matrix(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
203
204    ## maybe not optimal
205    setMethod("solve", signature(a = "Matrix", b = "missing"),
206              function(a, b, ...) solve(a, Diagonal(nrow(a))))
207
208  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
209            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, as.matrix(b)))
210    ## when no sub-class method is found, bail out
211    setMethod("solve", signature(a = "Matrix", b = "matrix"),
212              function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))
213    setMethod("solve", signature(a = "Matrix", b = "Matrix"),
214              function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
215
216  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
217  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 242  Line 245
245                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
246
247
248    ## FIXME: All of these should never be called
249    setMethod("chol", signature(x = "Matrix"),
250              function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))
251    setMethod("determinant", signature(x = "Matrix"),
252              function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))
253
254  setMethod("diag", signature(x = "Matrix"),  setMethod("diag", signature(x = "Matrix"),
255            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
256  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
257            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
258
259  ## Group Methods  ## Group Methods
setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)
## "fallback":
setMethod("-", signature(e1 = "Matrix", e2 = "missing"),
function(e1) {
warning("inefficient method used for \"- e1\"")
0-e1
})

## bail-outs:
setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),
function(e1, e2) {
d <- dimCheck(e1,e2)
.bail.out.2(.Generic, class(e1), class(e2))
})
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)))

260
261    ##-> see ./Ops.R
262
263  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
264  ###  ###
# Line 301  Line 292
292            function(x,i,j, drop)            function(x,i,j, drop)
293            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
294
295  ##  "logical *vector* indexing, such as  M [ M >= 10 ] :  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
296  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  ## The following is *both* for    M [ <logical>   ]
297                           drop = "ANY"),  ##                 and also for   M [ <logical> , ]
298            function (x, i, j, drop) {  .M.sub.i.logical <- function (x, i, j, drop)
299    {
300        nA <- nargs()
301        if(nA == 2) { ##  M [ M >= 7 ]
302            ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
303                as(x, geClass(x))@x[as.vector(i)]                as(x, geClass(x))@x[as.vector(i)]
304                ## -> error when lengths don't match                ## -> error when lengths don't match
305            })      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
306            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
307
308  ## FIXME: The following is good for    M [ <logical>   ]      } else stop("nargs() = ", nA,
309  ##        *BUT* it also triggers for   M [ <logical> , ] where it is *WRONG*                  ".  Extraneous illegal arguments inside '[ .. ]' ?")
310  ##       using nargs() does not help: it gives '3' for both cases  }
311  if(FALSE)  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
312                             drop = "ANY"),
313              .M.sub.i.logical)
314  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
315                           drop = "ANY"),                           drop = "ANY"),
316            function (x, i, j, drop) {            .M.sub.i.logical)
## DEBUG
cat("[(Matrix,i,..): nargs=", nargs(),"\n")
as(x, geClass(x))@x[i] })
317
318
319  ## "FIXME:"  ## A[ ij ]  where ij is (i,j) 2-column matrix :
320  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?  .M.sub.i.2col <- function (x, i, j, drop)
321  ##  and                A[ LL ]  where LL is a logical *vector*  {
322  ## -> [.data.frame uses nargs() - can we do this in the *generic* ?      nA <- nargs()
323        if(nA == 2) { ##  M [ cbind(ii,jj) ]
324            if(!is.integer(nc <- ncol(i)))
325                stop("'i' has no integer column number",
326                     " should never happen; please report")
327            if(is.logical(i))
328                return(.M.sub.i.logical(x,i,j,drop))
329            else if(!is.numeric(i) || nc != 2)
330                stop("such indexing must be by logical or 2-column numeric matrix")
331            m <- nrow(i)
332            if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
333            ## else
334            i1 <- i[,1]
335            i2 <- i[,2]
336            ## potentially inefficient -- FIXME --
337            unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
338
339        } else stop("nargs() = ", nA,
340                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
341    }
342    setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
343              .M.sub.i.2col)
344
345
346  ### "[<-" : -----------------  ### "[<-" : -----------------
# Line 333  Line 349
349  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
350                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
351            function (x, value) {            function (x, value) {
352                x@x <- value                ## Fails for 'nMatrix' ... FIXME : make sure have method there
353                  x@x <- rep(value, length = length(x@x))
354                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
355                x                x
356            })            })
357
358  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
359    ## ----------------   The cheap general method --- FIXME: provide special ones
360    .M.repl.i.2col <- function (x, i, j, value)
361    {
362        nA <- nargs()
363        if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value
364            if(!is.integer(nc <- ncol(i)))
365                stop("'i' has no integer column number",
366                     " should never happen; please report")
367            else if(!is.numeric(i) || nc != 2)
368                stop("such indexing must be by logical or 2-column numeric matrix")
369            if(is.logical(i)) {
370                message(".M.repl.i.2col(): drop 'matrix' case ...")
371                i <- c(i) # drop "matrix"
372                return( callNextMethod() )
373            }
374            if(!is.integer(i)) storage.mode(i) <- "integer"
375            if(any(i < 0))
376                stop("negative values are not allowed in a matrix subscript")
377            if(any(is.na(i)))
378                stop("NAs are not allowed in subscripted assignments")
379            if(any(i0 <- (i == 0))) # remove them
380                i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
381            ## now have integer i >= 1
382            m <- nrow(i)
383            ## mod.x <- .type.kind[.M.kind(x)]
384            if(length(value) > 0 && m %% length(value) != 0)
385                warning("number of items to replace is not a multiple of replacement length")
386            ## recycle:
387            value <- rep(value, length = m)
388            i1 <- i[,1]
389            i2 <- i[,2]
390            ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
391            for(k in seq_len(m))
392                x[i1[k], i2[k]] <- value[k]
393
394            x
395        } else stop("nargs() = ", nA,
396                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
397    }
398
399    setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
400                                    value = "replValue"),
401              .M.repl.i.2col)
402
403
404    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
405                                    value = "Matrix"),
406                     function (x, i, j, value) {
407    ### *TEMPORARY* diagnostic output:
408    ##                  cat("<Matrix1>[i,j] <- <Matrix1>:\n<Matrix1> = x :")
409    ##                  str(x)
410    ##                  cat("<Matrix2> = value :")
411    ##                  str(value)
412    ##                  cat("i :"); if(!missing(i)) str(i) else cat("<missing>\n")
413    ##                  cat("j :"); if(!missing(j)) str(j) else cat("<missing>\n")
414
415                         callGeneric(x=x, i=i, j=j, value = as.vector(value))
416                     })
417    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
418                                    value = "Matrix"),
419                     function (x, i, j, value)
420                     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
421
422    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
423                                    value = "matrix"),
424                     function (x, i, j, value)
425                     callGeneric(x=x, i=i, j=j, value = c(value)))
426
427  ## (ANY,ANY,ANY) is used when no `real method' is implemented :  ## (ANY,ANY,ANY) is used when no `real method' is implemented :
428  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
429                                  value = "ANY"),                                  value = "ANY"),
430            function (x, i, j, value) {            function (x, i, j, value) {
431                if(!is.atomic(value))                if(!is.atomic(value))
432                    stop("RHS 'value' must match matrix class ", class(x))                    stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
433                                   class(value),class(x)))
434                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
435            })            })

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

 root@r-forge.r-project.org ViewVC Help Powered by ViewVC 1.0.0
Thanks to: