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

Legend:
Removed from v.1226  
changed lines
  Added in v.2518

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