tests/testthat/test_adj_sum_partition.R

context("Testing adj_sum_partition")

test_that("weights within partitions coincides", {

    for (i in seq.int(50)) {    
        
        # create random matrix
        n = sample(10:50, 1)
        A = matrix(
            sample.int(2, n^2, replace = T), 
            nrow = n) - 1L
        diag(A) = 0L
        
        # weighted matrix
        if(i %% 2 == 0) {
            # numeric weights
            w = rnorm(sum(A))
        } else {
            # non-negative integer weights
            w = rpois(sum(A), 3)
        }
        W = ifelse(A == 1, w, 0)
        
        # partition into random groups of random size
        p_size = sample.int(n - 1, 1L)
        part = sample.int(p_size, n, replace = T)
        
        # compare sums
        sum1 = sum(W[outer(part, part, `==`)])
        sum2 = adj_sum_partition(W, part)
        
        expect_equal(sum1, sum2)
        
    }
    
})

test_that("weights within partitions coincides (sparse)", {
    
    library(Matrix)
    
    for (i in seq.int(50)) {    
        
        # create random matrix
        n = sample(10:50, 1)
        A = matrix(
            sample.int(2, n^2, replace = T), 
            nrow = n) - 1L
        diag(A) = 0L
        
        # weighted matrix
        if(i %% 2 == 0) {
            # numeric weights
            w = rnorm(sum(A))
        } else {
            # non-negative integer weights
            w = rpois(sum(A), 3)
        }
        W = ifelse(A == 1, w, 0)
        
        # partition into random groups of random size
        p_size = sample.int(n - 1, 1L)
        part = sample.int(p_size, n, replace = T)
        
        # compare sums
        sum1 = sum(W[outer(part, part, `==`)])
        sum2 = adj_sum_partition_sp(Matrix(W, sparse = T), part)
        
        expect_equal(sum1, sum2)
        
    }
    
})
baruuum/btoolbox documentation built on Aug. 17, 2020, 1:29 a.m.