# Building an analysis pipeline with targets
# https://tidyecology.com/posts/building-a-pipeline-with-targets/
#
# 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)

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"))
}

## ---- graph ----
tg <- data.frame(
  target = c("raw_samples", "taxon_lookup", "chem", "clean_samples", "qc_flags",
             "reach_ept", "reach_table", "model", "boot", "perm", "rarefy",
             "figure", "report"),
  cost = c(3, 1, 1, 6, 9, 10, 2, 2, 40, 38, 30, 10, 1),
  stringsAsFactors = FALSE)

ed <- data.frame(rbind(
  c("raw_samples",   "clean_samples"),
  c("taxon_lookup",  "clean_samples"),
  c("clean_samples", "qc_flags"),
  c("clean_samples", "reach_ept"),
  c("reach_ept",     "reach_table"),
  c("chem",          "reach_table"),
  c("reach_table",   "model"),
  c("reach_table",   "boot"),
  c("reach_table",   "perm"),
  c("reach_table",   "rarefy"),
  c("model",         "figure"),
  c("rarefy",        "figure"),
  c("model",         "report"),
  c("boot",          "report"),
  c("perm",          "report")), stringsAsFactors = FALSE)
names(ed) <- c("from", "to")

parents_of  <- function(edges, node) edges$from[edges$to == node]
children_of <- function(edges, node) edges$to[edges$from == node]
cost_of     <- function(nodes) sum(tg$cost[match(nodes, tg$target)])

topo_order <- function(nodes, edges) {
  left <- nodes
  done <- character(0)
  while (length(left) > 0) {
    ready <- left[sapply(left, function(n) all(parents_of(edges, n) %in% done))]
    if (length(ready) == 0) stop("the graph has a cycle: ",
                                 paste(left, collapse = ", "))
    done <- c(done, ready)
    left <- setdiff(left, ready)
  }
  done
}

downstream <- function(edges, changed) {
  front <- changed
  hit <- changed
  while (length(front) > 0) {
    nxt <- setdiff(unique(edges$to[edges$from %in% front]), hit)
    hit <- c(hit, nxt)
    front <- nxt
  }
  hit
}

ord <- topo_order(tg$target, ed)
total_cost <- sum(tg$cost)
round(c(targets = nrow(tg), edges = nrow(ed), total_cost_seconds = total_cost,
        leaves = sum(!tg$target %in% ed$from),
        roots = sum(!tg$target %in% ed$to)), 4)
print(ord)

## ---- cycle ----
bad_edges <- rbind(ed, data.frame(from = "report", to = "clean_samples"))
cat(tryCatch({ topo_order(tg$target, bad_edges); "sorted" },
             error = function(e) conditionMessage(e)), "\n")

## ---- fig-graph ----
lay <- tg
lay$y <- c(1.1, 0, -1.5, 0.6, -0.9, 0.8, 0, 1.6, 0.55, -0.55, -1.6, -1.1, 1.1)
depth <- setNames(rep(1, nrow(tg)), tg$target)
for (n in ord) {
  p <- parents_of(ed, n)
  if (length(p) > 0) depth[n] <- max(depth[p]) + 1
}
lay$x <- depth[lay$target]
lay$share <- sapply(lay$target, function(n)
  100 * cost_of(downstream(ed, n)) / total_cost)
lay$vj <- ifelse(lay$target %in% c("qc_flags", "figure"), 1.75, -0.75)   # label below where an edge would cross it

seg <- data.frame(x = lay$x[match(ed$from, lay$target)],
                  y = lay$y[match(ed$from, lay$target)],
                  xe = lay$x[match(ed$to, lay$target)],
                  ye = lay$y[match(ed$to, lay$target)])
gap <- 0.1
len <- sqrt((seg$xe - seg$x)^2 + ((seg$ye - seg$y) / 3)^2)
seg$x1 <- seg$x + (seg$xe - seg$x) * gap / len
seg$y1 <- seg$y + (seg$ye - seg$y) * gap / len
seg$x2 <- seg$xe - (seg$xe - seg$x) * gap / len
seg$y2 <- seg$ye - (seg$ye - seg$y) * gap / len

