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

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