tests/testthat/test-functional_plots.R

# Functional audit of the plot.<class> S3 method family: every method
# registered by autograph is looked up in a fixture registry (precooked
# data objects where available, live-generated results otherwise) and its
# plot must build. Methods without a registered fixture, or whose fixture
# cannot be generated (e.g. missing Suggests package), skip with a
# greppable AUDIT message rather than silently escaping the audit.

# One fixture factory per plotted class. Factories are functions so that
# generation errors are caught per-class and reported as audit skips.
plot_fixture_registry <- list(
  ag_conv   = NULL, # internal wrapper class, exercised via traces.monan
  ag_gof    = NULL, # internal wrapper class, exercised via sienaGOF etc.
  grapht    = NULL, # print method for animations, tested in test-grapht.R
  goldfishChangepoints = function() autograph::goldfish_changepoints,
  goldfishOutliers     = function() autograph::goldfish_outliers,
  goldfishOnset        = function() autograph::goldfish_onset,
  goldfishMargins      = function() autograph::goldfish_margins,
  goldfishGOF          = function() autograph::goldfish_gof,
  goldfishTimeTest     = function() autograph::goldfish_time,
  # The aliases kept for the older class names. The fixture is the precooked
  # object with an old class put back: an alias restores dispatch only, so what
  # it must plot is an object of the current shape under the older name.
  diagnose_outliers     = function() {
    x <- autograph::goldfish_outliers
    class(x)[1] <- "diagnose_outliers"
    x
  },
  diagnose_changepoints = function() {
    x <- autograph::goldfish_changepoints
    class(x)[1] <- "diagnose_changepoints"
    x
  },
  outliers.goldfish     = function() {
    x <- autograph::goldfish_outliers
    class(x)[1] <- "outliers.goldfish"
    x
  },
  changepoints.goldfish = function() {
    x <- autograph::goldfish_changepoints
    class(x)[1] <- "changepoints.goldfish"
    x
  },
  # The overview draws each panel from a goldfish diagnostic rather than from
  # the fit alone, so with goldfish absent or older than 1.9.21 every panel
  # drops and the method prints and returns NULL. The audit accepts that, so
  # this fixture exercises the composition where goldfish can supply it and
  # the message where it cannot.
  goldfishFit           = function() autograph::goldfish_fit,
  result.goldfish       = function() {
    x <- autograph::goldfish_fit
    class(x)[1] <- "result.goldfish"
    x
  },
  diff_model  = function() autograph::res_manynet_diff,
  diffs_model = function() autograph::res_migraph_diff,
  # A sweep as `infernet::sweep_diffusion()` binds it, made here so that
  # the test does not need infernet.
  diffusionSweep = function() {
    set.seed(123)
    runs <- lapply(c(0.2, 0.8), function(p) lapply(1:3, function(j) {
      d <- as.data.frame(manynet::as_diffusion(manynet::play_diffusion(
        manynet::ison_adolescents, seeds = 1, transmissibility = p, steps = 5)))
      names(d)[names(d) == "t"] <- "time"
      data.frame(transmissibility = p, sim = j, d)
    }))
    out <- dplyr::as_tibble(do.call(rbind, unlist(runs, recursive = FALSE)))
    class(out) <- c("diffusionSweep", class(out))
    attr(out, "vary") <- "transmissibility"
    out
  },
  # The measures of each run as `infernet::sweep_opinion()` binds them.
  opinionSweep = function() {
    out <- dplyr::tibble(confidence = rep(c(0.1, 0.3), each = 3), sim = rep(1:3, 2),
                         clusters = c(5, 6, 5, 2, 2, 1), consensus = c(rep(FALSE, 5), TRUE),
                         spread = c(0.3, 0.3, 0.28, 0.1, 0.12, 0),
                         mean = 0.5, steps = 20, settled = TRUE)
    class(out) <- c("opinionSweep", class(out))
    attr(out, "vary") <- "confidence"
    out
  },
  diffusionModel = function() {
    set.seed(123)
    manynet::as_diffusion(manynet::play_diffusion(manynet::ison_adolescents,
                                                  seeds = 1,
                                                  transmissibility = 0.5))
  },
  diffusionTransitions = function() {
    set.seed(123)
    net <- manynet::play_diffusion(manynet::ison_adolescents, seeds = 1,
                                   recovery = 0.2)
    if (!inherits(net, "stocnet")) return(NULL)
    net$info$transitions
  },
  opinionModel = function() {
    if (!exists("play_opinion", asNamespace("manynet"))) return(NULL)
    set.seed(123)
    manynet::as_opinion(manynet::play_opinion(manynet::create_ring(6),
                                              opinions = stats::runif(6)))
  },
  mobilityModel = function() {
    set.seed(123)
    places <- manynet::add_node_attribute(manynet::create_lattice(25), "group",
                                          rep(c(0, 1, NA, 1, 0), 5))
    manynet::as_mobility(manynet::play_mobility(places, "group"))
  },
  learn_model = function() {
    set.seed(123)
    manynet::play_learning(manynet::create_ring(6), beliefs = stats::runif(6))
  },
  mnet        = function() manynet::ison_adolescents,
  stocnet     = function() manynet::as_stocnet(manynet::ison_adolescents),
  matrix      = function() manynet::as_matrix(manynet::ison_adolescents),
  netreg      = function() autograph::res_infernet_reg,
  netlm       = function() autograph::res_migraph_reg,
  # Nothing on CRAN makes a new 'netlogit' since migraph 2.0.0 moved the
  # regression to infernet, which returns a 'netreg'. A 'netlogit' has the same
  # fields as a 'netlm', and `plot.netlogit()` reads only those.
  netlogit    = function() {
    x <- autograph::res_migraph_reg
    class(x) <- "netlogit"
    x
  },
  infernetConfusion = function() {
    # infernet is not in Suggests until it is on CRAN, so skip this class only
    if (!requireNamespace("infernet", quietly = TRUE)) return(NULL)
    net <- manynet::mutate_nodes(manynet::ison_adolescents, Age = 12:19)
    fit <- infernet::estimate_mrqap(. ~ ego(Age) + alter(Age), net,
                                    times = 20, control = list(seed = 1))
    infernet::diagnose_confusion(fit, times = 50)
  },
  network_test = function() autograph::res_migraph_test,
  network_measures = function() {
    meas <- data.frame(time = 1:10, value = cumsum(stats::rnorm(10)))
    class(meas) <- c("network_measures", class(meas))
    meas
  },
  network_measure = function() autograph::res_netrics_robust$failure,
  node_measure = function() {
    testthat::skip_if_not_installed("netrics")
    netrics::node_by_degree(manynet::ison_adolescents)
  },
  tie_measure = function() {
    testthat::skip_if_not_installed("netrics")
    netrics::tie_by_betweenness(manynet::ison_adolescents)
  },
  node_member = function() {
    testthat::skip_if_not_installed("netrics")
    netrics::node_in_walktrap(manynet::ison_southern_women, "e")
  },
  node_motif = function() {
    testthat::skip_if_not_installed("netrics")
    netrics::node_x_triad(manynet::ison_adolescents)
  },
  network_motif = function() {
    testthat::skip_if_not_installed("netrics")
    netrics::net_x_triad(manynet::ison_adolescents)
  },
  ergm = function() {
    testthat::skip_if_not_installed("ergm")
    autograph::load_ergm_res()
  },
  gof.ergm        = function() autograph::ergm_gof,
  sienaGOF        = function() autograph::siena_gof,
  gof.stats.monan = function() autograph::monan_gof,
  traces.monan    = function() autograph::monan_conv,
  influenceTable  = function() autograph::siena_influence,
  selectionTable  = function() autograph::siena_selection
)

