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

Legend:
Removed from v.1347  
changed lines
  Added in v.2517

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