SCM

SCM Repository

[matrix] Annotation of /pkg/R/Matrix.R
ViewVC logotype

Annotation of /pkg/R/Matrix.R

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1332 - (view) (download)

1 : maechler 607 #### Toplevel ``virtual'' class "Matrix"
2 :    
3 : maechler 1331
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 : maechler 956 ## ## probably not needed eventually:
10 :     ## setAs(from = "ddenseMatrix", to = "matrix",
11 :     ## function(from) {
12 :     ## if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")
13 :     ## array(from@x, dim = d, dimnames = dimnames(from))
14 :     ## })
15 : maechler 607
16 : maechler 676 ## should propagate to all subclasses:
17 : maechler 658 setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))
18 : maechler 956 ## for 'Matrix' objects, as.array() should be equivalent:
19 :     setMethod("as.array", signature(x = "Matrix"), function(x) as(x, "matrix"))
20 : bates 1326 ## head and tail apply to all Matrix objects for which subscripting is allowed
21 :     setMethod("head", signature(x = "Matrix"),
22 :     function(x, n = 6, ...)
23 :     x[seq(len = min(n, nrow(x))), , drop = FALSE])
24 :     setMethod("tail", signature(x = "Matrix"),
25 : maechler 1329 function (x, n = 6, addrownums = TRUE, ...)
26 : bates 1326 {
27 :     nrx <- nrow(x)
28 :     sel <- seq(to = nrx, length = min(n, nrx))
29 :     ans <- x[sel, , drop = FALSE]
30 : maechler 1329 if (addrownums && is.null(rownames(x)))
31 : bates 1326 rownames(ans) <- paste("[", sel, ",]", sep = "")
32 :     ans
33 :     })
34 : maechler 658
35 : maechler 956 ## slow "fall back" method {subclasses should have faster ones}:
36 :     setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
37 : maechler 1331 function(x) as.vector(as(x, "matrix")))
38 : maechler 956
39 :    
40 : maechler 1174 ## Note that isSymmetric is *not* exported
41 :     ## but that "base" has an isSymmetric() S3-generic since R 2.3.0
42 : maechler 1108 setMethod("isSymmetric", signature(object = "symmetricMatrix"),
43 : maechler 973 function(object,tol) TRUE)
44 : maechler 1108 setMethod("isSymmetric", signature(object = "triangularMatrix"),
45 : maechler 1174 ## TRUE iff diagonal:
46 :     function(object,tol) isDiagonal(object))
47 : maechler 1189
48 : maechler 1174 if(paste(R.version$major, R.version$minor, sep=".") < "2.3")
49 :     ## need a "matrix" method as in R 2.3 and later
50 :     setMethod("isSymmetric", signature(object = "matrix"),
51 : maechler 1189 function(object, tol = 100*.Machine$double.eps, ...)
52 :     {
53 :     ## pretest: is it square?
54 :     d <- dim(object)
55 :     if(d[1] != d[2]) return(FALSE)
56 :     ## for `broken' all.equal in R <= 2.2.x:
57 :     dn <- dimnames(object)
58 :     if(!identical(dn[1], dn[2])) return(FALSE)
59 :     test <-
60 :     if(is.complex(object))
61 :     all.equal.numeric(object, Conj(t(object)), tol = tol, ...)
62 :     else # numeric, character, ..
63 :     all.equal(object, t(object), tol = tol, ...)
64 :     isTRUE(test)
65 :     })
66 : maechler 973
67 : maechler 1174
68 : maechler 1165 setMethod("isTriangular", signature(object = "triangularMatrix"),
69 : maechler 1238 function(object, ...) TRUE)
70 : maechler 1165
71 : maechler 1238 setMethod("isTriangular", signature(object = "matrix"), isTriMat)
72 :    
73 : maechler 1174 setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
74 : maechler 886
75 : maechler 1174
76 :    
77 : maechler 579 setMethod("dim", signature(x = "Matrix"),
78 : maechler 698 function(x) x@Dim, valueClass = "integer")
79 : maechler 579 setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
80 : maechler 607 ## not exported but used more than once for "dimnames<-" method :
81 :     ## -- or do only once for all "Matrix" classes ??
82 :     dimnamesGets <- function (x, value) {
83 :     d <- dim(x)
84 :     if (!is.list(value) || length(value) != 2 ||
85 : maechler 698 !(is.null(v1 <- value[[1]]) || length(v1) == d[1]) ||
86 :     !(is.null(v2 <- value[[2]]) || length(v2) == d[2]))
87 :     stop(sprintf("invalid dimnames given for '%s' object", class(x)))
88 : maechler 607 x@Dimnames <- list(if(!is.null(v1)) as.character(v1),
89 : maechler 698 if(!is.null(v2)) as.character(v2))
90 : maechler 607 x
91 :     }
92 :     setMethod("dimnames<-", signature(x = "Matrix", value = "list"),
93 : maechler 698 dimnamesGets)
94 : maechler 579
95 : maechler 658 setMethod("unname", signature("Matrix", force="missing"),
96 : maechler 698 function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
97 : maechler 607
98 : bates 10 Matrix <-
99 : maechler 954 function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
100 : maechler 1174 sparse = NULL)
101 : bates 10 {
102 : maechler 954 sparseDefault <- function(m)
103 : maechler 1174 prod(dim(m)) > 2*sum(as(m, "matrix") != 0)
104 : maechler 954
105 :     i.M <- is(data, "Matrix")
106 :     if(is.null(sparse) && (i.M || is(data, "matrix")))
107 : maechler 1174 sparse <- sparseDefault(data)
108 : maechler 954
109 :     if (i.M) {
110 : maechler 1174 sM <- is(data,"sparseMatrix")
111 :     if((sparse && sM) || (!sparse && !sM))
112 :     return(data)
113 :     ## else : convert dense <-> sparse -> at end
114 : maechler 954 }
115 :     else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
116 : maechler 698 if (missing(nrow))
117 :     nrow <- ceiling(length(data)/ncol)
118 :     else if (missing(ncol))
119 :     ncol <- ceiling(length(data)/nrow)
120 : maechler 1315 if(length(data) == 1 && data == 0 && !identical(sparse,FALSE)) {
121 :     if(is.null(sparse)) sparse <- TRUE
122 :     ## will be sparse: do NOT construct full matrix!
123 :     data <- new(if(is.numeric(data)) "dgTMatrix" else
124 :     if(is.logical(data)) "lgTMatrix" else
125 :     stop("invalid 'data'"),
126 :     Dim = as.integer(c(nrow,ncol)),
127 : maechler 1332 Dimnames = if(is.null(dimnames)) list(NULL,NULL)
128 :     else dimnames)
129 : maechler 1315 } else { ## normal case
130 :     data <- .Internal(matrix(data, nrow, ncol, byrow))
131 :     if(is.null(sparse))
132 :     sparse <- sparseDefault(data)
133 :     dimnames(data) <- dimnames
134 :     }
135 : maechler 1189 } else if (!is.null(dimnames))
136 :     dimnames(data) <- dimnames
137 : maechler 954
138 :     ## 'data' is now a "matrix" or "Matrix"
139 : maechler 1174
140 :     ## check for symmetric / triangular / diagonal :
141 :     isSym <- isSymmetric(data)
142 :     if((isTri <- !isSym))
143 :     isTri <- isTriangular(data)
144 :     isDiag <- isSym # cannot be diagonal if it isn't symmetric
145 :     if(isDiag)
146 :     isDiag <- isDiagonal(data)
147 :    
148 : maechler 965 ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R
149 : maechler 1174
150 :     ## Find proper matrix class 'cl'
151 :     cl <-
152 :     if(isDiag)
153 :     "diagonalMatrix" # -> will automatically check for type
154 :     else {
155 :     ## consider it's type
156 :     ctype <-
157 :     if(is(data,"Matrix")) class(data)
158 :     else {
159 :     if("complex" == (ctype <- typeof(data)))
160 :     "z" else ctype
161 :     }
162 :     ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
163 :     if(ctype == "z")
164 :     stop("complex matrices not yet implemented in Matrix package")
165 :     if(ctype == "i") {
166 :     warning("integer matrices not yet implemented in 'Matrix'; ",
167 :     "using 'double' ones'")
168 :     ctype <- "d"
169 :     }
170 :     paste(ctype,
171 :     if(sparse) {
172 :     if(isSym) "sCMatrix" else
173 :     if(isTri) "tCMatrix" else "gCMatrix"
174 :     } else { ## dense
175 :     if(isSym) "syMatrix" else
176 :     if(isTri) "trMatrix" else "geMatrix"
177 :     }, sep="")
178 :     }
179 :    
180 :     ## Now coerce and return
181 :     as(data, cl)
182 : bates 10 }
183 :    
184 : bates 683 ## Methods for operations where one argument is numeric
185 : maechler 512
186 : maechler 698 ## Using as.matrix() and rbind()
187 :     ## in order to get dimnames from names {at least potentially}:
188 :    
189 : bates 683 setMethod("%*%", signature(x = "Matrix", y = "numeric"),
190 : maechler 698 function(x, y) callGeneric(x, as.matrix(y)))
191 : bates 683
192 :     setMethod("%*%", signature(x = "numeric", y = "Matrix"),
193 : maechler 698 function(x, y) callGeneric(rbind(x), y))
194 : bates 683
195 :     setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
196 : maechler 698 function(x, y = NULL) callGeneric(x, as.matrix(y)))
197 : bates 683 setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
198 : maechler 1331 function(x, y = NULL) callGeneric(as.matrix(x), y))
199 : bates 683
200 : maechler 1331 ## The as.matrix() promotion seems illogical to MM,
201 :     ## but is according to help(tcrossprod, package = "base") :
202 :     setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
203 :     function(x, y = NULL) callGeneric(x, as.matrix(y)))
204 :     setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
205 :     function(x, y = NULL) callGeneric(as.matrix(x), y))
206 :    
207 : bates 683 setMethod("solve", signature(a = "Matrix", b = "numeric"),
208 : maechler 698 function(a, b, ...) callGeneric(a, as.matrix(b)))
209 : maechler 848
210 : maechler 925 ## bail-out methods in order to get better error messages
211 :     setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
212 :     function (x, y)
213 :     stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
214 :     class(x), class(y))))
215 : maechler 946
216 : maechler 925 setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
217 : maechler 946 function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
218 : maechler 956 setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
219 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
220 : maechler 1331 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 : maechler 925
225 : maechler 1331 ## 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 : maechler 956 ## There are special sparse methods; this is a "fall back":
232 :     setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
233 :     FUN = "ANY", make.dimnames = "ANY"),
234 :     function(X, Y, FUN, make.dimnames, ...) {
235 :     X <- as(X, "matrix") ; Matrix(callGeneric()) })
236 :     setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
237 :     FUN = "ANY", make.dimnames = "ANY"),
238 :     function(X, Y, FUN, make.dimnames, ...) {
239 :     Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
240 :    
241 :    
242 : maechler 1315 setMethod("diag", signature(x = "Matrix"),
243 :     function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
244 : maechler 946 setMethod("t", signature(x = "Matrix"),
245 :     function(x) .bail.out.1(.Generic, class(x)))
246 : maechler 925
247 : maechler 956 ## Group Methods
248 :     setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)
249 :     ## "fallback":
250 :     setMethod("-", signature(e1 = "Matrix", e2 = "missing"),
251 :     function(e1) {
252 :     warning("inefficient method used for \"- e1\"")
253 :     0-e1
254 :     })
255 :    
256 :     ## bail-outs:
257 : maechler 946 setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),
258 : maechler 954 function(e1, e2) {
259 :     d <- dimCheck(e1,e2)
260 :     .bail.out.2(.Generic, class(e1), class(e2))
261 :     })
262 : maechler 946 setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),
263 :     function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
264 :     setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),
265 :     function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
266 :    
267 :    
268 :    
269 : maechler 871 ### --------------------------------------------------------------------------
270 :     ###
271 :     ### Subsetting "[" and
272 :     ### SubAssign "[<-" : The "missing" cases can be dealt with here, "at the top":
273 : maechler 868
274 : maechler 886 ## Using "index" for indices should allow
275 : maechler 875 ## integer (numeric), logical, or character (names!) indices :
276 :    
277 : maechler 868 ## "x[]":
278 :     setMethod("[", signature(x = "Matrix",
279 :     i = "missing", j = "missing", drop = "ANY"),
280 :     function (x, i, j, drop) x)
281 : maechler 1225
282 : maechler 868 ## missing 'drop' --> 'drop = TRUE'
283 :     ## -----------
284 :     ## select rows
285 : maechler 886 setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
286 : maechler 868 drop = "missing"),
287 :     function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))
288 :     ## select columns
289 : maechler 886 setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
290 : maechler 868 drop = "missing"),
291 :     function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))
292 : maechler 886 setMethod("[", signature(x = "Matrix", i = "index", j = "index",
293 : maechler 868 drop = "missing"),
294 :     function(x,i,j, drop) callGeneric(x, i=i, j=j, drop= TRUE))
295 :    
296 : maechler 875 ## bail out if any of (i,j,drop) is "non-sense"
297 :     setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
298 :     function(x,i,j, drop)
299 :     stop("invalid or not-yet-implemented 'Matrix' subsetting"))
300 :    
301 : maechler 1225 ## "logical *vector* indexing, such as M [ M >= 10 ] :
302 :     setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
303 :     drop = "ANY"),
304 :     function (x, i, j, drop) {
305 :     as(x, geClass(x))@x[as.vector(i)]
306 : maechler 1329 ## -> error when lengths don't match
307 : maechler 1225 })
308 :    
309 : maechler 1329 ## FIXME: The following is good for M [ <logical> ]
310 :     ## *BUT* it also triggers for M [ <logical> , ] where it is *WRONG*
311 :     ## using nargs() does not help: it gives '3' for both cases
312 :     if(FALSE)
313 : maechler 1225 setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
314 :     drop = "ANY"),
315 : maechler 1329 function (x, i, j, drop) {
316 :     ## DEBUG
317 :     cat("[(Matrix,i,..): nargs=", nargs(),"\n")
318 :     as(x, geClass(x))@x[i] })
319 : maechler 1225
320 :    
321 : maechler 868 ## "FIXME:"
322 :     ## How can we get at A[ ij ] where ij is (i,j) 2-column matrix?
323 :     ## and A[ LL ] where LL is a logical *vector*
324 : maechler 886 ## -> [.data.frame uses nargs() - can we do this in the *generic* ?
325 : maechler 868
326 :    
327 : maechler 871 ### "[<-" : -----------------
328 : maechler 868
329 : maechler 871 ## x[] <- value :
330 :     setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
331 : maechler 1189 value = "ANY"),## double/logical/...
332 :     function (x, value) {
333 :     x@x <- value
334 :     validObject(x)# check if type and lengths above match
335 :     x
336 :     })
337 : maechler 871
338 : maechler 1189 ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);
339 :     ## (ANY,ANY,ANY) is used when no `real method' is implemented :
340 : maechler 871 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
341 :     value = "ANY"),
342 : maechler 1189 function (x, i, j, value) {
343 :     if(!is.atomic(value))
344 :     stop("RHS 'value' must match matrix class ", class(x))
345 :     else stop("not-yet-implemented 'Matrix[<-' method")
346 :     })
347 : maechler 871
348 :    
349 : maechler 1290 ## The trivial methods :
350 :     setMethod("cbind2", signature(x = "Matrix", y = "NULL"),
351 :     function(x, y) x)
352 :     setMethod("cbind2", signature(x = "Matrix", y = "missing"),
353 :     function(x, y) x)
354 :     setMethod("cbind2", signature(x = "NULL", y="Matrix"),
355 :     function(x, y) x)
356 : maechler 871
357 : maechler 1290 setMethod("rbind2", signature(x = "Matrix", y = "NULL"),
358 :     function(x, y) x)
359 :     setMethod("rbind2", signature(x = "Matrix", y = "missing"),
360 :     function(x, y) x)
361 :     setMethod("rbind2", signature(x = "NULL", y="Matrix"),
362 :     function(x, y) x)
363 : maechler 875
364 : maechler 1290 ## Makes sure one gets x decent error message for the unimplemented cases:
365 :     setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),
366 :     function(x, y) {
367 :     rowCheck(x,y)
368 :     stop(gettextf("cbind2() method for (%s,%s) not-yet defined",
369 :     class(x), class(y)))
370 :     })
371 : maechler 908
372 : maechler 1290 ## Use a working fall back {particularly useful for sparse}:
373 :     ## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones
374 :     setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),
375 :     function(x, y) {
376 :     colCheck(x,y)
377 :     t(cbind2(t(x), t(y)))
378 :     })

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