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 2820 - (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 : mmaechler 2820 ## Allow Diagonal(4), Diagonal(x=1:5), and Diagonal(4, TRUE)
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 : mmaechler 2820 lx.1 <- lx == 1L
21 :     stopifnot(lx.1 || lx == n) # but keep 'x' short for now
22 : maechler 1575 if(is.logical(x))
23 :     cl <- "ldiMatrix"
24 :     else if(is.numeric(x)) {
25 :     cl <- "ddiMatrix"
26 :     x <- as.numeric(x)
27 :     }
28 :     else if(is.complex(x)) {
29 :     cl <- "zdiMatrix" # will not yet work
30 :     } else stop("'x' has invalid data type")
31 : mmaechler 2820 if(lx.1 && !is.na(x) && x == 1) # cheap check for uni-diagonal..
32 :     new(cl, Dim = c(n,n), diag = "U")
33 :     else
34 :     new(cl, Dim = c(n,n), diag = "N",
35 :     x = if(lx.1) rep.int(x,n) else x)
36 : maechler 1109 }
37 :     }
38 :    
39 : mmaechler 2508 .sparseDiagonal <- function(n, x = rep.int(1,m), uplo = "U",
40 :     shape = if(missing(cols)) "t" else "g",
41 :     kind, cols = if(n) 0:(n - 1L) else integer(0))
42 :     {
43 : maechler 2144 stopifnot(n == (n. <- as.integer(n)), (n <- n.) >= 0)
44 : mmaechler 2508 if(!missing(cols))
45 :     stopifnot(0 <= (cols <- as.integer(cols)), cols < n)
46 :     m <- length(cols)
47 :     if(missing(kind))
48 :     kind <-
49 :     if(is.double(x)) "d"
50 :     else if(is.logical(x)) "l"
51 :     else { ## for now
52 :     storage.mode(x) <- "double"
53 :     "d"
54 :     }
55 :     else stopifnot(any(kind == c("d","l","n")))
56 :     if(kind != "n") {
57 :     if((lx <- length(x)) == 1) x <- rep.int(x, m)
58 :     else if(lx != m) stop("length(x) must be either 1 or #{cols}")
59 :     }
60 : mmaechler 2226 stopifnot(is.character(shape), nchar(shape) == 1,
61 :     any(shape == c("t","s","g"))) # triangular / symmetric / general
62 : mmaechler 2508 if(kind == "n") {
63 :     if(shape == "g")
64 :     new("ngCMatrix", Dim = c(n,m), i = cols, p = 0:m)
65 :     else new(paste0("n", shape, "CMatrix"), Dim = c(n,m), uplo = uplo,
66 :     i = cols, p = 0:m)
67 :     }
68 :     ## kind != "n" -- have x slot :
69 :     else if(shape == "g")
70 :     new(paste0(kind, "gCMatrix"), Dim = c(n,m),
71 :     x = x, i = cols, p = 0:m)
72 :     else new(paste0(kind, shape, "CMatrix"), Dim = c(n,m), uplo = uplo,
73 :     x = x, i = cols, p = 0:m)
74 : maechler 2144 }
75 :    
76 : mmaechler 2226 ## Pkg 'spdep' had (relatively slow) versions of this as_dsCMatrix_I()
77 :     .symDiagonal <- function(n, x = rep.int(1,n), uplo = "U")
78 :     .sparseDiagonal(n, x, uplo, shape = "s")
79 :    
80 : mmaechler 2608 # instead of diagU2N(as(Diagonal(n), "CsparseMatrix")), diag = "N" in any case:
81 : mmaechler 2226 .trDiagonal <- function(n, x = rep.int(1,n), uplo = "U")
82 :     .sparseDiagonal(n, x, uplo, shape = "t")
83 :    
84 :    
85 : mmaechler 2764 ## This is modified from a post of Bert Gunter to R-help on 1 Sep 2005.
86 :     ## Bert's code built on a post by Andy Liaw who most probably was influenced
87 :     ## by earlier posts, notably one by Scott Chasalow on S-news, 16 Jan 2002
88 :     ## who posted his bdiag() function written in December 1995.
89 : mmaechler 2209 if(FALSE)##--- no longer used:
90 : mmaechler 2206 .bdiag <- function(lst) {
91 : mmaechler 2764 ## block-diagonal matrix [a dgTMatrix] from list of matrices
92 : mmaechler 2206 stopifnot(is.list(lst), length(lst) >= 1)
93 : mmaechler 2813 dims <- vapply(lst, dim, 1L, USE.NAMES=FALSE)
94 : maechler 1617 ## make sure we had all matrices:
95 :     if(!(is.matrix(dims) && nrow(dims) == 2))
96 :     stop("some arguments are not matrices")
97 : maechler 1845 csdim <- rbind(rep.int(0L, 2),
98 : mmaechler 2206 apply(dims, 1, cumsum))
99 :     r <- new("dgTMatrix")
100 :     r@Dim <- as.integer(csdim[nrow(csdim),])
101 : maechler 1617 add1 <- matrix(1:0, 2,2)
102 : mmaechler 2206 for(i in seq_along(lst)) {
103 : maechler 1617 indx <- apply(csdim[i:(i+1),] + add1, 2, function(n) n[1]:n[2])
104 :     if(is.null(dim(indx))) ## non-square matrix
105 : mmaechler 2206 r[indx[[1]],indx[[2]]] <- lst[[i]]
106 : maechler 1617 else ## square matrix
107 : mmaechler 2206 r[indx[,1], indx[,2]] <- lst[[i]]
108 : maechler 1617 }
109 : mmaechler 2206 r
110 : maechler 1617 }
111 : mmaechler 2209 ## expand(<mer>) needed something like bdiag() for lower-triangular
112 :     ## (Tsparse) Matrices; hence Doug Bates provided a much more efficient
113 :     ## implementation for those; now extended and generalized:
114 : mmaechler 2206 .bdiag <- function(lst) {
115 : mmaechler 2209 ## block-diagonal matrix [a dgTMatrix] from list of matrices
116 : mmaechler 2206 stopifnot(is.list(lst), (nl <- length(lst)) >= 1)
117 : maechler 1617
118 : mmaechler 2206 Tlst <- lapply(lapply(lst, Matrix:::as_Csp2), # includes "diagU2N"
119 : mmaechler 2209 as, "TsparseMatrix")
120 : mmaechler 2206 if(nl == 1) return(Tlst[[1]])
121 :     ## else
122 : mmaechler 2813 i_off <- c(0L, cumsum(vapply(Tlst, nrow, 1L)))
123 :     j_off <- c(0L, cumsum(vapply(Tlst, ncol, 1L)))
124 : mmaechler 2209
125 : mmaechler 2813 clss <- vapply(Tlst, class, "")
126 : mmaechler 2741 typ <- substr(clss, 2, 2)
127 :     knd <- substr(clss, 1, 1)
128 :     sym <- typ == "s" # symmetric ones
129 :     tri <- typ == "t" # triangular ones
130 :     use.n <- any(is.n <- knd == "n")
131 :     if(use.n && !(use.n <- all(is.n))) {
132 : mmaechler 2209 Tlst[is.n] <- lapply(Tlst[is.n], as, "lMatrix")
133 : mmaechler 2741 knd [is.n] <- "l"
134 :     }
135 :     use.l <- !use.n && all(knd == "l")
136 : mmaechler 2209 if(all(sym)) { ## result should be *symmetric*
137 : mmaechler 2813 uplos <- vapply(Tlst, slot, ".", "uplo") ## either "U" or "L"
138 : mmaechler 2209 tLU <- table(uplos)# of length 1 or 2 ..
139 :     if(length(tLU) == 1) { ## all "U" or all "L"
140 :     useU <- uplos[1] == "U"
141 :     } else { ## length(tLU) == 2, counting "L" and "U"
142 :     useU <- diff(tLU) >= 0
143 :     if(useU && (hasL <- tLU[1] > 0))
144 :     Tlst[hasL] <- lapply(Tlst[hasL], t)
145 :     else if(!useU && (hasU <- tLU[2] > 0))
146 :     Tlst[hasU] <- lapply(Tlst[hasU], t)
147 :     }
148 :     if(use.n) { ## return nsparseMatrix :
149 :     r <- new("nsTMatrix")
150 :     } else {
151 : mmaechler 2741 r <- new(paste0(if(use.l) "l" else "d", "sTMatrix"))
152 : mmaechler 2209 r@x <- unlist(lapply(Tlst, slot, "x"))
153 :     }
154 :     r@uplo <- if(useU) "U" else "L"
155 :     }
156 : mmaechler 2813 else if(all(tri) && { ULs <- vapply(Tlst, slot, ".", "uplo")## "U" or "L"
157 : mmaechler 2209 all(ULs[1L] == ULs[-1L]) } ## all upper or all lower
158 :     ){ ## *triangular* result
159 :    
160 :     if(use.n) { ## return nsparseMatrix :
161 :     r <- new("ntTMatrix")
162 :     } else {
163 : mmaechler 2741 r <- new(paste0(if(use.l) "l" else "d", "tTMatrix"))
164 : mmaechler 2209 r@x <- unlist(lapply(Tlst, slot, "x"))
165 :     }
166 :     r@uplo <- ULs[1L]
167 :     }
168 :     else {
169 :     if(any(sym))
170 :     Tlst[sym] <- lapply(Tlst[sym], as, "generalMatrix")
171 :     if(use.n) { ## return nsparseMatrix :
172 :     r <- new("ngTMatrix")
173 :     } else {
174 : mmaechler 2741 r <- new(paste0(if(use.l) "l" else "d", "gTMatrix"))
175 : mmaechler 2209 r@x <- unlist(lapply(Tlst, slot, "x"))
176 :     }
177 :     }
178 :     r@Dim <- c(i_off[nl+1], j_off[nl + 1])
179 :     r@i <- unlist(lapply(1:nl, function(k) Tlst[[k]]@i + i_off[k]))
180 :     r@j <- unlist(lapply(1:nl, function(k) Tlst[[k]]@j + j_off[k]))
181 :     r
182 : mmaechler 2206 }
183 :    
184 :     bdiag <- function(...) {
185 :     if((nA <- nargs()) == 0) return(new("dgCMatrix"))
186 :     if(nA == 1 && !is.list(...))
187 :     return(as(..., "CsparseMatrix"))
188 :     alis <- if(nA == 1 && is.list(..1)) ..1 else list(...)
189 :     if(length(alis) == 1)
190 :     return(as(alis[[1]], "CsparseMatrix"))
191 :    
192 :     ## else : two or more arguments
193 :     as(.bdiag(alis), "CsparseMatrix")
194 :     }
195 :    
196 :    
197 : maechler 2136 .diag2tT <- function(from, uplo = "U", kind = .M.kind(from)) {
198 :     ## to triangular Tsparse
199 : maechler 1845 i <- if(from@diag == "U") integer(0) else seq_len(from@Dim[1]) - 1L
200 : mmaechler 2778 new(paste0(kind, "tTMatrix"),
201 : maechler 1654 diag = from@diag, Dim = from@Dim, Dimnames = from@Dimnames,
202 : maechler 2128 uplo = uplo,
203 : maechler 1654 x = from@x, # <- ok for diag = "U" and "N" (!)
204 :     i = i, j = i)
205 :     }
206 : maechler 1109
207 : maechler 2136 .diag2sT <- function(from, uplo = "U", kind = .M.kind(from)) {
208 :     ## to symmetric Tsparse
209 : maechler 2128 n <- from@Dim[1]
210 :     i <- seq_len(n) - 1L
211 : mmaechler 2778 new(paste0(kind, "sTMatrix"),
212 : maechler 1845 Dim = from@Dim, Dimnames = from@Dimnames,
213 : maechler 2128 i = i, j = i, uplo = uplo,
214 :     x = if(from@diag == "N") from@x else ## "U"-diag
215 :     rep.int(switch(kind,
216 :     "d" = 1.,
217 :     "l" =,
218 :     "n" = TRUE,
219 :     ## otherwise
220 :     stop("'", kind,"' kind not yet implemented")), n))
221 : maechler 1845 }
222 :    
223 : maechler 2128 ## diagonal -> triangular, upper / lower depending on "partner":
224 : maechler 2144 diag2tT.u <- function(d, x, kind = .M.kind(d))
225 :     .diag2tT(d, uplo = if(is(x,"triangularMatrix")) x@uplo else "U", kind)
226 : maechler 2128
227 : mmaechler 2175 ## diagonal -> sparse {triangular OR symmetric} (upper / lower) depending on "partner":
228 :     diag2Tsmart <- function(d, x, kind = .M.kind(d)) {
229 :     clx <- getClassDef(class(x))
230 :     if(extends(clx, "symmetricMatrix"))
231 :     .diag2sT(d, uplo = x@uplo, kind)
232 :     else
233 :     .diag2tT(d, uplo = if(extends(clx,"triangularMatrix")) x@uplo else "U", kind)
234 :     }
235 : maechler 2136
236 : mmaechler 2814 ## FIXME: should not be needed {when ddi* is dsparse* etc}:
237 :     setMethod("is.finite", signature(x = "diagonalMatrix"),
238 :     function(x) is.finite(.diag2tT(x)))
239 :     setMethod("is.infinite", signature(x = "diagonalMatrix"),
240 :     function(x) is.infinite(.diag2tT(x)))
241 : mmaechler 2175
242 : maechler 2136 ## In order to evade method dispatch ambiguity warnings,
243 :     ## and because we can save a .M.kind() call, we use this explicit
244 :     ## "hack" instead of signature x = "diagonalMatrix" :
245 :     ##
246 :     ## ddi*:
247 :     diag2tT <- function(from) .diag2tT(from, "U", "d")
248 :     setAs("ddiMatrix", "triangularMatrix", diag2tT)
249 : mmaechler 2239 ##_no_longer_ setAs("ddiMatrix", "sparseMatrix", diag2tT)
250 : maechler 1805 ## needed too (otherwise <dense> -> Tsparse is taken):
251 : maechler 2136 setAs("ddiMatrix", "TsparseMatrix", diag2tT)
252 : mmaechler 2482 setAs("ddiMatrix", "dsparseMatrix", diag2tT)
253 : maechler 2136 setAs("ddiMatrix", "CsparseMatrix",
254 :     function(from) as(.diag2tT(from, "U", "d"), "CsparseMatrix"))
255 :     setAs("ddiMatrix", "symmetricMatrix",
256 :     function(from) .diag2sT(from, "U", "d"))
257 :     ##
258 :     ## ldi*:
259 :     diag2tT <- function(from) .diag2tT(from, "U", "l")
260 :     setAs("ldiMatrix", "triangularMatrix", diag2tT)
261 : mmaechler 2239 ##_no_longer_ setAs("ldiMatrix", "sparseMatrix", diag2tT)
262 : maechler 2136 ## needed too (otherwise <dense> -> Tsparse is taken):
263 :     setAs("ldiMatrix", "TsparseMatrix", diag2tT)
264 : mmaechler 2482 setAs("ldiMatrix", "lsparseMatrix", diag2tT)
265 : maechler 2136 setAs("ldiMatrix", "CsparseMatrix",
266 :     function(from) as(.diag2tT(from, "U", "l"), "CsparseMatrix"))
267 :     setAs("ldiMatrix", "symmetricMatrix",
268 :     function(from) .diag2sT(from, "U", "l"))
269 : maechler 1654
270 : maechler 1845
271 : maechler 2128 setAs("diagonalMatrix", "nMatrix",
272 :     function(from) {
273 :     n <- from@Dim[1]
274 :     i <- if(from@diag == "U") integer(0) else which(isN0(from@x)) - 1L
275 :     new("ntTMatrix", i = i, j = i, diag = from@diag,
276 :     Dim = from@Dim, Dimnames = from@Dimnames)
277 :     })
278 :    
279 : mmaechler 2237 setAs("diagonalMatrix", "nsparseMatrix", function(from) as(from, "nMatrix"))
280 : maechler 2128
281 : mmaechler 2175 ## Cheap fast substitute for diag() which *does* preserve the mode of x :
282 :     mkDiag <- function(x, n) {
283 :     y <- matrix(as0(mod=mode(x)), n,n)
284 : mmaechler 2820 if (n > 0) y[1L + 0:(n - 1L) * (n + 1)] <- x
285 : mmaechler 2175 y
286 :     }
287 :    
288 : maechler 1109 setAs("diagonalMatrix", "matrix",
289 :     function(from) {
290 : mmaechler 2175 ## want "ldiMatrix" -> <logical> "matrix" :
291 :     mkDiag(if(from@diag == "U") as1(from@x) else from@x,
292 :     n = from@Dim[1])
293 : maechler 1109 })
294 :    
295 : maechler 2098 setMethod("as.vector", signature(x = "diagonalMatrix", mode="missing"),
296 :     function(x, mode) {
297 :     n <- x@Dim[1]
298 : mmaechler 2175 mod.x <- mode(x@x)
299 :     r <- vector(mod.x, length = n^2)
300 : maechler 2098 if(n)
301 : mmaechler 2820 r[1 + 0:(n - 1L) * (n + 1)] <-
302 : mmaechler 2175 if(x@diag == "U") as1(mod=mod.x) else x@x
303 : maechler 2098 r
304 :     })
305 :    
306 : maechler 1654 setAs("diagonalMatrix", "generalMatrix", # prefer sparse:
307 : maechler 2128 function(from) as(as(from, "CsparseMatrix"), "generalMatrix"))
308 : maechler 1174
309 : mmaechler 2268 setAs("diagonalMatrix", "denseMatrix",
310 :     function(from) as(as(from, "CsparseMatrix"), "denseMatrix"))
311 :    
312 : mmaechler 2185 .diag.x <- function(m) if(m@diag == "U") rep.int(as1(m@x), m@Dim[1]) else m@x
313 : maechler 1655
314 :     .diag.2N <- function(m) {
315 :     if(m@diag == "U") m@diag <- "N"
316 :     m
317 :     }
318 :    
319 : maechler 1174 setAs("ddiMatrix", "dgeMatrix",
320 : mmaechler 2183 function(from) .Call(dup_mMatrix_as_dgeMatrix, from))
321 :     setAs("ddiMatrix", "ddenseMatrix",
322 :     function(from) as(as(from, "triangularMatrix"),"denseMatrix"))
323 :     setAs("ldiMatrix", "ldenseMatrix",
324 :     function(from) as(as(from, "triangularMatrix"),"denseMatrix"))
325 : maechler 1174
326 : mmaechler 2183
327 : maechler 1109 setAs("matrix", "diagonalMatrix",
328 :     function(from) {
329 : maechler 1295 d <- dim(from)
330 : maechler 1109 if(d[1] != (n <- d[2])) stop("non-square matrix")
331 :     if(any(from[row(from) != col(from)] != 0))
332 : mmaechler 2341 stop("matrix with non-zero off-diagonals cannot be coerced to diagonalMatrix")
333 : maechler 1295 x <- diag(from)
334 :     if(is.logical(x)) {
335 :     cl <- "ldiMatrix"
336 : mmaechler 2341 uni <- allTrue(x) ## uni := {is it unit-diagonal ?}
337 : maechler 1295 } else {
338 :     cl <- "ddiMatrix"
339 : mmaechler 2341 uni <- allTrue(x == 1)
340 : maechler 1295 storage.mode(x) <- "double"
341 : maechler 1575 } ## TODO: complex
342 : maechler 1295 new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
343 :     x = if(uni) x[FALSE] else x)
344 : maechler 1109 })
345 :    
346 :     ## ``generic'' coercion to diagonalMatrix : build on isDiagonal() and diag()
347 :     setAs("Matrix", "diagonalMatrix",
348 :     function(from) {
349 : mmaechler 2341 d <- dim(from)
350 : maechler 1109 if(d[1] != (n <- d[2])) stop("non-square matrix")
351 : mmaechler 2341 if(!isDiagonal(from)) stop("matrix is not diagonal")
352 :     ## else:
353 :     x <- diag(from)
354 :     if(is.logical(x)) {
355 :     cl <- "ldiMatrix"
356 :     uni <- allTrue(x)
357 :     } else {
358 :     cl <- "ddiMatrix"
359 :     uni <- allTrue(x == 1)
360 :     storage.mode(x) <- "double"
361 :     } ## TODO: complex
362 :     new(cl, Dim = c(n,n), diag = if(uni) "U" else "N",
363 :     x = if(uni) x[FALSE] else x)
364 : maechler 1109 })
365 :    
366 : maechler 1708
367 : mmaechler 2185 setMethod("diag", signature(x = "diagonalMatrix"),
368 :     function(x = 1, nrow, ncol) .diag.x(x))
369 : maechler 1708
370 : maechler 2098 subDiag <- function(x, i, j, ..., drop) {
371 : mmaechler 2508 x <- as(x, "CsparseMatrix") ## << was "TsparseMatrix" (Csparse is faster now)
372 : maechler 1799 x <- if(missing(i))
373 :     x[, j, drop=drop]
374 :     else if(missing(j))
375 : mmaechler 2363 if(nargs() == 4) x[i, , drop=drop] else x[i, drop=drop]
376 : maechler 1799 else
377 :     x[i,j, drop=drop]
378 : maechler 2120 if(isS4(x) && isDiagonal(x)) as(x, "diagonalMatrix") else x
379 : maechler 1799 }
380 :    
381 :     setMethod("[", signature(x = "diagonalMatrix", i = "index",
382 :     j = "index", drop = "logical"), subDiag)
383 :     setMethod("[", signature(x = "diagonalMatrix", i = "index",
384 : mmaechler 2363 j = "missing", drop = "logical"),
385 :     function(x, i, j, ..., drop) {
386 :     na <- nargs()
387 :     Matrix.msg("diag[i,m,l] : nargs()=", na, .M.level = 2)
388 :     if(na == 4)
389 :     subDiag(x, i=i, , drop=drop)
390 :     else subDiag(x, i=i, drop=drop)
391 :     })
392 : maechler 1799 setMethod("[", signature(x = "diagonalMatrix", i = "missing",
393 :     j = "index", drop = "logical"),
394 : maechler 2098 function(x, i, j, ..., drop) subDiag(x, j=j, drop=drop))
395 : maechler 1799
396 : maechler 1617 ## When you assign to a diagonalMatrix, the result should be
397 : maechler 1708 ## diagonal or sparse ---
398 :     ## FIXME: this now fails because the "denseMatrix" methods come first in dispatch
399 : maechler 2098 ## Only(?) current bug: x[i] <- value is wrong when i is *vector*
400 :     replDiag <- function(x, i, j, ..., value) {
401 : mmaechler 2811 x <- as(x, "CsparseMatrix")# was "Tsparse.." till 2012-07
402 : maechler 1710 if(missing(i))
403 :     x[, j] <- value
404 : maechler 2098 else if(missing(j)) { ## x[i , ] <- v *OR* x[i] <- v
405 :     na <- nargs()
406 :     ## message("diagnosing replDiag() -- nargs()= ", na)
407 :     if(na == 4)
408 :     x[i, ] <- value
409 :     else if(na == 3)
410 :     x[i] <- value
411 :     else stop("Internal bug: nargs()=",na,"; please report")
412 :     } else
413 : maechler 1710 x[i,j] <- value
414 :     if(isDiagonal(x)) as(x, "diagonalMatrix") else x
415 :     }
416 : maechler 1617
417 : maechler 1710 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
418 :     j = "index", value = "replValue"), replDiag)
419 : maechler 2098
420 : maechler 1710 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index",
421 :     j = "missing", value = "replValue"),
422 : maechler 2098 function(x,i,j, ..., value) {
423 :     ## message("before replDiag() -- nargs()= ", nargs())
424 :     if(nargs() == 3)
425 :     replDiag(x, i=i, value=value)
426 :     else ## nargs() == 4 :
427 :     replDiag(x, i=i, , value=value)
428 :     })
429 :    
430 : mmaechler 2192 setReplaceMethod("[", signature(x = "diagonalMatrix",
431 :     i = "matrix", # 2-col.matrix
432 : maechler 2096 j = "missing", value = "replValue"),
433 : maechler 2098 function(x,i,j, ..., value) {
434 : maechler 2096 if(ncol(i) == 2) {
435 :     if(all((ii <- i[,1]) == i[,2])) { # replace in diagonal only
436 : mmaechler 2192 if(x@diag == "U") {
437 :     one <- as1(x@x)
438 :     if(any(value != one | is.na(value))) {
439 :     x@diag <- "N"
440 :     x@x <- rep.int(one, x@Dim[1])
441 : mmaechler 2811 } else return(x)
442 : mmaechler 2192 }
443 : maechler 2096 x@x[ii] <- value
444 :     x
445 :     } else { ## no longer diagonal, but remain sparse:
446 : mmaechler 2239 x <- as(x, "TsparseMatrix")
447 : maechler 2096 x[i] <- value
448 :     x
449 :     }
450 :     }
451 :     else { # behave as "base R": use as if vector
452 :     x <- as(x, "matrix")
453 :     x[i] <- value
454 :     Matrix(x)
455 :     }
456 :     })
457 :    
458 : maechler 1710 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing",
459 :     j = "index", value = "replValue"),
460 : maechler 2098 function(x,i,j, ..., value) replDiag(x, j=j, value=value))
461 : maechler 1710
462 : mmaechler 2207 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing", j = "index",
463 : mmaechler 2239 value = "sparseMatrix"),
464 : mmaechler 2207 function (x, i, j, ..., value)
465 :     callGeneric(x=x, , j=j, value = as(value, "sparseVector")))
466 :     setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "missing",
467 : mmaechler 2239 value = "sparseMatrix"),
468 : mmaechler 2207 function (x, i, j, ..., value)
469 :     callGeneric(x=x, i=i, , value = as(value, "sparseVector")))
470 :     setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "index",
471 : mmaechler 2239 value = "sparseMatrix"),
472 : mmaechler 2207 function (x, i, j, ..., value)
473 :     callGeneric(x=x, i=i, j=j, value = as(value, "sparseVector")))
474 : maechler 1710
475 : mmaechler 2207 setReplaceMethod("[", signature(x = "diagonalMatrix", i = "missing", j = "index",
476 :     value = "sparseVector"),
477 :     replDiag)
478 :     setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "missing",
479 :     value = "sparseVector"),
480 :     replDiag)
481 :     setReplaceMethod("[", signature(x = "diagonalMatrix", i = "index", j = "index",
482 :     value = "sparseVector"),
483 :     replDiag)
484 :    
485 :    
486 : maechler 1109 setMethod("t", signature(x = "diagonalMatrix"),
487 :     function(x) { x@Dimnames <- x@Dimnames[2:1] ; x })
488 :    
489 : maechler 1331 setMethod("isDiagonal", signature(object = "diagonalMatrix"),
490 :     function(object) TRUE)
491 :     setMethod("isTriangular", signature(object = "diagonalMatrix"),
492 :     function(object) TRUE)
493 : maechler 1109 setMethod("isSymmetric", signature(object = "diagonalMatrix"),
494 : maechler 2112 function(object, ...) TRUE)
495 : maechler 1109
496 : maechler 2112 setMethod("symmpart", signature(x = "diagonalMatrix"), function(x) x)
497 :     setMethod("skewpart", signature(x = "diagonalMatrix"), setZero)
498 :    
499 : maechler 2133 setMethod("chol", signature(x = "ddiMatrix"),
500 :     function(x, pivot, ...) {
501 : mmaechler 2183 if(x@diag == "U") return(x)
502 :     ## else
503 : maechler 2133 if(any(x@x < 0))
504 :     stop("chol() is undefined for diagonal matrix with negative entries")
505 : maechler 1654 x@x <- sqrt(x@x)
506 :     x
507 :     })
508 :     ## chol(L) is L for logical diagonal:
509 : maechler 2133 setMethod("chol", signature(x = "ldiMatrix"), function(x, pivot, ...) x)
510 : maechler 1654
511 : mmaechler 2175 setMethod("determinant", signature(x = "diagonalMatrix", logarithm = "logical"),
512 : mmaechler 2185 function(x, logarithm, ...) mkDet(.diag.x(x), logarithm))
513 : mmaechler 2175
514 : mmaechler 2183 setMethod("norm", signature(x = "diagonalMatrix", type = "character"),
515 :     function(x, type, ...) {
516 :     if((n <- x@Dim[1]) == 0) return(0) # as for "sparseMatrix"
517 :     type <- toupper(substr(type[1], 1, 1))
518 :     isU <- (x@diag == "U") # unit-diagonal
519 :     if(type == "F") sqrt(if(isU) n else sum(x@x^2))
520 :     else { ## norm == "I","1","O","M" :
521 :     if(isU) 1 else max(abs(x@x))
522 :     }
523 :     })
524 :    
525 :    
526 :    
527 : maechler 1109 ## Basic Matrix Multiplication {many more to add}
528 : maechler 1654 ## ---------------------
529 :     ## Note that "ldi" logical are treated as numeric
530 : maechler 1109 diagdiagprod <- function(x, y) {
531 : mmaechler 2633 dimCheck(x,y)
532 : maechler 1109 if(x@diag != "U") {
533 : maechler 1654 if(y@diag != "U") {
534 :     nx <- x@x * y@x
535 :     if(is.numeric(nx) && !is.numeric(x@x))
536 :     x <- as(x, "dMatrix")
537 :     x@x <- as.numeric(nx)
538 :     }
539 :     return(x)
540 : maechler 1109 } else ## x is unit diagonal
541 :     return(y)
542 :     }
543 :    
544 : maechler 1654 setMethod("%*%", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
545 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
546 :    
547 : maechler 1654 formals(diagdiagprod) <- alist(x=, y=x)
548 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
549 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
550 : maechler 1654 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "diagonalMatrix"),
551 : maechler 1109 diagdiagprod, valueClass = "ddiMatrix")
552 : maechler 1654 setMethod("crossprod", signature(x = "diagonalMatrix", y = "missing"),
553 :     diagdiagprod, valueClass = "ddiMatrix")
554 :     setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "missing"),
555 :     diagdiagprod, valueClass = "ddiMatrix")
556 : maechler 1109
557 :    
558 :     diagmatprod <- function(x, y) {
559 : mmaechler 2183 ## x is diagonalMatrix
560 : maechler 1109 dx <- dim(x)
561 :     dy <- dim(y)
562 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
563 :     as(if(x@diag == "U") y else x@x * y, "Matrix")
564 :     }
565 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "matrix"),
566 : maechler 1654 diagmatprod)
567 : mmaechler 2183 ## sneaky .. :
568 : maechler 1109 formals(diagmatprod) <- alist(x=, y=NULL)
569 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "matrix"),
570 : maechler 1654 diagmatprod)
571 : maechler 1109
572 : mmaechler 2183 diagGeprod <- function(x, y) {
573 : maechler 1109 dx <- dim(x)
574 :     dy <- dim(y)
575 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
576 :     if(x@diag != "U")
577 :     y@x <- x@x * y@x
578 :     y
579 :     }
580 : mmaechler 2183 setMethod("%*%", signature(x= "diagonalMatrix", y= "dgeMatrix"), diagGeprod)
581 :     setMethod("%*%", signature(x= "diagonalMatrix", y= "lgeMatrix"), diagGeprod)
582 :     formals(diagGeprod) <- alist(x=, y=NULL)
583 : maechler 1109 setMethod("crossprod", signature(x = "diagonalMatrix", y = "dgeMatrix"),
584 : mmaechler 2183 diagGeprod, valueClass = "dgeMatrix")
585 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "lgeMatrix"),
586 :     diagGeprod)
587 : maechler 1109
588 : mmaechler 2183 matdiagprod <- function(x, y) {
589 :     dx <- dim(x)
590 :     dy <- dim(y)
591 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
592 :     Matrix(if(y@diag == "U") x else x * rep(y@x, each = dx[1]))
593 :     }
594 : maechler 1109 setMethod("%*%", signature(x = "matrix", y = "diagonalMatrix"),
595 : mmaechler 2183 matdiagprod)
596 :     formals(matdiagprod) <- alist(x=, y=NULL)
597 :     setMethod("tcrossprod", signature(x = "matrix", y = "diagonalMatrix"),
598 :     matdiagprod)
599 : maechler 1109
600 : mmaechler 2183 gediagprod <- function(x, y) {
601 :     dx <- dim(x)
602 :     dy <- dim(y)
603 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
604 :     if(y@diag == "N")
605 :     x@x <- x@x * rep(y@x, each = dx[1])
606 :     x
607 :     }
608 :     setMethod("%*%", signature(x= "dgeMatrix", y= "diagonalMatrix"), gediagprod)
609 :     setMethod("%*%", signature(x= "lgeMatrix", y= "diagonalMatrix"), gediagprod)
610 :     formals(gediagprod) <- alist(x=, y=NULL)
611 :     setMethod("tcrossprod", signature(x = "dgeMatrix", y = "diagonalMatrix"),
612 :     gediagprod)
613 :     setMethod("tcrossprod", signature(x = "lgeMatrix", y = "diagonalMatrix"),
614 :     gediagprod)
615 : maechler 1109
616 : maechler 1295 ## crossprod {more of these}
617 : maechler 1109
618 : maechler 1295 ## tcrossprod --- all are not yet there: do the dense ones here:
619 : maechler 1109
620 : mmaechler 2183 setMethod("%*%", signature(x = "diagonalMatrix", y = "denseMatrix"),
621 :     function(x, y) if(x@diag == "U") y else x %*% as(y, "generalMatrix"))
622 :     setMethod("%*%", signature(x = "denseMatrix", y = "diagonalMatrix"),
623 :     function(x, y) if(y@diag == "U") x else as(x, "generalMatrix") %*% y)
624 :    
625 :    
626 : maechler 1295 ## FIXME:
627 :     ## setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "denseMatrix"),
628 :     ## function(x, y = NULL) {
629 :     ## })
630 : maechler 1109
631 : dmbates 2417 Cspdiagprod <- function(x, y) {
632 : dmbates 2458 dx <- dim(x <- .Call(Csparse_diagU2N, x))
633 : dmbates 2417 dy <- dim(y)
634 :     if(dx[2] != dy[1]) stop("non-matching dimensions")
635 : mmaechler 2674 if(y@diag == "N") {
636 :     if(!all(y@x[1L] == y@x[-1L]) && is(x, "symmetricMatrix"))
637 :     x <- as(x, "generalMatrix")
638 :     ind <- rep.int(seq_len(dx[2]), x@p[-1] - x@p[-dx[2]-1L])
639 :     x@x <- x@x * y@x[ind]
640 :     }
641 : mmaechler 2608 if(is(x, "compMatrix") && length(xf <- x@factors)) {
642 :     ## instead of dropping all factors, be smart about some
643 :     ## TODO ......
644 :     x@factors <- list()
645 :     }
646 : dmbates 2417 x
647 :     }
648 : maechler 1109
649 : dmbates 2417 diagCspprod <- function(x, y) {
650 :     dx <- dim(x)
651 : dmbates 2458 dy <- dim(y <- .Call(Csparse_diagU2N, y))
652 : dmbates 2417 if(dx[2] != dy[1]) stop("non-matching dimensions")
653 : mmaechler 2674 if(x@diag == "N") {
654 :     if(!all(x@x[1L] == x@x[-1L]) && is(y, "symmetricMatrix"))
655 :     y <- as(y, "generalMatrix")
656 :     y@x <- y@x * x@x[y@i + 1L]
657 :     }
658 : mmaechler 2608 if(is(y, "compMatrix") && length(yf <- y@factors)) {
659 :     ## instead of dropping all factors, be smart about some
660 :     ## TODO
661 :     keep <- character()
662 :     if(iLU <- names(yf) == "LU") {
663 :     ## TODO keep <- "LU"
664 :     }
665 :     y@factors <- yf[keep]
666 :     }
667 : dmbates 2417 y
668 :     }
669 :    
670 :     setMethod("crossprod", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
671 :     function(x, y = NULL) diagCspprod(x, y))
672 :    
673 : maechler 1799 setMethod("crossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
674 : dmbates 2417 function(x, y = NULL) diagCspprod(x, as(y, "CsparseMatrix")))
675 : maechler 1295
676 : dmbates 2417 ## Prefer calling diagCspprod to Cspdiagprod if going to transpose anyway
677 :     ## x'y == (y'x)'
678 :     setMethod("crossprod", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
679 :     function(x, y = NULL) t(diagCspprod(y, x)))
680 :    
681 : maechler 1799 setMethod("crossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
682 : dmbates 2417 function(x, y = NULL) t(diagCspprod(y, as(x, "Csparsematrix"))))
683 : maechler 1799
684 : dmbates 2417 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
685 :     function(x, y = NULL) diagCspprod(x, t(y)))
686 :    
687 : maechler 1799 setMethod("tcrossprod", signature(x = "diagonalMatrix", y = "sparseMatrix"),
688 : dmbates 2417 function(x, y = NULL) diagCspprod(x, t(as(y, "CsparseMatrix"))))
689 : maechler 1799
690 : dmbates 2417 setMethod("tcrossprod", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
691 :     function(x, y = NULL) Cspdiagprod(x, y))
692 :    
693 : maechler 1799 setMethod("tcrossprod", signature(x = "sparseMatrix", y = "diagonalMatrix"),
694 : dmbates 2417 function(x, y = NULL) Cspdiagprod(as(x, "CsparseMatrix"), y))
695 : mmaechler 2472
696 : dmbates 2417 setMethod("%*%", signature(x = "diagonalMatrix", y = "CsparseMatrix"),
697 :     function(x, y) diagCspprod(x, y))
698 : maechler 1799
699 :     setMethod("%*%", signature(x = "diagonalMatrix", y = "sparseMatrix"),
700 : dmbates 2417 function(x, y) diagCspprod(as(x, "CsparseMatrix"), y))
701 : mmaechler 2472
702 : mmaechler 2183 setMethod("%*%", signature(x = "sparseMatrix", y = "diagonalMatrix"),
703 : dmbates 2417 function(x, y) Cspdiagprod(as(x, "CsparseMatrix"), y))
704 :    
705 : maechler 1799 setMethod("%*%", signature(x = "CsparseMatrix", y = "diagonalMatrix"),
706 : dmbates 2417 function(x, y) Cspdiagprod(x, y))
707 :    
708 : maechler 1799 ## TODO: Write tests in ./tests/ which ensure that many "ops" with diagonal*
709 :     ## do indeed work by going through sparse (and *not* ddense)!
710 :    
711 :     setMethod("solve", signature(a = "diagonalMatrix", b = "missing"),
712 :     function(a, b, ...) {
713 :     a@x <- 1/ a@x
714 :     a@Dimnames <- a@Dimnames[2:1]
715 :     a
716 :     })
717 :    
718 :     solveDiag <- function(a, b, ...) {
719 : mmaechler 2633 if(a@Dim[1] != nrow(b))
720 : maechler 1799 stop("incompatible matrix dimensions")
721 :     ## trivially invert a 'in place' and multiply:
722 :     a@x <- 1/ a@x
723 :     a@Dimnames <- a@Dimnames[2:1]
724 :     a %*% b
725 :     }
726 :     setMethod("solve", signature(a = "diagonalMatrix", b = "matrix"),
727 :     solveDiag)
728 :     setMethod("solve", signature(a = "diagonalMatrix", b = "Matrix"),
729 :     solveDiag)
730 :    
731 : maechler 2106 ## Schur() ---> ./eigen.R
732 : maechler 1799
733 :    
734 :    
735 : mmaechler 2175 ###---------------- <Ops> (<Arith>, <Logic>, <Compare> ) ----------------------
736 : maechler 1295
737 : maechler 1655 ## Use function for several signatures, in order to evade
738 : mmaechler 2175 diagOdiag <- function(e1,e2) {
739 :     ## result should also be diagonal _ if possible _
740 : maechler 1655 r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"
741 : mmaechler 2175 ## Check what happens with non-diagonals, i.e. (0 o 0), (FALSE o 0), ...:
742 :     r00 <- callGeneric(if(is.numeric(e1@x)) 0 else FALSE,
743 :     if(is.numeric(e2@x)) 0 else FALSE)
744 :     if(is0(r00)) { ## r00 == 0 or FALSE --- result *is* diagonal
745 : mmaechler 2814 if(is.numeric(r)) { # "double" *or* "integer"
746 : mmaechler 2175 if(is.numeric(e2@x)) {
747 :     e2@x <- r; return(.diag.2N(e2)) }
748 :     if(!is.numeric(e1@x))
749 :     ## e.g. e1, e2 are logical;
750 :     e1 <- as(e1, "dMatrix")
751 : mmaechler 2814 if(!is.double(r)) r <- as.double(r)
752 : mmaechler 2175 }
753 :     else if(is.logical(r))
754 :     e1 <- as(e1, "lMatrix")
755 :     else stop("intermediate 'r' is of type", typeof(r))
756 :     e1@x <- r
757 :     .diag.2N(e1)
758 : maechler 1655 }
759 : mmaechler 2175 else { ## result not diagonal, but at least symmetric:
760 : mmaechler 2496 ## e.g., m == m
761 : mmaechler 2175 isNum <- (is.numeric(r) || is.numeric(r00))
762 :     isLog <- (is.logical(r) || is.logical(r00))
763 : mmaechler 2496 Matrix.msg("exploding <diag> o <diag> into dense matrix", .M.level = 2)
764 : mmaechler 2175 d <- e1@Dim
765 :     n <- d[1]
766 :     stopifnot(length(r) == n)
767 : mmaechler 2814 if(isNum && !is.double(r)) r <- as.double(r)
768 : mmaechler 2175 xx <- as.vector(matrix(rbind(r, matrix(r00,n,n)), n,n))
769 :     newcl <-
770 : mmaechler 2811 paste0(if(isNum) "d" else if(isLog) {
771 : mmaechler 2175 if(!any(is.na(r)) && !any(is.na(r00))) "n" else "l"
772 : mmaechler 2811 } else stop("not yet implemented .. please report"), "syMatrix")
773 : mmaechler 2175
774 :     new(newcl, Dim = e1@Dim, Dimnames = e1@Dimnames, x = xx)
775 :     }
776 : maechler 1655 }
777 :    
778 : mmaechler 2175 ### This would be *the* way, but we get tons of "ambiguous method dispatch"
779 : mmaechler 2185 ## we use this hack instead of signature x = "diagonalMatrix" :
780 :     diCls <- names(getClass("diagonalMatrix")@subclasses)
781 : mmaechler 2175 if(FALSE) {
782 : maechler 1655 setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),
783 :     diagOdiag)
784 : mmaechler 2175 } else { ## These are just for method disambiguation:
785 :     for(c1 in diCls)
786 :     for(c2 in diCls)
787 :     setMethod("Ops", signature(e1 = c1, e2 = c2), diagOdiag)
788 :     }
789 : maechler 1655
790 : mmaechler 2493 ## diagonal o triangular |--> triangular
791 :     ## diagonal o symmetric |--> symmetric
792 : maechler 1845 ## {also when other is sparse: do these "here" --
793 :     ## before conversion to sparse, since that loses "diagonality"}
794 : mmaechler 2811 diagOtri <- function(e1,e2) {
795 :     ## result must be triangular
796 :     r <- callGeneric(d1 <- .diag.x(e1), diag(e2)) # error if not "compatible"
797 :     ## Check what happens with non-diagonals, i.e. (0 o 0), (FALSE o 0), ...:
798 :     e1.0 <- if(.n1 <- is.numeric(d1 )) 0 else FALSE
799 :     r00 <- callGeneric(e1.0, if(.n2 <- is.numeric(e2[0])) 0 else FALSE)
800 :     if(is0(r00)) { ## r00 == 0 or FALSE --- result *is* triangular
801 :     diag(e2) <- r
802 :     ## check what happens "in the triangle"
803 :     e2.2 <- if(.n2) 2 else TRUE
804 :     if(!callGeneric(e1.0, e2.2) == e2.2) { # values "in triangle" can change:
805 :     n <- dim(e2)[1L]
806 :     it <- indTri(n, upper = (e2@uplo == "U"))
807 :     e2[it] <- callGeneric(e1.0, e2[it])
808 :     }
809 :     e2
810 :     }
811 :     else { ## result not triangular ---> general
812 :     rr <- as(e2, "generalMatrix")
813 :     diag(rr) <- r
814 :     rr
815 :     }
816 :     }
817 : maechler 1845
818 : mmaechler 2811
819 :     setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "triangularMatrix"),
820 :     diagOtri)
821 :     ## For the reverse, Ops == "Arith" | "Compare" | "Logic"
822 :     ## 'Arith' := '"+"', '"-"', '"*"', '"^"', '"%%"', '"%/%"', '"/"'
823 :     setMethod("Arith", signature(e1 = "triangularMatrix", e2 = "diagonalMatrix"),
824 :     function(e1,e2)
825 :     { ## this must only trigger for *dense* e1
826 :     switch(.Generic,
827 :     "+" = .Call(dtrMatrix_addDiag, as(e1,"dtrMatrix"), .diag.x(e2)),
828 :     "-" = .Call(dtrMatrix_addDiag, as(e1,"dtrMatrix"), - .diag.x(e2)),
829 :     "*" = {
830 :     n <- e2@Dim[1L]
831 :     d2 <- if(e2@diag == "U") { # unit-diagonal
832 :     d <- rep.int(as1(e2@x), n)
833 :     e2@x <- d
834 :     e2@diag <- "N"
835 :     d
836 :     } else e2@x
837 :     e2@x <- diag(e1) * d2
838 :     e2
839 :     },
840 :     "^" = { ## will be dense ( as <ANY> ^ 0 == 1 ):
841 :     e1 ^ as(e2, "denseMatrix")
842 :     },
843 :     ## otherwise:
844 :     callGeneric(e1, diag2Tsmart(e2,e1)))
845 :     })
846 :    
847 :     ## Compare --> 'swap' (e.g. e1 < e2 <==> e2 > e1 ):
848 :     setMethod("Compare", signature(e1 = "triangularMatrix", e2 = "diagonalMatrix"),
849 :     .Cmp.swap)
850 :     ## '&' and "|' are commutative:
851 :     setMethod("Logic", signature(e1 = "triangularMatrix", e2 = "diagonalMatrix"),
852 :     function(e1,e2) callGeneric(e2, e1))
853 :    
854 : maechler 1655 ## For almost everything else, diag* shall be treated "as sparse" :
855 : maechler 1295 ## These are cheap implementations via coercion
856 :    
857 : maechler 2144 ## For disambiguation --- define this for "sparseMatrix" , then for "ANY";
858 :     ## and because we can save an .M.kind() call, we use this explicit
859 :     ## "hack" for all diagonalMatrix *subclasses* instead of just "diagonalMatrix" :
860 :     ##
861 :     ## ddi*:
862 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "sparseMatrix"),
863 : mmaechler 2175 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2))
864 : maechler 2144 setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ddiMatrix"),
865 : mmaechler 2175 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "d")))
866 : maechler 2144 ## ldi*
867 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "sparseMatrix"),
868 : mmaechler 2175 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2))
869 : maechler 2144 setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ldiMatrix"),
870 : mmaechler 2175 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "l")))
871 : maechler 1654
872 : mmaechler 2820 ## Ops: Arith --> numeric : "dMatrix"
873 :     ## Compare --> logical
874 :     ## Logic --> logical: "lMatrix"
875 : mmaechler 2175
876 : mmaechler 2820 ## Other = "numeric" : stay diagonal if possible
877 : mmaechler 2175 ## ddi*: Arith: result numeric, potentially ddiMatrix
878 : mmaechler 2813 for(arg2 in c("numeric","logical"))
879 :     setMethod("Arith", signature(e1 = "ddiMatrix", e2 = arg2),
880 : maechler 2144 function(e1,e2) {
881 : mmaechler 2820 n <- e1@Dim[1]
882 : maechler 2144 f0 <- callGeneric(0, e2)
883 :     if(all(is0(f0))) { # remain diagonal
884 : maechler 2157 L1 <- (le <- length(e2)) == 1L
885 : mmaechler 2820 if(e1@diag == "U") {
886 :     if(any((r <- callGeneric(1, e2)) != 1)) {
887 :     e1@diag <- "N"
888 :     e1@x[seq_len(n)] <- r # possibly recycling r
889 :     } ## else: result = e1 (is "U" diag)
890 :     } else {
891 : maechler 2144 r <- callGeneric(e1@x, e2)
892 : mmaechler 2820 ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
893 :     e1@x[] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
894 :     }
895 :     e1
896 :     } else
897 :     callGeneric(diag2tT.u(e1,e2, "d"), e2)
898 : maechler 2144 })
899 : maechler 1655
900 : mmaechler 2813 for(arg1 in c("numeric","logical"))
901 :     setMethod("Arith", signature(e1 = arg1, e2 = "ddiMatrix"),
902 : maechler 2144 function(e1,e2) {
903 : mmaechler 2820 n <- e2@Dim[1]
904 : maechler 2144 f0 <- callGeneric(e1, 0)
905 :     if(all(is0(f0))) { # remain diagonal
906 : maechler 2157 L1 <- (le <- length(e1)) == 1L
907 : mmaechler 2820 if(e2@diag == "U") {
908 :     if(any((r <- callGeneric(e1, 1)) != 1)) {
909 :     e2@diag <- "N"
910 :     e2@x[seq_len(n)] <- r # possibly recycling r
911 :     } ## else: result = e2 (is "U" diag)
912 :     } else {
913 : maechler 2144 r <- callGeneric(e1, e2@x)
914 : mmaechler 2820 ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
915 :     e2@x[] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
916 :     }
917 :     e2
918 :     } else
919 :     callGeneric(e1, diag2tT.u(e2,e1, "d"))
920 : maechler 2144 })
921 : mmaechler 2175
922 :     ## ldi* Arith --> result numeric, potentially ddiMatrix
923 : mmaechler 2813 for(arg2 in c("numeric","logical"))
924 :     setMethod("Arith", signature(e1 = "ldiMatrix", e2 = arg2),
925 : mmaechler 2175 function(e1,e2) {
926 : mmaechler 2820 n <- e1@Dim[1]
927 : mmaechler 2175 f0 <- callGeneric(0, e2)
928 :     if(all(is0(f0))) { # remain diagonal
929 :     L1 <- (le <- length(e2)) == 1L
930 : mmaechler 2820 E <- copyClass(e1, "ddiMatrix", c("diag", "Dim", "Dimnames"))#FIXME: if ok, check=FALSE
931 :     ## E <- copyClass(e1, "ddiMatrix", check=FALSE)
932 :     ## storage.mode(E@x) <- "double"
933 :     if(e1@diag == "U") {
934 :     if(any((r <- callGeneric(1, e2)) != 1)) {
935 :     E@diag <- "N"
936 :     E@x[seq_len(n)] <- r # possibly recycling r
937 :     } ## else: result = E (is "U" diag)
938 :     } else {
939 : mmaechler 2175 r <- callGeneric(e1@x, e2)
940 : mmaechler 2820 ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
941 :     E@x[seq_len(n)] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
942 : mmaechler 2814 }
943 : mmaechler 2820 E
944 :     } else
945 :     callGeneric(diag2tT.u(e1,e2, "l"), e2)
946 : mmaechler 2175 })
947 :    
948 : mmaechler 2813 for(arg1 in c("numeric","logical"))
949 :     setMethod("Arith", signature(e1 = arg1, e2 = "ldiMatrix"),
950 : mmaechler 2175 function(e1,e2) {
951 : mmaechler 2820 n <- e2@Dim[1]
952 : mmaechler 2175 f0 <- callGeneric(e1, 0)
953 :     if(all(is0(f0))) { # remain diagonal
954 :     L1 <- (le <- length(e1)) == 1L
955 : mmaechler 2820 E <- copyClass(e2, "ddiMatrix", c("diag", "Dim", "Dimnames"))#FIXME: if ok, check=FALSE
956 :     ## E <- copyClass(e2, "ddiMatrix", check=FALSE)
957 :     ## storage.mode(E@x) <- "double"
958 :     if(e2@diag == "U") {
959 :     if(any((r <- callGeneric(e1, 1)) != 1)) {
960 :     E@diag <- "N"
961 :     E@x[seq_len(n)] <- r # possibly recycling r
962 :     } ## else: result = E (is "U" diag)
963 :     } else {
964 : mmaechler 2175 r <- callGeneric(e1, e2@x)
965 : mmaechler 2820 ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
966 :     E@x[seq_len(n)] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
967 : mmaechler 2814 }
968 : mmaechler 2820 E
969 :     } else
970 :     callGeneric(e1, diag2tT.u(e2,e1, "l"))
971 : mmaechler 2175 })
972 :    
973 : mmaechler 2820 ## ddi*: for "Ops" without "Arith": <Compare> or <Logic> --> result logical, potentially ldi
974 :     ##
975 :     ## Note that ("numeric", "ddiMatrix") is simply swapped, e.g.,
976 :     if(FALSE) {
977 :     selectMethod("<", c("numeric","lMatrix"))# Compare
978 :     selectMethod("&", c("numeric","lMatrix"))# Logic
979 :     } ## so we don't need to define a method here :
980 :    
981 : mmaechler 2813 for(arg2 in c("numeric","logical"))
982 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = arg2),
983 : mmaechler 2175 function(e1,e2) {
984 : mmaechler 2820 n <- e1@Dim[1]
985 : mmaechler 2175 f0 <- callGeneric(0, e2)
986 :     if(all(is0(f0))) { # remain diagonal
987 :     L1 <- (le <- length(e2)) == 1L
988 : mmaechler 2820 E <- copyClass(e1, "ldiMatrix", c("diag", "Dim", "Dimnames"))#FIXME: if ok, check=FALSE
989 :     ## E <- copyClass(e1, "ldiMatrix", check=FALSE)
990 :     ## storage.mode(E@x) <- "logical"
991 :     if(e1@diag == "U") {
992 :     if(any((r <- callGeneric(1, e2)) != 1)) {
993 :     E@diag <- "N"
994 :     E@x[seq_len(n)] <- r # possibly recycling r
995 :     } ## else: result = E (is "U" diag)
996 :     } else {
997 : mmaechler 2175 r <- callGeneric(e1@x, e2)
998 : mmaechler 2820 ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
999 :     E@x[seq_len(n)] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
1000 : mmaechler 2814 }
1001 : mmaechler 2820 E
1002 :     } else
1003 :     callGeneric(diag2tT.u(e1,e2, "d"), e2)
1004 : mmaechler 2175 })
1005 :    
1006 : mmaechler 2820 ## ldi*: for "Ops" without "Arith": <Compare> or <Logic> --> result logical, potentially ldi
1007 : mmaechler 2813 for(arg2 in c("numeric","logical"))
1008 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = arg2),
1009 : maechler 2144 function(e1,e2) {
1010 : mmaechler 2820 n <- e1@Dim[1]
1011 : maechler 2144 f0 <- callGeneric(FALSE, e2)
1012 :     if(all(is0(f0))) { # remain diagonal
1013 : maechler 2157 L1 <- (le <- length(e2)) == 1L
1014 : mmaechler 2820
1015 :     if(e1@diag == "U") {
1016 :     if(any((r <- callGeneric(TRUE, e2)) != 1)) {
1017 :     e1@diag <- "N"
1018 :     e1@x[seq_len(n)] <- r # possibly recycling r
1019 :     } ## else: result = e1 (is "U" diag)
1020 :     } else {
1021 : maechler 2144 r <- callGeneric(e1@x, e2)
1022 : mmaechler 2820 ## "future fixme": if we have idiMatrix, and r is 'integer', use idiMatrix
1023 :     e1@x[] <- if(L1) r else r[1L + ((n+1)*(0:(n-1L))) %% le]
1024 :     }
1025 :     e1
1026 :     } else
1027 :     callGeneric(diag2tT.u(e1,e2, "l"), e2)
1028 : maechler 2144 })
1029 : maechler 1655
1030 : maechler 2144
1031 :     ## Not {"sparseMatrix", "numeric} : {"denseMatrix", "matrix", ... }
1032 : mmaechler 2196 for(other in c("ANY", "Matrix", "dMatrix")) {
1033 :     ## ddi*:
1034 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = other),
1035 : mmaechler 2493 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2))
1036 : mmaechler 2196 setMethod("Ops", signature(e1 = other, e2 = "ddiMatrix"),
1037 : mmaechler 2493 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "d")))
1038 : mmaechler 2196 ## ldi*:
1039 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = other),
1040 : mmaechler 2493 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2))
1041 : mmaechler 2196 setMethod("Ops", signature(e1 = other, e2 = "ldiMatrix"),
1042 : mmaechler 2493 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "l")))
1043 : mmaechler 2196 }
1044 : mmaechler 2331
1045 :     ## Direct subclasses of "denseMatrix": currently ddenseMatrix, ldense... :
1046 :     dense.subCl <- local({ dM.scl <- getClass("denseMatrix")@subclasses
1047 : mmaechler 2813 names(dM.scl)[vapply(dM.scl, slot, 0, "distance") == 1] })
1048 : mmaechler 2268 for(DI in diCls) {
1049 : mmaechler 2814 dMeth <- if(extends(DI, "dMatrix"))
1050 :     function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2)
1051 :     else # "lMatrix", the only other kind for now
1052 :     function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2)
1053 : mmaechler 2331 for(c2 in c(dense.subCl, "Matrix")) {
1054 : mmaechler 2814 for(Fun in c("*", "&")) {
1055 : mmaechler 2268 setMethod(Fun, signature(e1 = DI, e2 = c2),
1056 :     function(e1,e2) callGeneric(e1, Diagonal(x = diag(e2))))
1057 :     setMethod(Fun, signature(e1 = c2, e2 = DI),
1058 :     function(e1,e2) callGeneric(Diagonal(x = diag(e1)), e2))
1059 :     }
1060 : mmaechler 2814 setMethod("^", signature(e1 = c2, e2 = DI),
1061 :     function(e1,e2) callGeneric(Diagonal(x = diag(e1)), e2))
1062 :     for(Fun in c("%%", "%/%", "/")) ## 0 <op> 0 |--> NaN for these.
1063 :     setMethod(Fun, signature(e1 = DI, e2 = c2), dMeth)
1064 : mmaechler 2175 }
1065 :     }
1066 : maechler 2144
1067 :    
1068 : mmaechler 2175 ### "Summary" : "max" "min" "range" "prod" "sum" "any" "all"
1069 : mmaechler 2345 ### ---------- the last 4: separately here
1070 : mmaechler 2175 for(cl in diCls) {
1071 :     setMethod("any", cl,
1072 :     function (x, ..., na.rm) {
1073 :     if(any(x@Dim == 0)) FALSE
1074 :     else if(x@diag == "U") TRUE else any(x@x, ..., na.rm = na.rm)
1075 :     })
1076 : mmaechler 2341 setMethod("all", cl, function (x, ..., na.rm) {
1077 :     n <- x@Dim[1]
1078 :     if(n >= 2) FALSE
1079 :     else if(n == 0 || x@diag == "U") TRUE
1080 :     else all(x@x, ..., na.rm = na.rm)
1081 :     })
1082 :     setMethod("prod", cl, function (x, ..., na.rm) {
1083 :     n <- x@Dim[1]
1084 :     if(n >= 2) 0
1085 :     else if(n == 0 || x@diag == "U") 1
1086 :     else ## n == 1, diag = "N" :
1087 :     prod(x@x, ..., na.rm = na.rm)
1088 :     })
1089 : mmaechler 2175
1090 :     setMethod("sum", cl,
1091 :     function(x, ..., na.rm) {
1092 :     r <- sum(x@x, ..., na.rm = na.rm)# double or integer, correctly
1093 :     if(x@diag == "U" && !is.na(r)) r + x@Dim[1] else r
1094 :     })
1095 :     }
1096 :    
1097 :     ## The remaining ones are max, min, range :
1098 :    
1099 :     setMethod("Summary", "ddiMatrix",
1100 :     function(x, ..., na.rm) {
1101 :     if(any(x@Dim == 0)) callGeneric(numeric(0), ..., na.rm=na.rm)
1102 :     else if(x@diag == "U")
1103 :     callGeneric(x@x, 0, 1, ..., na.rm=na.rm)
1104 :     else callGeneric(x@x, 0, ..., na.rm=na.rm)
1105 :     })
1106 :     setMethod("Summary", "ldiMatrix",
1107 :     function(x, ..., na.rm) {
1108 :     if(any(x@Dim == 0)) callGeneric(logical(0), ..., na.rm=na.rm)
1109 :     else if(x@diag == "U")
1110 :     callGeneric(x@x, FALSE, TRUE, ..., na.rm=na.rm)
1111 :     else callGeneric(x@x, FALSE, ..., na.rm=na.rm)
1112 :     })
1113 :    
1114 :    
1115 :    
1116 : maechler 1109 ## similar to prTriang() in ./Auxiliaries.R :
1117 :     prDiag <-
1118 :     function(x, digits = getOption("digits"), justify = "none", right = TRUE)
1119 :     {
1120 :     cf <- array(".", dim = x@Dim, dimnames = x@Dimnames)
1121 :     cf[row(cf) == col(cf)] <-
1122 :     sapply(diag(x), format, digits = digits, justify = justify)
1123 :     print(cf, quote = FALSE, right = right)
1124 :     invisible(x)
1125 :     }
1126 :    
1127 : mmaechler 2237 ## somewhat consistent with "print" for sparseMatrix :
1128 :     setMethod("print", signature(x = "diagonalMatrix"), prDiag)
1129 :    
1130 : maechler 1109 setMethod("show", signature(object = "diagonalMatrix"),
1131 : maechler 1592 function(object) {
1132 :     d <- dim(object)
1133 :     cl <- class(object)
1134 : mmaechler 2203 cat(sprintf('%d x %d diagonal matrix of class "%s"',
1135 : maechler 1592 d[1], d[2], cl))
1136 : mmaechler 2203 if(d[1] < 50) {
1137 :     cat("\n")
1138 :     prDiag(object)
1139 :     } else {
1140 :     cat(", with diagonal entries\n")
1141 :     show(diag(object))
1142 :     invisible(object)
1143 :     }
1144 : maechler 1592 })
1145 : mmaechler 2813
1146 :     rm(dense.subCl, diCls)# not used elsewhere
1147 : mmaechler 2820
1148 :     setMethod("summary", signature(object = "diagonalMatrix"),
1149 :     function(object, ...) {
1150 :     d <- dim(object)
1151 :     r <- summary(object@x, ...)
1152 :     attr(r, "header") <-
1153 :     sprintf('%d x %d diagonal Matrix of class "%s"',
1154 :     d[1], d[2], class(object))
1155 :     ## use ole' S3 technology for such a simple case
1156 :     class(r) <- c("diagSummary", class(r))
1157 :     r
1158 :     })
1159 :    
1160 :     print.diagSummary <- function (x, ...) {
1161 :     cat(attr(x, "header"),"\n")
1162 :     class(x) <- class(x)[-1]
1163 :     print(x, ...)
1164 :     invisible(x)
1165 :     }

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