test_that("every registered plot method has a fixture and builds", {
  skip_on_cran()
  for (cls in ag_plot_classes()) {
    if (!cls %in% names(plot_fixture_registry)) {
      # New plot methods must be added to the registry above
      fail(paste0("AUDIT [plot.", cls, "]: no fixture registered"))
      next
    }
    factory <- plot_fixture_registry[[cls]]
    if (is.null(factory)) next # covered elsewhere, see registry comments
    # suppressWarnings: fixture generators may warn upstream (e.g. infernet)
    fixture <- run_or_skip(suppressWarnings(factory()),
                           paste0("plot.", cls), "fixture")
    if (is.null(fixture)) next # fixture needs a package that is not installed
    p <- run_or_skip(plot(fixture), paste0("plot.", cls), "plot")
    if (is.null(p)) next # methods may validly print a message and return NULL
    # suppressWarnings: data-dependent smoothing warnings (loess etc.) are
    # not what this audit is checking for
    run_or_skip(suppressWarnings(expect_buildable(p)),
                paste0("plot.", cls), "build")
  }
})

# Deeper, deterministic checks for the analysis methods that the audit above
# only smoke-tests.

test_that("measure plots support histogram and density types", {
  skip_on_cran()
  skip_if_not_installed("netrics")
  deg <- netrics::node_by_degree(manynet::ison_adolescents)
  expect_buildable(plot(deg))
  expect_buildable(plot(deg, type = "h"))
  expect_buildable(plot(deg, type = "d"))
  tb <- netrics::tie_by_betweenness(manynet::ison_adolescents)
  expect_buildable(plot(tb, type = "h"))
  expect_buildable(plot(tb, type = "d"))
})

