SCM

SCM Repository

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

Annotation of /pkg/Matrix/R/diagMatrix.R

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1654 - (view) (download)
Original Path: pkg/R/diagMatrix.R

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 1654 ## given the above, the following 4 coercions should be all unneeded;
90 :     ## we prefer triangular to general:
91 : maechler 1295 setAs("ddiMatrix", "dgTMatrix",
92 :     function(from) {
93 : maechler 1654 .Deprecated("as(, \"sparseMatrix\")")
94 : maechler 1295 n <- from@Dim[1]
95 : maechler 1654 i <- seq_len(n) - 1:1
96 : maechler 1295 new("dgTMatrix", i = i, j = i,
97 :     x = if(from@diag == "U") rep(1,n) else from@x,
98 :     Dim = c(n,n), Dimnames = from@Dimnames) })
99 :    
100 :     setAs("ddiMatrix", "dgCMatrix",
101 :     function(from) as(as(from, "dgTMatrix"), "dgCMatrix"))
102 :    
103 :     setAs("ldiMatrix", "lgTMatrix",
104 :     function(from) {
105 : maechler 1654 .Deprecated("as(, \"sparseMatrix\")")
106 : maechler 1295 n <- from@Dim[1]
107 : maechler 1575 if(from@diag == "U") { # unit-diagonal
108 :     x <- rep.int(TRUE, n)
109 : maechler 1654 i <- seq_len(n) - 1:1
110 : maechler 1575 } else { # "normal"
111 :     nz <- nz.NA(from@x, na. = TRUE)
112 :     x <- from@x[nz]
113 :     i <- which(nz) - 1:1
114 :     }
115 :     new("lgTMatrix", i = i, j = i, x = x,
116 : maechler 1295 Dim = c(n,n), Dimnames = from@Dimnames) })
117 :    
118 :     setAs("ldiMatrix", "lgCMatrix",
119 :     function(from) as(as(from, "lgTMatrix"), "lgCMatrix"))
120 :    
121 :    
122 : maechler 1447 if(FALSE) # now have faster "ddense" -> "dge"
123 : maechler 1174 setAs("ddiMatrix", "dgeMatrix",
124 :     function(from) as(as(from, "matrix"), "dgeMatrix"))
125 :    
126 : maechler 1109 setAs("matrix", "diagonalMatrix",
127 :     function(from) {
128 : maechler 1295 d <- dim(from)
129 : maechler 1109 if(d[1] != (n <- d[2])) stop("non-square matrix")
130 :     if(any(from[row(from) != col(from)] != 0))
131 :     stop("has non-zero off-diagonal entries")
132 : maechler 1295 x <- diag(from)
133 :     if(is.logical(x)) {
134 :     cl <- "ldiMatrix"
135 :     uni <- all(x)
136 :     } else {
137 :     cl <- "ddiMatrix"
138 :     uni <- all(x == 1)
139 :     storage.mode(x) <- "double"
140 : maechler 1575 } ## TODO: complex
141 : maechler 1295 new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
142 :     x = if(uni) x[FALSE] else x)
143 : maechler 1109 })
144 :    
145 :     ## ``generic'' coercion to diagonalMatrix : build on isDiagonal() and diag()
146 :     setAs("Matrix", "diagonalMatrix",
147 :     function(from) {
148 :     d <- dim(from)
149 :     if(d[1] != (n <- d[2])) stop("non-square matrix")
150 :     if(!isDiagonal(from)) stop("matrix is not diagonal")
151 :     ## else:
152 :     x <- diag(from)
153 :     if(is.logical(x)) {
154 :     cl <- "ldiMatrix"
155 :     uni <- all(x)
156 :     } else {
157 :     cl <- "ddiMatrix"
158 :     uni <- all(x == 1)
159 :     storage.mode(x) <- "double"
160 :     }
161 :     new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
162 :     x = if(uni) x[FALSE] else x)
163 :     })
164 :    
165 : maechler 1617 ## When you assign to a diagonalMatrix, the result should be
166 :     ## diagonal or sparse
167 :     setReplaceMethod("[", signature(x = "diagonalMatrix",
168 :     i = "ANY", j = "ANY", value = "ANY"),
169 :     function(x, i, j, value) {
170 :     r <- callGeneric(x = as(x,"sparseMatrix"),
171 :     i=i, j=j, value=value)
172 :     if(isDiagonal(r)) as(r, "diagonalMatrix") else r
173 :     })
174 :    
175 :    
176 : maechler 1109 setMethod("t", signature(x = "diagonalMatrix"),
177 :     function(x) { x@Dimnames <- x@Dimnames[2:1] ; x })
178 :    
179 : maechler 1331 setMethod("isDiagonal", signature(object = "diagonalMatrix"),
180 :     function(object) TRUE)
181 :     setMethod("isTriangular", signature(object = "diagonalMatrix"),
182 :     function(object) TRUE)
183 : maechler 1109 setMethod("isSymmetric", signature(object = "diagonalMatrix"),
184 :     function(object) TRUE)
185 :    
186 : maechler 1654 setMethod("chol", signature(x = "ddiMatrix"),# pivot = "ANY"
187 :     function(x, pivot) {
188 :     if(any(x@x < 0)) stop("chol() is undefined for diagonal matrix with negative entries")
189 :     x@x <- sqrt(x@x)
190 :     x
191 :     })
192 :     ## chol(L) is L for logical diagonal:
193 :     setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot) x)
194 :    
195 :    
196 : maechler 1109 setMethod("diag", signature(x = "diagonalMatrix"),
197 :     function(x = 1, nrow, ncol = n) {
198 :     if(x@diag == "U")
199 :     rep.int(if(is.logical(x@x)) TRUE else 1, x@Dim[1])
200 :     else x@x
201 :     })
202 :    
203 :     setMethod("!", "ldiMatrix", function(e1) {
204 :     if(e1@diag == "N")
205 :     e1@x <- !e1@x
206 :     else { ## "U"
207 :     e1@diag <- "N"
208 :     e1@x <- rep.int(FALSE, e1@Dim[1])
209 :     }
210 :     x
211 :     })
212 :    
213 :     ## Basic Matrix Multiplication {many more to add}
214 : maechler 1654 ## ---------------------
215 :     ## Note that "ldi" logical are treated as numeric
216 : maechler 1109 diagdiagprod <- function(x, y) {
217 :     if(any(dim(x) != dim(y))) stop("non-matching dimensions")
218 :     if(x@diag != "U") {
219 : maechler 1654 if(y@diag != "U") {
220 :     nx <- x@x * y@x
221 :     if(is.numeric(nx) && !is.numeric(x@x))
222 :     x <- as(x, "dMatrix")
223 :     x@x <- as.numeric(nx)
224 :     }
225 :     return(x)
226 : maechler 1109 } else ## x is unit diagonal
227 :     return(y)
228 :     }
229 :    
230 : maechler 1654 setMethod("%*%", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
231 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
232 :    
233 : maechler 1654 formals(diagdiagprod) <- alist(x=, y=x)
234 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
235 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
236 : maechler 1654 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
237 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
238 : maechler 1654 setMethod("crossprod", signature(x = "diagonalMatrix", y = "missing"),
239 :     diagdiagprod, valueClass = "ddiMatrix")
240 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "missing"),
241 :     diagdiagprod, valueClass = "ddiMatrix")
242 : maechler 1109
243 :    
244 :     diagmatprod <- function(x, y) {
245 :     dx <- dim(x)
246 :     dy <- dim(y)
247 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
248 :     n <- dx[1]
249 :     as(if(x@diag == "U") y else x@x * y, "Matrix")
250 :     }
251 :    
252 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),
253 : maechler 1654 diagmatprod)
254 : maechler 1109 formals(diagmatprod) <- alist(x=, y=NULL)
255 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),
256 : maechler 1654 diagmatprod)
257 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "matrix"),
258 :     diagmatprod)
259 : maechler 1109
260 :     diagdgeprod <- function(x, y) {
261 :     dx <- dim(x)
262 :     dy <- dim(y)
263 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
264 :     if(x@diag != "U")
265 :     y@x <- x@x * y@x
266 :     y
267 :     }
268 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "dgeMatrix"),
269 :     diagdgeprod, valueClass = "dgeMatrix")
270 :     formals(diagdgeprod) <- alist(x=, y=NULL)
271 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),
272 :     diagdgeprod, valueClass = "dgeMatrix")
273 :    
274 :     setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),
275 :     function(x, y) {
276 : maechler 1635 dx <- dim(x)
277 :     dy <- dim(y)
278 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
279 :     as(if(y@diag == "U") x else x * rep(y@x, each = dx[1]), "Matrix")
280 :     })
281 : maechler 1109
282 :     setMethod("%*%", signature(x = "dgeMatrix", 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 :     if(y@diag == "N")
288 :     x@x <- x@x * rep(y@x, each = dx[1])
289 :     x
290 :     })
291 : maechler 1109
292 : maechler 1295 ## crossprod {more of these}
293 : maechler 1109
294 : maechler 1295 ## tcrossprod --- all are not yet there: do the dense ones here:
295 : maechler 1109
296 : maechler 1295 ## FIXME:
297 :     ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),
298 :     ## function(x, y = NULL) {
299 :     ## })
300 : maechler 1109
301 : maechler 1295 ## setMethod("tcrossprod", signature(x = "denseMatrix", y = "diagonalMatrix"),
302 :     ## function(x, y = NULL) {
303 :     ## })
304 : maechler 1109
305 : maechler 1295
306 : maechler 1654 ### ---------------- diagonal o sparse -----------------------------
307 : maechler 1295
308 :     ## These are cheap implementations via coercion
309 :    
310 : maechler 1654 setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "sparseMatrix"),
311 :     function(e1,e2) callGeneric(as(e1, "sparseMatrix"), e2))
312 :     setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "diagonalMatrix"),
313 :     function(e1,e2) callGeneric(e1, as(e2, "sparseMatrix")))
314 :    
315 : maechler 1295 ## FIXME?: In theory, this can be done *FASTER*, in some cases, via tapply1()
316 :    
317 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),
318 :     function(x, y) as(x, "sparseMatrix") %*% y)
319 :    
320 :     setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),
321 :     function(x, y) x %*% as(y, "sparseMatrix"))
322 :    
323 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
324 :     function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })
325 :    
326 :     setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
327 :     function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })
328 :    
329 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
330 :     function(x, y = NULL) { x <- as(x, "sparseMatrix"); callGeneric() })
331 :    
332 :     setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
333 :     function(x, y = NULL) { y <- as(y, "sparseMatrix"); callGeneric() })
334 :    
335 :    
336 :    
337 :    
338 : maechler 1109 ## similar to prTriang() in ./Auxiliaries.R :
339 :     prDiag <-
340 :     function(x, digits = getOption("digits"), justify = "none", right = TRUE)
341 :     {
342 :     cf <- array(".", dim = x@Dim, dimnames = x@Dimnames)
343 :     cf[row(cf) == col(cf)] <-
344 :     sapply(diag(x), format, digits = digits, justify = justify)
345 :     print(cf, quote = FALSE, right = right)
346 :     invisible(x)
347 :     }
348 :    
349 :     setMethod("show", signature(object = "diagonalMatrix"),
350 : maechler 1592 function(object) {
351 :     d <- dim(object)
352 :     cl <- class(object)
353 :     cat(sprintf('%d x %d diagonal matrix of class "%s"\n',
354 :     d[1], d[2], cl))
355 :     prDiag(object)
356 :     })

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