diff --git a/NEWS.md b/NEWS.md index eca5c1d..ba724bf 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,13 @@ # fastRG (development version) +- **Breaking change:** fixed `expected_edges()` and `expected_density()` double counting edges in undirected models. Since 0.4.0 fixed the edge over-sampling in #19, both have been twice the true value, because each undirected edge appears in `A` twice (as `A[i, j]` and `A[j, i]`). As a result, **specifying `expected_density = d` for any undirected model produced graphs with density about `d / 2`**, and print methods reported twice the number of edges actually sampled. + - `expected_edges()` is now the expected number of undirected edges, counting self-loops once: `(sum(P) + trace(P)) / 2` for `P = X S X'`. + - `expected_density()` is now the expected number of edges between distinct nodes divided by `choose(n, 2)`: `(sum(P) - trace(P)) / (n (n - 1))`. + - `expected_degree()`, `expected_degrees()`, sampling and population spectra were already correct and are unchanged, as are all directed models. + - Undirected models built with `expected_density` now sample twice as many edges as before, so graphs sampled with a given seed will differ. + +- `erdos_renyi()` and `directed_erdos_renyi()` now error when neither `p` nor a scaling argument such as `expected_degree` or `expected_density` is given. Previously the check never fired, because it looked up the generic functions `expected_degree()` (or `expected_in_degree()` / `expected_out_degree()`) instead of the arguments, and the model silently used `p = 0.5`. + - `sample_edgelist()`, `sample_igraph()` and `sample_tidygraph()` gain a `multigraph` argument. The default, `multigraph = TRUE`, keeps the current behavior: Poisson graphs are returned as multigraphs with repeated edges. With `multigraph = FALSE`, repeated edges are collapsed into a single edge with an integer `weight` attribute (an edgelist column, or an `igraph` edge attribute) that equals the corresponding entry of `sample_sparse()`. In undirected graphs `(i, j)` and `(j, i)` are collapsed together. The `weight` attribute is always present when `multigraph = FALSE`, so Bernoulli graphs (`poisson_edges = FALSE`) get weights of 1 (#30). - Fixed `sample_sparse()`, `sample_igraph()` and `sample_tidygraph()` erroring on directed rectangular models (`n != d`) when no edges are sampled. Empty graphs now have the same output types as non-empty ones: `sample_edgelist()` returns a tibble with integer `from` and `to` columns instead of a base matrix of doubles, and `sample_sparse()` returns a symmetric `dsCMatrix` for undirected models. diff --git a/R/directed_erdos_renyi.R b/R/directed_erdos_renyi.R index ecd9863..009df77 100644 --- a/R/directed_erdos_renyi.R +++ b/R/directed_erdos_renyi.R @@ -44,7 +44,8 @@ validate_directed_erdos_renyi <- function(x) { #' @param n Number of nodes in graph. #' #' @param p Probability of an edge between any two nodes. You must specify -#' either `p`, `expected_in_degree`, or `expected_out_degree`. +#' either `p`, `expected_in_degree`, `expected_out_degree` or +#' `expected_density`. #' #' @inheritDotParams directed_factor_model expected_in_degree expected_out_degree #' @inherit directed_factor_model params return @@ -77,12 +78,14 @@ directed_erdos_renyi <- function( X <- Matrix(1, nrow = n, ncol = 1) Y <- Matrix(1, nrow = n, ncol = 1) - if ( - is.null(p) && is.null(expected_in_degree) && is.null(expected_out_degree) - ) { + # the scaling arguments arrive via `...`, so look for them by name (a + # bare `expected_in_degree` would find the generic function) + scaling <- c("expected_in_degree", "expected_out_degree", "expected_density") + + if (is.null(p) && !any(scaling %in% names(list(...)))) { stop( - "Must specify either `p`, `expected_in_degree` or ", - " `expected_out_degree`.", + "Must specify either `p`, `expected_in_degree`, ", + "`expected_out_degree` or `expected_density`.", call. = FALSE ) } diff --git a/R/expected-degrees.R b/R/expected-degrees.R index 031cb3e..61b37a8 100644 --- a/R/expected-degrees.R +++ b/R/expected-degrees.R @@ -5,12 +5,44 @@ #' #' @inherit sample_edgelist references params #' -#' @return Expected edge counts, or graph densities. -#' -#' @details Note that the runtime of the `fastRG` algorithm is proportional to -#' the expected number of edges in the graph. Expected edge count will be -#' an underestimate of expected number of edges for Bernoulli -#' graphs. See the Rohe et al for details. +#' @return Expected edge counts, degrees, or graph densities. +#' +#' @details Write \eqn{P = \mathbb{E}[A \mid X, S] = X S X^T}{P = E[A | X, S] = X S X'} +#' for an undirected factor model, and +#' \eqn{P = X S Y^T}{P = X S Y'} for a directed one. +#' +#' For **undirected** graphs, every edge between distinct nodes `i` and +#' `j` appears twice in the symmetric adjacency matrix `A`, as both +#' `A[i, j]` and `A[j, i]`, while a self-loop appears once, as `A[i, i]`. +#' Accordingly: +#' +#' - `expected_edges()` is the expected number of edges, counting each +#' undirected edge once: \eqn{(\sum_{ij} P_{ij} + \mathrm{tr}(P)) / 2}{(sum(P) + trace(P)) / 2}. +#' This includes expected self-loops, even when +#' `allow_self_loops = FALSE`. +#' - `expected_degree()` is the expected mean degree, i.e. the average +#' row sum of \eqn{P}{P}: \eqn{\sum_{ij} P_{ij} / n}{sum(P) / n}. +#' `expected_degrees()` gives the expected degree of each node. +#' - `expected_density()` is the expected number of edges between +#' distinct nodes, divided by the number of pairs of distinct nodes: +#' \eqn{(\sum_{ij} P_{ij} - \mathrm{tr}(P)) / (n (n - 1))}{(sum(P) - trace(P)) / (n (n - 1))}. +#' This is the average edge probability (or rate) between distinct +#' nodes, and does not depend on self-loops. +#' +#' For **directed** graphs, `expected_edges()` is +#' \eqn{\sum_{ij} P_{ij}}{sum(P)}, `expected_out_degree()` and +#' `expected_in_degree()` divide this by the number of rows and columns +#' of `A`, and `expected_density()` divides it by the number of entries +#' of `A`. +#' +#' These are expectations under Poisson edges. For Bernoulli graphs +#' (`poisson_edges = FALSE`), they are computed from the Poisson +#' parameterization of `S`, and overestimate edge counts slightly when +#' edge probabilities are large. +#' +#' Note that the runtime of the `fastRG` algorithm is proportional to +#' the expected number of edges in the graph. See Rohe et al. (2018) for +#' details. #' #' @export #' @@ -32,7 +64,7 @@ #' A <- sample_sparse(b_model) #' #' # compare -#' mean(rowSums(triu(A))) +#' mean(rowSums(A)) #' #' pop * a + pop * b # analytical average degree #' @@ -86,11 +118,22 @@ expected_edges.directed_factor_model <- function(factor_model, ...) { #' @export expected_edges.undirected_factor_model <- function(factor_model, ...) { - X <- factor_model$X - S <- factor_model$S + # each edge between distinct nodes is counted twice in sum(P), once as + # P[i, j] and once as P[j, i], but self-loops are only counted once (#19) + (expected_sum(factor_model) + expected_trace(factor_model)) / 2 +} - Cx <- Diagonal(n = ncol(X), x = colSums(X)) - sum(Cx %*% S %*% Cx) +# sum of all entries of P = E[A | X, S] = X S X', without forming P +expected_sum <- function(factor_model) { + cx <- colSums(factor_model$X) + as.numeric(crossprod(cx, factor_model$S %*% cx)) +} + +# trace of P = E[A | X, S] = X S X', i.e. the expected number of +# self-loops, without forming P +expected_trace <- function(factor_model) { + X <- factor_model$X + sum((X %*% factor_model$S) * X) } #' @rdname expected_edges @@ -137,12 +180,16 @@ expected_density <- function(factor_model, ...) { #' @export expected_degree.undirected_factor_model <- function(factor_model, ...) { - expected_edges(factor_model) / as.numeric(factor_model$n) + # mean row sum of P, i.e. the mean expected degree + expected_sum(factor_model) / as.numeric(factor_model$n) } #' @export expected_density.undirected_factor_model <- function(factor_model, ...) { - expected_edges(factor_model) / as.numeric(choose(factor_model$n, 2)) + # mean of P[i, j] over pairs of distinct nodes i != j + n <- as.numeric(factor_model$n) + off_diagonal <- expected_sum(factor_model) - expected_trace(factor_model) + off_diagonal / (n * (n - 1)) } #' @export diff --git a/R/undirected_erdos_renyi.R b/R/undirected_erdos_renyi.R index 5049a9b..6b70536 100644 --- a/R/undirected_erdos_renyi.R +++ b/R/undirected_erdos_renyi.R @@ -28,7 +28,7 @@ validate_undirected_erdos_renyi <- function(x) { #' @param n Number of nodes in graph. #' #' @param p Probability of an edge between any two nodes. You must specify -#' either `p` or `expected_degree`. +#' either `p`, `expected_degree` or `expected_density`. #' #' @inheritDotParams undirected_factor_model expected_degree #' @inherit undirected_factor_model params return @@ -64,8 +64,15 @@ erdos_renyi <- function( ) { X <- Matrix(1, nrow = n, ncol = 1) - if (is.null(p) && is.null(expected_degree)) { - stop("Must specify either `p` or `expected_degree`.", call. = FALSE) + # `expected_degree` and `expected_density` arrive via `...`, so look for + # them by name (a bare `expected_degree` would find the generic function) + scaling <- c("expected_degree", "expected_density") + + if (is.null(p) && !any(scaling %in% names(list(...)))) { + stop( + "Must specify either `p`, `expected_degree` or `expected_density`.", + call. = FALSE + ) } if (is.null(p)) { diff --git a/R/undirected_factor_model.R b/R/undirected_factor_model.R index 1452d9f..dea099e 100644 --- a/R/undirected_factor_model.R +++ b/R/undirected_factor_model.R @@ -108,7 +108,9 @@ validate_undirected_factor_model <- function(x) { #' `expected_degree` and `expected_density` at the same time. #' #' @param expected_density If specified, the desired expected density -#' of the graph. Specifying `expected_density` simply rescales `S` +#' of the graph, that is, the expected number of edges between distinct +#' nodes divided by `choose(n, 2)`. See [expected_density()]. +#' Specifying `expected_density` simply rescales `S` #' to achieve this. Defaults to `NULL`. Do not specify both #' `expected_degree` and `expected_density` at the same time. #' diff --git a/man/chung_lu.Rd b/man/chung_lu.Rd index fcff3dd..2916ea0 100644 --- a/man/chung_lu.Rd +++ b/man/chung_lu.Rd @@ -40,7 +40,9 @@ of the graph. Specifying \code{expected_degree} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} \item{\code{expected_density}}{If specified, the desired expected density -of the graph. Specifying \code{expected_density} simply rescales \code{S} +of the graph, that is, the expected number of edges between distinct +nodes divided by \code{choose(n, 2)}. See \code{\link[=expected_density]{expected_density()}}. +Specifying \code{expected_density} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} }} diff --git a/man/dcsbm.Rd b/man/dcsbm.Rd index f2c9a75..141bcd3 100644 --- a/man/dcsbm.Rd +++ b/man/dcsbm.Rd @@ -60,7 +60,9 @@ of the graph. Specifying \code{expected_degree} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} \item{\code{expected_density}}{If specified, the desired expected density -of the graph. Specifying \code{expected_density} simply rescales \code{S} +of the graph, that is, the expected number of edges between distinct +nodes divided by \code{choose(n, 2)}. See \code{\link[=expected_density]{expected_density()}}. +Specifying \code{expected_density} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} }} diff --git a/man/directed_erdos_renyi.Rd b/man/directed_erdos_renyi.Rd index 7e3658d..9cf9941 100644 --- a/man/directed_erdos_renyi.Rd +++ b/man/directed_erdos_renyi.Rd @@ -29,7 +29,8 @@ to achieve this. Defaults to \code{NULL}. Specify only one of }} \item{p}{Probability of an edge between any two nodes. You must specify -either \code{p}, \code{expected_in_degree}, or \code{expected_out_degree}.} +either \code{p}, \code{expected_in_degree}, \code{expected_out_degree} or +\code{expected_density}.} \item{poisson_edges}{Logical indicating whether or not multiple edges are allowed to form between a pair of diff --git a/man/erdos_renyi.Rd b/man/erdos_renyi.Rd index 66e5a45..08d59d3 100644 --- a/man/erdos_renyi.Rd +++ b/man/erdos_renyi.Rd @@ -19,7 +19,7 @@ to achieve this. Defaults to \code{NULL}. Do not specify both }} \item{p}{Probability of an edge between any two nodes. You must specify -either \code{p} or \code{expected_degree}.} +either \code{p}, \code{expected_degree} or \code{expected_density}.} \item{poisson_edges}{Logical indicating whether or not multiple edges are allowed to form between a pair of diff --git a/man/expected_edges.Rd b/man/expected_edges.Rd index 551b5a0..c22af35 100644 --- a/man/expected_edges.Rd +++ b/man/expected_edges.Rd @@ -28,17 +28,50 @@ expected_density(factor_model, ...) \item{...}{Ignored. Do not use.} } \value{ -Expected edge counts, or graph densities. +Expected edge counts, degrees, or graph densities. } \description{ These calculations are conditional on the latent factors \code{X} and \code{Y}. } \details{ +Write \eqn{P = \mathbb{E}[A \mid X, S] = X S X^T}{P = E[A | X, S] = X S X'} +for an undirected factor model, and +\eqn{P = X S Y^T}{P = X S Y'} for a directed one. + +For \strong{undirected} graphs, every edge between distinct nodes \code{i} and +\code{j} appears twice in the symmetric adjacency matrix \code{A}, as both +\code{A[i, j]} and \code{A[j, i]}, while a self-loop appears once, as \code{A[i, i]}. +Accordingly: +\itemize{ +\item \code{expected_edges()} is the expected number of edges, counting each +undirected edge once: \eqn{(\sum_{ij} P_{ij} + \mathrm{tr}(P)) / 2}{(sum(P) + trace(P)) / 2}. +This includes expected self-loops, even when +\code{allow_self_loops = FALSE}. +\item \code{expected_degree()} is the expected mean degree, i.e. the average +row sum of \eqn{P}{P}: \eqn{\sum_{ij} P_{ij} / n}{sum(P) / n}. +\code{expected_degrees()} gives the expected degree of each node. +\item \code{expected_density()} is the expected number of edges between +distinct nodes, divided by the number of pairs of distinct nodes: +\eqn{(\sum_{ij} P_{ij} - \mathrm{tr}(P)) / (n (n - 1))}{(sum(P) - trace(P)) / (n (n - 1))}. +This is the average edge probability (or rate) between distinct +nodes, and does not depend on self-loops. +} + +For \strong{directed} graphs, \code{expected_edges()} is +\eqn{\sum_{ij} P_{ij}}{sum(P)}, \code{expected_out_degree()} and +\code{expected_in_degree()} divide this by the number of rows and columns +of \code{A}, and \code{expected_density()} divides it by the number of entries +of \code{A}. + +These are expectations under Poisson edges. For Bernoulli graphs +(\code{poisson_edges = FALSE}), they are computed from the Poisson +parameterization of \code{S}, and overestimate edge counts slightly when +edge probabilities are large. + Note that the runtime of the \code{fastRG} algorithm is proportional to -the expected number of edges in the graph. Expected edge count will be -an underestimate of expected number of edges for Bernoulli -graphs. See the Rohe et al for details. +the expected number of edges in the graph. See Rohe et al. (2018) for +details. } \examples{ @@ -58,7 +91,7 @@ b_model A <- sample_sparse(b_model) # compare -mean(rowSums(triu(A))) +mean(rowSums(A)) pop * a + pop * b # analytical average degree diff --git a/man/mmsbm.Rd b/man/mmsbm.Rd index 2ba776d..54be6bd 100644 --- a/man/mmsbm.Rd +++ b/man/mmsbm.Rd @@ -59,7 +59,9 @@ of the graph. Specifying \code{expected_degree} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} \item{\code{expected_density}}{If specified, the desired expected density -of the graph. Specifying \code{expected_density} simply rescales \code{S} +of the graph, that is, the expected number of edges between distinct +nodes divided by \code{choose(n, 2)}. See \code{\link[=expected_density]{expected_density()}}. +Specifying \code{expected_density} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} }} diff --git a/man/overlapping_sbm.Rd b/man/overlapping_sbm.Rd index fa99e17..ad41365 100644 --- a/man/overlapping_sbm.Rd +++ b/man/overlapping_sbm.Rd @@ -50,7 +50,9 @@ of the graph. Specifying \code{expected_degree} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} \item{\code{expected_density}}{If specified, the desired expected density -of the graph. Specifying \code{expected_density} simply rescales \code{S} +of the graph, that is, the expected number of edges between distinct +nodes divided by \code{choose(n, 2)}. See \code{\link[=expected_density]{expected_density()}}. +Specifying \code{expected_density} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} }} diff --git a/man/planted_partition.Rd b/man/planted_partition.Rd index 85adaa3..ea63756 100644 --- a/man/planted_partition.Rd +++ b/man/planted_partition.Rd @@ -34,7 +34,9 @@ of the graph. Specifying \code{expected_degree} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} \item{\code{expected_density}}{If specified, the desired expected density -of the graph. Specifying \code{expected_density} simply rescales \code{S} +of the graph, that is, the expected number of edges between distinct +nodes divided by \code{choose(n, 2)}. See \code{\link[=expected_density]{expected_density()}}. +Specifying \code{expected_density} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} }} diff --git a/man/sbm.Rd b/man/sbm.Rd index ccb2947..92e7761 100644 --- a/man/sbm.Rd +++ b/man/sbm.Rd @@ -44,7 +44,9 @@ of the graph. Specifying \code{expected_degree} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} \item{\code{expected_density}}{If specified, the desired expected density -of the graph. Specifying \code{expected_density} simply rescales \code{S} +of the graph, that is, the expected number of edges between distinct +nodes divided by \code{choose(n, 2)}. See \code{\link[=expected_density]{expected_density()}}. +Specifying \code{expected_density} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} }} diff --git a/man/undirected_factor_model.Rd b/man/undirected_factor_model.Rd index 0554ea6..1c89ee0 100644 --- a/man/undirected_factor_model.Rd +++ b/man/undirected_factor_model.Rd @@ -30,7 +30,9 @@ to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} \item{expected_density}{If specified, the desired expected density -of the graph. Specifying \code{expected_density} simply rescales \code{S} +of the graph, that is, the expected number of edges between distinct +nodes divided by \code{choose(n, 2)}. See \code{\link[=expected_density]{expected_density()}}. +Specifying \code{expected_density} simply rescales \code{S} to achieve this. Defaults to \code{NULL}. Do not specify both \code{expected_degree} and \code{expected_density} at the same time.} diff --git a/tests/testthat/test-degree-scaling.R b/tests/testthat/test-degree-scaling.R index 0d8843b..e54d858 100644 --- a/tests/testthat/test-degree-scaling.R +++ b/tests/testthat/test-degree-scaling.R @@ -46,7 +46,15 @@ test_that("undirected expected degree computed consistently", { }) test_that("undirected density computed consistently", { - # see issue 19 + # see issue 19. density is the expected number of edges between + # distinct nodes, divided by choose(n, 2). in a two block SBM with equal + # blocks of size pop, there are 2 * choose(pop, 2) within-block pairs and + # pop^2 between-block pairs, so the analytic density is + # + # (2 * choose(pop, 2) * a + pop^2 * b) / choose(n, 2) + # + # which is approximately (a + b) / 2 for large n. before this fix, this test + # (and expected_density()) used twice that value set.seed(27) @@ -56,40 +64,37 @@ test_that("undirected density computed consistently", { b <- .05 B <- matrix(c(a, b, b, a), nrow = 2) + analytic_density <- (2 * choose(pop, 2) * a + pop^2 * b) / choose(n, 2) + b_model <- sbm( n = n, B = B, poisson_edges = TRUE ) - expect_equal( - expected_density(b_model), # computed - n * (pop * a + pop * b) / choose(n, 2), # expected undirected degree density, possibly being a little sloppy about the diagonal - tolerance = 0.05 - ) + expect_equal(expected_density(b_model), analytic_density) A <- sample_sparse(b_model) + # edges between distinct nodes are the strict upper triangle of A + off_diagonal_edges <- (sum(A) - sum(Matrix::diag(A))) / 2 + expect_equal( - sum(A) / choose(n, 2), # computed - n * (pop * a + pop * b) / choose(n, 2), # expected "undirected edge degree", - tolerance = 0.05 + off_diagonal_edges / choose(n, 2), + analytic_density, + tolerance = 0.02 ) model2 <- sbm(n = n, B = B, expected_density = 0.15) - expect_equal( - expected_density(model2), # computed - n * (pop * a + pop * b) / choose(n, 2), # expected undirected degree density, possibly being a little sloppy about the diagonal - tolerance = 0.02 - ) + expect_equal(expected_density(model2), 0.15) A2 <- sample_sparse(model2) expect_equal( - sum(A2) / choose(n, 2), # computed - 0.15, # expected "undirected edge degree", - tolerance = 0.05 + (sum(A2) - sum(Matrix::diag(A2))) / 2 / choose(n, 2), + 0.15, + tolerance = 0.02 ) }) diff --git a/tests/testthat/test-diagonal-sampling.R b/tests/testthat/test-diagonal-sampling.R index f8778e4..c59edc7 100644 --- a/tests/testthat/test-diagonal-sampling.R +++ b/tests/testthat/test-diagonal-sampling.R @@ -178,8 +178,11 @@ test_that("sampled diagonal matches diag(X S X') for heterogeneous factors", { expect_equal(sum(A_bar[off_diag]) / sum(EA[off_diag]), 1, tolerance = 0.02) # with the diagonal fixed, sampled totals match expected_edges() and - # expected_degree() exactly in expectation (#19) - expect_equal(sum(A_bar) / expected_edges(ufm), 1, tolerance = 0.02) + # expected_degree() exactly in expectation (#19). each undirected edge + # between distinct nodes appears twice in A and each self-loop once, so + # the number of edges is (sum(A) + trace(A)) / 2 + edges_bar <- (sum(A_bar) + sum(diag(A_bar))) / 2 + expect_equal(edges_bar / expected_edges(ufm), 1, tolerance = 0.02) expect_equal(mean(rowSums(A_bar)), expected_degree(ufm), tolerance = 0.02) # average of sampled graphs has the population spectrum, rather than diff --git a/tests/testthat/test-expected-edges-density.R b/tests/testthat/test-expected-edges-density.R new file mode 100644 index 0000000..c95d6a1 --- /dev/null +++ b/tests/testthat/test-expected-edges-density.R @@ -0,0 +1,305 @@ +# Verification of expected_edges(), expected_degree() and expected_density() +# for undirected factor models. +# +# Write P = E[A | X, S] = X S X'. The argument has three steps, each tested +# separately below: +# +# 1. Algebra. The closed forms used by the package equal the definitions +# written as explicit sums over the entries of a dense P: +# +# expected_edges = sum_{i <= j} P[i, j] = (sum(P) + tr(P)) / 2 +# expected_degree = mean_i sum_j P[i, j] = sum(P) / n +# expected_density = mean_{i != j} P[i, j] = (sum(P) - tr(P)) / (n (n - 1)) +# +# 2. Counting. In every sampled undirected graph, each edge between +# distinct nodes appears twice in the symmetric adjacency matrix A and +# each self-loop appears once, so +# +# number of edges = (sum(A) + tr(A)) / 2 +# edges between distinct nodes = (sum(A) - tr(A)) / 2 +# +# This is a deterministic identity, checked on every sample. +# +# 3. Distribution. sample_edgelist() draws m ~ Poisson(sum(X (S / 2) X')) +# and places each edge independently with probability proportional to +# P, so by Poisson splitting each unordered pair {i, j}, i < j, gets an +# independent Poisson(P[i, j] / 2 + P[j, i] / 2) = Poisson(P[i, j]) +# number of edges. Self-loops get Poisson(P[i, i] / 2) from the sampler +# plus Poisson(P[i, i] / 2) from the top-up added in #46, which is +# Poisson(P[i, i]). Hence, for Poisson graphs, *exactly*: +# +# number of edges ~ Poisson(expected_edges) +# edges between distinct nodes ~ Poisson(expected_density * choose(n, 2)) +# +# so totals over many replicates can be tested with exact z-scores, +# rather than ad hoc tolerances. + +dense_reference <- function(model) { + P <- as.matrix(model$X %*% model$S %*% Matrix::t(model$X)) + n <- nrow(P) + off_diagonal <- row(P) != col(P) + + list( + edges = sum(P[upper.tri(P, diag = TRUE)]), + degree = mean(rowSums(P)), + degrees = rowSums(P), + density = mean(P[off_diagonal]), + off_diagonal_edges = sum(P[upper.tri(P)]) + ) +} + +# z-score of an observed total of `reps` independent Poisson(mu) draws +poisson_z <- function(total, mu, reps) { + (total - reps * mu) / sqrt(reps * mu) +} + +reference_models <- function() { + set.seed(27) + n <- 60 + k <- 3 + + X_dense <- matrix(rexp(n * k), nrow = n) + S_asym <- matrix(runif(k * k), nrow = k) + + X_sparse <- Matrix::rsparsematrix(n, k, density = 0.3, rand.x = function(m) runif(m)) + X_sparse[cbind(seq_len(n), rep_len(seq_len(k), n))] <- 1 + + list( + dense_asymmetric_S = undirected_factor_model(X_dense, S_asym), + sparse_X = undirected_factor_model(X_sparse, diag(k) * 0.3 + 0.05), + rank_one = undirected_factor_model(matrix(rexp(n), ncol = 1), matrix(0.2)), + scaled_degree = undirected_factor_model(X_dense, S_asym, expected_degree = 4), + scaled_density = undirected_factor_model(X_dense, S_asym, expected_density = 0.1), + erdos_renyi = erdos_renyi(n = n, p = 0.1), + sbm = sbm(n = n, B = matrix(c(0.3, 0.05, 0.05, 0.2), 2), block_sizes = c(25, 35)), + dcsbm = dcsbm(theta = rexp(n) + 0.5, B = diag(3) * 0.4 + 0.05, pi = c(0.2, 0.3, 0.5)), + planted_partition = planted_partition(n = n, k = 3, within_block = 0.3, between_block = 0.05), + chung_lu = chung_lu(theta = rexp(n) + 1), + mmsbm = suppressMessages(mmsbm(theta = rexp(n) + 0.5, B = diag(3) * 0.4 + 0.05, alpha = rep(1, 3))), + overlapping_sbm = overlapping_sbm(n = n, B = diag(3) * 0.4 + 0.05) + ) +} + +test_that("step 1: closed forms equal explicit sums over a dense P", { + for (name in names(models <- reference_models())) { + model <- models[[name]] + ref <- dense_reference(model) + + expect_equal(expected_edges(model), ref$edges, tolerance = 1e-10, label = name) + expect_equal(expected_degree(model), ref$degree, tolerance = 1e-10, label = name) + expect_equal(expected_degrees(model), unname(ref$degrees), tolerance = 1e-10, label = name) + expect_equal(expected_density(model), ref$density, tolerance = 1e-10, label = name) + + # and the pieces are consistent with each other + n <- model$n + expect_equal( + expected_density(model) * choose(n, 2), + ref$off_diagonal_edges, + tolerance = 1e-10, + label = name + ) + } +}) + +test_that("step 2: every sampled graph satisfies the edge counting identities", { + models <- reference_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) + + for (seed in 1:5) { + # the same seed gives the same graph in all three representations + set.seed(seed) + el <- sample_edgelist(model) + set.seed(seed) + A <- sample_sparse(model) + set.seed(seed) + g <- sample_igraph(model) + + tr <- sum(Matrix::diag(A)) + loops_in_el <- sum(el$from == el$to) + + # one edgelist row per undirected edge, stored with from <= to + expect_true(all(el$from <= el$to), label = label) + + # edges between distinct nodes appear twice in A, loops once + expect_equal(nrow(el), (sum(A) + tr) / 2, label = label) + expect_equal(nrow(el) - loops_in_el, (sum(A) - tr) / 2, label = label) + expect_equal(loops_in_el, tr, label = label) + + # igraph agrees on the number of edges and self-loops + expect_equal(igraph::ecount(g), nrow(el), label = label) + expect_equal(sum(igraph::which_loop(g)), loops_in_el, label = label) + + if (!loops) { + expect_equal(tr, 0, label = label) + } + } + } + } + } +}) + +test_that("step 3: Poisson edge totals are exactly Poisson(expected_edges())", { + # Monte Carlo checks take ~20s in total + skip_on_cran() + + set.seed(27) + reps <- 400 + models <- reference_models() + + for (name in names(models)) { + model <- models[[name]] + mu_edges <- expected_edges(model) + mu_off <- expected_density(model) * choose(model$n, 2) + + counts <- replicate(reps, { + el <- sample_edgelist(model) + c(all = nrow(el), off = sum(el$from != el$to)) + }) + + z_all <- poisson_z(sum(counts["all", ]), mu_edges, reps) + z_off <- poisson_z(sum(counts["off", ]), mu_off, reps) + + # |z| > 4.5 has probability about 7e-6 under the null, per check + expect_lt(abs(z_all), 4.5, label = paste(name, "all edges z")) + expect_lt(abs(z_off), 4.5, label = paste(name, "off-diagonal edges z")) + + # Poisson: variance equals mean. check the dispersion of the total + # edge count too (ratio of sample variance to mean is ~ 1 +/- 0.07) + dispersion <- stats::var(counts["all", ]) / mean(counts["all", ]) + expect_equal(dispersion, 1, tolerance = 0.25, label = paste(name, "dispersion")) + } +}) + +test_that("without self-loops, edges between distinct nodes are still Poisson", { + # Monte Carlo checks take ~20s in total + skip_on_cran() + + set.seed(27) + reps <- 400 + models <- reference_models() + + for (name in c("dense_asymmetric_S", "dcsbm", "chung_lu")) { + model <- models[[name]] + model$allow_self_loops <- FALSE + mu_off <- expected_density(model) * choose(model$n, 2) + + total <- sum(replicate(reps, nrow(sample_edgelist(model)))) + expect_lt(abs(poisson_z(total, mu_off, reps)), 4.5, label = name) + } +}) + +test_that("expected_density = d gives undirected graphs of density d", { + # Monte Carlo checks take ~20s in total + skip_on_cran() + + set.seed(27) + n <- 400 + d <- 0.02 + reps <- 100 + pairs <- choose(n, 2) + + builders <- list( + undirected_factor_model = function() { + undirected_factor_model(matrix(rexp(n * 2), n), diag(2) + 0.1, expected_density = d) + }, + erdos_renyi = function() erdos_renyi(n = n, expected_density = d), + sbm = function() sbm(n = n, B = diag(3) * 0.5 + 0.1, expected_density = d), + dcsbm = function() dcsbm(theta = rexp(n) + 0.5, B = diag(3) * 0.5 + 0.1, expected_density = d), + planted_partition = function() { + planted_partition(n = n, k = 3, within_block = 0.5, between_block = 0.1, expected_density = d) + }, + chung_lu = function() chung_lu(theta = rexp(n) + 1, expected_density = d), + mmsbm = function() { + suppressMessages(mmsbm(theta = rexp(n) + 0.5, B = diag(3) * 0.5 + 0.1, alpha = rep(1, 3), expected_density = d)) + }, + overlapping_sbm = function() overlapping_sbm(n = n, B = diag(3) * 0.5 + 0.1, expected_density = d) + ) + + for (name in names(builders)) { + model <- builders[[name]]() + expect_equal(expected_density(model), d, label = name) + + off <- sum(replicate(reps, { + el <- sample_edgelist(model) + sum(el$from != el$to) + })) + + # exact Poisson test of the realized density against d + expect_lt(abs(poisson_z(off, d * pairs, reps)), 4.5, label = name) + + # and directly, the realized density is d (not d / 2) + expect_equal(off / reps / pairs, d, tolerance = 0.05, label = name) + } +}) + +test_that("Bernoulli SBMs realize the requested density exactly", { + # Monte Carlo checks take ~20s in total + skip_on_cran() + + # for blockmodels, poisson_edges = FALSE gives P(edge {i, j}) = B[z_i, z_j] + # exactly, after rescaling B to the requested density + set.seed(27) + n <- 300 + d <- 0.05 + reps <- 100 + pairs <- choose(n, 2) + + model <- sbm( + n = n, + B = matrix(c(0.6, 0.1, 0.1, 0.4), 2), + block_sizes = c(120, 180), + poisson_edges = FALSE, + allow_self_loops = FALSE, + expected_density = d + ) + + off <- sum(replicate(reps, nrow(sample_edgelist(model)))) + + # a sum of independent Bernoullis has variance at most its mean, so the + # Poisson z-score is conservative here + expect_lt(abs(poisson_z(off, d * pairs, reps)), 4.5) + expect_equal(off / reps / pairs, d, tolerance = 0.03) +}) + +test_that("directed expectations are unchanged and exactly Poisson", { + # Monte Carlo checks take ~20s in total + skip_on_cran() + + set.seed(27) + n <- 50 + d <- 40 + reps <- 400 + + model <- directed_factor_model( + X = matrix(rexp(n * 2), n), + S = matrix(runif(6), 2, 3), + Y = matrix(rexp(d * 3), d), + expected_density = 0.05 + ) + + P <- as.matrix(model$X %*% model$S %*% Matrix::t(model$Y)) + expect_equal(expected_edges(model), sum(P), tolerance = 1e-10) + expect_equal(expected_density(model), mean(P), tolerance = 1e-10) + expect_equal(expected_out_degree(model), mean(rowSums(P)), tolerance = 1e-10) + expect_equal(expected_in_degree(model), mean(colSums(P)), tolerance = 1e-10) + + total <- sum(replicate(reps, nrow(sample_edgelist(model)))) + expect_lt(abs(poisson_z(total, expected_edges(model), reps)), 4.5) +}) + +test_that("erdos_renyi() requires p or a scaling argument", { + expect_error(erdos_renyi(n = 10), "Must specify either") + expect_silent(erdos_renyi(n = 10, expected_degree = 2)) + expect_silent(erdos_renyi(n = 10, expected_density = 0.1)) + + expect_error(directed_erdos_renyi(n = 10), "Must specify either") + expect_silent(directed_erdos_renyi(n = 10, expected_in_degree = 2)) + expect_silent(directed_erdos_renyi(n = 10, expected_density = 0.1)) +})