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 1467, Wed Aug 30 21:35:09 2006 UTC revision 1673, Mon Nov 6 20:54:26 2006 UTC
# Line 6  Line 6 
6  setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))  setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))
7  setAs("Matrix", "denseMatrix",  function(from) as_dense(from))  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 19  Line 24 
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:  ## head and tail apply to all Matrix objects for which subscripting is allowed:
27  ## if(paste(R.version$major, R.version$minor, sep=".") < "2.4") {  setMethod("head", signature(x = "Matrix"), utils::head.matrix)
28      setMethod("head", signature(x = "Matrix"), utils:::head.matrix)  setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
     setMethod("tail", signature(x = "Matrix"), utils:::tail.matrix)  
 ## } else { # R 2.4.0 and newer  
 ##     setMethod("head", signature(x = "Matrix"), utils::head.matrix)  
 ##     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"),
# Line 79  Line 79 
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)                sparse = NULL, forceCheck = FALSE)
81  {  {
82      sparseDefault <- function(m)      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
         prod(dim(m)) > 2*sum(is.na(m <- as(m, "matrix")) | m != 0)  
83    
84      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
85      if(is.null(sparse) && (i.M || is(data, "matrix")))  
86        if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
87          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
88    
89      doDN <- TRUE      doDN <- TRUE
90      if (i.M && !forceCheck) {      if (i.M) {
91          sM <- is(data,"sparseMatrix")          sM <- is(data,"sparseMatrix")
92          if((sparse && sM) || (!sparse && !sM))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
93              return(data)              return(data)
94          ## else : convert  dense <-> sparse -> at end          ## else : convert  dense <-> sparse -> at end
95      }      }
# Line 98  Line 98 
98              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
99          else if (missing(ncol))          else if (missing(ncol))
100              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
101          if(length(data) == 1 && !is.na(data) && data == 0 &&          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
102             !identical(sparse, FALSE)) {              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
103                if(is.null(sparse)) sparse1 <- sparse <- TRUE
             if(is.null(sparse)) sparse <- TRUE  
104              ## will be sparse: do NOT construct full matrix!              ## will be sparse: do NOT construct full matrix!
105              data <- new(if(is.numeric(data)) "dgTMatrix" else              data <- new(if(is.numeric(data)) "dgTMatrix" else
106                          if(is.logical(data)) "lgTMatrix" else                          if(is.logical(data)) "lgTMatrix" else
# Line 129  Line 128 
128      if(isDiag)      if(isDiag)
129          isDiag <- isDiagonal(data)          isDiag <- isDiagonal(data)
130    
 ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R  
   
131      ## Find proper matrix class 'cl'      ## Find proper matrix class 'cl'
132      cl <-      cl <-
133          if(isDiag)          if(isDiag && !isTRUE(sparse1))
134              "diagonalMatrix" # -> will automatically check for type              "diagonalMatrix" # -> will automatically check for type
135          else {          else {
136              ## consider it's type              ## consider it's type
# Line 174  Line 171 
171            function(x, y) callGeneric(x, as.matrix(y)))            function(x, y) callGeneric(x, as.matrix(y)))
172    
173  setMethod("%*%", signature(x = "numeric", y = "Matrix"),  setMethod("%*%", signature(x = "numeric", y = "Matrix"),
174            function(x, y) callGeneric(rbind(x), y))            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
175    
176  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
177            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
# Line 188  Line 185 
185  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
186            function(x, y = NULL)  callGeneric(as.matrix(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
187    
188    ## maybe not optimal
189    setMethod("solve", signature(a = "Matrix", b = "missing"),
190              function(a, b, ...) solve(a, Diagonal(nrow(a))))
191    
192  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
193            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, as.matrix(b)))
194    ## when no sub-class method is found, bail out
195    setMethod("solve", signature(a = "Matrix", b = "matrix"),
196              function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))
197    
198  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
199  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 223  Line 227 
227                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
228    
229    
230    ## FIXME: All of these should never be called
231    setMethod("chol", signature(x = "Matrix"),
232              function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))
233    setMethod("determinant", signature(x = "Matrix"),
234              function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))
235    
236  setMethod("diag", signature(x = "Matrix"),  setMethod("diag", signature(x = "Matrix"),
237            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
238  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
# Line 237  Line 247 
247                0-e1                0-e1
248            })            })
249    
250  ## bail-outs:  ## old-style matrices are made into new ones
251  setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),  setMethod("Ops", signature(e1 = "Matrix", e2 = "matrix"),
252              function(e1, e2) callGeneric(e1, Matrix(e2)))
253    ##          callGeneric(e1, Matrix(e2, sparse=is(e1,"sparseMatrix"))))
254    setMethod("Ops", signature(e1 = "matrix", e2 = "Matrix"),
255              function(e1, e2) callGeneric(Matrix(e1), e2))
256    
257    ## bail-outs -- on highest possible level, hence "Ops", not "Compare"/"Arith" :
258    setMethod("Ops", signature(e1 = "Matrix", e2 = "Matrix"),
259            function(e1, e2) {            function(e1, e2) {
260                d <- dimCheck(e1,e2)                d <- dimCheck(e1,e2)
261                .bail.out.2(.Generic, class(e1), class(e2))                .bail.out.2(.Generic, class(e1), class(e2))
262            })            })
263  setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),  setMethod("Ops", signature(e1 = "Matrix", e2 = "ANY"),
264            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
265  setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),  setMethod("Ops", signature(e1 = "ANY", e2 = "Matrix"),
266            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))            function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
267    
268    
# Line 282  Line 299 
299            function(x,i,j, drop)            function(x,i,j, drop)
300            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
301    
302  ##  "logical *vector* indexing, such as  M [ M >= 10 ] :  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
303  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  ## The following is *both* for    M [ <logical>   ]
304                           drop = "ANY"),  ##                 and also for   M [ <logical> , ]
305            function (x, i, j, drop) {  .M.sub.i.logical <- function (x, i, j, drop)
306    {
307        nA <- nargs()
308        if(nA == 2) { ##  M [ M >= 7 ]
309            ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
310                as(x, geClass(x))@x[as.vector(i)]                as(x, geClass(x))@x[as.vector(i)]
311                ## -> error when lengths don't match                ## -> error when lengths don't match
312            })      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
313            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
314    
315  ## FIXME: The following is good for    M [ <logical>   ]      } else stop("nargs() = ", nA,
316  ##        *BUT* it also triggers for   M [ <logical> , ] where it is *WRONG*                  " should never happen; please report.")
317  ##       using nargs() does not help: it gives '3' for both cases  }
318  if(FALSE)  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
319                             drop = "ANY"),
320              .M.sub.i.logical)
321  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
322                           drop = "ANY"),                           drop = "ANY"),
323            function (x, i, j, drop) {            .M.sub.i.logical)
324                ## DEBUG  
               cat("[(Matrix,i,..): nargs=", nargs(),"\n")  
               as(x, geClass(x))@x[i] })  
325    
326    ## A[ ij ]  where ij is (i,j) 2-column matrix :
327    .M.sub.i.2col <- function (x, i, j, drop)
328    {
329        nA <- nargs()
330        if(nA == 2) { ##  M [ cbind(ii,jj) ]
331            if(!is.integer(nc <- ncol(i)))
332                stop("'i' has no integer column number",
333                     " should never happen; please report")
334            if(is.logical(i))
335                return(.M.sub.i.logical(x,i,j,drop))
336            else if(!is.numeric(i) || nc != 2)
337                stop("such indexing must be by logical or 2-column numeric matrix")
338            m <- nrow(i)
339            if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
340            ## else
341            i1 <- i[,1]
342            i2 <- i[,2]
343            ## potentially inefficient -- FIXME --
344            unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
345    
346  ## "FIXME:"      } else stop("nargs() = ", nA, " should never happen; please report.")
347  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?  }
348  ##  and                A[ LL ]  where LL is a logical *vector*  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
349  ## -> [.data.frame uses nargs() - can we do this in the *generic* ?            .M.sub.i.2col)
350    
351    
352  ### "[<-" : -----------------  ### "[<-" : -----------------
# Line 314  Line 355 
355  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
356                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
357            function (x, value) {            function (x, value) {
358                  ## Fails for 'nMatrix' ... FIXME : make sure have method there
359                x@x <- value                x@x <- value
360                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
361                x                x
362            })            })
363    
364  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
365    .M.repl.i.2col <- function (x, i, j, value)
366    {
367        nA <- nargs()
368        if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value
369            if(!is.integer(nc <- ncol(i)))
370                stop("'i' has no integer column number",
371                     " should never happen; please report")
372            if(is.logical(i)) {
373                i <- c(i) # drop "matrix"
374                return( callNextMethod() )
375            } else if(!is.numeric(i) || nc != 2)
376                stop("such indexing must be by logical or 2-column numeric matrix")
377            m <- nrow(i)
378            mod.x <- .type.kind[.M.kind(x)]
379            if(length(value) > 0 && m %% length(value) != 0)
380                warning("number of items to replace is not a multiple of replacement length")
381            ## recycle:
382            value <- rep(value, length = m)
383            i1 <- i[,1]
384            i2 <- i[,2]
385            ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
386            for(k in seq_len(m))
387                x[i1[k], i2[k]] <- value[k]
388            x
389    
390        } else stop("nargs() = ", nA, " should never happen; please report.")
391    }
392    setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
393                                    value = "replValue"),
394              .M.repl.i.2col)
395    
396    
397    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
398                                    value = "Matrix"),
399                     function (x, i, j, value)
400                     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
401    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
402                                    value = "matrix"),
403                     function (x, i, j, value)
404                     callGeneric(x=x, i=i, j=j, value = c(value)))
405    
406  ## (ANY,ANY,ANY) is used when no `real method' is implemented :  ## (ANY,ANY,ANY) is used when no `real method' is implemented :
407  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
408                                  value = "ANY"),                                  value = "ANY"),
409            function (x, i, j, value) {            function (x, i, j, value) {
410                if(!is.atomic(value))                if(!is.atomic(value))
411                    stop("RHS 'value' must match matrix class ", class(x))                    stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
412                                   class(value),class(x)))
413                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
414            })            })
415    

Legend:
Removed from v.1467  
changed lines
  Added in v.1673

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