ggplot(lay, aes(x, y)) +
  geom_segment(data = seg, aes(x = x1, y = y1, xend = x2, yend = y2),
               inherit.aes = FALSE, colour = "#9aa295", linewidth = 0.5,
               arrow = arrow(length = unit(0.08, "inches"), type = "closed")) +
  geom_point(aes(fill = share), shape = 21, size = 5.6, colour = te_pal$ink,
             stroke = 0.7) +
  geom_text(aes(label = paste0(target, "\n", cost, " s"), vjust = vj),
            lineheight = 0.9, size = 2.8, colour = te_pal$ink) +
  scale_fill_gradient(low = te_pal$sage, high = te_pal$clay,
                      name = "Cost rerun if this target changes (per cent)") +
  scale_x_continuous(breaks = 1:6, limits = c(0.6, 6.4)) +
  scale_y_continuous(limits = c(-2.2, 2.5)) +
  labs(x = "Depth in the graph", y = NULL,
       title = "Changing the first target reruns 98.7 per cent of the cost") +
  theme_te() +
  theme(legend.position = "top", axis.text.y = element_blank(),
        panel.grid.major.y = element_blank())

## ---- stale ----
stale_of <- function(changed) {
  d <- downstream(ed, changed)
  c(stale = length(d), cost = cost_of(d), percent = 100 * cost_of(d) / total_cost)
}

inval <- t(sapply(tg$target, function(n) stale_of(n)))
inval <- data.frame(target = rownames(inval), inval, row.names = NULL)
print(inval[order(-inval$percent), ])

round(c(cheapest_change_percent = min(inval$percent),
        dearest_change_percent = max(inval$percent),
        median_change_percent = median(inval$percent),
        targets_that_invalidate_over_half = sum(inval$percent > 50),
        targets_that_invalidate_only_themselves = sum(inval$stale == 1)), 4)

## ---- fig-stale ----
sl <- data.frame(
  target = factor(rep(inval$target, 2), levels = inval$target[order(inval$percent)]),
  value = c(inval$stale, inval$percent),
  lab = c(sprintf("%.0f", inval$stale), sprintf("%.1f", inval$percent)),
  share = rep(inval$percent, 2),
  panel = factor(rep(c("Targets made stale (count)",
                       "Share of total pipeline cost (per cent)"),
                     each = nrow(inval)),
                 levels = c("Targets made stale (count)",
                            "Share of total pipeline cost (per cent)")))

ggplot(sl, aes(value, target, fill = share)) +
  geom_col(width = 0.72) +
  geom_text(aes(label = lab), hjust = -0.15, size = 2.9, colour = te_pal$ink) +
  facet_wrap(~panel, scales = "free_x") +
  scale_fill_gradient(low = te_pal$sage, high = te_pal$clay,
                      name = "Cost rerun if this target changes (per cent)") +
  scale_x_continuous(expand = expansion(mult = c(0, 0.18)),
                     breaks = function(lims)
                       if (lims[2] < 20) seq(0, 10, by = 5) else seq(0, 90, by = 30)) +
  labs(x = NULL, y = NULL,
       title = "Six of the thirteen steps put over half the pipeline out of date") +
  theme_te() +
  theme(legend.position = "top",
        strip.text = element_text(colour = te_pal$ink, face = "bold", size = 9),
        panel.spacing.x = unit(1.6, "lines"),
        panel.grid.major.y = element_blank())

## ---- field-data ----
set.seed(20260815)
n_pool <- 30
n_taxa <- 40
n_rep  <- 3

tp_pool <- round(exp(rnorm(n_pool, log(45), 0.85)), 1)
enrich  <- (log2(tp_pool) - min(log2(tp_pool))) /
  (max(log2(tp_pool)) - min(log2(tp_pool)))
tol <- c(sort(runif(22, 0, 0.62)), runif(18, 0.3, 1))
occ_p <- outer(enrich, tol, function(e, t) plogis(2.6 + 6.5 * (t - e)))
occ <- matrix(runif(n_pool * n_taxa) < occ_p, n_pool, n_taxa)

meta <- data.frame(
  reach  = rep(seq_len(n_pool), each = n_rep),
  rep    = rep(seq_len(n_rep), n_pool),
  effort = round(runif(n_pool * n_rep, 7, 12), 1))
