# SCM Repository

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

# Diff of /pkg/R/Matrix.R

revision 1290, Thu Jun 8 09:30:21 2006 UTC revision 1714, Thu Dec 28 22:11:32 2006 UTC
# Line 1  Line 1
1  #### Toplevel ``virtual'' class "Matrix"  #### Toplevel ``virtual'' class "Matrix"
2
3
4    ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)
5
6    setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))
7    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 12  Line 23
23  ## for 'Matrix' objects, as.array() should be equivalent:  ## for 'Matrix' objects, as.array() should be equivalent:
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:
28    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"),
32            function(x) as.vector(as(x, "matrix")))            function(x) as.vector(as(x, "matrix")))
33
34    ## mainly need these for "dMatrix" or "lMatrix" respectively, but why not general:
35    setMethod("as.numeric", signature(x = "Matrix"),
36              function(x, ...) as.numeric(as.vector(x)))
37    setMethod("as.logical", signature(x = "Matrix"),
38              function(x, ...) as.logical(as.vector(x)))
39
40  ## Note that isSymmetric is *not* exported
41  ## but that "base" has an isSymmetric() S3-generic since R 2.3.0  ## "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 56  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 75  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)                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
100      if (i.M) {      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 97  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 && is0(data) && !identical(sparse, FALSE)) {
112                ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
113                if(is.null(sparse)) sparse1 <- sparse <- TRUE
114                ## will be sparse: do NOT construct full matrix!
115                data <- new(if(is.numeric(data)) "dgTMatrix" else
116                            if(is.logical(data)) "lgTMatrix" else
117                            stop("invalid 'data'"),
118                            Dim = as.integer(c(nrow,ncol)),
119                            Dimnames = if(is.null(dimnames)) list(NULL,NULL)
120                            else dimnames)
121            } else { ## normal case
122          data <- .Internal(matrix(data, nrow, ncol, byrow))          data <- .Internal(matrix(data, nrow, ncol, byrow))
123          if(is.null(sparse))          if(is.null(sparse))
124              sparse <- sparseDefault(data)              sparse <- sparseDefault(data)
125          dimnames(data) <- dimnames          dimnames(data) <- dimnames
126      } else if (!is.null(dimnames))          }
127          dimnames(data) <- dimnames          doDN <- FALSE
128        }
129      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
130        if (doDN && !is.null(dimnames))
131            dimnames(data) <- dimnames
132
133      ## check for symmetric / triangular / diagonal :      ## check for symmetric / triangular / diagonal :
134      isSym <- isSymmetric(data)      isSym <- isSymmetric(data)
# Line 114  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 159  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)))

188  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
189            function(x, y = NULL)  callGeneric(rbind(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
190
191    ## The as.matrix() promotion seems illogical to MM,
192    ## but is according to help(tcrossprod, package = "base") :
193    setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
194              function(x, y = NULL) callGeneric(x, as.matrix(y)))
195    setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
196              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 180  Line 215
215            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
216  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
217            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
218    setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
219              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
220    setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
221              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
222
223    ## cheap fallbacks
224    setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
225              function(x, y = NULL) t(x) %*% y)
226    setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
227              function(x, y = NULL) x %*% t(y))
228
229  ## There are special sparse methods; this is a "fall back":  ## There are special sparse methods; this is a "fall back":
230  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
# Line 192  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"),
247              function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
248  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
249            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
250
251  ## 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)))

252
253    ##-> see ./Ops.R
254
255  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
256  ###  ###
# Line 249  Line 284
284            function(x,i,j, drop)            function(x,i,j, drop)
285            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
286
287  ##  "logical *vector* indexing, such as  M [ M >= 10 ] :  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
288  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  ## The following is *both* for    M [ <logical>   ]
289                           drop = "ANY"),  ##                 and also for   M [ <logical> , ]
290            function (x, i, j, drop) {  .M.sub.i.logical <- function (x, i, j, drop)
291    {
292        nA <- nargs()
293        if(nA == 2) { ##  M [ M >= 7 ]
294            ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
295                as(x, geClass(x))@x[as.vector(i)]                as(x, geClass(x))@x[as.vector(i)]
296                                          # -> error when lengths don't match          ## -> error when lengths don't match
297            })      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
298            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
299
300        } else stop("nargs() = ", nA,
301                    " should never happen; please report.")
302    }
303    setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
304                             drop = "ANY"),
305              .M.sub.i.logical)
306  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
307                           drop = "ANY"),                           drop = "ANY"),
308            function (x, i, j, drop) as(x, geClass(x))@x[i])            .M.sub.i.logical)
309
310
311  ## "FIXME:"  ## A[ ij ]  where ij is (i,j) 2-column matrix :
312  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?  .M.sub.i.2col <- function (x, i, j, drop)
313  ##  and                A[ LL ]  where LL is a logical *vector*  {
314  ## -> [.data.frame uses nargs() - can we do this in the *generic* ?      nA <- nargs()
315        if(nA == 2) { ##  M [ cbind(ii,jj) ]
316            if(!is.integer(nc <- ncol(i)))
317                stop("'i' has no integer column number",
318                     " should never happen; please report")
319            if(is.logical(i))
320                return(.M.sub.i.logical(x,i,j,drop))
321            else if(!is.numeric(i) || nc != 2)
322                stop("such indexing must be by logical or 2-column numeric matrix")
323            m <- nrow(i)
324            if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
325            ## else
326            i1 <- i[,1]
327            i2 <- i[,2]
328            ## potentially inefficient -- FIXME --
329            unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
330
331        } else stop("nargs() = ", nA, " should never happen; please report.")
332    }
333    setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
334              .M.sub.i.2col)
335
336
337  ### "[<-" : -----------------  ### "[<-" : -----------------
# Line 274  Line 340
340  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
341                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
342            function (x, value) {            function (x, value) {
343                  ## Fails for 'nMatrix' ... FIXME : make sure have method there
344                x@x <- value                x@x <- value
345                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
346                x                x
347            })            })
348
349  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
350    .M.repl.i.2col <- function (x, i, j, value)
351    {
352        nA <- nargs()
353        if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value
354            if(!is.integer(nc <- ncol(i)))
355                stop("'i' has no integer column number",
356                     " should never happen; please report")
357            if(is.logical(i)) {
358                i <- c(i) # drop "matrix"
359                return( callNextMethod() )
360            } else if(!is.numeric(i) || nc != 2)
361                stop("such indexing must be by logical or 2-column numeric matrix")
362            m <- nrow(i)
363            mod.x <- .type.kind[.M.kind(x)]
364            if(length(value) > 0 && m %% length(value) != 0)
365                warning("number of items to replace is not a multiple of replacement length")
366            ## recycle:
367            value <- rep(value, length = m)
368            i1 <- i[,1]
369            i2 <- i[,2]
370            ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
371            for(k in seq_len(m))
372                x[i1[k], i2[k]] <- value[k]
373            x
374
375        } else stop("nargs() = ", nA, " should never happen; please report.")
376    }
377    setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
378                                    value = "replValue"),
379              .M.repl.i.2col)
380
381
382    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
383                                    value = "Matrix"),
384                     function (x, i, j, value) {
385    ### FIXME: *TEMPORARY* diagnostic output:
386                         cat("<Matrix1>[i,j] <- <Matrix1>:\n<Matrix1> = x :")
387                         str(x)
388                         cat("<Matrix2> = value :")
389                         str(value)
390                         cat("i :"); if(!missing(i)) str(i) else cat("<missing>\n")
391                         cat("j :"); if(!missing(j)) str(j) else cat("<missing>\n")
392
393                         callGeneric(x=x, i=i, j=j, value = as.vector(value))
394                     })
395    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
396                                    value = "Matrix"),
397                     function (x, i, j, value)
398                     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
399
400    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
401                                    value = "matrix"),
402                     function (x, i, j, value)
403                     callGeneric(x=x, i=i, j=j, value = c(value)))
404
405  ## (ANY,ANY,ANY) is used when no `real method' is implemented :  ## (ANY,ANY,ANY) is used when no `real method' is implemented :
406  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
407                                  value = "ANY"),                                  value = "ANY"),
408            function (x, i, j, value) {            function (x, i, j, value) {
409                if(!is.atomic(value))                if(!is.atomic(value))
410                    stop("RHS 'value' must match matrix class ", class(x))                    stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
411                                   class(value),class(x)))
412                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
413            })            })

## 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.1290 changed lines Added in v.1714