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 1707, Thu Dec 21 08:03:05 2006 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)
setMethod("tail", signature(x = "Matrix"), utils:::tail.matrix)
## } else { # R 2.4.0 and newer
##     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("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
61
62
63  ## not exported but used more than once for "dimnames<-" method :  ## not exported but used more than once for "dimnames<-" method :
64  ## -- or do only once for all "Matrix" classes ??  ## -- or do only once for all "Matrix" classes ??
65  dimnamesGets <- function (x, value) {  dimnamesGets <- function (x, value) {
# Line 96  Line 78
78  setMethod("unname", signature("Matrix", force="missing"),  setMethod("unname", signature("Matrix", force="missing"),
79            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
80
81    setMethod("all", signature(x = "Matrix"),
82              function(x, ..., na.rm) { x <- as(x, "lMatrix"); callNextMethod()})
83    setMethod("any", signature(x = "Matrix"),
84              function(x, ..., na.rm) { x <- as(x, "lMatrix"); callNextMethod()})
85
86
87
88  Matrix <-  Matrix <-
89      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
90                sparse = NULL, forceCheck = FALSE)                sparse = NULL, forceCheck = FALSE)
91  {  {
92      sparseDefault <- function(m)      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
prod(dim(m)) > 2*sum(as(m, "matrix") != 0)
93
94      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
95      if(is.null(sparse) && (i.M || is(data, "matrix")))
96        if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
97          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
98
99      doDN <- TRUE      doDN <- TRUE
100      if (i.M && !forceCheck) {      if (i.M) {
101          sM <- is(data,"sparseMatrix")          sM <- is(data,"sparseMatrix")
102          if((sparse && sM) || (!sparse && !sM))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
103              return(data)              return(data)
104          ## else : convert  dense <-> sparse -> at end          ## else : convert  dense <-> sparse -> at end
105      }      }
# Line 119  Line 108
108              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
109          else if (missing(ncol))          else if (missing(ncol))
110              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
111          if(length(data) == 1 && data == 0 && !identical(sparse,FALSE)) {          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
112              if(is.null(sparse)) sparse <- TRUE              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
113                if(is.null(sparse)) sparse1 <- sparse <- TRUE
114              ## will be sparse: do NOT construct full matrix!              ## will be sparse: do NOT construct full matrix!
115              data <- new(if(is.numeric(data)) "dgTMatrix" else              data <- new(if(is.numeric(data)) "dgTMatrix" else
116                          if(is.logical(data)) "lgTMatrix" else                          if(is.logical(data)) "lgTMatrix" else
# Line 148  Line 138
138      if(isDiag)      if(isDiag)
139          isDiag <- isDiagonal(data)          isDiag <- isDiagonal(data)
140
### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R

141      ## Find proper matrix class 'cl'      ## Find proper matrix class 'cl'
142      cl <-      cl <-
143          if(isDiag)          if(isDiag && !isTRUE(sparse1))
144              "diagonalMatrix" # -> will automatically check for type              "diagonalMatrix" # -> will automatically check for type
145          else {          else {
146              ## consider it's type              ## consider it's type
# Line 193  Line 181
181            function(x, y) callGeneric(x, as.matrix(y)))            function(x, y) callGeneric(x, as.matrix(y)))
182
183  setMethod("%*%", signature(x = "numeric", y = "Matrix"),  setMethod("%*%", signature(x = "numeric", y = "Matrix"),
184            function(x, y) callGeneric(rbind(x), y))            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
185
186  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
187            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
# Line 207  Line 195
195  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
196            function(x, y = NULL)  callGeneric(as.matrix(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
197
198    ## maybe not optimal
199    setMethod("solve", signature(a = "Matrix", b = "missing"),
200              function(a, b, ...) solve(a, Diagonal(nrow(a))))
201
202  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
203            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, as.matrix(b)))
204    ## when no sub-class method is found, bail out
205    setMethod("solve", signature(a = "Matrix", b = "matrix"),
206              function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))
207
208  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
209  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 242  Line 237
237                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
238
239
240    ## FIXME: All of these should never be called
241    setMethod("chol", signature(x = "Matrix"),
242              function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))
243    setMethod("determinant", signature(x = "Matrix"),
244              function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))
245
246  setMethod("diag", signature(x = "Matrix"),  setMethod("diag", signature(x = "Matrix"),
247            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
248  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
# Line 256  Line 257
257                0-e1                0-e1
258            })            })
259
260  ## bail-outs:  ## old-style matrices are made into new ones
261  setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),  setMethod("Ops", signature(e1 = "Matrix", e2 = "matrix"),
262              function(e1, e2) callGeneric(e1, Matrix(e2)))
263    ##          callGeneric(e1, Matrix(e2, sparse=is(e1,"sparseMatrix"))))
264    setMethod("Ops", signature(e1 = "matrix", e2 = "Matrix"),
265              function(e1, e2) callGeneric(Matrix(e1), e2))
266
267    ## bail-outs -- on highest possible level, hence "Ops", not "Compare"/"Arith" :
268    setMethod("Ops", signature(e1 = "Matrix", e2 = "Matrix"),
269            function(e1, e2) {            function(e1, e2) {
270                d <- dimCheck(e1,e2)                d <- dimCheck(e1,e2)
271                .bail.out.2(.Generic, class(e1), class(e2))                .bail.out.2(.Generic, class(e1), class(e2))
272            })            })
273  setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),  setMethod("Ops", signature(e1 = "Matrix", e2 = "ANY"),
274            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
275  setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),  setMethod("Ops", signature(e1 = "ANY", e2 = "Matrix"),
276            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
277
278
# Line 301  Line 309
309            function(x,i,j, drop)            function(x,i,j, drop)
310            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
311
312  ##  "logical *vector* indexing, such as  M [ M >= 10 ] :  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
313  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  ## The following is *both* for    M [ <logical>   ]
314                           drop = "ANY"),  ##                 and also for   M [ <logical> , ]
315            function (x, i, j, drop) {  .M.sub.i.logical <- function (x, i, j, drop)
316    {
317        nA <- nargs()
318        if(nA == 2) { ##  M [ M >= 7 ]
319            ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
320                as(x, geClass(x))@x[as.vector(i)]                as(x, geClass(x))@x[as.vector(i)]
321                ## -> error when lengths don't match                ## -> error when lengths don't match
322            })      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
323            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
324
325  ## FIXME: The following is good for    M [ <logical>   ]      } else stop("nargs() = ", nA,
326  ##        *BUT* it also triggers for   M [ <logical> , ] where it is *WRONG*                  " should never happen; please report.")
327  ##       using nargs() does not help: it gives '3' for both cases  }
328  if(FALSE)  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
329                             drop = "ANY"),
330              .M.sub.i.logical)
331  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
332                           drop = "ANY"),                           drop = "ANY"),
333            function (x, i, j, drop) {            .M.sub.i.logical)
334                ## DEBUG
cat("[(Matrix,i,..): nargs=", nargs(),"\n")
as(x, geClass(x))@x[i] })
335
336    ## A[ ij ]  where ij is (i,j) 2-column matrix :
337    .M.sub.i.2col <- function (x, i, j, drop)
338    {
339        nA <- nargs()
340        if(nA == 2) { ##  M [ cbind(ii,jj) ]
341            if(!is.integer(nc <- ncol(i)))
342                stop("'i' has no integer column number",
343                     " should never happen; please report")
344            if(is.logical(i))
345                return(.M.sub.i.logical(x,i,j,drop))
346            else if(!is.numeric(i) || nc != 2)
347                stop("such indexing must be by logical or 2-column numeric matrix")
348            m <- nrow(i)
349            if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
350            ## else
351            i1 <- i[,1]
352            i2 <- i[,2]
353            ## potentially inefficient -- FIXME --
354            unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
355
356  ## "FIXME:"      } else stop("nargs() = ", nA, " should never happen; please report.")
357  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?  }
358  ##  and                A[ LL ]  where LL is a logical *vector*  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
359  ## -> [.data.frame uses nargs() - can we do this in the *generic* ?            .M.sub.i.2col)
360
361
362  ### "[<-" : -----------------  ### "[<-" : -----------------
# Line 333  Line 365
365  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
366                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
367            function (x, value) {            function (x, value) {
368                  ## Fails for 'nMatrix' ... FIXME : make sure have method there
369                x@x <- value                x@x <- value
370                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
371                x                x
372            })            })
373
374  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
375    .M.repl.i.2col <- function (x, i, j, value)
376    {
377        nA <- nargs()
378        if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value
379            if(!is.integer(nc <- ncol(i)))
380                stop("'i' has no integer column number",
381                     " should never happen; please report")
382            if(is.logical(i)) {
383                i <- c(i) # drop "matrix"
384                return( callNextMethod() )
385            } else if(!is.numeric(i) || nc != 2)
386                stop("such indexing must be by logical or 2-column numeric matrix")
387            m <- nrow(i)
388            mod.x <- .type.kind[.M.kind(x)]
389            if(length(value) > 0 && m %% length(value) != 0)
390                warning("number of items to replace is not a multiple of replacement length")
391            ## recycle:
392            value <- rep(value, length = m)
393            i1 <- i[,1]
394            i2 <- i[,2]
395            ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
396            for(k in seq_len(m))
397                x[i1[k], i2[k]] <- value[k]
398            x
399
400        } else stop("nargs() = ", nA, " should never happen; please report.")
401    }
402    setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
403                                    value = "replValue"),
404              .M.repl.i.2col)
405
406
407    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
408                                    value = "Matrix"),
409                     function (x, i, j, value) {
410    ### FIXME: *TEMPORARY* diagnostic output:
411                         cat("<Matrix1>[i,j] <- <Matrix1>:\n<Matrix1> = x :")
412                         str(x)
413                         cat("<Matrix2> = value :")
414                         str(value)
415                         cat("i :"); if(!missing(i)) str(i) else cat("<missing>\n")
416                         cat("j :"); if(!missing(j)) str(j) else cat("<missing>\n")
417
418                         callGeneric(x=x, i=i, j=j, value = as.vector(value))
419                     })
420    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
421                                    value = "Matrix"),
422                     function (x, i, j, value)
423                     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
424
425    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
426                                    value = "matrix"),
427                     function (x, i, j, value)
428                     callGeneric(x=x, i=i, j=j, value = c(value)))
429
430  ## (ANY,ANY,ANY) is used when no `real method' is implemented :  ## (ANY,ANY,ANY) is used when no `real method' is implemented :
431  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
432                                  value = "ANY"),                                  value = "ANY"),
433            function (x, i, j, value) {            function (x, i, j, value) {
434                if(!is.atomic(value))                if(!is.atomic(value))
435                    stop("RHS 'value' must match matrix class ", class(x))                    stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
436                                   class(value),class(x)))
437                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
438            })            })
439
# Line 356  Line 445
445            function(x, y) x)            function(x, y) x)
446  setMethod("cbind2", signature(x = "NULL", y="Matrix"),  setMethod("cbind2", signature(x = "NULL", y="Matrix"),
447            function(x, y) x)            function(x, y) x)
448    setMethod("cbind2", signature(x = "Matrix", y = "numeric"),
449              function(x, y) callGeneric(x, as.matrix(y)))
450    setMethod("cbind2", signature(x = "numeric", y = "Matrix"),
451              function(x, y) callGeneric(as.matrix(x), y))
452    setMethod("cbind2", signature(x = "ANY", y = "Matrix"),
453              function(x, y) .bail.out.2(.Generic, class(x), class(y)))
454    setMethod("cbind2", signature(x = "Matrix", y = "ANY"),
455              function(x, y) .bail.out.2(.Generic, class(x), class(y)))
456
457
458
459  setMethod("rbind2", signature(x = "Matrix", y = "NULL"),  setMethod("rbind2", signature(x = "Matrix", y = "NULL"),
460            function(x, y) x)            function(x, y) x)
# Line 363  Line 462
462            function(x, y) x)            function(x, y) x)
463  setMethod("rbind2", signature(x = "NULL", y="Matrix"),  setMethod("rbind2", signature(x = "NULL", y="Matrix"),
464            function(x, y) x)            function(x, y) x)
465    setMethod("rbind2", signature(x = "Matrix", y = "numeric"),
466              function(x, y) callGeneric(x, matrix(y, nrow = 1)))
467    setMethod("rbind2", signature(x = "numeric", y = "Matrix"),
468              function(x, y) callGeneric(matrix(x, nrow = 1), y))
469    setMethod("rbind2", signature(x = "ANY", y = "Matrix"),
470              function(x, y) .bail.out.2(.Generic, class(x), class(y)))
471    setMethod("rbind2", signature(x = "Matrix", y = "ANY"),
472              function(x, y) .bail.out.2(.Generic, class(x), class(y)))
473
474  ## Makes sure one gets x decent error message for the unimplemented cases:  ## Makes sure one gets x decent error message for the unimplemented cases:
475  setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),  setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),

Legend:
 Removed from v.1455 changed lines Added in v.1707