short <- sample(nrow(meta), 9)
meta$effort[short] <- round(runif(9, 2, 4.6), 1)
det_p <- plogis(-1.4 + 0.30 * meta$effort)
obs <- matrix(FALSE, nrow(meta), n_taxa)
for (i in seq_len(nrow(meta)))
  obs[i, ] <- occ[meta$reach[i], ] & (runif(n_taxa) < det_p[i])

ept_v1 <- seq_len(n_taxa) <= 22
ept_v2 <- ept_v1
ept_v2[c(23, 24)] <- TRUE
ept_v2[22] <- FALSE

round(c(reaches_in_pool = n_pool, taxa = n_taxa, samples = nrow(meta),
        ept_taxa_lookup_v1 = sum(ept_v1), ept_taxa_lookup_v2 = sum(ept_v2),
        median_effort_minutes = median(meta$effort),
        shortened_samples = length(short),
        samples_in_the_first_build = sum(meta$reach <= 24),
        phosphorus_lowest = min(tp_pool), phosphorus_highest = max(tp_pool)), 4)

## ---- recipes ----
rec <- list()

rec$raw_samples <- function(v, p) {
  keep <- meta$reach <= p$n_reach & !(meta$reach %in% p$drop_reach)
  list(meta = meta[keep, ], obs = obs[keep, , drop = FALSE])
}
rec$taxon_lookup <- function(v, p) if (p$lookup == 1) ept_v1 else ept_v2
rec$chem <- function(v, p) {
  tp <- tp_pool[seq_len(p$n_reach)]
  if (p$chem_fix) tp[c(7, 19)] <- tp[c(7, 19)] * c(0.42, 0.55)
  data.frame(reach = seq_len(p$n_reach), tp = tp)
}
rec$clean_samples <- function(v, p) {
  r <- v$raw_samples
  keep <- r$meta$effort >= p$min_effort
  list(meta = r$meta[keep, ], obs = r$obs[keep, v$taxon_lookup, drop = FALSE])
}
rec$qc_flags <- function(v, p) {
  c(kept = nrow(v$clean_samples$meta),
    dropped = nrow(v$raw_samples$meta) - nrow(v$clean_samples$meta))
}
rec$reach_ept <- function(v, p) {
  cs <- v$clean_samples
  rs <- sort(unique(cs$meta$reach))
  val <- sapply(rs, function(r) {
    ix <- which(cs$meta$reach == r)
    if (p$standardise == "per_sample") mean(rowSums(cs$obs[ix, , drop = FALSE]))
    else sum(colSums(cs$obs[ix, , drop = FALSE]) > 0)
  })
  data.frame(reach = rs, ept = val)
}
rec$reach_table <- function(v, p) {
  m <- merge(v$reach_ept, v$chem, by = "reach")
  m$lp <- log2(m$tp)
  m
}
fit_it <- function(d) lm(ept ~ lp, data = d)
rec$model <- function(v, p) fit_it(v$reach_table)
rec$boot <- function(v, p) {
  d <- v$reach_table
  set.seed(p$boot_seed)
  s <- replicate(p$boot_reps, {
    ix <- sample(nrow(d), nrow(d), replace = TRUE)
    coef(fit_it(d[ix, ]))["lp"]
  })
  unname(quantile(s, c(0.025, 0.975)))
}
rec$perm <- function(v, p) {
  d <- v$reach_table
  set.seed(p$perm_seed)
  obs_slope <- coef(fit_it(d))["lp"]
  nul <- replicate(p$perm_reps, {
    dd <- d
    dd$lp <- sample(dd$lp)
    coef(fit_it(dd))["lp"]
  })
  unname((1 + sum(abs(nul) >= abs(obs_slope))) / (p$perm_reps + 1))
}
rec$rarefy <- function(v, p) round(mean(v$reach_table$ept), 4)
rec$figure <- function(v, p) c(points = nrow(v$reach_table), theme = p$fig_theme)
rec$report <- function(v, p)
  c(slope = unname(coef(v$model)["lp"]), lo = v$boot[1], hi = v$boot[2],
    p = v$perm)

settings <- list(n_reach = 24, drop_reach = integer(0), min_effort = 5,
                 lookup = 1, chem_fix = FALSE, standardise = "per_sample",
                 boot_reps = 400, boot_seed = 11, perm_reps = 400,
                 perm_seed = 12, fig_theme = 1)

