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 1513, Tue Sep 5 13:16:23 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    setMethod("head", signature(x = "Matrix"), utils::head.matrix)
23    setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
24    
25    ## slow "fall back" method {subclasses should have faster ones}:
26    setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
27              function(x) as.vector(as(x, "matrix")))
28    
29    ## mainly need these for "dMatrix" or "lMatrix" respectively, but why not general:
30    setMethod("as.numeric", signature(x = "Matrix"),
31              function(x, ...) as.numeric(as.vector(x)))
32    setMethod("as.logical", signature(x = "Matrix"),
33              function(x, ...) as.logical(as.vector(x)))
34    
35    
36    ## "base" has an isSymmetric() S3-generic since R 2.3.0
37    setMethod("isSymmetric", signature(object = "symmetricMatrix"),
38              function(object,tol) TRUE)
39    setMethod("isSymmetric", signature(object = "triangularMatrix"),
40              ## TRUE iff diagonal:
41              function(object,tol) isDiagonal(object))
42    
43    setMethod("isTriangular", signature(object = "triangularMatrix"),
44              function(object, ...) TRUE)
45    
46    setMethod("isTriangular", signature(object = "matrix"), isTriMat)
47    
48    setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
49    
50    
51    
52  setMethod("dim", signature(x = "Matrix"),  setMethod("dim", signature(x = "Matrix"),
53            function(x) x@Dim, valueClass = "integer")            function(x) x@Dim, valueClass = "integer")
# Line 62  Line 71 
71            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
72    
73  Matrix <-  Matrix <-
74      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
75                  sparse = NULL, forceCheck = FALSE)
76  {  {
77      if (is(data, "Matrix")) return(data)      sparseDefault <- function(m)
78      if (is.matrix(data)) { val <- data }          prod(dim(m)) > 2*sum(is.na(m <- as(m, "matrix")) | m != 0)
79      else { ## cut & paste from "base::matrix" :  
80        i.M <- is(data, "Matrix")
81        if(is.null(sparse) && (i.M || is(data, "matrix")))
82            sparse <- sparseDefault(data)
83    
84        doDN <- TRUE
85        if (i.M && !forceCheck) {
86            sM <- is(data,"sparseMatrix")
87            if((sparse && sM) || (!sparse && !sM))
88                return(data)
89            ## else : convert  dense <-> sparse -> at end
90        }
91        else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
92          if (missing(nrow))          if (missing(nrow))
93              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
94          else if (missing(ncol))          else if (missing(ncol))
95              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
96          val <- .Internal(matrix(data, nrow, ncol, byrow))          if(length(data) == 1 && !is.na(data) && data == 0 &&
97          dimnames(val) <- dimnames             !identical(sparse, FALSE)) {
98    
99                if(is.null(sparse)) sparse <- TRUE
100                ## will be sparse: do NOT construct full matrix!
101                data <- new(if(is.numeric(data)) "dgTMatrix" else
102                            if(is.logical(data)) "lgTMatrix" else
103                            stop("invalid 'data'"),
104                            Dim = as.integer(c(nrow,ncol)),
105                            Dimnames = if(is.null(dimnames)) list(NULL,NULL)
106                            else dimnames)
107            } else { ## normal case
108                data <- .Internal(matrix(data, nrow, ncol, byrow))
109                if(is.null(sparse))
110                    sparse <- sparseDefault(data)
111                dimnames(data) <- dimnames
112      }      }
113      as(val, "dgeMatrix")          doDN <- FALSE
114        }
115        ## 'data' is now a "matrix" or "Matrix"
116        if (doDN && !is.null(dimnames))
117            dimnames(data) <- dimnames
118    
119        ## check for symmetric / triangular / diagonal :
120        isSym <- isSymmetric(data)
121        if((isTri <- !isSym))
122            isTri <- isTriangular(data)
123        isDiag <- isSym # cannot be diagonal if it isn't symmetric
124        if(isDiag)
125            isDiag <- isDiagonal(data)
126    
127    ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R
128    
129        ## Find proper matrix class 'cl'
130        cl <-
131            if(isDiag)
132                "diagonalMatrix" # -> will automatically check for type
133            else {
134                ## consider it's type
135                ctype <-
136                    if(is(data,"Matrix")) class(data)
137                    else {
138                        if("complex" == (ctype <- typeof(data)))
139                            "z" else ctype
140                    }
141                ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
142                if(ctype == "z")
143                    stop("complex matrices not yet implemented in Matrix package")
144                if(ctype == "i") {
145                    warning("integer matrices not yet implemented in 'Matrix'; ",
146                            "using 'double' ones'")
147                    ctype <- "d"
148                }
149                paste(ctype,
150                      if(sparse) {
151                          if(isSym) "sCMatrix" else
152                          if(isTri) "tCMatrix" else "gCMatrix"
153                      } else { ## dense
154                          if(isSym) "syMatrix" else
155                          if(isTri) "trMatrix" else "geMatrix"
156                      }, sep="")
157            }
158    
159        ## Now coerce and return
160        as(data, cl)
161  }  }
162    
163  ## Methods for operations where one argument is numeric  ## Methods for operations where one argument is numeric
# Line 90  Line 173 
173    
174  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
175            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
   
