# Interaction rewiring and its sampling floor
# https://tidyecology.com/posts/interaction-rewiring-from-undersampling/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-07

## ---- setup ----
library(ggplot2)
library(patchwork)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- simulator ----
n_plant <- 25
n_poll  <- 40
match_w <- 0.15
n_cell  <- n_plant * n_poll
row_id  <- rep(seq_len(n_plant), times = n_poll)
col_id  <- rep(seq_len(n_poll), each = n_plant)

make_web <- function() {
  list(trait_p = runif(n_plant), trait_a = runif(n_poll),
       act_p = rlnorm(n_plant), act_a = rlnorm(n_poll))
}
web_prob <- function(w) {
  cell <- outer(w$act_p, w$act_a) *
    exp(-outer(w$trait_p, w$trait_a, "-")^2 / (2 * match_w^2))
  as.vector(cell / sum(cell))
}
make_pair <- function(loss, rewire) {
  w1 <- make_web()
  w2 <- w1
  if (rewire > 0) {
    moved <- sample(n_poll, round(rewire * n_poll))
    w2$trait_a[moved] <- runif(length(moved))
  }
  p1 <- web_prob(w1)
  p2 <- web_prob(w2)
  if (loss > 0) {
    lost <- sample(n_poll, round(loss * n_poll))
    p2[col_id %in% lost] <- 0
    p2 <- p2 / sum(p2)
  }
  list(p1 = p1, p2 = p2)
}
draw_counts <- function(p, m) as.vector(rmultinom(1, m, p))

partition <- function(x1, x2) {
  seen1 <- x1 > 0
  seen2 <- x2 > 0
  n_both <- sum(seen1 & seen2)
  n_diff <- sum(seen1 != seen2)
  denom  <- 2 * n_both + n_diff
  row_sh <- tabulate(row_id[seen1], n_plant) > 0 & tabulate(row_id[seen2], n_plant) > 0
  col_sh <- tabulate(col_id[seen1], n_poll) > 0 & tabulate(col_id[seen2], n_poll) > 0
  shared <- row_sh[row_id] & col_sh[col_id]
  both_sh <- sum(seen1 & seen2 & shared)
  diff_sh <- sum((seen1 != seen2) & shared)
  sp_same <- all((tabulate(row_id[seen1], n_plant) > 0) == (tabulate(row_id[seen2], n_plant) > 0)) &&
    all((tabulate(col_id[seen1], n_poll) > 0) == (tabulate(col_id[seen2], n_poll) > 0))
  c(wn = n_diff / denom,
    os_poisot = diff_sh / (2 * both_sh + diff_sh),
    os_common = diff_sh / denom,
    same_species = sp_same)
}

## ---- floorgrid ----
efforts  <- c(200, 500, 1000, 3000, 10000)
n_pair   <- 200
loss_use <- 0.3

floor_cf <- function(p, m) {
  detect <- 1 - (1 - p)^m
  sum(detect * (1 - detect)) / sum(detect)
}

set.seed(20917)
grid_list <- list()
for (m_eff in efforts) {
  for (loss in c(0, loss_use)) {
    out <- replicate(n_pair, {
      pr <- make_pair(loss, 0)
      c(partition(draw_counts(pr$p1, m_eff), draw_counts(pr$p2, m_eff)),
        closed = floor_cf(pr$p1, m_eff))
    })
    grid_list[[length(grid_list) + 1]] <- data.frame(
      effort = m_eff, loss = loss,
      wn = mean(out["wn", ]), os_poisot = mean(out["os_poisot", ]),
      os_common = mean(out["os_common", ]),
      os_se = sd(out["os_poisot", ]) / sqrt(n_pair),
      same_species = mean(out["same_species", ]),
      closed = mean(out["closed", ]))
  }
}
floor_tab <- do.call(rbind, grid_list)
floor_tab$share_poisot <- floor_tab$os_poisot / floor_tab$wn
floor_tab$share_common <- floor_tab$os_common / floor_tab$wn

pick <- function(col, m_eff, loss) floor_tab[[col]][floor_tab$effort == m_eff & floor_tab$loss == loss]
cf_diff <- floor_tab$closed - floor_tab$os_poisot
cf_gap_hi <- max(abs(cf_diff)[floor_tab$loss == 0 & floor_tab$effort >= 1000])
cf_gap_500 <- cf_diff[floor_tab$loss == 0 & floor_tab$effort == 500]
cf_gap_200 <- cf_diff[floor_tab$loss == 0 & floor_tab$effort == 200]
round(floor_tab[, c("effort", "loss", "wn", "os_poisot", "closed", "share_poisot", "share_common")], 3)

