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

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

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge