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 1708 - (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 1618 ## Most of these work; this is a last resort:
10 : maechler 1548 setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:
11 :     function(from) .bail.out.2("coerce", class(from), class(to)))
12 : maechler 1618 setAs(from = "matrix", to = "Matrix", function(from) Matrix(from))
13 : maechler 1548
14 : maechler 956 ## ## probably not needed eventually:
15 :     ## setAs(from = "ddenseMatrix", to = "matrix",
16 :     ## function(from) {
17 :     ## if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")
18 :     ## array(from@x, dim = d, dimnames = dimnames(from))
19 :     ## })
20 : maechler 607
21 : maechler 676 ## should propagate to all subclasses:
22 : maechler 658 setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))
23 : maechler 956 ## for 'Matrix' objects, as.array() should be equivalent:
24 :     setMethod("as.array", signature(x = "Matrix"), function(x) as(x, "matrix"))
25 : maechler 658
26 : maechler 1347 ## head and tail apply to all Matrix objects for which subscripting is allowed:
27 : maechler 1513 setMethod("head", signature(x = "Matrix"), utils::head.matrix)
28 :     setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
29 : maechler 1390
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 1467 ## "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 1165 setMethod("isTriangular", signature(object = "triangularMatrix"),
49 : maechler 1238 function(object, ...) TRUE)
50 : maechler 1165
51 : maechler 1238 setMethod("isTriangular", signature(object = "matrix"), isTriMat)
52 :    
53 : maechler 1174 setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
54 : maechler 886
55 : maechler 1174
56 :    
57 : maechler 579 setMethod("dim", signature(x = "Matrix"),
58 : maechler 698 function(x) x@Dim, valueClass = "integer")
59 : maechler 1705
60 : maechler 579 setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
61 : maechler 1705
62 :    
63 : maechler 607 ## not exported but used more than once for "dimnames<-" method :
64 :     ## -- or do only once for all "Matrix" classes ??
65 :     dimnamesGets <- function (x, value) {
66 :     d <- dim(x)
67 :     if (!is.list(value) || length(value) != 2 ||
68 : maechler 698 !(is.null(v1 <- value[[1]]) || length(v1) == d[1]) ||
69 :     !(is.null(v2 <- value[[2]]) || length(v2) == d[2]))
70 :     stop(sprintf("invalid dimnames given for '%s' object", class(x)))
71 : maechler 607 x@Dimnames <- list(if(!is.null(v1)) as.character(v1),
72 : maechler 698 if(!is.null(v2)) as.character(v2))
73 : maechler 607 x
74 :     }
75 :     setMethod("dimnames<-", signature(x = "Matrix", value = "list"),
76 : maechler 698 dimnamesGets)
77 : maechler 579
78 : maechler 658 setMethod("unname", signature("Matrix", force="missing"),
79 : maechler 698 function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
80 : maechler 607
81 : maechler 1705 setMethod("all", signature(x = "Matrix"),
82 :     function(x, ..., na.rm) { x <- as(x, "lMatrix"); callNextMethod()})
83 :     setMethod("any", signature(x = "Matrix"),
84 :     function(x, ..., na.rm) { x <- as(x, "lMatrix"); callNextMethod()})
85 :    
86 :    
87 :    
88 : bates 10 Matrix <-
89 : maechler 954 function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
90 : maechler 1455 sparse = NULL, forceCheck = FALSE)
91 : bates 10 {
92 : maechler 1665 sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
93 : maechler 954
94 :     i.M <- is(data, "Matrix")
95 : maechler 1618
96 :     if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
97 : maechler 1174 sparse <- sparseDefault(data)
98 : maechler 954
99 : maechler 1455 doDN <- TRUE
100 : maechler 1551 if (i.M) {
101 : maechler 1174 sM <- is(data,"sparseMatrix")
102 : maechler 1551 if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
103 : maechler 1174 return(data)
104 :     ## else : convert dense <-> sparse -> at end
105 : maechler 954 }
106 :     else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
107 : maechler 698 if (missing(nrow))
108 :     nrow <- ceiling(length(data)/ncol)
109 :     else if (missing(ncol))
110 :     ncol <- ceiling(length(data)/nrow)
111 : maechler 1618 if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
112 :     ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
113 :     if(is.null(sparse)) sparse1 <- sparse <- TRUE
114 : maechler 1315 ## will be sparse: do NOT construct full matrix!
115 :     data <- new(if(is.numeric(data)) "dgTMatrix" else
116 :     if(is.logical(data)) "lgTMatrix" else
117 :     stop("invalid 'data'"),
118 :     Dim = as.integer(c(nrow,ncol)),
119 : maechler 1332 Dimnames = if(is.null(dimnames)) list(NULL,NULL)
120 :     else dimnames)
121 : maechler 1315 } else { ## normal case
122 :     data <- .Internal(matrix(data, nrow, ncol, byrow))
123 :     if(is.null(sparse))
124 :     sparse <- sparseDefault(data)
125 :     dimnames(data) <- dimnames
126 :     }
127 : maechler 1455 doDN <- FALSE
128 :     }
129 :     ## 'data' is now a "matrix" or "Matrix"
130 :     if (doDN && !is.null(dimnames))
131 : maechler 1189 dimnames(data) <- dimnames
132 : maechler 954
133 : maechler 1174 ## check for symmetric / triangular / diagonal :
134 :     isSym <- isSymmetric(data)
135 :     if((isTri <- !isSym))
136 :     isTri <- isTriangular(data)
137 :     isDiag <- isSym # cannot be diagonal if it isn't symmetric
138 :     if(isDiag)
139 :     isDiag <- isDiagonal(data)
140 :    
141 :     ## Find proper matrix class 'cl'
142 :     cl <-
143 : maechler 1618 if(isDiag && !isTRUE(sparse1))
144 : maechler 1174 "diagonalMatrix" # -> will automatically check for type
145 :     else {
146 :     ## consider it's type
147 :     ctype <-
148 :     if(is(data,"Matrix")) class(data)
149 :     else {
150 :     if("complex" == (ctype <- typeof(data)))
151 :     "z" else ctype
152 :     }
153 :     ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
154 :     if(ctype == "z")
155 :     stop("complex matrices not yet implemented in Matrix package")
156 :     if(ctype == "i") {
157 :     warning("integer matrices not yet implemented in 'Matrix'; ",
158 :     "using 'double' ones'")
159 :     ctype <- "d"
160 :     }
161 :     paste(ctype,
162 :     if(sparse) {
163 :     if(isSym) "sCMatrix" else
164 :     if(isTri) "tCMatrix" else "gCMatrix"
165 :     } else { ## dense
166 :     if(isSym) "syMatrix" else
167 :     if(isTri) "trMatrix" else "geMatrix"
168 :     }, sep="")
169 :     }
170 :    
171 :     ## Now coerce and return
172 :     as(data, cl)
173 : bates 10 }
174 :    
175 : bates 683 ## Methods for operations where one argument is numeric
176 : maechler 512
177 : maechler 698 ## Using as.matrix() and rbind()
178 :     ## in order to get dimnames from names {at least potentially}:
179 :    
180 : bates 683 setMethod("%*%", signature(x = "Matrix", y = "numeric"),
181 : maechler 698 function(x, y) callGeneric(x, as.matrix(y)))
182 : bates 683
183 :     setMethod("%*%", signature(x = "numeric", y = "Matrix"),
184 : maechler 1660 function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
185 : bates 683
186 :     setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
187 : maechler 698 function(x, y = NULL) callGeneric(x, as.matrix(y)))
188 : bates 683 setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
189 : maechler 1331 function(x, y = NULL) callGeneric(as.matrix(x), y))
190 : bates 683
191 : maechler 1331 ## The as.matrix() promotion seems illogical to MM,
192 :     ## but is according to help(tcrossprod, package = "base") :
193 :     setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
194 :     function(x, y = NULL) callGeneric(x, as.matrix(y)))
195 :     setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
196 :     function(x, y = NULL) callGeneric(as.matrix(x), y))
197 :    
198 : maechler 1665 ## maybe not optimal
199 :     setMethod("solve", signature(a = "Matrix", b = "missing"),
200 :     function(a, b, ...) solve(a, Diagonal(nrow(a))))
201 :    
202 : bates 683 setMethod("solve", signature(a = "Matrix", b = "numeric"),
203 : maechler 698 function(a, b, ...) callGeneric(a, as.matrix(b)))
204 : maechler 1659 ## when no sub-class method is found, bail out
205 :     setMethod("solve", signature(a = "Matrix", b = "matrix"),
206 :     function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))
207 : maechler 848
208 : maechler 925 ## bail-out methods in order to get better error messages
209 :     setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
210 :     function (x, y)
211 :     stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
212 :     class(x), class(y))))
213 : maechler 946
214 : maechler 925 setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
215 : maechler 946 function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
216 : maechler 956 setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
217 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
218 : maechler 1331 setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
219 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
220 :     setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
221 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
222 : maechler 925
223 : maechler 1331 ## cheap fallbacks
224 :     setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
225 :     function(x, y = NULL) t(x) %*% y)
226 :     setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
227 :     function(x, y = NULL) x %*% t(y))
228 :    
229 : maechler 956 ## There are special sparse methods; this is a "fall back":
230 :     setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
231 :     FUN = "ANY", make.dimnames = "ANY"),
232 :     function(X, Y, FUN, make.dimnames, ...) {
233 :     X <- as(X, "matrix") ; Matrix(callGeneric()) })
234 :     setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
235 :     FUN = "ANY", make.dimnames = "ANY"),
236 :     function(X, Y, FUN, make.dimnames, ...) {
237 :     Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
238 :    
239 :    
240 : maechler 1654 ## FIXME: All of these should never be called
241 :     setMethod("chol", signature(x = "Matrix"),
242 :     function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))
243 :     setMethod("determinant", signature(x = "Matrix"),
244 :     function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))
245 :    
246 : maechler 1315 setMethod("diag", signature(x = "Matrix"),
247 :     function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
248 : maechler 946 setMethod("t", signature(x = "Matrix"),
249 :     function(x) .bail.out.1(.Generic, class(x)))
250 : maechler 925
251 : maechler 956 ## Group Methods
252 :     setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)
253 :     ## "fallback":
254 :     setMethod("-", signature(e1 = "Matrix", e2 = "missing"),
255 :     function(e1) {
256 :     warning("inefficient method used for \"- e1\"")
257 :     0-e1
258 :     })
259 :    
260 : maechler 1655 ## old-style matrices are made into new ones
261 :     setMethod("Ops", signature(e1 = "Matrix", e2 = "matrix"),
262 :     function(e1, e2) callGeneric(e1, Matrix(e2)))
263 :     ## callGeneric(e1, Matrix(e2, sparse=is(e1,"sparseMatrix"))))
264 :     setMethod("Ops", signature(e1 = "matrix", e2 = "Matrix"),
265 :     function(e1, e2) callGeneric(Matrix(e1), e2))
266 :    
267 : maechler 1654 ## bail-outs -- on highest possible level, hence "Ops", not "Compare"/"Arith" :
268 :     setMethod("Ops", signature(e1 = "Matrix", e2 = "Matrix"),
269 : maechler 954 function(e1, e2) {
270 :     d <- dimCheck(e1,e2)
271 :     .bail.out.2(.Generic, class(e1), class(e2))
272 :     })
273 : maechler 1654 setMethod("Ops", signature(e1 = "Matrix", e2 = "ANY"),
274 : maechler 946 function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
275 : maechler 1654 setMethod("Ops", signature(e1 = "ANY", e2 = "Matrix"),
276 : maechler 946 function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
277 :    
278 :    
279 :    
280 : maechler 871 ### --------------------------------------------------------------------------
281 :     ###
282 :     ### Subsetting "[" and
283 :     ### SubAssign "[<-" : The "missing" cases can be dealt with here, "at the top":
284 : maechler 868
285 : maechler 886 ## Using "index" for indices should allow
286 : maechler 875 ## integer (numeric), logical, or character (names!) indices :
287 :    
288 : maechler 868 ## "x[]":
289 :     setMethod("[", signature(x = "Matrix",
290 :     i = "missing", j = "missing", drop = "ANY"),
291 :     function (x, i, j, drop) x)
292 : maechler 1225
293 : maechler 868 ## missing 'drop' --> 'drop = TRUE'
294 :     ## -----------
295 :     ## select rows
296 : maechler 886 setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
297 : maechler 868 drop = "missing"),
298 :     function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))
299 :     ## select columns
300 : maechler 886 setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
301 : maechler 868 drop = "missing"),
302 :     function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))
303 : maechler 886 setMethod("[", signature(x = "Matrix", i = "index", j = "index",
304 : maechler 868 drop = "missing"),
305 :     function(x,i,j, drop) callGeneric(x, i=i, j=j, drop= TRUE))
306 :    
307 : maechler 875 ## bail out if any of (i,j,drop) is "non-sense"
308 :     setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
309 :     function(x,i,j, drop)
310 :     stop("invalid or not-yet-implemented 'Matrix' subsetting"))
311 :    
312 : maechler 1472 ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
313 :     ## The following is *both* for M [ <logical> ]
314 :     ## and also for M [ <logical> , ]
315 :     .M.sub.i.logical <- function (x, i, j, drop)
316 :     {
317 :     nA <- nargs()
318 :     if(nA == 2) { ## M [ M >= 7 ]
319 : maechler 1673 ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
320 : maechler 1472 as(x, geClass(x))@x[as.vector(i)]
321 :     ## -> error when lengths don't match
322 :     } else if(nA == 3) { ## M [ M[,1, drop=FALSE] >= 7, ]
323 :     stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
324 :    
325 :     } else stop("nargs() = ", nA,
326 :     " should never happen; please report.")
327 :     }
328 : maechler 1225 setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
329 :     drop = "ANY"),
330 : maechler 1472 .M.sub.i.logical)
331 : maechler 1225 setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
332 :     drop = "ANY"),
333 : maechler 1472 .M.sub.i.logical)
334 : maechler 1225
335 :    
336 : maechler 1673 ## A[ ij ] where ij is (i,j) 2-column matrix :
337 :     .M.sub.i.2col <- function (x, i, j, drop)
338 :     {
339 :     nA <- nargs()
340 :     if(nA == 2) { ## M [ cbind(ii,jj) ]
341 :     if(!is.integer(nc <- ncol(i)))
342 :     stop("'i' has no integer column number",
343 :     " should never happen; please report")
344 :     if(is.logical(i))
345 :     return(.M.sub.i.logical(x,i,j,drop))
346 :     else if(!is.numeric(i) || nc != 2)
347 :     stop("such indexing must be by logical or 2-column numeric matrix")
348 :     m <- nrow(i)
349 :     if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
350 :     ## else
351 :     i1 <- i[,1]
352 :     i2 <- i[,2]
353 :     ## potentially inefficient -- FIXME --
354 :     unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
355 : maechler 868
356 : maechler 1673 } else stop("nargs() = ", nA, " should never happen; please report.")
357 :     }
358 :     setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
359 :     .M.sub.i.2col)
360 : maechler 868
361 : maechler 1472
362 : maechler 871 ### "[<-" : -----------------
363 : maechler 868
364 : maechler 871 ## x[] <- value :
365 :     setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
366 : maechler 1189 value = "ANY"),## double/logical/...
367 :     function (x, value) {
368 : maechler 1615 ## Fails for 'nMatrix' ... FIXME : make sure have method there
369 :     x@x <- value
370 :     validObject(x)# check if type and lengths above match
371 :     x
372 : maechler 1189 })
373 : maechler 871
374 : maechler 1673 ## A[ ij ] <- value, where ij is (i,j) 2-column matrix :
375 :     .M.repl.i.2col <- function (x, i, j, value)
376 :     {
377 :     nA <- nargs()
378 :     if(nA == 3) { ## M [ cbind(ii,jj) ] <- value
379 :     if(!is.integer(nc <- ncol(i)))
380 :     stop("'i' has no integer column number",
381 :     " should never happen; please report")
382 :     if(is.logical(i)) {
383 :     i <- c(i) # drop "matrix"
384 :     return( callNextMethod() )
385 :     } else if(!is.numeric(i) || nc != 2)
386 :     stop("such indexing must be by logical or 2-column numeric matrix")
387 :     m <- nrow(i)
388 :     mod.x <- .type.kind[.M.kind(x)]
389 :     if(length(value) > 0 && m %% length(value) != 0)
390 :     warning("number of items to replace is not a multiple of replacement length")
391 :     ## recycle:
392 :     value <- rep(value, length = m)
393 :     i1 <- i[,1]
394 :     i2 <- i[,2]
395 :     ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
396 :     for(k in seq_len(m))
397 :     x[i1[k], i2[k]] <- value[k]
398 :     x
399 :    
400 :     } else stop("nargs() = ", nA, " should never happen; please report.")
401 :     }
402 :     setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
403 :     value = "replValue"),
404 :     .M.repl.i.2col)
405 :    
406 :    
407 : maechler 1615 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
408 :     value = "Matrix"),
409 : maechler 1705 function (x, i, j, value) {
410 :     ### FIXME: *TEMPORARY* diagnostic output:
411 :     cat("<Matrix1>[i,j] <- <Matrix1>:\n<Matrix1> = x :")
412 :     str(x)
413 :     cat("<Matrix2> = value :")
414 :     str(value)
415 :     cat("i :"); if(!missing(i)) str(i) else cat("<missing>\n")
416 :     cat("j :"); if(!missing(j)) str(j) else cat("<missing>\n")
417 :    
418 :     callGeneric(x=x, i=i, j=j, value = as.vector(value))
419 :     })
420 :     setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
421 :     value = "Matrix"),
422 : maechler 1615 function (x, i, j, value)
423 :     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
424 : maechler 1705
425 : maechler 1615 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
426 :     value = "matrix"),
427 :     function (x, i, j, value)
428 :     callGeneric(x=x, i=i, j=j, value = c(value)))
429 :    
430 : maechler 1189 ## (ANY,ANY,ANY) is used when no `real method' is implemented :
431 : maechler 871 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
432 :     value = "ANY"),
433 : maechler 1189 function (x, i, j, value) {
434 :     if(!is.atomic(value))
435 : maechler 1615 stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
436 :     class(value),class(x)))
437 : maechler 1189 else stop("not-yet-implemented 'Matrix[<-' method")
438 :     })

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