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

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