test_that("ergm gof plot obs and sims factor levels are aligned", {
  # Regression test: the observed and simulated statistics are joined by name,
  # so R's check.names must not rewrite the numeric column names to "X0" etc.,
  # and the resulting factor levels must sort numerically rather than
  # lexically ("10" before "2").
  p <- plot(ergm_gof)
  sims_levels <- levels(p$data$name)
  numeric_vals <- suppressWarnings(as.numeric(sims_levels))
  expect_true(!any(is.na(numeric_vals)),
              info = "Factor levels should be numeric, not R-modified names (e.g. 'X0')")
  expect_equal(numeric_vals, sort(numeric_vals))
})

test_that("robustness curves plot, alone and together", {
  skip_on_cran()
  robust <- autograph::res_netrics_robust
  expect_buildable(plot(robust$failure))
  p <- plot(failure = robust$failure, attack = robust$attack)
  expect_buildable(p)
  built <- ggplot2::ggplot_build(p)
  expect_length(unique(built$data[[2]]$colour), 2)
  expect_equal(p$theme$legend.position, "bottom")
  expect_equal(levels(p$data$result)[1],
               paste0("failure (R = ",
                      format(round(as.numeric(robust$failure), 2), nsmall = 2),
                      ")"))
  # Repeated labels are numbered
  p2 <- plot(robust$failure, robust$failure)
  expect_match(levels(p2$data$result), "random failure \\([12]\\)")
})

test_that("a network measure without a curve returns NULL with a message", {
  meas <- structure(0.5, class = c("network_measure", "numeric"))
  expect_message(out <- plot(meas), "no curve to plot")
  expect_null(out)
})

test_that("network measures over time plot as a trace", {
  meas <- data.frame(time = 1:10, value = cumsum(stats::rnorm(10)))
  class(meas) <- c("network_measures", class(meas))
  expect_buildable(plot(meas))
})

test_that("matrix plots support memberships, two-mode and signed data", {
  skip_on_cran()
  skip_if_not_installed("netrics")
  memb <- netrics::node_in_walktrap(manynet::ison_adolescents, "e")
  expect_buildable(plot(manynet::as_matrix(manynet::ison_adolescents),
                        membership = memb))
  memb2 <- netrics::node_in_walktrap(manynet::ison_southern_women, "e")
  expect_buildable(plot(manynet::as_matrix(manynet::ison_southern_women),
                        membership = memb2))
  signed <- manynet::to_signed(manynet::create_ring(6))
  expect_buildable(plot(manynet::as_matrix(signed)))
  # unlabelled matrices get generated node names
  expect_buildable(plot(manynet::as_matrix(manynet::create_ring(6))))
})

test_that("diffusion summaries plot for mnet and diff_model objects", {
  skip_on_cran()
  set.seed(123)
  diff <- manynet::play_diffusion(manynet::create_ring(8), seeds = 1)
  expect_buildable(plot(diff)) # mnet dispatch, changing -> as_diffusion
  expect_buildable(plot(manynet::ison_adolescents)) # mnet dispatch, static
  expect_buildable(plot(autograph::res_manynet_diff, all_steps = FALSE))
})

test_that("goldfish diagnostics print a message when nothing is found", {
  # Both flags are logical columns as goldfish 1.9.21 emits them: `outlier`
  # replaces the old "YES"/"NO" strings, and `cpt` the old list of a data
  # frame and a vector of break positions.
  quiet_outliers <- autograph::goldfish_outliers
  quiet_outliers$outlier <- rep(FALSE, nrow(quiet_outliers))
  expect_output(out <- plot(quiet_outliers), "No outliers found")
  expect_null(out)
  quiet_cpts <- autograph::goldfish_changepoints
  quiet_cpts$cpt <- rep(FALSE, nrow(quiet_cpts))
  expect_output(out <- plot(quiet_cpts), "No regime changes found")
  expect_null(out)
})

test_that("motif plots draw the corresponding motif panels", {
  skip_on_cran()
  undirected_triads <- structure(
    matrix(1, 1, 4, dimnames = list(NULL, c("003", "102", "201", "300"))),
    class = c("node_motif", "matrix"))
  expect_buildable(plot(undirected_triads))
  dyads <- structure(c(Mutual = 1, Asymmetric = 2, Null = 3),
                     class = "network_motif")
  expect_buildable(plot(dyads))
  unknown <- structure(c(Z9 = 1), class = "network_motif")
  expect_error(plot(unknown), "cannot be illustrated yet")
})

