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 2144 - (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 2128 lx <- length(x)
20 :     stopifnot(lx == 1 || lx == n) # but keep 'x' short for now
21 : maechler 1575 if(is.logical(x))
22 :     cl <- "ldiMatrix"
23 :     else if(is.numeric(x)) {
24 :     cl <- "ddiMatrix"
25 :     x <- as.numeric(x)
26 :     }
27 :     else if(is.complex(x)) {
28 :     cl <- "zdiMatrix" # will not yet work
29 :     } else stop("'x' has invalid data type")
30 : maechler 2128 new(cl, Dim = c(n,n), diag = "N",
31 :     x = if(lx == 1) rep.int(x,n) else x)
32 : maechler 1109 }
33 :     }
34 :    
35 : maechler 2144 ## Pkg 'spdep' had (relatively slow) versions of this as_dsCMatrix_I()
36 :     .symDiagonal <- function(n, x = rep.int(1,n), uplo = "U") {
37 :     stopifnot(n == (n. <- as.integer(n)), (n <- n.) >= 0)
38 :     if((lx <- length(x)) == 1) x <- rep.int(x, n)
39 :     else if(lx != n) stop("length(x) must be 1 or n")
40 :     cls <-
41 :     if(is.double(x)) "dsCMatrix"
42 :     else if(is.logical(x)) "lsCMatrix"
43 :     else { ## for now
44 :     storage.mode(x) <- "double"
45 :     "dsCMatrix"
46 :     }
47 :     new(cls, Dim = c(n,n), x = x, uplo = uplo,
48 :     i = if(n) 0:(n - 1L) else integer(0), p = 0:n)
49 :     }
50 :    
51 : maechler 1617 ### This is modified from a post of Bert Gunter to R-help on 1 Sep 2005.
52 :     ### Bert's code built on a post by Andy Liaw who most probably was influenced
53 :     ### by earlier posts, notably one by Scott Chasalow on S-news, 16 Jan 2002
54 :     ### who posted his bdiag() function written in December 1995.
55 :    
56 :     bdiag <- function(...) {
57 :     if(nargs() == 0) return(new("dgCMatrix"))
58 :     ## else :
59 :     mlist <- if (nargs() == 1) as.list(...) else list(...)
60 :     dims <- sapply(mlist, dim)
61 :     ## make sure we had all matrices:
62 :     if(!(is.matrix(dims) && nrow(dims) == 2))
63 :     stop("some arguments are not matrices")
64 : maechler 1845 csdim <- rbind(rep.int(0L, 2),
65 : maechler 1617 apply(sapply(mlist, dim), 1, cumsum))
66 :     ret <- new("dgTMatrix", Dim = as.integer(csdim[nrow(csdim),]))
67 :     add1 <- matrix(1:0, 2,2)
68 : maechler 1654 for(i in seq_along(mlist)) {
69 : maechler 1617 indx <- apply(csdim[i:(i+1),] + add1, 2, function(n) n[1]:n[2])
70 :     if(is.null(dim(indx))) ## non-square matrix
71 :     ret[indx[[1]],indx[[2]]] <- mlist[[i]]
72 :     else ## square matrix
73 :     ret[indx[,1],indx[,2]] <- mlist[[i]]
74 :     }
75 :     ## slightly debatable if we really should return Csparse.. :
76 :     as(ret, "CsparseMatrix")
77 :     }
78 :    
79 : maechler 2128
80 : maechler 2136 .diag2tT <- function(from, uplo = "U", kind = .M.kind(from)) {
81 :     ## to triangular Tsparse
82 : maechler 1845 i <- if(from@diag == "U") integer(0) else seq_len(from@Dim[1]) - 1L
83 : maechler 2136 new(paste(kind, "tTMatrix", sep=''),
84 : maechler 1654 diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,
85 : maechler 2128 uplo = uplo,
86 : maechler 1654 x = from@x, # <- ok for diag = "U" and "N" (!)
87 :     i = i, j = i)
88 :     }
89 : maechler 1109
90 : maechler 2136 .diag2sT <- function(from, uplo = "U", kind = .M.kind(from)) {
91 :     ## to symmetric Tsparse
92 : maechler 2128 n <- from@Dim[1]
93 :     i <- seq_len(n) - 1L
94 :     new(paste(kind, "sTMatrix", sep=''),
95 : maechler 1845 Dim = from@Dim, Dimnames = from@Dimnames,
96 : maechler 2128 i = i, j = i, uplo = uplo,
97 :     x = if(from@diag == "N") from@x else ## "U"-diag
98 :     rep.int(switch(kind,
99 :     "d" = 1.,
100 :     "l" =,
101 :     "n" = TRUE,
102 :     ## otherwise
103 :     stop("'", kind,"' kind not yet implemented")), n))
104 : maechler 1845 }
105 :    
106 : maechler 2128 ## diagonal -> triangular, upper / lower depending on "partner":
107 : maechler 2144 diag2tT.u <- function(d, x, kind = .M.kind(d))
108 :     .diag2tT(d, uplo = if(is(x,"triangularMatrix")) x@uplo else "U", kind)
109 : maechler 2128
110 : maechler 2136
111 :     ## In order to evade method dispatch ambiguity warnings,
112 :     ## and because we can save a .M.kind() call, we use this explicit
113 :     ## "hack" instead of signature x = "diagonalMatrix" :
114 :     ##
115 :     ## ddi*:
116 :     diag2tT <- function(from) .diag2tT(from, "U", "d")
117 :     setAs("ddiMatrix", "triangularMatrix", diag2tT)
118 :     setAs("ddiMatrix", "sparseMatrix", diag2tT)
119 : maechler 1805 ## needed too (otherwise <dense> -> Tsparse is taken):
120 : maechler 2136 setAs("ddiMatrix", "TsparseMatrix", diag2tT)
121 :     setAs("ddiMatrix", "CsparseMatrix",
122 :     function(from) as(.diag2tT(from, "U", "d"), "CsparseMatrix"))
123 :     setAs("ddiMatrix", "symmetricMatrix",
124 :     function(from) .diag2sT(from, "U", "d"))
125 :     ##
126 :     ## ldi*:
127 :     diag2tT <- function(from) .diag2tT(from, "U", "l")
128 :     setAs("ldiMatrix", "triangularMatrix", diag2tT)
129 :     setAs("ldiMatrix", "sparseMatrix", diag2tT)
130 :     ## needed too (otherwise <dense> -> Tsparse is taken):
131 :     setAs("ldiMatrix", "TsparseMatrix", diag2tT)
132 :     setAs("ldiMatrix", "CsparseMatrix",
133 :     function(from) as(.diag2tT(from, "U", "l"), "CsparseMatrix"))
134 :     setAs("ldiMatrix", "symmetricMatrix",
135 :     function(from) .diag2sT(from, "U", "l"))
136 : maechler 1654
137 : maechler 1845
138 : maechler 2128 setAs("diagonalMatrix", "nMatrix",
139 :     function(from) {
140 :     n <- from@Dim[1]
141 :     i <- if(from@diag == "U") integer(0) else which(isN0(from@x)) - 1L
142 :     new("ntTMatrix", i = i, j = i, diag = from@diag,
143 :     Dim = from@Dim, Dimnames = from@Dimnames)
144 :     })
145 :    
146 :    
147 : maechler 1109 setAs("diagonalMatrix", "matrix",
148 :     function(from) {
149 :     n <- from@Dim[1]
150 :     diag(x = if(from@diag == "U") { if(is.numeric(from@x)) 1. else TRUE
151 :     } else from@x,
152 :     nrow = n, ncol = n)
153 :     })
154 :    
155 : maechler 2098 setMethod("as.vector", signature(x = "diagonalMatrix", mode="missing"),
156 :     function(x, mode) {
157 :     n <- x@Dim[1]
158 :     mod <- mode(x@x)
159 :     r <- vector(mod, length = n^2)
160 :     if(n)
161 :     r[1 + 0:(n - 1) * (n + 1)] <-
162 :     if(x@diag == "U")
163 :     switch(mod, "integer"= 1L,
164 :     "numeric"= 1, "logical"= TRUE)
165 :     else x@x
166 :     r
167 :     })
168 :    
169 : maechler 1654 setAs("diagonalMatrix", "generalMatrix", # prefer sparse:
170 : maechler 2128 function(from) as(as(from, "CsparseMatrix"), "generalMatrix"))
171 : maechler 1174
172 : maechler 1655 .diag.x <- function(m) {
173 :     if(m@diag == "U")
174 : maechler 2136 rep.int(if(is.numeric(m@x)) 1. else TRUE, m@Dim[1])
175 : maechler 1655 else m@x
176 :     }
177 :    
178 :     .diag.2N <- function(m) {
179 :     if(m@diag == "U") m@diag <- "N"
180 :     m
181 :     }
182 :    
183 : maechler 2128 if(FALSE) {
184 : maechler 1654 ## given the above, the following 4 coercions should be all unneeded;
185 :     ## we prefer triangular to general:
186 : maechler 1295 setAs("ddiMatrix", "dgTMatrix",
187 :     function(from) {
188 : maechler 1654 .Deprecated("as(, \"sparseMatrix\")")
189 : maechler 1295 n <- from@Dim[1]
190 : maechler 1845 i <- seq_len(n) - 1L
191 : maechler 1655 new("dgTMatrix", i = i, j = i, x = .diag.x(from),
192 : maechler 1295 Dim = c(n,n), Dimnames = from@Dimnames) })
193 :    
194 :     setAs("ddiMatrix", "dgCMatrix",
195 : maechler 1655 function(from) as(as(from, "sparseMatrix"), "dgCMatrix"))
196 : maechler 1295
197 :     setAs("ldiMatrix", "lgTMatrix",
198 :     function(from) {
199 : maechler 1654 .Deprecated("as(, \"sparseMatrix\")")
200 : maechler 1295 n <- from@Dim[1]
201 : maechler 1575 if(from@diag == "U") { # unit-diagonal
202 :     x <- rep.int(TRUE, n)
203 : maechler 1845 i <- seq_len(n) - 1L
204 : maechler 1575 } else { # "normal"
205 :     nz <- nz.NA(from@x, na. = TRUE)
206 :     x <- from@x[nz]
207 : maechler 1845 i <- which(nz) - 1L
208 : maechler 1575 }
209 :     new("lgTMatrix", i = i, j = i, x = x,
210 : maechler 1295 Dim = c(n,n), Dimnames = from@Dimnames) })
211 :    
212 :     setAs("ldiMatrix", "lgCMatrix",
213 :     function(from) as(as(from, "lgTMatrix"), "lgCMatrix"))
214 : maechler 2128 }
215 : maechler 1295
216 :    
217 : maechler 1447 if(FALSE) # now have faster "ddense" -> "dge"
218 : maechler 1174 setAs("ddiMatrix", "dgeMatrix",
219 :     function(from) as(as(from, "matrix"), "dgeMatrix"))
220 :    
221 : maechler 1109 setAs("matrix", "diagonalMatrix",
222 :     function(from) {
223 : maechler 1295 d <- dim(from)
224 : maechler 1109 if(d[1] != (n <- d[2])) stop("non-square matrix")
225 :     if(any(from[row(from) != col(from)] != 0))
226 :     stop("has non-zero off-diagonal entries")
227 : maechler 1295 x <- diag(from)
228 :     if(is.logical(x)) {
229 :     cl <- "ldiMatrix"
230 :     uni <- all(x)
231 :     } else {
232 :     cl <- "ddiMatrix"
233 :     uni <- all(x == 1)
234 :     storage.mode(x) <- "double"
235 : maechler 1575 } ## TODO: complex
236 : maechler 1295 new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
237 :     x = if(uni) x[FALSE] else x)
238 : maechler 1109 })
239 :    
240 :     ## ``generic'' coercion to diagonalMatrix : build on isDiagonal() and diag()
241 :     setAs("Matrix", "diagonalMatrix",
242 :     function(from) {
243 :     d <- dim(from)
244 :     if(d[1] != (n <- d[2])) stop("non-square matrix")
245 :     if(!isDiagonal(from)) stop("matrix is not diagonal")
246 :     ## else:
247 :     x <- diag(from)
248 :     if(is.logical(x)) {
249 :     cl <- "ldiMatrix"
250 :     uni <- all(x)
251 :     } else {
252 :     cl <- "ddiMatrix"
253 :     uni <- all(x == 1)
254 :     storage.mode(x) <- "double"
255 :     }
256 :     new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
257 :     x = if(uni) x[FALSE] else x)
258 :     })
259 :    
260 : maechler 1708
261 : maechler 2136 ## In order to evade method dispatch ambiguity warnings,
262 :     ## we use this hack instead of signature x = "diagonalMatrix" :
263 :     diCls <- names(getClass("diagonalMatrix")@subclasses)
264 :     for(cls in diCls) {
265 :     setMethod("diag", signature(x = cls),
266 :     function(x = 1, nrow, ncol) .diag.x(x))
267 :     }
268 : maechler 1708
269 : maechler 1799
270 : maechler 2098 subDiag <- function(x, i, j, ..., drop) {
271 : maechler 1799 x <- as(x, "sparseMatrix")
272 :     x <- if(missing(i))
273 :     x[, j, drop=drop]
274 :     else if(missing(j))
275 :     x[i, , drop=drop]
276 :     else
277 :     x[i,j, drop=drop]
278 : maechler 2120 if(isS4(x) && isDiagonal(x)) as(x, "diagonalMatrix") else x
279 : maechler 1799 }
280 :    
281 :     setMethod("[", signature(x = "diagonalMatrix", i = "index",
282 :     j = "index", drop = "logical"), subDiag)
283 :     setMethod("[", signature(x = "diagonalMatrix", i = "index",
284 :     j = "missing", drop = "logical"),
285 : maechler 2098 function(x, i, j, ..., drop) subDiag(x, i=i, drop=drop))
286 : maechler 1799 setMethod("[", signature(x = "diagonalMatrix", i = "missing",
287 :     j = "index", drop = "logical"),
288 : maechler 2098 function(x, i, j, ..., drop) subDiag(x, j=j, drop=drop))
289 : maechler 1799
290 : maechler 1617 ## When you assign to a diagonalMatrix, the result should be
291 : maechler 1708 ## diagonal or sparse ---
292 :     ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch
293 : maechler 2098 ## Only(?) current bug: x[i] <- value is wrong when i is *vector*
294 :     replDiag <- function(x, i, j, ..., value) {
295 : maechler 1710 x <- as(x, "sparseMatrix")
296 :     if(missing(i))
297 :     x[, j] <- value
298 : maechler 2098 else if(missing(j)) { ## x[i , ] <- v *OR* x[i] <- v
299 :     na <- nargs()
300 :     ## message("diagnosing replDiag() -- nargs()= ", na)
301 :     if(na == 4)
302 :     x[i, ] <- value
303 :     else if(na == 3)
304 :     x[i] <- value
305 :     else stop("Internal bug: nargs()=",na,"; please report")
306 :     } else
307 : maechler 1710 x[i,j] <- value
308 :     if(isDiagonal(x)) as(x, "diagonalMatrix") else x
309 :     }
310 : maechler 1617
311 : maechler 1710 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
312 :     j = "index", value = "replValue"), replDiag)
313 : maechler 2098
314 : maechler 1710 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
315 :     j = "missing", value = "replValue"),
316 : maechler 2098 function(x,i,j, ..., value) {
317 :     ## message("before replDiag() -- nargs()= ", nargs())
318 :     if(nargs() == 3)
319 :     replDiag(x, i=i, value=value)
320 :     else ## nargs() == 4 :
321 :     replDiag(x, i=i, , value=value)
322 :     })
323 :    
324 : maechler 2096 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "matrix", # 2-col.matrix
325 :     j = "missing", value = "replValue"),
326 : maechler 2098 function(x,i,j, ..., value) {
327 : maechler 2096 if(ncol(i) == 2) {
328 :     if(all((ii <- i[,1]) == i[,2])) { # replace in diagonal only
329 :     x@x[ii] <- value
330 :     x
331 :     } else { ## no longer diagonal, but remain sparse:
332 :     x <- as(x, "sparseMatrix")
333 :     x[i] <- value
334 :     x
335 :     }
336 :     }
337 :     else { # behave as "base R": use as if vector
338 :     x <- as(x, "matrix")
339 :     x[i] <- value
340 :     Matrix(x)
341 :     }
342 :     })
343 :    
344 : maechler 1710 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",
345 :     j = "index", value = "replValue"),
346 : maechler 2098 function(x,i,j, ..., value) replDiag(x, j=j, value=value))
347 : maechler 1710
348 :    
349 : maechler 1109 setMethod("t", signature(x = "diagonalMatrix"),
350 :     function(x) { x@Dimnames <- x@Dimnames[2:1] ; x })
351 :    
352 : maechler 1331 setMethod("isDiagonal", signature(object = "diagonalMatrix"),
353 :     function(object) TRUE)
354 :     setMethod("isTriangular", signature(object = "diagonalMatrix"),
355 :     function(object) TRUE)
356 : maechler 1109 setMethod("isSymmetric", signature(object = "diagonalMatrix"),
357 : maechler 2112 function(object, ...) TRUE)
358 : maechler 1109
359 : maechler 2112 setMethod("symmpart", signature(x = "diagonalMatrix"), function(x) x)
360 :     setMethod("skewpart", signature(x = "diagonalMatrix"), setZero)
361 :    
362 : maechler 2133 setMethod("chol", signature(x = "ddiMatrix"),
363 :     function(x, pivot, ...) {
364 :     if(any(x@x < 0))
365 :     stop("chol() is undefined for diagonal matrix with negative entries")
366 : maechler 1654 x@x <- sqrt(x@x)
367 :     x
368 :     })
369 :     ## chol(L) is L for logical diagonal:
370 : maechler 2133 setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot, ...) x)
371 : maechler 1654
372 : maechler 1109 ## Basic Matrix Multiplication {many more to add}
373 : maechler 1654 ## ---------------------
374 :     ## Note that "ldi" logical are treated as numeric
375 : maechler 1109 diagdiagprod <- function(x, y) {
376 :     if(any(dim(x) != dim(y))) stop("non-matching dimensions")
377 :     if(x@diag != "U") {
378 : maechler 1654 if(y@diag != "U") {
379 :     nx <- x@x * y@x
380 :     if(is.numeric(nx) && !is.numeric(x@x))
381 :     x <- as(x, "dMatrix")
382 :     x@x <- as.numeric(nx)
383 :     }
384 :     return(x)
385 : maechler 1109 } else ## x is unit diagonal
386 :     return(y)
387 :     }
388 :    
389 : maechler 1654 setMethod("%*%", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
390 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
391 :    
392 : maechler 1654 formals(diagdiagprod) <- alist(x=, y=x)
393 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
394 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
395 : maechler 1654 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
396 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
397 : maechler 1654 setMethod("crossprod", signature(x = "diagonalMatrix", y = "missing"),
398 :     diagdiagprod, valueClass = "ddiMatrix")
399 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "missing"),
400 :     diagdiagprod, valueClass = "ddiMatrix")
401 : maechler 1109
402 :    
403 :     diagmatprod <- function(x, y) {
404 :     dx <- dim(x)
405 :     dy <- dim(y)
406 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
407 :     n <- dx[1]
408 :     as(if(x@diag == "U") y else x@x * y, "Matrix")
409 :     }
410 :    
411 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),
412 : maechler 1654 diagmatprod)
413 : maechler 1109 formals(diagmatprod) <- alist(x=, y=NULL)
414 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),
415 : maechler 1654 diagmatprod)
416 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "matrix"),
417 :     diagmatprod)
418 : maechler 1109
419 :     diagdgeprod <- function(x, y) {
420 :     dx <- dim(x)
421 :     dy <- dim(y)
422 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
423 :     if(x@diag != "U")
424 :     y@x <- x@x * y@x
425 :     y
426 :     }
427 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "dgeMatrix"),
428 :     diagdgeprod, valueClass = "dgeMatrix")
429 :     formals(diagdgeprod) <- alist(x=, y=NULL)
430 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),
431 :     diagdgeprod, valueClass = "dgeMatrix")
432 :    
433 :     setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),
434 :     function(x, y) {
435 : maechler 1635 dx <- dim(x)
436 :     dy <- dim(y)
437 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
438 :     as(if(y@diag == "U") x else x * rep(y@x, each = dx[1]), "Matrix")
439 :     })
440 : maechler 1109
441 :     setMethod("%*%", signature(x = "dgeMatrix", y = "diagonalMatrix"),
442 :     function(x, y) {
443 : maechler 1635 dx <- dim(x)
444 :     dy <- dim(y)
445 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
446 :     if(y@diag == "N")
447 :     x@x <- x@x * rep(y@x, each = dx[1])
448 :     x
449 :     })
450 : maechler 1109
451 : maechler 1295 ## crossprod {more of these}
452 : maechler 1109
453 : maechler 1295 ## tcrossprod --- all are not yet there: do the dense ones here:
454 : maechler 1109
455 : maechler 1295 ## FIXME:
456 :     ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),
457 :     ## function(x, y = NULL) {
458 :     ## })
459 : maechler 1109
460 : maechler 1295 ## setMethod("tcrossprod", signature(x = "denseMatrix", y = "diagonalMatrix"),
461 :     ## function(x, y = NULL) {
462 :     ## })
463 : maechler 1109
464 : maechler 1799 setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
465 : maechler 2123 function(x, y = NULL) crossprod(as(x, "sparseMatrix"), y))
466 : maechler 1295
467 : maechler 1799 setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
468 : maechler 2123 function(x, y = NULL) crossprod(x, as(y, "sparseMatrix")))
469 : maechler 1799
470 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
471 : maechler 2123 function(x, y = NULL) tcrossprod(as(x, "sparseMatrix"), y))
472 : maechler 1799
473 :     setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
474 : maechler 2123 function(x, y = NULL) tcrossprod(x, as(y, "sparseMatrix")))
475 : maechler 1799
476 :    
477 :     ## FIXME?: In theory, this can be done *FASTER*, in some cases, via tapply1()
478 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),
479 :     function(x, y) as(x, "sparseMatrix") %*% y)
480 :     ## NB: The previous is *not* triggering for "ddi" o "dgC" (= distance 3)
481 :     ## since there's a "ddense" o "Csparse" at dist. 2 => triggers first.
482 :     ## ==> do this:
483 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
484 :     function(x, y) as(x, "CsparseMatrix") %*% y)
485 :     setMethod("%*%", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
486 :     function(x, y) x %*% as(y, "CsparseMatrix"))
487 :     ## NB: this is *not* needed for Tsparse & Rsparse
488 :     ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*
489 :     ## do indeed work by going through sparse (and *not* ddense)!
490 :    
491 :     setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),
492 :     function(x, y) x %*% as(y, "sparseMatrix"))
493 :    
494 :    
495 :     setMethod("solve", signature(a = "diagonalMatrix", b = "missing"),
496 :     function(a, b, ...) {
497 :     a@x <- 1/ a@x
498 :     a@Dimnames <- a@Dimnames[2:1]
499 :     a
500 :     })
501 :    
502 :     solveDiag <- function(a, b, ...) {
503 :     if((n <- a@Dim[1]) != nrow(b))
504 :     stop("incompatible matrix dimensions")
505 :     ## trivially invert a 'in place' and multiply:
506 :     a@x <- 1/ a@x
507 :     a@Dimnames <- a@Dimnames[2:1]
508 :     a %*% b
509 :     }
510 :     setMethod("solve", signature(a = "diagonalMatrix", b = "matrix"),
511 :     solveDiag)
512 :     setMethod("solve", signature(a = "diagonalMatrix", b = "Matrix"),
513 :     solveDiag)
514 :    
515 : maechler 2106 ## Schur() ---> ./eigen.R
516 : maechler 1799
517 :    
518 :    
519 : maechler 1654 ### ---------------- diagonal o sparse -----------------------------
520 : maechler 1295
521 : maechler 1655
522 :     ## Use function for several signatures, in order to evade
523 :     ## ambiguous dispatch for "ddi", since there's also Arith(ddense., ddense.)
524 :     diagOdiag <- function(e1,e2) { # result should also be diagonal
525 :     r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"
526 :     if(is.numeric(r)) {
527 :     if(is.numeric(e2@x)) {
528 :     e2@x <- r; return(.diag.2N(e2)) }
529 :     if(!is.numeric(e1@x))
530 :     ## e.g. e1, e2 are logical;
531 :     e1 <- as(e1, "dMatrix")
532 :     }
533 :     else if(is.logical(r))
534 :     e1 <- as(e1, "lMatrix")
535 :     else stop("intermediate 'r' is of type", typeof(r))
536 :     e1@x <- r
537 :     .diag.2N(e1)
538 :     }
539 :    
540 :     setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),
541 :     diagOdiag)
542 :     ## These two are just for method disambiguation:
543 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "diagonalMatrix"),
544 :     diagOdiag)
545 :     setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "ddiMatrix"),
546 :     diagOdiag)
547 :    
548 : maechler 1845 ## FIXME: diagonal o triangular |--> triangular
549 :     ## ----- diagonal o symmetric |--> symmetric
550 :     ## {also when other is sparse: do these "here" --
551 :     ## before conversion to sparse, since that loses "diagonality"}
552 :    
553 : maechler 1655 ## For almost everything else, diag* shall be treated "as sparse" :
554 : maechler 1295 ## These are cheap implementations via coercion
555 :    
556 : maechler 2144 ## For disambiguation --- define this for "sparseMatrix" , then for "ANY";
557 :     ## and because we can save an .M.kind() call, we use this explicit
558 :     ## "hack" for all diagonalMatrix *subclasses* instead of just "diagonalMatrix" :
559 :     ##
560 :     ## ddi*:
561 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "sparseMatrix"),
562 :     function(e1,e2) callGeneric(diag2tT.u(e1,e2, "d"), e2))
563 :     setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ddiMatrix"),
564 :     function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "d")))
565 :     ## ldi*
566 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "sparseMatrix"),
567 :     function(e1,e2) callGeneric(diag2tT.u(e1,e2, "l"), e2))
568 :     setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ldiMatrix"),
569 :     function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "l")))
570 : maechler 1654
571 : maechler 2144 ## other = "numeric" : stay diagonal if possible
572 :     ## ddi*:
573 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "numeric"),
574 :     function(e1,e2) {
575 :     n <- e1@Dim[1]; nsq <- n*n
576 :     f0 <- callGeneric(0, e2)
577 :     if(all(is0(f0))) { # remain diagonal
578 :     if(e1@diag == "U" && (r <- callGeneric(1, e2)) != 1)
579 :     e1@diag <- "N"
580 :     else
581 :     r <- callGeneric(e1@x, e2)
582 :     e1@x <- if(length(e2) == nsq) r else rep(r, length.out = nsq)
583 :     return(e1)
584 :     }
585 :     callGeneric(diag2tT.u(e1,e2, "d"), e2)
586 :     })
587 : maechler 1655
588 : maechler 2144 setMethod("Ops", signature(e1 = "numeric", e2 = "ddiMatrix"),
589 :     function(e1,e2) {
590 :     n <- e2@Dim[1]; nsq <- n*n
591 :     f0 <- callGeneric(e1, 0)
592 :     if(all(is0(f0))) { # remain diagonal
593 :     if(e2@diag == "U" && (r <- callGeneric(e1, 1)) != 1)
594 :     e2@diag <- "N"
595 :     else
596 :     r <- callGeneric(e1, e2@x)
597 :     e2@x <- if(length(e1) == nsq) r else rep(r, length.out = nsq)
598 :     return(e2)
599 :     }
600 :     callGeneric(e1, diag2tT.u(e2,e1, "d"))
601 :     })
602 :     ## ldi*:
603 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "numeric"),
604 :     function(e1,e2) {
605 :     n <- e1@Dim[1]; nsq <- n*n
606 :     f0 <- callGeneric(FALSE, e2)
607 :     if(all(is0(f0))) { # remain diagonal
608 :     if(e1@diag == "U" && (r <- callGeneric(TRUE, e2)) != 1)
609 :     e1@diag <- "N"
610 :     else
611 :     r <- callGeneric(e1@x, e2)
612 :     e1@x <- if(length(e2) == nsq) r else rep(r, length.out = nsq)
613 :     return(e1)
614 :     }
615 :     callGeneric(diag2tT.u(e1,e2, "l"), e2)
616 :     })
617 : maechler 1655
618 : maechler 2144 setMethod("Ops", signature(e1 = "numeric", e2 = "ldiMatrix"),
619 :     function(e1,e2) {
620 :     n <- e2@Dim[1]; nsq <- n*n
621 :     f0 <- callGeneric(e1, FALSE)
622 :     if(all(is0(f0))) { # remain diagonal
623 :     if(e2@diag == "U" && (r <- callGeneric(e1, TRUE)) != 1)
624 :     e2@diag <- "N"
625 :     else
626 :     r <- callGeneric(e1, e2@x)
627 :     e2@x <- if(length(e1) == nsq) r else rep(r, length.out = nsq)
628 :     return(e2)
629 :     }
630 :     callGeneric(e1, diag2tT.u(e2,e1, "l"))
631 :     })
632 :    
633 :    
634 :    
635 :     ## Not {"sparseMatrix", "numeric} : {"denseMatrix", "matrix", ... }
636 :     ## ddi*:
637 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "ANY"),
638 :     function(e1,e2) callGeneric(diag2tT.u(e1,e2, "d"), e2))
639 :     setMethod("Ops", signature(e1 = "ANY", e2 = "ddiMatrix"),
640 :     function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "d")))
641 :     ## ldi*:
642 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "ANY"),
643 :     function(e1,e2) callGeneric(diag2tT.u(e1,e2, "l"), e2))
644 :     setMethod("Ops", signature(e1 = "ANY", e2 = "ldiMatrix"),
645 :     function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "l")))
646 :    
647 :    
648 :    
649 : maechler 1109 ## similar to prTriang() in ./Auxiliaries.R :
650 :     prDiag <-
651 :     function(x, digits = getOption("digits"), justify = "none", right = TRUE)
652 :     {
653 :     cf <- array(".", dim = x@Dim, dimnames = x@Dimnames)
654 :     cf[row(cf) == col(cf)] <-
655 :     sapply(diag(x), format, digits = digits, justify = justify)
656 :     print(cf, quote = FALSE, right = right)
657 :     invisible(x)
658 :     }
659 :    
660 :     setMethod("show", signature(object = "diagonalMatrix"),
661 : maechler 1592 function(object) {
662 :     d <- dim(object)
663 :     cl <- class(object)
664 :     cat(sprintf('%d x %d diagonal matrix of class "%s"\n',
665 :     d[1], d[2], cl))
666 :     prDiag(object)
667 :     })

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