build_all <- function(p) {
  v <- list()
  for (n in ord) v[[n]] <- rec[[n]](v, p)
  v
}
v0 <- build_all(settings)
round(v0$report, 4)
print(v0$qc_flags)

## ---- edits ----
edits <- list(
  list(lab = "figure axis relabelled",           tgt = "figure",
       set = list(fig_theme = 2)),
  list(lab = "effort threshold 5 to 8 minutes",  tgt = "clean_samples",
       set = list(min_effort = 8)),
  list(lab = "bootstrap 400 to 1200 draws",      tgt = "boot",
       set = list(boot_reps = 1200)),
  list(lab = "taxon lookup revised",             tgt = "taxon_lookup",
       set = list(lookup = 2)),
  list(lab = "September batch arrives",          tgt = c("raw_samples", "chem"),
       set = list(n_reach = 30)),
  list(lab = "phosphorus recalibrated",          tgt = "chem",
       set = list(chem_fix = TRUE)),
  list(lab = "richness pooled over replicates",  tgt = "reach_ept",
       set = list(standardise = "pooled")),
  list(lab = "permutation 400 to 1000 shuffles", tgt = "perm",
       set = list(perm_reps = 1000)),
  list(lab = "one reach excluded",               tgt = "raw_samples",
       set = list(drop_reach = 9L)),
  list(lab = "effort threshold back to 7",       tgt = "clean_samples",
       set = list(min_effort = 7)),
  list(lab = "second reach excluded",            tgt = "raw_samples",
       set = list(drop_reach = c(9L, 27L))),
  list(lab = "figure theme changed",             tgt = "figure",
       set = list(fig_theme = 3)))

mental <- ed[!(ed$from == "reach_table" & ed$to == "boot"), ]
mental <- rbind(mental, data.frame(from = "chem", to = "clean_samples"))

edit_cost <- t(sapply(edits, function(e)
  c(graph = cost_of(downstream(ed, e$tgt)),
    memory = cost_of(downstream(mental, e$tgt)),
    everything = total_cost)))
print(data.frame(edit = sapply(edits, function(e) e$lab), edit_cost))
round(c(mean_cost_invalidated_per_edit_percent =
          mean(100 * edit_cost[, "graph"] / total_cost),
        edits_that_invalidate_over_half = sum(edit_cost[, "graph"] > total_cost / 2)), 4)

## ---- strategies ----
run_sequence <- function(mode) {
  p <- settings
  v <- build_all(p)
  cost <- total_cost
  out <- data.frame(step = 0, cost = cost, rebuilt = length(ord),
                    slope = v$report[["slope"]], lo = v$report[["lo"]],
                    hi = v$report[["hi"]], pval = v$report[["p"]])
  for (k in seq_along(edits)) {
    e <- edits[[k]]
    for (nm in names(e$set)) p[[nm]] <- e$set[[nm]]
    hit <- switch(mode,
                  everything = tg$target,
                  graph = downstream(ed, e$tgt),
                  memory = downstream(mental, e$tgt))
    hit <- ord[ord %in% hit]
    for (n in hit) v[[n]] <- rec[[n]](v, p)
    cost <- cost + cost_of(hit)
    out <- rbind(out, data.frame(step = k, cost = cost, rebuilt = length(hit),
                                 slope = v$report[["slope"]],
                                 lo = v$report[["lo"]], hi = v$report[["hi"]],
                                 pval = v$report[["p"]]))
  }
  rownames(out) <- NULL
  out
}

truth_sequence <- function() {
  p <- settings
  v <- build_all(p)
  out <- data.frame(step = 0, slope = v$report[["slope"]], lo = v$report[["lo"]],
                    hi = v$report[["hi"]], pval = v$report[["p"]])
  for (k in seq_along(edits)) {
    for (nm in names(edits[[k]]$set)) p[[nm]] <- edits[[k]]$set[[nm]]
    v <- build_all(p)
    out <- rbind(out, data.frame(step = k, slope = v$report[["slope"]],
                                 lo = v$report[["lo"]], hi = v$report[["hi"]],
                                 pval = v$report[["p"]]))
  }
  rownames(out) <- NULL
  out
}

A <- run_sequence("everything")
G <- run_sequence("graph")
M <- run_sequence("memory")
TR <- truth_sequence()

