SCM

SCM Repository

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

Annotation of /pkg/R/diagMatrix.R

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1708 - (view) (download)

1 : maechler 1617 #### All methods for "diagonalMatrix" and its subclasses,
2 :     #### currently "ddiMatrix", "ldiMatrix"
3 :    
4 : maechler 1109 ## Purpose: Constructor of diagonal matrices -- ~= diag() ,
5 :     ## but *not* diag() extractor!
6 :     Diagonal <- function(n, x = NULL)
7 :     {
8 : maechler 1575 ## Allow Diagonal(4) and Diagonal(x=1:5)
9 : maechler 1109 if(missing(n))
10 : maechler 1575 n <- length(x)
11 : maechler 1109 else {
12 : maechler 1575 stopifnot(length(n) == 1, n == as.integer(n), n >= 0)
13 :     n <- as.integer(n)
14 : maechler 1109 }
15 :    
16 : maechler 1654 if(missing(x)) ## unit diagonal matrix
17 : maechler 1575 new("ddiMatrix", Dim = c(n,n), diag = "U")
18 : maechler 1109 else {
19 : maechler 1575 stopifnot(length(x) == n)
20 :     if(is.logical(x))
21 :     cl <- "ldiMatrix"
22 :     else if(is.numeric(x)) {
23 :     cl <- "ddiMatrix"
24 :     x <- as.numeric(x)
25 :     }
26 :     else if(is.complex(x)) {
27 :     cl <- "zdiMatrix" # will not yet work
28 :     } else stop("'x' has invalid data type")
29 :     new(cl, Dim = c(n,n), diag = "N", x = x)
30 : maechler 1109 }
31 :     }
32 :    
33 : maechler 1617 ### This is modified from a post of Bert Gunter to R-help on 1 Sep 2005.
34 :     ### Bert's code built on a post by Andy Liaw who most probably was influenced
35 :     ### by earlier posts, notably one by Scott Chasalow on S-news, 16 Jan 2002
36 :     ### who posted his bdiag() function written in December 1995.
37 :    
38 :     bdiag <- function(...) {
39 :     if(nargs() == 0) return(new("dgCMatrix"))
40 :     ## else :
41 :     mlist <- if (nargs() == 1) as.list(...) else list(...)
42 :     dims <- sapply(mlist, dim)
43 :     ## make sure we had all matrices:
44 :     if(!(is.matrix(dims) && nrow(dims) == 2))
45 :     stop("some arguments are not matrices")
46 :     csdim <- rbind(rep.int(0:0, 2),
47 :     apply(sapply(mlist, dim), 1, cumsum))
48 :     ret <- new("dgTMatrix", Dim = as.integer(csdim[nrow(csdim),]))
49 :     add1 <- matrix(1:0, 2,2)
50 : maechler 1654 for(i in seq_along(mlist)) {
51 : maechler 1617 indx <- apply(csdim[i:(i+1),] + add1, 2, function(n) n[1]:n[2])
52 :     if(is.null(dim(indx))) ## non-square matrix
53 :     ret[indx[[1]],indx[[2]]] <- mlist[[i]]
54 :     else ## square matrix
55 :     ret[indx[,1],indx[,2]] <- mlist[[i]]
56 :     }
57 :     ## slightly debatable if we really should return Csparse.. :
58 :     as(ret, "CsparseMatrix")
59 :     }
60 :    
61 : maechler 1654 diag2T <- function(from) {
62 :     i <- if(from@diag == "U") integer(0) else seq_len(from@Dim[1]) - 1:1
63 :     new(paste(.M.kind(from), "tTMatrix", sep=''),
64 :     diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,
65 :     x = from@x, # <- ok for diag = "U" and "N" (!)
66 :     i = i, j = i)
67 :     }
68 : maechler 1109
69 : maechler 1654 setAs("diagonalMatrix", "triangularMatrix", diag2T)
70 :     setAs("diagonalMatrix", "sparseMatrix", diag2T)
71 :     ## is better than this:
72 :     ## setAs("diagonalMatrix", "sparseMatrix",
73 :     ## function(from)
74 :     ## as(from, if(is(from, "dMatrix")) "dgCMatrix" else "lgCMatrix"))
75 :     setAs("diagonalMatrix", "CsparseMatrix",
76 :     function(from) as(diag2T(from), "CsparseMatrix"))
77 :    
78 : maechler 1109 setAs("diagonalMatrix", "matrix",
79 :     function(from) {
80 :     n <- from@Dim[1]
81 :     diag(x = if(from@diag == "U") { if(is.numeric(from@x)) 1. else TRUE
82 :     } else from@x,
83 :     nrow = n, ncol = n)
84 :     })
85 :    
86 : maechler 1654 setAs("diagonalMatrix", "generalMatrix", # prefer sparse:
87 :     function(from) as(from, paste(.M.kind(from), "gCMatrix", sep='')))
88 : maechler 1174
89 : maechler 1655 .diag.x <- function(m) {
90 :     if(m@diag == "U")
91 :     rep.int(if(is.numeric(m@x)) 1. else TRUE,
92 :     m@Dim[1])
93 :     else m@x
94 :     }
95 :    
96 :     .diag.2N <- function(m) {
97 :     if(m@diag == "U") m@diag <- "N"
98 :     m
99 :     }
100 :    
101 : maechler 1654 ## given the above, the following 4 coercions should be all unneeded;
102 :     ## we prefer triangular to general:
103 : maechler 1295 setAs("ddiMatrix", "dgTMatrix",
104 :     function(from) {
105 : maechler 1654 .Deprecated("as(, \"sparseMatrix\")")
106 : maechler 1295 n <- from@Dim[1]
107 : maechler 1654 i <- seq_len(n) - 1:1
108 : maechler 1655 new("dgTMatrix", i = i, j = i, x = .diag.x(from),
109 : maechler 1295 Dim = c(n,n), Dimnames = from@Dimnames) })
110 :    
111 :     setAs("ddiMatrix", "dgCMatrix",
112 : maechler 1655 function(from) as(as(from, "sparseMatrix"), "dgCMatrix"))
113 : maechler 1295
114 :     setAs("ldiMatrix", "lgTMatrix",
115 :     function(from) {
116 : maechler 1654 .Deprecated("as(, \"sparseMatrix\")")
117 : maechler 1295 n <- from@Dim[1]
118 : maechler 1575 if(from@diag == "U") { # unit-diagonal
119 :     x <- rep.int(TRUE, n)
120 : maechler 1654 i <- seq_len(n) - 1:1
121 : maechler 1575 } else { # "normal"
122 :     nz <- nz.NA(from@x, na. = TRUE)
123 :     x <- from@x[nz]
124 :     i <- which(nz) - 1:1
125 :     }
126 :     new("lgTMatrix", i = i, j = i, x = x,
127 : maechler 1295 Dim = c(n,n), Dimnames = from@Dimnames) })
128 :    
129 :     setAs("ldiMatrix", "lgCMatrix",
130 :     function(from) as(as(from, "lgTMatrix"), "lgCMatrix"))
131 :    
132 :    
133 : maechler 1447 if(FALSE) # now have faster "ddense" -> "dge"
134 : maechler 1174 setAs("ddiMatrix", "dgeMatrix",
135 :     function(from) as(as(from, "matrix"), "dgeMatrix"))
136 :    
137 : maechler 1109 setAs("matrix", "diagonalMatrix",
138 :     function(from) {
139 : maechler 1295 d <- dim(from)
140 : maechler 1109 if(d[1] != (n <- d[2])) stop("non-square matrix")
141 :     if(any(from[row(from) != col(from)] != 0))
142 :     stop("has non-zero off-diagonal entries")
143 : maechler 1295 x <- diag(from)
144 :     if(is.logical(x)) {
145 :     cl <- "ldiMatrix"
146 :     uni <- all(x)
147 :     } else {
148 :     cl <- "ddiMatrix"
149 :     uni <- all(x == 1)
150 :     storage.mode(x) <- "double"
151 : maechler 1575 } ## TODO: complex
152 : maechler 1295 new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
153 :     x = if(uni) x[FALSE] else x)
154 : maechler 1109 })
155 :    
156 :     ## ``generic'' coercion to diagonalMatrix : build on isDiagonal() and diag()
157 :     setAs("Matrix", "diagonalMatrix",
158 :     function(from) {
159 :     d <- dim(from)
160 :     if(d[1] != (n <- d[2])) stop("non-square matrix")
161 :     if(!isDiagonal(from)) stop("matrix is not diagonal")
162 :     ## else:
163 :     x <- diag(from)
164 :     if(is.logical(x)) {
165 :     cl <- "ldiMatrix"
166 :     uni <- all(x)
167 :     } else {
168 :     cl <- "ddiMatrix"
169 :     uni <- all(x == 1)
170 :     storage.mode(x) <- "double"
171 :     }
172 :     new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
173 :     x = if(uni) x[FALSE] else x)
174 :     })
175 :    
176 : maechler 1708
177 :     setMethod("diag", signature(x = "diagonalMatrix"),
178 :     function(x = 1, nrow, ncol = n) .diag.x(x))
179 :    
180 : maechler 1617 ## When you assign to a diagonalMatrix, the result should be
181 : maechler 1708 ## diagonal or sparse ---
182 :     ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch
183 : maechler 1617 setReplaceMethod("[", signature(x = "diagonalMatrix",
184 :     i = "ANY", j = "ANY", value = "ANY"),
185 :     function(x, i, j, value) {
186 :     r <- callGeneric(x = as(x,"sparseMatrix"),
187 :     i=i, j=j, value=value)
188 :     if(isDiagonal(r)) as(r, "diagonalMatrix") else r
189 :     })
190 :    
191 :    
192 : maechler 1109 setMethod("t", signature(x = "diagonalMatrix"),
193 :     function(x) { x@Dimnames <- x@Dimnames[2:1] ; x })
194 :    
195 : maechler 1331 setMethod("isDiagonal", signature(object = "diagonalMatrix"),
196 :     function(object) TRUE)
197 :     setMethod("isTriangular", signature(object = "diagonalMatrix"),
198 :     function(object) TRUE)
199 : maechler 1109 setMethod("isSymmetric", signature(object = "diagonalMatrix"),
200 :     function(object) TRUE)
201 :    
202 : maechler 1654 setMethod("chol", signature(x = "ddiMatrix"),# pivot = "ANY"
203 :     function(x, pivot) {
204 :     if(any(x@x < 0)) stop("chol() is undefined for diagonal matrix with negative entries")
205 :     x@x <- sqrt(x@x)
206 :     x
207 :     })
208 :     ## chol(L) is L for logical diagonal:
209 :     setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot) x)
210 :    
211 : maechler 1109 setMethod("!", "ldiMatrix", function(e1) {
212 :     if(e1@diag == "N")
213 :     e1@x <- !e1@x
214 :     else { ## "U"
215 :     e1@diag <- "N"
216 :     e1@x <- rep.int(FALSE, e1@Dim[1])
217 :     }
218 :     x
219 :     })
220 :    
221 :     ## Basic Matrix Multiplication {many more to add}
222 : maechler 1654 ## ---------------------
223 :     ## Note that "ldi" logical are treated as numeric
224 : maechler 1109 diagdiagprod <- function(x, y) {
225 :     if(any(dim(x) != dim(y))) stop("non-matching dimensions")
226 :     if(x@diag != "U") {
227 : maechler 1654 if(y@diag != "U") {
228 :     nx <- x@x * y@x
229 :     if(is.numeric(nx) && !is.numeric(x@x))
230 :     x <- as(x, "dMatrix")
231 :     x@x <- as.numeric(nx)
232 :     }
233 :     return(x)
234 : maechler 1109 } else ## x is unit diagonal
235 :     return(y)
236 :     }
237 :    
238 : maechler 1654 setMethod("%*%", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
239 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
240 :    
241 : maechler 1654 formals(diagdiagprod) <- alist(x=, y=x)
242 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
243 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
244 : maechler 1654 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
245 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
246 : maechler 1654 setMethod("crossprod", signature(x = "diagonalMatrix", y = "missing"),
247 :     diagdiagprod, valueClass = "ddiMatrix")
248 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "missing"),
249 :     diagdiagprod, valueClass = "ddiMatrix")
250 : maechler 1109
251 :    
252 :     diagmatprod <- function(x, y) {
253 :     dx <- dim(x)
254 :     dy <- dim(y)
255 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
256 :     n <- dx[1]
257 :     as(if(x@diag == "U") y else x@x * y, "Matrix")
258 :     }
259 :    
260 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),
261 : maechler 1654 diagmatprod)
262 : maechler 1109 formals(diagmatprod) <- alist(x=, y=NULL)
263 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),
264 : maechler 1654 diagmatprod)
265 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "matrix"),
266 :     diagmatprod)
267 : maechler 1109
268 :     diagdgeprod <- function(x, y) {
269 :     dx <- dim(x)
270 :     dy <- dim(y)
271 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
272 :     if(x@diag != "U")
273 :     y@x <- x@x * y@x
274 :     y
275 :     }
276 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "dgeMatrix"),
277 :     diagdgeprod, valueClass = "dgeMatrix")
278 :     formals(diagdgeprod) <- alist(x=, y=NULL)
279 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),
280 :     diagdgeprod, valueClass = "dgeMatrix")
281 :    
282 :     setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),
283 :     function(x, y) {
284 : maechler 1635 dx <- dim(x)
285 :     dy <- dim(y)
286 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
287 :     as(if(y@diag == "U") x else x * rep(y@x, each = dx[1]), "Matrix")
288 :     })
289 : maechler 1109
290 :     setMethod("%*%", signature(x = "dgeMatrix", y = "diagonalMatrix"),
291 :     function(x, y) {
292 : maechler 1635 dx <- dim(x)
293 :     dy <- dim(y)
294 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
295 :     if(y@diag == "N")
296 :     x@x <- x@x * rep(y@x, each = dx[1])
297 :     x
298 :     })
299 : maechler 1109
300 : maechler 1295 ## crossprod {more of these}
301 : maechler 1109
302 : maechler 1295 ## tcrossprod --- all are not yet there: do the dense ones here:
303 : maechler 1109
304 : maechler 1295 ## FIXME:
305 :     ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),
306 :     ## function(x, y = NULL) {
307 :     ## })
308 : maechler 1109
309 : maechler 1295 ## setMethod("tcrossprod", signature(x = "denseMatrix", y = "diagonalMatrix"),
310 :     ## function(x, y = NULL) {
311 :     ## })
312 : maechler 1109
313 : maechler 1295
314 : maechler 1654 ### ---------------- diagonal o sparse -----------------------------
315 : maechler 1295
316 : maechler 1655
317 :     ## Use function for several signatures, in order to evade
318 :     ## ambiguous dispatch for "ddi", since there's also Arith(ddense., ddense.)
319 :     diagOdiag <- function(e1,e2) { # result should also be diagonal
320 :     r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"
321 :     if(is.numeric(r)) {
322 :     if(is.numeric(e2@x)) {
323 :     e2@x <- r; return(.diag.2N(e2)) }
324 :     if(!is.numeric(e1@x))
325 :     ## e.g. e1, e2 are logical;
326 :     e1 <- as(e1, "dMatrix")
327 :     }
328 :     else if(is.logical(r))
329 :     e1 <- as(e1, "lMatrix")
330 :     else stop("intermediate 'r' is of type", typeof(r))
331 :     e1@x <- r
332 :     .diag.2N(e1)
333 :     }
334 :    
335 :     setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),
336 :     diagOdiag)
337 :     ## These two are just for method disambiguation:
338 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "diagonalMatrix"),
339 :     diagOdiag)
340 :     setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ddiMatrix"),
341 :     diagOdiag)
342 :    
343 :     ## For almost everything else, diag* shall be treated "as sparse" :
344 : maechler 1295 ## These are cheap implementations via coercion
345 :    
346 : maechler 1655 ## for disambiguation
347 : maechler 1654 setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "sparseMatrix"),
348 :     function(e1,e2) callGeneric(as(e1, "sparseMatrix"), e2))
349 :     setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "diagonalMatrix"),
350 :     function(e1,e2) callGeneric(e1, as(e2, "sparseMatrix")))
351 : maechler 1655 ## in general:
352 :     setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ANY"),
353 :     function(e1,e2) callGeneric(as(e1,"sparseMatrix"), e2))
354 :     setMethod("Ops", signature(e1 = "ANY", e2 = "diagonalMatrix"),
355 :     function(e1,e2) callGeneric(e1, as(e2,"sparseMatrix")))
356 : maechler 1654
357 : maechler 1655
358 :    
359 : maechler 1295 ## FIXME?: In theory, this can be done *FASTER*, in some cases, via tapply1()
360 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),
361 :     function(x, y) as(x, "sparseMatrix") %*% y)
362 : maechler 1682 ## NB: The previous is *not* triggering for "ddi" o "dgC" (= distance 3)
363 :     ## since there's a "ddense" o "Csparse" at dist. 2 => triggers first.
364 :     ## ==> do this:
365 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
366 :     function(x, y) as(x, "CsparseMatrix") %*% y)
367 :     ## NB: this is *not* needed for Tsparse & Rsparse
368 :     ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*
369 :     ## do indeed work by going throug sparse (and *not* ddense)!
370 : maechler 1295
371 :     setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),
372 :     function(x, y) x %*% as(y, "sparseMatrix"))
373 :    
374 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
375 :     function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })
376 :    
377 :     setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
378 :     function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })
379 :    
380 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
381 :     function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })
382 :    
383 :     setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
384 :     function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })
385 :    
386 :    
387 : maechler 1109 ## similar to prTriang() in ./Auxiliaries.R :
388 :     prDiag <-
389 :     function(x, digits = getOption("digits"), justify = "none", right = TRUE)
390 :     {
391 :     cf <- array(".", dim = x@Dim, dimnames = x@Dimnames)
392 :     cf[row(cf) == col(cf)] <-
393 :     sapply(diag(x), format, digits = digits, justify = justify)
394 :     print(cf, quote = FALSE, right = right)
395 :     invisible(x)
396 :     }
397 :    
398 :     setMethod("show", signature(object = "diagonalMatrix"),
399 : maechler 1592 function(object) {
400 :     d <- dim(object)
401 :     cl <- class(object)
402 :     cat(sprintf('%d x %d diagonal matrix of class "%s"\n',
403 :     d[1], d[2], cl))
404 :     prDiag(object)
405 :     })

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