SCM

SCM Repository

[matrix] Diff of /pkg/tests/indexing.R
ViewVC logotype

Diff of /pkg/tests/indexing.R

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1362, Thu Aug 10 09:44:55 2006 UTC revision 2496, Sat Nov 14 17:24:42 2009 UTC
# Line 1  Line 1 
1  #### For both 'Extract' ("[") and 'Replace' ("[<-") Method testing  ## For both 'Extract' ("[") and 'Replace' ("[<-") Method testing
2    
3  library(Matrix)  library(Matrix)
4    
5  source(system.file("test-tools.R", package = "Matrix"))# identical3() etc  source(system.file("test-tools.R", package = "Matrix"), keep.source = FALSE)
6    ##-> identical3() etc
7    
8    if(interactive()) {
9        options(error = recover, warn = 1)
10    } else if(FALSE) { ## MM @ testing
11        options(error = recover, Matrix.verbose = TRUE, warn = 1)
12    } else options(Matrix.verbose = TRUE, warn = 1)
13    
14    
15  ### Dense Matrices  ### Dense Matrices
16    
17  m <- Matrix(1:28, nrow = 7)  m <- Matrix(1:28 +0, nrow = 7)
18  validObject(m) ; m@x <- as.double(m@x) ; validObject(m)  validObject(m)
19  stopifnot(identical(m, m[]),  stopifnot(identical(m, m[]),
20            identical(m[2, 3],  16), # simple number            identical(m[2, 3],  16), # simple number
21            identical(m[2, 3:4], c(16,23))) # simple numeric of length 2            identical(m[2, 3:4], c(16,23)), # simple numeric of length 2
22              identical(m[NA,NA], as(Matrix(NA, 7,4), "dMatrix")))
23    
24  m[2, 3:4, drop=FALSE] # sub matrix of class 'dgeMatrix'  m[2, 3:4, drop=FALSE] # sub matrix of class 'dgeMatrix'
25  m[-(4:7), 3:4]        # dito; the upper right corner of 'm'  m[-(4:7), 3:4]        # ditto; the upper right corner of 'm'
26    
27  ## rows or columns only:  ## rows or columns only:
28  m[1,]     # first row, as simple numeric vector  m[1,]     # first row, as simple numeric vector
# Line 32  Line 41 
41  mn <- m  mn <- m
42  dimnames(mn) <- list(paste("r",letters[1:nrow(mn)],sep=""),  dimnames(mn) <- list(paste("r",letters[1:nrow(mn)],sep=""),
43                       LETTERS[1:ncol(mn)])                       LETTERS[1:ncol(mn)])
44    checkMatrix(mn)
45  mn["rd", "D"]  mn["rd", "D"]
46    ## Printing sparse colnames:
47    ms <- as(mn,"sparseMatrix")
48    ms[sample(28, 20)] <- 0
49    ms <- t(rbind2(ms, 3*ms))
50    cnam1 <- capture.output(show(ms))[2] ; op <- options("sparse.colnames" = "abb3")
51    cnam2 <- capture.output(show(ms))[2] ; options(op) # revert
52  stopifnot(identical(mn["rc", "D"], mn[3,4]), mn[3,4] == 24,  stopifnot(identical(mn["rc", "D"], mn[3,4]), mn[3,4] == 24,
53            identical(mn[, "A"], mn[,1]), mn[,1] == 1:7,            identical(mn[, "A"], mn[,1]), mn[,1] == 1:7,
54            identical(mn[c("re", "rb"), "B"], mn[c(5,2), 2])            identical(mn[c("re", "rb"), "B"], mn[c(5,2), 2]),
55            )            ## sparse printing
56              grep("^ +$", cnam1) == 1, # cnam1 is empty
57              identical(cnam2,
58                        paste(" ", paste(rep(rownames(mn), 2), collapse=" "))))
59    
60  mo <- m  mo <- m
61  m[2,3] <- 100  m[2,3] <- 100
# Line 44  Line 63 
63  m[, 1] <- -1  m[, 1] <- -1
64  m[1:3,]  m[1:3,]
65    
66    m. <- as.matrix(m)
67    
68    ## m[ cbind(i,j) ] indexing:
69    iN <- ij <- cbind(1:6, 2:3)
70    iN[2:3,] <- iN[5,2] <- NA
71    stopifnot(identical(m[ij], m.[ij]),
72              identical(m[iN], m.[iN]))
73    
74    ## testing operations on logical Matrices rather more than indexing:
75  g10 <- m [ m > 10 ]  g10 <- m [ m > 10 ]
76  stopifnot(18 == length(g10))  stopifnot(18 == length(g10))
 ## needs R >= 2.3.0 [Buglet in R(<= 2.2.1)'s possibleExtends()]:  
