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

Legend:
Removed from v.1215  
changed lines
  Added in v.2505

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