agrees <- function(x) all(abs(x$slope - TR$slope) < 1e-9 &
                            abs(x$lo - TR$lo) < 1e-9 & abs(x$hi - TR$hi) < 1e-9)
round(c(cost_rebuild_everything = max(A$cost),
        cost_from_memory = max(M$cost),
        cost_let_the_graph_decide = max(G$cost),
        ratio_everything_over_graph = max(A$cost) / max(G$cost),
        ratio_memory_over_graph = max(M$cost) / max(G$cost),
        graph_saves_percent = 100 * (1 - max(G$cost) / max(A$cost)),
        memory_does_less_work_than_graph_percent =
          100 * (1 - max(M$cost) / max(G$cost)),
        target_rebuilds_everything = sum(A$rebuilt[-1]),
        target_rebuilds_graph = sum(G$rebuilt[-1]),
        target_rebuilds_memory = sum(M$rebuilt[-1])), 4)

c(rebuild_everything_matches_truth = agrees(A),
  graph_matches_truth = agrees(G),
  memory_matches_truth = agrees(M))

## ---- answer ----
wrong_ci <- abs(M$lo - TR$lo) > 1e-9 | abs(M$hi - TR$hi) > 1e-9
visible <- M$slope < M$lo | M$slope > M$hi
boot_due <- sapply(edits, function(e) "boot" %in% downstream(ed, e$tgt))
boot_run <- sapply(edits, function(e) "boot" %in% downstream(mental, e$tgt))

k <- nrow(M)
round(c(edits_after_which_the_estimate_was_wrong = sum(abs(M$slope - TR$slope) > 1e-9),
        edits_after_which_the_p_value_was_wrong = sum(abs(M$pval - TR$pval) > 1e-12),
        edits_after_which_the_interval_was_wrong = sum(wrong_ci),
        bootstrap_rebuilds_the_graph_would_have_run = sum(boot_due),
        bootstrap_rebuilds_the_analyst_ran = sum(boot_run),
        states_where_the_estimate_falls_outside_its_own_interval = sum(visible),
        wrong_states_with_no_visible_symptom = sum(wrong_ci) - sum(visible)), 4)

round(c(final_taxa_lost_per_doubling = -TR$slope[k],
        correct_interval_low = -TR$hi[k], correct_interval_high = -TR$lo[k],
        reported_interval_low = -M$hi[k], reported_interval_high = -M$lo[k],
        correct_width = TR$hi[k] - TR$lo[k],
        reported_width = M$hi[k] - M$lo[k],
        low_end_understated_percent = 100 * (M$hi[k] - TR$hi[k]) / -TR$hi[k],
        high_end_understated_percent = 100 * (M$lo[k] - TR$lo[k]) / -TR$lo[k],
        overlap_of_the_two_intervals =
          min(TR$hi[k], M$hi[k]) - max(TR$lo[k], M$lo[k]),
        biggest_move_of_the_correct_interval_in_one_edit =
          max(abs(diff(TR$lo)))), 4)

## ---- fig-strategies ----
lv <- c("Rebuild everything", "From memory", "Let the graph decide")
cost_df <- data.frame(
  step = rep(A$step, 3),
  value = c(A$cost, M$cost, G$cost),
  strategy = factor(rep(lv, each = nrow(A)), levels = lv),
  panel = "Cumulative rebuild cost (declared seconds)")
band_df <- data.frame(
  step = rep(A$step, 3),
  lo = -c(A$hi, M$hi, G$hi), hi = -c(A$lo, M$lo, G$lo),
  strategy = factor(rep(lv, each = nrow(A)), levels = lv),
  panel = "Reported EPT taxa lost per doubling of phosphorus")
est_df <- data.frame(step = A$step, value = -A$slope,
                     panel = "Reported EPT taxa lost per doubling of phosphorus")
pal3 <- c(te_pal$gold, te_pal$clay, te_pal$forest)

# the everything and graph bands hold identical values at every step, so the
# first is traced as an outline: three fills would paint over one another
band_fill <- band_df[band_df$strategy != "Rebuild everything", ]
band_edge <- band_df[band_df$strategy == "Rebuild everything", ]