77  stopifnot(10 == length(m[ m <= 10 ]))  stopifnot(10 == length(m[ m <= 10 ]))
78    sel <- (20 <  m) & (m <  150)
79    sel.<- (20 <  m.)& (m.<  150)
80    nsel <-(20 >= m) | (m >= 150)
81    (ssel <- as(sel, "sparseMatrix"))
82    stopifnot(is(sel, "lMatrix"), is(ssel, "lsparseMatrix"),
83              identical3(as.mat(sel.), as.mat(sel), as.mat(ssel)),
84              identical3(!sel, !ssel, nsel), # !<sparse> is typically dense
85              identical3(m[ sel],  m[ ssel], as.matrix(m)[as.matrix( ssel)]),
86              identical3(m[!sel],  m[!ssel], as.matrix(m)[as.matrix(!ssel)])
87              )
88    
89    ## more sparse Matrices --------------------------------------
 ### Sparse Matrices --------------------------------------  
90    
91  m <- 1:800  m <- 1:800
92  set.seed(101) ; m[sample(800, 600)] <- 0  set.seed(101) ; m[sample(800, 600)] <- 0
# Line 66  Line 102 
102  mC[1:2,]  mC[1:2,]
103  mC[7,  drop = FALSE]  mC[7,  drop = FALSE]
104  assert.EQ.mat(mC[1:2,], mm[1:2,])  assert.EQ.mat(mC[1:2,], mm[1:2,])
105  stopifnot(all.equal(mC[,3],   mm[,3]))  
106    ## *repeated* (aka 'duplicated') indices - did not work at all ...
107    i <- rep(8:10,2)
108    j <- c(2:4, 4:3)
109    assert.EQ.mat(mC[i,], mm[i,])
110    assert.EQ.mat(mC[,j], mm[,j])
111    ## FIXME? assert.EQ.mat(mC[,NA], mm[,NA]) -- mC[,NA] is all 0 "instead" of all NA
112    ## MM currently thinks we should  NOT  allow  <sparse>[ <NA> ]
113    assert.EQ.mat(mC[i, 2:1], mm[i, 2:1])
114    assert.EQ.mat(mC[c(4,1,2:1), j], mm[c(4,1,2:1), j])
115    assert.EQ.mat(mC[i,j], mm[i,j])
116    set.seed(7)
117    for(n in 1:50) {
118        i <- sample(sample(nrow(mC), 7), 20, replace = TRUE)
119        j <- sample(sample(ncol(mC), 6), 17, replace = TRUE)
120        assert.EQ.mat(mC[i,j], mm[i,j])
121    }
122    
123    ##---- Symmetric indexing of symmetric Matrix ----------
124    m. <- mC; m.[, c(2, 7:12)] <- 0
125    validObject(S <- crossprod(add.simpleDimnames(m.) %% 100))
126    ss <- as(S, "matrix")
127    ds <- as(S, "denseMatrix")
128    ## NA-indexing of *dense* Matrices: should work as traditionally
129    assert.EQ.mat(ds[NA,NA], ss[NA,NA])
130    assert.EQ.mat(ds[NA,  ], ss[NA,])
131    assert.EQ.mat(ds[  ,NA], ss[,NA])
132    stopifnot(identical(ds[2 ,NA], ss[2,NA]),
133              identical(ds[NA, 1], ss[NA, 1]))
134    T <- as(S, "TsparseMatrix")
135    ## non-repeated indices:
136    i <- c(7:5, 2:4);assert.EQ.mat(T[i,i], ss[i,i])
137    ## NA in indices  -- check that we get a helpful error message:
138    i[2] <- NA
139    er <- tryCatch(T[i,i], error = function(e)e)
140    stopifnot(as.logical(grep("indices.*sparse Matrices", er$message)))
141    
142    N <- nrow(T)
143    set.seed(11)
144    for(n in 1:50) {
145        i <- sample(N, max(2, sample(N,1)), replace = FALSE)
146        validObject(Tii <- T[i,i])
147        stopifnot(is(Tii, "dsTMatrix"), # remained symmetric Tsparse
148                  identical(t(Tii), t(T)[i,i]))
149        assert.EQ.mat(Tii, ss[i,i])
150    }
151    
152    ## repeated ones ``the challenge'' (to do smartly):
153    j <- c(4, 4, 9, 12, 9, 4, 17, 3, 18, 4, 12, 18, 4, 9)
154    assert.EQ.mat(T[j,j], ss[j,j])
155    ## and another two sets  (a, A) &  (a., A.) :
156    a <- matrix(0, 6,6)
157    a[upper.tri(a)] <- (utr <- c(2, 0,-1, 0,0,5, 7,0,0,0, 0,0,-2,0,8))
158    ta <- t(a); ta[upper.tri(a)] <- utr; a <- t(ta)
159    diag(a) <- c(0,3,0,4,6,0)
160    A <- as(Matrix(a), "TsparseMatrix")
161    A. <- A
162    diag(A.) <- 10 * (1:6)
163    a. <- as(A., "matrix")
164    ## More testing {this was not working for a long time..}
165    set.seed(1)
166    for(n in 1:100) {
167        i <- sample(1:nrow(A), 3+2*rpois(1, lam=3), replace=TRUE)
168        Aii  <- A[i,i]
169        A.ii <- A.[i,i]
170        stopifnot(class(Aii) == class(A),
171                  class(A.ii) == class(A.))
172        assert.EQ.mat(Aii , a [i,i])
173        assert.EQ.mat(A.ii, a.[i,i])
174        assert.EQ.mat(T[i,i], ss[i,i])
175    }
176    
177    
178    stopifnot(all.equal(mC[,3], mm[,3]),
179              identical(mC[ij], mm[ij]),
180              identical(mC[iN], mm[iN]))
181    
182  assert.EQ.mat(mC[7, , drop=FALSE], mm[7, , drop=FALSE])  assert.EQ.mat(mC[7, , drop=FALSE], mm[7, , drop=FALSE])
183    identical    (mC[7,   drop=FALSE], mm[7,   drop=FALSE]) # *vector* indexing
184    
185  stopifnot(dim(mC[numeric(0), ]) == c(0,20), # used to give warnings  stopifnot(dim(mC[numeric(0), ]) == c(0,20), # used to give warnings
186            dim(mC[, integer(0)]) == c(40,0),            dim(mC[, integer(0)]) == c(40,0),
187            identical(mC[, integer(0)], mC[, FALSE]),            identical(mC[, integer(0)], mC[, FALSE]))
           identical(mC[7,  drop = FALSE],  
                     mC[7,, drop = FALSE]))  
