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 873, Sat Aug 27 21:26:23 2005 UTC revision 1835, Fri May 11 10:41:21 2007 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  identical3 <- function(x,y,z)   identical(x,y) && identical (y,z)  source(system.file("test-tools.R", package = "Matrix"))# identical3() etc
 identical4 <- function(a,b,c,d) identical(a,b) && identical3(b,c,d)  
6    
7  ### Dense Matrices  ### Dense Matrices
8    
9  m <- Matrix(1:28, nrow = 7)  m <- Matrix(1:28 +0, nrow = 7)
10  validObject(m) ; m@x <- as.double(m@x) ; validObject(m)  validObject(m)
11  stopifnot(identical(m, m[]),  stopifnot(identical(m, m[]),
12            identical(m[2, 3],  16), # simple number            identical(m[2, 3],  16), # simple number
13            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
# Line 21  Line 20 
20  m[,2]     # 2nd column  m[,2]     # 2nd column
21  m[,1:2]   # sub matrix of first two columns  m[,1:2]   # sub matrix of first two columns
22  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
23    m[integer(0),] #-> 0 x 4 Matrix
24    m[2:4, numeric(0)] #-> 3 x 0 Matrix
25    
26  ## logical indexing  ## logical indexing
27  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]),
28            identical(m[2,], m[(1:nrow(m)) == 2, ]),            identical(m[2,], m[(1:nrow(m)) == 2, ]),
29            identical(m[,3:4], m[, (1:4) >= 3]))            identical(m[,3:4], m[, (1:4) >= 3]))
30    
31  ## dimnames index (TODO)  ## dimnames indexing:
32    mn <- m
33    dimnames(mn) <- list(paste("r",letters[1:nrow(mn)],sep=""),
34                         LETTERS[1:ncol(mn)])
35    mn["rd", "D"]
36    stopifnot(identical(mn["rc", "D"], mn[3,4]), mn[3,4] == 24,
37              identical(mn[, "A"], mn[,1]), mn[,1] == 1:7,
38              identical(mn[c("re", "rb"), "B"], mn[c(5,2), 2])
39              )
40    
41    mo <- m
42    m[2,3] <- 100
43    m[1:2, 4] <- 200
44    m[, 1] <- -1
45    m[1:3,]
46    
47    m. <- as.matrix(m)
48    
49    ## m[ cbind(i,j) ] indexing:
50    ij <- cbind(1:6, 2:3)
51    stopifnot(identical(m[ij], m.[ij]))
52    
53    ## testing operations on logical Matrices rather more than indexing:
54    g10 <- m [ m > 10 ]
55    stopifnot(18 == length(g10))
56    stopifnot(10 == length(m[ m <= 10 ]))
57    sel <- (20 <  m) & (m <  150)
58    sel.<- (20 <  m.)& (m.<  150)
59    nsel <-(20 >= m) | (m >= 150)
60    (ssel <- as(sel, "sparseMatrix"))
61    stopifnot(is(sel, "lMatrix"), is(ssel, "lsparseMatrix"),
62              identical3(as.mat(sel.), as.mat(sel), as.mat(ssel)),
63              identical3(!sel, !ssel, nsel), # !<sparse> is typically dense
64              identical3(m[ sel],  m[ ssel], as.matrix(m)[as.matrix( ssel)]),
65              identical3(m[!sel],  m[!ssel], as.matrix(m)[as.matrix(!ssel)])
66              )
67    
68  ## TODO: more --- particularly once we have "m > 10" working!  ## more sparse Matrices --------------------------------------
   
   
 ### Sparse Matrices  
