From 38648f788b5c66242887fcba25804ea3add6c2d3 Mon Sep 17 00:00:00 2001 From: Alex Hayes Date: Tue, 17 Nov 2026 13:51:06 -0800 Subject: [PATCH 1/3] Add multigraph argument to edgelist, igraph and tidygraph samplers multigraph = TRUE (the default) keeps the current behavior of returning Poisson graphs as multigraphs. multigraph = FALSE collapses repeated edges into a single edge with an integer weight equal to the corresponding sample_sparse() entry, on all three igraph code paths. Co-Authored-By: Claude Opus 5.5 --- NAMESPACE | 1 + R/fastRG-package.R | 1 + R/sample_edgelist.R | 59 +++++++++++++++++++++++++++++++---- R/sample_igraph.R | 43 +++++++++++++++++++------ R/sample_tidygraph.R | 25 ++++++++++----- R/utils.R | 33 ++++++++++++++++++++ man/sample_edgelist.Rd | 31 +++++++++++++++--- man/sample_edgelist.matrix.Rd | 24 ++++++++++++-- man/sample_igraph.Rd | 38 ++++++++++++++++++---- man/sample_sparse.Rd | 7 +++++ man/sample_tidygraph.Rd | 38 ++++++++++++++++++---- 11 files changed, 258 insertions(+), 42 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 3169658..4ca3d3c 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -64,6 +64,7 @@ import(ggplot2) importFrom(RSpectra,eigs_sym) importFrom(RSpectra,svds) importFrom(glue,glue) +importFrom(rlang,.data) importFrom(stats,rmultinom) importFrom(stats,rpois) importFrom(tibble,tibble) diff --git a/R/fastRG-package.R b/R/fastRG-package.R index 512e866..812b944 100644 --- a/R/fastRG-package.R +++ b/R/fastRG-package.R @@ -1,6 +1,7 @@ #' @import Matrix #' @importFrom glue glue #' @importFrom tibble tibble +#' @importFrom rlang .data NULL # The following block is used by usethis to automatically manage diff --git a/R/sample_edgelist.R b/R/sample_edgelist.R index dad9827..7815e92 100644 --- a/R/sample_edgelist.R +++ b/R/sample_edgelist.R @@ -12,9 +12,25 @@ #' #' @param ... Ignored. Do not use. #' +#' @param multigraph Logical scalar, only relevant for Poisson graphs +#' (`poisson_edges = TRUE`), where a pair of nodes can be connected by +#' more than one edge. When `TRUE` (the default), such repeated edges are +#' represented as a multigraph, that is, as repeated edges (or repeated +#' rows of an edgelist) without any edge weights. When `FALSE`, repeated +#' edges between the same pair of nodes are collapsed into a single edge +#' with an integer `weight` attribute that counts the number of times +#' the edge was sampled. This weight is the corresponding entry of the +#' adjacency matrix returned by [sample_sparse()]. In undirected graphs, +#' the edges `(i, j)` and `(j, i)` are the same edge and are collapsed +#' together. When `multigraph = FALSE` the `weight` attribute is always +#' present, even for Bernoulli graphs (`poisson_edges = FALSE`), where +#' every weight is `1`. +#' #' @return A single realization of a random Poisson (or Bernoulli) #' Dot Product Graph, represented as a [tibble::tibble()] with two -#' integer columns, `from` and `to`. +#' integer columns, `from` and `to`. When `multigraph = FALSE`, there +#' is an additional integer column `weight` and each `(from, to)` pair +#' appears at most once. #' #' **NOTE**: Indices for isolated nodes will not appear in the edgelist! #' This can lead to issues if you construct network objects from the @@ -92,6 +108,13 @@ #' #' sample_tidygraph(ufm) #' +#' ### weighted graphs instead of multigraphs ------------ +#' +#' # collapse repeated edges into a single edge with an integer weight +#' +#' sample_edgelist(ufm, multigraph = FALSE) +#' sample_igraph(ufm, multigraph = FALSE) +#' #' ##### directed examples ---------------------------- #' #' n2 <- 100 @@ -145,9 +168,11 @@ #' sample_edgelist <- function( factor_model, - ... + ..., + multigraph = TRUE ) { rlang::check_dots_unnamed() + check_multigraph(multigraph) UseMethod("sample_edgelist") } @@ -155,7 +180,8 @@ sample_edgelist <- function( #' @export sample_edgelist.undirected_factor_model <- function( factor_model, - ... + ..., + multigraph = TRUE ) { X <- factor_model$X n <- factor_model$n @@ -191,6 +217,13 @@ sample_edgelist.undirected_factor_model <- function( edgelist <- dplyr::filter(edgelist, to != from) } + # from <= to for every edge here (including the self-loops added above), + # so (i, j) and (j, i) are already the same row and collapsing by + # (from, to) counts undirected edges, matching sample_sparse() + if (!multigraph) { + edgelist <- collapse_multiedges(edgelist) + } + edgelist } @@ -198,7 +231,8 @@ sample_edgelist.undirected_factor_model <- function( #' @export sample_edgelist.directed_factor_model <- function( factor_model, - ... + ..., + multigraph = TRUE ) { X <- factor_model$X S <- factor_model$S @@ -210,7 +244,8 @@ sample_edgelist.directed_factor_model <- function( Y, TRUE, factor_model$poisson_edges, - factor_model$allow_self_loops + factor_model$allow_self_loops, + multigraph = multigraph ) } @@ -256,6 +291,7 @@ sample_edgelist.directed_factor_model <- function( #' #' @param ... Ignored, for generic consistency only. #' +#' @inheritParams sample_edgelist #' @inherit sample_edgelist return details references #' #' @export @@ -285,13 +321,15 @@ sample_edgelist.matrix <- function( directed, poisson_edges, allow_self_loops, - ... + ..., + multigraph = TRUE ) { X <- factor_model stopifnot(is.logical(directed)) stopifnot(is.logical(poisson_edges)) stopifnot(is.logical(allow_self_loops)) + check_multigraph(multigraph) n <- nrow(X) d <- nrow(Y) @@ -311,6 +349,11 @@ sample_edgelist.matrix <- function( if (m == 0) { edge_list <- matrix(0, nrow = 0, ncol = 2) colnames(edge_list) <- c("from", "to") + + if (!multigraph) { + return(collapse_multiedges(edge_list)) + } + return(edge_list) } @@ -431,6 +474,10 @@ sample_edgelist.matrix <- function( edgelist <- dplyr::filter(edgelist, to != from) } + if (!multigraph) { + edgelist <- collapse_multiedges(edgelist) + } + edgelist } diff --git a/R/sample_igraph.R b/R/sample_igraph.R index 18fad06..04e0812 100644 --- a/R/sample_igraph.R +++ b/R/sample_igraph.R @@ -2,9 +2,14 @@ #' #' @inherit sample_edgelist params details references examples description #' -#' @return An [igraph::igraph()] object that is possibly a -#' multigraph (that is, we take there to be multiple edges -#' rather than weighted edges). +#' @return An [igraph::igraph()] object. For Poisson graphs +#' (`poisson_edges = TRUE`) with `multigraph = TRUE` (the default), this +#' is possibly a multigraph (that is, we take there to be multiple edges +#' rather than weighted edges). With `multigraph = FALSE`, repeated edges +#' are instead collapsed into a single edge, and every edge has an integer +#' `weight` attribute equal to the corresponding entry of the +#' [sample_sparse()] adjacency matrix (all weights are `1` when +#' `poisson_edges = FALSE`). #' #' When `factor_model` is **undirected**: #' @@ -26,9 +31,11 @@ #' sample_igraph <- function( factor_model, - ... + ..., + multigraph = TRUE ) { rlang::check_dots_unnamed() + check_multigraph(multigraph) rlang::check_installed("igraph", "to return graphs as `igraph` objects.") @@ -39,9 +46,10 @@ sample_igraph <- function( #' @export sample_igraph.undirected_factor_model <- function( factor_model, - ... + ..., + multigraph = TRUE ) { - edgelist <- sample_edgelist(factor_model, ...) + edgelist <- sample_edgelist(factor_model, ..., multigraph = multigraph) nodes <- tibble(name = 1:nrow(factor_model$X)) igraph::graph_from_data_frame(edgelist, directed = FALSE, vertices = nodes) } @@ -50,10 +58,11 @@ sample_igraph.undirected_factor_model <- function( #' @export sample_igraph.directed_factor_model <- function( factor_model, - ... + ..., + multigraph = TRUE ) { if (factor_model$n == factor_model$d) { - edgelist <- sample_edgelist(factor_model, ...) + edgelist <- sample_edgelist(factor_model, ..., multigraph = multigraph) nodes <- tibble(name = 1:nrow(factor_model$X)) one_mode <- igraph::graph_from_data_frame( edgelist, @@ -67,5 +76,21 @@ sample_igraph.directed_factor_model <- function( # a bipartite graph rather than using the usual one-mode tools A <- sample_sparse(factor_model, ...) - igraph::graph_from_biadjacency_matrix(A, directed = FALSE, multiple = TRUE) + + if (multigraph) { + return( + igraph::graph_from_biadjacency_matrix(A, directed = FALSE, multiple = TRUE) + ) + } + + bipartite <- igraph::graph_from_biadjacency_matrix( + A, + directed = FALSE, + weighted = TRUE + ) + + # entries of A are counts stored as doubles, keep weights integer to match + # sample_edgelist(multigraph = FALSE) + igraph::E(bipartite)$weight <- as.integer(igraph::E(bipartite)$weight) + bipartite } diff --git a/R/sample_tidygraph.R b/R/sample_tidygraph.R index 18174a0..98fdc2b 100644 --- a/R/sample_tidygraph.R +++ b/R/sample_tidygraph.R @@ -2,9 +2,14 @@ #' #' @inherit sample_edgelist params details references examples description #' -#' @return A [tidygraph::tbl_graph()] object that is possibly a -#' multigraph (that is, we take there to be multiple edges -#' rather than weighted edges). +#' @return A [tidygraph::tbl_graph()] object. For Poisson graphs +#' (`poisson_edges = TRUE`) with `multigraph = TRUE` (the default), this +#' is possibly a multigraph (that is, we take there to be multiple edges +#' rather than weighted edges). With `multigraph = FALSE`, repeated edges +#' are instead collapsed into a single edge, and the edge data has an +#' integer `weight` column equal to the corresponding entry of the +#' [sample_sparse()] adjacency matrix (all weights are `1` when +#' `poisson_edges = FALSE`). #' #' When `factor_model` is **undirected**: #' @@ -26,9 +31,11 @@ #' sample_tidygraph <- function( factor_model, - ... + ..., + multigraph = TRUE ) { rlang::check_dots_unnamed() + check_multigraph(multigraph) rlang::check_installed("igraph", "to return graphs as `tidygraph` objects.") UseMethod("sample_tidygraph") @@ -38,9 +45,10 @@ sample_tidygraph <- function( #' @export sample_tidygraph.undirected_factor_model <- function( factor_model, - ... + ..., + multigraph = TRUE ) { - ig <- sample_igraph(factor_model, ...) + ig <- sample_igraph(factor_model, ..., multigraph = multigraph) tidygraph::as_tbl_graph(ig, directed = FALSE) } @@ -48,8 +56,9 @@ sample_tidygraph.undirected_factor_model <- function( #' @export sample_tidygraph.directed_factor_model <- function( factor_model, - ... + ..., + multigraph = TRUE ) { - ig <- sample_igraph(factor_model, ...) + ig <- sample_igraph(factor_model, ..., multigraph = multigraph) tidygraph::as_tbl_graph(ig, directed = TRUE) } diff --git a/R/utils.R b/R/utils.R index ecfe976..b79f802 100644 --- a/R/utils.R +++ b/R/utils.R @@ -27,6 +27,39 @@ l1_normalize_within <- function(x, block) { do.call(c, lapply(split(x, block), l1_normalize)) } +check_multigraph <- function(multigraph, call = rlang::caller_env()) { + if (!rlang::is_bool(multigraph)) { + rlang::abort( + paste0( + "`multigraph` must be a single `TRUE` or `FALSE`, not ", + obj_type(multigraph), + "." + ), + call = call + ) + } + invisible(multigraph) +} + +obj_type <- function(x) { + if (is.null(x)) { + return("`NULL`") + } + if (length(x) != 1) { + return(paste0("a ", class(x)[1], " vector of length ", length(x))) + } + paste0("`", deparse(x), "`") +} + +# collapse repeated (from, to) rows of an edgelist into a single row with +# an integer `weight` column counting the repeats. for undirected +# edgelists, callers must ensure from <= to beforehand so that (i, j) and +# (j, i) are collapsed together +collapse_multiedges <- function(edgelist) { + edgelist <- tibble::as_tibble(edgelist) + dplyr::count(edgelist, .data$from, .data$to, name = "weight") +} + utils::globalVariables( c("i", "j", "value", "x") ) diff --git a/man/sample_edgelist.Rd b/man/sample_edgelist.Rd index 19e79be..78ad733 100644 --- a/man/sample_edgelist.Rd +++ b/man/sample_edgelist.Rd @@ -6,22 +6,38 @@ \alias{sample_edgelist.directed_factor_model} \title{Sample a random edgelist from a random dot product graph} \usage{ -sample_edgelist(factor_model, ...) +sample_edgelist(factor_model, ..., multigraph = TRUE) -\method{sample_edgelist}{undirected_factor_model}(factor_model, ...) +\method{sample_edgelist}{undirected_factor_model}(factor_model, ..., multigraph = TRUE) -\method{sample_edgelist}{directed_factor_model}(factor_model, ...) +\method{sample_edgelist}{directed_factor_model}(factor_model, ..., multigraph = TRUE) } \arguments{ \item{factor_model}{A \code{\link[=directed_factor_model]{directed_factor_model()}} or \code{\link[=undirected_factor_model]{undirected_factor_model()}}.} \item{...}{Ignored. Do not use.} + +\item{multigraph}{Logical scalar, only relevant for Poisson graphs +(\code{poisson_edges = TRUE}), where a pair of nodes can be connected by +more than one edge. When \code{TRUE} (the default), such repeated edges are +represented as a multigraph, that is, as repeated edges (or repeated +rows of an edgelist) without any edge weights. When \code{FALSE}, repeated +edges between the same pair of nodes are collapsed into a single edge +with an integer \code{weight} attribute that counts the number of times +the edge was sampled. This weight is the corresponding entry of the +adjacency matrix returned by \code{\link[=sample_sparse]{sample_sparse()}}. In undirected graphs, +the edges \verb{(i, j)} and \verb{(j, i)} are the same edge and are collapsed +together. When \code{multigraph = FALSE} the \code{weight} attribute is always +present, even for Bernoulli graphs (\code{poisson_edges = FALSE}), where +every weight is \code{1}.} } \value{ A single realization of a random Poisson (or Bernoulli) Dot Product Graph, represented as a \code{\link[tibble:tibble]{tibble::tibble()}} with two -integer columns, \code{from} and \code{to}. +integer columns, \code{from} and \code{to}. When \code{multigraph = FALSE}, there +is an additional integer column \code{weight} and each \verb{(from, to)} pair +appears at most once. \strong{NOTE}: Indices for isolated nodes will not appear in the edgelist! This can lead to issues if you construct network objects from the @@ -100,6 +116,13 @@ sample_igraph(ufm) sample_tidygraph(ufm) +### weighted graphs instead of multigraphs ------------ + +# collapse repeated edges into a single edge with an integer weight + +sample_edgelist(ufm, multigraph = FALSE) +sample_igraph(ufm, multigraph = FALSE) + ##### directed examples ---------------------------- n2 <- 100 diff --git a/man/sample_edgelist.matrix.Rd b/man/sample_edgelist.matrix.Rd index 17511c0..1888717 100644 --- a/man/sample_edgelist.matrix.Rd +++ b/man/sample_edgelist.matrix.Rd @@ -12,7 +12,8 @@ directed, poisson_edges, allow_self_loops, - ... + ..., + multigraph = TRUE ) \method{sample_edgelist}{Matrix}( @@ -22,7 +23,8 @@ directed, poisson_edges, allow_self_loops, - ... + ..., + multigraph = TRUE ) } \arguments{ @@ -56,11 +58,27 @@ Defaults to \code{TRUE}. When \code{FALSE}, sampling proceeds allowing self-loops, and these are then removed after the fact.} \item{...}{Ignored, for generic consistency only.} + +\item{multigraph}{Logical scalar, only relevant for Poisson graphs +(\code{poisson_edges = TRUE}), where a pair of nodes can be connected by +more than one edge. When \code{TRUE} (the default), such repeated edges are +represented as a multigraph, that is, as repeated edges (or repeated +rows of an edgelist) without any edge weights. When \code{FALSE}, repeated +edges between the same pair of nodes are collapsed into a single edge +with an integer \code{weight} attribute that counts the number of times +the edge was sampled. This weight is the corresponding entry of the +adjacency matrix returned by \code{\link[=sample_sparse]{sample_sparse()}}. In undirected graphs, +the edges \verb{(i, j)} and \verb{(j, i)} are the same edge and are collapsed +together. When \code{multigraph = FALSE} the \code{weight} attribute is always +present, even for Bernoulli graphs (\code{poisson_edges = FALSE}), where +every weight is \code{1}.} } \value{ A single realization of a random Poisson (or Bernoulli) Dot Product Graph, represented as a \code{\link[tibble:tibble]{tibble::tibble()}} with two -integer columns, \code{from} and \code{to}. +integer columns, \code{from} and \code{to}. When \code{multigraph = FALSE}, there +is an additional integer column \code{weight} and each \verb{(from, to)} pair +appears at most once. \strong{NOTE}: Indices for isolated nodes will not appear in the edgelist! This can lead to issues if you construct network objects from the diff --git a/man/sample_igraph.Rd b/man/sample_igraph.Rd index 99b7234..7d4ad5e 100644 --- a/man/sample_igraph.Rd +++ b/man/sample_igraph.Rd @@ -6,22 +6,41 @@ \alias{sample_igraph.directed_factor_model} \title{Sample a random dot product graph as an igraph graph} \usage{ -sample_igraph(factor_model, ...) +sample_igraph(factor_model, ..., multigraph = TRUE) -\method{sample_igraph}{undirected_factor_model}(factor_model, ...) +\method{sample_igraph}{undirected_factor_model}(factor_model, ..., multigraph = TRUE) -\method{sample_igraph}{directed_factor_model}(factor_model, ...) +\method{sample_igraph}{directed_factor_model}(factor_model, ..., multigraph = TRUE) } \arguments{ \item{factor_model}{A \code{\link[=directed_factor_model]{directed_factor_model()}} or \code{\link[=undirected_factor_model]{undirected_factor_model()}}.} \item{...}{Ignored. Do not use.} + +\item{multigraph}{Logical scalar, only relevant for Poisson graphs +(\code{poisson_edges = TRUE}), where a pair of nodes can be connected by +more than one edge. When \code{TRUE} (the default), such repeated edges are +represented as a multigraph, that is, as repeated edges (or repeated +rows of an edgelist) without any edge weights. When \code{FALSE}, repeated +edges between the same pair of nodes are collapsed into a single edge +with an integer \code{weight} attribute that counts the number of times +the edge was sampled. This weight is the corresponding entry of the +adjacency matrix returned by \code{\link[=sample_sparse]{sample_sparse()}}. In undirected graphs, +the edges \verb{(i, j)} and \verb{(j, i)} are the same edge and are collapsed +together. When \code{multigraph = FALSE} the \code{weight} attribute is always +present, even for Bernoulli graphs (\code{poisson_edges = FALSE}), where +every weight is \code{1}.} } \value{ -An \code{\link[igraph:aaa-igraph-package]{igraph::igraph()}} object that is possibly a -multigraph (that is, we take there to be multiple edges -rather than weighted edges). +An \code{\link[igraph:aaa-igraph-package]{igraph::igraph()}} object. For Poisson graphs +(\code{poisson_edges = TRUE}) with \code{multigraph = TRUE} (the default), this +is possibly a multigraph (that is, we take there to be multiple edges +rather than weighted edges). With \code{multigraph = FALSE}, repeated edges +are instead collapsed into a single edge, and every edge has an integer +\code{weight} attribute equal to the corresponding entry of the +\code{\link[=sample_sparse]{sample_sparse()}} adjacency matrix (all weights are \code{1} when +\code{poisson_edges = FALSE}). When \code{factor_model} is \strong{undirected}: @@ -106,6 +125,13 @@ sample_igraph(ufm) sample_tidygraph(ufm) +### weighted graphs instead of multigraphs ------------ + +# collapse repeated edges into a single edge with an integer weight + +sample_edgelist(ufm, multigraph = FALSE) +sample_igraph(ufm, multigraph = FALSE) + ##### directed examples ---------------------------- n2 <- 100 diff --git a/man/sample_sparse.Rd b/man/sample_sparse.Rd index 02a4eae..ca76d34 100644 --- a/man/sample_sparse.Rd +++ b/man/sample_sparse.Rd @@ -100,6 +100,13 @@ sample_igraph(ufm) sample_tidygraph(ufm) +### weighted graphs instead of multigraphs ------------ + +# collapse repeated edges into a single edge with an integer weight + +sample_edgelist(ufm, multigraph = FALSE) +sample_igraph(ufm, multigraph = FALSE) + ##### directed examples ---------------------------- n2 <- 100 diff --git a/man/sample_tidygraph.Rd b/man/sample_tidygraph.Rd index 9ae36dc..8ee4806 100644 --- a/man/sample_tidygraph.Rd +++ b/man/sample_tidygraph.Rd @@ -6,22 +6,41 @@ \alias{sample_tidygraph.directed_factor_model} \title{Sample a random dot product graph as a tidygraph graph} \usage{ -sample_tidygraph(factor_model, ...) +sample_tidygraph(factor_model, ..., multigraph = TRUE) -\method{sample_tidygraph}{undirected_factor_model}(factor_model, ...) +\method{sample_tidygraph}{undirected_factor_model}(factor_model, ..., multigraph = TRUE) -\method{sample_tidygraph}{directed_factor_model}(factor_model, ...) +\method{sample_tidygraph}{directed_factor_model}(factor_model, ..., multigraph = TRUE) } \arguments{ \item{factor_model}{A \code{\link[=directed_factor_model]{directed_factor_model()}} or \code{\link[=undirected_factor_model]{undirected_factor_model()}}.} \item{...}{Ignored. Do not use.} + +\item{multigraph}{Logical scalar, only relevant for Poisson graphs +(\code{poisson_edges = TRUE}), where a pair of nodes can be connected by +more than one edge. When \code{TRUE} (the default), such repeated edges are +represented as a multigraph, that is, as repeated edges (or repeated +rows of an edgelist) without any edge weights. When \code{FALSE}, repeated +edges between the same pair of nodes are collapsed into a single edge +with an integer \code{weight} attribute that counts the number of times +the edge was sampled. This weight is the corresponding entry of the +adjacency matrix returned by \code{\link[=sample_sparse]{sample_sparse()}}. In undirected graphs, +the edges \verb{(i, j)} and \verb{(j, i)} are the same edge and are collapsed +together. When \code{multigraph = FALSE} the \code{weight} attribute is always +present, even for Bernoulli graphs (\code{poisson_edges = FALSE}), where +every weight is \code{1}.} } \value{ -A \code{\link[tidygraph:tbl_graph]{tidygraph::tbl_graph()}} object that is possibly a -multigraph (that is, we take there to be multiple edges -rather than weighted edges). +A \code{\link[tidygraph:tbl_graph]{tidygraph::tbl_graph()}} object. For Poisson graphs +(\code{poisson_edges = TRUE}) with \code{multigraph = TRUE} (the default), this +is possibly a multigraph (that is, we take there to be multiple edges +rather than weighted edges). With \code{multigraph = FALSE}, repeated edges +are instead collapsed into a single edge, and the edge data has an +integer \code{weight} column equal to the corresponding entry of the +\code{\link[=sample_sparse]{sample_sparse()}} adjacency matrix (all weights are \code{1} when +\code{poisson_edges = FALSE}). When \code{factor_model} is \strong{undirected}: @@ -106,6 +125,13 @@ sample_igraph(ufm) sample_tidygraph(ufm) +### weighted graphs instead of multigraphs ------------ + +# collapse repeated edges into a single edge with an integer weight + +sample_edgelist(ufm, multigraph = FALSE) +sample_igraph(ufm, multigraph = FALSE) + ##### directed examples ---------------------------- n2 <- 100 From ed46bb829a1d43b4747658ffda97d03c87c77a7f Mon Sep 17 00:00:00 2001 From: Alex Hayes Date: Tue, 17 Nov 2026 13:51:06 -0800 Subject: [PATCH 2/3] Test the multigraph argument Co-Authored-By: Claude Opus 5.5 --- tests/testthat/_snaps/multigraph.md | 8 + tests/testthat/test-multigraph.R | 335 ++++++++++++++++++++++++++++ 2 files changed, 343 insertions(+) create mode 100644 tests/testthat/_snaps/multigraph.md create mode 100644 tests/testthat/test-multigraph.R diff --git a/tests/testthat/_snaps/multigraph.md b/tests/testthat/_snaps/multigraph.md new file mode 100644 index 0000000..6d12448 --- /dev/null +++ b/tests/testthat/_snaps/multigraph.md @@ -0,0 +1,8 @@ +# bad multigraph input gives a clear error + + Code + sample_igraph(fm, multigraph = NA) + Condition + Error in `sample_igraph()`: + ! `multigraph` must be a single `TRUE` or `FALSE`, not `NA`. + diff --git a/tests/testthat/test-multigraph.R b/tests/testthat/test-multigraph.R new file mode 100644 index 0000000..45036aa --- /dev/null +++ b/tests/testthat/test-multigraph.R @@ -0,0 +1,335 @@ +# all samplers consume the RNG identically (sample_sparse(), sample_igraph() +# and sample_tidygraph() all go through sample_edgelist()), so with a common +# seed the collapsed weights must match sample_sparse() entry by entry + +# nonzero entries of a sparse adjacency matrix as a sorted (from, to, weight) +# data frame. for undirected graphs keep only the upper triangle, matching +# the from <= to convention of sample_edgelist() +sparse_triplets <- function(A, undirected) { + A <- as(as(A, "generalMatrix"), "TsparseMatrix") + df <- data.frame(from = A@i + 1L, to = A@j + 1L, weight = A@x) + df <- df[df$weight != 0, ] + if (undirected) { + df <- df[df$from <= df$to, ] + } + sort_triplets(df) +} + +sort_triplets <- function(df) { + df <- as.data.frame(df) + df$from <- as.integer(df$from) + df$to <- as.integer(df$to) + df$weight <- as.integer(df$weight) + df <- df[order(df$from, df$to), c("from", "to", "weight")] + rownames(df) <- NULL + df +} + +# edges of a one-mode igraph as a sorted (from, to, weight) data frame +igraph_triplets <- function(g, undirected) { + df <- igraph::as_data_frame(g, what = "edges") + from <- as.integer(df$from) + to <- as.integer(df$to) + if (undirected) { + df$from <- pmin(from, to) + df$to <- pmax(from, to) + } else { + df$from <- from + df$to <- to + } + sort_triplets(df) +} + +# edges of a bipartite igraph built by graph_from_biadjacency_matrix(), where +# vertices 1..n are rows of A and vertices n + 1, ..., n + d are columns +bipartite_triplets <- function(g, n) { + df <- igraph::as_data_frame(g, what = "edges") + from <- pmin(df$from, df$to) + to <- pmax(df$from, df$to) + df$from <- from + df$to <- to - n + sort_triplets(df) +} + +make_ufm <- function(poisson_edges = TRUE, allow_self_loops = TRUE) { + set.seed(30) + n <- 60 + k <- 3 + X <- matrix(rpois(n = n * k, 1), nrow = n) + S <- matrix(runif(n = k * k, 0, .1), nrow = k) + # dense enough that there are many repeated edges and self-loops + undirected_factor_model( + X, + S, + expected_degree = 20, + poisson_edges = poisson_edges, + allow_self_loops = allow_self_loops + ) +} + +make_fm <- function(d = 60, poisson_edges = TRUE, allow_self_loops = TRUE) { + set.seed(31) + n <- 60 + k1 <- 3 + k2 <- 2 + X <- matrix(rpois(n = n * k1, 1), nrow = n) + S <- matrix(runif(n = k1 * k2, 0, .1), nrow = k1, ncol = k2) + Y <- matrix(rexp(n = k2 * d, 1), nrow = d) + directed_factor_model( + X, + S, + Y, + expected_in_degree = 20, + poisson_edges = poisson_edges, + allow_self_loops = allow_self_loops + ) +} + +test_that("multigraph = TRUE is the default and is unchanged", { + ufm <- make_ufm() + fm_square <- make_fm(d = 60) + fm_rect <- make_fm(d = 40) + + for (model in list(ufm, fm_square, fm_rect)) { + set.seed(1) + el_default <- sample_edgelist(model) + set.seed(1) + el_true <- sample_edgelist(model, multigraph = TRUE) + expect_identical(el_default, el_true) + expect_named(el_default, c("from", "to")) + + # the multigraph really does have repeated edges + expect_true(anyDuplicated(el_default) > 0) + + set.seed(1) + ig_default <- sample_igraph(model) + set.seed(1) + ig_true <- sample_igraph(model, multigraph = TRUE) + expect_true(igraph::identical_graphs(ig_default, ig_true)) + expect_false("weight" %in% igraph::edge_attr_names(ig_default)) + expect_true(any(igraph::which_multiple(ig_default))) + + # one edge per sampled edge + set.seed(1) + A <- sample_sparse(model) + total <- if (inherits(model, "undirected_factor_model")) { + sum(Matrix::triu(A)) + } else { + sum(A) + } + expect_equal(igraph::ecount(ig_default), total) + expect_equal(nrow(el_default), total) + + set.seed(1) + tg_default <- sample_tidygraph(model) + expect_s3_class(tg_default, "tbl_graph") + expect_false("weight" %in% igraph::edge_attr_names(tg_default)) + expect_equal(igraph::ecount(tg_default), total) + } +}) + +test_that("undirected: collapsed weights match sample_sparse()", { + ufm <- make_ufm() + + set.seed(2) + A <- sample_sparse(ufm) + expected <- sparse_triplets(A, undirected = TRUE) + + # make sure the test actually exercises collapsing and self-loops + expect_true(any(expected$weight > 1)) + expect_true(any(expected$from == expected$to)) + + set.seed(2) + el <- sample_edgelist(ufm, multigraph = FALSE) + expect_named(el, c("from", "to", "weight")) + expect_type(el$weight, "integer") + expect_true(all(el$from <= el$to)) + expect_equal(anyDuplicated(el[c("from", "to")]), 0) + expect_equal(sort_triplets(el), expected) + + set.seed(2) + ig <- sample_igraph(ufm, multigraph = FALSE) + expect_false(igraph::is_directed(ig)) + expect_equal(igraph::vcount(ig), ufm$n) + expect_type(igraph::E(ig)$weight, "integer") + expect_false(any(igraph::which_multiple(ig))) + expect_equal(igraph_triplets(ig, undirected = TRUE), expected) + + set.seed(2) + tg <- sample_tidygraph(ufm, multigraph = FALSE) + expect_s3_class(tg, "tbl_graph") + expect_equal(igraph_triplets(tg, undirected = TRUE), expected) + + # total weight equals the number of rows of the multigraph edgelist + set.seed(2) + el_multi <- sample_edgelist(ufm) + expect_equal(sum(el$weight), nrow(el_multi)) +}) + +test_that("undirected: (i, j) and (j, i) are collapsed together", { + ufm <- make_ufm() + + set.seed(3) + el <- sample_edgelist(ufm, multigraph = FALSE) + unordered <- paste(pmin(el$from, el$to), pmax(el$from, el$to)) + expect_equal(anyDuplicated(unordered), 0) +}) + +test_that("undirected without self-loops: weights match sample_sparse()", { + ufm <- make_ufm(allow_self_loops = FALSE) + + set.seed(4) + expected <- sparse_triplets(sample_sparse(ufm), undirected = TRUE) + + set.seed(4) + el <- sample_edgelist(ufm, multigraph = FALSE) + expect_false(any(el$from == el$to)) + expect_equal(sort_triplets(el), expected) + + set.seed(4) + ig <- sample_igraph(ufm, multigraph = FALSE) + expect_equal(igraph_triplets(ig, undirected = TRUE), expected) +}) + +test_that("directed square: collapsed weights match sample_sparse()", { + fm <- make_fm(d = 60) + + set.seed(5) + A <- sample_sparse(fm) + expected <- sparse_triplets(A, undirected = FALSE) + expect_true(any(expected$weight > 1)) + + set.seed(5) + el <- sample_edgelist(fm, multigraph = FALSE) + expect_named(el, c("from", "to", "weight")) + expect_type(el$weight, "integer") + expect_equal(sort_triplets(el), expected) + + # directed edges are not symmetrized: (i, j) and (j, i) stay distinct + expect_true(any(el$from > el$to)) + + set.seed(5) + ig <- sample_igraph(fm, multigraph = FALSE) + expect_true(igraph::is_directed(ig)) + expect_type(igraph::E(ig)$weight, "integer") + expect_equal(igraph_triplets(ig, undirected = FALSE), expected) + + set.seed(5) + tg <- sample_tidygraph(fm, multigraph = FALSE) + expect_s3_class(tg, "tbl_graph") + expect_equal(igraph_triplets(tg, undirected = FALSE), expected) +}) + +test_that("directed rectangular: collapsed weights match sample_sparse()", { + fm <- make_fm(d = 40) + + set.seed(6) + A <- sample_sparse(fm) + expected <- sparse_triplets(A, undirected = FALSE) + expect_true(any(expected$weight > 1)) + + set.seed(6) + el <- sample_edgelist(fm, multigraph = FALSE) + expect_equal(sort_triplets(el), expected) + + set.seed(6) + ig <- sample_igraph(fm, multigraph = FALSE) + expect_true(igraph::is_bipartite(ig)) + expect_equal(igraph::vcount(ig), fm$n + fm$d) + expect_type(igraph::E(ig)$weight, "integer") + expect_false(any(igraph::which_multiple(ig))) + expect_equal(bipartite_triplets(ig, fm$n), expected) + + set.seed(6) + tg <- sample_tidygraph(fm, multigraph = FALSE) + expect_s3_class(tg, "tbl_graph") + expect_equal(bipartite_triplets(tg, fm$n), expected) +}) + +test_that("poisson_edges = FALSE gives a weight column of 1s", { + models <- list( + make_ufm(poisson_edges = FALSE), + make_fm(d = 60, poisson_edges = FALSE), + make_fm(d = 40, poisson_edges = FALSE) + ) + + for (model in models) { + # multigraph = TRUE: no duplicates and no weight, as before + set.seed(7) + el_multi <- sample_edgelist(model) + expect_named(el_multi, c("from", "to")) + expect_equal(anyDuplicated(el_multi), 0) + + set.seed(7) + el <- sample_edgelist(model, multigraph = FALSE) + expect_named(el, c("from", "to", "weight")) + expect_true(all(el$weight == 1L)) + expect_equal(nrow(el), nrow(el_multi)) + + set.seed(7) + ig <- sample_igraph(model, multigraph = FALSE) + expect_true(all(igraph::E(ig)$weight == 1L)) + expect_equal(igraph::ecount(ig), nrow(el_multi)) + + set.seed(7) + tg <- sample_tidygraph(model, multigraph = FALSE) + expect_true(all(igraph::E(tg)$weight == 1L)) + } +}) + +test_that("multigraph = FALSE with no sampled edges", { + X <- matrix(1, nrow = 30, ncol = 1) + ufm <- undirected_factor_model(X, matrix(1), expected_degree = 1e-10) + fm <- directed_factor_model(X, matrix(1), X, expected_in_degree = 1e-10) + + set.seed(8) + el <- sample_edgelist(ufm, multigraph = FALSE) + expect_equal(nrow(el), 0) + expect_named(el, c("from", "to", "weight")) + + set.seed(8) + el <- sample_edgelist(fm, multigraph = FALSE) + expect_equal(nrow(el), 0) + expect_named(el, c("from", "to", "weight")) + + set.seed(8) + ig <- sample_igraph(fm, multigraph = FALSE) + expect_equal(igraph::ecount(ig), 0) + expect_equal(igraph::vcount(ig), 30) +}) + +test_that("multigraph is passed through and does not trip check_dots", { + ufm <- make_ufm() + + # multigraph must be named, and unknown named arguments still error + expect_error(sample_edgelist(ufm, foo = 1)) + expect_error(sample_igraph(ufm, foo = 1)) + expect_error(sample_tidygraph(ufm, foo = 1)) + + # sample_sparse() does not take a multigraph argument + expect_error(sample_sparse(ufm, multigraph = FALSE)) +}) + +test_that("bad multigraph input gives a clear error", { + ufm <- make_ufm() + fm <- make_fm(d = 40) + + bad <- list(NA, NULL, "no", 1, c(TRUE, FALSE), logical(0)) + + for (value in bad) { + expect_error( + sample_edgelist(ufm, multigraph = value), + "`multigraph` must be a single `TRUE` or `FALSE`" + ) + expect_error( + sample_igraph(fm, multigraph = value), + "`multigraph` must be a single `TRUE` or `FALSE`" + ) + expect_error( + sample_tidygraph(ufm, multigraph = value), + "`multigraph` must be a single `TRUE` or `FALSE`" + ) + } + + expect_snapshot(sample_igraph(fm, multigraph = NA), error = TRUE) +}) From 72ec02386e5f96922134f3bb4fbe2d616ceac15c Mon Sep 17 00:00:00 2001 From: Alex Hayes Date: Tue, 17 Nov 2026 13:51:06 -0800 Subject: [PATCH 3/3] Add NEWS bullet for multigraph argument (#30) Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/NEWS.md b/NEWS.md index 47cfdee..7ddc869 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # fastRG (development version) +- `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). + - fastRG now requires R >= 4.4.0. irlba 2.4.1, which fastRG uses in tests and vignettes, fails on earlier R versions because `is.atomic(NULL)` changed in R 4.4.0. - Fixed undersampling of self-loops in undirected models. Since 0.4.0, the diagonal of `A` was sampled at half the intended rate, so `E[A | X, S]` did not equal `X S X'` on the diagonal. `sample_edgelist.undirected_factor_model()` now adds independent Poisson self-loops at the missing rate when `allow_self_loops = TRUE`, so `E[A | X, S] = X S X'` holds exactly. This only affects sampling: `S`, `expected_*()` and population spectra are unchanged, and so are the off-diagonal fixes from #19 and #31. Graphs sampled with a given seed will differ from previous versions (#46).