188  validObject(print(mT[,c(2,4)]))  validObject(print(mT[,c(2,4)]))
189  stopifnot(all.equal(mT[2,], mm[2,]),  stopifnot(all.equal(mT[2,], mm[2,]),
190            ## row or column indexing in combination with t() :            ## row or column indexing in combination with t() :
# Line 86  Line 197 
197            identical3(mm[3,], mC[3,], mT[3,]),            identical3(mm[3,], mC[3,], mT[3,]),
198            identical3(mT[2,3], mC[2,3], 0),            identical3(mT[2,3], mC[2,3], 0),
199            identical(mT[], mT),            identical(mT[], mT),
200            ## TODO: identical4() with  m[c(3,7), 2:4] - fail because of 'dimnames'            identical4(       mm[c(3,7), 2:4],  as.mat( m[c(3,7), 2:4]),
201            identical3(as(mC[c(3,7), 2:4],"matrix"), mm[c(3,7), 2:4],                       as.mat(mT[c(3,7), 2:4]), as.mat(mC[c(3,7), 2:4]))
202                       as(mT[c(3,7), 2:4],"matrix")))            )
203    
204  x.x <- crossprod(mC)  x.x <- crossprod(mC)
205  stopifnot(class(x.x) == "dsCMatrix",  stopifnot(class(x.x) == "dsCMatrix",
206            class(x.x. <- round(x.x / 10000)) == "dsCMatrix")            class(x.x. <- round(x.x / 10000)) == "dsCMatrix",
207              identical(x.x[cbind(2:6, 2:6)],
208                        diag(x.x [2:6, 2:6])))
209  head(x.x.) # Note the *non*-structural 0's printed as "0"  head(x.x.) # Note the *non*-structural 0's printed as "0"
210  ## FIXME (once we require 2.4.x or higher):  tail(x.x., -3) # all but the first three lines
 ##  tail(x.x., -2) # the last two lines  