## ---- fig-floor ----
floor_long <- rbind(
  data.frame(effort = floor_tab$effort[floor_tab$loss == 0],
             value = floor_tab$os_poisot[floor_tab$loss == 0],
             series = "beta_OS, unchanging web"),
  data.frame(effort = floor_tab$effort[floor_tab$loss == loss_use],
             value = floor_tab$os_poisot[floor_tab$loss == loss_use],
             series = "beta_OS, 30 per cent of pollinators lost"),
  data.frame(effort = floor_tab$effort[floor_tab$loss == loss_use],
             value = floor_tab$wn[floor_tab$loss == loss_use],
             series = "beta_WN, 30 per cent of pollinators lost"))
cf_line <- data.frame(effort = floor_tab$effort[floor_tab$loss == 0],
                      value = floor_tab$closed[floor_tab$loss == 0])

ggplot(floor_long, aes(effort, value)) +
  geom_line(data = cf_line, colour = te_ink, linetype = "dashed", linewidth = 0.7) +
  geom_line(aes(colour = series), linewidth = 0.9) +
  geom_point(aes(colour = series), size = 2.4) +
  scale_colour_manual(values = c(te_forest, te_gold, te_rust), name = NULL) +
  scale_x_log10(breaks = efforts) +
  scale_y_continuous(limits = c(0, NA)) +
  guides(colour = guide_legend(ncol = 1)) +
  labs(x = "records per year (log scale)", y = "dissimilarity",
       title = "A floor that only effort lowers",
       subtitle = "dashed: closed form sum p(1 - p) / sum p for the unchanging web") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- rarefy ----
set.seed(41)
rare_out <- replicate(n_pair, {
  pr <- make_pair(0, 0)
  x_small <- draw_counts(pr$p1, 500)
  x_large <- draw_counts(pr$p2, 1500)
  keep <- sample(rep.int(seq_len(n_cell), x_large), 500)
  x_rare <- tabulate(keep, n_cell)
  c(unequal = partition(x_small, x_large)[["os_poisot"]],
    rarefied = partition(x_small, x_rare)[["os_poisot"]])
})
rare_mean <- rowMeans(rare_out)

## ---- fig-share ----
share_df <- rbind(
  data.frame(effort = floor_tab$effort[floor_tab$loss == loss_use],
             share = floor_tab$share_poisot[floor_tab$loss == loss_use],
             form = "Poisot: beta_OS on its own denominator"),
  data.frame(effort = floor_tab$effort[floor_tab$loss == loss_use],
             share = floor_tab$share_common[floor_tab$loss == loss_use],
             form = "Common denominator (Frund 2021)"))

ggplot(share_df, aes(effort, share, colour = form)) +
  geom_hline(yintercept = 0, colour = te_ink, linewidth = 0.6) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.4) +
  scale_colour_manual(values = c(te_forest, te_rust), name = NULL) +
  scale_x_log10(breaks = efforts) +
  scale_y_continuous(limits = c(0, 1)) +
  guides(colour = guide_legend(ncol = 1)) +
  labs(x = "records per year (log scale)", y = "share of beta_WN called rewiring",
       title = "Pure species loss, read as rewiring",
       subtitle = "the true share in this scenario is zero (solid line)") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- recordtests ----
n_test <- 200
n_perm <- 99
mc_se_05 <- sqrt(0.05 * 0.95 / n_test)

os_cells <- function(cells1, cells2) {
  seen1 <- tabulate(cells1, n_cell) > 0
  seen2 <- tabulate(cells2, n_cell) > 0
  row_sh <- tabulate(row_id[seen1], n_plant) > 0 & tabulate(row_id[seen2], n_plant) > 0
  col_sh <- tabulate(col_id[seen1], n_poll) > 0 & tabulate(col_id[seen2], n_poll) > 0
  shared <- row_sh[row_id] & col_sh[col_id]
  diff_sh <- sum((seen1 != seen2) & shared)
  both_sh <- sum(seen1 & seen2 & shared)
  if (diff_sh + both_sh == 0) return(0)
  diff_sh / (2 * both_sh + diff_sh)
}
perm_records <- function(cells1, cells2, nperm = n_perm) {
  obs  <- os_cells(cells1, cells2)
  pool <- c(cells1, cells2)
  n1   <- length(cells1)
  null_os <- vapply(seq_len(nperm), function(i) {
    shuffled <- sample(pool)
    os_cells(shuffled[seq_len(n1)], shuffled[-seq_len(n1)])
  }, numeric(1))
  (1 + sum(null_os >= obs)) / (nperm + 1)
}
draw_cells <- function(p, m) sample.int(n_cell, m, replace = TRUE, prob = p)

