# 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 1655, Mon Oct 30 17:16:27 2006 UTC
# Line 1  Line 1
1  #### Toplevel ``virtual'' class "Matrix"  #### Toplevel ``virtual'' class "Matrix"
2
3  ## probably not needed eventually:
4  setAs(from = "ddenseMatrix", to = "matrix",  ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)
5        function(from) {
6            if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")  setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))
7            array(from@x, dim = d, dimnames = dimnames(from))  setAs("Matrix", "denseMatrix",  function(from) as_dense(from))
8        })
9    ## Most of these work; this is a last resort:
10  ## private function to be used as show() method possibly more than once  setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:
11  prMatrix <- function(object) {        function(from) .bail.out.2("coerce", class(from), class(to)))
12      d <- dim(object)  setAs(from = "matrix", to = "Matrix", function(from) Matrix(from))
13      cl <- class(object)
14      cat(sprintf('%d x %d Matrix of class "%s"\n', d[1], d[2], cl))  ## ## probably not needed eventually:
15      m <- as(object, "matrix")  ## setAs(from = "ddenseMatrix", to = "matrix",
16      maxp <- getOption("max.print")  ##       function(from) {
17      if(prod(d) <= maxp) print(m)  ##        if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")
18      else { ## d[1] > maxp / d[2] >= nr :  ##        array(from@x, dim = d, dimnames = dimnames(from))
19          nr <- maxp %/% d[2]  ##       })
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)
20
21  ## should propagate to all subclasses:  ## should propagate to all subclasses:
22  setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))  setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))
23    ## for 'Matrix' objects, as.array() should be equivalent:
24    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}:
31    setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
32              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
41    ## "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    setMethod("isTriangular", signature(object = "triangularMatrix"),
49              function(object, ...) TRUE)
50
51    setMethod("isTriangular", signature(object = "matrix"), isTriMat)
52
53    setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
54
55
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")
# Line 62  Line 76
76            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
77
78  Matrix <-  Matrix <-
79      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
80                  sparse = NULL, forceCheck = FALSE)
81  {  {
82      if (is(data, "Matrix")) return(data)      sparseDefault <- function(m)
83      if (is.matrix(data)) { val <- data }          prod(dim(m)) > 2*sum(is.na(m <- as(m, "matrix")) | m != 0)
84      else { ## cut & paste from "base::matrix" :
85        i.M <- is(data, "Matrix")
86
87        if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
88            sparse <- sparseDefault(data)
89
90        doDN <- TRUE
91        if (i.M) {
92            sM <- is(data,"sparseMatrix")
93            if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
94                return(data)
95            ## else : convert  dense <-> sparse -> at end
96        }
97        else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
98          if (missing(nrow))          if (missing(nrow))
99              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
100          else if (missing(ncol))          else if (missing(ncol))
101              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
102          val <- .Internal(matrix(data, nrow, ncol, byrow))          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
103          dimnames(val) <- dimnames              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
104                if(is.null(sparse)) sparse1 <- sparse <- TRUE
105                ## will be sparse: do NOT construct full matrix!
106                data <- new(if(is.numeric(data)) "dgTMatrix" else
107                            if(is.logical(data)) "lgTMatrix" else
108                            stop("invalid 'data'"),
109                            Dim = as.integer(c(nrow,ncol)),
110                            Dimnames = if(is.null(dimnames)) list(NULL,NULL)
111                            else dimnames)
112            } else { ## normal case
113                data <- .Internal(matrix(data, nrow, ncol, byrow))
114                if(is.null(sparse))
115                    sparse <- sparseDefault(data)
116                dimnames(data) <- dimnames
117            }
118            doDN <- FALSE
119      }      }
120      as(val, "dgeMatrix")      ## 'data' is now a "matrix" or "Matrix"
121        if (doDN && !is.null(dimnames))
122            dimnames(data) <- dimnames
123
124        ## check for symmetric / triangular / diagonal :
125        isSym <- isSymmetric(data)
126        if((isTri <- !isSym))
127            isTri <- isTriangular(data)
128        isDiag <- isSym # cannot be diagonal if it isn't symmetric
129        if(isDiag)
130            isDiag <- isDiagonal(data)
131
132        ## Find proper matrix class 'cl'
133        cl <-
134            if(isDiag && !isTRUE(sparse1))
135                "diagonalMatrix" # -> will automatically check for type
136            else {
137                ## consider it's type
138                ctype <-
139                    if(is(data,"Matrix")) class(data)
140                    else {
141                        if("complex" == (ctype <- typeof(data)))
142                            "z" else ctype
143                    }
144                ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
145                if(ctype == "z")
146                    stop("complex matrices not yet implemented in Matrix package")
147                if(ctype == "i") {
148                    warning("integer matrices not yet implemented in 'Matrix'; ",
149                            "using 'double' ones'")
150                    ctype <- "d"
151                }
152                paste(ctype,
153                      if(sparse) {
154                          if(isSym) "sCMatrix" else
155                          if(isTri) "tCMatrix" else "gCMatrix"
156                      } else { ## dense
157                          if(isSym) "syMatrix" else
158                          if(isTri) "trMatrix" else "geMatrix"
159                      }, sep="")
160            }
161
162        ## Now coerce and return
163        as(data, cl)
164  }  }
165
166  ## Methods for operations where one argument is numeric  ## Methods for operations where one argument is numeric
# Line 90  Line 176
176
177  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
178            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))

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

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