211    
212  lx.x <- as(x.x, "lsCMatrix") # FALSE only for "structural" 0  lx.x <- as(x.x, "lsCMatrix") # FALSE only for "structural" 0
213  if(FALSE) { ## FIXME: needs coercion  "lsCMatrix" to "lgTMatrix"  (l10 <- lx.x[1:10, 1:10])# "lsC"
214      lx.x[1:10, 1:10]  (l3 <-  lx.x[1:3, ])
215      lx.x[1:3, ]  m.x <- as.mat(x.x) # as.mat() *drops* (NULL,NULL) dimnames
216  }  stopifnot(class(l10) == "lsCMatrix", # symmetric indexing -> symmetric !
217              identical(as.mat(lx.x), m.x != 0),
218              identical(as.logical(lx.x), as.logical(m.x)),
219              identical(as.mat(l10), m.x[1:10, 1:10] != 0),
220              identical(as.mat(l3 ), m.x[1:3, ] != 0)
221              )
222    
223    ##-- Sub*assignment* with repeated / duplicated index:
224    A <- Matrix(0,4,3) ; A[c(1,2,1), 2] <- 1 ; A
225    B <- A;              B[c(1,2,1), 2] <- 1:3; B; B. <- B
226    B.[3,] <- rbind(4:2)
227    diag(B.) <- 10 * diag(B.)
228    C <- B.; C[,2] <- C[,2];  C[1,] <- C[1,]; C[2:3,2:1] <- C[2:3,2:1]
229    stopifnot(identical(unname(as.matrix(A)),
230                        local({a <- matrix(0,4,3); a[c(1,2,1), 2] <-  1 ; a})),
231              identical(unname(as.matrix(B)),
232                        local({a <- matrix(0,4,3); a[c(1,2,1), 2] <- 1:3; a})),
233              identical(C, drop0(B.)))
234    
235    
236    ## used to fail
237    n <- 5 ## or much larger
238    sm <- new("dsTMatrix", i=as.integer(1),j=as.integer(1),
239              Dim=as.integer(c(n,n)), x = 1)
240    (cm <- as(sm, "CsparseMatrix"))
241    sm[2,]
242    stopifnot(sm[2,] == c(0:1, rep.int(0,ncol(sm)-2)),
243              sm[2,] == cm[2,],
244              sm[,3] == sm[3,],
245              all(sm[,-(1:3)] == t(sm[-(1:3),])), # all(<lge.>)
246              all(sm[,-(1:3)] == 0)
247              )
248    
249    m0 <- Diagonal(5)
250    stopifnot(identical(m0[2,], m0[,2]),
251              identical(m0[,1], c(1,0,0,0,0)))
252    ### Diagonal -- Sparse:
253    (m1 <- as(m0, "TsparseMatrix"))  # dtTMatrix
254    (m2 <- as(m0, "CsparseMatrix")) # dtCMatrix
255    m1g <- as(m1, "generalMatrix")
256    stopifnot(is(m1g, "dgTMatrix"))
257    assert.EQ.mat(m2[1:3,],    diag(5)[1:3,])
258    assert.EQ.mat(m2[,c(4,1)], diag(5)[,c(4,1)])
259    stopifnot(identical(m2[1:3,], as(m1[1:3,], "CsparseMatrix")),
260              identical(Matrix:::uniqTsparse(m1[, c(4,2)]),
261                        Matrix:::uniqTsparse(as(m2[, c(4,2)], "TsparseMatrix")))
262              )## failed in 0.9975-11
263    
264    (uTr <- new("dtTMatrix", Dim = c(3L,3L), diag="U"))
265    uTr[1,] <- 0
266    assert.EQ.mat(uTr, cbind(0, rbind(0,diag(2))))
267    
268    M <- m0; M[1,] <- 0
269    stopifnot(identical(M, Diagonal(x=c(0, rep(1,4)))))
270    M <- m0; M[,3] <- 3 ; M ; stopifnot(is(M, "sparseMatrix"), M[,3] == 3)
271    checkMatrix(M)
272    M <- m0; M[1:3, 3] <- 0 ;M
273    T <- m0; T[1:3, 3] <- 10
274    stopifnot(identical(M, Diagonal(x=c(1,1, 0, 1,1))),
275              is(T, "triangularMatrix"), identical(T[,3], c(10,10,10,0,0)))
276    
277    M <- m1; M[1,] <- 0 ; M ; assert.EQ.mat(M, diag(c(0,rep(1,4))), tol=0)
278    M <- m1; M[,3] <- 3 ; stopifnot(is(M,"sparseMatrix"), M[,3] == 3)
279    checkMatrix(M)
280    M <- m1; M[1:3, 3] <- 0 ;M
281    assert.EQ.mat(M, diag(c(1,1, 0, 1,1)), tol=0)
282    T <- m1; T[1:3, 3] <- 10; checkMatrix(T)
283    stopifnot(is(T, "dtTMatrix"), identical(T[,3], c(10,10,10,0,0)))
284    
285    M <- m2; M[1,] <- 0 ; M ; assert.EQ.mat(M, diag(c(0,rep(1,4))), tol=0)
286    M <- m2; M[,3] <- 3 ; stopifnot(is(M,"sparseMatrix"), M[,3] == 3)
287    checkMatrix(M)
288    M <- m2; M[1:3, 3] <- 0 ;M
289    assert.EQ.mat(M, diag(c(1,1, 0, 1,1)), tol=0)
290    T <- m2; T[1:3, 3] <- 10; checkMatrix(T)
291    stopifnot(is(T, "dtCMatrix"), identical(T[,3], c(10,10,10,0,0)))
292    
293    
294    ## "Vector indices" -------------------
295    .iniDiag.example <- expression({
296        D <- Diagonal(6)
297        M <- as(D,"dgeMatrix")
298        m <- as(D,"matrix")
299        s <- as(D,"TsparseMatrix")
300        S <- as(s,"CsparseMatrix")
301    })
302    eval(.iniDiag.example)
303    i <- c(3,1,6); v <- c(10,15,20)
304    ## (logical,value) which both are recycled:
305    L <- c(TRUE, rep(FALSE,8)) ; z <- c(50,99)
306    
307    ## vector subassignment, both with integer & logical
308    ## these now work correctly {though not very efficiently; hence warnings}
309    m[i] <- v # the role model: only first column is affected
310    M[i] <- v; assert.EQ.mat(M,m) # dge
311    D[i] <- v; assert.EQ.mat(D,m) # ddi -> dtT -> dgT
312    s[i] <- v; assert.EQ.mat(s,m) # dtT -> dgT
313    S[i] <- v; assert.EQ.mat(S,m); S # dtC -> dtT -> dgT -> dgC
314    stopifnot(identical(s,D))
315    ## logical
316    eval(.iniDiag.example)
317    m[L] <- z
318    M[L] <- z; assert.EQ.mat(M,m)
319    D[L] <- z; assert.EQ.mat(D,m)
320    s[L] <- z; assert.EQ.mat(s,m)
321    S[L] <- z; assert.EQ.mat(S,m) ; S
322    
323    ## indexing [i]  vs  [i,] --- now ok
324    eval(.iniDiag.example)
325    stopifnot(identical5(m[i], M[i], D[i], s[i], S[i]))
326    stopifnot(identical5(m[L], M[L], D[L], s[L], S[L]))
327    ## bordercase ' drop = .' *vector* indexing {failed till 2009-04-..)
328    stopifnot(identical5(m[i,drop=FALSE], M[i,drop=FALSE], D[i,drop=FALSE],
329                         s[i,drop=FALSE], S[i,drop=FALSE]))
330    stopifnot(identical5(m[L,drop=FALSE], M[L,drop=FALSE], D[L,drop=FALSE],
331                         s[L,drop=FALSE], S[L,drop=FALSE]))
332    ## using L for row-indexing should give an error
333    assertError(m[L,]); assertError(m[L,, drop=FALSE])
334    ## these did not signal an error, upto (including) 0.999375-30:
335    assertError(s[L,]); assertError(s[L,, drop=FALSE])
336    assertError(S[L,]); assertError(S[L,, drop=FALSE])
337    
338    ## row indexing:
339    assert.EQ.mat(D[i,], m[i,])
340    assert.EQ.mat(M[i,], m[i,])
341    assert.EQ.mat(s[i,], m[i,])
342    assert.EQ.mat(S[i,], m[i,])
343    ## column indexing:
344    assert.EQ.mat(D[,i], m[,i])
345    assert.EQ.mat(M[,i], m[,i])
346    assert.EQ.mat(s[,i], m[,i])
347    assert.EQ.mat(S[,i], m[,i])
348    
349    
350  ## --- negative indices ----------  ## --- negative indices ----------
351  mc <- mC[1:5, 1:7]  mc <- mC[1:5, 1:7]
# Line 149  Line 393 
393    
394  mt[c(2,4), ] <- 0; stopifnot(as(mt[c(2,4), ],"matrix") == 0)  mt[c(2,4), ] <- 0; stopifnot(as(mt[c(2,4), ],"matrix") == 0)
395  mt[2:3, 4:7] <- 33  mt[2:3, 4:7] <- 33
396  validObject(mt)  checkMatrix(mt)
397  mt  mt
398    
399  mc[1,4] <- -99 ; stopifnot(mc[1,4] == -99)  mc[1,4] <- -99 ; stopifnot(mc[1,4] == -99)
# Line 157  Line 401 
401  mc[1,4] <- -99 ; stopifnot(mc[1,4] == -99)  mc[1,4] <- -99 ; stopifnot(mc[1,4] == -99)
402  mc[1:2,4:3] <- 4:1; stopifnot(as.matrix(mc[1:2,4:3]) == 4:1)  mc[1:2,4:3] <- 4:1; stopifnot(as.matrix(mc[1:2,4:3]) == 4:1)
403    
 ## Debugging:  R bug --   debug(Matrix:::replCmat)  has no effect  
   
