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

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