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 676, Sat Mar 26 15:59:18 2005 UTC revision 1551, Tue Sep 12 16:39:13 2006 UTC
# Line 1  Line 1 
1  #### Toplevel ``virtual'' class "Matrix"  #### Toplevel ``virtual'' class "Matrix"
2    
 ## probably not needed eventually:  
 setAs(from = "ddenseMatrix", to = "matrix",  
       function(from) {  
           if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")  
           array(from@x, dim = d, dimnames = dimnames(from))  
       })  
   
 ## private function to be used as show() method possibly more than once  
 prMatrix <- function(object) {  
     d <- dim(object)  
     cl <- class(object)  
     cat(sprintf('%d x %d Matrix of class "%s"\n', d[1], d[2], cl))  
 ##- no longer needed: have no objects of virtual classes:  
 ##     if(cl == "Matrix") { ## have no data slot  
 ##         cat("Dim = ", d)  
 ##         if(any(sapply(object@Dimnames,length) > 0)) {  
 ##             cat("; Dimnames = ")  
 ##             str(object@Dimnames)  
 ##         }  
 ##         cat("\n")  
 ##     } else { # not "Matrix", hence have data 'x' slot  
         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)  
   
 setMethod("show", signature(object = "sparseMatrix"),  
    function(object) {  
        d <- dim(object)  
        cl <- class(object)  
        cat(sprintf('%d x %d sparse Matrix of class "%s"\n', d[1], d[2], cl))  
   
        maxp <- getOption("max.print")  
        if(prod(d) <= maxp) print(as(object, "matrix"))  
        else { ## d[1] > maxp / d[2] >= nr :  
            cat("\n Not printing large sparse matrix -- maybe increase options(max.print)\n")  
            if(FALSE) { ### need storage economic "[,]" method for sparse!!  
                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)  
    })  
3    
4  ## this may go away {since sparse matrices need something better!} :  ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)
5  setMethod("show", signature(object = "Matrix"), prMatrix)  
6    setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))
7    setAs("Matrix", "denseMatrix",  function(from) as_dense(from))
8    
9    setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:
10          function(from) .bail.out.2("coerce", class(from), class(to)))
11    
12    ## ## probably not needed eventually:
13    ## setAs(from = "ddenseMatrix", to = "matrix",
14    ##       function(from) {
15    ##        if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")
16    ##        array(from@x, dim = d, dimnames = dimnames(from))
17    ##       })
18    
19  ## should propagate to all subclasses:  ## should propagate to all subclasses:
20  setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))  setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))
21    ## for 'Matrix' objects, as.array() should be equivalent:
22    setMethod("as.array",  signature(x = "Matrix"), function(x) as(x, "matrix"))
23    
24    ## head and tail apply to all Matrix objects for which subscripting is allowed:
25    setMethod("head", signature(x = "Matrix"), utils::head.matrix)
26    setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
27    
28    ## slow "fall back" method {subclasses should have faster ones}:
29    setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
30              function(x) as.vector(as(x, "matrix")))
31    
32    ## mainly need these for "dMatrix" or "lMatrix" respectively, but why not general:
33    setMethod("as.numeric", signature(x = "Matrix"),
34              function(x, ...) as.numeric(as.vector(x)))
35    setMethod("as.logical", signature(x = "Matrix"),
36              function(x, ...) as.logical(as.vector(x)))
37    
38    
39    ## "base" has an isSymmetric() S3-generic since R 2.3.0
40    setMethod("isSymmetric", signature(object = "symmetricMatrix"),
41              function(object,tol) TRUE)
42    setMethod("isSymmetric", signature(object = "triangularMatrix"),
43              ## TRUE iff diagonal:
44              function(object,tol) isDiagonal(object))
45    
46    setMethod("isTriangular", signature(object = "triangularMatrix"),
47              function(object, ...) TRUE)
48    
49    setMethod("isTriangular", signature(object = "matrix"), isTriMat)
50    
51    setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
52    
53    
54    
55  setMethod("dim", signature(x = "Matrix"),  setMethod("dim", signature(x = "Matrix"),
56            function(x) x@Dim, valueClass = "integer")            function(x) x@Dim, valueClass = "integer")
# Line 88  Line 74 
74            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
75    
76  Matrix <-  Matrix <-
77      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
78                  sparse = NULL, forceCheck = FALSE)
79  {  {
80      if (is(data, "Matrix")) return(data)      sparseDefault <- function(m)
81      if (is.matrix(data)) { val <- data }          prod(dim(m)) > 2*sum(is.na(m <- as(m, "matrix")) | m != 0)
82      else { ## cut & paste from "base::matrix" :  
83        i.M <- is(data, "Matrix")
84        if(is.null(sparse) && (i.M || is(data, "matrix")))
85            sparse <- sparseDefault(data)
86    
87        doDN <- TRUE
88        if (i.M) {
89            sM <- is(data,"sparseMatrix")
90            if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
91                return(data)
92            ## else : convert  dense <-> sparse -> at end
93        }
94        else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
95          if (missing(nrow))          if (missing(nrow))
96              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
97          else if (missing(ncol))          else if (missing(ncol))
98              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
99          val <- .Internal(matrix(data, nrow, ncol, byrow))          if(length(data) == 1 && !is.na(data) && data == 0 &&
100          dimnames(val) <- dimnames             !identical(sparse, FALSE)) {
     }  
     as(val, "dgeMatrix")  
 }  
101    
102                if(is.null(sparse)) sparse <- TRUE
103                ## will be sparse: do NOT construct full matrix!
104                data <- new(if(is.numeric(data)) "dgTMatrix" else
105                            if(is.logical(data)) "lgTMatrix" else
106                            stop("invalid 'data'"),
107                            Dim = as.integer(c(nrow,ncol)),
108                            Dimnames = if(is.null(dimnames)) list(NULL,NULL)
109                            else dimnames)
110            } else { ## normal case
111                data <- .Internal(matrix(data, nrow, ncol, byrow))
112                if(is.null(sparse))
113                    sparse <- sparseDefault(data)
114                dimnames(data) <- dimnames
115            }
116            doDN <- FALSE
117        }
118        ## 'data' is now a "matrix" or "Matrix"
119        if (doDN && !is.null(dimnames))
120            dimnames(data) <- dimnames
121    
122        ## check for symmetric / triangular / diagonal :
123        isSym <- isSymmetric(data)
124        if((isTri <- !isSym))
125            isTri <- isTriangular(data)
126        isDiag <- isSym # cannot be diagonal if it isn't symmetric
127        if(isDiag)
128            isDiag <- isDiagonal(data)
129    
130    ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R
131    
132        ## Find proper matrix class 'cl'
133        cl <-
134            if(isDiag)
135                "diagonalMatrix" # -> will automatically check for type
136            else {
137                ## consider it's type
138                ctype <-
139                    if(is(data,"Matrix")) class(data)
140                    else {
141                        if("complex" == (ctype <- typeof(data)))
142                            "z" else ctype
143                    }
144                ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
145                if(ctype == "z")
146                    stop("complex matrices not yet implemented in Matrix package")
147                if(ctype == "i") {
148                    warning("integer matrices not yet implemented in 'Matrix'; ",
149                            "using 'double' ones'")
150                    ctype <- "d"
151                }
152                paste(ctype,
153                      if(sparse) {
154                          if(isSym) "sCMatrix" else
155                          if(isTri) "tCMatrix" else "gCMatrix"
156                      } else { ## dense
157                          if(isSym) "syMatrix" else
158                          if(isTri) "trMatrix" else "geMatrix"
159                      }, sep="")
160            }
161    
162        ## Now coerce and return
163        as(data, cl)
164    }
165    
166    ## Methods for operations where one argument is numeric
167    
168    ## Using as.matrix() and rbind()
169    ## in order to get dimnames from names {at least potentially}:
170    
171    setMethod("%*%", signature(x = "Matrix", y = "numeric"),
172              function(x, y) callGeneric(x, as.matrix(y)))
173    
174    setMethod("%*%", signature(x = "numeric", y = "Matrix"),
175              function(x, y) callGeneric(rbind(x), y))
176    
177    setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
178              function(x, y = NULL) callGeneric(x, as.matrix(y)))
179    setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
180              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"),
190              function(a, b, ...) callGeneric(a, as.matrix(b)))
191    
192    ## bail-out methods in order to get better error messages
193    setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
194              function (x, y)
195              stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
196                            class(x), class(y))))
197    
198    setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
199              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
200    setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
201              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
202    setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
203              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
204    setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
205              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
206    
207    ## cheap fallbacks
208    setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
209              function(x, y = NULL) t(x) %*% y)
210    setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
211              function(x, y = NULL) x %*% t(y))
212    
213    ## There are special sparse methods; this is a "fall back":
214    setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
215                                     FUN = "ANY", make.dimnames = "ANY"),
216              function(X, Y, FUN, make.dimnames, ...) {
217                  X <- as(X, "matrix") ; Matrix(callGeneric()) })
218    setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
219                                     FUN = "ANY", make.dimnames = "ANY"),
220              function(X, Y, FUN, make.dimnames, ...) {
221                  Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
222    
223    
224    setMethod("diag", signature(x = "Matrix"),
225              function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
226    setMethod("t", signature(x = "Matrix"),
227              function(x) .bail.out.1(.Generic, class(x)))
228    
229    ## Group Methods
230    setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)
231    ## "fallback":
232    setMethod("-", signature(e1 = "Matrix", e2 = "missing"),
233              function(e1) {
234                  warning("inefficient method used for \"- e1\"")
235                  0-e1
236              })
237    
238    ## bail-outs:
239    setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),
240              function(e1, e2) {
241                  d <- dimCheck(e1,e2)
242                  .bail.out.2(.Generic, class(e1), class(e2))
243              })
244    setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),
245              function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
246    setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),
247              function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
248    
 if(FALSE) { ##--- not-yet used -- {almost same code also in ./dgeMatrix.R }  
249    
 ## utility for as.Matrix() {which is currently invalid }  
 Matrix.class <- function(x, tol = 0, symmetry = TRUE, unit.diagonal = TRUE,  
                          triangularity = c(TRUE, TRUE),  
                          orthogonality = c(TRUE, TRUE),  
                          normality = c(TRUE, TRUE))  
 {  
     val <- "Matrix"  
     x <- as.matrix(x)  
     if (symmetry) {  
         if (is.Hermitian(x, tol)) val <- c("Hermitian", val)  
     }  
     if (triangularity[1]) {  
         if (is.LowerTriangular(x, tol)) {  
             val <- c("LowerTriangular", val)  
             if (unit.diagonal)  
                 if (max(Mod(diag(x) - 1)) <= tol)  
                     val <- c("UnitLowerTriangular", val)  
         }  
     }  
     if (triangularity[2]) {  
         if (is.UpperTriangular(x, tol)) {  
             val <- c("UpperTriangular", val)  
             if (unit.diagonal)  
                 if (max(Mod(diag(x) - 1)) <= tol)  
                     val <- c("UnitUpperTriangular", val)  
         }  
     }  
     if (orthogonality[1]) {  
         if (is.ColOrthonormal(x, tol)) {  
             val <- c("ColOrthoNormal", "ColOrthogonal", val)  
         } else {  
             if (Orthogonal.test(x, normal = FALSE) <= tol)  
                 val <- c("ColOrthogonal", val)  
         }  
     }  
     if (orthogonality[2]) {  
         if (normality[2] && is.RowOrthonormal(x, tol)) {  
             val <- c("RowOrthoNormal", "RowOrthogonal", val)  
         } else {  
             if (Orthogonal.test(x, byrow = TRUE, normal = FALSE) <= tol)  
                 val <- c("RowOrthogonal", val)  
         }  
     }  
     val  
 }  
250    
251  as.Matrix <- function(x, tol = .Machine$double.eps)  ### --------------------------------------------------------------------------
252    ###
253    ### Subsetting "["  and
254    ### SubAssign  "[<-" : The "missing" cases can be dealt with here, "at the top":
255    
256    ## Using "index" for indices should allow
257    ## integer (numeric), logical, or character (names!) indices :
258    
259    ## "x[]":
260    setMethod("[", signature(x = "Matrix",
261                             i = "missing", j = "missing", drop = "ANY"),
262              function (x, i, j, drop) x)
263    
264    ## missing 'drop' --> 'drop = TRUE'
265    ##                     -----------
266    ## select rows
267    setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
268                             drop = "missing"),
269              function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))
270    ## select columns
271    setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
272                             drop = "missing"),
273              function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))
274    setMethod("[", signature(x = "Matrix", i = "index", j = "index",
275                             drop = "missing"),
276              function(x,i,j, drop) callGeneric(x, i=i, j=j, drop= TRUE))
277    
278    ## bail out if any of (i,j,drop) is "non-sense"
279    setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
280              function(x,i,j, drop)
281              stop("invalid or not-yet-implemented 'Matrix' subsetting"))
282    
283    ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
284    ## The following is *both* for    M [ <logical>   ]
285    ##                 and also for   M [ <logical> , ]
286    .M.sub.i.logical <- function (x, i, j, drop)
287  {  {
288      asObject(if (inherits(x, "Matrix")) x else as.matrix(x),      nA <- nargs()
289               Matrix.class(x, tol = tol))      if(nA == 2) { ##  M [ M >= 7 ]
290            as(x, geClass(x))@x[as.vector(i)]
291            ## -> error when lengths don't match
292        } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
293            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
294    
295        } else stop("nargs() = ", nA,
296                    " should never happen; please report.")
297  }  }
298    setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
299                             drop = "ANY"),
300              .M.sub.i.logical)
301    setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
302                             drop = "ANY"),
303              .M.sub.i.logical)
304    
305    
306    ## "FIXME:"
307    ## ------ get at  A[ ij ]  where ij is (i,j) 2-column matrix?
308    
309  }## not-yet used  
310    
311    ### "[<-" : -----------------
312    
313    ## x[] <- value :
314    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
315                                    value = "ANY"),## double/logical/...
316              function (x, value) {
317                  x@x <- value
318                  validObject(x)# check if type and lengths above match
319                  x
320              })
321    
322    ## 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",
325                                    value = "ANY"),
326              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    ## Use a working fall back {particularly useful for sparse}:
357    ## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones
358    setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),
359              function(x, y) {
360                  colCheck(x,y)
361                  t(cbind2(t(x), t(y)))
362              })

Legend:
Removed from v.676  
changed lines
  Added in v.1551

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