scen_tab <- data.frame(scenario = c("unchanging", "species loss only",
                                    "rewiring 15 per cent", "rewiring 30 per cent"),
                       loss = c(0, loss_use, 0, 0), rewire = c(0, 0, 0.15, 0.3))
set.seed(3203)
rec_list <- list()
for (m_eff in c(500, 3000)) {
  for (k in seq_len(nrow(scen_tab))) {
    p_val <- replicate(n_test, {
      pr <- make_pair(scen_tab$loss[k], scen_tab$rewire[k])
      perm_records(draw_cells(pr$p1, m_eff), draw_cells(pr$p2, m_eff))
    })
    rec_list[[length(rec_list) + 1]] <- data.frame(
      effort = m_eff, scenario = scen_tab$scenario[k], reject = mean(p_val <= 0.05))
  }
}
rec_tab <- do.call(rbind, rec_list)
rpick <- function(m_eff, scen) rec_tab$reject[rec_tab$effort == m_eff & rec_tab$scenario == scen]
rec_tab

## ---- bouttests ----
bout_len  <- 6
n_bout    <- 200

draw_bouts <- function(p, nb, lens, constancy) {
  cell_mat <- matrix(p, n_plant, n_poll)
  col_mass <- colSums(cell_mat)
  poll <- sample.int(n_poll, nb, replace = TRUE, prob = col_mass)
  cum_plant <- apply(sweep(cell_mat, 2, col_mass, "/"), 2, cumsum)
  pick_plant <- function(pl) {
    u <- runif(length(pl))
    pmin(1 + rowSums(u > t(cum_plant[, pl, drop = FALSE])), n_plant)
  }
  kmax <- max(lens)
  plants <- matrix(0L, nb, kmax)
  plants[, 1] <- pick_plant(poll)
  if (kmax > 1) {
    for (k in 2:kmax) {
      stay <- runif(nb) < constancy
      plants[, k] <- ifelse(stay, plants[, k - 1], pick_plant(poll))
    }
  }
  cells <- plants + (poll - 1L) * n_plant
  cells[col(cells) > lens] <- 0L
  cells
}
perm_bouts <- function(bouts1, bouts2, nperm = n_perm) {
  obs  <- os_cells(bouts1, bouts2)
  pool <- rbind(bouts1, bouts2)
  n1   <- nrow(bouts1)
  null_os <- vapply(seq_len(nperm), function(i) {
    idx <- sample.int(nrow(pool), n1)
    os_cells(pool[idx, ], pool[-idx, ])
  }, numeric(1))
  (1 + sum(null_os >= obs)) / (nperm + 1)
}
pad_bouts <- function(bouts, width) {
  if (ncol(bouts) >= width) return(bouts)
  cbind(bouts, matrix(0L, nrow(bouts), width - ncol(bouts)))
}
bout_cell <- function(rewire, constancy, record_test) {
  p_out <- replicate(n_test, {
    pr <- make_pair(0, rewire)
    b1 <- draw_bouts(pr$p1, n_bout, rep(bout_len, n_bout), constancy)
    b2 <- draw_bouts(pr$p2, n_bout, rep(bout_len, n_bout), constancy)
    c(record = if (record_test) perm_records(b1[b1 > 0], b2[b2 > 0]) else NA,
      bout = perm_bouts(b1, b2))
  })
  rowMeans(p_out <= 0.05)
}

set.seed(6601)
bout_null_c1   <- bout_cell(0, 1, TRUE)
bout_null_c05  <- bout_cell(0, 0.5, TRUE)
bout_rew15     <- bout_cell(0.15, 1, FALSE)
bout_rew30     <- bout_cell(0.3, 1, FALSE)
bout_null_c1
bout_null_c05

