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 2175 - (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 : mmaechler 2175 ## diagonal -> sparse {triangular OR symmetric} (upper / lower) depending on "partner":
111 :     diag2Tsmart <- function(d, x, kind = .M.kind(d)) {
112 :     clx <- getClassDef(class(x))
113 :     if(extends(clx, "symmetricMatrix"))
114 :     .diag2sT(d, uplo = x@uplo, kind)
115 :     else
116 :     .diag2tT(d, uplo = if(extends(clx,"triangularMatrix")) x@uplo else "U", kind)
117 :     }
118 : maechler 2136
119 : mmaechler 2175
120 : maechler 2136 ## In order to evade method dispatch ambiguity warnings,
121 :     ## and because we can save a .M.kind() call, we use this explicit
122 :     ## "hack" instead of signature x = "diagonalMatrix" :
123 :     ##
124 :     ## ddi*:
125 :     diag2tT <- function(from) .diag2tT(from, "U", "d")
126 :     setAs("ddiMatrix", "triangularMatrix", diag2tT)
127 :     setAs("ddiMatrix", "sparseMatrix", diag2tT)
128 : maechler 1805 ## needed too (otherwise <dense> -> Tsparse is taken):
129 : maechler 2136 setAs("ddiMatrix", "TsparseMatrix", diag2tT)
130 :     setAs("ddiMatrix", "CsparseMatrix",
131 :     function(from) as(.diag2tT(from, "U", "d"), "CsparseMatrix"))
132 :     setAs("ddiMatrix", "symmetricMatrix",
133 :     function(from) .diag2sT(from, "U", "d"))
134 :     ##
135 :     ## ldi*:
136 :     diag2tT <- function(from) .diag2tT(from, "U", "l")
137 :     setAs("ldiMatrix", "triangularMatrix", diag2tT)
138 :     setAs("ldiMatrix", "sparseMatrix", diag2tT)
139 :     ## needed too (otherwise <dense> -> Tsparse is taken):
140 :     setAs("ldiMatrix", "TsparseMatrix", diag2tT)
141 :     setAs("ldiMatrix", "CsparseMatrix",
142 :     function(from) as(.diag2tT(from, "U", "l"), "CsparseMatrix"))
143 :     setAs("ldiMatrix", "symmetricMatrix",
144 :     function(from) .diag2sT(from, "U", "l"))
145 : maechler 1654
146 : maechler 1845
147 : maechler 2128 setAs("diagonalMatrix", "nMatrix",
148 :     function(from) {
149 :     n <- from@Dim[1]
150 :     i <- if(from@diag == "U") integer(0) else which(isN0(from@x)) - 1L
151 :     new("ntTMatrix", i = i, j = i, diag = from@diag,
152 :     Dim = from@Dim, Dimnames = from@Dimnames)
153 :     })
154 :    
155 :    
156 : mmaechler 2175 ## Cheap fast substitute for diag() which *does* preserve the mode of x :
157 :     mkDiag <- function(x, n) {
158 :     y <- matrix(as0(mod=mode(x)), n,n)
159 :     if (n > 0) y[1L + 0:(n - 1L) * (n + 1L)] <- x
160 :     y
161 :     }
162 :    
163 : maechler 1109 setAs("diagonalMatrix", "matrix",
164 :     function(from) {
165 : mmaechler 2175 ## want "ldiMatrix" -> <logical> "matrix" :
166 :     mkDiag(if(from@diag == "U") as1(from@x) else from@x,
167 :     n = from@Dim[1])
168 : maechler 1109 })
169 :    
170 : maechler 2098 setMethod("as.vector", signature(x = "diagonalMatrix", mode="missing"),
171 :     function(x, mode) {
172 :     n <- x@Dim[1]
173 : mmaechler 2175 mod.x <- mode(x@x)
174 :     r <- vector(mod.x, length = n^2)
175 : maechler 2098 if(n)
176 :     r[1 + 0:(n - 1) * (n + 1)] <-
177 : mmaechler 2175 if(x@diag == "U") as1(mod=mod.x) else x@x
178 : maechler 2098 r
179 :     })
180 :    
181 : maechler 1654 setAs("diagonalMatrix", "generalMatrix", # prefer sparse:
182 : maechler 2128 function(from) as(as(from, "CsparseMatrix"), "generalMatrix"))
183 : maechler 1174
184 : maechler 1655 .diag.x <- function(m) {
185 :     if(m@diag == "U")
186 : maechler 2136 rep.int(if(is.numeric(m@x)) 1. else TRUE, m@Dim[1])
187 : maechler 1655 else m@x
188 :     }
189 :    
190 :     .diag.2N <- function(m) {
191 :     if(m@diag == "U") m@diag <- "N"
192 :     m
193 :     }
194 :    
195 : maechler 2128 if(FALSE) {
196 : maechler 1654 ## given the above, the following 4 coercions should be all unneeded;
197 :     ## we prefer triangular to general:
198 : maechler 1295 setAs("ddiMatrix", "dgTMatrix",
199 :     function(from) {
200 : maechler 1654 .Deprecated("as(, \"sparseMatrix\")")
201 : maechler 1295 n <- from@Dim[1]
202 : maechler 1845 i <- seq_len(n) - 1L
203 : maechler 1655 new("dgTMatrix", i = i, j = i, x = .diag.x(from),
204 : maechler 1295 Dim = c(n,n), Dimnames = from@Dimnames) })
205 :    
206 :     setAs("ddiMatrix", "dgCMatrix",
207 : maechler 1655 function(from) as(as(from, "sparseMatrix"), "dgCMatrix"))
208 : maechler 1295
209 :     setAs("ldiMatrix", "lgTMatrix",
210 :     function(from) {
211 : maechler 1654 .Deprecated("as(, \"sparseMatrix\")")
212 : maechler 1295 n <- from@Dim[1]
213 : maechler 1575 if(from@diag == "U") { # unit-diagonal
214 :     x <- rep.int(TRUE, n)
215 : maechler 1845 i <- seq_len(n) - 1L
216 : maechler 1575 } else { # "normal"
217 :     nz <- nz.NA(from@x, na. = TRUE)
218 :     x <- from@x[nz]
219 : maechler 1845 i <- which(nz) - 1L
220 : maechler 1575 }
221 :     new("lgTMatrix", i = i, j = i, x = x,
222 : maechler 1295 Dim = c(n,n), Dimnames = from@Dimnames) })
223 :    
224 :     setAs("ldiMatrix", "lgCMatrix",
225 :     function(from) as(as(from, "lgTMatrix"), "lgCMatrix"))
226 : maechler 2128 }
227 : maechler 1295
228 :    
229 : maechler 1447 if(FALSE) # now have faster "ddense" -> "dge"
230 : maechler 1174 setAs("ddiMatrix", "dgeMatrix",
231 :     function(from) as(as(from, "matrix"), "dgeMatrix"))
232 :    
233 : maechler 1109 setAs("matrix", "diagonalMatrix",
234 :     function(from) {
235 : maechler 1295 d <- dim(from)
236 : maechler 1109 if(d[1] != (n <- d[2])) stop("non-square matrix")
237 :     if(any(from[row(from) != col(from)] != 0))
238 :     stop("has non-zero off-diagonal entries")
239 : maechler 1295 x <- diag(from)
240 :     if(is.logical(x)) {
241 :     cl <- "ldiMatrix"
242 :     uni <- all(x)
243 :     } else {
244 :     cl <- "ddiMatrix"
245 :     uni <- all(x == 1)
246 :     storage.mode(x) <- "double"
247 : maechler 1575 } ## TODO: complex
248 : maechler 1295 new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
249 :     x = if(uni) x[FALSE] else x)
250 : maechler 1109 })
251 :    
252 :     ## ``generic'' coercion to diagonalMatrix : build on isDiagonal() and diag()
253 :     setAs("Matrix", "diagonalMatrix",
254 :     function(from) {
255 :     d <- dim(from)
256 :     if(d[1] != (n <- d[2])) stop("non-square matrix")
257 :     if(!isDiagonal(from)) stop("matrix is not diagonal")
258 :     ## else:
259 :     x <- diag(from)
260 :     if(is.logical(x)) {
261 :     cl <- "ldiMatrix"
262 :     uni <- all(x)
263 :     } else {
264 :     cl <- "ddiMatrix"
265 :     uni <- all(x == 1)
266 :     storage.mode(x) <- "double"
267 :     }
268 :     new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
269 :     x = if(uni) x[FALSE] else x)
270 :     })
271 :    
272 : maechler 1708
273 : maechler 2136 ## In order to evade method dispatch ambiguity warnings,
274 :     ## we use this hack instead of signature x = "diagonalMatrix" :
275 :     diCls <- names(getClass("diagonalMatrix")@subclasses)
276 :     for(cls in diCls) {
277 :     setMethod("diag", signature(x = cls),
278 :     function(x = 1, nrow, ncol) .diag.x(x))
279 :     }
280 : maechler 1708
281 : maechler 1799
282 : maechler 2098 subDiag <- function(x, i, j, ..., drop) {
283 : maechler 1799 x <- as(x, "sparseMatrix")
284 :     x <- if(missing(i))
285 :     x[, j, drop=drop]
286 :     else if(missing(j))
287 :     x[i, , drop=drop]
288 :     else
289 :     x[i,j, drop=drop]
290 : maechler 2120 if(isS4(x) && isDiagonal(x)) as(x, "diagonalMatrix") else x
291 : maechler 1799 }
292 :    
293 :     setMethod("[", signature(x = "diagonalMatrix", i = "index",
294 :     j = "index", drop = "logical"), subDiag)
295 :     setMethod("[", signature(x = "diagonalMatrix", i = "index",
296 :     j = "missing", drop = "logical"),
297 : maechler 2098 function(x, i, j, ..., drop) subDiag(x, i=i, drop=drop))
298 : maechler 1799 setMethod("[", signature(x = "diagonalMatrix", i = "missing",
299 :     j = "index", drop = "logical"),
300 : maechler 2098 function(x, i, j, ..., drop) subDiag(x, j=j, drop=drop))
301 : maechler 1799
302 : maechler 1617 ## When you assign to a diagonalMatrix, the result should be
303 : maechler 1708 ## diagonal or sparse ---
304 :     ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch
305 : maechler 2098 ## Only(?) current bug: x[i] <- value is wrong when i is *vector*
306 :     replDiag <- function(x, i, j, ..., value) {
307 : maechler 1710 x <- as(x, "sparseMatrix")
308 :     if(missing(i))
309 :     x[, j] <- value
310 : maechler 2098 else if(missing(j)) { ## x[i , ] <- v *OR* x[i] <- v
311 :     na <- nargs()
312 :     ## message("diagnosing replDiag() -- nargs()= ", na)
313 :     if(na == 4)
314 :     x[i, ] <- value
315 :     else if(na == 3)
316 :     x[i] <- value
317 :     else stop("Internal bug: nargs()=",na,"; please report")
318 :     } else
319 : maechler 1710 x[i,j] <- value
320 :     if(isDiagonal(x)) as(x, "diagonalMatrix") else x
321 :     }
322 : maechler 1617
323 : maechler 1710 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
324 :     j = "index", value = "replValue"), replDiag)
325 : maechler 2098
326 : maechler 1710 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
327 :     j = "missing", value = "replValue"),
328 : maechler 2098 function(x,i,j, ..., value) {
329 :     ## message("before replDiag() -- nargs()= ", nargs())
330 :     if(nargs() == 3)
331 :     replDiag(x, i=i, value=value)
332 :     else ## nargs() == 4 :
333 :     replDiag(x, i=i, , value=value)
334 :     })
335 :    
336 : maechler 2096 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "matrix", # 2-col.matrix
337 :     j = "missing", value = "replValue"),
338 : maechler 2098 function(x,i,j, ..., value) {
339 : maechler 2096 if(ncol(i) == 2) {
340 :     if(all((ii <- i[,1]) == i[,2])) { # replace in diagonal only
341 :     x@x[ii] <- value
342 :     x
343 :     } else { ## no longer diagonal, but remain sparse:
344 :     x <- as(x, "sparseMatrix")
345 :     x[i] <- value
346 :     x
347 :     }
348 :     }
349 :     else { # behave as "base R": use as if vector
350 :     x <- as(x, "matrix")
351 :     x[i] <- value
352 :     Matrix(x)
353 :     }
354 :     })
355 :    
356 : maechler 1710 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",
357 :     j = "index", value = "replValue"),
358 : maechler 2098 function(x,i,j, ..., value) replDiag(x, j=j, value=value))
359 : maechler 1710
360 :    
361 : maechler 1109 setMethod("t", signature(x = "diagonalMatrix"),
362 :     function(x) { x@Dimnames <- x@Dimnames[2:1] ; x })
363 :    
364 : maechler 1331 setMethod("isDiagonal", signature(object = "diagonalMatrix"),
365 :     function(object) TRUE)
366 :     setMethod("isTriangular", signature(object = "diagonalMatrix"),
367 :     function(object) TRUE)
368 : maechler 1109 setMethod("isSymmetric", signature(object = "diagonalMatrix"),
369 : maechler 2112 function(object, ...) TRUE)
370 : maechler 1109
371 : maechler 2112 setMethod("symmpart", signature(x = "diagonalMatrix"), function(x) x)
372 :     setMethod("skewpart", signature(x = "diagonalMatrix"), setZero)
373 :    
374 : maechler 2133 setMethod("chol", signature(x = "ddiMatrix"),
375 :     function(x, pivot, ...) {
376 :     if(any(x@x < 0))
377 :     stop("chol() is undefined for diagonal matrix with negative entries")
378 : maechler 1654 x@x <- sqrt(x@x)
379 :     x
380 :     })
381 :     ## chol(L) is L for logical diagonal:
382 : maechler 2133 setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot, ...) x)
383 : maechler 1654
384 : mmaechler 2175 setMethod("determinant", signature(x = "diagonalMatrix", logarithm = "logical"),
385 :     function(x, logarithm, ...) mkDet(x@x, logarithm))
386 :    
387 : maechler 1109 ## Basic Matrix Multiplication {many more to add}
388 : maechler 1654 ## ---------------------
389 :     ## Note that "ldi" logical are treated as numeric
390 : maechler 1109 diagdiagprod <- function(x, y) {
391 :     if(any(dim(x) != dim(y))) stop("non-matching dimensions")
392 :     if(x@diag != "U") {
393 : maechler 1654 if(y@diag != "U") {
394 :     nx <- x@x * y@x
395 :     if(is.numeric(nx) && !is.numeric(x@x))
396 :     x <- as(x, "dMatrix")
397 :     x@x <- as.numeric(nx)
398 :     }
399 :     return(x)
400 : maechler 1109 } else ## x is unit diagonal
401 :     return(y)
402 :     }
403 :    
404 : maechler 1654 setMethod("%*%", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
405 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
406 :    
407 : maechler 1654 formals(diagdiagprod) <- alist(x=, y=x)
408 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
409 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
410 : maechler 1654 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
411 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
412 : maechler 1654 setMethod("crossprod", signature(x = "diagonalMatrix", y = "missing"),
413 :     diagdiagprod, valueClass = "ddiMatrix")
414 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "missing"),
415 :     diagdiagprod, valueClass = "ddiMatrix")
416 : maechler 1109
417 :    
418 :     diagmatprod <- function(x, y) {
419 :     dx <- dim(x)
420 :     dy <- dim(y)
421 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
422 :     n <- dx[1]
423 :     as(if(x@diag == "U") y else x@x * y, "Matrix")
424 :     }
425 :    
426 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),
427 : maechler 1654 diagmatprod)
428 : maechler 1109 formals(diagmatprod) <- alist(x=, y=NULL)
429 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),
430 : maechler 1654 diagmatprod)
431 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "matrix"),
432 :     diagmatprod)
433 : maechler 1109
434 :     diagdgeprod <- function(x, y) {
435 :     dx <- dim(x)
436 :     dy <- dim(y)
437 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
438 :     if(x@diag != "U")
439 :     y@x <- x@x * y@x
440 :     y
441 :     }
442 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "dgeMatrix"),
443 :     diagdgeprod, valueClass = "dgeMatrix")
444 :     formals(diagdgeprod) <- alist(x=, y=NULL)
445 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),
446 :     diagdgeprod, valueClass = "dgeMatrix")
447 :    
448 :     setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),
449 :     function(x, y) {
450 : maechler 1635 dx <- dim(x)
451 :     dy <- dim(y)
452 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
453 :     as(if(y@diag == "U") x else x * rep(y@x, each = dx[1]), "Matrix")
454 :     })
455 : maechler 1109
456 :     setMethod("%*%", signature(x = "dgeMatrix", y = "diagonalMatrix"),
457 :     function(x, y) {
458 : maechler 1635 dx <- dim(x)
459 :     dy <- dim(y)
460 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
461 :     if(y@diag == "N")
462 :     x@x <- x@x * rep(y@x, each = dx[1])
463 :     x
464 :     })
465 : maechler 1109
466 : maechler 1295 ## crossprod {more of these}
467 : maechler 1109
468 : maechler 1295 ## tcrossprod --- all are not yet there: do the dense ones here:
469 : maechler 1109
470 : maechler 1295 ## FIXME:
471 :     ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),
472 :     ## function(x, y = NULL) {
473 :     ## })
474 : maechler 1109
475 : maechler 1295 ## setMethod("tcrossprod", signature(x = "denseMatrix", y = "diagonalMatrix"),
476 :     ## function(x, y = NULL) {
477 :     ## })
478 : maechler 1109
479 : maechler 1799 setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
480 : maechler 2123 function(x, y = NULL) crossprod(as(x, "sparseMatrix"), y))
481 : maechler 1295
482 : maechler 1799 setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
483 : maechler 2123 function(x, y = NULL) crossprod(x, as(y, "sparseMatrix")))
484 : maechler 1799
485 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
486 : maechler 2123 function(x, y = NULL) tcrossprod(as(x, "sparseMatrix"), y))
487 : maechler 1799
488 :     setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
489 : maechler 2123 function(x, y = NULL) tcrossprod(x, as(y, "sparseMatrix")))
490 : maechler 1799
491 :    
492 :     ## FIXME?: In theory, this can be done *FASTER*, in some cases, via tapply1()
493 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),
494 :     function(x, y) as(x, "sparseMatrix") %*% y)
495 :     ## NB: The previous is *not* triggering for "ddi" o "dgC" (= distance 3)
496 :     ## since there's a "ddense" o "Csparse" at dist. 2 => triggers first.
497 :     ## ==> do this:
498 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
499 :     function(x, y) as(x, "CsparseMatrix") %*% y)
500 :     setMethod("%*%", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
501 :     function(x, y) x %*% as(y, "CsparseMatrix"))
502 :     ## NB: this is *not* needed for Tsparse & Rsparse
503 :     ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*
504 :     ## do indeed work by going through sparse (and *not* ddense)!
505 :    
506 :     setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),
507 :     function(x, y) x %*% as(y, "sparseMatrix"))
508 :    
509 :    
510 :     setMethod("solve", signature(a = "diagonalMatrix", b = "missing"),
511 :     function(a, b, ...) {
512 :     a@x <- 1/ a@x
513 :     a@Dimnames <- a@Dimnames[2:1]
514 :     a
515 :     })
516 :    
517 :     solveDiag <- function(a, b, ...) {
518 :     if((n <- a@Dim[1]) != nrow(b))
519 :     stop("incompatible matrix dimensions")
520 :     ## trivially invert a 'in place' and multiply:
521 :     a@x <- 1/ a@x
522 :     a@Dimnames <- a@Dimnames[2:1]
523 :     a %*% b
524 :     }
525 :     setMethod("solve", signature(a = "diagonalMatrix", b = "matrix"),
526 :     solveDiag)
527 :     setMethod("solve", signature(a = "diagonalMatrix", b = "Matrix"),
528 :     solveDiag)
529 :    
530 : maechler 2106 ## Schur() ---> ./eigen.R
531 : maechler 1799
532 :    
533 :    
534 : mmaechler 2175 ###---------------- <Ops> (<Arith>, <Logic>, <Compare> ) ----------------------
535 : maechler 1295
536 : maechler 1655 ## Use function for several signatures, in order to evade
537 :     ## ambiguous dispatch for "ddi", since there's also Arith(ddense., ddense.)
538 : mmaechler 2175 diagOdiag <- function(e1,e2) {
539 :     ## result should also be diagonal _ if possible _
540 : maechler 1655 r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"
541 : mmaechler 2175 ## Check what happens with non-diagonals, i.e. (0 o 0), (FALSE o 0), ...:
542 :     r00 <- callGeneric(if(is.numeric(e1@x)) 0 else FALSE,
543 :     if(is.numeric(e2@x)) 0 else FALSE)
544 :     if(is0(r00)) { ## r00 == 0 or FALSE --- result *is* diagonal
545 :     if(is.numeric(r)) {
546 :     if(is.numeric(e2@x)) {
547 :     e2@x <- r; return(.diag.2N(e2)) }
548 :     if(!is.numeric(e1@x))
549 :     ## e.g. e1, e2 are logical;
550 :     e1 <- as(e1, "dMatrix")
551 :     }
552 :     else if(is.logical(r))
553 :     e1 <- as(e1, "lMatrix")
554 :     else stop("intermediate 'r' is of type", typeof(r))
555 :     e1@x <- r
556 :     .diag.2N(e1)
557 : maechler 1655 }
558 : mmaechler 2175 else { ## result not diagonal, but at least symmetric:
559 :     isNum <- (is.numeric(r) || is.numeric(r00))
560 :     isLog <- (is.logical(r) || is.logical(r00))
561 :    
562 :     if(getOption("verbose"))
563 :     message("exploding <diag> o <diag> into dense matrix")
564 :     d <- e1@Dim
565 :     n <- d[1]
566 :     stopifnot(length(r) == n)
567 :     xx <- as.vector(matrix(rbind(r, matrix(r00,n,n)), n,n))
568 :     newcl <-
569 :     paste(if(isNum) "d" else if(isLog) {
570 :     if(!any(is.na(r)) && !any(is.na(r00))) "n" else "l"
571 :     } else stop("not yet implemented .. please report")
572 :     ,
573 :     "syMatrix", sep='')
574 :    
575 :     new(newcl, Dim = e1@Dim, Dimnames = e1@Dimnames, x = xx)
576 :     }
577 : maechler 1655 }
578 :    
579 : mmaechler 2175 ### This would be *the* way, but we get tons of "ambiguous method dispatch"
580 :     if(FALSE) {
581 : maechler 1655 setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),
582 :     diagOdiag)
583 : mmaechler 2175 } else { ## These are just for method disambiguation:
584 :     for(c1 in diCls)
585 :     for(c2 in diCls)
586 :     setMethod("Ops", signature(e1 = c1, e2 = c2), diagOdiag)
587 :     }
588 : maechler 1655
589 : maechler 1845 ## FIXME: diagonal o triangular |--> triangular
590 :     ## ----- diagonal o symmetric |--> symmetric
591 :     ## {also when other is sparse: do these "here" --
592 :     ## before conversion to sparse, since that loses "diagonality"}
593 :    
594 : maechler 1655 ## For almost everything else, diag* shall be treated "as sparse" :
595 : maechler 1295 ## These are cheap implementations via coercion
596 :    
597 : maechler 2144 ## For disambiguation --- define this for "sparseMatrix" , then for "ANY";
598 :     ## and because we can save an .M.kind() call, we use this explicit
599 :     ## "hack" for all diagonalMatrix *subclasses* instead of just "diagonalMatrix" :
600 :     ##
601 :     ## ddi*:
602 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "sparseMatrix"),
603 : mmaechler 2175 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2))
604 : maechler 2144 setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ddiMatrix"),
605 : mmaechler 2175 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "d")))
606 : maechler 2144 ## ldi*
607 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "sparseMatrix"),
608 : mmaechler 2175 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2))
609 : maechler 2144 setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ldiMatrix"),
610 : mmaechler 2175 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "l")))
611 : maechler 1654
612 : mmaechler 2175 ## Ops: Arith --> numeric : "dMatrix"
613 :     ## Compare --> logical
614 :     ## Logic --> logical: "lMatrix"
615 :    
616 : maechler 2144 ## other = "numeric" : stay diagonal if possible
617 : mmaechler 2175 ## ddi*: Arith: result numeric, potentially ddiMatrix
618 :     setMethod("Arith", signature(e1 = "ddiMatrix", e2 = "numeric"),
619 : maechler 2144 function(e1,e2) {
620 :     n <- e1@Dim[1]; nsq <- n*n
621 :     f0 <- callGeneric(0, e2)
622 :     if(all(is0(f0))) { # remain diagonal
623 : maechler 2157 L1 <- (le <- length(e2)) == 1L
624 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
625 :     if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
626 : maechler 2144 e1@diag <- "N"
627 : maechler 2157 if(L1) r <- rep.int(r, n)
628 :     } else
629 : maechler 2144 r <- callGeneric(e1@x, e2)
630 : maechler 2157 e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
631 : maechler 2144 return(e1)
632 :     }
633 :     callGeneric(diag2tT.u(e1,e2, "d"), e2)
634 :     })
635 : maechler 1655
636 : mmaechler 2175 setMethod("Arith", signature(e1 = "numeric", e2 = "ddiMatrix"),
637 : maechler 2144 function(e1,e2) {
638 :     n <- e2@Dim[1]; nsq <- n*n
639 :     f0 <- callGeneric(e1, 0)
640 :     if(all(is0(f0))) { # remain diagonal
641 : maechler 2157 L1 <- (le <- length(e1)) == 1L
642 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
643 :     if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
644 : maechler 2144 e2@diag <- "N"
645 : maechler 2157 if(L1) r <- rep.int(r, n)
646 :     } else
647 : maechler 2144 r <- callGeneric(e1, e2@x)
648 : maechler 2157 e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
649 : maechler 2144 return(e2)
650 :     }
651 :     callGeneric(e1, diag2tT.u(e2,e1, "d"))
652 :     })
653 : mmaechler 2175
654 :     ## ldi* Arith --> result numeric, potentially ddiMatrix
655 :     setMethod("Arith", signature(e1 = "ldiMatrix", e2 = "numeric"),
656 :     function(e1,e2) {
657 :     n <- e1@Dim[1]; nsq <- n*n
658 :     f0 <- callGeneric(0, e2)
659 :     if(all(is0(f0))) { # remain diagonal
660 :     L1 <- (le <- length(e2)) == 1L
661 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
662 :     if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
663 :     e1@diag <- "N"
664 :     if(L1) r <- rep.int(r, n)
665 :     } else
666 :     r <- callGeneric(e1@x, e2)
667 :     e1 <- copyClass(e1, "ddiMatrix", c("diag", "Dim", "Dimnames"))
668 :     e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
669 :     return(e1)
670 :     }
671 :     callGeneric(diag2tT.u(e1,e2, "d"), e2)
672 :     })
673 :    
674 :     setMethod("Arith", signature(e1 = "numeric", e2 = "ldiMatrix"),
675 :     function(e1,e2) {
676 :     n <- e2@Dim[1]; nsq <- n*n
677 :     f0 <- callGeneric(e1, 0)
678 :     if(all(is0(f0))) { # remain diagonal
679 :     L1 <- (le <- length(e1)) == 1L
680 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
681 :     if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
682 :     e2@diag <- "N"
683 :     if(L1) r <- rep.int(r, n)
684 :     } else
685 :     r <- callGeneric(e1, e2@x)
686 :     e2 <- copyClass(e2, "ddiMatrix", c("diag", "Dim", "Dimnames"))
687 :     e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
688 :     return(e2)
689 :     }
690 :     callGeneric(e1, diag2tT.u(e2,e1, "d"))
691 :     })
692 :    
693 :     ## ddi*: for "Ops" without Arith --> result logical, potentially ldi
694 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "numeric"),
695 :     function(e1,e2) {
696 :     n <- e1@Dim[1]; nsq <- n*n
697 :     f0 <- callGeneric(0, e2)
698 :     if(all(is0(f0))) { # remain diagonal
699 :     L1 <- (le <- length(e2)) == 1L
700 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
701 :     if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
702 :     e1@diag <- "N"
703 :     if(L1) r <- rep.int(r, n)
704 :     } else
705 :     r <- callGeneric(e1@x, e2)
706 :     e1 <- copyClass(e1, "ldiMatrix", c("diag", "Dim", "Dimnames"))
707 :     e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
708 :     return(e1)
709 :     }
710 :     callGeneric(diag2tT.u(e1,e2, "l"), e2)
711 :     })
712 :    
713 :     setMethod("Ops", signature(e1 = "numeric", e2 = "ddiMatrix"),
714 :     function(e1,e2) {
715 :     n <- e2@Dim[1]; nsq <- n*n
716 :     f0 <- callGeneric(e1, 0)
717 :     if(all(is0(f0))) { # remain diagonal
718 :     L1 <- (le <- length(e1)) == 1L
719 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
720 :     if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
721 :     e2@diag <- "N"
722 :     if(L1) r <- rep.int(r, n)
723 :     } else
724 :     r <- callGeneric(e1, e2@x)
725 :     e2 <- copyClass(e2, "ldiMatrix", c("diag", "Dim", "Dimnames"))
726 :     e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
727 :     return(e2)
728 :     }
729 :     callGeneric(e1, diag2tT.u(e2,e1, "l"))
730 :     })
731 :    
732 :     ## ldi*: for "Ops" without Arith --> result logical, potentially ldi
733 : maechler 2144 setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "numeric"),
734 :     function(e1,e2) {
735 :     n <- e1@Dim[1]; nsq <- n*n
736 :     f0 <- callGeneric(FALSE, e2)
737 :     if(all(is0(f0))) { # remain diagonal
738 : maechler 2157 L1 <- (le <- length(e2)) == 1L
739 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
740 :     if(e1@diag == "U" && any((r <- callGeneric(TRUE, e2)) != 1)) {
741 : maechler 2144 e1@diag <- "N"
742 : maechler 2157 if(L1) r <- rep.int(r, n)
743 :     } else
744 : maechler 2144 r <- callGeneric(e1@x, e2)
745 : maechler 2157 e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
746 : maechler 2144 return(e1)
747 :     }
748 :     callGeneric(diag2tT.u(e1,e2, "l"), e2)
749 :     })
750 : maechler 1655
751 : maechler 2144 setMethod("Ops", signature(e1 = "numeric", e2 = "ldiMatrix"),
752 :     function(e1,e2) {
753 :     n <- e2@Dim[1]; nsq <- n*n
754 :     f0 <- callGeneric(e1, FALSE)
755 :     if(all(is0(f0))) { # remain diagonal
756 : maechler 2157 L1 <- (le <- length(e1)) == 1L
757 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
758 :     if(e2@diag == "U" && any((r <- callGeneric(e1, TRUE)) != 1)) {
759 : maechler 2144 e2@diag <- "N"
760 : maechler 2157 if(L1) r <- rep.int(r, n)
761 :     } else
762 : maechler 2144 r <- callGeneric(e1, e2@x)
763 : maechler 2157 e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
764 : maechler 2144 return(e2)
765 :     }
766 :     callGeneric(e1, diag2tT.u(e2,e1, "l"))
767 :     })
768 :    
769 :    
770 :    
771 :     ## Not {"sparseMatrix", "numeric} : {"denseMatrix", "matrix", ... }
772 :     ## ddi*:
773 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "ANY"),
774 :     function(e1,e2) callGeneric(diag2tT.u(e1,e2, "d"), e2))
775 :     setMethod("Ops", signature(e1 = "ANY", e2 = "ddiMatrix"),
776 :     function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "d")))
777 :     ## ldi*:
778 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "ANY"),
779 :     function(e1,e2) callGeneric(diag2tT.u(e1,e2, "l"), e2))
780 :     setMethod("Ops", signature(e1 = "ANY", e2 = "ldiMatrix"),
781 :     function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "l")))
782 :    
783 : mmaechler 2175 ## This should *not* dispatch to <dense> methods (in ./Ops.R ), as
784 :     ## FALSE & <anything> |-> FALSE : hence result should be diagonal:
785 :     for(cl in diCls) {
786 :     setMethod("&", signature(e1 = cl, e2 = "ANY"),
787 :     function(e1,e2) e1 & as(e2,"Matrix"))
788 :     setMethod("&", signature(e1 = "ANY", e2 = cl),
789 :     function(e1,e2) as(e1,"Matrix") & e2)
790 :     for(c2 in c("denseMatrix", "Matrix")) {
791 :     setMethod("&", signature(e1 = cl, e2 = c2),
792 :     function(e1,e2) e1 & Diagonal(x = diag(e2)))
793 :     setMethod("&", signature(e1 = c2, e2 = cl),
794 :     function(e1,e2) Diagonal(x = diag(e1)) & e2)
795 :     }
796 :     }
797 : maechler 2144
798 :    
799 : mmaechler 2175 ### "Summary" : "max" "min" "range" "prod" "sum" "any" "all"
800 :     ### ---------- any, all: separately here
801 :     for(cl in diCls) {
802 :     setMethod("any", cl,
803 :     function (x, ..., na.rm) {
804 :     if(any(x@Dim == 0)) FALSE
805 :     else if(x@diag == "U") TRUE else any(x@x, ..., na.rm = na.rm)
806 :     })
807 :     setMethod("all", cl, function (x, ..., na.rm) any(x@Dim == 0))
808 :     setMethod("prod", cl, function (x, ..., na.rm) as.numeric(any(x@Dim == 0)))
809 :    
810 :     setMethod("sum", cl,
811 :     function(x, ..., na.rm) {
812 :     r <- sum(x@x, ..., na.rm = na.rm)# double or integer, correctly
813 :     if(x@diag == "U" && !is.na(r)) r + x@Dim[1] else r
814 :     })
815 :     }
816 :    
817 :     ## The remaining ones are max, min, range :
818 :    
819 :     setMethod("Summary", "ddiMatrix",
820 :     function(x, ..., na.rm) {
821 :     if(any(x@Dim == 0)) callGeneric(numeric(0), ..., na.rm=na.rm)
822 :     else if(x@diag == "U")
823 :     callGeneric(x@x, 0, 1, ..., na.rm=na.rm)
824 :     else callGeneric(x@x, 0, ..., na.rm=na.rm)
825 :     })
826 :     setMethod("Summary", "ldiMatrix",
827 :     function(x, ..., na.rm) {
828 :     if(any(x@Dim == 0)) callGeneric(logical(0), ..., na.rm=na.rm)
829 :     else if(x@diag == "U")
830 :     callGeneric(x@x, FALSE, TRUE, ..., na.rm=na.rm)
831 :     else callGeneric(x@x, FALSE, ..., na.rm=na.rm)
832 :     })
833 :    
834 :    
835 :    
836 : maechler 1109 ## similar to prTriang() in ./Auxiliaries.R :
837 :     prDiag <-
838 :     function(x, digits = getOption("digits"), justify = "none", right = TRUE)
839 :     {
840 :     cf <- array(".", dim = x@Dim, dimnames = x@Dimnames)
841 :     cf[row(cf) == col(cf)] <-
842 :     sapply(diag(x), format, digits = digits, justify = justify)
843 :     print(cf, quote = FALSE, right = right)
844 :     invisible(x)
845 :     }
846 :    
847 :     setMethod("show", signature(object = "diagonalMatrix"),
848 : maechler 1592 function(object) {
849 :     d <- dim(object)
850 :     cl <- class(object)
851 :     cat(sprintf('%d x %d diagonal matrix of class "%s"\n',
852 :     d[1], d[2], cl))
853 :     prDiag(object)
854 :     })

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