SCM

SCM Repository

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

Diff of /pkg/R/Matrix.R

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 949, Wed Sep 28 09:17:08 2005 UTC revision 1290, Thu Jun 8 09:30:21 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        })  ##       })
   
 setMethod("show", signature(object = "ddenseMatrix"),  
           function(object) prMatrix(object))  
   
 ##- ## 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"),  
           function(object) prMatrix(object))  
9    
10  ## should propagate to all subclasses:  ## should propagate to all subclasses:
11  setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))  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    
15    ## slow "fall back" method {subclasses should have faster ones}:
16    setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
17              function(x) as.vector(as(x, "matrix")))
18    
19    
20  ## Note that isSymmetric is *not* exported  ## Note that isSymmetric is *not* exported
21    ## but that "base" has an isSymmetric() S3-generic since R 2.3.0
22  setMethod("isSymmetric", signature(object = "symmetricMatrix"),  setMethod("isSymmetric", signature(object = "symmetricMatrix"),
23            function(object) TRUE)            function(object,tol) TRUE)
24  setMethod("isSymmetric", signature(object = "triangularMatrix"),  setMethod("isSymmetric", signature(object = "triangularMatrix"),
25            ## FIXME: 'TRUE' if *diagonal*, i.e. return(isDiagonal(object))            ## TRUE iff diagonal:
26            function(object) FALSE)            function(object,tol) isDiagonal(object))
27  setMethod("isDiagonal", signature(object = "sparseMatrix"),  
28            function(object) {  if(paste(R.version$major, R.version$minor, sep=".") < "2.3")
29                gT <- as(object, "TsparseMatrix")      ## need a "matrix" method as in R 2.3 and later
30                all(gT@i == gT@j)      setMethod("isSymmetric", signature(object = "matrix"),
31                  function(object, tol = 100*.Machine$double.eps, ...)
32              {
33                  ## pretest: is it square?
34                  d <- dim(object)
35                  if(d[1] != d[2]) return(FALSE)
36                  ## for `broken' all.equal in R <= 2.2.x:
37                  dn <- dimnames(object)
38                  if(!identical(dn[1], dn[2])) return(FALSE)
39                  test <-
40                      if(is.complex(object))
41                          all.equal.numeric(object, Conj(t(object)), tol = tol, ...)
42                      else              # numeric, character, ..
43                          all.equal(object, t(object), tol = tol, ...)
44                  isTRUE(test)
45            })            })
46    
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")
59  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
# Line 57  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)
81  {  {
82      if (is(data, "Matrix")) return(data)      sparseDefault <- function(m)
83      if (is.matrix(data)) { val <- data }          prod(dim(m)) > 2*sum(as(m, "matrix") != 0)
84      else { ## cut & paste from "base::matrix" :  
85        i.M <- is(data, "Matrix")
86        if(is.null(sparse) && (i.M || is(data, "matrix")))
87            sparse <- sparseDefault(data)
88    
89        if (i.M) {
90            sM <- is(data,"sparseMatrix")
91            if((sparse && sM) || (!sparse && !sM))
92                return(data)
93            ## else : convert  dense <-> sparse -> at end
94        }
95        else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
96          if (missing(nrow))          if (missing(nrow))
97              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
98          else if (missing(ncol))          else if (missing(ncol))
99              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
100          val <- .Internal(matrix(data, nrow, ncol, byrow))          data <- .Internal(matrix(data, nrow, ncol, byrow))
101          dimnames(val) <- dimnames          if(is.null(sparse))
102                sparse <- sparseDefault(data)
103            dimnames(data) <- dimnames
104        } else if (!is.null(dimnames))
105            dimnames(data) <- dimnames
106    
107        ## 'data' is now a "matrix" or "Matrix"
108    
109        ## check for symmetric / triangular / diagonal :
110        isSym <- isSymmetric(data)
111        if((isTri <- !isSym))
112            isTri <- isTriangular(data)
113        isDiag <- isSym # cannot be diagonal if it isn't symmetric
114        if(isDiag)
115            isDiag <- isDiagonal(data)
116    
117    ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R
118    
119        ## Find proper matrix class 'cl'
120        cl <-
121            if(isDiag)
122                "diagonalMatrix" # -> will automatically check for type
123            else {
124                ## consider it's type
125                ctype <-
126                    if(is(data,"Matrix")) class(data)
127                    else {
128                        if("complex" == (ctype <- typeof(data)))
129                            "z" else ctype
130                    }
131                ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
132                if(ctype == "z")
133                    stop("complex matrices not yet implemented in Matrix package")
134                if(ctype == "i") {
135                    warning("integer matrices not yet implemented in 'Matrix'; ",
136                            "using 'double' ones'")
137                    ctype <- "d"
138      }      }
139      as(val, "dgeMatrix")              paste(ctype,
140                      if(sparse) {
141                          if(isSym) "sCMatrix" else
142                          if(isTri) "tCMatrix" else "gCMatrix"
143                      } else { ## dense
144                          if(isSym) "syMatrix" else
145                          if(isTri) "trMatrix" else "geMatrix"
146                      }, sep="")
147            }
148    
149        ## Now coerce and return
150        as(data, cl)
151  }  }
152    
153  ## Methods for operations where one argument is numeric  ## Methods for operations where one argument is numeric
# Line 100  Line 178 
178    
179  setMethod("crossprod", signature(x = "Matrix", y = "ANY"),  setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
180            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
181    setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
182              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
183    
184    ## There are special sparse methods; this is a "fall back":
185    setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
186                                     FUN = "ANY", make.dimnames = "ANY"),
187              function(X, Y, FUN, make.dimnames, ...) {
188                  X <- as(X, "matrix") ; Matrix(callGeneric()) })
189    setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
190                                     FUN = "ANY", make.dimnames = "ANY"),
191              function(X, Y, FUN, make.dimnames, ...) {
192                  Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
193    
194    
195  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
196            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
197    
198  ## Group Methods (bail-out)  ## Group Methods
199    setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)
200    ## "fallback":
201    setMethod("-", signature(e1 = "Matrix", e2 = "missing"),
202              function(e1) {
203                  warning("inefficient method used for \"- e1\"")
204                  0-e1
205              })
206    
207    ## bail-outs:
208  setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),  setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),
209            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))            function(e1, e2) {
210                  d <- dimCheck(e1,e2)
211                  .bail.out.2(.Generic, class(e1), class(e2))
212              })
213  setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),  setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),
214            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
215  setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),  setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),
# Line 126  Line 229 
229  setMethod("[", signature(x = "Matrix",  setMethod("[", signature(x = "Matrix",
230                           i = "missing", j = "missing", drop = "ANY"),                           i = "missing", j = "missing", drop = "ANY"),
231            function (x, i, j, drop) x)            function (x, i, j, drop) x)
232    
233  ## missing 'drop' --> 'drop = TRUE'  ## missing 'drop' --> 'drop = TRUE'
234  ##                     -----------  ##                     -----------
235  ## select rows  ## select rows
# Line 145  Line 249 
249            function(x,i,j, drop)            function(x,i,j, drop)
250            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
251    
252    ##  "logical *vector* indexing, such as  M [ M >= 10 ] :
253    setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
254                             drop = "ANY"),
255              function (x, i, j, drop) {
256                  as(x, geClass(x))@x[as.vector(i)]
257                                            # -> error when lengths don't match
258              })
259    
260    setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
261                             drop = "ANY"),
262              function (x, i, j, drop) as(x, geClass(x))@x[i])
263    
264    
265  ## "FIXME:"  ## "FIXME:"
266  ## 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?
267  ##  and                A[ LL ]  where LL is a logical *vector*  ##  and                A[ LL ]  where LL is a logical *vector*
# Line 155  Line 272 
272    
273  ## x[] <- value :  ## x[] <- value :
274  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
275                                  value = "index"),##  double/logical/...                                  value = "ANY"),## double/logical/...
276            function (x, value) { x@x <- value ; validObject(x); x })            function (x, value) {
277                  x@x <- value
278                  validObject(x)# check if type and lengths above match
279                  x
280              })
281    
282  ## Otherwise (value is not "index"): bail out  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);
283    ## (ANY,ANY,ANY) is used when no `real method' is implemented :
284  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
285                                  value = "ANY"),                                  value = "ANY"),
286            function (x, i, j, value)            function (x, i, j, value) {
287                   if(!is(value,"index"))                if(!is.atomic(value))
288                   stop("RHS 'value' must be of class \"index\"")                    stop("RHS 'value' must match matrix class ", class(x))
289                   else stop("not-yet-implemented 'Matrix[<-' method"))                else stop("not-yet-implemented 'Matrix[<-' method")
290              })
   
   
 ## NOTE: the following only works for R 2.2.x (and later) ---  
 ## ----  *and* 'Matrix' must have been *installed* by R >= 2.2.x  
291    
 if(paste(R.version$major, R.version$minor, sep=".") >= "2.2") {  
292    
293      ## The trivial methods :      ## The trivial methods :
294      setMethod("cbind2", signature(x = "Matrix", y = "NULL"),      setMethod("cbind2", signature(x = "Matrix", y = "NULL"),
# Line 196  Line 313 
313                                  class(x), class(y)))                                  class(x), class(y)))
314                })                })
315    
316    ## Use a working fall back {particularly useful for sparse}:
317    ## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones
318      setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),      setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),
319                function(x, y) {                function(x, y) {
320                    colCheck(x,y)                    colCheck(x,y)
321                    stop(gettextf("rbind2() method for (%s,%s) not-yet defined",                t(cbind2(t(x), t(y)))
                                 class(x), class(y)))  
322                })                })
 }## R-2.2.x and newer  

Legend:
Removed from v.949  
changed lines
  Added in v.1290

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge