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