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 871, Fri Aug 26 17:26:49 2005 UTC revision 1467, Wed Aug 30 21:35:09 2006 UTC
# Line 1  Line 1 
1  #### Toplevel ``virtual'' class "Matrix"  #### Toplevel ``virtual'' class "Matrix"
2    
3  ## probably not needed eventually:  
4  setAs(from = "ddenseMatrix", to = "matrix",  ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)
5        function(from) {  
6            if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")  setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))
7            array(from@x, dim = d, dimnames = dimnames(from))  setAs("Matrix", "denseMatrix",  function(from) as_dense(from))
8        })  
9    ## ## probably not needed eventually:
10  ## private function to be used as show() method possibly more than once  ## setAs(from = "ddenseMatrix", to = "matrix",
11  prMatrix <- function(object) {  ##       function(from) {
12      d <- dim(object)  ##        if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")
13      cl <- class(object)  ##        array(from@x, dim = d, dimnames = dimnames(from))
14      cat(sprintf('%d x %d Matrix of class "%s"\n', d[1], d[2], cl))  ##       })
     m <- as(object, "matrix")  
     maxp <- getOption("max.print")  
     if(prod(d) <= maxp) print(m)  
     else { ## d[1] > maxp / d[2] >= nr :  
         nr <- maxp %/% d[2]  
         n2 <- ceiling(nr / 2)  
         print(head(m, max(1, n2)))  
         cat("\n ..........\n\n")  
         print(tail(m, max(1, nr - n2)))  
     }  
     ## DEBUG: cat("str(.):\n") ; str(object)  
     invisible(object)# as print() S3 methods do  
 }  
   
 setMethod("show", signature(object = "ddenseMatrix"), prMatrix)  
   
 ##- ## 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"), prMatrix)  
15    
16  ## should propagate to all subclasses:  ## should propagate to all subclasses:
17  setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))  setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))
18    ## for 'Matrix' objects, as.array() should be equivalent:
19    setMethod("as.array",  signature(x = "Matrix"), function(x) as(x, "matrix"))
20    
21    ## head and tail apply to all Matrix objects for which subscripting is allowed:
22    ## if(paste(R.version$major, R.version$minor, sep=".") < "2.4") {
23        setMethod("head", signature(x = "Matrix"), utils:::head.matrix)
24        setMethod("tail", signature(x = "Matrix"), utils:::tail.matrix)
25    ## } else { # R 2.4.0 and newer
26    ##     setMethod("head", signature(x = "Matrix"), utils::head.matrix)
27    ##     setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
28    ## }
29    
30    ## slow "fall back" method {subclasses should have faster ones}:
31    setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
32              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    
41    ## "base" has an isSymmetric() S3-generic since R 2.3.0
42    setMethod("isSymmetric", signature(object = "symmetricMatrix"),
43              function(object,tol) TRUE)
44    setMethod("isSymmetric", signature(object = "triangularMatrix"),
45              ## TRUE iff diagonal:
46              function(object,tol) isDiagonal(object))
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")
# Line 62  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, forceCheck = FALSE)
81  {  {
82      if (is(data, "Matrix")) return(data)      sparseDefault <- function(m)
83      if (is.matrix(data)) { val <- data }          prod(dim(m)) > 2*sum(is.na(m <- as(m, "matrix")) | m != 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        doDN <- TRUE
90        if (i.M && !forceCheck) {
91            sM <- is(data,"sparseMatrix")
92            if((sparse && sM) || (!sparse && !sM))
93                return(data)
94            ## else : convert  dense <-> sparse -> at end
95        }
96        else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
97          if (missing(nrow))          if (missing(nrow))
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          val <- .Internal(matrix(data, nrow, ncol, byrow))          if(length(data) == 1 && !is.na(data) && data == 0 &&
102          dimnames(val) <- dimnames             !identical(sparse, FALSE)) {
103    
104                if(is.null(sparse)) 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))
114                if(is.null(sparse))
115                    sparse <- sparseDefault(data)
116                dimnames(data) <- dimnames
117            }
118            doDN <- FALSE
119        }
120        ## 'data' is now a "matrix" or "Matrix"
121        if (doDN && !is.null(dimnames))
122            dimnames(data) <- dimnames
123    
124        ## check for symmetric / triangular / diagonal :
125        isSym <- isSymmetric(data)
126        if((isTri <- !isSym))
127            isTri <- isTriangular(data)
128        isDiag <- isSym # cannot be diagonal if it isn't symmetric
129        if(isDiag)
130            isDiag <- isDiagonal(data)
131    
132    ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R
133    
134        ## Find proper matrix class 'cl'
135        cl <-
136            if(isDiag)
137                "diagonalMatrix" # -> will automatically check for type
138            else {
139                ## consider it's type
140                ctype <-
141                    if(is(data,"Matrix")) class(data)
142                    else {
143                        if("complex" == (ctype <- typeof(data)))
144                            "z" else ctype
145                    }
146                ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
147                if(ctype == "z")
148                    stop("complex matrices not yet implemented in Matrix package")
149                if(ctype == "i") {
150                    warning("integer matrices not yet implemented in 'Matrix'; ",
151                            "using 'double' ones'")
152                    ctype <- "d"
153      }      }
154      as(val, "dgeMatrix")              paste(ctype,
155                      if(sparse) {
156                          if(isSym) "sCMatrix" else
157                          if(isTri) "tCMatrix" else "gCMatrix"
158                      } else { ## dense
159                          if(isSym) "syMatrix" else
160                          if(isTri) "trMatrix" else "geMatrix"
161                      }, sep="")
162            }
163    
164        ## Now coerce and return
165        as(data, cl)
166  }  }
167    
168  ## Methods for operations where one argument is numeric  ## Methods for operations where one argument is numeric
# Line 90  Line 178 
178    
179  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
180            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
   
