SCM

SCM Repository

[matrix] Annotation of /pkg/R/sparseMatrix.R
ViewVC logotype

Annotation of /pkg/R/sparseMatrix.R

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2102 - (view) (download)

1 : bates 684 ### Define Methods that can be inherited for all subclasses
2 :    
3 : maechler 925 ### Idea: Coercion between *VIRTUAL* classes -- as() chooses "closest" classes
4 :     ### ---- should also work e.g. for dense-triangular --> sparse-triangular !
5 : maechler 868
6 : maechler 1472 ##-> see als ./dMatrix.R, ./ddenseMatrix.R and ./lMatrix.R
7 : maechler 868
8 : maechler 1472 setAs("ANY", "sparseMatrix", function(from) as(from, "CsparseMatrix"))
9 : maechler 868
10 : maechler 1845 setAs("sparseMatrix", "generalMatrix", as_gSparse)
11 : maechler 1472
12 : maechler 1845 setAs("sparseMatrix", "symmetricMatrix", as_sSparse)
13 :    
14 :     setAs("sparseMatrix", "triangularMatrix", as_tSparse)
15 :    
16 : maechler 1932 spMatrix <- function(nrow, ncol,
17 :     i = integer(), j = integer(), x = numeric())
18 :     {
19 : maechler 1852 dim <- c(as.integer(nrow), as.integer(ncol))
20 :     ## The conformability of (i,j,x) with itself and with 'dim'
21 :     ## is checked automatically by internal "validObject()" inside new(.):
22 :     kind <- .M.kind(x)
23 :     new(paste(kind, "gTMatrix", sep=''), Dim = dim,
24 :     x = if(kind == "d") as.double(x) else x,
25 :     ## our "Tsparse" Matrices use 0-based indices :
26 :     i = as.integer(i - 1L),
27 :     j = as.integer(j - 1L))
28 :     }
29 :    
30 :    
31 : maechler 871 ## "graph" coercions -- this needs the graph package which is currently
32 :     ## ----- *not* required on purpose
33 :     ## Note: 'undirected' graph <==> 'symmetric' matrix
34 :    
35 : maechler 1271 ## Add some utils that may no longer be needed in future versions of the 'graph' package
36 :     graph.has.weights <- function(g) "weight" %in% names(edgeDataDefaults(g))
37 :    
38 :     graph.wgtMatrix <- function(g)
39 :     {
40 :     ## Purpose: work around "graph" package's as(g, "matrix") bug
41 :     ## ----------------------------------------------------------------------
42 :     ## Arguments: g: an object inheriting from (S4) class "graph"
43 :     ## ----------------------------------------------------------------------
44 :     ## Author: Martin Maechler, based on Seth Falcon's code; Date: 12 May 2006
45 :    
46 :     ## MM: another buglet for the case of "no edges":
47 :     if(numEdges(g) == 0) {
48 :     p <- length(nd <- nodes(g))
49 :     return( matrix(0, p,p, dimnames = list(nd, nd)) )
50 :     }
51 :     ## Usual case, when there are edges:
52 :     has.w <- "weight" %in% names(edgeDataDefaults(g))
53 :     if(has.w) {
54 :     w <- unlist(edgeData(g, attr = "weight"))
55 :     has.w <- any(w != 1)
56 :     } ## now 'has.w' is TRUE iff there are weights != 1
57 :     m <- as(g, "matrix")
58 :     ## now is a 0/1 - matrix (instead of 0/wgts) with the 'graph' bug
59 :     if(has.w) { ## fix it if needed
60 :     tm <- t(m)
61 :     tm[tm != 0] <- w
62 :     t(tm)
63 :     }
64 :     else m
65 :     }
66 :    
67 :    
68 :     setAs("graphAM", "sparseMatrix",
69 : bates 862 function(from) {
70 : maechler 1271 symm <- edgemode(from) == "undirected" && isSymmetric(from@adjMat)
71 :     ## This is only ok if there are no weights...
72 :     if(graph.has.weights(from)) {
73 :     as(graph.wgtMatrix(from),
74 :     if(symm) "dsTMatrix" else "dgTMatrix")
75 :     }
76 :     else { ## no weights: 0/1 matrix -> logical
77 :     as(as(from, "matrix"),
78 : maechler 1548 if(symm) "nsTMatrix" else "ngTMatrix")
79 : maechler 1271 }
80 : bates 862 })
81 : maechler 1271
82 : bates 1476 setAs("graph", "CsparseMatrix",
83 : bates 1479 function(from) as(as(from, "graphNEL"), "CsparseMatrix"))
84 : maechler 687
85 : bates 1474 setAs("graphNEL", "CsparseMatrix",
86 : maechler 1565 function(from) as(as(from, "TsparseMatrix"), "CsparseMatrix"))
87 :    
88 :     setAs("graphNEL", "TsparseMatrix",
89 : maechler 1271 function(from) {
90 : maechler 1565 nd <- nodes(from)
91 : bates 1474 dm <- rep.int(length(nd), 2)
92 : maechler 1271 symm <- edgemode(from) == "undirected"
93 : bates 1474
94 : maechler 1565 if(graph.has.weights(from)) {
95 :     eWts <- edgeWeights(from)
96 :     lens <- unlist(lapply(eWts, length))
97 :     i <- rep.int(0:(dm[1]-1), lens) # column indices (0-based)
98 :     To <- unlist(lapply(eWts, names))
99 : maechler 1832 j <- as.integer(match(To,nd) - 1L) # row indices (0-based)
100 : maechler 1565 ## symm <- symm && <weights must also be symmetric>: improbable
101 :     ## if(symm) new("dsTMatrix", .....) else
102 :     new("dgTMatrix", i = i, j = j, x = unlist(eWts),
103 :     Dim = dm, Dimnames = list(nd, nd))
104 :     }
105 :     else { ## no weights: 0/1 matrix -> logical
106 :     edges <- lapply(from@edgeL[nd], "[[", "edges")
107 :     lens <- unlist(lapply(edges, length))
108 :     ## nnz <- sum(unlist(lens)) # number of non-zeros
109 :     i <- rep.int(0:(dm[1]-1), lens) # column indices (0-based)
110 :     j <- as.integer(unlist(edges) - 1) # row indices (0-based)
111 :     if(symm) { # symmetric: ensure upper triangle
112 :     tmp <- i
113 :     flip <- i > j
114 :     i[flip] <- j[flip]
115 :     j[flip] <- tmp[flip]
116 :     new("nsTMatrix", i = i, j = j, Dim = dm,
117 :     Dimnames = list(nd, nd), uplo = "U")
118 :     } else {
119 :     new("ngTMatrix", i = i, j = j, Dim = dm,
120 :     Dimnames = list(nd, nd))
121 :     }
122 : bates 1474 }
123 : maechler 1271 })
124 : maechler 687
125 : maechler 871 setAs("sparseMatrix", "graph", function(from) as(from, "graphNEL"))
126 :     setAs("sparseMatrix", "graphNEL",
127 : maechler 1271 function(from) as(as(from, "TsparseMatrix"), "graphNEL"))
128 : maechler 908
129 : maechler 1348 Tsp2grNEL <- function(from) {
130 :     d <- dim(from)
131 :     if(d[1] != d[2])
132 : maechler 1513 stop("only square matrices can be used as incidence matrices for graphs")
133 : maechler 1348 n <- d[1]
134 :     if(n == 0) return(new("graphNEL"))
135 :     if(is.null(rn <- dimnames(from)[[1]]))
136 :     rn <- as.character(1:n)
137 :     from <- uniq(from) ## Need to 'uniquify' the triplets!
138 : maechler 908
139 : maechler 1348 if(isSymmetric(from)) { # either "symmetricMatrix" or otherwise
140 :     ##-> undirected graph: every edge only once!
141 :     if(!is(from, "symmetricMatrix")) {
142 :     ## a general matrix which happens to be symmetric
143 :     ## ==> remove the double indices
144 :     from <- tril(from)
145 :     }
146 : maechler 1565 eMode <- "undirected"
147 :     } else {
148 :     eMode <- "directed"
149 : maechler 1348 }
150 : maechler 1565 ## every edge is there only once, either upper or lower triangle
151 : maechler 1832 ft1 <- cbind(rn[from@i + 1L], rn[from@j + 1L])
152 : maechler 1565 ## not yet: graph::ftM2graphNEL(.........)
153 :     ftM2graphNEL(ft1, W = from@x, V= rn, edgemode= eMode)
154 : maechler 871
155 : maechler 1348 }
156 :     setAs("TsparseMatrix", "graphNEL", Tsp2grNEL)
157 : maechler 871
158 : maechler 1348
159 : maechler 868 ### Subsetting -- basic things (drop = "missing") are done in ./Matrix.R
160 : maechler 687
161 : maechler 925 ### FIXME : we defer to the "*gT" -- conveniently, but not efficient for gC !
162 : maechler 687
163 : maechler 925 ## [dl]sparse -> [dl]gT -- treat both in one via superclass
164 :     ## -- more useful when have "z" (complex) and even more
165 : maechler 687
166 : maechler 925 setMethod("[", signature(x = "sparseMatrix", i = "index", j = "missing",
167 : maechler 868 drop = "logical"),
168 : maechler 2098 function (x, i,j, ..., drop) {
169 : maechler 1725 cld <- getClassDef(class(x))
170 : maechler 1751 if(!extends(cld, "generalMatrix")) x <- as(x, "generalMatrix")
171 : maechler 2098 ## viaCl <- paste(.M.kind(x, cld), "gTMatrix", sep='')
172 :     x <- callGeneric(x = as(x, "TsparseMatrix"), i=i, drop=drop)
173 : maechler 1751 ## try_as(x, c(cl, sub("T","C", viaCl)))
174 :     if(is(x, "Matrix") && extends(cld, "CsparseMatrix"))
175 :     as(x, "CsparseMatrix") else x
176 :     })
177 : maechler 687
178 : maechler 925 setMethod("[", signature(x = "sparseMatrix", i = "missing", j = "index",
179 : maechler 868 drop = "logical"),
180 : maechler 2098 function (x,i,j, ..., drop) {
181 : maechler 1725 cld <- getClassDef(class(x))
182 : maechler 1751 if(!extends(cld, "generalMatrix")) x <- as(x, "generalMatrix")
183 : maechler 2098 ## viaCl <- paste(.M.kind(x, cld), "gTMatrix", sep='')
184 :     x <- callGeneric(x = as(x, "TsparseMatrix"), j=j, drop=drop)
185 : maechler 1751 if(is(x, "Matrix") && extends(cld, "CsparseMatrix"))
186 :     as(x, "CsparseMatrix") else x
187 :     })
188 : maechler 868
189 : maechler 925 setMethod("[", signature(x = "sparseMatrix",
190 : maechler 886 i = "index", j = "index", drop = "logical"),
191 : maechler 2056 function (x, i, j, ..., drop) {
192 : maechler 1725 cld <- getClassDef(class(x))
193 : maechler 1665 ## be smart to keep symmetric indexing of <symm.Mat.> symmetric:
194 : maechler 1725 doSym <- (extends(cld, "symmetricMatrix") &&
195 : maechler 1665 length(i) == length(j) && all(i == j))
196 : maechler 1751 if(!doSym && !extends(cld, "generalMatrix"))
197 :     x <- as(x, "generalMatrix")
198 : maechler 2098 ## viaCl <- paste(.M.kind(x, cld),
199 :     ## if(doSym) "sTMatrix" else "gTMatrix", sep='')
200 :     x <- callGeneric(x = as(x, "TsparseMatrix"), i=i, j=j, drop=drop)
201 : maechler 1725 if(is(x, "Matrix") && extends(cld, "CsparseMatrix"))
202 : maechler 1751 as(x, "CsparseMatrix") else x
203 : maechler 1665 })
204 : maechler 868
205 :    
206 : maechler 1673 ## setReplaceMethod("[", .........)
207 :     ## -> ./Tsparse.R
208 :     ## & ./Csparse.R
209 :     ## FIXME: also for RsparseMatrix
210 : maechler 1226
211 :    
212 : maechler 1714 ## Group Methods
213 : maechler 1226
214 : maechler 1737 setMethod("Math",
215 :     signature(x = "sparseMatrix"),
216 :     function(x) callGeneric(as(x, "CsparseMatrix")))
217 : maechler 868
218 : maechler 1737 ## further group methods -> see ./Ops.R
219 : maechler 1472
220 :    
221 : maechler 1737
222 : maechler 687 ### --- show() method ---
223 :    
224 : maechler 1389 ## FIXME(?) -- ``merge this'' (at least ``synchronize'') with
225 :     ## - - - prMatrix() from ./Auxiliaries.R
226 : maechler 1705 ## FIXME: prTriang() in ./Auxiliaries.R should also get align = "fancy"
227 : maechler 1947 ## --> help for this is currently (rudimentary) in ../man/sparseMatrix-class.Rd
228 :     printSpMatrix <- function(x, digits = getOption("digits"),
229 :     maxp = getOption("max.print"), zero.print = ".",
230 :     col.names, note.dropping.colnames = TRUE,
231 :     col.trailer = '', align = c("fancy", "right"))
232 : maechler 687 {
233 : maechler 1903 cl <- getClassDef(class(x))
234 : maechler 1737 stopifnot(extends(cl, "sparseMatrix"))
235 : maechler 1903 d <- dim(x)
236 : maechler 1389 if(prod(d) > maxp) { # "Large" => will be "cut"
237 :     ## only coerce to dense that part which won't be cut :
238 :     nr <- maxp %/% d[2]
239 : maechler 1903 m <- as(x[1:max(1, nr), ,drop=FALSE], "Matrix")
240 : maechler 1389 } else {
241 : maechler 1903 m <- as(x, "matrix")
242 : maechler 1389 }
243 : maechler 1947 dn <- dimnames(m) ## will be === dimnames(cx)
244 : maechler 1737 logi <- extends(cl,"lsparseMatrix") || extends(cl,"nsparseMatrix")
245 : maechler 1315 if(logi)
246 : maechler 1947 cx <- array("N", dim(m), dimnames=dn)
247 : maechler 1673 else { ## numeric (or --not yet-- complex):
248 : maechler 1903 cx <- apply(m, 2, format)
249 :     if(is.null(dim(cx))) {# e.g. in 1 x 1 case
250 :     dim(cx) <- dim(m)
251 : maechler 1947 dimnames(cx) <- dn
252 : maechler 1315 }
253 : maechler 687 }
254 : maechler 1947 if (missing(col.names))
255 :     col.names <- {
256 :     if(!is.null(cc <- getOption("sparse.colnames")))
257 :     cc
258 :     else if(is.null(dn[[2]]))
259 :     FALSE
260 :     else { # has column names == dn[[2]]
261 :     ncol(x) < 10
262 :     }
263 :     }
264 :     if(identical(col.names, FALSE))
265 : maechler 1903 cx <- emptyColnames(cx, msg.if.not.empty = note.dropping.colnames)
266 : maechler 1947 else if(is.character(col.names)) {
267 :     stopifnot(length(col.names) == 1)
268 :     cn <- col.names
269 :     switch(substr(cn, 1,3),
270 :     "abb" = {
271 :     iarg <- as.integer(sub("^[^0-9]*", '', cn))
272 :     colnames(cx) <- abbreviate(colnames(cx), minlength = iarg)
273 :     },
274 :     "sub" = {
275 :     iarg <- as.integer(sub("^[^0-9]*", '', cn))
276 :     colnames(cx) <- substr(colnames(cx), 1, iarg)
277 :     },
278 :     stop("invalid 'col.names' string: ", cn))
279 :     }
280 :     ## else: nothing to do for col.names == TRUE
281 : maechler 687 if(is.logical(zero.print))
282 :     zero.print <- if(zero.print) "0" else " "
283 : maechler 1315 if(logi) {
284 : maechler 1903 cx[!m] <- zero.print
285 :     cx[m] <- "|"
286 : maechler 1315 } else { # non logical
287 :     ## show only "structural" zeros as 'zero.print', not all of them..
288 :     ## -> cannot use 'm'
289 : maechler 1903 d <- dim(cx)
290 :     ne <- length(iN0 <- 1L + encodeInd(non0ind(x, cl), nr = d[1]))
291 : maechler 1705 if(0 < ne && ne < prod(d)) {
292 :     align <- match.arg(align)
293 : maechler 2098 if(align == "fancy" && !is.integer(m)) {
294 : maechler 1705 fi <- apply(m, 2, format.info) ## fi[3,] == 0 <==> not expo.
295 :     ## now 'format' the zero.print by padding it with ' ' on the right:
296 :     ## case 1: non-exponent: fi[2,] + as.logical(fi[2,] > 0)
297 :     ## the column numbers of all 'zero' entries -- (*large*)
298 : maechler 1832 cols <- 1L + (0:(prod(d)-1L))[-iN0] %/% d[1]
299 : maechler 1705 pad <-
300 :     ifelse(fi[3,] == 0,
301 :     fi[2,] + as.logical(fi[2,] > 0),
302 :     ## exponential:
303 :     fi[2,] + fi[3,] + 4)
304 : maechler 1737 ## now be efficient ; sprintf() is relatively slow
305 :     ## and pad is much smaller than 'cols'; instead of "simply"
306 :     ## zero.print <- sprintf("%-*s", pad[cols] + 1, zero.print)
307 :     if(any(doP <- pad > 0)) {#
308 :     ## only pad those that need padding - *before* expanding
309 :     z.p.pad <- rep.int(zero.print, length(pad))
310 :     z.p.pad[doP] <- sprintf("%-*s", pad[doP] + 1, zero.print)
311 :     zero.print <- z.p.pad[cols]
312 :     }
313 :     else
314 :     zero.print <- rep.int(zero.print, length(cols))
315 : maechler 1705 } ## else "right" : nothing to do
316 :    
317 : maechler 1903 cx[-iN0] <- zero.print
318 : maechler 1705 } else if (ne == 0)# all zeroes
319 : maechler 1903 cx[] <- zero.print
320 : maechler 1315 }
321 : maechler 1870 if(col.trailer != '')
322 : maechler 1903 cx <- cbind(cx, col.trailer, deparse.level = 0)
323 : maechler 1705 ## right = TRUE : cheap attempt to get better "." alignment
324 : maechler 1903 print(cx, quote = FALSE, right = TRUE, max = maxp)
325 :     invisible(x)
326 : maechler 687 }
327 :    
328 : maechler 1947 setMethod("print", signature(x = "sparseMatrix"), printSpMatrix)
329 : maechler 1903
330 : maechler 687 setMethod("show", signature(object = "sparseMatrix"),
331 :     function(object) {
332 :     d <- dim(object)
333 :     cl <- class(object)
334 :     cat(sprintf('%d x %d sparse Matrix of class "%s"\n', d[1], d[2], cl))
335 :     maxp <- getOption("max.print")
336 :     if(prod(d) <= maxp)
337 : maechler 1947 printSpMatrix(object, maxp = maxp)
338 : maechler 687 else { ## d[1] > maxp / d[2] >= nr : -- this needs [,] working:
339 : maechler 1737
340 : maechler 687 nR <- d[1] # nrow
341 : maechler 1737 useW <- getOption("width") - (format.info(nR)[1] + 3+1)
342 :     ## space for "[<last>,] "
343 : maechler 1845
344 :     ## --> suppress rows and/or columns in printing ...
345 :    
346 : maechler 1737 suppCols <- (d[2] * 2 > useW)
347 :     nc <- if(suppCols) (useW - (1 + 6)) %/% 2 else d[2]
348 : maechler 1870 ## sp+ col.trailer
349 :     col.trailer <- if(suppCols) "......" else ""
350 : maechler 1737 nr <- maxp %/% nc
351 :     suppRows <- (nr < nR)
352 :     if(suppRows) {
353 :     if(suppCols)
354 :     object <- object[ , 1:nc, drop = FALSE]
355 :     n2 <- ceiling(nr / 2)
356 : maechler 1947 printSpMatrix(object[seq_len(min(nR, max(1, n2))), , drop=FALSE],
357 :     col.trailer = col.trailer)
358 : maechler 1737 cat("\n ..............................",
359 :     "\n ..........suppressing rows in show(); maybe adjust 'options(max.print= *)'",
360 :     "\n ..............................\n\n", sep='')
361 :     ## tail() automagically uses "[..,]" rownames:
362 : maechler 1947 printSpMatrix(tail(object, max(1, nr-n2)),
363 :     col.trailer = col.trailer)
364 : maechler 1737 }
365 :     else if(suppCols) {
366 : maechler 1947 printSpMatrix(object[ , 1:nc , drop = FALSE],
367 :     col.trailer = col.trailer)
368 : maechler 1737
369 :     cat("\n .....suppressing columns in show(); maybe adjust 'options(max.print= *)'",
370 :     "\n ..............................\n", sep='')
371 :     }
372 : maechler 1947 else stop("logic programming error in printSpMatrix(), please report")
373 : maechler 1737
374 : maechler 687 invisible(object)
375 :     }
376 :     })
377 : maechler 886
378 :    
379 : maechler 1852 ## For very large and very sparse matrices, the above show()
380 :     ## is not really helpful; Use summary() as an alternative:
381 :    
382 :     setMethod("summary", signature(object = "sparseMatrix"),
383 :     function(object, ...) {
384 :     d <- dim(object)
385 :     T <- as(object, "TsparseMatrix")
386 :     ## return a data frame (int, int, {double|logical|...}) :
387 :     r <- data.frame(i = T@i + 1L, j = T@j + 1L, x = T@x)
388 :     attr(r, "header") <-
389 : maechler 1855 sprintf('%d x %d sparse Matrix of class "%s", with %d entries',
390 :     d[1], d[2], class(object), nnzero(object))
391 : maechler 1852 ## use ole' S3 technology for such a simple case
392 :     class(r) <- c("sparseSummary", class(r))
393 :     r
394 :     })
395 :    
396 :     print.sparseSummary <- function (x, ...) {
397 :     cat(attr(x, "header"),"\n")
398 :     print.data.frame(x, ...)
399 :     invisible(x)
400 :     }
401 :    
402 : maechler 1108 setMethod("isSymmetric", signature(object = "sparseMatrix"),
403 : maechler 973 function(object, tol = 100*.Machine$double.eps) {
404 : maechler 886 ## pretest: is it square?
405 :     d <- dim(object)
406 :     if(d[1] != d[2]) return(FALSE)
407 :     ## else slower test
408 : maechler 973 if (is(object, "dMatrix"))
409 : maechler 886 ## use gC; "T" (triplet) is *not* unique!
410 : maechler 1659 isTRUE(all.equal(.as.dgC.0.factors( object),
411 :     .as.dgC.0.factors(t(object)), tol = tol))
412 : maechler 973 else if (is(object, "lMatrix"))
413 : maechler 886 ## test for exact equality; FIXME(?): identical() too strict?
414 :     identical(as(object, "lgCMatrix"),
415 :     as(t(object), "lgCMatrix"))
416 : maechler 1548 else if (is(object, "nMatrix"))
417 :     ## test for exact equality; FIXME(?): identical() too strict?
418 :     identical(as(object, "ngCMatrix"),
419 :     as(t(object), "ngCMatrix"))
420 : maechler 886 else stop("not yet implemented")
421 :     })
422 : maechler 1174
423 : maechler 1238
424 : maechler 1659 ## These two are not (yet?) exported:
425 : maechler 1174 setMethod("isTriangular", signature(object = "sparseMatrix"),
426 : maechler 1238 function(object, upper = NA)
427 :     isTriC(as(object, "CsparseMatrix"), upper))
428 : maechler 1174
429 :     setMethod("isDiagonal", signature(object = "sparseMatrix"),
430 :     function(object) {
431 : maechler 1799 d <- dim(object)
432 :     if(d[1] != d[2]) return(FALSE)
433 :     ## else
434 : maechler 1174 gT <- as(object, "TsparseMatrix")
435 :     all(gT@i == gT@j)
436 :     })
437 :    
438 : maechler 1290
439 : maechler 1472 setMethod("diag", signature(x = "sparseMatrix"),
440 :     function(x, nrow, ncol = n) diag(as(x, "CsparseMatrix")))
441 :    
442 : maechler 1845 setMethod("dim<-", signature(x = "sparseMatrix", value = "ANY"),
443 :     function(x, value) {
444 :     if(!is.numeric(value) || length(value) != 2)
445 :     stop("dim(.) value must be numeric of length 2")
446 :     if(prod(dim(x)) != prod(value <- as.integer(value)))
447 :     stop("dimensions don't match the number of cells")
448 :     ## be careful to keep things sparse
449 :     as(spV2M(as(x, "sparseVector"), nrow=value[1], ncol=value[2]),
450 :     class(x))
451 :     })
452 :    
453 :    
454 : maechler 2005 setMethod("norm", signature(x = "sparseMatrix", type = "character"),
455 :     function(x, type, ...) {
456 :     ## as(*, "dsparseMatrix") fails e.g. for "lgT*", but why use it anyway?
457 :     ## if(!is(x, "dsparseMatrix"))
458 :     ## x <- as(x, "dsparseMatrix")
459 :     type <- toupper(substr(type[1], 1, 1))
460 :     switch(type, ## max(<empty>, 0) |--> 0
461 :     "O" = ,
462 :     "1" = max(colSums(abs(x)), 0), ## One-norm (L_1)
463 :     "I" = max(rowSums(abs(x)), 0), ## L_Infinity
464 :     "F" = sqrt(sum(x^2)), ## Frobenius
465 :     "M" = max(abs(x), 0), ## Maximum modulus of all
466 :     ## otherwise:
467 :     stop("invalid 'type'"))
468 :     })
469 :    
470 : maechler 2048 setMethod("rcond", signature(x = "sparseMatrix", type = "character"),
471 :     function(x, type, ...) {
472 : maechler 2072 d <- dim(x)
473 : maechler 2102 ## FIXME: qr.R(qr(.)) warns about differing R (permutation!)
474 :     ## really fix qr.R() *or* go via dense in any cases
475 : maechler 2072 rcond(if(d[1] == d[2]) {
476 : maechler 2102 warning("rcond(.) via sparse -> dense coercion")
477 : maechler 2072 as(x, "denseMatrix")
478 :     } else if(d[1] > d[2]) qr.R(qr(x)) else qr.R(qr(t(x))),
479 :     type = type)
480 :     })
481 : maechler 2048
482 : maechler 2096 setMethod("cov2cor", signature(V = "sparseMatrix"),
483 :     function(V) {
484 :     ## like stats::cov2cor() but making sure all matrices stay sparse
485 :     p <- (d <- dim(V))[1]
486 :     if (p != d[2])
487 :     stop("'V' is not a *square* matrix")
488 :     if(!is(V, "dMatrix"))
489 :     V <- as(V, "dMatrix")# actually "dsparseMatrix"
490 :     Is <- sqrt(1/diag(V))
491 :     if (any(!is.finite(Is))) ## original had 0 or NA
492 :     warning("diag(.) had 0 or NA entries; non-finite result is doubtful")
493 :     ## TODO: if <diagonal> %*% <sparse> was implemented more efficiently
494 :     ## we'd rather use that!
495 :     Is <- as(Diagonal(x = Is), "sparseMatrix")
496 :     r <- Is %*% V %*% Is
497 :     r[cbind(1L:p,1L:p)] <- 1 # exact in diagonal
498 :     as(r, "symmetricMatrix")
499 :     })
500 : maechler 2072
501 : maechler 2096
502 :    
503 : bates 1895 lm.fit.sparse <-
504 :     function(x, y, offset = NULL, method = c("qr", "cholesky"),
505 :     tol = 1e-7, singular.ok = TRUE, transpose = FALSE, ...)
506 : maechler 2043 ### Fit a linear model, __ given __ a sparse model matrix 'x'
507 :     ### using a sparse QR or a sparse Cholesky factorization
508 : bates 1895 {
509 :     stopifnot(is(x, "dsparseMatrix"))
510 : maechler 2005 ## if(!is(x, "dsparseMatrix"))
511 :     ## x <- as(x, "dsparseMatrix")
512 : bates 1895 yy <- as.numeric(y)
513 :     if (!is.null(offset)) {
514 : maechler 2005 stopifnot(length(offset) == length(y))
515 :     yy <- yy - as.numeric(offset)
516 : bates 1895 }
517 :     ans <- switch(as.character(method)[1],
518 : maechler 2005 cholesky =
519 :     .Call(dgCMatrix_cholsol,
520 :     as(if (transpose) x else t(x), "dgCMatrix"), yy),
521 :     qr =
522 :     .Call(dgCMatrix_qrsol,
523 :     as(if (transpose) t(x) else x, "dgCMatrix"), yy),
524 :     ## otherwise:
525 :     stop("unknown method ", dQuote(method))
526 :     )
527 : bates 1895 ans
528 :     }
529 :    
530 : maechler 1911 fac2sparse <- function(from, to = c("d","i","l","n","z"))
531 :     {
532 :     ## factor(-like) --> sparseMatrix {also works for integer, character}
533 :     levs <- levels(fact <- factor(from)) # drop unused levels
534 :     n <- length(fact)
535 :     to <- match.arg(to)
536 :     res <- new(paste(to, "gCMatrix", sep=''))
537 :     res@i <- as.integer(fact) - 1L # 0-based
538 :     res@p <- 0:n
539 :     res@Dim <- c(length(levs), n)
540 :     res@Dimnames <- list(levs, NULL)
541 :     if(to != "n")
542 :     res@x <- rep.int(switch(to,
543 :     "d" = 1., "i" = 1L, "l" = TRUE, "z" = 1+0i),
544 :     n)
545 :     res
546 :     }
547 : bates 1895
548 : maechler 1911 setAs("factor", "sparseMatrix", function(from) fac2sparse(from, to = "d"))
549 : bates 2094
550 : maechler 2095 ## xtabs returning a sparse matrix. This is cut'n'paste
551 :     ## of xtabs() in <Rsrc>/src/library/stats/R/xtabs.R ;
552 :     ## with the new argument 'sparse'
553 :     xtabs <- function(formula = ~., data = parent.frame(), subset, sparse = FALSE,
554 :     na.action, exclude = c(NA, NaN), drop.unused.levels = FALSE)
555 : bates 2094 {
556 : maechler 2095 if (missing(formula) && missing(data))
557 :     stop("must supply either 'formula' or 'data'")
558 :     if(!missing(formula)){
559 :     ## We need to coerce the formula argument now, but model.frame
560 :     ## will coerce the original version later.
561 :     formula <- as.formula(formula)
562 :     if (!inherits(formula, "formula"))
563 :     stop("'formula' missing or incorrect")
564 : bates 2094 }
565 : maechler 2095 if (any(attr(terms(formula, data = data), "order") > 1))
566 :     stop("interactions are not allowed")
567 : bates 2094 m <- match.call(expand.dots = FALSE)
568 : maechler 2095 if (is.matrix(eval(m$data, parent.frame())))
569 :     m$data <- as.data.frame(data)
570 :     m$... <- m$exclude <- m$drop.unused.levels <- m$sparse <- NULL
571 : bates 2094 m[[1]] <- as.name("model.frame")
572 :     mf <- eval(m, parent.frame())
573 :     if(length(formula) == 2) {
574 :     by <- mf
575 :     y <- NULL
576 :     }
577 :     else {
578 :     i <- attr(attr(mf, "terms"), "response")
579 :     by <- mf[-i]
580 :     y <- mf[[i]]
581 :     }
582 :     by <- lapply(by, function(u) {
583 :     if(!is.factor(u)) u <- factor(u, exclude = exclude)
584 :     u[ , drop = drop.unused.levels]
585 :     })
586 : maechler 2095 if(!sparse) { ## identical to stats::xtabs
587 :     x <-
588 :     if(is.null(y))
589 :     do.call("table", by)
590 :     else if(NCOL(y) == 1)
591 :     tapply(y, by, sum)
592 :     else {
593 :     z <- lapply(as.data.frame(y), tapply, by, sum)
594 :     array(unlist(z),
595 :     dim = c(dim(z[[1]]), length(z)),
596 :     dimnames = c(dimnames(z[[1]]), list(names(z))))
597 :     }
598 :     x[is.na(x)] <- 0
599 :     class(x) <- c("xtabs", "table")
600 :     attr(x, "call") <- match.call()
601 :     x
602 :    
603 :     } else { ## sparse
604 :     if (length(by) != 2)
605 :     stop("xtabs(*, sparse=TRUE) applies only to two-way tables")
606 :     rows <- by[[1]]
607 :     cols <- by[[2]]
608 :     rl <- levels(rows)
609 :     cl <- levels(cols)
610 :     if (is.null(y))
611 :     y <- rep.int(1, length(rows))
612 :     as(new("dgTMatrix",
613 :     i = as.integer(rows) - 1L,
614 :     j = as.integer(cols) - 1L,
615 : bates 2097 x = as.double(y),
616 : maechler 2095 Dim = c(length(rl), length(cl)),
617 :     Dimnames = list(rl, cl)), "CsparseMatrix")
618 :     }
619 : bates 2094 }

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