ggplot(cost_df, aes(step, value)) +
  geom_ribbon(data = band_fill, aes(y = NULL, ymin = lo, ymax = hi, fill = strategy),
              alpha = 0.5) +
  geom_ribbon(data = band_edge, aes(y = NULL, ymin = lo, ymax = hi,
                                    colour = strategy),
              fill = NA, linetype = 2, linewidth = 0.6, show.legend = FALSE) +
  geom_line(data = est_df, aes(step, value), colour = te_pal$ink,
            linewidth = 0.9) +
  geom_point(data = est_df, aes(step, value), colour = te_pal$ink, size = 1.7) +
  geom_line(aes(colour = strategy), linewidth = 0.9) +
  geom_segment(data = data.frame(
    step = 5, value = 3.62,
    panel = "Reported EPT taxa lost per doubling of phosphorus"),
    aes(x = step, xend = step, y = value, yend = 4.2), colour = te_pal$ink,
    linewidth = 0.4) +
  geom_text(data = data.frame(
    step = 5, value = 3.48,
    panel = "Reported EPT taxa lost per doubling of phosphorus"),
    label = "reported estimate", size = 3.1, colour = te_pal$ink) +
  facet_wrap(~panel, ncol = 1, scales = "free_y") +
  scale_colour_manual(values = pal3, name = NULL, drop = FALSE) +
  scale_fill_manual(values = pal3, name = NULL, drop = FALSE, guide = "none") +
  scale_x_continuous(breaks = 0:12) +
  labs(x = "Edits made, in order",
       y = NULL,
       title = "The strategy that did the least work reported a nine-edit-old interval") +
  theme_te() +
  theme(legend.position = "top",
        strip.text = element_text(colour = te_pal$ink, face = "bold", size = 9))

## ---- parallel ----
longest <- setNames(rep(NA_real_, nrow(tg)), tg$target)
for (n in ord) {
  p <- parents_of(ed, n)
  longest[n] <- tg$cost[tg$target == n] + if (length(p)) max(longest[p]) else 0
}
crit_len <- max(longest)
crit_path <- names(which.max(longest))
while (length(parents_of(ed, crit_path[1])) > 0) {
  p <- parents_of(ed, crit_path[1])
  crit_path <- c(p[which.max(longest[p])], crit_path)
}

cost_half <- tg$cost
cost_half[tg$target == "boot"] <- tg$cost[tg$target == "boot"] / 2
longest_half <- setNames(rep(NA_real_, nrow(tg)), tg$target)
for (n in ord) {
  p <- parents_of(ed, n)
  longest_half[n] <- cost_half[tg$target == n] +
    if (length(p)) max(longest_half[p]) else 0
}

makespan <- function(workers) {
  finish <- setNames(rep(NA_real_, nrow(tg)), tg$target)
  free <- rep(0, workers)
  left <- ord
  while (length(left) > 0) {
    ready <- left[sapply(left, function(n) all(!is.na(finish[parents_of(ed, n)])))]
    ready <- ready[order(-tg$cost[match(ready, tg$target)])]
    n <- ready[1]
    dep <- if (length(parents_of(ed, n))) max(finish[parents_of(ed, n)]) else 0
    w <- which.min(free)
    finish[n] <- max(free[w], dep) + tg$cost[tg$target == n]
    free[w] <- finish[n]
    left <- setdiff(left, n)
  }
  max(finish)
}

sched <- data.frame(workers = 1:6)
sched$makespan <- sapply(sched$workers, makespan)
sched$speedup <- total_cost / sched$makespan
print(round(sched, 4))
print(crit_path)
round(c(total_cost_seconds = total_cost,
        critical_path_seconds = crit_len,
        critical_path_targets = length(crit_path),
        theoretical_ceiling = total_cost / crit_len,
        speedup_at_three_workers = sched$speedup[3],
        gain_from_a_fourth_worker = sched$speedup[4] - sched$speedup[3],
        share_of_cost_on_the_critical_path = 100 * cost_of(crit_path) / total_cost,
        critical_path_if_the_bootstrap_were_twice_as_fast = max(longest_half),
        ceiling_if_the_bootstrap_were_twice_as_fast =
          sum(cost_half) / max(longest_half)), 4)
print(longest_half[c("figure", "report", "perm", "boot")])

## ---- fig-parallel ----
ceiling_val <- total_cost / crit_len