## ---- nullexample ----
set.seed(808)
ex_pair <- make_pair(0, 0)
ex_b1 <- draw_bouts(ex_pair$p1, n_bout, rep(bout_len, n_bout), 1)
ex_b2 <- draw_bouts(ex_pair$p2, n_bout, rep(bout_len, n_bout), 1)
ex_obs <- os_cells(ex_b1, ex_b2)
n_show <- 999
ex_rec_pool <- c(ex_b1[ex_b1 > 0], ex_b2[ex_b2 > 0])
ex_n1 <- sum(ex_b1 > 0)
ex_null_rec <- vapply(seq_len(n_show), function(i) {
  s <- sample(ex_rec_pool); os_cells(s[seq_len(ex_n1)], s[-seq_len(ex_n1)])
}, numeric(1))
ex_pool <- rbind(ex_b1, ex_b2)
ex_null_bout <- vapply(seq_len(n_show), function(i) {
  idx <- sample.int(nrow(ex_pool), n_bout); os_cells(ex_pool[idx, ], ex_pool[-idx, ])
}, numeric(1))
ex_q_rec  <- mean(ex_null_rec >= ex_obs)
ex_q_bout <- mean(ex_null_bout >= ex_obs)

## ---- fig-nulls ----
null_df <- rbind(data.frame(os = ex_null_rec, null = "shuffle records"),
                 data.frame(os = ex_null_bout, null = "shuffle bouts"))
ggplot(null_df, aes(os, fill = null)) +
  geom_histogram(bins = 45, position = "identity", alpha = 0.75, colour = NA) +
  geom_vline(xintercept = ex_obs, colour = te_ink, linewidth = 0.9) +
  scale_fill_manual(values = c(te_forest, te_gold), name = NULL) +
  labs(x = "beta_OS", y = "permutations",
       title = "Shuffling records forgets the bouts",
       subtitle = "vertical line: observed beta_OS of one unchanging pair") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- boutlength ----
perm_strata <- function(bouts1, bouts2, nperm = n_perm) {
  obs  <- os_cells(bouts1, bouts2)
  pool <- rbind(bouts1, bouts2)
  lens <- rowSums(pool > 0)
  year <- rep(1:2, c(nrow(bouts1), nrow(bouts2)))
  base_order <- order(lens)
  null_os <- vapply(seq_len(nperm), function(i) {
    lab <- integer(length(year))
    lab[order(lens, runif(length(lens)))] <- year[base_order]
    os_cells(pool[lab == 1, , drop = FALSE], pool[lab == 2, , drop = FALSE])
  }, numeric(1))
  (1 + sum(null_os >= obs)) / (nperm + 1)
}
mu_short <- 2
mu_long  <- 8
varlen_cell <- function(n_short, n_long, constancy, rewire = 0, record_test = FALSE) {
  p_out <- replicate(n_test, {
    pr <- make_pair(0, rewire)
    b1 <- draw_bouts(pr$p1, n_short, 1 + rpois(n_short, mu_short), constancy)
    b2 <- draw_bouts(pr$p2, n_long, 1 + rpois(n_long, mu_long), constancy)
    width <- max(ncol(b1), ncol(b2))
    b1 <- pad_bouts(b1, width)
    b2 <- pad_bouts(b2, width)
    c(record = if (record_test) perm_records(b1[b1 > 0], b2[b2 > 0]) else NA,
      bout = perm_bouts(b1, b2), strata = perm_strata(b1, b2))
  })
  rowMeans(p_out <= 0.05)
}
# expected plant choices per year: a bout of length 1 + Poisson(mu) makes 1 + (1 - constancy) * mu;
# after a bout shuffle both years draw from one pool, so their ratio is the ratio of bout counts
choice_ratio <- function(n_short, n_long, constancy) {
  c(observed = n_long * (1 + (1 - constancy) * mu_long) / (n_short * (1 + (1 - constancy) * mu_short)),
    shuffled = n_long / n_short)
}
set.seed(7702)
vl_a_c1  <- varlen_cell(400, 133, 1, record_test = TRUE)
vl_a_c05 <- varlen_cell(400, 133, 0.5, record_test = TRUE)
vl_b_c05 <- varlen_cell(267, 267, 0.5)
vl_b_c08 <- varlen_cell(267, 267, 0.8)
vl_c_c05 <- varlen_cell(133, 400, 0.5)
vl_pow_a_c1  <- varlen_cell(400, 133, 1, 0.3)
vl_pow_a_c05 <- varlen_cell(400, 133, 0.5, 0.3)
vl_pow_b_c05 <- varlen_cell(267, 267, 0.5, 0.3)
cr_a <- choice_ratio(400, 133, 0.5)
cr_b <- choice_ratio(267, 267, 0.5)
cr_c <- choice_ratio(133, 400, 0.5)
rbind(a_c1 = vl_a_c1, a_c05 = vl_a_c05, b_c05 = vl_b_c05, b_c08 = vl_b_c08, c_c05 = vl_c_c05,
      pow_a_c1 = vl_pow_a_c1, pow_a_c05 = vl_pow_a_c05, pow_b_c05 = vl_pow_b_c05)
