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 2158 - (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 2113 ##> why should this be needed; can still happen in <Tsparse>[..]:
171 :     ##> if(!extends(cld, "generalMatrix")) x <- as(x, "generalMatrix")
172 :     ## viaCl <- paste(.M.kind(x, cld), "gTMatrix", sep='')
173 :     x <- as(x, "TsparseMatrix")[i, , drop=drop]
174 :     ##simpler than x <- callGeneric(x = as(x, "TsparseMatrix"), i=i, drop=drop)
175 : maechler 1751 ## try_as(x, c(cl, sub("T","C", viaCl)))
176 :     if(is(x, "Matrix") && extends(cld, "CsparseMatrix"))
177 :     as(x, "CsparseMatrix") else x
178 :     })
179 : maechler 687
180 : maechler 925 setMethod("[", signature(x = "sparseMatrix", i = "missing", j = "index",
181 : maechler 868 drop = "logical"),
182 : maechler 2098 function (x,i,j, ..., drop) {
183 : maechler 1725 cld <- getClassDef(class(x))
184 : maechler 2113 ##> why should this be needed; can still happen in <Tsparse>[..]:
185 :     ##> if(!extends(cld, "generalMatrix")) x <- as(x, "generalMatrix")
186 :     ## viaCl <- paste(.M.kind(x, cld), "gTMatrix", sep='')
187 :    
188 :     x <- as(x, "TsparseMatrix")[, j, drop=drop]
189 :     ##simpler than x <- callGeneric(x = as(x, "TsparseMatrix"), j=j, drop=drop)
190 : maechler 1751 if(is(x, "Matrix") && extends(cld, "CsparseMatrix"))
191 :     as(x, "CsparseMatrix") else x
192 :     })
193 : maechler 868
194 : maechler 925 setMethod("[", signature(x = "sparseMatrix",
195 : maechler 886 i = "index", j = "index", drop = "logical"),
196 : maechler 2056 function (x, i, j, ..., drop) {
197 : maechler 1725 cld <- getClassDef(class(x))
198 : maechler 1665 ## be smart to keep symmetric indexing of <symm.Mat.> symmetric:
199 : maechler 2113 ##> doSym <- (extends(cld, "symmetricMatrix") &&
200 :     ##> length(i) == length(j) && all(i == j))
201 :     ##> why should this be needed; can still happen in <Tsparse>[..]:
202 :     ##> if(!doSym && !extends(cld, "generalMatrix"))
203 :     ##> x <- as(x, "generalMatrix")
204 :     ## viaCl <- paste(.M.kind(x, cld),
205 :     ## if(doSym) "sTMatrix" else "gTMatrix", sep='')
206 :     x <- as(x, "TsparseMatrix")[i, j, drop=drop]
207 : maechler 1725 if(is(x, "Matrix") && extends(cld, "CsparseMatrix"))
208 : maechler 1751 as(x, "CsparseMatrix") else x
209 : maechler 1665 })
210 : maechler 868
211 :    
212 : maechler 1673 ## setReplaceMethod("[", .........)
213 :     ## -> ./Tsparse.R
214 :     ## & ./Csparse.R
215 :     ## FIXME: also for RsparseMatrix
216 : maechler 1226
217 :    
218 : maechler 1714 ## Group Methods
219 : maechler 1226
220 : maechler 1737 setMethod("Math",
221 :     signature(x = "sparseMatrix"),
222 :     function(x) callGeneric(as(x, "CsparseMatrix")))
223 : maechler 868
224 : maechler 1737 ## further group methods -> see ./Ops.R
225 : maechler 1472
226 :    
227 : maechler 1737
228 : maechler 687 ### --- show() method ---
229 :    
230 : maechler 1389 ## FIXME(?) -- ``merge this'' (at least ``synchronize'') with
231 :     ## - - - prMatrix() from ./Auxiliaries.R
232 : maechler 1705 ## FIXME: prTriang() in ./Auxiliaries.R should also get align = "fancy"
233 : maechler 1947 ## --> help for this is currently (rudimentary) in ../man/sparseMatrix-class.Rd
234 :     printSpMatrix <- function(x, digits = getOption("digits"),
235 :     maxp = getOption("max.print"), zero.print = ".",
236 :     col.names, note.dropping.colnames = TRUE,
237 :     col.trailer = '', align = c("fancy", "right"))
238 : maechler 687 {
239 : maechler 1903 cl <- getClassDef(class(x))
240 : maechler 1737 stopifnot(extends(cl, "sparseMatrix"))
241 : maechler 1903 d <- dim(x)
242 : maechler 1389 if(prod(d) > maxp) { # "Large" => will be "cut"
243 :     ## only coerce to dense that part which won't be cut :
244 :     nr <- maxp %/% d[2]
245 : maechler 1903 m <- as(x[1:max(1, nr), ,drop=FALSE], "Matrix")
246 : maechler 1389 } else {
247 : maechler 1903 m <- as(x, "matrix")
248 : maechler 1389 }
249 : maechler 1947 dn <- dimnames(m) ## will be === dimnames(cx)
250 : maechler 1737 logi <- extends(cl,"lsparseMatrix") || extends(cl,"nsparseMatrix")
251 : maechler 1315 if(logi)
252 : maechler 1947 cx <- array("N", dim(m), dimnames=dn)
253 : maechler 1673 else { ## numeric (or --not yet-- complex):
254 : maechler 1903 cx <- apply(m, 2, format)
255 :     if(is.null(dim(cx))) {# e.g. in 1 x 1 case
256 :     dim(cx) <- dim(m)
257 : maechler 1947 dimnames(cx) <- dn
258 : maechler 1315 }
259 : maechler 687 }
260 : maechler 1947 if (missing(col.names))
261 :     col.names <- {
262 :     if(!is.null(cc <- getOption("sparse.colnames")))
263 :     cc
264 :     else if(is.null(dn[[2]]))
265 :     FALSE
266 :     else { # has column names == dn[[2]]
267 :     ncol(x) < 10
268 :     }
269 :     }
270 :     if(identical(col.names, FALSE))
271 : maechler 1903 cx <- emptyColnames(cx, msg.if.not.empty = note.dropping.colnames)
272 : maechler 1947 else if(is.character(col.names)) {
273 :     stopifnot(length(col.names) == 1)
274 :     cn <- col.names
275 :     switch(substr(cn, 1,3),
276 :     "abb" = {
277 :     iarg <- as.integer(sub("^[^0-9]*", '', cn))
278 :     colnames(cx) <- abbreviate(colnames(cx), minlength = iarg)
279 :     },
280 :     "sub" = {
281 :     iarg <- as.integer(sub("^[^0-9]*", '', cn))
282 :     colnames(cx) <- substr(colnames(cx), 1, iarg)
283 :     },
284 :     stop("invalid 'col.names' string: ", cn))
285 :     }
286 :     ## else: nothing to do for col.names == TRUE
287 : maechler 687 if(is.logical(zero.print))
288 :     zero.print <- if(zero.print) "0" else " "
289 : maechler 1315 if(logi) {
290 : maechler 1903 cx[!m] <- zero.print
291 :     cx[m] <- "|"
292 : maechler 1315 } else { # non logical
293 :     ## show only "structural" zeros as 'zero.print', not all of them..
294 :     ## -> cannot use 'm'
295 : maechler 1903 d <- dim(cx)
296 :     ne <- length(iN0 <- 1L + encodeInd(non0ind(x, cl), nr = d[1]))
297 : maechler 1705 if(0 < ne && ne < prod(d)) {
298 :     align <- match.arg(align)
299 : maechler 2098 if(align == "fancy" && !is.integer(m)) {
300 : maechler 1705 fi <- apply(m, 2, format.info) ## fi[3,] == 0 <==> not expo.
301 :     ## now 'format' the zero.print by padding it with ' ' on the right:
302 :     ## case 1: non-exponent: fi[2,] + as.logical(fi[2,] > 0)
303 :     ## the column numbers of all 'zero' entries -- (*large*)
304 : maechler 1832 cols <- 1L + (0:(prod(d)-1L))[-iN0] %/% d[1]
305 : maechler 1705 pad <-
306 :     ifelse(fi[3,] == 0,
307 :     fi[2,] + as.logical(fi[2,] > 0),
308 :     ## exponential:
309 :     fi[2,] + fi[3,] + 4)
310 : maechler 1737 ## now be efficient ; sprintf() is relatively slow
311 :     ## and pad is much smaller than 'cols'; instead of "simply"
312 :     ## zero.print <- sprintf("%-*s", pad[cols] + 1, zero.print)
313 :     if(any(doP <- pad > 0)) {#
314 :     ## only pad those that need padding - *before* expanding
315 :     z.p.pad <- rep.int(zero.print, length(pad))
316 :     z.p.pad[doP] <- sprintf("%-*s", pad[doP] + 1, zero.print)
317 :     zero.print <- z.p.pad[cols]
318 :     }
319 :     else
320 :     zero.print <- rep.int(zero.print, length(cols))
321 : maechler 1705 } ## else "right" : nothing to do
322 :    
323 : maechler 1903 cx[-iN0] <- zero.print
324 : maechler 1705 } else if (ne == 0)# all zeroes
325 : maechler 1903 cx[] <- zero.print
326 : maechler 1315 }
327 : maechler 1870 if(col.trailer != '')
328 : maechler 1903 cx <- cbind(cx, col.trailer, deparse.level = 0)
329 : maechler 1705 ## right = TRUE : cheap attempt to get better "." alignment
330 : maechler 1903 print(cx, quote = FALSE, right = TRUE, max = maxp)
331 :     invisible(x)
332 : maechler 687 }
333 :    
334 : maechler 1947 setMethod("print", signature(x = "sparseMatrix"), printSpMatrix)
335 : maechler 1903
336 : maechler 687 setMethod("show", signature(object = "sparseMatrix"),
337 :     function(object) {
338 :     d <- dim(object)
339 :     cl <- class(object)
340 :     cat(sprintf('%d x %d sparse Matrix of class "%s"\n', d[1], d[2], cl))
341 :     maxp <- getOption("max.print")
342 :     if(prod(d) <= maxp)
343 : maechler 1947 printSpMatrix(object, maxp = maxp)
344 : maechler 687 else { ## d[1] > maxp / d[2] >= nr : -- this needs [,] working:
345 : maechler 1737
346 : maechler 687 nR <- d[1] # nrow
347 : maechler 1737 useW <- getOption("width") - (format.info(nR)[1] + 3+1)
348 :     ## space for "[<last>,] "
349 : maechler 1845
350 :     ## --> suppress rows and/or columns in printing ...
351 :    
352 : maechler 1737 suppCols <- (d[2] * 2 > useW)
353 :     nc <- if(suppCols) (useW - (1 + 6)) %/% 2 else d[2]
354 : maechler 1870 ## sp+ col.trailer
355 :     col.trailer <- if(suppCols) "......" else ""
356 : maechler 1737 nr <- maxp %/% nc
357 :     suppRows <- (nr < nR)
358 :     if(suppRows) {
359 :     if(suppCols)
360 :     object <- object[ , 1:nc, drop = FALSE]
361 :     n2 <- ceiling(nr / 2)
362 : maechler 1947 printSpMatrix(object[seq_len(min(nR, max(1, n2))), , drop=FALSE],
363 :     col.trailer = col.trailer)
364 : maechler 1737 cat("\n ..............................",
365 :     "\n ..........suppressing rows in show(); maybe adjust 'options(max.print= *)'",
366 :     "\n ..............................\n\n", sep='')
367 :     ## tail() automagically uses "[..,]" rownames:
368 : maechler 1947 printSpMatrix(tail(object, max(1, nr-n2)),
369 :     col.trailer = col.trailer)
370 : maechler 1737 }
371 :     else if(suppCols) {
372 : maechler 1947 printSpMatrix(object[ , 1:nc , drop = FALSE],
373 :     col.trailer = col.trailer)
374 : maechler 1737
375 :     cat("\n .....suppressing columns in show(); maybe adjust 'options(max.print= *)'",
376 :     "\n ..............................\n", sep='')
377 :     }
378 : maechler 1947 else stop("logic programming error in printSpMatrix(), please report")
379 : maechler 1737
380 : maechler 687 invisible(object)
381 :     }
382 :     })
383 : maechler 886
384 :    
385 : maechler 1852 ## For very large and very sparse matrices, the above show()
386 :     ## is not really helpful; Use summary() as an alternative:
387 :    
388 :     setMethod("summary", signature(object = "sparseMatrix"),
389 :     function(object, ...) {
390 :     d <- dim(object)
391 :     T <- as(object, "TsparseMatrix")
392 :     ## return a data frame (int, int, {double|logical|...}) :
393 :     r <- data.frame(i = T@i + 1L, j = T@j + 1L, x = T@x)
394 :     attr(r, "header") <-
395 : maechler 1855 sprintf('%d x %d sparse Matrix of class "%s", with %d entries',
396 :     d[1], d[2], class(object), nnzero(object))
397 : maechler 1852 ## use ole' S3 technology for such a simple case
398 :     class(r) <- c("sparseSummary", class(r))
399 :     r
400 :     })
401 :    
402 :     print.sparseSummary <- function (x, ...) {
403 :     cat(attr(x, "header"),"\n")
404 :     print.data.frame(x, ...)
405 :     invisible(x)
406 :     }
407 :    
408 : maechler 1108 setMethod("isSymmetric", signature(object = "sparseMatrix"),
409 : maechler 2113 function(object, tol = 100*.Machine$double.eps, ...) {
410 : maechler 886 ## pretest: is it square?
411 :     d <- dim(object)
412 :     if(d[1] != d[2]) return(FALSE)
413 : maechler 2115
414 :     ## else slower test using t() --
415 :    
416 :     ## FIXME (for tol = 0): use cholmod_symmetry(A, 1, ...)
417 :     ## for tol > 0 should modify cholmod_symmetry(..) to work with tol
418 :    
419 :     ## or slightly simpler, rename and export is_sym() in ../src/cs_utils.c
420 :    
421 :    
422 : maechler 973 if (is(object, "dMatrix"))
423 : maechler 886 ## use gC; "T" (triplet) is *not* unique!
424 : maechler 1659 isTRUE(all.equal(.as.dgC.0.factors( object),
425 : maechler 2113 .as.dgC.0.factors(t(object)),
426 :     tol = tol, ...))
427 : maechler 973 else if (is(object, "lMatrix"))
428 : maechler 886 ## test for exact equality; FIXME(?): identical() too strict?
429 : maechler 2115 identical(as( object, "lgCMatrix"),
430 : maechler 886 as(t(object), "lgCMatrix"))
431 : maechler 1548 else if (is(object, "nMatrix"))
432 :     ## test for exact equality; FIXME(?): identical() too strict?
433 : maechler 2115 identical(as( object, "ngCMatrix"),
434 : maechler 1548 as(t(object), "ngCMatrix"))
435 : maechler 886 else stop("not yet implemented")
436 :     })
437 : maechler 1174
438 : maechler 1238
439 : maechler 2110 setMethod("isTriangular", signature(object = "CsparseMatrix"), isTriC)
440 :     setMethod("isTriangular", signature(object = "TsparseMatrix"), isTriT)
441 : maechler 1174
442 :     setMethod("isDiagonal", signature(object = "sparseMatrix"),
443 :     function(object) {
444 : maechler 1799 d <- dim(object)
445 :     if(d[1] != d[2]) return(FALSE)
446 :     ## else
447 : maechler 1174 gT <- as(object, "TsparseMatrix")
448 :     all(gT@i == gT@j)
449 :     })
450 :    
451 : maechler 1290
452 : maechler 1472 setMethod("diag", signature(x = "sparseMatrix"),
453 :     function(x, nrow, ncol = n) diag(as(x, "CsparseMatrix")))
454 :    
455 : maechler 1845 setMethod("dim<-", signature(x = "sparseMatrix", value = "ANY"),
456 :     function(x, value) {
457 :     if(!is.numeric(value) || length(value) != 2)
458 :     stop("dim(.) value must be numeric of length 2")
459 :     if(prod(dim(x)) != prod(value <- as.integer(value)))
460 :     stop("dimensions don't match the number of cells")
461 :     ## be careful to keep things sparse
462 :     as(spV2M(as(x, "sparseVector"), nrow=value[1], ncol=value[2]),
463 :     class(x))
464 :     })
465 :    
466 :    
467 : maechler 2005 setMethod("norm", signature(x = "sparseMatrix", type = "character"),
468 :     function(x, type, ...) {
469 :     ## as(*, "dsparseMatrix") fails e.g. for "lgT*", but why use it anyway?
470 :     ## if(!is(x, "dsparseMatrix"))
471 :     ## x <- as(x, "dsparseMatrix")
472 :     type <- toupper(substr(type[1], 1, 1))
473 :     switch(type, ## max(<empty>, 0) |--> 0
474 :     "O" = ,
475 :     "1" = max(colSums(abs(x)), 0), ## One-norm (L_1)
476 :     "I" = max(rowSums(abs(x)), 0), ## L_Infinity
477 :     "F" = sqrt(sum(x^2)), ## Frobenius
478 :     "M" = max(abs(x), 0), ## Maximum modulus of all
479 :     ## otherwise:
480 :     stop("invalid 'type'"))
481 :     })
482 :    
483 : maechler 2158 setMethod("rcond", signature(x = "sparseMatrix", norm = "character"),
484 :     function(x, norm, ...) {
485 : maechler 2072 d <- dim(x)
486 : maechler 2102 ## FIXME: qr.R(qr(.)) warns about differing R (permutation!)
487 :     ## really fix qr.R() *or* go via dense in any cases
488 : maechler 2072 rcond(if(d[1] == d[2]) {
489 : maechler 2102 warning("rcond(.) via sparse -> dense coercion")
490 : maechler 2072 as(x, "denseMatrix")
491 :     } else if(d[1] > d[2]) qr.R(qr(x)) else qr.R(qr(t(x))),
492 : maechler 2158 norm = norm, ...)
493 : maechler 2072 })
494 : maechler 2048
495 : maechler 2096 setMethod("cov2cor", signature(V = "sparseMatrix"),
496 :     function(V) {
497 :     ## like stats::cov2cor() but making sure all matrices stay sparse
498 :     p <- (d <- dim(V))[1]
499 :     if (p != d[2])
500 :     stop("'V' is not a *square* matrix")
501 :     if(!is(V, "dMatrix"))
502 :     V <- as(V, "dMatrix")# actually "dsparseMatrix"
503 :     Is <- sqrt(1/diag(V))
504 :     if (any(!is.finite(Is))) ## original had 0 or NA
505 :     warning("diag(.) had 0 or NA entries; non-finite result is doubtful")
506 :     ## TODO: if <diagonal> %*% <sparse> was implemented more efficiently
507 :     ## we'd rather use that!
508 :     Is <- as(Diagonal(x = Is), "sparseMatrix")
509 :     r <- Is %*% V %*% Is
510 :     r[cbind(1L:p,1L:p)] <- 1 # exact in diagonal
511 :     as(r, "symmetricMatrix")
512 :     })
513 : maechler 2072
514 : maechler 2144 setMethod("is.na", signature(x = "sparseMatrix"),
515 :     function(x) {
516 :     if(any((inax <- is.na(x@x)))) {
517 :     r <- as(x, "lMatrix")# will be "lsparseMatrix" - *has* x slot
518 :     r@x <- inax
519 :     as(r, "nMatrix") # a 'pattern matrix
520 :     } else {
521 :     d <- x@Dim
522 :     new("ngCMatrix", Dim = d, Dimnames = dimnames(x),
523 :     i = integer(0), p = rep.int(0L, d[2]+1L))
524 :     }
525 :     })
526 : maechler 2096
527 :    
528 : bates 1895 lm.fit.sparse <-
529 :     function(x, y, offset = NULL, method = c("qr", "cholesky"),
530 :     tol = 1e-7, singular.ok = TRUE, transpose = FALSE, ...)
531 : maechler 2043 ### Fit a linear model, __ given __ a sparse model matrix 'x'
532 :     ### using a sparse QR or a sparse Cholesky factorization
533 : bates 1895 {
534 :     stopifnot(is(x, "dsparseMatrix"))
535 : maechler 2005 ## if(!is(x, "dsparseMatrix"))
536 :     ## x <- as(x, "dsparseMatrix")
537 : bates 1895 yy <- as.numeric(y)
538 :     if (!is.null(offset)) {
539 : maechler 2005 stopifnot(length(offset) == length(y))
540 :     yy <- yy - as.numeric(offset)
541 : bates 1895 }
542 :     ans <- switch(as.character(method)[1],
543 : maechler 2005 cholesky =
544 :     .Call(dgCMatrix_cholsol,
545 :     as(if (transpose) x else t(x), "dgCMatrix"), yy),
546 :     qr =
547 :     .Call(dgCMatrix_qrsol,
548 :     as(if (transpose) t(x) else x, "dgCMatrix"), yy),
549 :     ## otherwise:
550 :     stop("unknown method ", dQuote(method))
551 :     )
552 : bates 1895 ans
553 :     }
554 :    
555 : maechler 1911 fac2sparse <- function(from, to = c("d","i","l","n","z"))
556 :     {
557 :     ## factor(-like) --> sparseMatrix {also works for integer, character}
558 :     levs <- levels(fact <- factor(from)) # drop unused levels
559 :     n <- length(fact)
560 :     to <- match.arg(to)
561 :     res <- new(paste(to, "gCMatrix", sep=''))
562 :     res@i <- as.integer(fact) - 1L # 0-based
563 :     res@p <- 0:n
564 :     res@Dim <- c(length(levs), n)
565 :     res@Dimnames <- list(levs, NULL)
566 :     if(to != "n")
567 :     res@x <- rep.int(switch(to,
568 :     "d" = 1., "i" = 1L, "l" = TRUE, "z" = 1+0i),
569 :     n)
570 :     res
571 :     }
572 : bates 1895
573 : maechler 1911 setAs("factor", "sparseMatrix", function(from) fac2sparse(from, to = "d"))
574 : bates 2094
575 : maechler 2095 ## xtabs returning a sparse matrix. This is cut'n'paste
576 :     ## of xtabs() in <Rsrc>/src/library/stats/R/xtabs.R ;
577 :     ## with the new argument 'sparse'
578 :     xtabs <- function(formula = ~., data = parent.frame(), subset, sparse = FALSE,
579 :     na.action, exclude = c(NA, NaN), drop.unused.levels = FALSE)
580 : bates 2094 {
581 : maechler 2095 if (missing(formula) && missing(data))
582 :     stop("must supply either 'formula' or 'data'")
583 :     if(!missing(formula)){
584 :     ## We need to coerce the formula argument now, but model.frame
585 :     ## will coerce the original version later.
586 :     formula <- as.formula(formula)
587 :     if (!inherits(formula, "formula"))
588 :     stop("'formula' missing or incorrect")
589 : bates 2094 }
590 : maechler 2095 if (any(attr(terms(formula, data = data), "order") > 1))
591 :     stop("interactions are not allowed")
592 : bates 2094 m <- match.call(expand.dots = FALSE)
593 : maechler 2095 if (is.matrix(eval(m$data, parent.frame())))
594 :     m$data <- as.data.frame(data)
595 :     m$... <- m$exclude <- m$drop.unused.levels <- m$sparse <- NULL
596 : bates 2094 m[[1]] <- as.name("model.frame")
597 :     mf <- eval(m, parent.frame())
598 :     if(length(formula) == 2) {
599 :     by <- mf
600 :     y <- NULL
601 :     }
602 :     else {
603 :     i <- attr(attr(mf, "terms"), "response")
604 :     by <- mf[-i]
605 :     y <- mf[[i]]
606 :     }
607 :     by <- lapply(by, function(u) {
608 :     if(!is.factor(u)) u <- factor(u, exclude = exclude)
609 :     u[ , drop = drop.unused.levels]
610 :     })
611 : maechler 2095 if(!sparse) { ## identical to stats::xtabs
612 :     x <-
613 :     if(is.null(y))
614 :     do.call("table", by)
615 :     else if(NCOL(y) == 1)
616 :     tapply(y, by, sum)
617 :     else {
618 :     z <- lapply(as.data.frame(y), tapply, by, sum)
619 :     array(unlist(z),
620 :     dim = c(dim(z[[1]]), length(z)),
621 :     dimnames = c(dimnames(z[[1]]), list(names(z))))
622 :     }
623 :     x[is.na(x)] <- 0
624 :     class(x) <- c("xtabs", "table")
625 :     attr(x, "call") <- match.call()
626 :     x
627 :    
628 :     } else { ## sparse
629 :     if (length(by) != 2)
630 :     stop("xtabs(*, sparse=TRUE) applies only to two-way tables")
631 :     rows <- by[[1]]
632 :     cols <- by[[2]]
633 :     rl <- levels(rows)
634 :     cl <- levels(cols)
635 :     if (is.null(y))
636 :     y <- rep.int(1, length(rows))
637 :     as(new("dgTMatrix",
638 :     i = as.integer(rows) - 1L,
639 :     j = as.integer(cols) - 1L,
640 : bates 2097 x = as.double(y),
641 : maechler 2095 Dim = c(length(rl), length(cl)),
642 :     Dimnames = list(rl, cl)), "CsparseMatrix")
643 :     }
644 : 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