181  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
182            function(x, y = NULL)  callGeneric(rbind(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
183    
184    ## The as.matrix() promotion seems illogical to MM,
185    ## but is according to help(tcrossprod, package = "base") :
186    setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
187              function(x, y = NULL) callGeneric(x, as.matrix(y)))
188    setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
189              function(x, y = NULL)  callGeneric(as.matrix(x), y))
190    
191  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
192            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, as.matrix(b)))
193    
194    ## bail-out methods in order to get better error messages
195    setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
196              function (x, y)
197              stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
198                            class(x), class(y))))
199    
200    setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
201              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
202    setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
203              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
204    setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
205              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
206    setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
207              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
208    
209    ## cheap fallbacks
210    setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
211              function(x, y = NULL) t(x) %*% y)
212    setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
213              function(x, y = NULL) x %*% t(y))
214    
215    ## There are special sparse methods; this is a "fall back":
216    setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
217                                     FUN = "ANY", make.dimnames = "ANY"),
218              function(X, Y, FUN, make.dimnames, ...) {
219                  X <- as(X, "matrix") ; Matrix(callGeneric()) })
220    setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
221                                     FUN = "ANY", make.dimnames = "ANY"),
222              function(X, Y, FUN, make.dimnames, ...) {
223                  Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
224    
225    
226    setMethod("diag", signature(x = "Matrix"),
227              function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
228    setMethod("t", signature(x = "Matrix"),
229              function(x) .bail.out.1(.Generic, class(x)))
230    
231    ## Group Methods
232    setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)
233    ## "fallback":
234    setMethod("-", signature(e1 = "Matrix", e2 = "missing"),
235              function(e1) {
236                  warning("inefficient method used for \"- e1\"")
237                  0-e1
238              })
239    
240    ## bail-outs:
241    setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),
242              function(e1, e2) {
243                  d <- dimCheck(e1,e2)
244                  .bail.out.2(.Generic, class(e1), class(e2))
245              })
246    setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),
247              function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
248    setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),
249              function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
250    
251    
252    
253  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
254  ###  ###
255  ### Subsetting "["  and  ### Subsetting "["  and
256  ### SubAssign  "[<-" : The "missing" cases can be dealt with here, "at the top":  ### SubAssign  "[<-" : The "missing" cases can be dealt with here, "at the top":
257    
258    ## Using "index" for indices should allow
259    ## integer (numeric), logical, or character (names!) indices :
260    
261  ## "x[]":  ## "x[]":
262  setMethod("[", signature(x = "Matrix",  setMethod("[", signature(x = "Matrix",
263                           i = "missing", j = "missing", drop = "ANY"),                           i = "missing", j = "missing", drop = "ANY"),
264            function (x, i, j, drop) x)            function (x, i, j, drop) x)
265    
266  ## missing 'drop' --> 'drop = TRUE'  ## missing 'drop' --> 'drop = TRUE'
267  ##                     -----------  ##                     -----------
268  ## select rows  ## select rows
269  setMethod("[", signature(x = "Matrix", i = "numeric", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
270                           drop = "missing"),                           drop = "missing"),
271            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))
272  ## select columns  ## select columns
273  setMethod("[", signature(x = "Matrix", i = "missing", j = "numeric",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
274                           drop = "missing"),                           drop = "missing"),
275            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))
276  setMethod("[", signature(x = "Matrix", i = "numeric", j = "numeric",  setMethod("[", signature(x = "Matrix", i = "index", j = "index",
277                           drop = "missing"),                           drop = "missing"),
278            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))
279    
280    ## bail out if any of (i,j,drop) is "non-sense"
281    setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
282              function(x,i,j, drop)
283              stop("invalid or not-yet-implemented 'Matrix' subsetting"))
284    
285    ##  "logical *vector* indexing, such as  M [ M >= 10 ] :
286    setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
287                             drop = "ANY"),
288              function (x, i, j, drop) {
289                  as(x, geClass(x))@x[as.vector(i)]
290                  ## -> error when lengths don't match
291              })
292    
293    ## FIXME: The following is good for    M [ <logical>   ]
294    ##        *BUT* it also triggers for   M [ <logical> , ] where it is *WRONG*
295    ##       using nargs() does not help: it gives '3' for both cases
296    if(FALSE)
297    setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
298                             drop = "ANY"),
299              function (x, i, j, drop) {
300                  ## DEBUG
301                  cat("[(Matrix,i,..): nargs=", nargs(),"\n")
302                  as(x, geClass(x))@x[i] })
303    
304    
305  ## "FIXME:"  ## "FIXME:"
306  ## 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?
307  ##  and                A[ LL ]  where LL is a logical *vector*  ##  and                A[ LL ]  where LL is a logical *vector*
308    ## -> [.data.frame uses nargs() - can we do this in the *generic* ?
309    
310    
311  ### "[<-" : -----------------  ### "[<-" : -----------------
312    
313  ## x[] <- value :  ## x[] <- value :
314  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
315                                  value = "vector"),##  double/logical/...                                  value = "ANY"),## double/logical/...
316            function (x, value) { x@x <- value ; validObject(x); x })            function (x, value) {
317                  x@x <- value
318                  validObject(x)# check if type and lengths above match
319                  x
320              })
321    
322  ## Otherwise (value is not "vector"): bail out  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);
323    ## (ANY,ANY,ANY) is used when no `real method' is implemented :
324  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
325                                  value = "ANY"),                                  value = "ANY"),
326            function (x, i, j, value) stop("RHS 'value' must be of class \"vector\""))            function (x, i, j, value) {
327                  if(!is.atomic(value))
328                      stop("RHS 'value' must match matrix class ", class(x))
329                  else stop("not-yet-implemented 'Matrix[<-' method")
330              })
331    
332    
333    ## The trivial methods :
334    setMethod("cbind2", signature(x = "Matrix", y = "NULL"),
335              function(x, y) x)
336    setMethod("cbind2", signature(x = "Matrix", y = "missing"),
337              function(x, y) x)
338    setMethod("cbind2", signature(x = "NULL", y="Matrix"),
339              function(x, y) x)
340    
341    setMethod("rbind2", signature(x = "Matrix", y = "NULL"),
342              function(x, y) x)
343    setMethod("rbind2", signature(x = "Matrix", y = "missing"),
344              function(x, y) x)
345    setMethod("rbind2", signature(x = "NULL", y="Matrix"),
346              function(x, y) x)
347    
348    ## Makes sure one gets x decent error message for the unimplemented cases:
349    setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),
350              function(x, y) {
351                  rowCheck(x,y)
352                  stop(gettextf("cbind2() method for (%s,%s) not-yet defined",
353                                class(x), class(y)))
354              })
355    
356  if(FALSE) ## The following can't work as long as cbind is function(..., *)  ## Use a working fall back {particularly useful for sparse}:
357  setMethod("cbind", signature(a = "Matrix", b = "Matrix"),  ## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones
358            function(a, b, ...) {  setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),
359                da <- Dim(a)            function(x, y) {
360                db <- Dim(b)                colCheck(x,y)
361                if(da[1] != db[1])                t(cbind2(t(x), t(y)))
                   stop("Matrices must have same number of rows for cbind()ing")  
362            })            })

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

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