strata_size <- c(vl_a_c1[["strata"]], vl_a_c05[["strata"]], vl_b_c05[["strata"]],
                 vl_b_c08[["strata"]], vl_c_c05[["strata"]])
bout_size_pc <- c(vl_a_c05[["bout"]], vl_b_c05[["bout"]], vl_b_c08[["bout"]], vl_c_c05[["bout"]])
strata_z <- max(abs(strata_size - 0.05)) / mc_se_05
rbind(cr_a, cr_b, cr_c)

## ---- fig-tests ----
size_df <- data.frame(
  scheme = rep(c("independent records, 500", "independent records, 3000",
                 "bouts of 6, constancy 1", "bouts of 6, constancy 0.5",
                 "400 short, 133 long, constancy 1", "400 short, 133 long, constancy 0.5",
                 "267 short, 267 long, constancy 0.5", "267 short, 267 long, constancy 0.8",
                 "133 short, 400 long, constancy 0.5"), each = 3),
  test = rep(c("shuffle records", "shuffle bouts", "shuffle bouts within length"), 9),
  reject = c(rpick(500, "unchanging"), NA, NA, rpick(3000, "unchanging"), NA, NA,
             bout_null_c1[["record"]], bout_null_c1[["bout"]], NA,
             bout_null_c05[["record"]], bout_null_c05[["bout"]], NA,
             vl_a_c1[c("record", "bout", "strata")], vl_a_c05[c("record", "bout", "strata")],
             vl_b_c05[c("record", "bout", "strata")], vl_b_c08[c("record", "bout", "strata")],
             vl_c_c05[c("record", "bout", "strata")]))
size_df <- size_df[!is.na(size_df$reject), ]
size_df$scheme <- factor(size_df$scheme, levels = rev(unique(size_df$scheme)))

pow_df <- data.frame(
  scheme = rep(c("independent records, 500: records", "independent records, 3000: records",
                 "bouts of 6, constancy 1: bouts"), each = 2),
  shift = rep(c("15 per cent of pollinators", "30 per cent of pollinators"), 3),
  reject = c(rpick(500, "rewiring 15 per cent"), rpick(500, "rewiring 30 per cent"),
             rpick(3000, "rewiring 15 per cent"), rpick(3000, "rewiring 30 per cent"),
             bout_rew15[["bout"]], bout_rew30[["bout"]]))
pow_df <- rbind(pow_df, data.frame(
  scheme = c("400 short, 133 long, constancy 1: bouts",
             "400 short, 133 long, constancy 1: within length",
             "400 short, 133 long, constancy 0.5: within length",
             "267 short, 267 long, constancy 0.5: within length"),
  shift = "30 per cent of pollinators",
  reject = c(vl_pow_a_c1[["bout"]], vl_pow_a_c1[["strata"]],
             vl_pow_a_c05[["strata"]], vl_pow_b_c05[["strata"]])))
pow_df$scheme <- factor(pow_df$scheme, levels = rev(unique(pow_df$scheme)))

p_size <- ggplot(size_df, aes(reject, scheme, colour = test)) +
  geom_vline(xintercept = 0.05, linetype = "dashed", colour = te_body, linewidth = 0.6) +
  geom_point(size = 3, alpha = 0.9) +
  scale_colour_manual(values = c(te_forest, te_gold, te_rust), name = NULL) +
  scale_x_continuous(limits = c(0, 1)) +
  guides(colour = guide_legend(nrow = 2)) +
  labs(x = "rejection rate, unchanging web", y = NULL, title = "Size") +
  theme_datasheet() +
  theme(legend.position = "bottom")
p_pow <- ggplot(pow_df, aes(reject, scheme, shape = shift)) +
  geom_point(size = 3, colour = te_ink, stroke = 1.1) +
  scale_shape_manual(values = c(1, 16), name = NULL) +
  scale_x_continuous(limits = c(0, 1)) +
  labs(x = "rejection rate, valid test", y = NULL, title = "Power") +
  theme_datasheet() +
  theme(legend.position = "bottom")
(p_size / p_pow) +
  plot_layout(heights = c(3.2, 2.5)) +
  plot_annotation(theme = theme_datasheet())
