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 2196 - (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 : mmaechler 2192 setReplaceMethod("[", signature(x = "diagonalMatrix",
297 :     i = "matrix", # 2-col.matrix
298 : maechler 2096 j = "missing", value = "replValue"),
299 : maechler 2098 function(x,i,j, ..., value) {
300 : maechler 2096 if(ncol(i) == 2) {
301 :     if(all((ii <- i[,1]) == i[,2])) { # replace in diagonal only
302 : mmaechler 2192 if(x@diag == "U") {
303 :     one <- as1(x@x)
304 :     if(any(value != one | is.na(value))) {
305 :     x@diag <- "N"
306 :     x@x <- rep.int(one, x@Dim[1])
307 :     }
308 :     }
309 : maechler 2096 x@x[ii] <- value
310 :     x
311 :     } else { ## no longer diagonal, but remain sparse:
312 :     x <- as(x, "sparseMatrix")
313 :     x[i] <- value
314 :     x
315 :     }
316 :     }
317 :     else { # behave as "base R": use as if vector
318 :     x <- as(x, "matrix")
319 :     x[i] <- value
320 :     Matrix(x)
321 :     }
322 :     })
323 :    
324 : maechler 1710 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",
325 :     j = "index", value = "replValue"),
326 : maechler 2098 function(x,i,j, ..., value) replDiag(x, j=j, value=value))
327 : maechler 1710
328 :    
329 : maechler 1109 setMethod("t", signature(x = "diagonalMatrix"),
330 :     function(x) { x@Dimnames <- x@Dimnames[2:1] ; x })
331 :    
332 : maechler 1331 setMethod("isDiagonal", signature(object = "diagonalMatrix"),
333 :     function(object) TRUE)
334 :     setMethod("isTriangular", signature(object = "diagonalMatrix"),
335 :     function(object) TRUE)
336 : maechler 1109 setMethod("isSymmetric", signature(object = "diagonalMatrix"),
337 : maechler 2112 function(object, ...) TRUE)
338 : maechler 1109
339 : maechler 2112 setMethod("symmpart", signature(x = "diagonalMatrix"), function(x) x)
340 :     setMethod("skewpart", signature(x = "diagonalMatrix"), setZero)
341 :    
342 : maechler 2133 setMethod("chol", signature(x = "ddiMatrix"),
343 :     function(x, pivot, ...) {
344 : mmaechler 2183 if(x@diag == "U") return(x)
345 :     ## else
346 : maechler 2133 if(any(x@x < 0))
347 :     stop("chol() is undefined for diagonal matrix with negative entries")
348 : maechler 1654 x@x <- sqrt(x@x)
349 :     x
350 :     })
351 :     ## chol(L) is L for logical diagonal:
352 : maechler 2133 setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot, ...) x)
353 : maechler 1654
354 : mmaechler 2175 setMethod("determinant", signature(x = "diagonalMatrix", logarithm = "logical"),
355 : mmaechler 2185 function(x, logarithm, ...) mkDet(.diag.x(x), logarithm))
356 : mmaechler 2175
357 : mmaechler 2183 setMethod("norm", signature(x = "diagonalMatrix", type = "character"),
358 :     function(x, type, ...) {
359 :     if((n <- x@Dim[1]) == 0) return(0) # as for "sparseMatrix"
360 :     type <- toupper(substr(type[1], 1, 1))
361 :     isU <- (x@diag == "U") # unit-diagonal
362 :     if(type == "F") sqrt(if(isU) n else sum(x@x^2))
363 :     else { ## norm == "I","1","O","M" :
364 :     if(isU) 1 else max(abs(x@x))
365 :     }
366 :     })
367 :    
368 :    
369 :    
370 : maechler 1109 ## Basic Matrix Multiplication {many more to add}
371 : maechler 1654 ## ---------------------
372 :     ## Note that "ldi" logical are treated as numeric
373 : maechler 1109 diagdiagprod <- function(x, y) {
374 : mmaechler 2183 n <- dimCheck(x,y)[1]
375 : maechler 1109 if(x@diag != "U") {
376 : maechler 1654 if(y@diag != "U") {
377 :     nx <- x@x * y@x
378 :     if(is.numeric(nx) && !is.numeric(x@x))
379 :     x <- as(x, "dMatrix")
380 :     x@x <- as.numeric(nx)
381 :     }
382 :     return(x)
383 : maechler 1109 } else ## x is unit diagonal
384 :     return(y)
385 :     }
386 :    
387 : maechler 1654 setMethod("%*%", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
388 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
389 :    
390 : maechler 1654 formals(diagdiagprod) <- alist(x=, y=x)
391 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
392 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
393 : maechler 1654 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
394 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
395 : maechler 1654 setMethod("crossprod", signature(x = "diagonalMatrix", y = "missing"),
396 :     diagdiagprod, valueClass = "ddiMatrix")
397 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "missing"),
398 :     diagdiagprod, valueClass = "ddiMatrix")
399 : maechler 1109
400 :    
401 :     diagmatprod <- function(x, y) {
402 : mmaechler 2183 ## x is diagonalMatrix
403 : maechler 1109 dx <- dim(x)
404 :     dy <- dim(y)
405 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
406 :     n <- dx[1]
407 :     as(if(x@diag == "U") y else x@x * y, "Matrix")
408 :     }
409 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),
410 : maechler 1654 diagmatprod)
411 : mmaechler 2183 ## sneaky .. :
412 : maechler 1109 formals(diagmatprod) <- alist(x=, y=NULL)
413 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),
414 : maechler 1654 diagmatprod)
415 : maechler 1109
416 : mmaechler 2183 diagGeprod <- function(x, y) {
417 : maechler 1109 dx <- dim(x)
418 :     dy <- dim(y)
419 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
420 :     if(x@diag != "U")
421 :     y@x <- x@x * y@x
422 :     y
423 :     }
424 : mmaechler 2183 setMethod("%*%", signature(x= "diagonalMatrix", y= "dgeMatrix"), diagGeprod)
425 :     setMethod("%*%", signature(x= "diagonalMatrix", y= "lgeMatrix"), diagGeprod)
426 :     formals(diagGeprod) <- alist(x=, y=NULL)
427 : maechler 1109 setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),
428 : mmaechler 2183 diagGeprod, valueClass = "dgeMatrix")
429 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "lgeMatrix"),
430 :     diagGeprod)
431 : maechler 1109
432 : mmaechler 2183 matdiagprod <- function(x, y) {
433 :     dx <- dim(x)
434 :     dy <- dim(y)
435 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
436 :     Matrix(if(y@diag == "U") x else x * rep(y@x, each = dx[1]))
437 :     }
438 : maechler 1109 setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),
439 : mmaechler 2183 matdiagprod)
440 :     formals(matdiagprod) <- alist(x=, y=NULL)
441 :     setMethod("tcrossprod", signature(x = "matrix", y = "diagonalMatrix"),
442 :     matdiagprod)
443 : maechler 1109
444 : mmaechler 2183 gediagprod <- function(x, y) {
445 :     dx <- dim(x)
446 :     dy <- dim(y)
447 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
448 :     if(y@diag == "N")
449 :     x@x <- x@x * rep(y@x, each = dx[1])
450 :     x
451 :     }
452 :     setMethod("%*%", signature(x= "dgeMatrix", y= "diagonalMatrix"), gediagprod)
453 :     setMethod("%*%", signature(x= "lgeMatrix", y= "diagonalMatrix"), gediagprod)
454 :     formals(gediagprod) <- alist(x=, y=NULL)
455 :     setMethod("tcrossprod", signature(x = "dgeMatrix", y = "diagonalMatrix"),
456 :     gediagprod)
457 :     setMethod("tcrossprod", signature(x = "lgeMatrix", y = "diagonalMatrix"),
458 :     gediagprod)
459 : maechler 1109
460 : maechler 1295 ## crossprod {more of these}
461 : maechler 1109
462 : maechler 1295 ## tcrossprod --- all are not yet there: do the dense ones here:
463 : maechler 1109
464 : mmaechler 2183 setMethod("%*%", signature(x = "diagonalMatrix", y = "denseMatrix"),
465 :     function(x, y) if(x@diag == "U") y else x %*% as(y, "generalMatrix"))
466 :     setMethod("%*%", signature(x = "denseMatrix", y = "diagonalMatrix"),
467 :     function(x, y) if(y@diag == "U") x else as(x, "generalMatrix") %*% y)
468 :    
469 :    
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 : mmaechler 2183 setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),
496 :     function(x, y) x %*% as(y, "sparseMatrix"))
497 : maechler 1799 ## NB: The previous is *not* triggering for "ddi" o "dgC" (= distance 3)
498 :     ## since there's a "ddense" o "Csparse" at dist. 2 => triggers first.
499 :     ## ==> do this:
500 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
501 :     function(x, y) as(x, "CsparseMatrix") %*% y)
502 :     setMethod("%*%", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
503 :     function(x, y) x %*% as(y, "CsparseMatrix"))
504 :     ## NB: this is *not* needed for Tsparse & Rsparse
505 :     ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*
506 :     ## do indeed work by going through sparse (and *not* ddense)!
507 :    
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 : mmaechler 2185 ## we use this hack instead of signature x = "diagonalMatrix" :
581 :     diCls <- names(getClass("diagonalMatrix")@subclasses)
582 : mmaechler 2175 if(FALSE) {
583 : maechler 1655 setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),
584 :     diagOdiag)
585 : mmaechler 2175 } else { ## These are just for method disambiguation:
586 :     for(c1 in diCls)
587 :     for(c2 in diCls)
588 :     setMethod("Ops", signature(e1 = c1, e2 = c2), diagOdiag)
589 :     }
590 : maechler 1655
591 : maechler 1845 ## FIXME: diagonal o triangular |--> triangular
592 :     ## ----- diagonal o symmetric |--> symmetric
593 :     ## {also when other is sparse: do these "here" --
594 :     ## before conversion to sparse, since that loses "diagonality"}
595 :    
596 : maechler 1655 ## For almost everything else, diag* shall be treated "as sparse" :
597 : maechler 1295 ## These are cheap implementations via coercion
598 :    
599 : maechler 2144 ## For disambiguation --- define this for "sparseMatrix" , then for "ANY";
600 :     ## and because we can save an .M.kind() call, we use this explicit
601 :     ## "hack" for all diagonalMatrix *subclasses* instead of just "diagonalMatrix" :
602 :     ##
603 :     ## ddi*:
604 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "sparseMatrix"),
605 : mmaechler 2175 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2))
606 : maechler 2144 setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ddiMatrix"),
607 : mmaechler 2175 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "d")))
608 : maechler 2144 ## ldi*
609 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "sparseMatrix"),
610 : mmaechler 2175 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2))
611 : maechler 2144 setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ldiMatrix"),
612 : mmaechler 2175 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "l")))
613 : maechler 1654
614 : mmaechler 2175 ## Ops: Arith --> numeric : "dMatrix"
615 :     ## Compare --> logical
616 :     ## Logic --> logical: "lMatrix"
617 :    
618 : maechler 2144 ## other = "numeric" : stay diagonal if possible
619 : mmaechler 2175 ## ddi*: Arith: result numeric, potentially ddiMatrix
620 :     setMethod("Arith", signature(e1 = "ddiMatrix", e2 = "numeric"),
621 : maechler 2144 function(e1,e2) {
622 :     n <- e1@Dim[1]; nsq <- n*n
623 :     f0 <- callGeneric(0, e2)
624 :     if(all(is0(f0))) { # remain diagonal
625 : maechler 2157 L1 <- (le <- length(e2)) == 1L
626 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
627 :     if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
628 : maechler 2144 e1@diag <- "N"
629 : maechler 2157 if(L1) r <- rep.int(r, n)
630 :     } else
631 : maechler 2144 r <- callGeneric(e1@x, e2)
632 : maechler 2157 e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
633 : maechler 2144 return(e1)
634 :     }
635 :     callGeneric(diag2tT.u(e1,e2, "d"), e2)
636 :     })
637 : maechler 1655
638 : mmaechler 2175 setMethod("Arith", signature(e1 = "numeric", e2 = "ddiMatrix"),
639 : maechler 2144 function(e1,e2) {
640 :     n <- e2@Dim[1]; nsq <- n*n
641 :     f0 <- callGeneric(e1, 0)
642 :     if(all(is0(f0))) { # remain diagonal
643 : maechler 2157 L1 <- (le <- length(e1)) == 1L
644 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
645 :     if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
646 : maechler 2144 e2@diag <- "N"
647 : maechler 2157 if(L1) r <- rep.int(r, n)
648 :     } else
649 : maechler 2144 r <- callGeneric(e1, e2@x)
650 : maechler 2157 e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
651 : maechler 2144 return(e2)
652 :     }
653 :     callGeneric(e1, diag2tT.u(e2,e1, "d"))
654 :     })
655 : mmaechler 2175
656 :     ## ldi* Arith --> result numeric, potentially ddiMatrix
657 :     setMethod("Arith", signature(e1 = "ldiMatrix", e2 = "numeric"),
658 :     function(e1,e2) {
659 :     n <- e1@Dim[1]; nsq <- n*n
660 :     f0 <- callGeneric(0, e2)
661 :     if(all(is0(f0))) { # remain diagonal
662 :     L1 <- (le <- length(e2)) == 1L
663 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
664 :     if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
665 :     e1@diag <- "N"
666 :     if(L1) r <- rep.int(r, n)
667 :     } else
668 :     r <- callGeneric(e1@x, e2)
669 :     e1 <- copyClass(e1, "ddiMatrix", c("diag", "Dim", "Dimnames"))
670 :     e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
671 :     return(e1)
672 :     }
673 :     callGeneric(diag2tT.u(e1,e2, "d"), e2)
674 :     })
675 :    
676 :     setMethod("Arith", signature(e1 = "numeric", e2 = "ldiMatrix"),
677 :     function(e1,e2) {
678 :     n <- e2@Dim[1]; nsq <- n*n
679 :     f0 <- callGeneric(e1, 0)
680 :     if(all(is0(f0))) { # remain diagonal
681 :     L1 <- (le <- length(e1)) == 1L
682 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
683 :     if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
684 :     e2@diag <- "N"
685 :     if(L1) r <- rep.int(r, n)
686 :     } else
687 :     r <- callGeneric(e1, e2@x)
688 :     e2 <- copyClass(e2, "ddiMatrix", c("diag", "Dim", "Dimnames"))
689 :     e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
690 :     return(e2)
691 :     }
692 :     callGeneric(e1, diag2tT.u(e2,e1, "d"))
693 :     })
694 :    
695 :     ## ddi*: for "Ops" without Arith --> result logical, potentially ldi
696 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "numeric"),
697 :     function(e1,e2) {
698 :     n <- e1@Dim[1]; nsq <- n*n
699 :     f0 <- callGeneric(0, e2)
700 :     if(all(is0(f0))) { # remain diagonal
701 :     L1 <- (le <- length(e2)) == 1L
702 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
703 :     if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
704 :     e1@diag <- "N"
705 :     if(L1) r <- rep.int(r, n)
706 :     } else
707 :     r <- callGeneric(e1@x, e2)
708 :     e1 <- copyClass(e1, "ldiMatrix", c("diag", "Dim", "Dimnames"))
709 :     e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
710 :     return(e1)
711 :     }
712 :     callGeneric(diag2tT.u(e1,e2, "l"), e2)
713 :     })
714 :    
715 :     setMethod("Ops", signature(e1 = "numeric", e2 = "ddiMatrix"),
716 :     function(e1,e2) {
717 :     n <- e2@Dim[1]; nsq <- n*n
718 :     f0 <- callGeneric(e1, 0)
719 :     if(all(is0(f0))) { # remain diagonal
720 :     L1 <- (le <- length(e1)) == 1L
721 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
722 :     if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
723 :     e2@diag <- "N"
724 :     if(L1) r <- rep.int(r, n)
725 :     } else
726 :     r <- callGeneric(e1, e2@x)
727 :     e2 <- copyClass(e2, "ldiMatrix", c("diag", "Dim", "Dimnames"))
728 :     e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
729 :     return(e2)
730 :     }
731 :     callGeneric(e1, diag2tT.u(e2,e1, "l"))
732 :     })
733 :    
734 :     ## ldi*: for "Ops" without Arith --> result logical, potentially ldi
735 : maechler 2144 setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "numeric"),
736 :     function(e1,e2) {
737 :     n <- e1@Dim[1]; nsq <- n*n
738 :     f0 <- callGeneric(FALSE, e2)
739 :     if(all(is0(f0))) { # remain diagonal
740 : maechler 2157 L1 <- (le <- length(e2)) == 1L
741 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
742 :     if(e1@diag == "U" && any((r <- callGeneric(TRUE, e2)) != 1)) {
743 : maechler 2144 e1@diag <- "N"
744 : maechler 2157 if(L1) r <- rep.int(r, n)
745 :     } else
746 : maechler 2144 r <- callGeneric(e1@x, e2)
747 : maechler 2157 e1@x <- if(L1) r else r[1L + n*(0:(n-1L))]
748 : maechler 2144 return(e1)
749 :     }
750 :     callGeneric(diag2tT.u(e1,e2, "l"), e2)
751 :     })
752 : maechler 1655
753 : maechler 2144 setMethod("Ops", signature(e1 = "numeric", e2 = "ldiMatrix"),
754 :     function(e1,e2) {
755 :     n <- e2@Dim[1]; nsq <- n*n
756 :     f0 <- callGeneric(e1, FALSE)
757 :     if(all(is0(f0))) { # remain diagonal
758 : maechler 2157 L1 <- (le <- length(e1)) == 1L
759 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
760 :     if(e2@diag == "U" && any((r <- callGeneric(e1, TRUE)) != 1)) {
761 : maechler 2144 e2@diag <- "N"
762 : maechler 2157 if(L1) r <- rep.int(r, n)
763 :     } else
764 : maechler 2144 r <- callGeneric(e1, e2@x)
765 : maechler 2157 e2@x <- if(L1) r else r[1L + n*(0:(n-1L))]
766 : maechler 2144 return(e2)
767 :     }
768 :     callGeneric(e1, diag2tT.u(e2,e1, "l"))
769 :     })
770 :    
771 :    
772 :    
773 :     ## Not {"sparseMatrix", "numeric} : {"denseMatrix", "matrix", ... }
774 : mmaechler 2196 for(other in c("ANY", "Matrix", "dMatrix")) {
775 :     ## ddi*:
776 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = other),
777 :     function(e1,e2) callGeneric(diag2tT.u(e1,e2, "d"), e2))
778 :     setMethod("Ops", signature(e1 = other, e2 = "ddiMatrix"),
779 :     function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "d")))
780 :     ## ldi*:
781 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = other),
782 :     function(e1,e2) callGeneric(diag2tT.u(e1,e2, "l"), e2))
783 :     setMethod("Ops", signature(e1 = other, e2 = "ldiMatrix"),
784 :     function(e1,e2) callGeneric(e1, diag2tT.u(e2,e1, "l")))
785 :     }
786 : mmaechler 2175 ## This should *not* dispatch to <dense> methods (in ./Ops.R ), as
787 :     ## FALSE & <anything> |-> FALSE : hence result should be diagonal:
788 :     for(cl in diCls) {
789 :     setMethod("&", signature(e1 = cl, e2 = "ANY"),
790 :     function(e1,e2) e1 & as(e2,"Matrix"))
791 :     setMethod("&", signature(e1 = "ANY", e2 = cl),
792 :     function(e1,e2) as(e1,"Matrix") & e2)
793 :     for(c2 in c("denseMatrix", "Matrix")) {
794 :     setMethod("&", signature(e1 = cl, e2 = c2),
795 :     function(e1,e2) e1 & Diagonal(x = diag(e2)))
796 :     setMethod("&", signature(e1 = c2, e2 = cl),
797 :     function(e1,e2) Diagonal(x = diag(e1)) & e2)
798 :     }
799 :     }
800 : maechler 2144
801 :    
802 : mmaechler 2175 ### "Summary" : "max" "min" "range" "prod" "sum" "any" "all"
803 :     ### ---------- any, all: separately here
804 :     for(cl in diCls) {
805 :     setMethod("any", cl,
806 :     function (x, ..., na.rm) {
807 :     if(any(x@Dim == 0)) FALSE
808 :     else if(x@diag == "U") TRUE else any(x@x, ..., na.rm = na.rm)
809 :     })
810 :     setMethod("all", cl, function (x, ..., na.rm) any(x@Dim == 0))
811 :     setMethod("prod", cl, function (x, ..., na.rm) as.numeric(any(x@Dim == 0)))
812 :    
813 :     setMethod("sum", cl,
814 :     function(x, ..., na.rm) {
815 :     r <- sum(x@x, ..., na.rm = na.rm)# double or integer, correctly
816 :     if(x@diag == "U" && !is.na(r)) r + x@Dim[1] else r
817 :     })
818 :     }
819 :    
820 :     ## The remaining ones are max, min, range :
821 :    
822 :     setMethod("Summary", "ddiMatrix",
823 :     function(x, ..., na.rm) {
824 :     if(any(x@Dim == 0)) callGeneric(numeric(0), ..., na.rm=na.rm)
825 :     else if(x@diag == "U")
826 :     callGeneric(x@x, 0, 1, ..., na.rm=na.rm)
827 :     else callGeneric(x@x, 0, ..., na.rm=na.rm)
828 :     })
829 :     setMethod("Summary", "ldiMatrix",
830 :     function(x, ..., na.rm) {
831 :     if(any(x@Dim == 0)) callGeneric(logical(0), ..., na.rm=na.rm)
832 :     else if(x@diag == "U")
833 :     callGeneric(x@x, FALSE, TRUE, ..., na.rm=na.rm)
834 :     else callGeneric(x@x, FALSE, ..., na.rm=na.rm)
835 :     })
836 :    
837 :    
838 :    
839 : maechler 1109 ## similar to prTriang() in ./Auxiliaries.R :
840 :     prDiag <-
841 :     function(x, digits = getOption("digits"), justify = "none", right = TRUE)
842 :     {
843 :     cf <- array(".", dim = x@Dim, dimnames = x@Dimnames)
844 :     cf[row(cf) == col(cf)] <-
845 :     sapply(diag(x), format, digits = digits, justify = justify)
846 :     print(cf, quote = FALSE, right = right)
847 :     invisible(x)
848 :     }
849 :    
850 :     setMethod("show", signature(object = "diagonalMatrix"),
851 : maechler 1592 function(object) {
852 :     d <- dim(object)
853 :     cl <- class(object)
854 :     cat(sprintf('%d x %d diagonal matrix of class "%s"\n',
855 :     d[1], d[2], cl))
856 :     prDiag(object)
857 :     })

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