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 2813 - (view) (download)

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

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