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 1738, Tue Jan 23 17:17:15 2007 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 56  Line 56 
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    
60    setMethod("length", "Matrix", function(x) prod(dim(x)))
61    
62  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
63    
64    
65  ## not exported but used more than once for "dimnames<-" method :  ## not exported but used more than once for "dimnames<-" method :
66  ## -- or do only once for all "Matrix" classes ??  ## -- or do only once for all "Matrix" classes ??
67  dimnamesGets <- function (x, value) {  dimnamesGets <- function (x, value) {
# Line 75  Line 80 
80  setMethod("unname", signature("Matrix", force="missing"),  setMethod("unname", signature("Matrix", force="missing"),
81            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
82    
83    setMethod("all", signature(x = "Matrix"),
84              function(x, ..., na.rm) { x <- as(x, "lMatrix"); callGeneric()})
85    setMethod("any", signature(x = "Matrix"),
86              function(x, ..., na.rm) { x <- as(x, "lMatrix"); callGeneric()})
87    
88    
89    
90  Matrix <-  Matrix <-
91      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
92                sparse = NULL)                sparse = NULL, forceCheck = FALSE)
93  {  {
94      sparseDefault <- function(m)      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
         prod(dim(m)) > 2*sum(as(m, "matrix") != 0)  
95    
96      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
97      if(is.null(sparse) && (i.M || is(data, "matrix")))  
98        if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
99          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
100    
101        doDN <- TRUE
102      if (i.M) {      if (i.M) {
103          sM <- is(data,"sparseMatrix")          sM <- is(data,"sparseMatrix")
104          if((sparse && sM) || (!sparse && !sM))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
105              return(data)              return(data)
106          ## else : convert  dense <-> sparse -> at end          ## else : convert  dense <-> sparse -> at end
107      }      }
# Line 97  Line 110 
110              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
111          else if (missing(ncol))          else if (missing(ncol))
112              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
113            if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
114                ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
115                if(is.null(sparse)) sparse1 <- 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)) list(NULL,NULL)
122                            else dimnames)
123            } else { ## normal case
124          data <- .Internal(matrix(data, nrow, ncol, byrow))          data <- .Internal(matrix(data, nrow, ncol, byrow))
125          if(is.null(sparse))          if(is.null(sparse))
126              sparse <- sparseDefault(data)              sparse <- sparseDefault(data)
127          dimnames(data) <- dimnames          dimnames(data) <- dimnames
128      } else if (!is.null(dimnames))          }
129          dimnames(data) <- dimnames          doDN <- FALSE
130        }
131      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
132        if (doDN && !is.null(dimnames))
133            dimnames(data) <- dimnames
134    
135      ## check for symmetric / triangular / diagonal :      ## check for symmetric / triangular / diagonal :
136      isSym <- isSymmetric(data)      isSym <- isSymmetric(data)
# Line 114  Line 140 
140      if(isDiag)      if(isDiag)
141          isDiag <- isDiagonal(data)          isDiag <- isDiagonal(data)
142    
 ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R  
   
