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

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

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