# SCM Repository

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

# Diff of /pkg/R/Matrix.R

revision 871, Fri Aug 26 17:26:49 2005 UTC revision 1389, Fri Aug 18 13:53:33 2006 UTC
# Line 1  Line 1
1  #### Toplevel ``virtual'' class "Matrix"  #### Toplevel ``virtual'' class "Matrix"
2
## probably not needed eventually:
setAs(from = "ddenseMatrix", to = "matrix",
function(from) {
if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")
array(from@x, dim = d, dimnames = dimnames(from))
})
3
4  ## private function to be used as show() method possibly more than once  ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)
5  prMatrix <- function(object) {
6      d <- dim(object)  setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))
7      cl <- class(object)  setAs("Matrix", "denseMatrix",  function(from) as_dense(from))
8      cat(sprintf('%d x %d Matrix of class "%s"\n', d[1], d[2], cl))
9      m <- as(object, "matrix")  ## ## probably not needed eventually:
10      maxp <- getOption("max.print")  ## setAs(from = "ddenseMatrix", to = "matrix",
11      if(prod(d) <= maxp) print(m)  ##       function(from) {
12      else { ## d[1] > maxp / d[2] >= nr :  ##        if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")
13          nr <- maxp %/% d[2]  ##        array(from@x, dim = d, dimnames = dimnames(from))
14          n2 <- ceiling(nr / 2)  ##       })
cat("\n ..........\n\n")
print(tail(m, max(1, nr - n2)))
}
## DEBUG: cat("str(.):\n") ; str(object)
invisible(object)# as print() S3 methods do
}

setMethod("show", signature(object = "ddenseMatrix"), prMatrix)