ggplot(sched, aes(workers, speedup)) +
  geom_hline(yintercept = ceiling_val, linetype = 2, colour = te_pal$clay,
             linewidth = 0.8) +
  geom_line(colour = te_pal$forest, linewidth = 1) +
  geom_point(colour = te_pal$forest, size = 3.4) +
  geom_text(aes(label = sprintf("%.2f", speedup)), vjust = 1.9, size = 3.2,
            colour = te_pal$ink) +
  annotate("text", x = 3.5, y = ceiling_val + 0.11,
           label = sprintf("ceiling set by the critical path: %.4f", ceiling_val),
           size = 3.2, colour = te_pal$clay) +
  scale_x_continuous(breaks = 1:6) +
  scale_y_continuous(limits = c(0.75, 2.75)) +
  labs(x = "Workers running targets at the same time",
       y = "Speed-up over one worker",
       title = "A third worker is worth having and a fifth is worth nothing") +
  theme_te()

## ---- freeze ----
n_posts <- 634  # posts on this site when the section was written
round(c(posts_when_written = n_posts,
        share_of_post_renders_a_one_post_edit_invalidates = 100 / n_posts,
        site_level_pages_downstream_of_every_post = 3), 4)

## ---- cache-demo ----
dir.create(cache_dir <- tempfile("cache-demo-"))
in_dir <- function(f) file.path(cache_dir, f)
reach_csv <- v0$reach_table[, c("reach", "ept", "tp")]
for (f in c("reach_table.csv", "reach_raw.csv")) write.csv(reach_csv, in_dir(f), row.names = FALSE)
writeLines("recalibrate <- function(d) d", in_dir("helpers.R"))
cached <- function(label, key, body)
  c(sprintf("```{r %s, cache = TRUE%s}", label, key), body,
    sprintf("cat('%s', round(coef(lm(ept ~ log2(tp), data = rt))[[2]], 4))", label), "```")
from_csv <- "rt <- read.csv('reach_table.csv')"
from_helper <- c("source('helpers.R')", "rt <- recalibrate(read.csv('reach_raw.csv'))")
writeLines(c(
  cached("plain", "", from_csv),
  cached("keyed", ", cache.extra = tools::md5sum('reach_table.csv')", from_csv),
  cached("sourced", ", cache.extra = tools::md5sum('reach_raw.csv')", from_helper),
  cached("both", ", cache.extra = tools::md5sum(c('reach_raw.csv', 'helpers.R'))",
         from_helper)), in_dir("report.Rmd"))
knit_once <- function() {
  cmd <- sprintf(".libPaths(%s); setwd(%s); knitr::knit('report.Rmd', quiet = TRUE)",
                 deparse1(.libPaths()), deparse1(cache_dir))
  status <- system2(file.path(R.home("bin"), "Rscript"), c("--vanilla", "-e", shQuote(cmd)),
                    stdout = FALSE, stderr = FALSE)
  md <- readLines(in_dir("report.md"))
  hit <- Filter(function(h) length(h) == 3, regmatches(md, regexec("^## (\\w+) (\\S+)$", md)))
  stopifnot(status == 0, length(hit) == 4)
  setNames(as.numeric(sapply(hit, `[`, 3)), sapply(hit, `[`, 2))
}
knit_1 <- knit_once()
writeLines(c("recalibrate <- function(d) {    # what rec$chem does with chem_fix = TRUE",
             "  i <- d$reach %in% c(7, 19); d$tp[i] <- d$tp[i] * c(0.42, 0.55); d }"),
           in_dir("helpers.R"))
source(in_dir("helpers.R"))
write.csv(recalibrate(reach_csv), in_dir("reach_table.csv"), row.names = FALSE)
knit_2 <- knit_once()
unlink(cache_dir, recursive = TRUE)
v_fix <- build_all(modifyList(settings, list(chem_fix = TRUE)))
new_slope <- round(v_fix$report[["slope"]], 4)
stopifnot(all(knit_1 == round(v0$report[["slope"]], 4)), new_slope != knit_1[["plain"]],
          knit_2[c("plain", "sourced")] == knit_1[c("plain", "sourced")],
          abs(knit_2[c("keyed", "both")] - new_slope) < 1e-9)
data.frame(first_knit = knit_1, second_knit = knit_2[names(knit_1)],
           pipeline_after_recalibration = new_slope)