176  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
177            function(x, y = NULL)  callGeneric(rbind(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
178    
179    ## The as.matrix() promotion seems illogical to MM,
180    ## but is according to help(tcrossprod, package = "base") :
181    setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
182              function(x, y = NULL) callGeneric(x, as.matrix(y)))
183    setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
184              function(x, y = NULL)  callGeneric(as.matrix(x), y))
185    
186  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
187            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, as.matrix(b)))
188    
189    ## bail-out methods in order to get better error messages
190    setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
191              function (x, y)
192              stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
193                            class(x), class(y))))
194    
195    setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
196              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
197    setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
198              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
199    setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
200              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
201    setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
202              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
203    
204    ## cheap fallbacks
205    setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
206              function(x, y = NULL) t(x) %*% y)
207    setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
208              function(x, y = NULL) x %*% t(y))
209    
210    ## There are special sparse methods; this is a "fall back":
211    setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
212                                     FUN = "ANY", make.dimnames = "ANY"),
213              function(X, Y, FUN, make.dimnames, ...) {
214                  X <- as(X, "matrix") ; Matrix(callGeneric()) })
215    setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
216                                     FUN = "ANY", make.dimnames = "ANY"),
217              function(X, Y, FUN, make.dimnames, ...) {
218                  Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
219    
220    
221    setMethod("diag", signature(x = "Matrix"),
222              function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
223    setMethod("t", signature(x = "Matrix"),
224              function(x) .bail.out.1(.Generic, class(x)))
225    
226    ## Group Methods
227    setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)
228    ## "fallback":
229    setMethod("-", signature(e1 = "Matrix", e2 = "missing"),
230              function(e1) {
231                  warning("inefficient method used for \"- e1\"")
232                  0-e1
233              })
234    
235    ## bail-outs:
236    setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),
237              function(e1, e2) {
238                  d <- dimCheck(e1,e2)
239                  .bail.out.2(.Generic, class(e1), class(e2))
240              })
241    setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),
242              function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
243    setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),
244              function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
245    
246    
247    
248  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
249  ###  ###
250  ### Subsetting "["  and  ### Subsetting "["  and
251  ### SubAssign  "[<-" : The "missing" cases can be dealt with here, "at the top":  ### SubAssign  "[<-" : The "missing" cases can be dealt with here, "at the top":
252    
253    ## Using "index" for indices should allow
254    ## integer (numeric), logical, or character (names!) indices :
255    
256  ## "x[]":  ## "x[]":
257  setMethod("[", signature(x = "Matrix",  setMethod("[", signature(x = "Matrix",
258                           i = "missing", j = "missing", drop = "ANY"),                           i = "missing", j = "missing", drop = "ANY"),
259            function (x, i, j, drop) x)            function (x, i, j, drop) x)
260    
261  ## missing 'drop' --> 'drop = TRUE'  ## missing 'drop' --> 'drop = TRUE'
262  ##                     -----------  ##                     -----------
263  ## select rows  ## select rows
264  setMethod("[", signature(x = "Matrix", i = "numeric", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
265                           drop = "missing"),                           drop = "missing"),
266            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))
267  ## select columns  ## select columns
268  setMethod("[", signature(x = "Matrix", i = "missing", j = "numeric",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
269                           drop = "missing"),                           drop = "missing"),
270            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))
271  setMethod("[", signature(x = "Matrix", i = "numeric", j = "numeric",  setMethod("[", signature(x = "Matrix", i = "index", j = "index",
272                           drop = "missing"),                           drop = "missing"),
273            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))
274    
275    ## bail out if any of (i,j,drop) is "non-sense"
276    setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
277              function(x,i,j, drop)
278              stop("invalid or not-yet-implemented 'Matrix' subsetting"))
279    
280    ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
281    ## The following is *both* for    M [ <logical>   ]
282    ##                 and also for   M [ <logical> , ]
283    .M.sub.i.logical <- function (x, i, j, drop)
284    {
285        nA <- nargs()
286        if(nA == 2) { ##  M [ M >= 7 ]
287            as(x, geClass(x))@x[as.vector(i)]
288            ## -> error when lengths don't match
289        } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
290            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
291    
292        } else stop("nargs() = ", nA,
293                    " should never happen; please report.")
294    }
295    setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
296                             drop = "ANY"),
297              .M.sub.i.logical)
298    setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
299                             drop = "ANY"),
300              .M.sub.i.logical)
301    
302    
303  ## "FIXME:"  ## "FIXME:"
304  ## 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?
 ##  and                A[ LL ]  where LL is a logical *vector*  
