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 2417 - (view) (download)
Original Path: pkg/R/diagMatrix.R

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

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