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

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