diff --git a/tests/testthat/helper-invariants.R b/tests/testthat/helper-invariants.R new file mode 100644 index 0000000..cae3abc --- /dev/null +++ b/tests/testthat/helper-invariants.R @@ -0,0 +1,99 @@ +# shared helpers for property-based tests. these check invariants that +# must hold for any model, rather than pinning particular values + +# column of the (single) nonzero entry in each row of a block membership +# matrix, with 0 for rows that are entirely zero +membership_column <- function(X) { + X <- as.matrix(X) + out <- max.col(X != 0, ties.method = "first") + out[rowSums(X != 0) == 0] <- 0L + out +} + +# dense P = E[A | X, S] for any factor model +dense_expectation <- function(model) { + as.matrix(expectation(model)) +} + +# z-score of an observed total of `reps` independent Poisson(mu) draws +poisson_total_z <- function(total, mu, reps = 1) { + (total - reps * mu) / sqrt(reps * mu) +} + +# Bonferroni-corrected two-sided normal critical value for `m` simultaneous +# z-tests at overall level `alpha` +bonferroni_z <- function(m, alpha = 1e-3) { + stats::qnorm(1 - alpha / (2 * m)) +} + +# check the internal consistency of a (undirected) dcsbm-like model: z, X, +# theta and pi all describe the same nodes, in the same order +expect_dcsbm_consistent <- function(m) { + X <- as.matrix(m$X) + n <- m$n + k <- m$k + + expect_equal(dim(X), c(n, k)) + expect_s3_class(m$z, "factor") + expect_length(m$z, n) + expect_equal(nlevels(m$z), k) + expect_length(m$theta, n) + expect_length(m$pi, k) + expect_equal(sum(m$pi), 1) + expect_true(all(m$pi >= 0)) + + # each row of X has exactly one nonzero entry, in column z[i], and it is + # theta[i] + expect_true(all(rowSums(X != 0) <= 1)) + nonzero <- m$theta > 0 + expect_equal(membership_column(X)[nonzero], as.integer(m$z)[nonzero]) + expect_equal(unname(rowSums(X)), as.numeric(m$theta)) + + # S is symmetric and the right size + expect_equal(dim(m$S), c(k, k)) + expect_true(isSymmetric(as.matrix(m$S))) + + invisible(m) +} + +# check the internal consistency of a directed_dcsbm +expect_directed_dcsbm_consistent <- function(m) { + X <- as.matrix(m$X) + Y <- as.matrix(m$Y) + + expect_equal(dim(X), c(m$n, m$k1)) + expect_equal(dim(Y), c(m$d, m$k2)) + expect_equal(dim(m$S), c(m$k1, m$k2)) + + expect_length(m$z_out, m$n) + expect_length(m$z_in, m$d) + expect_equal(nlevels(m$z_out), m$k1) + expect_equal(nlevels(m$z_in), m$k2) + expect_length(m$theta_out, m$n) + expect_length(m$theta_in, m$d) + expect_length(m$pi_out, m$k1) + expect_length(m$pi_in, m$k2) + expect_equal(sum(m$pi_out), 1) + expect_equal(sum(m$pi_in), 1) + + expect_equal(membership_column(X), as.integer(m$z_out)) + expect_equal(membership_column(Y), as.integer(m$z_in)) + expect_equal(unname(rowSums(X)), as.numeric(m$theta_out)) + expect_equal(unname(rowSums(Y)), as.numeric(m$theta_in)) + + invisible(m) +} + +# all four samplers, run from the same seed. they all consume the RNG the +# same way, so they describe the same graph +sample_all <- function(model, seed, multigraph = TRUE) { + set.seed(seed) + el <- sample_edgelist(model, multigraph = multigraph) + set.seed(seed) + A <- sample_sparse(model) + set.seed(seed) + ig <- sample_igraph(model, multigraph = multigraph) + set.seed(seed) + tg <- sample_tidygraph(model, multigraph = multigraph) + list(el = el, A = A, ig = ig, tg = tg) +} diff --git a/tests/testthat/test-edge-cases.R b/tests/testthat/test-edge-cases.R new file mode 100644 index 0000000..10f6a4a --- /dev/null +++ b/tests/testthat/test-edge-cases.R @@ -0,0 +1,177 @@ +# tiny graphs, empty graphs, empty blocks and other boundary cases + +test_that("tiny undirected and directed models sample with every sampler", { + set.seed(100) + models <- list( + er_1 = erdos_renyi(n = 1, p = 0.5), + er_2 = erdos_renyi(n = 2, p = 0.5), + sbm_2 = sbm(n = 2, B = diag(2) * 0.5), + pp_3 = planted_partition(n = 3, k = 3, within_block = 0.5, between_block = 0.1), + directed_er_1 = directed_erdos_renyi(n = 1, p = 0.5), + directed_2 = directed_dcsbm(theta_out = c(1, 2), theta_in = c(2, 1), B = diag(2)), + rectangular_1_by_3 = directed_factor_model(matrix(1), matrix(0.5), matrix(1, 3, 1)) + ) + + for (name in names(models)) { + model <- models[[name]] + directed <- inherits(model, "directed_factor_model") + d <- if (directed) model$d else model$n + + for (seed in 1:5) { + s <- sample_all(model, seed) + expect_equal(dim(s$A), c(model$n, d), label = name) + expect_s3_class(s$el, "tbl_df") + expect_equal(igraph::ecount(s$ig), nrow(s$el), label = name) + } + } +}) + +test_that("models with no edges give empty graphs of the right shape", { + models <- list( + undirected = undirected_factor_model(matrix(1, 6, 1), matrix(0)), + directed_square = directed_erdos_renyi(n = 6, p = 0), + directed_rectangular = directed_factor_model(matrix(1, 6, 1), matrix(0), matrix(1, 4, 1)), + zero_block_sbm = sbm(n = 6, B = matrix(c(0, 0, 0, 0), 2), poisson_edges = FALSE) + ) + + for (name in names(models)) { + model <- models[[name]] + expect_equal(expected_edges(model), 0, label = name) + + for (multigraph in c(TRUE, FALSE)) { + s <- sample_all(model, 1, multigraph = multigraph) + expect_equal(nrow(s$el), 0, label = name) + expect_equal(sum(s$A), 0, label = name) + expect_equal(igraph::ecount(s$ig), 0, label = name) + expect_equal(igraph::ecount(s$tg), 0, label = name) + if (!multigraph) { + expect_named(s$el, c("from", "to", "weight")) + } + } + } +}) + +test_that("empty blocks and zero-probability blocks get no nodes and no edges", { + set.seed(101) + B <- matrix(c(0.5, 0.2, 0.1, 0.2, 0.4, 0.3, 0.1, 0.3, 0.6), 3) + + m <- sbm(n = 20, B = B, block_sizes = c(8, 0, 12)) + expect_equal(sort(as.vector(table(m$z))), c(0, 8, 12)) + empty <- which(table(m$z) == 0) + expect_equal(sum(as.matrix(m$X)[, empty]), 0) + + m <- dcsbm(theta = rexp(20) + 0.5, B = B, pi = c(0.5, 0, 0.5)) + empty <- which(m$pi == 0) + expect_length(empty, 1) + expect_equal(sum(m$z == levels(m$z)[empty]), 0) + + # sampling never touches the empty block + P <- dense_expectation(m) + for (seed in 1:5) { + set.seed(seed) + A <- sample_sparse(m) + expect_true(all(as.matrix(A)[P == 0] == 0)) + } + + # directed models with empty blocks on either side + set.seed(102) + dm <- directed_dcsbm( + theta_out = rep(1, 15), + theta_in = rep(1, 15), + B = matrix(runif(6), 2), + block_sizes_out = c(0, 15), + pi_in = c(0.5, 0, 0.5) + ) + expect_true(any(table(dm$z_out) == 0)) + expect_true(any(table(dm$z_in) == 0)) + expect_equal(dim(sample_sparse(dm)), c(15, 15)) +}) + +test_that("balanced default block sizes differ by at most one", { + for (n in c(5, 7, 10, 23)) { + for (k in 1:5) { + sizes <- balanced_block_sizes(n, k) + expect_equal(sum(sizes), n) + expect_length(sizes, k) + expect_lte(max(sizes) - min(sizes), 1) + + set.seed(103) + m <- sbm(n = n, B = diag(k) * 0.5 + 0.1) + expect_equal(sort(as.vector(table(m$z))), sort(sizes)) + } + } +}) + +test_that("rank one models of every kind work", { + set.seed(104) + models <- list( + sbm = sbm(n = 10, B = matrix(0.3)), + dcsbm = dcsbm(theta = rexp(10), B = matrix(0.3)), + dcsbm_unsorted = dcsbm(theta = rexp(10), B = matrix(0.3), sort_nodes = FALSE), + planted_partition = planted_partition(n = 10, k = 1, within_block = 0.3, between_block = 0.1), + overlapping = overlapping_sbm(n = 10, B = matrix(0.3)), + directed = directed_dcsbm(theta_out = rexp(10), theta_in = rexp(10), B = matrix(0.3)), + directed_pp = directed_planted_partition(n = 10, k = 1, within_block = 0.3, between_block = 0.1) + ) + + for (name in names(models)) { + model <- models[[name]] + P <- dense_expectation(model) + expect_equal(qr(P)$rank, 1, label = name) + expect_no_error(sample_sparse(model)) + } +}) + +test_that("planted_partition() validates its inputs", { + expect_error( + planted_partition(n = 2, k = 3, within_block = 0.5, between_block = 0.1), + "less than or equal to `n`" + ) + expect_error( + planted_partition(n = 10, k = 2, within_block = 0.5, between_block = c(0.1, 0.2)), + "`between_block` must be a scalar" + ) + expect_error( + planted_partition(n = 10, k = 2, within_block = 0.5, between_block = 1.5), + "`between_block` must be between zero and one" + ) + expect_error( + planted_partition(n = 10, k = 2, within_block = -0.5, between_block = 0.1), + "non-negative" + ) +}) + +test_that("planted_partition() a and b parameterization divides by n", { + set.seed(105) + m <- planted_partition(n = 50, k = 2, a = 10, b = 2) + expect_equal(m$within_block, 10 / 50) + expect_equal(m$between_block, 2 / 50) + S <- as.matrix(m$S) + expect_equal(unique(diag(S)), 0.2) + expect_equal(unique(S[row(S) != col(S)]), 0.04) +}) + +test_that("sample_edgelist() works directly on matrices", { + set.seed(106) + X <- matrix(rexp(10), 5) + S <- matrix(c(0.5, 0.1, 0.2, 0.3), 2) + Y <- matrix(rexp(14), 7) + + el <- sample_edgelist(X, S, Y, TRUE, TRUE, TRUE) + expect_s3_class(el, "tbl_df") + expect_true(all(el$from %in% 1:5)) + expect_true(all(el$to %in% 1:7)) + + set.seed(106) + el_matrix <- sample_edgelist(Matrix::Matrix(X), Matrix::Matrix(S), Matrix::Matrix(Y), TRUE, TRUE, TRUE) + set.seed(106) + el_base <- sample_edgelist(X, S, Y, TRUE, TRUE, TRUE) + expect_identical(el_matrix, el_base) + + # undirected sampling puts every edge in the upper triangle + el <- sample_edgelist(X, S, X, FALSE, TRUE, TRUE) + expect_true(all(el$from <= el$to)) + + expect_error(sample_edgelist(X, S, Y, "yes", TRUE, TRUE)) + expect_error(sample_edgelist(X, S, Y, TRUE, TRUE, TRUE, multigraph = NA), "multigraph") +}) diff --git a/tests/testthat/test-expectation-monte-carlo.R b/tests/testthat/test-expectation-monte-carlo.R new file mode 100644 index 0000000..a629ce8 --- /dev/null +++ b/tests/testthat/test-expectation-monte-carlo.R @@ -0,0 +1,263 @@ +# Monte Carlo checks that sampled graphs have the expectation the model +# claims, entry by entry. +# +# Write P = expectation(model). Conditional on the latent factors, the +# entries of A (upper triangle and diagonal for undirected graphs) are +# independent, with +# +# Poisson graphs: A[i, j] ~ Poisson(P[i, j]) +# Bernoulli graphs: A[i, j] ~ Bernoulli(1 - exp(-P[i, j])) +# +# because Bernoulli graphs are sampled as Poisson graphs with rate P and +# then thresholded. So over `reps` independent replicates the entrywise +# totals T[i, j] are exactly Poisson(reps P[i, j]) or +# Binomial(reps, 1 - exp(-P[i, j])), and the Pearson statistic +# +# sum over cells (T - E[T])^2 / Var[T] +# +# is approximately chi-squared with one degree of freedom per cell, as long +# as E[T] is not small. The models below keep every reps * P[i, j] above +# ~50, so the chi-squared approximation is accurate, and we test at level +# 1e-4. Cells where the model says A[i, j] = 0 (no self-loops) must be +# exactly zero in every replicate. + +# sum of `reps` sampled adjacency matrices, as a dense matrix +sum_of_samples <- function(model, reps) { + total <- matrix(0, model$n, if (is.null(model$d)) model$n else model$d) + for (r in seq_len(reps)) { + total <- total + as.matrix(sample_sparse(model)) + } + total +} + +# the cells of A that are sampled independently +independent_cells <- function(model) { + P <- dense_expectation(model) + if (inherits(model, "undirected_factor_model")) { + upper.tri(P, diag = TRUE) + } else { + matrix(TRUE, nrow(P), ncol(P)) + } +} + +expect_entrywise_expectation <- function(model, reps, label, level = 1e-4) { + P <- dense_expectation(model) + total <- sum_of_samples(model, reps) + cells <- independent_cells(model) + + square <- nrow(P) == ncol(P) + zero <- matrix(FALSE, nrow(P), ncol(P)) + if (!model$allow_self_loops && square) { + diag(zero) <- TRUE + } + + # structural zeros are exactly zero + expect_true(all(total[zero] == 0), label = label) + + test <- cells & !zero + + if (model$poisson_edges) { + mean <- reps * P[test] + var <- mean + } else { + p <- 1 - exp(-P[test]) + mean <- reps * p + var <- reps * p * (1 - p) + } + + stat <- sum((total[test] - mean)^2 / var) + df <- sum(test) + + expect_lt(stat, stats::qchisq(1 - level, df), label = paste(label, "chi-squared")) + + # and the statistic is not suspiciously small either, which would mean + # that the variance is wrong + expect_gt(stat, stats::qchisq(level, df), label = paste(label, "chi-squared")) +} + +test_that("undirected Poisson graphs have E[A] = expectation(model)", { + skip_on_cran() + + set.seed(50) + n <- 10 + X <- matrix(runif(n * 2, 0.5, 1.5), n) + S <- matrix(c(0.8, 0.3, 0.1, 0.6), 2) # asymmetric, gets symmetrized + + for (loops in c(TRUE, FALSE)) { + model <- undirected_factor_model(X, S, allow_self_loops = loops) + expect_entrywise_expectation(model, reps = 150, label = paste("loops", loops)) + } +}) + +test_that("undirected Bernoulli graphs have E[A] = 1 - exp(-expectation(model))", { + skip_on_cran() + + set.seed(51) + n <- 10 + + for (loops in c(TRUE, FALSE)) { + # a general factor model: X has unequal weights, so the edge + # probabilities are not simply X S X' + model <- undirected_factor_model( + matrix(runif(n * 2, 0.5, 1.5), n), + matrix(c(0.5, 0.2, 0.2, 0.4), 2), + poisson_edges = FALSE, + allow_self_loops = loops + ) + expect_entrywise_expectation(model, reps = 400, label = paste("ufm loops", loops)) + + # for blockmodels, the edge probabilities are exactly B + B <- matrix(c(0.7, 0.2, 0.2, 0.4), 2) + m <- sbm(n = n, B = B, block_sizes = c(4, 6), poisson_edges = FALSE, allow_self_loops = loops) + z <- as.integer(m$z) + expect_equal(1 - exp(-dense_expectation(m)), B[z, z], ignore_attr = TRUE) + expect_entrywise_expectation(m, reps = 400, label = paste("sbm loops", loops)) + } +}) + +test_that("dense Bernoulli graphs near density one have the right density", { + # p close to one stresses the -log(1 - p) transformation, and requires + # many repeated Poisson edges to collapse into one + set.seed(52) + n <- 40 + p <- 0.97 + reps <- 20 + + for (loops in c(TRUE, FALSE)) { + model <- erdos_renyi(n = n, p = p, poisson_edges = FALSE, allow_self_loops = loops) + pairs <- choose(n, 2) + if (loops) n else 0 + + edges <- vapply(seq_len(reps), function(r) nrow(sample_edgelist(model)), numeric(1)) + + expect_true(all(edges <= pairs)) + # the total is exactly Binomial(reps * pairs, p) + z <- (sum(edges) - reps * pairs * p) / sqrt(reps * pairs * p * (1 - p)) + expect_lt(abs(z), 4.5) + } +}) + +test_that("directed Poisson and Bernoulli graphs have the right expectation", { + skip_on_cran() + + set.seed(53) + n <- 8 + + for (d in c(8, 11)) { + for (poisson in c(TRUE, FALSE)) { + # self-loops are only meaningful when rows and columns index the + # same nodes + for (loops in if (d == n) c(TRUE, FALSE) else TRUE) { + model <- directed_factor_model( + X = matrix(runif(n * 2, 0.5, 1.5), n), + S = matrix(c(0.6, 0.1, 0.3, 0.2, 0.4, 0.5), 2), + Y = matrix(runif(d * 3, 0.5, 1.5), d), + poisson_edges = poisson, + allow_self_loops = loops + ) + label <- paste("d", d, "poisson", poisson, "loops", loops) + expect_entrywise_expectation(model, reps = 200, label = label) + } + } + } +}) + +test_that("blockmodel constructors have E[A] = expectation(model)", { + skip_on_cran() + + set.seed(54) + n <- 9 + + models <- list( + dcsbm_unsorted = dcsbm( + theta = runif(n, 1, 2), + B = matrix(c(0.5, 0.2, 0.2, 0.3), 2), + pi = c(0.3, 0.7), + sort_nodes = FALSE + ), + mmsbm = mmsbm(theta = runif(n, 1, 2), B = matrix(c(0.6, 0.2, 0.2, 0.5), 2), alpha = c(1, 2)), + overlapping = overlapping_sbm(n = n, B = matrix(c(0.5, 0.2, 0.2, 0.4), 2), poisson_edges = FALSE), + directed_dcsbm = directed_dcsbm( + theta_out = runif(n, 1, 2), + theta_in = runif(n, 1, 2), + B = matrix(c(0.5, 0.2, 0.1, 0.4), 2), + force_identifiability = FALSE, + allow_self_loops = FALSE + ), + directed_pp = directed_planted_partition( + n = n, + k = 2, + within_block = 0.6, + between_block = 0.2, + poisson_edges = FALSE + ) + ) + + for (name in names(models)) { + expect_entrywise_expectation(models[[name]], reps = 250, label = name) + } +}) + +test_that("expected_degrees() matches the mean sampled degree of every node", { + skip_on_cran() + + # for Poisson graphs with self-loops, rowSums(A)[i] is a sum of + # independent Poisson entries, so its total over reps is exactly + # Poisson(reps * expected_degrees(model)[i]) + set.seed(55) + n <- 80 + reps <- 100 + + models <- list( + dcsbm = dcsbm(theta = rexp(n) + 0.2, B = diag(3) * 0.5 + 0.1, expected_degree = 8), + chung_lu = chung_lu(theta = rexp(n) + 0.2, expected_degree = 8), + mmsbm = mmsbm(theta = rexp(n) + 0.2, B = diag(3) * 0.5 + 0.1, alpha = rep(1, 3), expected_degree = 8) + ) + + for (name in names(models)) { + model <- models[[name]] + expected <- expected_degrees(model) + expect_equal(mean(expected), expected_degree(model)) + + total <- numeric(n) + for (r in seq_len(reps)) { + total <- total + rowSums(sample_sparse(model)) + } + + z <- poisson_total_z(total, expected, reps) + expect_lt(max(abs(z)), bonferroni_z(n), label = name) + } +}) + +test_that("directed in- and out-degrees match rowSums and colSums of the expectation", { + skip_on_cran() + + set.seed(56) + n <- 40 + d <- 25 + reps <- 100 + + model <- directed_factor_model( + X = matrix(rexp(n * 2), n), + S = matrix(runif(4), 2), + Y = matrix(rexp(d * 2), d), + expected_out_degree = 6 + ) + P <- dense_expectation(model) + + out_total <- numeric(n) + in_total <- numeric(d) + for (r in seq_len(reps)) { + A <- sample_sparse(model) + out_total <- out_total + rowSums(A) + in_total <- in_total + colSums(A) + } + + expect_lt( + max(abs(poisson_total_z(out_total, rowSums(P), reps))), + bonferroni_z(n) + ) + expect_lt( + max(abs(poisson_total_z(in_total, colSums(P), reps))), + bonferroni_z(d) + ) +}) diff --git a/tests/testthat/test-model-consistency.R b/tests/testthat/test-model-consistency.R new file mode 100644 index 0000000..900e2a4 --- /dev/null +++ b/tests/testthat/test-model-consistency.R @@ -0,0 +1,573 @@ +# internal consistency of constructed models across every combination of +# the structural flags. none of these sample graphs, so they are fast + +symmetrize <- function(B) (B + t(B)) / 2 + +# the matrix S should be after symmetrizing, reordering and (for Bernoulli +# graphs) transforming B to the Poisson parameterization +expected_S <- function(B, o, poisson_edges) { + S <- symmetrize(B)[o, o, drop = FALSE] + if (poisson_edges) S else -log(1 - S) +} + +test_that("dcsbm() keeps z, X, theta, pi and S consistent for every flag combination", { + # builds 120 models, about 5s + skip_on_cran() + + n <- 17 # not divisible by k + theta <- seq(0.5, 3, length.out = n) + + Bs <- list( + `1` = matrix(0.3), + `2` = matrix(c(0.5, 0.1, 0.2, 0.3), 2), # not symmetric + `3` = matrix(c(0.6, 0.1, 0.05, 0.1, 0.4, 0.2, 0.05, 0.2, 0.3), 3) + ) + + specs <- list( + default = function(k) list(), + block_sizes = function(k) list(block_sizes = c(rep(0, k - 1), n)[seq_len(k)]), + block_sizes_mixed = function(k) list(block_sizes = balanced_block_sizes(n, k)[k:1]), + pi = function(k) list(pi = seq_len(k) / sum(seq_len(k))), + pi_zero = function(k) list(pi = if (k == 1) 1 else c(0, rep(1, k - 1))) + ) + + for (k_name in names(Bs)) { + B <- Bs[[k_name]] + k <- nrow(B) + + for (spec_name in names(specs)) { + spec <- specs[[spec_name]](k) + + # the vector the blocks get sorted by + sort_key <- if (!is.null(spec$block_sizes)) { + spec$block_sizes / n + } else if (!is.null(spec$pi)) { + spec$pi + } else { + balanced_block_sizes(n, k) / n + } + + for (sort_nodes in c(TRUE, FALSE)) { + for (fi in c(TRUE, FALSE)) { + for (poisson in c(TRUE, FALSE)) { + # allow_self_loops does not affect construction, so pair each + # value with one value of poisson_edges to save time + for (loops in !poisson) { + label <- paste( + "k", k, spec_name, "sort", sort_nodes, "fi", fi, + "poisson", poisson, "loops", loops + ) + + set.seed(1) + m <- do.call( + dcsbm, + c( + list( + theta = theta, + B = B, + sort_nodes = sort_nodes, + force_identifiability = fi, + poisson_edges = poisson, + allow_self_loops = loops + ), + spec + ) + ) + + expect_s3_class(m, "undirected_dcsbm") + expect_dcsbm_consistent(m) + + # stored fields match the arguments + expect_identical(m$sorted, sort_nodes, label = label) + expect_identical(m$poisson_edges, poisson, label = label) + expect_identical(m$allow_self_loops, loops, label = label) + expect_equal(m$n, n, label = label) + expect_equal(m$k, k, label = label) + + o <- if (k > 1 && sort_nodes) order(sort_key) else seq_len(k) + + # B was permuted consistently with pi + expect_equal(m$pi, sort_key[o] / sum(sort_key), label = label) + expect_equal( + unname(as.matrix(m$S)), + unname(expected_S(B, o, poisson)), + tolerance = 1e-12, + label = label + ) + + counts <- as.vector(table(m$z)) + + # exact block sizes are respected, after relabeling + if (!is.null(spec$block_sizes)) { + expect_equal(counts, spec$block_sizes[o], label = label) + } + + # zero-probability blocks get no nodes + expect_true(all(counts[m$pi == 0] == 0), label = label) + + if (fi) { + sums <- tapply(m$theta, m$z, sum) + expect_equal( + as.vector(sums[counts > 0]), + rep(1, sum(counts > 0)), + label = label + ) + } + + if (sort_nodes) { + expect_false(is.unsorted(as.integer(m$z)), label = label) + # within each block, theta is non-increasing + for (block in split(m$theta, m$z)) { + expect_false(is.unsorted(rev(block)), label = label) + } + } else if (!fi) { + # unsorted models keep theta in node order + expect_equal(m$theta, theta, label = label) + } + } + } + } + } + } + } +}) + +test_that("dcsbm() with sort_nodes = FALSE keeps theta paired with its node", { + # with force_identifiability = TRUE, theta[i] is the input theta[i] + # divided by the total theta of node i's block + set.seed(2) + theta <- rexp(30) + 0.1 + m <- dcsbm( + theta = theta, + B = diag(3) * 0.2 + 0.05, + sort_nodes = FALSE, + force_identifiability = TRUE + ) + + block_totals <- tapply(theta, m$z, sum) + expect_equal(m$theta, theta / block_totals[as.integer(m$z)], ignore_attr = TRUE) +}) + +test_that("sbm() and planted_partition() have theta = 1 and the right S", { + for (sort_nodes in c(TRUE, FALSE)) { + for (poisson in c(TRUE, FALSE)) { + set.seed(3) + B <- matrix(c(0.5, 0.1, 0.1, 0.3), 2) + m <- sbm(n = 11, B = B, sort_nodes = sort_nodes, poisson_edges = poisson) + expect_s3_class(m, "undirected_sbm") + expect_dcsbm_consistent(m) + expect_equal(m$theta, rep(1, 11)) + expect_equal(unname(as.matrix(expectation(m))), unname(dense_expectation(m))) + + set.seed(3) + pp <- planted_partition( + n = 11, + k = 3, + within_block = 0.4, + between_block = 0.05, + sort_nodes = sort_nodes, + poisson_edges = poisson + ) + expect_dcsbm_consistent(pp) + + S <- as.matrix(pp$S) + transform <- if (poisson) identity else function(p) -log(1 - p) + expect_equal(unique(diag(S)), transform(0.4)) + expect_equal(unique(S[row(S) != col(S)]), transform(0.05)) + expect_equal(sort(as.vector(table(pp$z))), c(3, 4, 4)) + } + } +}) + +test_that("chung_lu() is a one-block dcsbm with theta as given", { + theta <- c(5, 1, 3, 2, 4, 2) + + for (sort_nodes in c(TRUE, FALSE)) { + for (fi in c(TRUE, FALSE)) { + set.seed(4) + m <- chung_lu(theta = theta, sort_nodes = sort_nodes, force_identifiability = fi) + + expect_s3_class(m, "undirected_dcsbm") + expect_dcsbm_consistent(m) + expect_equal(m$k, 1) + expect_equal(nlevels(m$z), 1) + expect_equal(as.matrix(m$S), matrix(1)) + + expected_theta <- if (fi) theta / sum(theta) else theta + if (sort_nodes) expected_theta <- sort(expected_theta, decreasing = TRUE) + expect_equal(m$theta, expected_theta) + + # expectation is the outer product of theta + expect_equal( + unname(dense_expectation(m)), + outer(expected_theta, expected_theta) + ) + } + } +}) + +test_that("chung_lu() generates theta from n with a message", { + set.seed(5) + expect_message(m <- chung_lu(n = 8), "LogNormal") + expect_equal(m$n, 8) + expect_length(m$theta, 8) + expect_error(chung_lu(), "Must specify either `n` or `theta`") + expect_error(chung_lu(n = 0), "positive integer") +}) + +test_that("mmsbm() keeps Z, theta, X and alpha consistent", { + n <- 25 + theta <- seq(1, 2, length.out = n) + B <- matrix(c(0.5, 0.1, 0.05, 0.1, 0.4, 0.2, 0.05, 0.2, 0.3), 3) + alpha <- c(3, 1, 2) + o <- order(alpha) + + for (sort_nodes in c(TRUE, FALSE)) { + for (force_pure in c(TRUE, FALSE)) { + for (poisson in c(TRUE, FALSE)) { + label <- paste("sort", sort_nodes, "pure", force_pure, "poisson", poisson) + set.seed(6) + m <- mmsbm( + theta = theta, + B = B, + alpha = alpha, + sort_nodes = sort_nodes, + force_pure = force_pure, + poisson_edges = poisson + ) + + expect_s3_class(m, "undirected_mmsbm") + expect_identical(m$sorted, sort_nodes) + expect_equal(m$alpha, sort(alpha), label = label) + expect_equal(dim(m$Z), c(n, 3), label = label) + expect_equal(unname(rowSums(m$Z)), rep(1, n), label = label) + expect_true(all(m$Z >= 0), label = label) + + # X = diag(theta) Z, row by row + expect_equal( + unname(as.matrix(m$X)), + unname(as.matrix(m$theta * m$Z)), + label = label + ) + expect_setequal(m$theta, theta) + if (!sort_nodes) expect_equal(m$theta, theta, label = label) + + expect_equal( + unname(as.matrix(m$S)), + unname(expected_S(B, o, poisson)), + tolerance = 1e-12, + label = label + ) + + if (force_pure) { + # every block has at least one pure node + expect_true(all(colSums(m$Z == 1) >= 1), label = label) + } + + if (sort_nodes) { + expect_equal(sort_by_all_columns_idx(m$X), seq_len(n), label = label) + } + } + } + } +}) + +test_that("mmsbm() validates its inputs", { + expect_error(mmsbm(B = diag(2)), "Must specify either `n` or `theta`") + expect_error(mmsbm(n = 0, B = diag(2)), "positive integer") + expect_error(mmsbm(theta = rep(1, 10)), "Must specify either `k` or `B`") + expect_error(mmsbm(theta = rep(1, 10), k = 0, alpha = 1), "positive integer") + expect_error(mmsbm(theta = rep(1, 10), B = matrix(1, 2, 3)), "square") + expect_error( + mmsbm(theta = rep(1, 10), B = diag(2), alpha = c(1, 1, 1)), + "must match length of `alpha`" + ) + + set.seed(7) + expect_message(mmsbm(theta = rep(1, 10), k = 2), "Uniform") + expect_message(mmsbm(n = 10, B = diag(2)), "LogNormal") +}) + +test_that("overlapping_sbm() keeps Z, X, pi and B consistent", { + n <- 30 + B <- matrix(c(0.6, 0.1, 0.05, 0.1, 0.4, 0.2, 0.05, 0.2, 0.3), 3) + pi <- c(0.5, 0.2, 0.3) + o <- order(pi) + + for (sort_nodes in c(TRUE, FALSE)) { + for (force_pure in c(TRUE, FALSE)) { + for (poisson in c(TRUE, FALSE)) { + for (loops in c(TRUE, FALSE)) { + label <- paste( + "sort", sort_nodes, "pure", force_pure, + "poisson", poisson, "loops", loops + ) + set.seed(8) + m <- overlapping_sbm( + n = n, + B = B, + pi = pi, + sort_nodes = sort_nodes, + force_pure = force_pure, + poisson_edges = poisson, + allow_self_loops = loops + ) + + X <- as.matrix(m$X) + expect_identical(m$sorted, sort_nodes, label = label) + expect_identical(m$poisson_edges, poisson, label = label) + expect_identical(m$allow_self_loops, loops, label = label) + expect_equal(dim(X), c(n, 3), label = label) + expect_true(all(X %in% c(0, 1)), label = label) + expect_true(all(rowSums(X) >= 1), label = label) + expect_equal(unname(as.matrix(m$Z)), unname(X), label = label) + expect_equal(m$pi, sort(pi), label = label) + expect_equal(unname(as.matrix(m$B)), B[o, o], label = label) + expect_equal( + unname(as.matrix(m$S)), + unname(expected_S(B, o, poisson)), + tolerance = 1e-12, + label = label + ) + + if (force_pure) { + expect_true(all(colSums(X[rowSums(X) == 1, , drop = FALSE]) >= 1)) + } + + if (sort_nodes) { + expect_equal(sort_by_all_columns_idx(X), seq_len(n), label = label) + } + } + } + } + } +}) + +test_that("overlapping_sbm() validates its inputs", { + expect_error(overlapping_sbm(n = 10), "Must specify either `k` or `B`") + expect_error(overlapping_sbm(n = 10, k = 0), "positive integer") + expect_error(overlapping_sbm(n = 10, B = matrix(0.1, 2, 3)), "square") + expect_error( + overlapping_sbm(n = 10, B = diag(2) * 0.5, pi = c(0.5, 0.5, 0.5)), + "Length of `pi`" + ) + expect_error( + overlapping_sbm(n = 10, B = diag(2) * 0.5, pi = c(0.5, 1.5)), + "contained in \\[0, 1\\]" + ) + expect_error(overlapping_sbm(n = 10, B = diag(2) * 1.5), "contained in \\[0, 1\\]") + expect_error(overlapping_sbm(n = 10, B = matrix(0.5, 2, 2)), "invertible") + + set.seed(9) + expect_message(m <- overlapping_sbm(n = 20, k = 3), "0.8 on the diagonal") + expect_equal(unname(diag(as.matrix(m$B))), rep(0.8, 3)) + expect_equal(unique(as.matrix(m$B)[row(m$B) != col(m$B)]), 0.05) +}) + +test_that("directed_dcsbm() is consistent for every flag combination", { + n <- 13 + theta_out <- seq(0.5, 2, length.out = n) + theta_in <- rev(seq(1, 4, length.out = n)) + + Bs <- list( + square_1 = matrix(0.4), + square_3 = matrix(c(0.6, 0.1, 0.05, 0.2, 0.4, 0.2, 0.05, 0.3, 0.3), 3), + rect_1_3 = matrix(c(0.2, 0.3, 0.4), 1), + rect_3_2 = matrix(c(0.6, 0.1, 0.05, 0.2, 0.4, 0.3), 3) + ) + + for (B_name in names(Bs)) { + B <- Bs[[B_name]] + + for (shared_blocks in c(FALSE, TRUE)) { + if (shared_blocks && nrow(B) != ncol(B)) next + + for (shared_theta in c(FALSE, TRUE)) { + if (shared_theta && !shared_blocks) next + + for (sort_nodes in c(TRUE, FALSE)) { + for (fi in c(TRUE, FALSE)) { + for (poisson in c(TRUE, FALSE)) { + label <- paste( + B_name, "shared_blocks", shared_blocks, + "shared_theta", shared_theta, "sort", sort_nodes, + "fi", fi, "poisson", poisson + ) + + theta_args <- if (shared_theta) { + list(theta_out = theta_out) + } else { + list(theta_out = theta_out, theta_in = theta_in) + } + + set.seed(10) + m <- do.call( + directed_dcsbm, + c( + theta_args, + list( + B = B, + shared_blocks = shared_blocks, + shared_theta = shared_theta, + sort_nodes = sort_nodes, + force_identifiability = fi, + poisson_edges = poisson + ) + ) + ) + + expect_s3_class(m, "directed_dcsbm") + expect_directed_dcsbm_consistent(m) + expect_identical(m$shared_blocks, shared_blocks, label = label) + expect_identical(m$shared_theta, shared_theta, label = label) + expect_identical(m$sorted, sort_nodes, label = label) + expect_identical(m$poisson_edges, poisson, label = label) + + # default block sizes are balanced on both sides + expect_equal( + sort(as.vector(table(m$z_out))), + sort(balanced_block_sizes(n, nrow(B))), + label = label + ) + expect_equal( + sort(as.vector(table(m$z_in))), + sort(balanced_block_sizes(n, ncol(B))), + label = label + ) + + if (shared_blocks) { + expect_identical(m$z_out, m$z_in, label = label) + } + + if (shared_theta) { + expect_identical(m$theta_out, m$theta_in, label = label) + } + + if (fi) { + expect_equal( + as.vector(tapply(m$theta_out, m$z_out, sum)), + rep(1, m$k1), + label = label + ) + expect_equal( + as.vector(tapply(m$theta_in, m$z_in, sum)), + rep(1, m$k2), + label = label + ) + } + + if (sort_nodes) { + expect_false(is.unsorted(as.integer(m$z_out)), label = label) + if (!shared_blocks) { + expect_false(is.unsorted(as.integer(m$z_in)), label = label) + } + } else if (!fi) { + expect_equal(m$theta_out, theta_out, label = label) + expected_in <- if (shared_theta) theta_out else theta_in + expect_equal(m$theta_in, expected_in, label = label) + } + + transform <- if (poisson) identity else function(p) -log(1 - p) + expect_setequal(as.vector(as.matrix(m$S)), transform(as.vector(B))) + } + } + } + } + } + } +}) + +test_that("directed_dcsbm() k_out / k_in generate a random B", { + set.seed(11) + expect_message( + m <- directed_dcsbm(theta_out = rep(1, 10), theta_in = rep(1, 10), k_out = 2, k_in = 3), + "Uniform" + ) + expect_equal(dim(m$S), c(2, 3)) + + # with shared blocks, either k_out or k_in is enough + set.seed(11) + m <- suppressMessages( + directed_dcsbm(theta_out = rep(1, 10), theta_in = rep(1, 10), k_out = 2, shared_blocks = TRUE) + ) + expect_equal(dim(m$S), c(2, 2)) +}) + +test_that("directed_dcsbm() validates theta, k and pi", { + B <- diag(2) * 0.5 + th <- rep(1, 10) + + expect_error( + directed_dcsbm(n = 0, B = B, shared_blocks = TRUE, shared_theta = TRUE), + "positive integer" + ) + expect_error( + directed_dcsbm(n = 10, theta_out = rep(1, 10), theta_in = rep(1, 10), B = B), + "not all three at once" + ) + expect_error(directed_dcsbm(n = 0, B = B), "positive integer") + expect_error( + directed_dcsbm(theta_out = rep(1, 10), theta_in = rep(1, 9), B = B), + "Length of `theta_out` must match length of `theta_in`" + ) + expect_error( + directed_dcsbm(n = 10, theta_out = rep(1, 10), B = B), + "but not both" + ) + expect_error(directed_dcsbm(theta_out = th, theta_in = th), "Must specify either `k_out` and `k_in` together") + expect_error(directed_dcsbm(theta_out = th, theta_in = th, k_out = 2), "Must specify either `k_out` and `k_in` together") + expect_error(directed_dcsbm(theta_out = th, theta_in = th, k_out = 0, k_in = 2), "`k_out` must be a positive integer") + expect_error(directed_dcsbm(theta_out = th, theta_in = th, k_out = 2, k_in = 0), "`k_in` must be a positive integer") + expect_error( + directed_dcsbm(theta_out = th, theta_in = th, B = B, pi_out = c(1, 1, 1)), + "Length of `pi_out` must match" + ) + expect_error( + directed_dcsbm(theta_out = th, theta_in = th, B = B, pi_in = c(1, 1, 1)), + "Length of `pi_in` must match" + ) + expect_error( + directed_dcsbm(theta_out = th, theta_in = th, B = B, pi_out = c(-1, 2)), + "`pi_out` must be >= 0" + ) + expect_error( + directed_dcsbm(theta_out = th, theta_in = th, B = B, pi_in = c(-1, 2)), + "`pi_in` must be >= 0" + ) + + set.seed(12) + expect_message(m <- directed_dcsbm(n = 10, B = B), "LogNormal") + expect_length(m$theta_out, 10) +}) + +test_that("random theta and B come with messages in dcsbm()", { + set.seed(13) + expect_message(m <- dcsbm(n = 10, B = diag(2)), "LogNormal") + expect_length(m$theta, 10) + expect_message(m <- dcsbm(theta = rep(1, 10), k = 3), "Uniform") + expect_equal(m$k, 3) +}) + +test_that("dcsbm() validates its inputs", { + expect_error(dcsbm(B = diag(2)), "Must specify either `n` or `theta`") + expect_error(dcsbm(n = 0, B = diag(2)), "positive integer") + expect_error(dcsbm(n = 10, theta = rep(1, 10), B = diag(2)), "only one of `n` and `theta`") + expect_error(dcsbm(theta = rep(1, 10)), "Must specify either `k` or `B`") + expect_error(dcsbm(theta = rep(1, 10), k = 0), "positive integer") + expect_error(dcsbm(theta = rep(1, 10), k = 2, B = diag(2)), "only one of `B` and `k`") + expect_error(dcsbm(theta = rep(1, 10), B = matrix(1, 2, 3)), "square") + expect_error( + dcsbm(theta = rep(1, 10), B = diag(2), block_sizes = c(5, 6)), + "Sum of `block_sizes`" + ) + expect_error( + dcsbm(theta = rep(1, 10), B = diag(2), pi = c(1, 1, 1)), + "Length of `pi`" + ) + expect_error( + dcsbm(theta = rep(1, 10), B = diag(2), pi = c(-1, 2)), + "must be >= 0" + ) + expect_error(dcsbm(theta = c(-1, rep(1, 9)), B = diag(2)), "non-negative") + expect_error(dcsbm(theta = rep(1, 10), B = -diag(2)), "non-negative") +}) diff --git a/tests/testthat/test-plotting.R b/tests/testthat/test-plotting.R new file mode 100644 index 0000000..1508afa --- /dev/null +++ b/tests/testthat/test-plotting.R @@ -0,0 +1,68 @@ +test_that("plot_dense_matrix() draws one tile per entry with the entry's value", { + A <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2) # 2 x 3, not symmetric + + p <- plot_dense_matrix(A) + expect_s3_class(p, "ggplot") + + long <- p$data + expect_equal(nrow(long), length(A)) + expect_equal(long$value, A[cbind(long$row, long$col)]) + + # columns of A run along the x axis, rows down the (reversed) y axis + built <- ggplot2::layer_data(p) + expect_equal(nrow(built), length(A)) + expect_equal(sort(unique(built$x)), 1:3) + expect_equal(sort(unique(-built$y)), 1:2) +}) + +test_that("plot_dense_matrix() ignores existing dimnames", { + A <- matrix(1:4, 2, dimnames = list(c("a", "b"), c("c", "d"))) + p <- plot_dense_matrix(A) + expect_equal(p$data$value, c(1, 2, 3, 4)) + expect_type(p$data$row, "double") + expect_type(p$data$col, "double") +}) + +test_that("plot_expectation() plots expectation() for every kind of model", { + set.seed(90) + models <- list( + undirected = sbm(n = 6, B = matrix(c(0.5, 0.1, 0.1, 0.3), 2)), + directed_square = directed_erdos_renyi(n = 5, p = 0.2), + directed_rectangular = directed_factor_model( + matrix(rexp(8), 4), + matrix(runif(4), 2), + matrix(rexp(14), 7) + ) + ) + + for (name in names(models)) { + model <- models[[name]] + P <- dense_expectation(model) + p <- plot_expectation(model) + expect_s3_class(p, "ggplot") + expect_equal(nrow(p$data), length(P), label = name) + expect_equal(p$data$value, P[cbind(p$data$row, p$data$col)], label = name) + expect_no_error(ggplot2::ggplot_build(p)) + } +}) + +test_that("plot_sparse_matrix() draws one tile per nonzero entry", { + set.seed(91) + undirected <- sample_sparse(sbm(n = 12, B = matrix(c(0.6, 0.1, 0.1, 0.4), 2))) + directed <- sample_sparse( + directed_factor_model(matrix(rexp(4), 4), matrix(2), matrix(rexp(7), 7)) + ) + + for (A in list(undirected, directed)) { + p <- plot_sparse_matrix(A) + expect_s3_class(p, "ggplot") + + general <- as(as(A, "generalMatrix"), "TsparseMatrix") + nonzero <- general@x != 0 + built <- ggplot2::layer_data(p) + expect_equal(nrow(built), sum(nonzero)) + expect_setequal(as.numeric(as.character(p$data$x)), unique(general@x[nonzero])) + } + + expect_error(plot_sparse_matrix(matrix(1, 2, 2))) +}) diff --git a/tests/testthat/test-print-methods.R b/tests/testthat/test-print-methods.R new file mode 100644 index 0000000..9a237ca --- /dev/null +++ b/tests/testthat/test-print-methods.R @@ -0,0 +1,200 @@ +# every print method runs and reports values that agree with the model + +expect_prints_undirected_summary <- function(m) { + out <- paste(capture.output(print(m)), collapse = "\n") + + expect_match(out, paste0("Nodes \\(n\\): ", m$n), label = class(m)[1]) + expect_match(out, paste0("Expected edges: ", round(expected_edges(m))), fixed = TRUE) + expect_match( + out, + paste0("Expected degree: ", round(expected_degree(m), 1)), + fixed = TRUE + ) + expect_match( + out, + paste0("Expected density: ", round(expected_density(m), 5)), + fixed = TRUE + ) + expect_match(out, paste0("Poisson edges: ", m$poisson_edges), fixed = TRUE) + expect_match(out, paste0("Allow self loops: ", m$allow_self_loops), fixed = TRUE) + expect_match(out, paste0("X: ", m$n, " x ", ncol(m$X)), fixed = TRUE) + expect_match(out, paste0("S: ", m$k, " x ", m$k), fixed = TRUE) + + invisible(out) +} + +expect_prints_directed_summary <- function(m) { + out <- paste(capture.output(print(m)), collapse = "\n") + + expect_match(out, paste0("Expected edges: ", round(expected_edges(m))), fixed = TRUE) + expect_match( + out, + paste0("Expected in degree: ", round(expected_in_degree(m), 1)), + fixed = TRUE + ) + expect_match( + out, + paste0("Expected out degree: ", round(expected_out_degree(m), 1)), + fixed = TRUE + ) + expect_match( + out, + paste0("Expected density: ", round(expected_density(m), 5)), + fixed = TRUE + ) + expect_match(out, paste0("X: ", m$n, " x ", m$k1), fixed = TRUE) + expect_match(out, paste0("S: ", m$k1, " x ", m$k2), fixed = TRUE) + expect_match(out, paste0("Y: ", m$d, " x ", m$k2), fixed = TRUE) + expect_match(out, paste0("Poisson edges: ", m$poisson_edges), fixed = TRUE) + expect_match(out, paste0("Allow self loops: ", m$allow_self_loops), fixed = TRUE) + + invisible(out) +} + +test_that("print.undirected_factor_model() reports the model", { + set.seed(1) + m <- undirected_factor_model( + matrix(rexp(40), 20), + diag(2) * 0.3 + 0.1, + poisson_edges = FALSE, + allow_self_loops = FALSE + ) + out <- expect_prints_undirected_summary(m) + expect_match(out, "Undirected Factor Model") + expect_match(out, "Rank (k): 2", fixed = TRUE) + + # erdos_renyi() uses the generic undirected print method + out <- expect_prints_undirected_summary(erdos_renyi(n = 30, p = 0.2)) + expect_match(out, "Undirected Factor Model") +}) + +test_that("print.directed_factor_model() reports the model", { + set.seed(2) + m <- directed_factor_model( + X = matrix(rexp(30), 15), + S = matrix(runif(6), 2, 3), + Y = matrix(rexp(24), 8), + expected_density = 0.1 + ) + out <- expect_prints_directed_summary(m) + expect_match(out, "Directed Factor Model") + expect_match(out, "(n): 15", fixed = TRUE) + expect_match(out, "(d): 8", fixed = TRUE) + expect_match(out, "(k1): 2", fixed = TRUE) + expect_match(out, "(k2): 3", fixed = TRUE) + + out <- expect_prints_directed_summary(directed_erdos_renyi(n = 12, p = 0.3)) + expect_match(out, "Directed Factor Model") +}) + +test_that("print.undirected_dcsbm() reports sorting and parameters", { + for (sort_nodes in c(TRUE, FALSE)) { + set.seed(3) + m <- dcsbm(theta = rexp(25) + 0.5, B = diag(3) * 0.4 + 0.05, sort_nodes = sort_nodes) + out <- expect_prints_undirected_summary(m) + expect_match(out, "Undirected Degree-Corrected Stochastic Blockmodel") + expect_match(out, "Blocks (k): 3", fixed = TRUE) + expect_match(out, "Block memberships (z): 25 [factor]", fixed = TRUE) + expect_match(out, "Degree heterogeneity (theta): 25 [numeric]", fixed = TRUE) + expect_match(out, "Block probabilities (pi): 3 [numeric]", fixed = TRUE) + + sorted <- if (sort_nodes) "(arranged by block)" else "(not arranged by block)" + expect_match(out, paste("Nodes (n): 25", sorted), fixed = TRUE) + } +}) + +test_that("print.undirected_sbm() reports sorting and parameters", { + for (sort_nodes in c(TRUE, FALSE)) { + set.seed(4) + m <- sbm(n = 20, B = diag(2) * 0.4 + 0.05, sort_nodes = sort_nodes) + out <- expect_prints_undirected_summary(m) + expect_match(out, "Undirected Stochastic Blockmodel") + expect_match(out, "Blocks (k): 2", fixed = TRUE) + expect_match(out, "Block memberships (z): 20 [factor]", fixed = TRUE) + + sorted <- if (sort_nodes) "(arranged by block)" else "(not arranged by block)" + expect_match(out, paste("Nodes (n): 20", sorted), fixed = TRUE) + } +}) + +test_that("print.undirected_mmsbm() reports sorting and parameters", { + for (sort_nodes in c(TRUE, FALSE)) { + set.seed(5) + m <- mmsbm( + theta = rexp(20) + 0.5, + B = diag(3) * 0.4 + 0.05, + alpha = c(1, 2, 3), + sort_nodes = sort_nodes + ) + out <- expect_prints_undirected_summary(m) + expect_match(out, "Mixed Membership Stochastic Blockmodel") + expect_match(out, "Blocks (k): 3", fixed = TRUE) + expect_match(out, "(Z): 20 x 3", fixed = TRUE) + expect_match(out, "Degree heterogeneity (theta): 20 [numeric]", fixed = TRUE) + expect_match(out, "Block propensities (alpha): 3 [numeric]", fixed = TRUE) + + sorted <- if (sort_nodes) "(arranged by block)" else "(not arranged by block)" + expect_match(out, paste("Nodes (n): 20", sorted), fixed = TRUE) + } +}) + +test_that("print.undirected_chung_lu() runs and reports the model", { + # chung_lu() objects currently dispatch to print.undirected_dcsbm(), so + # call the Chung-Lu method directly to check that it works + set.seed(6) + m <- chung_lu(theta = rexp(15) + 0.5) + expect_prints_undirected_summary(m) + + out <- paste(capture.output(print.undirected_chung_lu(m)), collapse = "\n") + expect_match(out, "Undirected Chung-Lu Graph") + expect_match(out, "Nodes (n): 15 (arranged by block)", fixed = TRUE) + expect_match(out, "Degree heterogeneity (theta): 15 [numeric]", fixed = TRUE) + expect_match(out, paste0("Expected edges: ", round(expected_edges(m))), fixed = TRUE) + expect_match( + out, + paste0("Expected density: ", round(expected_density(m), 5)), + fixed = TRUE + ) +}) + +test_that("print methods of the remaining models report the right values", { + set.seed(7) + expect_prints_undirected_summary( + planted_partition(n = 20, k = 2, within_block = 0.3, between_block = 0.05) + ) + expect_prints_undirected_summary( + overlapping_sbm(n = 20, B = diag(2) * 0.4 + 0.05, poisson_edges = FALSE) + ) + expect_prints_directed_summary( + directed_dcsbm(theta_out = rexp(20), theta_in = rexp(20), B = matrix(runif(6), 2)) + ) + expect_prints_directed_summary( + directed_planted_partition(n = 20, k = 2, within_block = 0.3, between_block = 0.05) + ) +}) + +test_that("blockmodel print methods report unsorted nodes", { + set.seed(8) + models <- list( + planted_partition(n = 20, k = 2, within_block = 0.3, between_block = 0.05, sort_nodes = FALSE), + directed_dcsbm(theta_out = rexp(20), theta_in = rexp(20), B = diag(2), sort_nodes = FALSE), + directed_planted_partition( + n = 20, + k = 2, + within_block = 0.3, + between_block = 0.05, + sort_nodes = FALSE + ) + ) + + for (m in models) { + expect_output(print(m), "Nodes (n): 20 (not arranged by block)", fixed = TRUE) + } +}) + +test_that("dim_and_class() describes matrices and vectors", { + expect_equal(dim_and_class(matrix(0, 2, 3)), "2 x 3 [matrix]") + expect_equal(dim_and_class(Matrix::Diagonal(2)), "2 x 2 [ddiMatrix]") + expect_equal(dim_and_class(1:4), "4 [integer]") + expect_equal(dim_and_class(factor(c("a", "b"))), "2 [factor]") +}) diff --git a/tests/testthat/test-sampler-agreement.R b/tests/testthat/test-sampler-agreement.R new file mode 100644 index 0000000..b601e1c --- /dev/null +++ b/tests/testthat/test-sampler-agreement.R @@ -0,0 +1,233 @@ +# sample_edgelist(), sample_sparse(), sample_igraph() and sample_tidygraph() +# describe the same graph for a common seed, and every sampled graph obeys +# the structural constraints of its model + +agreement_models <- function() { + set.seed(40) + n <- 30 + list( + ufm = undirected_factor_model( + matrix(rexp(n * 2), n), + matrix(c(0.2, 0.05, 0.1, 0.3), 2), + expected_degree = 6 + ), + erdos_renyi = erdos_renyi(n = n, p = 0.2), + sbm_k1 = sbm(n = n, B = matrix(0.3)), + dcsbm = dcsbm(theta = rexp(n) + 0.5, B = diag(3) * 0.4 + 0.05, expected_degree = 5), + dcsbm_unsorted = dcsbm( + theta = rexp(n) + 0.5, + B = diag(2) * 0.4 + 0.05, + sort_nodes = FALSE, + expected_degree = 5 + ), + mmsbm = mmsbm(theta = rexp(n) + 0.5, B = diag(2) * 0.4 + 0.05, alpha = c(1, 1)), + overlapping = overlapping_sbm(n = n, B = diag(2) * 0.4 + 0.05), + directed_square = directed_factor_model( + matrix(rexp(n * 2), n), + matrix(runif(6), 2, 3), + matrix(rexp(n * 3), n), + expected_out_degree = 5 + ), + directed_rect_wide = directed_factor_model( + matrix(rexp(n * 2), n), + matrix(runif(4), 2), + matrix(rexp(2 * (n + 7)), n + 7), + expected_out_degree = 5 + ), + directed_rect_tall = directed_factor_model( + matrix(rexp(n), n), + matrix(1), + matrix(rexp(11), 11), + expected_in_degree = 4 + ), + directed_dcsbm = directed_dcsbm( + theta_out = rexp(n), + theta_in = rexp(n), + B = matrix(runif(6), 2), + expected_out_degree = 5 + ), + directed_pp = directed_planted_partition( + n = n, + k = 3, + within_block = 0.4, + between_block = 0.05 + ) + ) +} + +test_that("all samplers agree and respect allow_self_loops / poisson_edges", { + # about 5s + skip_on_cran() + + # flipping poisson_edges on a built model thresholds the same Poisson + # rates, which is enough to check the structural constraints + models <- agreement_models() + + for (name in names(models)) { + for (loops in c(TRUE, FALSE)) { + for (poisson in c(TRUE, FALSE)) { + model <- models[[name]] + model$allow_self_loops <- loops + model$poisson_edges <- poisson + label <- paste(name, "loops", loops, "poisson", poisson) + + directed <- inherits(model, "directed_factor_model") + rectangular <- directed && model$n != model$d + n <- model$n + d <- if (directed) model$d else n + + for (seed in 1:2) { + s <- sample_all(model, seed) + el <- s$el + A <- s$A + ig <- s$ig + tg <- s$tg + + # output types + expect_s3_class(el, "tbl_df") + expect_type(el$from, "integer") + expect_type(el$to, "integer") + expect_equal(dim(A), c(n, d), label = label) + if (directed) { + expect_s4_class(A, "dgCMatrix") + } else { + expect_s4_class(A, "dsCMatrix") + } + expect_s3_class(tg, "tbl_graph") + + # node indices are in range + expect_true(all(el$from >= 1 & el$from <= n), label = label) + expect_true(all(el$to >= 1 & el$to <= d), label = label) + + # the edgelist and the adjacency matrix agree + diag_A <- if (rectangular) 0 else sum(Matrix::diag(A)) + if (directed) { + expect_equal(nrow(el), sum(A), label = label) + } else { + expect_true(all(el$from <= el$to), label = label) + expect_equal(nrow(el), (sum(A) + diag_A) / 2, label = label) + } + + # igraph and tidygraph have every node and every edge + expect_equal(igraph::ecount(ig), nrow(el), label = label) + expect_equal(igraph::ecount(tg), nrow(el), label = label) + expected_vertices <- if (rectangular) n + d else n + expect_equal(igraph::vcount(ig), expected_vertices, label = label) + expect_equal(igraph::vcount(tg), expected_vertices, label = label) + + # degrees agree with A + if (rectangular) { + deg <- igraph::degree(ig) + expect_equal(unname(deg[seq_len(n)]), unname(rowSums(A)), label = label) + expect_equal(unname(deg[n + seq_len(d)]), unname(colSums(A)), label = label) + } else if (directed) { + expect_equal(igraph::is_directed(ig), TRUE) + expect_equal(unname(igraph::degree(ig, mode = "out")), unname(rowSums(A)), label = label) + expect_equal(unname(igraph::degree(ig, mode = "in")), unname(colSums(A)), label = label) + } else { + expect_false(igraph::is_directed(ig)) + # igraph counts each self-loop twice towards the degree + expect_equal( + unname(igraph::degree(ig)), + unname(rowSums(A) + Matrix::diag(A)), + label = label + ) + } + + # structural constraints + if (!loops) { + expect_false(any(el$from == el$to), label = label) + if (!rectangular) { + expect_equal(sum(Matrix::diag(A)), 0, label = label) + } + } + + if (!poisson) { + expect_false(anyDuplicated(el[c("from", "to")]) > 0, label = label) + expect_lte(max(c(0, A@x)), 1) + expect_false(any(igraph::which_multiple(ig)), label = label) + } + + # collapsed weights add up to the multigraph edge count + set.seed(seed) + weighted <- sample_edgelist(model, multigraph = FALSE) + expect_equal(sum(weighted$weight), nrow(el), label = label) + expect_false(anyDuplicated(weighted[c("from", "to")]) > 0, label = label) + if (!poisson) { + expect_true(all(weighted$weight == 1), label = label) + } + } + } + } + } +}) + +test_that("sampling is reproducible for a fixed seed", { + models <- agreement_models() + + for (name in names(models)) { + model <- models[[name]] + + set.seed(99) + el1 <- sample_edgelist(model) + set.seed(99) + el2 <- sample_edgelist(model) + expect_identical(el1, el2, label = name) + + set.seed(99) + A1 <- sample_sparse(model) + set.seed(99) + A2 <- sample_sparse(model) + expect_identical(A1, A2, label = name) + } +}) + +test_that("constructors are reproducible for a fixed seed", { + builders <- list( + dcsbm = function() dcsbm(n = 20, k = 3), + sbm = function() sbm(n = 20, k = 2), + chung_lu = function() chung_lu(n = 20), + mmsbm = function() mmsbm(n = 20, k = 3), + overlapping = function() overlapping_sbm(n = 20, k = 3), + directed = function() directed_dcsbm(n = 20, k_out = 2, k_in = 3), + directed_pp = function() { + directed_planted_partition(n = 20, k = 2, a = 4, b = 1, pi = c(0.3, 0.7)) + } + ) + + for (name in names(builders)) { + set.seed(100) + m1 <- suppressMessages(builders[[name]]()) + set.seed(100) + m2 <- suppressMessages(builders[[name]]()) + expect_identical(m1, m2, label = name) + } +}) + +test_that("sorting nodes only relabels the nodes of an sbm", { + # with theta = 1, the sorted and unsorted models from the same seed have + # the same blocks, so their expectations agree up to a permutation + B <- matrix(c(0.5, 0.1, 0.05, 0.1, 0.4, 0.2, 0.05, 0.2, 0.3), 3) + + for (args in list(list(pi = c(0.5, 0.2, 0.3)), list(block_sizes = c(9, 4, 7)))) { + set.seed(41) + sorted <- do.call(sbm, c(list(n = 20, B = B, sort_nodes = TRUE), args)) + set.seed(41) + unsorted <- do.call(sbm, c(list(n = 20, B = B, sort_nodes = FALSE), args)) + + P_sorted <- dense_expectation(sorted) + P_unsorted <- dense_expectation(unsorted) + + # match blocks by their within-block rate, which is distinct per block + block_rate_sorted <- diag(as.matrix(sorted$S))[as.integer(sorted$z)] + block_rate_unsorted <- diag(as.matrix(unsorted$S))[as.integer(unsorted$z)] + expect_equal(sort(block_rate_sorted), sort(block_rate_unsorted)) + + perm <- order(-block_rate_unsorted) + perm_sorted <- order(-block_rate_sorted) + expect_equal( + unname(P_sorted[perm_sorted, perm_sorted]), + unname(P_unsorted[perm, perm]) + ) + } +}) diff --git a/tests/testthat/test-scaling-targets.R b/tests/testthat/test-scaling-targets.R new file mode 100644 index 0000000..910289c --- /dev/null +++ b/tests/testthat/test-scaling-targets.R @@ -0,0 +1,211 @@ +# expected_degree / expected_density / expected_in_degree / +# expected_out_degree rescale S to hit their target exactly, for every +# constructor, and invalid targets are rejected + +undirected_builders <- function(n, ...) { + theta <- seq(0.5, 2, length.out = n) + list( + undirected_factor_model = function(...) { + undirected_factor_model(cbind(theta, rev(theta)), matrix(c(0.3, 0.1, 0.2, 0.4), 2), ...) + }, + erdos_renyi = function(...) erdos_renyi(n = n, ...), + sbm = function(...) sbm(n = n, B = diag(3) * 0.3 + 0.1, ...), + dcsbm = function(...) dcsbm(theta = theta, B = diag(3) * 0.3 + 0.1, ...), + planted_partition = function(...) { + planted_partition(n = n, k = 3, within_block = 0.3, between_block = 0.1, ...) + }, + chung_lu = function(...) chung_lu(theta = theta, ...), + mmsbm = function(...) mmsbm(theta = theta, B = diag(3) * 0.3 + 0.1, alpha = rep(1, 3), ...), + overlapping_sbm = function(...) overlapping_sbm(n = n, B = diag(3) * 0.3 + 0.1, ...) + ) +} + +test_that("expected_degree and expected_density hit their targets for undirected models", { + n <- 40 + builders <- undirected_builders(n) + + for (name in names(builders)) { + for (loops in c(TRUE, FALSE)) { + set.seed(80) + m <- builders[[name]](expected_degree = 3.5, allow_self_loops = loops) + expect_equal(expected_degree(m), 3.5, label = name) + expect_equal(mean(expected_degrees(m)), 3.5, label = name) + expect_identical(m$allow_self_loops, loops) + + set.seed(80) + m <- builders[[name]](expected_density = 0.07, allow_self_loops = loops) + expect_equal(expected_density(m), 0.07, label = name) + } + } +}) + +test_that("scaling Bernoulli blockmodels hits the target on the probability scale", { + # for blockmodels with theta = 1, the Bernoulli edge probabilities are + # 1 - exp(-S), and these are what expected_degree / expected_density + # rescale + n <- 30 + + for (scaling in list(list(expected_degree = 4), list(expected_density = 0.1))) { + builders <- list( + sbm = function(...) sbm(n = n, B = diag(3) * 0.3 + 0.1, block_sizes = c(5, 10, 15), ...), + planted_partition = function(...) { + planted_partition(n = n, k = 3, within_block = 0.3, between_block = 0.1, ...) + }, + erdos_renyi = function(...) erdos_renyi(n = n, ...) + ) + + for (name in names(builders)) { + set.seed(81) + m <- do.call(builders[[name]], c(scaling, poisson_edges = FALSE)) + X <- as.matrix(m$X) + P_bernoulli <- X %*% (1 - exp(-as.matrix(m$S))) %*% t(X) + + if (!is.null(scaling$expected_degree)) { + expect_equal(mean(rowSums(P_bernoulli)), 4, label = name) + } else { + off <- P_bernoulli[row(P_bernoulli) != col(P_bernoulli)] + expect_equal(mean(off), 0.1, label = name) + } + + # the Poisson-scale summaries overestimate slightly, as documented + if (!is.null(scaling$expected_degree)) { + expect_gt(expected_degree(m), 4) + } else { + expect_gt(expected_density(m), 0.1) + } + } + } +}) + +test_that("directed scaling hits its target for every constructor, square or not", { + set.seed(82) + n <- 30 + d <- 45 + + builders <- list( + factor_model_square = function(...) { + directed_factor_model(matrix(rexp(n * 2), n), matrix(runif(6), 2, 3), matrix(rexp(n * 3), n), ...) + }, + factor_model_rectangular = function(...) { + directed_factor_model(matrix(rexp(n * 2), n), matrix(runif(6), 2, 3), matrix(rexp(d * 3), d), ...) + }, + erdos_renyi = function(...) directed_erdos_renyi(n = n, ...), + directed_dcsbm = function(...) { + directed_dcsbm(theta_out = rexp(n), theta_in = rexp(n), B = matrix(runif(6), 2), ...) + }, + directed_dcsbm_shared = function(...) { + directed_dcsbm( + theta_out = rexp(n), + B = matrix(runif(4), 2), + shared_blocks = TRUE, + shared_theta = TRUE, + ... + ) + }, + directed_pp = function(...) { + directed_planted_partition(n = n, k = 3, within_block = 0.4, between_block = 0.1, ...) + } + ) + + for (name in names(builders)) { + m <- builders[[name]](expected_in_degree = 2.5) + expect_equal(expected_in_degree(m), 2.5, label = name) + P <- dense_expectation(m) + expect_equal(mean(colSums(P)), 2.5, label = name) + + m <- builders[[name]](expected_out_degree = 3.5) + expect_equal(expected_out_degree(m), 3.5, label = name) + P <- dense_expectation(m) + expect_equal(mean(rowSums(P)), 3.5, label = name) + + m <- builders[[name]](expected_density = 0.06) + expect_equal(expected_density(m), 0.06, label = name) + P <- dense_expectation(m) + expect_equal(mean(P), 0.06, label = name) + + # in and out degree are tied together by the number of rows and columns + expect_equal( + expected_in_degree(m) * m$d, + expected_out_degree(m) * m$n, + label = name + ) + } +}) + +test_that("undirected_factor_model() rejects invalid scaling targets", { + X <- matrix(1, 5, 1) + S <- matrix(0.5) + + expect_error( + undirected_factor_model(X, S, expected_degree = 1, expected_density = 0.1), + "Cannot specify both" + ) + expect_error(undirected_factor_model(X, S, expected_degree = 0), "strictly greater than zero") + expect_error(undirected_factor_model(X, S, expected_degree = -1), "strictly greater than zero") + expect_error(undirected_factor_model(X, S, expected_density = 0), "strictly between zero and one") + expect_error(undirected_factor_model(X, S, expected_density = 1), "strictly between zero and one") + expect_error( + undirected_factor_model(X, S, expected_degree = 10, poisson_edges = FALSE), + "must not exceed 1 for Bernoulli graphs" + ) + expect_error(undirected_factor_model(-X, S), "non-negative") + expect_error(undirected_factor_model(X, -S), "non-negative") + expect_error(undirected_factor_model(matrix(1, 5, 2), S), "number of columns of `X`") + expect_error( + undirected_factor_model(X, S, allow_self_loops = "yes"), + "`allow_self_loops` must be a logical" + ) +}) + +test_that("directed_factor_model() rejects invalid scaling targets", { + X <- matrix(1, 5, 1) + S <- matrix(0.5) + Y <- matrix(1, 4, 1) + + expect_error( + directed_factor_model(X, S, Y, expected_in_degree = 1, expected_out_degree = 1), + "Must specify only one" + ) + expect_error( + directed_factor_model(X, S, Y, expected_in_degree = 1, expected_density = 0.1), + "Must specify only one" + ) + expect_error(directed_factor_model(X, S, Y, expected_in_degree = 0), "strictly greater than zero") + expect_error(directed_factor_model(X, S, Y, expected_out_degree = 0), "strictly greater than zero") + expect_error(directed_factor_model(X, S, Y, expected_density = 0), "strictly between zero and one") + expect_error(directed_factor_model(X, S, Y, expected_density = 1), "strictly between zero and one") + expect_error( + directed_factor_model(X, S, Y, expected_out_degree = 5, poisson_edges = FALSE), + "must not exceed 1 for Bernoulli graphs" + ) + expect_error(directed_factor_model(-X, S, Y), "non-negative") + expect_error(directed_factor_model(X, S, -Y), "non-negative") + expect_error(directed_factor_model(matrix(1, 5, 2), S, Y), "`k1` must equal") + expect_error(directed_factor_model(X, S, matrix(1, 4, 2)), "`k2` must equal") + expect_error( + directed_factor_model(X, S, Y, allow_self_loops = "yes"), + "`allow_self_loops` must be a logical" + ) +}) + +test_that("erdos_renyi() models have the requested edge probability", { + for (poisson in c(TRUE, FALSE)) { + m <- erdos_renyi(n = 25, p = 0.3, poisson_edges = poisson) + expect_s3_class(m, "undirected_erdos_renyi") + expect_equal(m$p, 0.3) + S <- as.matrix(m$S) + expect_equal(if (poisson) S else 1 - exp(-S), matrix(0.3)) + expect_equal(dim(m$X), c(25, 1)) + + dm <- directed_erdos_renyi(n = 25, p = 0.3, poisson_edges = poisson) + expect_s3_class(dm, "directed_erdos_renyi") + expect_equal(dm$p, 0.3) + S <- as.matrix(dm$S) + expect_equal(if (poisson) S else 1 - exp(-S), matrix(0.3)) + expect_equal(c(dm$n, dm$d), c(25, 25)) + } + + expect_error(erdos_renyi(n = 10, p = 0), "strictly between zero and one") + expect_error(erdos_renyi(n = 10, p = 1), "strictly between zero and one") + expect_error(directed_erdos_renyi(n = 10, p = -0.1), "non-negative") +}) diff --git a/tests/testthat/test-spectra-and-matrix-classes.R b/tests/testthat/test-spectra-and-matrix-classes.R new file mode 100644 index 0000000..f18f7e9 --- /dev/null +++ b/tests/testthat/test-spectra-and-matrix-classes.R @@ -0,0 +1,201 @@ +# eigs_sym() and svds() methods agree with dense decompositions of +# expectation(), and models built from base matrices and from the various +# Matrix classes are the same model + +projection <- function(U) U %*% solve(crossprod(U), t(U)) + +test_that("eigs_sym() matches eigen() of the expectation", { + set.seed(60) + n <- 30 + + models <- list( + ufm = undirected_factor_model( + matrix(rexp(n * 3), n), + matrix(c(0.5, 0.1, 0.2, 0.1, 0.3, 0.05, 0.2, 0.05, 0.4), 3) + ), + # a mixing matrix with a negative eigenvalue + indefinite_sbm = sbm(n = n, B = matrix(c(0.1, 0.5, 0.5, 0.1), 2), block_sizes = c(12, 18)), + dcsbm = dcsbm(theta = rexp(n) + 0.5, B = diag(3) * 0.5 + c(0.1, 0.2, 0.3)), + mmsbm = mmsbm(theta = rexp(n) + 0.5, B = diag(3) * 0.5 + 0.1, alpha = rep(1, 3)), + overlapping = overlapping_sbm(n = n, B = diag(3) * 0.5 + 0.1) + ) + + for (name in names(models)) { + model <- models[[name]] + k <- model$k + dense <- eigen(dense_expectation(model), symmetric = TRUE) + top <- order(abs(dense$values), decreasing = TRUE)[seq_len(k)] + + eig <- eigs_sym(model) + expect_length(eig$values, k) + + expect_equal( + sort(eig$values), + sort(dense$values[top]), + tolerance = 1e-8, + label = name + ) + expect_equal( + projection(eig$vectors), + projection(dense$vectors[, top, drop = FALSE]), + tolerance = 1e-6, + label = name + ) + + # fewer eigenpairs than the rank + eig1 <- eigs_sym(model, k = 1) + expect_equal(abs(eig1$values), max(abs(dense$values)), tolerance = 1e-8, label = name) + } +}) + +test_that("svds() matches svd() of the expectation for undirected models", { + set.seed(61) + n <- 30 + model <- undirected_factor_model( + matrix(rexp(n * 3), n), + matrix(c(0.1, 0.5, 0.2, 0.5, 0.1, 0.05, 0.2, 0.05, 0.4), 3) + ) + + dense <- svd(dense_expectation(model)) + s <- svds(model) + + expect_equal(s$d, dense$d[1:3], tolerance = 1e-8) + expect_equal(projection(s$u), projection(dense$u[, 1:3]), tolerance = 1e-6) + expect_equal(projection(s$v), projection(dense$v[, 1:3]), tolerance = 1e-6) + + s2 <- svds(model, k = 2, nu = 0, nv = 2) + expect_equal(s2$d, dense$d[1:2], tolerance = 1e-8) + expect_equal(ncol(s2$v), 2) +}) + +test_that("svds() matches svd() of the expectation for directed models", { + set.seed(62) + + for (d in c(30, 45)) { + model <- directed_factor_model( + X = matrix(rexp(30 * 3), 30), + S = matrix(runif(6), 3, 2), + Y = matrix(rexp(d * 2), d) + ) + P <- dense_expectation(model) + expect_equal(dim(P), c(30, d)) + + dense <- svd(P) + s <- svds(model) + + # the default k is the smaller rank + expect_length(s$d, 2) + expect_equal(s$d, dense$d[1:2], tolerance = 1e-8, label = paste("d", d)) + expect_equal(projection(s$u), projection(dense$u[, 1:2]), tolerance = 1e-6) + expect_equal(projection(s$v), projection(dense$v[, 1:2]), tolerance = 1e-6) + + s1 <- svds(model, k = 1) + expect_equal(s1$d, dense$d[1], tolerance = 1e-8) + } +}) + +test_that("directed_dcsbm() spectra match its expectation", { + set.seed(63) + model <- directed_dcsbm( + theta_out = rexp(30) + 0.5, + theta_in = rexp(30) + 0.5, + B = matrix(c(0.6, 0.1, 0.2, 0.1, 0.5, 0.3), 2) + ) + dense <- svd(dense_expectation(model)) + expect_equal(svds(model)$d, dense$d[1:2], tolerance = 1e-8) +}) + +test_that("Matrix inputs give the same model as base matrix inputs", { + set.seed(64) + n <- 20 + X <- matrix(rexp(n * 2), n) + X[sample(length(X), 15)] <- 0 + S <- matrix(c(0.4, 0.1, 0.1, 0.3), 2) + + reference <- undirected_factor_model(X, S, expected_degree = 3) + + Xs <- list( + dgeMatrix = Matrix::Matrix(X, sparse = FALSE), + dgCMatrix = Matrix::Matrix(X, sparse = TRUE) + ) + Ss <- list( + dgeMatrix = Matrix::Matrix(S, sparse = FALSE), + dsyMatrix = Matrix::forceSymmetric(Matrix::Matrix(S, sparse = FALSE)), + dgCMatrix = methods::as(Matrix::Matrix(S, sparse = TRUE), "generalMatrix") + ) + + for (x_name in names(Xs)) { + for (s_name in names(Ss)) { + label <- paste(x_name, s_name) + m <- undirected_factor_model(Xs[[x_name]], Ss[[s_name]], expected_degree = 3) + + expect_equal(unname(as.matrix(m$S)), unname(as.matrix(reference$S)), label = label) + expect_equal(expected_edges(m), expected_edges(reference), label = label) + expect_equal(expected_degrees(m), expected_degrees(reference), label = label) + expect_equal(expected_density(m), expected_density(reference), label = label) + expect_equal( + unname(dense_expectation(m)), + unname(dense_expectation(reference)), + label = label + ) + + # and the same seed gives the same graph + set.seed(1) + A <- sample_sparse(m) + set.seed(1) + A_ref <- sample_sparse(reference) + expect_equal(A, A_ref, label = label) + } + } +}) + +test_that("diagonal Matrix mixing matrices work in every constructor", { + D <- Matrix::Diagonal(2, c(0.4, 0.2)) + B <- as.matrix(D) + + for (poisson in c(TRUE, FALSE)) { + set.seed(65) + m_ddi <- sbm(n = 12, B = D, poisson_edges = poisson) + set.seed(65) + m_base <- sbm(n = 12, B = B, poisson_edges = poisson) + expect_equal(unname(as.matrix(m_ddi$S)), unname(as.matrix(m_base$S))) + expect_identical(m_ddi$z, m_base$z) + + set.seed(66) + d_ddi <- directed_dcsbm(theta_out = rep(1, 12), theta_in = rep(1, 12), B = D, poisson_edges = poisson) + set.seed(66) + d_base <- directed_dcsbm(theta_out = rep(1, 12), theta_in = rep(1, 12), B = B, poisson_edges = poisson) + expect_equal(unname(as.matrix(d_ddi$S)), unname(as.matrix(d_base$S))) + expect_equal(expected_edges(d_ddi), expected_edges(d_base)) + + set.seed(67) + o_ddi <- overlapping_sbm(n = 12, B = D, poisson_edges = poisson) + set.seed(67) + o_base <- overlapping_sbm(n = 12, B = B, poisson_edges = poisson) + expect_equal(unname(as.matrix(o_ddi$S)), unname(as.matrix(o_base$S))) + expect_equal(unname(as.matrix(o_ddi$X)), unname(as.matrix(o_base$X))) + } + + set.seed(68) + m <- mmsbm(theta = rep(1, 12), B = D, alpha = c(1, 1)) + expect_equal(unname(as.matrix(m$S)), B) + + set.seed(69) + el <- sample_edgelist(m) + expect_s3_class(el, "tbl_df") +}) + +test_that("non-symmetric S is symmetrized in undirected models", { + set.seed(70) + X <- matrix(rexp(20), 10) + S <- matrix(c(0.4, 0.3, 0.1, 0.2), 2) + + m <- undirected_factor_model(X, S) + expect_equal(unname(as.matrix(m$S)), (S + t(S)) / 2) + + P <- dense_expectation(m) + expect_equal(P, t(P)) + + m2 <- dcsbm(theta = rep(1, 10), B = S, sort_nodes = FALSE) + expect_true(isSymmetric(unname(as.matrix(m2$S)))) +})