305    
306    
307    
# Line 130  Line 309 
309    
310  ## x[] <- value :  ## x[] <- value :
311  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
312                                  value = "vector"),##  double/logical/...                                  value = "ANY"),## double/logical/...
313            function (x, value) { x@x <- value ; validObject(x); x })            function (x, value) {
314                  x@x <- value
315                  validObject(x)# check if type and lengths above match
316                  x
317              })
318    
319  ## Otherwise (value is not "vector"): bail out  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);
320    ## (ANY,ANY,ANY) is used when no `real method' is implemented :
321  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
322                                  value = "ANY"),                                  value = "ANY"),
323            function (x, i, j, value) stop("RHS 'value' must be of class \"vector\""))            function (x, i, j, value) {
324                  if(!is.atomic(value))
325                      stop("RHS 'value' must match matrix class ", class(x))
326                  else stop("not-yet-implemented 'Matrix[<-' method")
327              })
328    
329    
330    ## The trivial methods :
331    setMethod("cbind2", signature(x = "Matrix", y = "NULL"),
332              function(x, y) x)
333    setMethod("cbind2", signature(x = "Matrix", y = "missing"),
334              function(x, y) x)
335    setMethod("cbind2", signature(x = "NULL", y="Matrix"),
336              function(x, y) x)
337    
338    setMethod("rbind2", signature(x = "Matrix", y = "NULL"),
339              function(x, y) x)
340    setMethod("rbind2", signature(x = "Matrix", y = "missing"),
341              function(x, y) x)
342    setMethod("rbind2", signature(x = "NULL", y="Matrix"),
343              function(x, y) x)
344    
345    ## Makes sure one gets x decent error message for the unimplemented cases:
346    setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),
347              function(x, y) {
348                  rowCheck(x,y)
349                  stop(gettextf("cbind2() method for (%s,%s) not-yet defined",
350                                class(x), class(y)))
351              })
352    
353  if(FALSE) ## The following can't work as long as cbind is function(..., *)  ## Use a working fall back {particularly useful for sparse}:
354  setMethod("cbind", signature(a = "Matrix", b = "Matrix"),  ## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones
355            function(a, b, ...) {  setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),
356                da <- Dim(a)            function(x, y) {
357                db <- Dim(b)                colCheck(x,y)
358                if(da[1] != db[1])                t(cbind2(t(x), t(y)))
                   stop("Matrices must have same number of rows for cbind()ing")  
359            })            })

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

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