404  mc[-1, 3] <- -2:1 # 0 should not be entered; 'value' recycled  mc[-1, 3] <- -2:1 # 0 should not be entered; 'value' recycled
405  mt[-1, 3] <- -2:1  mt[-1, 3] <- -2:1
406  stopifnot(mc@x != 0, mt@x != 0,  stopifnot(mc@x != 0, mt@x != 0,
407            mc[-1,3] == -2:1, mt[-1,3] == -2:1) ##--> BUG -- fixed            mc[-1,3] == -2:1, mt[-1,3] == -2:1) ## failed earlier
408  ## source("~/R/Pkgs/Matrix/R/Tsparse.R")  
409  ## Matrix_expand_pointers <- Matrix:::Matrix_expand_pointers  mc0 <- mc
410  ## -> open ../R/dgCMatrix.R  --> replCmat  .. now eval-line by line ..  mt0 <- as(mc0, "TsparseMatrix")
411    m0  <- as(mc0, "matrix")
412  ev <- 1:5 %% 2 == 0  set.seed(1)
413  mc[ev, 3] <- 0:1  for(i in 1:50) {
414  ##FIXME stopifnot(mc[ev, 3] == 0:1) ##-> BUG  {very peculiar; the 2nd time it works ...}      mc <- mc0; mt <- mt0 ; m <- m0
415  validObject(mc)      ev <- 1:5 %% 2 == round(runif(1))# 0 or 1
416  mc # now shows a non-structural zeros      j <- sample(ncol(mc), 1 + round(runif(1)))
417        nv <- rpois(sum(ev) * length(j), lambda = 1)
418        mc[ev, j] <- nv
419         m[ev, j] <- nv
420        mt[ev, j] <- nv
421        if(i %% 10 == 1) print(mc[ev,j, drop = FALSE])
422        stopifnot(as.vector(mc[ev, j]) == nv, ## failed earlier...
423                  as.vector(mt[ev, j]) == nv)
424        validObject(mc) ; assert.EQ.mat(mc, m)
425        validObject(mt) ; assert.EQ.mat(mt, m)
426    }
427    
428    mc # no longer has non-structural zeros
429  mc[ii, jj] <- 1:6  mc[ii, jj] <- 1:6
430  mc[c(2,5), c(3,5)] <- 3.2  mc[c(2,5), c(3,5)] <- 3.2
431  validObject(mc)  checkMatrix(mc)
432  (m. <- mc)  m. <- mc
433  ## FIXME: mc[4,] <- 0 # -> error -- another Bug  mc[4,] <- 0
434    mc
435    
436    S <- as(Diagonal(5),"TsparseMatrix")
437  H <- Hilbert(9)  H <- Hilbert(9)
438  Hc <- as(round(H, 3), "dsCMatrix")  Hc <- as(round(H, 3), "dsCMatrix")# a sparse matrix with no 0 ...
439  tril(Hc[1:5, 1:5])  (trH <- tril(Hc[1:5, 1:5]))
440    stopifnot(is(trH, "triangularMatrix"), trH@uplo == "L",
441              is(S, "triangularMatrix"))
442    
443    ## triangular assignment
444    ## the slick (but inefficient in case of sparse!) way to assign sub-diagonals:
445    ## equivalent to tmp <- `diag<-`(S[,-1], -2:1); S[,-1] <- tmp
446    ## which dispatches to (x="TsparseMatrix", i="missing",j="index", value="replValue")
447    diag(S[,-1]) <- -2:1 # used to give a wrong warning
448    S <- as(S,"triangularMatrix")
449    assert.EQ.mat(S, local({s <- diag(5); diag(s[,-1]) <- -2:1; s}))
450    
451    trH[c(1:2,4), c(2:3,5)] <- 0 # gave an *error* upto Jan.2008
452    trH[ lower.tri(trH) ] <- 0   # ditto, because of callNextMethod()
453    
454    m <- Matrix(0+1:28, nrow = 4)
455    m[-3,c(2,4:5,7)] <- m[ 3, 1:4] <- m[1:3, 6] <- 0
456    mT <- as(m, "dgTMatrix")
457    stopifnot(identical(mT[lower.tri(mT)],
458                        m [lower.tri(m) ]))
459    lM <- upper.tri(mT, diag=TRUE)
460    mT[lM] <- 0
461     m[lM] <- 0
462    assert.EQ.mat(mT, as(m,"matrix"))
463    mT[lM] <- -1:0
464     m[lM] <- -1:0
465    assert.EQ.mat(mT, as(m,"matrix"))
466    (mT <- drop0(mT))
467    
468  H[c(1:2, 4, 6:7), c(2:4,6)] <- 0  i <- c(1:2, 4, 6:7); j <- c(2:4,6)
469    H[i,j] <- 0
470  (H. <- round(as(H, "sparseMatrix"), 3)[ , 2:7])  (H. <- round(as(H, "sparseMatrix"), 3)[ , 2:7])
471  Hc. <- Hc  Hc. <- Hc
472  Hc.[c(1:2, 4, 6:7), c(2:4,6)] <- 0  Hc.[i,j] <- 0 ## now "works", but setting "non-structural" 0s
473    stopifnot(as.matrix(Hc.[i,j]) == 0)
474  Hc.[, 1:6]  Hc.[, 1:6]
475    
476  cat('Time elapsed: ', proc.time(),'\n') # for ``statistical reasons''  ## an example that failed for a long time
477    sy3 <- new("dsyMatrix", Dim = as.integer(c(2, 2)), x = c(14, -1, 2, -7))
478    checkMatrix(dm <- kronecker(Diagonal(2), sy3))# now sparse with new kronecker
479    dm <- Matrix(as.matrix(dm))# -> "dsyMatrix"
480    (s2 <- as(dm, "sparseMatrix"))
481    checkMatrix(st <- as(s2, "TsparseMatrix"))
482    stopifnot(is(s2, "symmetricMatrix"),
483              is(st, "symmetricMatrix"))
484    checkMatrix(s.32  <- st[1:3,1:2]) ## 3 x 2 - and *not* dsTMatrix
485    checkMatrix(s2.32 <- s2[1:3,1:2])
486    I <- c(1,4:3)
487    stopifnot(is(s2.32, "generalMatrix"),
488              is(s.32,  "generalMatrix"),
489              identical(as.mat(s.32), as.mat(s2.32)),
490              identical3(dm[1:3,-1], asD(s2[1:3,-1]), asD(st[1:3,-1])),
491              identical4(2, dm[4,3], s2[4,3], st[4,3]),
492              identical3(diag(dm), diag(s2), diag(st)),
493              is((cI <- s2[I,I]), "dsCMatrix"),
494              is((tI <- st[I,I]), "dsTMatrix"),
495              identical4(as.mat(dm)[I,I], as.mat(dm[I,I]), as.mat(tI), as.mat(cI))
496              )
497    
498    ## now sub-assign  and check for consistency
499    ## symmetric subassign should keep symmetry
500    st[I,I] <- 0; checkMatrix(st); stopifnot(is(st,"symmetricMatrix"))
501    s2[I,I] <- 0; checkMatrix(s2); stopifnot(is(s2,"symmetricMatrix"))
502    ##
503    m <- as.mat(st)
504     m[2:1,2:1] <- 4:1
505    st[2:1,2:1] <- 4:1
506    s2[2:1,2:1] <- 4:1
507    stopifnot(identical(m, as.mat(st)),
508              1:4 == as.vector(s2[1:2,1:2]),
509              identical(m, as.mat(s2)))
510    
511    ## now a slightly different situation for 's2' (had bug)
512    s2 <- as(dm, "sparseMatrix")
513    s2[I,I] <- 0; diag(s2)[2:3] <- -(1:2)
514    stopifnot(is(s2,"symmetricMatrix"), diag(s2) == c(0:-2,0))
515    t2 <- as(s2, "TsparseMatrix")
516    m <- as.mat(s2)
517    s2[2:1,2:1] <- 4:1
518    t2[2:1,2:1] <- 4:1
519     m[2:1,2:1] <- 4:1
520    assert.EQ.mat(t2, m)
521    assert.EQ.mat(s2, m)
522    ## and the same (for a different s2 !)
523    s2[2:1,2:1] <- 4:1
524    t2[2:1,2:1] <- 4:1
525    assert.EQ.mat(t2, m)# ok
526    assert.EQ.mat(s2, m)# failed in 0.9975-8
527    
528    
529    ## m[cbind(i,j)] <- value:
530    m.[ cbind(3:5, 1:3) ] <- 1:3
531    stopifnot(m.[3,1] == 1, m.[4,2] == 2)
532    x.x[ cbind(2:6, 2:6)] <- 12:16
533    stopifnot(isValid(x.x, "dsCMatrix"),
534              12:16 == as.mat(x.x)[cbind(2:6, 2:6)])
535    (ne1 <- (mc - m.) != 0)
536    stopifnot(identical(ne1, 0 != abs(mc - m.)))
537    (ge <- m. >= mc) # contains "=" -> result is dense
538    ne. <- mc != m.  # was wrong (+ warning)
539    stopifnot(identical(!(m. < mc), m. >= mc),
540              identical(m. < mc, as(!ge, "sparseMatrix")),
541              identical(ne., drop0(ne1)))
542    
543    d6 <- Diagonal(6)
544    ii <- c(1:2, 4:5)
545    d6[cbind(ii,ii)] <- 7*ii
546    stopifnot(is(d6, "ddiMatrix"), identical(d6, Diagonal(x=c(7*1:2,1,7*4:5,1))))
547    
548    for(j in 3:6) { ## even and odd j used to behave differently
549        M <- Matrix(0, j,j); m <- matrix(0, j,j)
550        T  <- as(M, "TsparseMatrix")
551        TG <- as(T, "generalMatrix")
552        G <-  as(M, "generalMatrix")
553        id <- cbind(1:j,1:j)
554        i2 <- cbind(1:j,j:1)
555        m[id] <- 1:j
556        M[id] <- 1:j ; stopifnot(is(M,"symmetricMatrix"))
557        T[id] <- 1:j ; stopifnot(is(T,"symmetricMatrix"))
558        G[id] <- 1:j
559        TG[id]<- 1:j
560        m[i2] <- 10
561        M[i2] <- 10 ; stopifnot(is(M,"symmetricMatrix"))
562        T[i2] <- 10 ; stopifnot(is(T,"symmetricMatrix"))
563        G[i2] <- 10
564        TG[i2]<- 10
565        ##
566        assert.EQ.mat(M, m)
567        assert.EQ.mat(T, m)
568        assert.EQ.mat(G, m)
569        assert.EQ.mat(TG,m)
570    }
571    
572    
573    ## drop, triangular, ...
574    (M3 <- Matrix(upper.tri(matrix(, 3, 3)))) # ltC; indexing used to fail
575    T3 <- as(M3, "TsparseMatrix")
576    stopifnot(identical(drop(M3), M3),
577              identical4(drop(M3[,2, drop = FALSE]), M3[,2, drop = TRUE],
578                         drop(T3[,2, drop = FALSE]), T3[,2, drop = TRUE]),
579              is(T3, "triangularMatrix"),
580              !is(T3[,2, drop=FALSE], "triangularMatrix")
581              )
582    
583    (T6 <- as(as(kronecker(Matrix(c(0,0,1,0),2,2), t(T3)), "lMatrix"),
584              "triangularMatrix"))
585    T6[1:4, -(1:3)] # failed (trying to coerce back to ltTMatrix)
586    stopifnot(identical(T6[1:4, -(1:3)][2:3, -3],
587                        spMatrix(2,2, i=c(1,2,2), j=c(1,1,2), x=rep(TRUE,3))))
588    
589    M <- Diagonal(4); M[1,2] <- 2
590    M. <- as(M, "CsparseMatrix")
591    (R <- as(M., "RsparseMatrix"))
592    (Ms <- symmpart(M.))
593    Rs <- as(Ms, "RsparseMatrix")
594    stopifnot(isValid(M, "triangularMatrix"),
595              isValid(M.,"triangularMatrix"),
596              isValid(Ms, "dsCMatrix"),
597              isValid(R,  "dtRMatrix"),
598              isValid(Rs, "dsRMatrix") )
599    stopifnot(dim(M[2:3, FALSE]) == c(2,0),
600              dim(R[2:3, FALSE]) == c(2,0),
601              identical(M [2:3,TRUE], M [2:3,]),
602              identical(M.[2:3,TRUE], M.[2:3,]),
603              identical(R [2:3,TRUE], R [2:3,]),
604              dim(R[FALSE, FALSE]) == c(0,0))
605    
606    n <- 50000L
607    Lrg <- new("dgTMatrix", Dim = c(n,n))
608    diag(Lrg) <- 1:n
609    dLrg <- as(Lrg, "diagonalMatrix")
610    stopifnot(identical(Diagonal(x = 1:n), dLrg))
611    diag(dLrg) <- 1 + diag(dLrg)
612    Clrg <- as(Lrg,"CsparseMatrix")
613    Ctrg <- as(Clrg, "triangularMatrix")
614    diag(Ctrg) <- 1 + diag(Ctrg)
615    stopifnot(identical(Diagonal(x = 1+ 1:n), dLrg),
616              identical(Ctrg, as(dLrg,"CsparseMatrix")))
617    
618    cc <- capture.output(show(dLrg))# show(<diag>) used to error for large n
619    
620    ## Large Matrix indexing / subassignment
621    ## ------------------------------------- (from ex. by Imran Rashid)
622    n <- 7000000
623    m <-  100000
624    nnz <- 20000
625    
626    set.seed(12)
627    f <- sparseMatrix(i = sample(n, size=nnz, replace=TRUE),
628                      j = sample(m, size=nnz, replace=TRUE))
629    str(f)
630    dim(f) # 6999863 x 99992
631    prod(dim(f)) # 699930301096 == 699'930'301'096  (~ 700'000 millions)
632    str(thisCol <-  f[,5000])# logi [~ 7 mio....]
633    sv <- as(thisCol, "sparseVector")
634    str(sv) ## "empty" !
635    validObject(spCol <- f[,5000, drop=FALSE])
636    ## ^^ FIXME slow Tsparse_to_Csparse from memory-hog
637    ## cholmod_sparse *CHOLMOD(triplet_to_sparse)
638    ## which has  "workspace: Iwork (max (nrow,ncol))"
639    ## in ../src/CHOLMOD/Core/cholmod_triplet.c  *and*
640    ## in ../src/CHOLMOD/Core/t_cholmod_triplet.c
641    ##
642    ## *not* identical(): as(spCol, "sparseVector")@length is "double"prec:
643    stopifnot(all.equal(as(spCol, "sparseVector"),
644                        as(sv,   "nsparseVector"), tol=0))
645    f[,5762] <- thisCol # now "fine" <<<<<<<<<< FIXME uses LARGE objects
646    ## is using  replCmat() in ../R/Csparse.R, then
647    ##           replTmat() in ../R/Tsparse.R
648    
649    fx <- sparseMatrix(i = sample(n, size=nnz, replace=TRUE),
650                       j = sample(m, size=nnz, replace=TRUE),
651                       x = round(10*rnorm(nnz)))
652    class(fx)## dgCMatrix
653    fx[,6000] <- (tC <- rep(thisCol, length=nrow(fx)))
654    thCol <- fx[,2000]
655    fx[,5762] <- thCol
656    stopifnot(is(f, "ngCMatrix"), is(fx, "dgCMatrix"),
657              identical(thisCol, f[,5762]),# perfect
658              identical(as.logical(fx[,6000]), tC),
659              identical(thCol,  fx[,5762]))
660    
661    cat('Time elapsed: ', (.pt <- proc.time()),'\n') # "stats"
662    ##
663    cat("checkMatrix() of all: \n---------\n")
664    Sys.setlocale("LC_COLLATE", "C")# to keep ls() reproducible
665    for(nm in ls()) if(is(.m <- get(nm), "Matrix")) {
666        cat(nm, "\n")
667        checkMatrix(.m, verbose = FALSE)
668    }
669    cat('Time elapsed: ', proc.time() - .pt,'\n') # "stats"
670    
671    if(!interactive()) warnings()
672    

Legend:
Removed from v.1362  
changed lines
  Added in v.2496

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