# graphs() variants: shared layouts, wave selection, and fallbacks

test_that("graphs() shares layouts across waves and selects waves", {
  skip_on_cran()
  nets <- lapply(1:5, function(i) {
    set.seed(i)
    manynet::generate_random(6)
  })
  # unnamed list of >4 networks reduces to first and last
  p <- suppressMessages(graphs(nets))
  expect_s3_class(p, "patchwork")
  # scalar waves keeps the first n; vector waves selects
  expect_s3_class(graphs(nets, waves = 2), "patchwork")
  expect_s3_class(graphs(nets, waves = c(2, 4)), "patchwork")
  # layouts based on last or both waves
  expect_s3_class(graphs(nets, waves = c(1, 2), based_on = "last"),
                  "patchwork")
  expect_s3_class(graphs(nets, waves = c(1, 2), based_on = "both"),
                  "patchwork")
})

# One scale per aesthetic across the panels, so that `patchwork` collects the
# guides into one legend and the same value is drawn the same way in each panel
# (stocnet/autograph#15).

test_that("graphs() shares continuous scales across panels", {
  skip_on_cran()
  m0 <- matrix(c(0, 0, 0, 2, 0,
                 0, 0, 4, 0, 0,
                 0, 4, 0, 0, 0,
                 2, 0, 0, 0, 1,
                 0, 0, 0, 1, 0), 5, 5,
               dimnames = list(letters[1:5], letters[1:5]))
  m1 <- m0
  m1[4, 5] <- 0
  m1[5, 4] <- 0
  p <- suppressMessages(graphs(list(manynet::as_igraph(m0),
                                    manynet::as_igraph(m1))))
  breaks <- lapply(1:2, function(i)
    p[[i]]$scales$get_scales("edge_width")$get_breaks())
  expect_equal(breaks[[1]], breaks[[2]])
  # The lighter network holds no tie of weight 1, but is still scaled for one
  expect_equal(p[[2]]$scales$get_scales("edge_width")$limits, c(1, 4))
  gt <- suppressMessages(patchwork::patchworkGrob(p))
  expect_length(grep("guide-box", gt$layout$name), 1)
})

test_that("graphs() shares categorical scales across panels", {
  skip_on_cran()
  ties <- matrix(c(0, 1, 1, 0,
                   1, 0, 1, 0,
                   1, 1, 0, 1,
                   0, 0, 1, 0), 4, 4,
                 dimnames = list(letters[1:4], letters[1:4]))
  n0 <- manynet::mutate_ties(manynet::as_igraph(ties),
                             type = c("a", "b", "c", "a"))
  fewer <- ties
  fewer[3, 4] <- 0
  fewer[4, 3] <- 0
  n1 <- manynet::mutate_ties(manynet::as_igraph(fewer),
                             type = c("a", "b", "a"))
  p <- suppressMessages(graphs(list(n0, n1), edge_color = "type"))
  labels <- lapply(1:2, function(i)
    p[[i]]$scales$get_scales("edge_colour")$get_labels())
  expect_equal(labels[[1]], labels[[2]])
  expect_equal(labels[[1]], c("a", "b", "c"))
  # "a" is drawn in the same colour in both panels, although only one of them
  # holds all three types
  drawn <- lapply(1:2, function(i)
    suppressMessages(ggplot2::ggplot_build(p[[i]]))$data[[1]]$edge_colour[1])
  expect_equal(drawn[[1]], drawn[[2]])
})

test_that("graphs() shares the diffusion scale across waves", {
  skip_on_cran()
  set.seed(2)
  diff <- manynet::play_diffusion(manynet::ison_adolescents)
  p <- suppressMessages(graphs(diff))
  labels <- lapply(1:2, function(i)
    p[[i]]$scales$get_scales("fill")$get_labels())
  expect_equal(labels[[1]], labels[[2]])
})

test_that("graphs() handles ego networks and changing networks", {
  skip_on_cran()
  # a full set of egos gets the star layout centred on each ego
  p <- suppressMessages(graphs(manynet::to_egos(manynet::ison_adolescents),
                               waves = 8))
  expect_s3_class(p, "patchwork")
  # a partial set is not an ego network, so layouts are independent
  p2 <- suppressMessages(graphs(manynet::to_egos(manynet::ison_adolescents),
                                waves = c(1, 2)))
  expect_s3_class(p2, "patchwork")
  set.seed(123)
  diff <- manynet::play_diffusion(manynet::create_ring(8), seeds = 1)
  expect_s3_class(suppressMessages(graphs(diff)), "patchwork")
  # networks with different node sets fall back to independent layouts
  uneven <- list(manynet::create_ring(4), manynet::create_ring(6))
  expect_s3_class(suppressMessages(graphs(uneven)), "patchwork")
})

