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 2741 - (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 : maechler 1617 ### 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 :     ### block-diagonal matrix [a dgTMatrix] from list of matrices
88 :     stopifnot(is.list(lst), length(lst) >= 1)
89 :     dims <- sapply(lst, dim, 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 :     i_off <- c(0L, cumsum(sapply(Tlst, nrow)))
119 :     j_off <- c(0L, cumsum(sapply(Tlst, ncol)))
120 : mmaechler 2209
121 :     clss <- sapply(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 :     uplos <- sapply(Tlst, slot, "uplo") ## either "U" or "L"
134 :     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 :     else if(all(tri) && { ULs <- sapply(Tlst, slot, "uplo")## "U" or "L"
153 :     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 : maechler 2136 new(paste(kind, "tTMatrix", sep=''),
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 :     new(paste(kind, "sTMatrix", sep=''),
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 2239 x <- as(x, "TsparseMatrix")
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 :     }
433 :     }
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 :     ## ambiguous dispatch for "ddi", since there's also Arith(ddense., ddense.)
730 : mmaechler 2175 diagOdiag <- function(e1,e2) {
731 :     ## result should also be diagonal _ if possible _
732 : maechler 1655 r <- callGeneric(.diag.x(e1), .diag.x(e2)) # error if not "compatible"
733 : mmaechler 2175 ## Check what happens with non-diagonals, i.e. (0 o 0), (FALSE o 0), ...:
734 :     r00 <- callGeneric(if(is.numeric(e1@x)) 0 else FALSE,
735 :     if(is.numeric(e2@x)) 0 else FALSE)
736 :     if(is0(r00)) { ## r00 == 0 or FALSE --- result *is* diagonal
737 :     if(is.numeric(r)) {
738 :     if(is.numeric(e2@x)) {
739 :     e2@x <- r; return(.diag.2N(e2)) }
740 :     if(!is.numeric(e1@x))
741 :     ## e.g. e1, e2 are logical;
742 :     e1 <- as(e1, "dMatrix")
743 :     }
744 :     else if(is.logical(r))
745 :     e1 <- as(e1, "lMatrix")
746 :     else stop("intermediate 'r' is of type", typeof(r))
747 :     e1@x <- r
748 :     .diag.2N(e1)
749 : maechler 1655 }
750 : mmaechler 2175 else { ## result not diagonal, but at least symmetric:
751 : mmaechler 2496 ## e.g., m == m
752 : mmaechler 2175 isNum <- (is.numeric(r) || is.numeric(r00))
753 :     isLog <- (is.logical(r) || is.logical(r00))
754 : mmaechler 2496 Matrix.msg("exploding <diag> o <diag> into dense matrix", .M.level = 2)
755 : mmaechler 2175 d <- e1@Dim
756 :     n <- d[1]
757 :     stopifnot(length(r) == n)
758 :     xx <- as.vector(matrix(rbind(r, matrix(r00,n,n)), n,n))
759 :     newcl <-
760 :     paste(if(isNum) "d" else if(isLog) {
761 :     if(!any(is.na(r)) && !any(is.na(r00))) "n" else "l"
762 :     } else stop("not yet implemented .. please report")
763 :     ,
764 :     "syMatrix", sep='')
765 :    
766 :     new(newcl, Dim = e1@Dim, Dimnames = e1@Dimnames, x = xx)
767 :     }
768 : maechler 1655 }
769 :    
770 : mmaechler 2175 ### This would be *the* way, but we get tons of "ambiguous method dispatch"
771 : mmaechler 2185 ## we use this hack instead of signature x = "diagonalMatrix" :
772 :     diCls <- names(getClass("diagonalMatrix")@subclasses)
773 : mmaechler 2175 if(FALSE) {
774 : maechler 1655 setMethod("Ops", signature(e1 = "diagonalMatrix", e2 = "diagonalMatrix"),
775 :     diagOdiag)
776 : mmaechler 2175 } else { ## These are just for method disambiguation:
777 :     for(c1 in diCls)
778 :     for(c2 in diCls)
779 :     setMethod("Ops", signature(e1 = c1, e2 = c2), diagOdiag)
780 :     }
781 : maechler 1655
782 : mmaechler 2493 ## diagonal o triangular |--> triangular
783 :     ## diagonal o symmetric |--> symmetric
784 : maechler 1845 ## {also when other is sparse: do these "here" --
785 :     ## before conversion to sparse, since that loses "diagonality"}
786 :    
787 : maechler 1655 ## For almost everything else, diag* shall be treated "as sparse" :
788 : maechler 1295 ## These are cheap implementations via coercion
789 :    
790 : maechler 2144 ## For disambiguation --- define this for "sparseMatrix" , then for "ANY";
791 :     ## and because we can save an .M.kind() call, we use this explicit
792 :     ## "hack" for all diagonalMatrix *subclasses* instead of just "diagonalMatrix" :
793 :     ##
794 :     ## ddi*:
795 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "sparseMatrix"),
796 : mmaechler 2175 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2))
797 : maechler 2144 setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ddiMatrix"),
798 : mmaechler 2175 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "d")))
799 : maechler 2144 ## ldi*
800 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "sparseMatrix"),
801 : mmaechler 2175 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2))
802 : maechler 2144 setMethod("Ops", signature(e1 = "sparseMatrix", e2 = "ldiMatrix"),
803 : mmaechler 2175 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "l")))
804 : maechler 1654
805 : mmaechler 2175 ## Ops: Arith --> numeric : "dMatrix"
806 :     ## Compare --> logical
807 :     ## Logic --> logical: "lMatrix"
808 :    
809 : maechler 2144 ## other = "numeric" : stay diagonal if possible
810 : mmaechler 2175 ## ddi*: Arith: result numeric, potentially ddiMatrix
811 :     setMethod("Arith", signature(e1 = "ddiMatrix", e2 = "numeric"),
812 : maechler 2144 function(e1,e2) {
813 : mmaechler 2203 n <- e1@Dim[1]; nsq <- n^2
814 : maechler 2144 f0 <- callGeneric(0, e2)
815 :     if(all(is0(f0))) { # remain diagonal
816 : maechler 2157 L1 <- (le <- length(e2)) == 1L
817 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
818 :     if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
819 : maechler 2144 e1@diag <- "N"
820 : maechler 2157 if(L1) r <- rep.int(r, n)
821 :     } else
822 : maechler 2144 r <- callGeneric(e1@x, e2)
823 : mmaechler 2197 e1@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
824 : maechler 2144 return(e1)
825 :     }
826 :     callGeneric(diag2tT.u(e1,e2, "d"), e2)
827 :     })
828 : maechler 1655
829 : mmaechler 2175 setMethod("Arith", signature(e1 = "numeric", e2 = "ddiMatrix"),
830 : maechler 2144 function(e1,e2) {
831 : mmaechler 2203 n <- e2@Dim[1]; nsq <- n^2
832 : maechler 2144 f0 <- callGeneric(e1, 0)
833 :     if(all(is0(f0))) { # remain diagonal
834 : maechler 2157 L1 <- (le <- length(e1)) == 1L
835 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
836 :     if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
837 : maechler 2144 e2@diag <- "N"
838 : maechler 2157 if(L1) r <- rep.int(r, n)
839 :     } else
840 : maechler 2144 r <- callGeneric(e1, e2@x)
841 : mmaechler 2197 e2@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
842 : maechler 2144 return(e2)
843 :     }
844 :     callGeneric(e1, diag2tT.u(e2,e1, "d"))
845 :     })
846 : mmaechler 2175
847 :     ## ldi* Arith --> result numeric, potentially ddiMatrix
848 :     setMethod("Arith", signature(e1 = "ldiMatrix", e2 = "numeric"),
849 :     function(e1,e2) {
850 : mmaechler 2203 n <- e1@Dim[1]; nsq <- n^2
851 : mmaechler 2175 f0 <- callGeneric(0, e2)
852 :     if(all(is0(f0))) { # remain diagonal
853 :     L1 <- (le <- length(e2)) == 1L
854 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
855 :     if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
856 :     e1@diag <- "N"
857 :     if(L1) r <- rep.int(r, n)
858 :     } else
859 :     r <- callGeneric(e1@x, e2)
860 :     e1 <- copyClass(e1, "ddiMatrix", c("diag", "Dim", "Dimnames"))
861 : mmaechler 2197 e1@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
862 : mmaechler 2175 return(e1)
863 :     }
864 :     callGeneric(diag2tT.u(e1,e2, "d"), e2)
865 :     })
866 :    
867 :     setMethod("Arith", signature(e1 = "numeric", e2 = "ldiMatrix"),
868 :     function(e1,e2) {
869 : mmaechler 2203 n <- e2@Dim[1]; nsq <- n^2
870 : mmaechler 2175 f0 <- callGeneric(e1, 0)
871 :     if(all(is0(f0))) { # remain diagonal
872 :     L1 <- (le <- length(e1)) == 1L
873 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
874 :     if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
875 :     e2@diag <- "N"
876 :     if(L1) r <- rep.int(r, n)
877 :     } else
878 :     r <- callGeneric(e1, e2@x)
879 :     e2 <- copyClass(e2, "ddiMatrix", c("diag", "Dim", "Dimnames"))
880 : mmaechler 2197 e2@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
881 : mmaechler 2175 return(e2)
882 :     }
883 :     callGeneric(e1, diag2tT.u(e2,e1, "d"))
884 :     })
885 :    
886 :     ## ddi*: for "Ops" without Arith --> result logical, potentially ldi
887 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = "numeric"),
888 :     function(e1,e2) {
889 : mmaechler 2203 n <- e1@Dim[1]; nsq <- n^2
890 : mmaechler 2175 f0 <- callGeneric(0, e2)
891 :     if(all(is0(f0))) { # remain diagonal
892 :     L1 <- (le <- length(e2)) == 1L
893 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
894 :     if(e1@diag == "U" && any((r <- callGeneric(1, e2)) != 1)) {
895 :     e1@diag <- "N"
896 :     if(L1) r <- rep.int(r, n)
897 :     } else
898 :     r <- callGeneric(e1@x, e2)
899 :     e1 <- copyClass(e1, "ldiMatrix", c("diag", "Dim", "Dimnames"))
900 : mmaechler 2197 e1@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
901 : mmaechler 2175 return(e1)
902 :     }
903 :     callGeneric(diag2tT.u(e1,e2, "l"), e2)
904 :     })
905 :    
906 :     setMethod("Ops", signature(e1 = "numeric", e2 = "ddiMatrix"),
907 :     function(e1,e2) {
908 : mmaechler 2203 n <- e2@Dim[1]; nsq <- n^2
909 : mmaechler 2175 f0 <- callGeneric(e1, 0)
910 :     if(all(is0(f0))) { # remain diagonal
911 :     L1 <- (le <- length(e1)) == 1L
912 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
913 :     if(e2@diag == "U" && any((r <- callGeneric(e1, 1)) != 1)) {
914 :     e2@diag <- "N"
915 :     if(L1) r <- rep.int(r, n)
916 :     } else
917 :     r <- callGeneric(e1, e2@x)
918 :     e2 <- copyClass(e2, "ldiMatrix", c("diag", "Dim", "Dimnames"))
919 : mmaechler 2197 e2@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
920 : mmaechler 2175 return(e2)
921 :     }
922 :     callGeneric(e1, diag2tT.u(e2,e1, "l"))
923 :     })
924 :    
925 :     ## ldi*: for "Ops" without Arith --> result logical, potentially ldi
926 : maechler 2144 setMethod("Ops", signature(e1 = "ldiMatrix", e2 = "numeric"),
927 :     function(e1,e2) {
928 : mmaechler 2203 n <- e1@Dim[1]; nsq <- n^2
929 : maechler 2144 f0 <- callGeneric(FALSE, e2)
930 :     if(all(is0(f0))) { # remain diagonal
931 : maechler 2157 L1 <- (le <- length(e2)) == 1L
932 :     if(!L1 && le != nsq) e2 <- rep(e2, length.out = nsq)
933 :     if(e1@diag == "U" && any((r <- callGeneric(TRUE, e2)) != 1)) {
934 : maechler 2144 e1@diag <- "N"
935 : maechler 2157 if(L1) r <- rep.int(r, n)
936 :     } else
937 : maechler 2144 r <- callGeneric(e1@x, e2)
938 : mmaechler 2197 e1@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
939 : maechler 2144 return(e1)
940 :     }
941 :     callGeneric(diag2tT.u(e1,e2, "l"), e2)
942 :     })
943 : maechler 1655
944 : maechler 2144 setMethod("Ops", signature(e1 = "numeric", e2 = "ldiMatrix"),
945 :     function(e1,e2) {
946 : mmaechler 2203 n <- e2@Dim[1]; nsq <- n^2
947 : maechler 2144 f0 <- callGeneric(e1, FALSE)
948 :     if(all(is0(f0))) { # remain diagonal
949 : maechler 2157 L1 <- (le <- length(e1)) == 1L
950 :     if(!L1 && le != nsq) e1 <- rep(e1, length.out = nsq)
951 :     if(e2@diag == "U" && any((r <- callGeneric(e1, TRUE)) != 1)) {
952 : maechler 2144 e2@diag <- "N"
953 : maechler 2157 if(L1) r <- rep.int(r, n)
954 :     } else
955 : maechler 2144 r <- callGeneric(e1, e2@x)
956 : mmaechler 2197 e2@x <- if(L1) r else r[1L + (n+1L)*(0:(n-1L))]
957 : maechler 2144 return(e2)
958 :     }
959 :     callGeneric(e1, diag2tT.u(e2,e1, "l"))
960 :     })
961 :    
962 :    
963 :    
964 :     ## Not {"sparseMatrix", "numeric} : {"denseMatrix", "matrix", ... }
965 : mmaechler 2196 for(other in c("ANY", "Matrix", "dMatrix")) {
966 :     ## ddi*:
967 :     setMethod("Ops", signature(e1 = "ddiMatrix", e2 = other),
968 : mmaechler 2493 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "d"), e2))
969 : mmaechler 2196 setMethod("Ops", signature(e1 = other, e2 = "ddiMatrix"),
970 : mmaechler 2493 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "d")))
971 : mmaechler 2196 ## ldi*:
972 :     setMethod("Ops", signature(e1 = "ldiMatrix", e2 = other),
973 : mmaechler 2493 function(e1,e2) callGeneric(diag2Tsmart(e1,e2, "l"), e2))
974 : mmaechler 2196 setMethod("Ops", signature(e1 = other, e2 = "ldiMatrix"),
975 : mmaechler 2493 function(e1,e2) callGeneric(e1, diag2Tsmart(e2,e1, "l")))
976 : mmaechler 2196 }
977 : mmaechler 2331
978 :     ## Direct subclasses of "denseMatrix": currently ddenseMatrix, ldense... :
979 : mmaechler 2544 if(FALSE)## too general, would contain denseModelMatrix:
980 : mmaechler 2331 dense.subCl <- local({ dM.scl <- getClass("denseMatrix")@subclasses
981 :     names(dM.scl)[sapply(dM.scl, slot, "distance") == 1] })
982 : mmaechler 2544 dense.subCl <- paste(c("d","l","n"), "denseMatrix", sep="")
983 : mmaechler 2268 for(DI in diCls) {
984 : mmaechler 2331 for(c2 in c(dense.subCl, "Matrix")) {
985 : mmaechler 2268 for(Fun in c("*", "^", "&")) {
986 :     setMethod(Fun, signature(e1 = DI, e2 = c2),
987 :     function(e1,e2) callGeneric(e1, Diagonal(x = diag(e2))))
988 :     setMethod(Fun, signature(e1 = c2, e2 = DI),
989 :     function(e1,e2) callGeneric(Diagonal(x = diag(e1)), e2))
990 :     }
991 :     ## NB: This arguably implicitly uses 0/0 :== 0 to keep diagonality
992 :     for(Fun in c("%%", "%/%", "/")) {
993 :     setMethod(Fun, signature(e1 = DI, e2 = c2),
994 :     function(e1,e2) callGeneric(e1, Diagonal(x = diag(e2))))
995 :     }
996 : mmaechler 2175 }
997 :     }
998 : maechler 2144
999 :    
1000 : mmaechler 2175 ### "Summary" : "max" "min" "range" "prod" "sum" "any" "all"
1001 : mmaechler 2345 ### ---------- the last 4: separately here
1002 : mmaechler 2175 for(cl in diCls) {
1003 :     setMethod("any", cl,
1004 :     function (x, ..., na.rm) {
1005 :     if(any(x@Dim == 0)) FALSE
1006 :     else if(x@diag == "U") TRUE else any(x@x, ..., na.rm = na.rm)
1007 :     })
1008 : mmaechler 2341 setMethod("all", cl, function (x, ..., na.rm) {
1009 :     n <- x@Dim[1]
1010 :     if(n >= 2) FALSE
1011 :     else if(n == 0 || x@diag == "U") TRUE
1012 :     else all(x@x, ..., na.rm = na.rm)
1013 :     })
1014 :     setMethod("prod", cl, function (x, ..., na.rm) {
1015 :     n <- x@Dim[1]
1016 :     if(n >= 2) 0
1017 :     else if(n == 0 || x@diag == "U") 1
1018 :     else ## n == 1, diag = "N" :
1019 :     prod(x@x, ..., na.rm = na.rm)
1020 :     })
1021 : mmaechler 2175
1022 :     setMethod("sum", cl,
1023 :     function(x, ..., na.rm) {
1024 :     r <- sum(x@x, ..., na.rm = na.rm)# double or integer, correctly
1025 :     if(x@diag == "U" && !is.na(r)) r + x@Dim[1] else r
1026 :     })
1027 :     }
1028 :    
1029 :     ## The remaining ones are max, min, range :
1030 :    
1031 :     setMethod("Summary", "ddiMatrix",
1032 :     function(x, ..., na.rm) {
1033 :     if(any(x@Dim == 0)) callGeneric(numeric(0), ..., na.rm=na.rm)
1034 :     else if(x@diag == "U")
1035 :     callGeneric(x@x, 0, 1, ..., na.rm=na.rm)
1036 :     else callGeneric(x@x, 0, ..., na.rm=na.rm)
1037 :     })
1038 :     setMethod("Summary", "ldiMatrix",
1039 :     function(x, ..., na.rm) {
1040 :     if(any(x@Dim == 0)) callGeneric(logical(0), ..., na.rm=na.rm)
1041 :     else if(x@diag == "U")
1042 :     callGeneric(x@x, FALSE, TRUE, ..., na.rm=na.rm)
1043 :     else callGeneric(x@x, FALSE, ..., na.rm=na.rm)
1044 :     })
1045 :    
1046 :    
1047 :    
1048 : maechler 1109 ## similar to prTriang() in ./Auxiliaries.R :
1049 :     prDiag <-
1050 :     function(x, digits = getOption("digits"), justify = "none", right = TRUE)
1051 :     {
1052 :     cf <- array(".", dim = x@Dim, dimnames = x@Dimnames)
1053 :     cf[row(cf) == col(cf)] <-
1054 :     sapply(diag(x), format, digits = digits, justify = justify)
1055 :     print(cf, quote = FALSE, right = right)
1056 :     invisible(x)
1057 :     }
1058 :    
1059 : mmaechler 2237 ## somewhat consistent with "print" for sparseMatrix :
1060 :     setMethod("print", signature(x = "diagonalMatrix"), prDiag)
1061 :    
1062 : maechler 1109 setMethod("show", signature(object = "diagonalMatrix"),
1063 : maechler 1592 function(object) {
1064 :     d <- dim(object)
1065 :     cl <- class(object)
1066 : mmaechler 2203 cat(sprintf('%d x %d diagonal matrix of class "%s"',
1067 : maechler 1592 d[1], d[2], cl))
1068 : mmaechler 2203 if(d[1] < 50) {
1069 :     cat("\n")
1070 :     prDiag(object)
1071 :     } else {
1072 :     cat(", with diagonal entries\n")
1073 :     show(diag(object))
1074 :     invisible(object)
1075 :     }
1076 : 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