69    
70  m <- 1:800  m <- 1:800
71  set.seed(101) ; m[sample(800, 600)] <- 0  set.seed(101) ; m[sample(800, 600)] <- 0
# Line 47  Line 80 
80  mC[,1]  mC[,1]
81  mC[1:2,]  mC[1:2,]
82  mC[7, drop = FALSE]  mC[7, drop = FALSE]
83    assert.EQ.mat(mC[1:2,], mm[1:2,])
84    
85  mT[,c(2,4)]  ## *repeated* (aka 'duplicated') indices - did not work at all ...
86  mT[1,]  i <- rep(8:10,2)
87  mT[4, drop = FALSE]  j <- c(2:4, 4:3)
88    assert.EQ.mat(mC[i,], mm[i,])
89    assert.EQ.mat(mC[,j], mm[,j])
90    assert.EQ.mat(mC[i, 2:1], mm[i, 2:1])
91    assert.EQ.mat(mC[c(4,1,2:1), j], mm[c(4,1,2:1), j])
92    assert.EQ.mat(mC[i,j], mm[i,j])
93    set.seed(7)
94    for(n in 1:50) {
95        i <- sample(sample(nrow(mC), 7), 20, replace = TRUE)
96        j <- sample(sample(ncol(mC), 6), 17, replace = TRUE)
97        assert.EQ.mat(mC[i,j], mm[i,j])
98    }
99    
100    ##---- Symmetric indexing of symmetric Matrix ----------
101    m. <- mC; m.[, c(2, 7:12)] <- 0
102    validObject(S <- crossprod(add.simpleDimnames(m.) %% 100))
103    ss <- as(S, "matrix")
104    T <- as(S, "TsparseMatrix")
105    ## non-repeated indices:
106    i <- c(7:5, 2:4);assert.EQ.mat(T[i,i], ss[i,i])
107    N <- nrow(T)
108    set.seed(11)
109    for(n in 1:50) {
110        i <- sample(N, max(2, sample(N,1)), replace = FALSE)
111        validObject(Tii <- T[i,i])
112        stopifnot(is(Tii, "dsTMatrix"), # remained symmetric Tsparse
113                  identical(t(Tii), t(T)[i,i]))
114        assert.EQ.mat(Tii, ss[i,i])
115    }
116    
117    ## repeated ones ``the challenge'' (to do smartly):
118    j <- c(4, 4, 9, 12, 9, 4, 17, 3, 18, 4, 12, 18, 4, 9)
119    assert.EQ.mat(T[j,j], ss[j,j])
120    ## and another two sets  (a, A) &  (a., A.) :
121    a <- matrix(0, 6,6)
122    a[upper.tri(a)] <- (utr <- c(2, 0,-1, 0,0,5, 7,0,0,0, 0,0,-2,0,8))
123    ta <- t(a); ta[upper.tri(a)] <- utr; a <- t(ta)
124    diag(a) <- c(0,3,0,4,6,0)
125    A <- as(Matrix(a), "TsparseMatrix")
126    A. <- A
127    diag(A.) <- 10 * (1:6)
128    a. <- as(A., "matrix")
129    ## More testing {this was not working for a long time..}
130    set.seed(1)
131    for(n in 1:100) {
132        i <- sample(1:nrow(A), 3+2*rpois(1, lam=3), replace=TRUE)
133        Aii  <- A[i,i]
134        A.ii <- A.[i,i]
135        stopifnot(class(Aii) == class(A),
136                  class(A.ii) == class(A.))
137        assert.EQ.mat(Aii , a [i,i])
138        assert.EQ.mat(A.ii, a.[i,i])
139        assert.EQ.mat(T[i,i], ss[i,i])
140    }
141    
142    
143    stopifnot(all.equal(mC[,3], mm[,3]),
144              identical(mC[ij], mm[ij]))
145    assert.EQ.mat(mC[7, , drop=FALSE], mm[7, , drop=FALSE])
146    
147    stopifnot(dim(mC[numeric(0), ]) == c(0,20), # used to give warnings
148              dim(mC[, integer(0)]) == c(40,0),
149              identical(mC[, integer(0)], mC[, FALSE]),
150              identical(mC[7,  drop = FALSE],
151                        mC[7,, drop = FALSE]))
152    validObject(print(mT[,c(2,4)]))
153    stopifnot(all.equal(mT[2,], mm[2,]),
154              ## row or column indexing in combination with t() :
155              identical(mT[2,], t(mT)[,2]),
156              identical(mT[-2,], t(t(mT)[,-2])),
157              identical(mT[c(2,5),], t(t(mT)[,c(2,5)]))
158              )
159    assert.EQ.mat(mT[4,, drop = FALSE], mm[4,, drop = FALSE])
160  stopifnot(identical3(mm[,1], mC[,1], mT[,1]),  stopifnot(identical3(mm[,1], mC[,1], mT[,1]),
161            identical3(mm[3,], mC[3,], mT[3,]),            identical3(mm[3,], mC[3,], mT[3,]),
162            identical3(mT[2,3], mC[2,3], 0),            identical3(mT[2,3], mC[2,3], 0),
163            identical(mT[], mT),            identical(mT[], mT),
164            ## TODO: identical4() with  m[c(3,7), 2:4]            identical4(       mm[c(3,7), 2:4],  as.mat( m[c(3,7), 2:4]),
165            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]))
166                       as(mT[c(3,7), 2:4],"matrix")))            )
167    
168    x.x <- crossprod(mC)
169    stopifnot(class(x.x) == "dsCMatrix",
170              class(x.x. <- round(x.x / 10000)) == "dsCMatrix",
171              identical(x.x[cbind(2:6, 2:6)],
172                        diag(x.x [2:6, 2:6])))
173    head(x.x.) # Note the *non*-structural 0's printed as "0"
174    tail(x.x., -3) # all but the first three lines
175    
176    lx.x <- as(x.x, "lsCMatrix") # FALSE only for "structural" 0
177    (l10 <- lx.x[1:10, 1:10])# "lsC"
178    (l3 <-  lx.x[1:3, ])
179    m.x <- as(x.x, "matrix")
180    stopifnot(class(l10) == "lsCMatrix", # symmetric indexing -> symmetric !
181              identical(as.mat(lx.x), m.x != 0),
182              identical(as.logical(lx.x), as.logical(m.x)),
183              identical(as.mat(l10), m.x[1:10, 1:10] != 0),
184              identical(as.mat(l3 ), m.x[1:3, ] != 0)
185              )
186    
187    ##-- Sub*assignment* with repeated / duplicated index:
188    A <- Matrix(0,4,3) ; A[c(1,2,1), 2] <- 1 ; A
189    B <- A;              B[c(1,2,1), 2] <- 1:3; B
190    stopifnot(identical(unname(as.matrix(A)),
191                        local({a <- matrix(0,4,3); a[c(1,2,1), 2] <-  1 ; a})),
192              identical(unname(as.matrix(B)),
193                        local({a <- matrix(0,4,3); a[c(1,2,1), 2] <- 1:3; a})))
194    
195    
196    ## used to fail
197    n <- 5 ## or much larger
198    sm <- new("dsTMatrix", i=as.integer(1),j=as.integer(1),
199              Dim=as.integer(c(n,n)), x = 1)
200    (cm <- as(sm, "CsparseMatrix"))
201    sm[2,]
202    stopifnot(sm[2,] == c(0:1, rep.int(0,ncol(sm)-2)),
203              sm[2,] == cm[2,],
204              sm[,3] == sm[3,],
205              all(sm[,-(1:3)] == t(sm[-(1:3),])), # all(<lge.>)
206              all(sm[,-(1:3)] == 0)
207              )
208    
209    ### Diagonal -- Sparse:
210    m0 <- Diagonal(5)
211    (m1 <- as(m0, "sparseMatrix"))  # dtTMatrix
212    (m2 <- as(m0, "CsparseMatrix")) # dtCMatrix (with an irrelevant warning)
213    m1g <- as(m1, "generalMatrix")
214    stopifnot(is(m1g, "dgTMatrix"))
215    assert.EQ.mat(m2[1:3,],    diag(5)[1:3,])
216    assert.EQ.mat(m2[,c(4,1)], diag(5)[,c(4,1)])
217    stopifnot(identical(m2[1:3,], as(m1[1:3,], "CsparseMatrix")),
218              identical(Matrix:::uniqTsparse(m1[, c(4,2)]),
219                        Matrix:::uniqTsparse(as(m2[, c(4,2)], "TsparseMatrix")))
220              )## failed in 0.9975-11
221    
222    M <- m0; M[1,] <- 0
223    stopifnot(identical(M, Diagonal(x=c(0, rep(1,4)))))
224    M <- m0; M[,3] <- 3 ; M ; stopifnot(is(M, "sparseMatrix"), M[,3] == 3)
225    validObject(M)
226    M <- m0; M[1:3, 3] <- 0 ;M
227    T <- m0; T[1:3, 3] <- 10
228    stopifnot(identical(M, Diagonal(x=c(1,1, 0, 1,1))),
229              is(T, "triangularMatrix"), identical(T[,3], c(10,10,10,0,0)))
230    
231    M <- m1; M[1,] <- 0 ; M ; assert.EQ.mat(M, diag(c(0,rep(1,4))), tol=0)
232    M <- m1; M[,3] <- 3 ; stopifnot(is(M,"sparseMatrix"), M[,3] == 3)
233    validObject(M)
234    M <- m1; M[1:3, 3] <- 0 ;M
235    assert.EQ.mat(M, diag(c(1,1, 0, 1,1)), tol=0)
236    T <- m1; T[1:3, 3] <- 10; validObject(T)
237    stopifnot(is(T, "dtTMatrix"), identical(T[,3], c(10,10,10,0,0)))
238    
239    M <- m2; M[1,] <- 0 ; M ; assert.EQ.mat(M, diag(c(0,rep(1,4))), tol=0)
240    M <- m2; M[,3] <- 3 ; stopifnot(is(M,"sparseMatrix"), M[,3] == 3)
241    validObject(M)
242    M <- m2; M[1:3, 3] <- 0 ;M
243    assert.EQ.mat(M, diag(c(1,1, 0, 1,1)), tol=0)
244    T <- m2; T[1:3, 3] <- 10; validObject(T)
245    stopifnot(is(T, "dtCMatrix"), identical(T[,3], c(10,10,10,0,0)))
246    
247    
248    ## --- negative indices ----------
249    mc <- mC[1:5, 1:7]
250    mt <- mT[1:5, 1:7]
251    ## sub matrix
252    assert.EQ.mat(mC[1:2, 0:3], mm[1:2, 0:3]) # test 0-index
253    stopifnot(identical(mc[-(3:5), 0:2], mC[1:2, 0:2]),
254              identical(mt[-(3:5), 0:2], mT[1:2, 0:2]),
255              identical(mC[2:3, 4],      mm[2:3, 4]))
256    assert.EQ.mat(mC[1:2,], mm[1:2,])
257    ## sub vector
258    stopifnot(identical4(mc[-(1:4), ], mC[5, 1:7],
259                         mt[-(1:4), ], mT[5, 1:7]))
260    stopifnot(identical4(mc[-(1:4), -(2:4)], mC[5, c(1,5:7)],
261                         mt[-(1:4), -(2:4)], mT[5, c(1,5:7)]))
262    
263    ## mixing of negative and positive must give error
264    assertError(mT[-1:1,])
265    
266    ## Sub *Assignment* ---- now works (partially):
267    mt0 <- mt
268    mt[1, 4] <- -99
269    mt[2:3, 1:6] <- 0
270    mt
271    m2 <- mt+mt
272    m2[1,4] <- -200
273    m2[c(1,3), c(5:6,2)] <- 1:6
274    stopifnot(m2[1,4] == -200,
275              as.vector(m2[c(1,3), c(5:6,2)]) == 1:6)
276    mt[,3] <- 30
277    mt[2:3,] <- 250
278    mt[1:5 %% 2 == 1, 3] <- 0
279    mt[3:1, 1:7 > 5] <- 0
280    mt
281    
282    tt <- as(mt,"matrix")
283    ii <- c(0,2,5)
284    jj <- c(2:3,5)
285    tt[ii, jj] <- 1:6 # 0 is just "dropped"
286    mt[ii, jj] <- 1:6
287    assert.EQ.mat(mt, tt)
288    
289    mt[1:5, 2:6]
290    as((mt0 - mt)[1:5,], "dsparseMatrix")# [1,5] and lines 2:3
291    
292    mt[c(2,4), ] <- 0; stopifnot(as(mt[c(2,4), ],"matrix") == 0)
293    mt[2:3, 4:7] <- 33
294    validObject(mt)
295    mt
296    
297    mc[1,4] <- -99 ; stopifnot(mc[1,4] == -99)
298    mc[1,4] <-  00 ; stopifnot(mc[1,4] ==  00)
299    mc[1,4] <- -99 ; stopifnot(mc[1,4] == -99)
300    mc[1:2,4:3] <- 4:1; stopifnot(as.matrix(mc[1:2,4:3]) == 4:1)
301    
302    mc[-1, 3] <- -2:1 # 0 should not be entered; 'value' recycled
303    mt[-1, 3] <- -2:1
304    stopifnot(mc@x != 0, mt@x != 0,
305              mc[-1,3] == -2:1, mt[-1,3] == -2:1) ## failed earlier
306    
307    mc0 <- mc
308    mt0 <- as(mc0, "TsparseMatrix")
309    m0  <- as(mc0, "matrix")
310    set.seed(1)
311    for(i in 1:50) {
312        mc <- mc0; mt <- mt0 ; m <- m0
313        ev <- 1:5 %% 2 == round(runif(1))# 0 or 1
314        j <- sample(ncol(mc), 1 + round(runif(1)))
315        nv <- rpois(sum(ev) * length(j), lambda = 1)
316        mc[ev, j] <- nv
317         m[ev, j] <- nv
318        mt[ev, j] <- nv
319        if(i %% 10 == 1) print(mc[ev,j, drop = FALSE])
320        stopifnot(as.vector(mc[ev, j]) == nv, ## failed earlier...
321                  as.vector(mt[ev, j]) == nv)
322        validObject(mc) ; assert.EQ.mat(mc, m)
323        validObject(mt) ; assert.EQ.mat(mt, m)
324    }
325    
326    mc # no longer has non-structural zeros
327    mc[ii, jj] <- 1:6
328    mc[c(2,5), c(3,5)] <- 3.2
329    validObject(mc)
330    m. <- mc
331    mc[4,] <- 0
332    mc
333    
334    H <- Hilbert(9)
335    Hc <- as(round(H, 3), "dsCMatrix")# a sparse matrix with no 0 ...
336    (trH <- tril(Hc[1:5, 1:5]))
337    stopifnot(is(trH, "triangularMatrix"), trH@uplo == "L")
338    
339    i <- c(1:2, 4, 6:7); j <- c(2:4,6)
340    H[i,j] <- 0
341    (H. <- round(as(H, "sparseMatrix"), 3)[ , 2:7])
342    Hc. <- Hc
343    Hc.[i,j] <- 0 ## now "works", but setting "non-structural" 0s
344    stopifnot(as.matrix(Hc.[i,j]) == 0)
345    Hc.[, 1:6]
346    
347    ## an example that failed for a long time
348    sy3 <- new("dsyMatrix", Dim = as.integer(c(2, 2)), x = c(14, -1, 2, -7))
349    validObject(dm <- kronecker(Diagonal(2), sy3))# now sparse with new kronecker
350    dm <- Matrix(as.matrix(dm))# -> "dsyMatrix"
351    (s2 <- as(dm, "sparseMatrix"))
352    validObject(st <- as(s2, "TsparseMatrix"))
353    stopifnot(is(s2, "symmetricMatrix"),
354              is(st, "symmetricMatrix"))
355    validObject(s.32  <- st[1:3,1:2]) ## 3 x 2 - and *not* dsTMatrix
356    validObject(s2.32 <- s2[1:3,1:2])
357    I <- c(1,4:3)
358    stopifnot(is(s2.32, "generalMatrix"),
359              is(s.32,  "generalMatrix"),
360              identical(as.mat(s.32), as.mat(s2.32)),
361              identical3(dm[1:3,-1], asD(s2[1:3,-1]), asD(st[1:3,-1])),
362              identical4(2, dm[4,3], s2[4,3], st[4,3]),
363              identical3(diag(dm), diag(s2), diag(st)),
364              is((cI <- s2[I,I]), "dsCMatrix"),
365              is((tI <- st[I,I]), "dsTMatrix"),
366              identical4(as.mat(dm)[I,I], as.mat(dm[I,I]), as.mat(tI), as.mat(cI))
367              )
368    
369    ## now sub-assign  and check for consistency
370    ## symmetric subassign should keep symmetry
371    st[I,I] <- 0; validObject(st); stopifnot(is(st,"symmetricMatrix"))
372    s2[I,I] <- 0; validObject(s2); stopifnot(is(s2,"symmetricMatrix"))
373    ##
374    m <- as.mat(st)
375     m[2:1,2:1] <- 4:1
376    st[2:1,2:1] <- 4:1
377    s2[2:1,2:1] <- 4:1
378    stopifnot(identical(m, as.mat(st)),
379              1:4 == as.vector(s2[1:2,1:2]),
380              identical(m, as.mat(s2)))
381    
382    ## now a slightly different situation for 's2' (had bug)
383    s2 <- as(dm, "sparseMatrix")
384    s2[I,I] <- 0; diag(s2)[2:3] <- -(1:2)
385    stopifnot(is(s2,"symmetricMatrix"), diag(s2) == c(0:-2,0))
386    t2 <- as(s2, "TsparseMatrix")
387    m <- as.mat(s2)
388    s2[2:1,2:1] <- 4:1
389    t2[2:1,2:1] <- 4:1
390     m[2:1,2:1] <- 4:1
391    assert.EQ.mat(t2, m)
392    assert.EQ.mat(s2, m)
393    ## and the same (for a different s2 !)
394    s2[2:1,2:1] <- 4:1
395    t2[2:1,2:1] <- 4:1
396    assert.EQ.mat(t2, m)# ok
397    assert.EQ.mat(s2, m)# failed in 0.9975-8
398    
399    
400    ## m[cbind(i,j)] <- value:
401    m.[ cbind(3:5, 1:3) ] <- 1:3
402    stopifnot(m.[3,1] == 1, m.[4,2] == 2)
403    x.x[ cbind(2:6, 2:6)] <- 12:16
404    validObject(x.x)
405    stopifnot(class(x.x) == "dsCMatrix",
406              12:16 == as.mat(x.x)[cbind(2:6, 2:6)])
407    (ne1 <- (mc - m.) != 0)
408    stopifnot(identical(ne1, 0 != abs(mc - m.)))
409    (ge <- m. >= mc) # contains "=" -> result is dense
410    ne. <- mc != m.  # was wrong (+ warning)
411    stopifnot(identical(!(m. < mc), m. >= mc),
412              identical(m. < mc, as(!ge, "sparseMatrix")),
413              identical(ne., Matrix:::drop0(ne1)))
414    
415    (M3 <- Matrix(upper.tri(matrix(, 3, 3)))) # ltC; indexing used to fail
416    T3 <- as(M3, "TsparseMatrix")
417    stopifnot(identical(drop(M3), M3),
418              identical4(drop(M3[,2, drop = FALSE]), M3[,2, drop = TRUE],
419                         drop(T3[,2, drop = FALSE]), T3[,2, drop = TRUE]),
420              is(T3, "triangularMatrix"),
421              !is(T3[,2, drop=FALSE], "triangularMatrix")
422              )
423    
424    cat('Time elapsed: ', proc.time(),'\n') # for ``statistical reasons''

Legend:
Removed from v.873  
changed lines
  Added in v.1835

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