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 1290, Thu Jun 8 09:30:21 2006 UTC revision 1660, Thu Nov 2 11:05:35 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:
27    setMethod("head", signature(x = "Matrix"), utils::head.matrix)
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 77  Line 77 
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)                sparse = NULL, forceCheck = FALSE)
81  {  {
82      sparseDefault <- function(m)      sparseDefault <- function(m)
83          prod(dim(m)) > 2*sum(as(m, "matrix") != 0)          prod(dim(m)) > 2*sum(is.na(m <- as(m, "matrix")) | m != 0)
84    
85      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
86      if(is.null(sparse) && (i.M || is(data, "matrix")))  
87        if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
88          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
89    
90        doDN <- TRUE
91      if (i.M) {      if (i.M) {
92          sM <- is(data,"sparseMatrix")          sM <- is(data,"sparseMatrix")
93          if((sparse && sM) || (!sparse && !sM))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
94              return(data)              return(data)
95          ## else : convert  dense <-> sparse -> at end          ## else : convert  dense <-> sparse -> at end
96      }      }
# Line 97  Line 99 
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            if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
103                ## 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))          data <- .Internal(matrix(data, nrow, ncol, byrow))
114          if(is.null(sparse))          if(is.null(sparse))
115              sparse <- sparseDefault(data)              sparse <- sparseDefault(data)
116          dimnames(data) <- dimnames          dimnames(data) <- dimnames
117      } else if (!is.null(dimnames))          }
118          dimnames(data) <- dimnames          doDN <- FALSE
119        }
120      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
121        if (doDN && !is.null(dimnames))
122            dimnames(data) <- dimnames
123    
124      ## check for symmetric / triangular / diagonal :      ## check for symmetric / triangular / diagonal :
125      isSym <- isSymmetric(data)      isSym <- isSymmetric(data)
# Line 114  Line 129 
129      if(isDiag)      if(isDiag)
130          isDiag <- isDiagonal(data)          isDiag <- isDiagonal(data)
131    
 ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R  
   
132      ## Find proper matrix class 'cl'      ## Find proper matrix class 'cl'
133      cl <-      cl <-
134          if(isDiag)          if(isDiag && !isTRUE(sparse1))
135              "diagonalMatrix" # -> will automatically check for type              "diagonalMatrix" # -> will automatically check for type
136          else {          else {
137              ## consider it's type              ## consider it's type
# Line 159  Line 172 
172            function(x, y) callGeneric(x, as.matrix(y)))            function(x, y) callGeneric(x, as.matrix(y)))
173    
174  setMethod("%*%", signature(x = "numeric", y = "Matrix"),  setMethod("%*%", signature(x = "numeric", y = "Matrix"),
175            function(x, y) callGeneric(rbind(x), y))            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
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    ## when no sub-class method is found, bail out
192    setMethod("solve", signature(a = "Matrix", b = "matrix"),
193              function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))
194    
195  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
196  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 180  Line 202 
202            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
203  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
204            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
205    setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
206              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
207    setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
208              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
209    
210    ## cheap fallbacks
211    setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
212              function(x, y = NULL) t(x) %*% y)
213    setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
214              function(x, y = NULL) x %*% t(y))
215    
216  ## There are special sparse methods; this is a "fall back":  ## There are special sparse methods; this is a "fall back":
217  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
# Line 192  Line 224 
224                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
225    
226    
227    ## FIXME: All of these should never be called
228    setMethod("chol", signature(x = "Matrix"),
229              function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))
230    setMethod("determinant", signature(x = "Matrix"),
231              function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))
232    
233    setMethod("diag", signature(x = "Matrix"),
234              function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
235  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
236            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
237    
# Line 204  Line 244 
244                0-e1                0-e1
245            })            })
246    
247  ## bail-outs:  ## old-style matrices are made into new ones
248  setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),  setMethod("Ops", signature(e1 = "Matrix", e2 = "matrix"),
249              function(e1, e2) callGeneric(e1, Matrix(e2)))
250    ##          callGeneric(e1, Matrix(e2, sparse=is(e1,"sparseMatrix"))))
251    setMethod("Ops", signature(e1 = "matrix", e2 = "Matrix"),
252              function(e1, e2) callGeneric(Matrix(e1), e2))
253    
254    ## bail-outs -- on highest possible level, hence "Ops", not "Compare"/"Arith" :
255    setMethod("Ops", signature(e1 = "Matrix", e2 = "Matrix"),
256            function(e1, e2) {            function(e1, e2) {
257                d <- dimCheck(e1,e2)                d <- dimCheck(e1,e2)
258                .bail.out.2(.Generic, class(e1), class(e2))                .bail.out.2(.Generic, class(e1), class(e2))
259            })            })
260  setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),  setMethod("Ops", signature(e1 = "Matrix", e2 = "ANY"),
261            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
262  setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),  setMethod("Ops", signature(e1 = "ANY", e2 = "Matrix"),
263            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
264    
265    
# Line 249  Line 296 
296            function(x,i,j, drop)            function(x,i,j, drop)
297            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
298    
299  ##  "logical *vector* indexing, such as  M [ M >= 10 ] :  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
300  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  ## The following is *both* for    M [ <logical>   ]
301                           drop = "ANY"),  ##                 and also for   M [ <logical> , ]
302            function (x, i, j, drop) {  .M.sub.i.logical <- function (x, i, j, drop)
303    {
304        nA <- nargs()
305        if(nA == 2) { ##  M [ M >= 7 ]
306                as(x, geClass(x))@x[as.vector(i)]                as(x, geClass(x))@x[as.vector(i)]
307                                          # -> error when lengths don't match          ## -> error when lengths don't match
308            })      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
309            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
310    
311        } else stop("nargs() = ", nA,
312                    " should never happen; please report.")
313    }
314    setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
315                             drop = "ANY"),
316              .M.sub.i.logical)
317  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
318                           drop = "ANY"),                           drop = "ANY"),
319            function (x, i, j, drop) as(x, geClass(x))@x[i])            .M.sub.i.logical)
320    
321    
322  ## "FIXME:"  ## "FIXME:"
323  ## 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?
324  ##  and                A[ LL ]  where LL is a logical *vector*  
 ## -> [.data.frame uses nargs() - can we do this in the *generic* ?  
325    
326    
327  ### "[<-" : -----------------  ### "[<-" : -----------------
# Line 274  Line 330 
330  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
331                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
332            function (x, value) {            function (x, value) {
333                  ## Fails for 'nMatrix' ... FIXME : make sure have method there
334                x@x <- value                x@x <- value
335                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
336                x                x
337            })            })
338    
339  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
340                                    value = "Matrix"),
341                     function (x, i, j, value)
342                     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
343    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
344                                    value = "matrix"),
345                     function (x, i, j, value)
346                     callGeneric(x=x, i=i, j=j, value = c(value)))
347    
348  ## (ANY,ANY,ANY) is used when no `real method' is implemented :  ## (ANY,ANY,ANY) is used when no `real method' is implemented :
349  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
350                                  value = "ANY"),                                  value = "ANY"),
351            function (x, i, j, value) {            function (x, i, j, value) {
352                if(!is.atomic(value))                if(!is.atomic(value))
353                    stop("RHS 'value' must match matrix class ", class(x))                    stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
354                                   class(value),class(x)))
355                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
356            })            })
357    

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

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