##- ## FIXME: The following is only for the "dMatrix" objects that are not
##- ##        "dense" nor "sparse" -- i.e. "packed" ones :
##- ## But these could be printed better -- "." for structural zeros.
##- setMethod("show", signature(object = "dMatrix"), prMatrix)
##- ## and improve this as well:
##- setMethod("show", signature(object = "pMatrix"), prMatrix)
##- ## this should now be superfluous [keep for safety for the moment]:
setMethod("show", signature(object = "Matrix"), prMatrix)
15
16  ## should propagate to all subclasses:  ## should propagate to all subclasses:
17  setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))  setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))
18    ## for 'Matrix' objects, as.array() should be equivalent:
19    setMethod("as.array",  signature(x = "Matrix"), function(x) as(x, "matrix"))
20
21    ## head and tail apply to all Matrix objects for which subscripting is allowed:
22    if(paste(R.version\$major, R.version\$minor, sep=".") < "2.4") {
24        setMethod("tail", signature(x = "Matrix"), utils:::tail.matrix)
25    } else { # R 2.4.0 and newer
27        setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
28    }
29    ## slow "fall back" method {subclasses should have faster ones}:
30    setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
31              function(x) as.vector(as(x, "matrix")))
32
33    ## mainly need these for "dMatrix" or "lMatrix" respectively, but why not general:
34    setMethod("as.numeric", signature(x = "Matrix"),
35              function(x, ...) as.numeric(as.vector(x)))
36    setMethod("as.logical", signature(x = "Matrix"),
37              function(x, ...) as.logical(as.vector(x)))
38
39
40    ## Note that isSymmetric is *not* exported
41    ## but that "base" has an isSymmetric() S3-generic since R 2.3.0
42    setMethod("isSymmetric", signature(object = "symmetricMatrix"),
43              function(object,tol) TRUE)
44    setMethod("isSymmetric", signature(object = "triangularMatrix"),
45              ## TRUE iff diagonal:
46              function(object,tol) isDiagonal(object))
47
48    if(paste(R.version\$major, R.version\$minor, sep=".") < "2.3")
49        ## need a "matrix" method as in R 2.3 and later
50        setMethod("isSymmetric", signature(object = "matrix"),
51                  function(object, tol = 100*.Machine\$double.eps, ...)
52              {
53                  ## pretest: is it square?
54                  d <- dim(object)
55                  if(d[1] != d[2]) return(FALSE)
56                  ## for `broken' all.equal in R <= 2.2.x:
57                  dn <- dimnames(object)
58                  if(!identical(dn[1], dn[2])) return(FALSE)
59                  test <-
60                      if(is.complex(object))
61                          all.equal.numeric(object, Conj(t(object)), tol = tol, ...)
62                      else              # numeric, character, ..
63                          all.equal(object, t(object), tol = tol, ...)
64                  isTRUE(test)
65              })
66
67
68    setMethod("isTriangular", signature(object = "triangularMatrix"),
69              function(object, ...) TRUE)
70
71    setMethod("isTriangular", signature(object = "matrix"), isTriMat)
72
73    setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
74
75
76
77  setMethod("dim", signature(x = "Matrix"),  setMethod("dim", signature(x = "Matrix"),
78            function(x) x@Dim, valueClass = "integer")            function(x) x@Dim, valueClass = "integer")
# Line 62  Line 96
96            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
97
98  Matrix <-  Matrix <-
99      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
100                  sparse = NULL)
101  {  {
102      if (is(data, "Matrix")) return(data)      sparseDefault <- function(m)
103      if (is.matrix(data)) { val <- data }          prod(dim(m)) > 2*sum(as(m, "matrix") != 0)
104      else { ## cut & paste from "base::matrix" :
105        i.M <- is(data, "Matrix")
106        if(is.null(sparse) && (i.M || is(data, "matrix")))
107            sparse <- sparseDefault(data)
108
109        if (i.M) {
110            sM <- is(data,"sparseMatrix")
111            if((sparse && sM) || (!sparse && !sM))
112                return(data)
113            ## else : convert  dense <-> sparse -> at end
114        }
115        else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
116          if (missing(nrow))          if (missing(nrow))
117              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
118          else if (missing(ncol))          else if (missing(ncol))
119              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
120          val <- .Internal(matrix(data, nrow, ncol, byrow))          if(length(data) == 1 && data == 0 && !identical(sparse,FALSE)) {
121          dimnames(val) <- dimnames              if(is.null(sparse)) sparse <- TRUE
122                ## will be sparse: do NOT construct full matrix!
123                data <- new(if(is.numeric(data)) "dgTMatrix" else
124                            if(is.logical(data)) "lgTMatrix" else
125                            stop("invalid 'data'"),
126                            Dim = as.integer(c(nrow,ncol)),
127                            Dimnames = if(is.null(dimnames)) list(NULL,NULL)
128                            else dimnames)
129            } else { ## normal case
130                data <- .Internal(matrix(data, nrow, ncol, byrow))
131                if(is.null(sparse))
132                    sparse <- sparseDefault(data)
133                dimnames(data) <- dimnames
134      }      }
135      as(val, "dgeMatrix")      } else if (!is.null(dimnames))
136            dimnames(data) <- dimnames
137
138        ## 'data' is now a "matrix" or "Matrix"
139
140        ## check for symmetric / triangular / diagonal :
141        isSym <- isSymmetric(data)
142        if((isTri <- !isSym))
143            isTri <- isTriangular(data)
144        isDiag <- isSym # cannot be diagonal if it isn't symmetric
145        if(isDiag)
146            isDiag <- isDiagonal(data)
147
148    ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R
149
150        ## Find proper matrix class 'cl'
151        cl <-
152            if(isDiag)
153                "diagonalMatrix" # -> will automatically check for type
154            else {
155                ## consider it's type
156                ctype <-
157                    if(is(data,"Matrix")) class(data)
158                    else {
159                        if("complex" == (ctype <- typeof(data)))
160                            "z" else ctype
161                    }
162                ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
163                if(ctype == "z")
164                    stop("complex matrices not yet implemented in Matrix package")
165                if(ctype == "i") {
166                    warning("integer matrices not yet implemented in 'Matrix'; ",
167                            "using 'double' ones'")
168                    ctype <- "d"
169                }
170                paste(ctype,
171                      if(sparse) {
172                          if(isSym) "sCMatrix" else
173                          if(isTri) "tCMatrix" else "gCMatrix"
174                      } else { ## dense
175                          if(isSym) "syMatrix" else
176                          if(isTri) "trMatrix" else "geMatrix"
177                      }, sep="")
178            }
179
180        ## Now coerce and return
181        as(data, cl)
182  }  }
183
184  ## Methods for operations where one argument is numeric  ## Methods for operations where one argument is numeric
# Line 90  Line 194
194
195  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
196            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))