143      ## Find proper matrix class 'cl'      ## Find proper matrix class 'cl'
144      cl <-      cl <-
145          if(isDiag)          if(isDiag && !isTRUE(sparse1))
146              "diagonalMatrix" # -> will automatically check for type              "diagonalMatrix" # -> will automatically check for type
147          else {          else {
148              ## consider it's type              ## consider it's type
# Line 159  Line 183 
183            function(x, y) callGeneric(x, as.matrix(y)))            function(x, y) callGeneric(x, as.matrix(y)))
184    
185  setMethod("%*%", signature(x = "numeric", y = "Matrix"),  setMethod("%*%", signature(x = "numeric", y = "Matrix"),
186            function(x, y) callGeneric(rbind(x), y))            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
187    
188  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
189            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
   
190  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
191            function(x, y = NULL)  callGeneric(rbind(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
192    
193    ## The as.matrix() promotion seems illogical to MM,
194    ## but is according to help(tcrossprod, package = "base") :
195    setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
196              function(x, y = NULL) callGeneric(x, as.matrix(y)))
197    setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
198              function(x, y = NULL)  callGeneric(as.matrix(x), y))
199    
200    ## maybe not optimal
201    setMethod("solve", signature(a = "Matrix", b = "missing"),
202              function(a, b, ...) solve(a, Diagonal(nrow(a))))
203    
204  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
205            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, as.matrix(b)))
206    ## when no sub-class method is found, bail out
207    setMethod("solve", signature(a = "Matrix", b = "matrix"),
208              function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))
209    
210  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
211  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 180  Line 217 
217            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
218  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
219            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            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":  ## There are special sparse methods; this is a "fall back":
232  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
# Line 192  Line 239 
239                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
240    
241    
242    ## FIXME: All of these should never be called
243    setMethod("chol", signature(x = "Matrix"),
244              function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))
245    setMethod("determinant", signature(x = "Matrix"),
246              function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))
247    
248    setMethod("diag", signature(x = "Matrix"),
249              function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
250  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
251            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
252    
253  ## Group Methods  ## Group Methods
 setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)  
 ## "fallback":  
 setMethod("-", signature(e1 = "Matrix", e2 = "missing"),  
           function(e1) {  
               warning("inefficient method used for \"- e1\"")  
               0-e1  
           })  
   
 ## bail-outs:  
 setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),  
           function(e1, e2) {  
               d <- dimCheck(e1,e2)  
               .bail.out.2(.Generic, class(e1), class(e2))  
           })  
 setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),  
           function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))  
 setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),  
           function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))  
   