test_that("graphs() lays out a list of stocnets with different nodes", {
  skip_on_cran()
  # `length()` of a stocnet counts its list parts, not its nodes, so every list
  # of stocnets was given one shared layout, and the panels with a different
  # number of nodes failed to build with "arguments imply differing number of
  # rows" (stocnet/manynet#186). The error comes when the plot is built.
  built <- function(p) {
    for (i in seq_along(p$patches$plots)) ggplot2::ggplot_build(p[[i]])
    ggplot2::ggplot_build(p[[length(p)]])
    p
  }
  ado <- manynet::as_stocnet(manynet::ison_adolescents)
  lotr <- manynet::as_stocnet(manynet::fict_lotr)
  egos <- manynet::to_egos(ado)
  races <- manynet::to_subgraphs(lotr, "Race")
  expect_s3_class(built(suppressMessages(graphs(egos, waves = 8))), "patchwork")
  expect_s3_class(built(suppressMessages(graphs(egos, waves = c(2, 4, 6)))),
                  "patchwork")
  expect_s3_class(built(suppressMessages(graphs(races, waves = 1:4))),
                  "patchwork")
  expect_s3_class(built(suppressMessages(graphs(races))), "patchwork")
  # networks of equal size but with different nodes do not share a layout
  expect_false(.same_nodes(egos[c(2, 3)]))
  expect_true(.same_nodes(list(ado, ado)))
})

test_that("graphs() draws a single static network with graphr()", {
  skip_on_cran()
  # Before, the network was iterated over as if it were a list, and failed with
  # "invalid to use names()<- on an S4 object of class 'dgCMatrix'".
  for (net in list(manynet::ison_adolescents,
                   manynet::as_stocnet(manynet::ison_adolescents))) {
    p <- suppressMessages(graphs(net))
    expect_s3_class(p, "ggplot")
    expect_false(inherits(p, "patchwork"))
  }
})

test_that("graphs() splits a bare longitudinal or dynamic network", {
  skip_on_cran()
  # A single longitudinal network (longitudinal but not "changing") is split
  # into its waves via to_waves(), mirroring grapht(). Previously this was not
  # split and iterating the raw object errored with
  # "invalid to use names()<- on an S4 object of class 'dgCMatrix'".
  expect_s3_class(suppressMessages(graphs(manynet::ison_monks)), "patchwork")
  # A single dynamic (event) network is split into cumulative slices via
  # to_slices(), so a bare dynamic network is accepted directly.
  expect_s3_class(suppressMessages(graphs(manynet::irps_nuclear)), "patchwork")
  # An interval (spell) network is split into per-period snapshots.
  expect_s3_class(suppressMessages(graphs(manynet::irps_wwi)), "patchwork")
})

test_that("graphs() draws panels with a single signed tie", {
  skip_on_cran()
  # The first slices of irps_nuclear hold one tie each. A single value was
  # passed to the layer as a literal colour, so the shared category
  # "Negative" reached grid as a colour name and drawing failed.
  p <- suppressMessages(graphs(manynet::irps_nuclear))
  for (i in seq_along(p$patches$plots)) expect_no_error(ggplot2::ggplot_build(p[[i]]))
  expect_no_error(ggplot2::ggplot_build(p[[length(p)]]))
  grDevices::pdf(NULL)
  on.exit(grDevices::dev.off())
  expect_no_error(print(p))
})

test_that("graphs() splits a longitudinal network with non-character changing attributes", {
  skip_on_cran()
  # fict_starwars is a changing+longitudinal network whose changing node
  # attributes include a logical `active` flag and numeric height/mass, which
  # manynet::to_waves() once aborted on with a vctrs "Can't combine <character>
  # and <logical>" error. See .split_time_network() in R/grapht.R.
  expect_true(manynet::is_changing(manynet::fict_starwars))
  expect_true("active" %in%
                manynet::net_node_attributes(manynet::fict_starwars))
  expect_true(is.logical(manynet::node_attribute(manynet::fict_starwars, "active")))
  expect_s3_class(suppressMessages(graphs(manynet::fict_starwars)), "patchwork")
})

Try the autograph package in your browser

Any scripts or data that you put into this service are public.

autograph documentation built on Nov. 16, 2026, 5:08 p.m.