197  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
198            function(x, y = NULL)  callGeneric(rbind(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
199
200    ## The as.matrix() promotion seems illogical to MM,
201    ## but is according to help(tcrossprod, package = "base") :
202    setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
203              function(x, y = NULL) callGeneric(x, as.matrix(y)))
204    setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
205              function(x, y = NULL)  callGeneric(as.matrix(x), y))
206
207  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
208            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, as.matrix(b)))
209
210    ## bail-out methods in order to get better error messages
211    setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
212              function (x, y)
213              stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
214                            class(x), class(y))))
215
216    setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
217              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
218    setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
219              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
220    setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
221              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
222    setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
223              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
224
225    ## cheap fallbacks
226    setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
227              function(x, y = NULL) t(x) %*% y)
228    setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
229              function(x, y = NULL) x %*% t(y))
230
231    ## There are special sparse methods; this is a "fall back":
232    setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
233                                     FUN = "ANY", make.dimnames = "ANY"),
234              function(X, Y, FUN, make.dimnames, ...) {
235                  X <- as(X, "matrix") ; Matrix(callGeneric()) })
236    setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
237                                     FUN = "ANY", make.dimnames = "ANY"),
238              function(X, Y, FUN, make.dimnames, ...) {
239                  Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
240
241
242    setMethod("diag", signature(x = "Matrix"),
243              function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
244    setMethod("t", signature(x = "Matrix"),
245              function(x) .bail.out.1(.Generic, class(x)))
246
247    ## Group Methods
248    setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)
249    ## "fallback":
250    setMethod("-", signature(e1 = "Matrix", e2 = "missing"),
251              function(e1) {
252                  warning("inefficient method used for \"- e1\"")
253                  0-e1
254              })
255
256    ## bail-outs:
257    setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),
258              function(e1, e2) {
259                  d <- dimCheck(e1,e2)
260                  .bail.out.2(.Generic, class(e1), class(e2))
261              })
262    setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),
263              function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
264    setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),
265              function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
266
267
268
269  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
270  ###  ###
271  ### Subsetting "["  and  ### Subsetting "["  and
272  ### SubAssign  "[<-" : The "missing" cases can be dealt with here, "at the top":  ### SubAssign  "[<-" : The "missing" cases can be dealt with here, "at the top":
273
274    ## Using "index" for indices should allow
275    ## integer (numeric), logical, or character (names!) indices :
276
277  ## "x[]":  ## "x[]":
278  setMethod("[", signature(x = "Matrix",  setMethod("[", signature(x = "Matrix",
279                           i = "missing", j = "missing", drop = "ANY"),                           i = "missing", j = "missing", drop = "ANY"),
280            function (x, i, j, drop) x)            function (x, i, j, drop) x)
281
282  ## missing 'drop' --> 'drop = TRUE'  ## missing 'drop' --> 'drop = TRUE'
283  ##                     -----------  ##                     -----------
284  ## select rows  ## select rows
285  setMethod("[", signature(x = "Matrix", i = "numeric", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
286                           drop = "missing"),                           drop = "missing"),
287            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))
288  ## select columns  ## select columns
289  setMethod("[", signature(x = "Matrix", i = "missing", j = "numeric",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
290                           drop = "missing"),                           drop = "missing"),
291            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))
292  setMethod("[", signature(x = "Matrix", i = "numeric", j = "numeric",  setMethod("[", signature(x = "Matrix", i = "index", j = "index",
293                           drop = "missing"),                           drop = "missing"),
294            function(x,i,j, drop) callGeneric(x, i=i, j=j, drop= TRUE))            function(x,i,j, drop) callGeneric(x, i=i, j=j, drop= TRUE))
295
296    ## bail out if any of (i,j,drop) is "non-sense"
297    setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
298              function(x,i,j, drop)
299              stop("invalid or not-yet-implemented 'Matrix' subsetting"))
300
301    ##  "logical *vector* indexing, such as  M [ M >= 10 ] :
302    setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
303                             drop = "ANY"),
304              function (x, i, j, drop) {
305                  as(x, geClass(x))@x[as.vector(i)]
306                  ## -> error when lengths don't match
307              })
308
309    ## FIXME: The following is good for    M [ <logical>   ]
310    ##        *BUT* it also triggers for   M [ <logical> , ] where it is *WRONG*
311    ##       using nargs() does not help: it gives '3' for both cases
312    if(FALSE)
313    setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
314                             drop = "ANY"),
315              function (x, i, j, drop) {
316                  ## DEBUG
317                  cat("[(Matrix,i,..): nargs=", nargs(),"\n")
318                  as(x, geClass(x))@x[i] })
319
320
321  ## "FIXME:"  ## "FIXME:"
322  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?
323  ##  and                A[ LL ]  where LL is a logical *vector*  ##  and                A[ LL ]  where LL is a logical *vector*
324    ## -> [.data.frame uses nargs() - can we do this in the *generic* ?
325
326
327  ### "[<-" : -----------------  ### "[<-" : -----------------
328
329  ## x[] <- value :  ## x[] <- value :
330  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
331                                  value = "vector"),##  double/logical/...                                  value = "ANY"),## double/logical/...
332            function (x, value) { x@x <- value ; validObject(x); x })            function (x, value) {
333                  x@x <- value
334                  validObject(x)# check if type and lengths above match
335                  x
336              })
337
338  ## Otherwise (value is not "vector"): bail out  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);
339    ## (ANY,ANY,ANY) is used when no `real method' is implemented :
340  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
341                                  value = "ANY"),                                  value = "ANY"),
342            function (x, i, j, value) stop("RHS 'value' must be of class \"vector\""))            function (x, i, j, value) {
343                  if(!is.atomic(value))
344                      stop("RHS 'value' must match matrix class ", class(x))
345                  else stop("not-yet-implemented 'Matrix[<-' method")
346              })
347
348
349    ## The trivial methods :
350    setMethod("cbind2", signature(x = "Matrix", y = "NULL"),
351              function(x, y) x)
352    setMethod("cbind2", signature(x = "Matrix", y = "missing"),
353              function(x, y) x)
354    setMethod("cbind2", signature(x = "NULL", y="Matrix"),
355              function(x, y) x)
356
357    setMethod("rbind2", signature(x = "Matrix", y = "NULL"),
358              function(x, y) x)
359    setMethod("rbind2", signature(x = "Matrix", y = "missing"),
360              function(x, y) x)
361    setMethod("rbind2", signature(x = "NULL", y="Matrix"),
362              function(x, y) x)
363
364    ## Makes sure one gets x decent error message for the unimplemented cases:
365    setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),
366              function(x, y) {
367                  rowCheck(x,y)
368                  stop(gettextf("cbind2() method for (%s,%s) not-yet defined",
369                                class(x), class(y)))
370              })
371
372  if(FALSE) ## The following can't work as long as cbind is function(..., *)  ## Use a working fall back {particularly useful for sparse}:
373  setMethod("cbind", signature(a = "Matrix", b = "Matrix"),  ## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones
374            function(a, b, ...) {  setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),
375                da <- Dim(a)            function(x, y) {
376                db <- Dim(b)                colCheck(x,y)
377                if(da[1] != db[1])                t(cbind2(t(x), t(y)))
stop("Matrices must have same number of rows for cbind()ing")
378            })            })

Legend:
 Removed from v.871 changed lines Added in v.1389