254    
255    ##-> see ./Ops.R
256    
257  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
258  ###  ###
# Line 249  Line 286 
286            function(x,i,j, drop)            function(x,i,j, drop)
287            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
288    
289  ##  "logical *vector* indexing, such as  M [ M >= 10 ] :  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
290  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  ## The following is *both* for    M [ <logical>   ]
291                           drop = "ANY"),  ##                 and also for   M [ <logical> , ]
292            function (x, i, j, drop) {  .M.sub.i.logical <- function (x, i, j, drop)
293    {
294        nA <- nargs()
295        if(nA == 2) { ##  M [ M >= 7 ]
296            ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
297                as(x, geClass(x))@x[as.vector(i)]                as(x, geClass(x))@x[as.vector(i)]
298                                          # -> error when lengths don't match          ## -> error when lengths don't match
299            })      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
300            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
301    
302        } else stop("nargs() = ", nA,
303                    " should never happen; please report.")
304    }
305    setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
306                             drop = "ANY"),
307              .M.sub.i.logical)
308  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
309                           drop = "ANY"),                           drop = "ANY"),
310            function (x, i, j, drop) as(x, geClass(x))@x[i])            .M.sub.i.logical)
311    
312    
313    ## A[ ij ]  where ij is (i,j) 2-column matrix :
314    .M.sub.i.2col <- function (x, i, j, drop)
315    {
316        nA <- nargs()
317        if(nA == 2) { ##  M [ cbind(ii,jj) ]
318            if(!is.integer(nc <- ncol(i)))
319                stop("'i' has no integer column number",
320                     " should never happen; please report")
321            if(is.logical(i))
322                return(.M.sub.i.logical(x,i,j,drop))
323            else if(!is.numeric(i) || nc != 2)
324                stop("such indexing must be by logical or 2-column numeric matrix")
325            m <- nrow(i)
326            if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
327            ## else
328            i1 <- i[,1]
329            i2 <- i[,2]
330            ## potentially inefficient -- FIXME --
331            unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
332    
333  ## "FIXME:"      } else stop("nargs() = ", nA, " should never happen; please report.")
334  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?  }
335  ##  and                A[ LL ]  where LL is a logical *vector*  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
336  ## -> [.data.frame uses nargs() - can we do this in the *generic* ?            .M.sub.i.2col)
337    
338    
339  ### "[<-" : -----------------  ### "[<-" : -----------------
# Line 274  Line 342 
342  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
343                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
344            function (x, value) {            function (x, value) {
345                  ## Fails for 'nMatrix' ... FIXME : make sure have method there
346                x@x <- value                x@x <- value
347                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
348                x                x
349            })            })
350    
351  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
352    ## ----------------   The cheap general method --- FIXME: provide special ones
353    .M.repl.i.2col <- function (x, i, j, value)
354    {
355        nA <- nargs()
356        if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value
357            if(!is.integer(nc <- ncol(i)))
358                stop("'i' has no integer column number",
359                     " should never happen; please report")
360            else if(!is.numeric(i) || nc != 2)
361                stop("such indexing must be by logical or 2-column numeric matrix")
362            if(is.logical(i)) {
363                message(".M.repl.i.2col(): drop 'matrix' case ...")
364                i <- c(i) # drop "matrix"
365                return( callNextMethod() )
366            }
367            if(!is.integer(i)) storage.mode(i) <- "integer"
368            if(any(i < 0))
369                stop("negative values are not allowed in a matrix subscript")
370            if(any(is.na(i)))
371                stop("NAs are not allowed in subscripted assignments")
372            if(any(i0 <- (i == 0))) # remove them
373                i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
374            ## now have integer i >= 1
375            m <- nrow(i)
376            ## mod.x <- .type.kind[.M.kind(x)]
377            if(length(value) > 0 && m %% length(value) != 0)
378                warning("number of items to replace is not a multiple of replacement length")
379            ## recycle:
380            value <- rep(value, length = m)
381            i1 <- i[,1]
382            i2 <- i[,2]
383            ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
384            for(k in seq_len(m))
385                x[i1[k], i2[k]] <- value[k]
386    
387            x
388        } else stop("nargs() = ", nA, " should never happen; please report.")
389    }
390    
391    setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
392                                    value = "replValue"),
393              .M.repl.i.2col)
394    
395    
396    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
397                                    value = "Matrix"),
398                     function (x, i, j, value) {
399    ### *TEMPORARY* diagnostic output:
400    ##                  cat("<Matrix1>[i,j] <- <Matrix1>:\n<Matrix1> = x :")
401    ##                  str(x)
402    ##                  cat("<Matrix2> = value :")
403    ##                  str(value)
404    ##                  cat("i :"); if(!missing(i)) str(i) else cat("<missing>\n")
405    ##                  cat("j :"); if(!missing(j)) str(j) else cat("<missing>\n")
406    
407                         callGeneric(x=x, i=i, j=j, value = as.vector(value))
408                     })
409    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
410                                    value = "Matrix"),
411                     function (x, i, j, value)
412                     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
413    
414    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
415                                    value = "matrix"),
416                     function (x, i, j, value)
417                     callGeneric(x=x, i=i, j=j, value = c(value)))
418    
419  ## (ANY,ANY,ANY) is used when no `real method' is implemented :  ## (ANY,ANY,ANY) is used when no `real method' is implemented :
420  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
421                                  value = "ANY"),                                  value = "ANY"),
422            function (x, i, j, value) {            function (x, i, j, value) {
423                if(!is.atomic(value))                if(!is.atomic(value))
424                    stop("RHS 'value' must match matrix class ", class(x))                    stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
425                                   class(value),class(x)))
426                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
427            })            })
   
   
 ## The trivial methods :  
 setMethod("cbind2", signature(x = "Matrix", y = "NULL"),  
           function(x, y) x)  
 setMethod("cbind2", signature(x = "Matrix", y = "missing"),  
           function(x, y) x)  
 setMethod("cbind2", signature(x = "NULL", y="Matrix"),  
           function(x, y) x)  
   
 setMethod("rbind2", signature(x = "Matrix", y = "NULL"),  
           function(x, y) x)  
 setMethod("rbind2", signature(x = "Matrix", y = "missing"),  
           function(x, y) x)  
 setMethod("rbind2", signature(x = "NULL", y="Matrix"),  
           function(x, y) x)  
   
 ## Makes sure one gets x decent error message for the unimplemented cases:  
 setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),  
           function(x, y) {  
               rowCheck(x,y)  
               stop(gettextf("cbind2() method for (%s,%s) not-yet defined",  
                             class(x), class(y)))  
           })  
   
 ## Use a working fall back {particularly useful for sparse}:  
 ## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones  
 setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),  
           function(x, y) {  
               colCheck(x,y)  
               t(cbind2(t(x), t(y)))  
           })  

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

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