# 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 1329, Fri Jul 21 06:47:06 2006 UTC
# Line 1  Line 1
1  #### Toplevel ``virtual'' class "Matrix"  #### Toplevel ``virtual'' class "Matrix"
2
3  ## probably not needed eventually:  ## ## probably not needed eventually:
4  setAs(from = "ddenseMatrix", to = "matrix",  ## setAs(from = "ddenseMatrix", to = "matrix",
5        function(from) {  ##       function(from) {
6            if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")  ##        if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")
7            array(from@x, dim = d, dimnames = dimnames(from))  ##        array(from@x, dim = d, dimnames = dimnames(from))
8    ##       })
9
10    ## should propagate to all subclasses:
11    setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))
12    ## for 'Matrix' objects, as.array() should be equivalent:
13    setMethod("as.array",  signature(x = "Matrix"), function(x) as(x, "matrix"))
14    ## head and tail apply to all Matrix objects for which subscripting is allowed
16              function(x, n = 6, ...)
17              x[seq(len = min(n, nrow(x))), , drop = FALSE])
18    setMethod("tail", signature(x = "Matrix"),
19              function (x, n = 6, addrownums = TRUE, ...)
20          {
21              nrx <- nrow(x)
22              sel <- seq(to = nrx, length = min(n, nrx))
23              ans <- x[sel, , drop = FALSE]
25                  rownames(ans) <- paste("[", sel, ",]", sep = "")
26              ans
27        })        })
28
29  ## private function to be used as show() method possibly more than once  ## slow "fall back" method {subclasses should have faster ones}:
30  prMatrix <- function(object) {  setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
31              function(x) as.vector(as(x, "matrix")))
32
33
34    ## Note that isSymmetric is *not* exported
35    ## but that "base" has an isSymmetric() S3-generic since R 2.3.0
36    setMethod("isSymmetric", signature(object = "symmetricMatrix"),
37              function(object,tol) TRUE)
38    setMethod("isSymmetric", signature(object = "triangularMatrix"),
39              ## TRUE iff diagonal:
40              function(object,tol) isDiagonal(object))
41
42    if(paste(R.version\$major, R.version\$minor, sep=".") < "2.3")
43        ## need a "matrix" method as in R 2.3 and later
44        setMethod("isSymmetric", signature(object = "matrix"),
45                  function(object, tol = 100*.Machine\$double.eps, ...)
46              {
47                  ## pretest: is it square?
48      d <- dim(object)      d <- dim(object)
49      cl <- class(object)                if(d[1] != d[2]) return(FALSE)
50      cat(sprintf('%d x %d Matrix of class "%s"\n', d[1], d[2], cl))                ## for `broken' all.equal in R <= 2.2.x:
51      m <- as(object, "matrix")                dn <- dimnames(object)
52      maxp <- getOption("max.print")                if(!identical(dn[1], dn[2])) return(FALSE)
53      if(prod(d) <= maxp) print(m)                test <-
54      else { ## d[1] > maxp / d[2] >= nr :                    if(is.complex(object))
55          nr <- maxp %/% d[2]                        all.equal.numeric(object, Conj(t(object)), tol = tol, ...)
56          n2 <- ceiling(nr / 2)                    else              # numeric, character, ..
57          print(head(m, max(1, n2)))                        all.equal(object, t(object), tol = tol, ...)
58          cat("\n ..........\n\n")                isTRUE(test)
59          print(tail(m, max(1, nr - n2)))            })
60      }
61      ## DEBUG: cat("str(.):\n") ; str(object)
62      invisible(object)# as print() S3 methods do  setMethod("isTriangular", signature(object = "triangularMatrix"),
63  }            function(object, ...) TRUE)
64
65  setMethod("show", signature(object = "ddenseMatrix"), prMatrix)  setMethod("isTriangular", signature(object = "matrix"), isTriMat)
66
67  ##- ## FIXME: The following is only for the "dMatrix" objects that are not  setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
68  ##- ##        "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)
69
## should propagate to all subclasses:
setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))
70
71  setMethod("dim", signature(x = "Matrix"),  setMethod("dim", signature(x = "Matrix"),
72            function(x) x@Dim, valueClass = "integer")            function(x) x@Dim, valueClass = "integer")
# Line 62  Line 90
90            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
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)
95  {  {
96      if (is(data, "Matrix")) return(data)      sparseDefault <- function(m)
97      if (is.matrix(data)) { val <- data }          prod(dim(m)) > 2*sum(as(m, "matrix") != 0)
98      else { ## cut & paste from "base::matrix" :
99        i.M <- is(data, "Matrix")
100        if(is.null(sparse) && (i.M || is(data, "matrix")))
101            sparse <- sparseDefault(data)
102
103        if (i.M) {
104            sM <- is(data,"sparseMatrix")
105            if((sparse && sM) || (!sparse && !sM))
106                return(data)
107            ## else : convert  dense <-> sparse -> at end
108        }
109        else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
110          if (missing(nrow))          if (missing(nrow))
111              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
112          else if (missing(ncol))          else if (missing(ncol))
113              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
114          val <- .Internal(matrix(data, nrow, ncol, byrow))          if(length(data) == 1 && data == 0 && !identical(sparse,FALSE)) {
115          dimnames(val) <- dimnames              if(is.null(sparse)) sparse <- TRUE
116                ## will be sparse: do NOT construct full matrix!
117                data <- new(if(is.numeric(data)) "dgTMatrix" else
118                            if(is.logical(data)) "lgTMatrix" else
119                            stop("invalid 'data'"),
120                            Dim = as.integer(c(nrow,ncol)),
121                            Dimnames = if(is.null(dimnames))
122                            list(NULL,NULL) else dimnames)
123            } else { ## normal case
124                data <- .Internal(matrix(data, nrow, ncol, byrow))
125                if(is.null(sparse))
126                    sparse <- sparseDefault(data)
127                dimnames(data) <- dimnames
128            }
129        } else if (!is.null(dimnames))
130            dimnames(data) <- dimnames
131
132        ## 'data' is now a "matrix" or "Matrix"
133
134        ## check for symmetric / triangular / diagonal :
135        isSym <- isSymmetric(data)
136        if((isTri <- !isSym))
137            isTri <- isTriangular(data)
138        isDiag <- isSym # cannot be diagonal if it isn't symmetric
139        if(isDiag)
140            isDiag <- isDiagonal(data)
141
142    ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R
143
144        ## Find proper matrix class 'cl'
145        cl <-
146            if(isDiag)
147                "diagonalMatrix" # -> will automatically check for type
148            else {
149                ## consider it's type
150                ctype <-
151                    if(is(data,"Matrix")) class(data)
152                    else {
153                        if("complex" == (ctype <- typeof(data)))
154                            "z" else ctype
155                    }
156                ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
157                if(ctype == "z")
158                    stop("complex matrices not yet implemented in Matrix package")
159                if(ctype == "i") {
160                    warning("integer matrices not yet implemented in 'Matrix'; ",
161                            "using 'double' ones'")
162                    ctype <- "d"
163      }      }
164      as(val, "dgeMatrix")              paste(ctype,
165                      if(sparse) {
166                          if(isSym) "sCMatrix" else
167                          if(isTri) "tCMatrix" else "gCMatrix"
168                      } else { ## dense
169                          if(isSym) "syMatrix" else
170                          if(isTri) "trMatrix" else "geMatrix"
171                      }, sep="")
172            }
173
174        ## Now coerce and return
175        as(data, cl)
176  }  }
177
178  ## Methods for operations where one argument is numeric  ## Methods for operations where one argument is numeric
# Line 97  Line 195
195  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
196            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, as.matrix(b)))
197
198    ## bail-out methods in order to get better error messages
199    setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
200              function (x, y)
201              stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
202                            class(x), class(y))))
203
204    setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
205              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
206    setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
207              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
208
209    ## There are special sparse methods; this is a "fall back":
210    setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
211                                     FUN = "ANY", make.dimnames = "ANY"),
212              function(X, Y, FUN, make.dimnames, ...) {
213                  X <- as(X, "matrix") ; Matrix(callGeneric()) })
214    setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
215                                     FUN = "ANY", make.dimnames = "ANY"),
216              function(X, Y, FUN, make.dimnames, ...) {
217                  Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
218
219
220    setMethod("diag", signature(x = "Matrix"),
221              function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
222    setMethod("t", signature(x = "Matrix"),
223              function(x) .bail.out.1(.Generic, class(x)))
224
225    ## Group Methods
226    setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)
227    ## "fallback":
228    setMethod("-", signature(e1 = "Matrix", e2 = "missing"),
229              function(e1) {
230                  warning("inefficient method used for \"- e1\"")
231                  0-e1
232              })
233
234    ## bail-outs:
235    setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),
236              function(e1, e2) {
237                  d <- dimCheck(e1,e2)
238                  .bail.out.2(.Generic, class(e1), class(e2))
239              })
240    setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),
241              function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
242    setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),
243              function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
244
245
246
247  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
248  ###  ###
249  ### Subsetting "["  and  ### Subsetting "["  and
250  ### SubAssign  "[<-" : The "missing" cases can be dealt with here, "at the top":  ### SubAssign  "[<-" : The "missing" cases can be dealt with here, "at the top":
251
252    ## Using "index" for indices should allow
253    ## integer (numeric), logical, or character (names!) indices :
254
255  ## "x[]":  ## "x[]":
256  setMethod("[", signature(x = "Matrix",  setMethod("[", signature(x = "Matrix",
257                           i = "missing", j = "missing", drop = "ANY"),                           i = "missing", j = "missing", drop = "ANY"),
258            function (x, i, j, drop) x)            function (x, i, j, drop) x)
259
260  ## missing 'drop' --> 'drop = TRUE'  ## missing 'drop' --> 'drop = TRUE'
261  ##                     -----------  ##                     -----------
262  ## select rows  ## select rows
263  setMethod("[", signature(x = "Matrix", i = "numeric", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
264                           drop = "missing"),                           drop = "missing"),
265            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))
266  ## select columns  ## select columns
267  setMethod("[", signature(x = "Matrix", i = "missing", j = "numeric",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
268                           drop = "missing"),                           drop = "missing"),
269            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))
270  setMethod("[", signature(x = "Matrix", i = "numeric", j = "numeric",  setMethod("[", signature(x = "Matrix", i = "index", j = "index",
271                           drop = "missing"),                           drop = "missing"),
272            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))
273
274    ## bail out if any of (i,j,drop) is "non-sense"
275    setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
276              function(x,i,j, drop)
277              stop("invalid or not-yet-implemented 'Matrix' subsetting"))
278
279    ##  "logical *vector* indexing, such as  M [ M >= 10 ] :
280    setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
281                             drop = "ANY"),
282              function (x, i, j, drop) {
283                  as(x, geClass(x))@x[as.vector(i)]
284                  ## -> error when lengths don't match
285              })
286
287    ## FIXME: The following is good for    M [ <logical>   ]
288    ##        *BUT* it also triggers for   M [ <logical> , ] where it is *WRONG*
289    ##       using nargs() does not help: it gives '3' for both cases
290    if(FALSE)
291    setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
292                             drop = "ANY"),
293              function (x, i, j, drop) {
294                  ## DEBUG
295                  cat("[(Matrix,i,..): nargs=", nargs(),"\n")
296                  as(x, geClass(x))@x[i] })
297
298
299  ## "FIXME:"  ## "FIXME:"
300  ## 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?
301  ##  and                A[ LL ]  where LL is a logical *vector*  ##  and                A[ LL ]  where LL is a logical *vector*
302    ## -> [.data.frame uses nargs() - can we do this in the *generic* ?
303
304
305  ### "[<-" : -----------------  ### "[<-" : -----------------
306
307  ## x[] <- value :  ## x[] <- value :
308  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
309                                  value = "vector"),##  double/logical/...                                  value = "ANY"),## double/logical/...
310            function (x, value) { x@x <- value ; validObject(x); x })            function (x, value) {
311                  x@x <- value
312                  validObject(x)# check if type and lengths above match
313                  x
314              })
315
316  ## Otherwise (value is not "vector"): bail out  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);
317    ## (ANY,ANY,ANY) is used when no `real method' is implemented :
318  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
319                                  value = "ANY"),                                  value = "ANY"),
320            function (x, i, j, value) stop("RHS 'value' must be of class \"vector\""))            function (x, i, j, value) {
321                  if(!is.atomic(value))
322                      stop("RHS 'value' must match matrix class ", class(x))
323                  else stop("not-yet-implemented 'Matrix[<-' method")
324              })
325
326
327    ## The trivial methods :
328    setMethod("cbind2", signature(x = "Matrix", y = "NULL"),
329              function(x, y) x)
330    setMethod("cbind2", signature(x = "Matrix", y = "missing"),
331              function(x, y) x)
332    setMethod("cbind2", signature(x = "NULL", y="Matrix"),
333              function(x, y) x)
334
335    setMethod("rbind2", signature(x = "Matrix", y = "NULL"),
336              function(x, y) x)
337    setMethod("rbind2", signature(x = "Matrix", y = "missing"),
338              function(x, y) x)
339    setMethod("rbind2", signature(x = "NULL", y="Matrix"),
340              function(x, y) x)
341
342    ## Makes sure one gets x decent error message for the unimplemented cases:
343    setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),
344              function(x, y) {
345                  rowCheck(x,y)
346                  stop(gettextf("cbind2() method for (%s,%s) not-yet defined",
347                                class(x), class(y)))
348              })
349
350  if(FALSE) ## The following can't work as long as cbind is function(..., *)  ## Use a working fall back {particularly useful for sparse}:
351  setMethod("cbind", signature(a = "Matrix", b = "Matrix"),  ## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones
352            function(a, b, ...) {  setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),
353                da <- Dim(a)            function(x, y) {
354                db <- Dim(b)                colCheck(x,y)
355                if(da[1] != db[1])                t(cbind2(t(x), t(y)))
stop("Matrices must have same number of rows for cbind()ing")
356            })            })

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