# Front-door adjustment when no instrument exists
# https://tidyecology.com/posts/front-door-adjustment/
#
# 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-11-13

## ---- 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))
}

a_gap <- 1.2; b_rec <- 0.9    # grazing into gap area, gap area into recruitment
g_ux  <- 0.9; g_uy  <- 1.1    # fertility into grazing, fertility into recruitment
n_plot <- 400; n_rep <- 500; ci_pct <- 95
eff_true <- a_gap * b_rec; direct_true <- 0L

sim_plots <- function(n, a = a_gap, b = b_rec, leak = 0) {
  fert  <- rnorm(n); graze <- g_ux * fert + rnorm(n)
  gap   <- a * graze + rnorm(n)
  seedl <- b * gap + leak * graze + g_uy * fert + rnorm(n)
  data.frame(graze = graze, gap = gap, seedl = seedl)
}

## ---- fig-dag ----
fert_x <- 0.75; fert_y <- 1.3          # fertility offset, so it is not over gap area
node <- data.frame(x = c(0, 1.5, 3, fert_x), y = c(0, 0, 0, fert_y),
  lab = c("grazing\nintensity", "gap\narea", "seedling\nrecruitment",
          "soil fertility\n(unmeasured)"))

trim <- function(x1, y1, x2, y2, pad_a, pad_b) {   # shorten an edge at both ends
  len <- sqrt((x2 - x1)^2 + (y2 - y1)^2)
  data.frame(x = x1 + (x2 - x1) * pad_a / len, y = y1 + (y2 - y1) * pad_a / len,
             xend = x2 - (x2 - x1) * pad_b / len, yend = y2 - (y2 - y1) * pad_b / len)
}
solid_edge <- rbind(trim(0, 0, 1.5, 0, 0.42, 0.30), trim(1.5, 0, 3, 0, 0.30, 0.55))
dash_edge  <- rbind(trim(fert_x, fert_y, 0, 0, 0.42, 0.36),
                    trim(fert_x, fert_y, 3, 0, 0.42, 0.42))
arrow_head <- arrow(length = unit(0.017, "npc"), type = "closed")

ggplot(node, aes(x, y)) +
  geom_segment(data = solid_edge, aes(x, y, xend = xend, yend = yend),
               colour = te_forest, linewidth = 0.8, arrow = arrow_head) +
  geom_segment(data = dash_edge, aes(x, y, xend = xend, yend = yend), colour = te_rust,
               linewidth = 0.8, linetype = "dashed", arrow = arrow_head) +
  annotate("curve", x = 0.2, y = -0.22, xend = 2.8, yend = -0.22, curvature = 0.28,
           colour = te_gold, linewidth = 0.7, linetype = "dotted",
           arrow = arrow_head) +
  annotate("text", x = 1.5, y = -0.66, label = "direct effect: assumed absent",
           colour = te_gold, size = 3.6) +
  geom_text(aes(label = lab), colour = te_ink, size = 3.9, lineheight = 0.95) +
  scale_x_continuous(limits = c(-0.55, 3.55)) +
  scale_y_continuous(limits = c(-0.95, 1.65)) +
  labs(title = "One measured mechanism, one unmeasured common cause") +
  theme_datasheet() +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        axis.title = element_blank(), axis.text = element_blank())

## ---- naive ----
three_est <- function(dat) {
  fit_a <- lm(gap ~ graze, data = dat); fit_b <- lm(seedl ~ gap + graze, data = dat)
  fit_n <- lm(seedl ~ graze, data = dat)
  a_hat <- coef(fit_a)[["graze"]]; b_hat <- coef(fit_b)[["gap"]]
  se_fd <- sqrt(b_hat^2 * summary(fit_a)$coefficients["graze", 2]^2 +
                a_hat^2 * summary(fit_b)$coefficients["gap", 2]^2)
  ci_n <- confint(fit_n)["graze", ]
  c(naive = coef(fit_n)[["graze"]], adjm = coef(fit_b)[["graze"]],
    fd = a_hat * b_hat, a_hat = a_hat, b_hat = b_hat,
    cov_n = as.numeric(ci_n[1] <= eff_true && eff_true <= ci_n[2]),
    cov_fd = as.numeric(abs(a_hat * b_hat - eff_true) <= 1.96 * se_fd))
}

set.seed(4021)
main_sim    <- replicate(n_rep, three_est(sim_plots(n_plot)))
main_mean   <- rowMeans(main_sim)
main_spread <- apply(main_sim, 1, sd)
naive_mean <- main_mean[["naive"]]
naive_bias <- naive_mean - eff_true
naive_cov  <- 100 * main_mean[["cov_n"]]
naive_pct  <- 100 * naive_bias / eff_true

## ---- frontdoor ----
front_door <- function(dat) {
  a_hat <- coef(lm(gap ~ graze, data = dat))[["graze"]]
  b_hat <- coef(lm(seedl ~ gap + graze, data = dat))[["gap"]]
  a_hat * b_hat
}

fd_mean <- main_mean[["fd"]]; fd_bias <- fd_mean - eff_true
fd_cov  <- 100 * main_mean[["cov_fd"]]
a_mean  <- main_mean[["a_hat"]]; b_mean <- main_mean[["b_hat"]]
mc_se   <- main_spread[["fd"]] / sqrt(n_rep)
rep_mcse <- 100 * sqrt(0.01 * ci_pct * (1 - 0.01 * ci_pct) / n_rep)
adjm_mean <- main_mean[["adjm"]]
b_bias    <- b_mean - b_rec

## ---- fig-three ----
est_long <- data.frame(est = c(main_sim["naive", ], main_sim["adjm", ], main_sim["fd", ]),
  which_est = rep(c("naive slope", "adjust for the mediator", "front-door"), each = n_rep))
est_long$which_est <- factor(est_long$which_est,
  levels = c("adjust for the mediator", "front-door", "naive slope"))

ggplot(est_long, aes(est, fill = which_est, colour = which_est)) +
  geom_density(alpha = 0.35, linewidth = 0.7) +
  geom_vline(xintercept = eff_true, linetype = "dashed", colour = te_ink,
             linewidth = 0.7) +
  annotate("text", x = eff_true, y = 0, label = "true total effect",
           colour = te_ink, size = 3.4, hjust = -0.06, vjust = -0.7) +
  scale_fill_manual(values = c(te_gold, te_forest, te_rust), name = NULL) +
  scale_colour_manual(values = c(te_gold, te_forest, te_rust), name = NULL) +
  labs(x = "estimated effect of grazing on recruitment", y = "density",
       title = "Only one of the three is aimed at the total effect",
       subtitle = sprintf("%d surveys of %d quadrats, fertility never measured",
                          n_rep, n_plot)) +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- coverage ----
fd_parts <- function(graze, gap, seedl) {
  n_obs <- length(graze)
  gz <- graze - mean(graze); gp <- gap - mean(gap); sy <- seedl - mean(seedl)
  s_zz <- sum(gz * gz); s_pp <- sum(gp * gp); s_pz <- sum(gp * gz)
  a_hat <- s_pz / s_zz; d_two <- s_pp * s_zz - s_pz^2
  se_a  <- sqrt(sum((gp - a_hat * gz)^2) / ((n_obs - 2) * s_zz))
  b_hat <- (s_zz * sum(gp * sy) - s_pz * sum(gz * sy)) / d_two
  z_hat <- (s_pp * sum(gz * sy) - s_pz * sum(gp * sy)) / d_two
  se_b  <- sqrt(sum((sy - b_hat * gp - z_hat * gz)^2) / (n_obs - 3) * s_zz / d_two)
  c(est = a_hat * b_hat, se = sqrt(b_hat^2 * se_a^2 + a_hat^2 * se_b^2),
    t_a = a_hat / se_a, t_b = b_hat / se_b)
}
fd_of <- function(dat) fd_parts(dat$graze, dat$gap, dat$seedl)

set.seed(2088); one_check <- sim_plots(n_plot)
stopifnot(all.equal(fd_of(one_check)[["est"]], front_door(one_check)))

n_cov <- 20000
regime <- data.frame(n = c(n_plot, n_plot, 50), a = c(a_gap, 0.1, 0.35),
                     b = c(b_rec, b_rec, 0.35))
set.seed(5108)
regime <- cbind(regime, t(vapply(seq_len(nrow(regime)), function(i) {
  reps <- replicate(n_cov, fd_of(sim_plots(regime$n[i], regime$a[i], regime$b[i])))
  hit  <- abs(reps["est", ] - regime$a[i] * regime$b[i]) <= 1.96 * reps["se", ]
  c(cover = 100 * mean(hit), mcse = 100 * sqrt(mean(hit) * (1 - mean(hit)) / n_cov),
    t_a = mean(reps["t_a", ]), t_b = mean(reps["t_b", ]),
    skew = mean((reps["est", ] - mean(reps["est", ]))^3) / sd(reps["est", ])^3)
}, numeric(5))))

## ---- bootci ----
n_bcov <- 1500; n_boot <- 299
w_n <- regime$n[3]; w_true <- regime$a[3] * regime$b[3]
set.seed(6613)
pair_hit <- replicate(n_bcov, {
  dat <- sim_plots(w_n, regime$a[3], regime$b[3])
  pt  <- fd_of(dat)
  bs  <- replicate(n_boot, { k <- sample.int(w_n, replace = TRUE)
    fd_parts(dat$graze[k], dat$gap[k], dat$seedl[k])[["est"]] })
  qq <- quantile(bs, c(0.025, 0.975))
  c(delta = as.numeric(abs(pt[["est"]] - w_true) <= 1.96 * pt[["se"]]),
    boot  = as.numeric(qq[[1]] <= w_true && w_true <= qq[[2]]))
})
pair_gain <- pair_hit["boot", ] - pair_hit["delta", ]
pair_diff <- 100 * mean(pair_gain); pair_se <- 100 * sd(pair_gain) / sqrt(n_bcov)

## ---- leakage ----
leak_set <- c(0, 0.1, 0.2, 0.4)
leak_one <- function(n) {
  fert  <- rnorm(n); graze <- g_ux * fert + rnorm(n)
  gap   <- a_gap * graze + rnorm(n); noise <- g_uy * fert + rnorm(n)
  a_hat <- coef(lm(gap ~ graze))[["graze"]]
  vapply(leak_set, function(lk) {
    seedl <- b_rec * gap + lk * graze + noise
    a_hat * coef(lm(seedl ~ gap + graze))[["gap"]] }, 0)
}

set.seed(9155)
leak_sim <- replicate(n_rep, leak_one(n_plot))
leak_tab <- data.frame(leak = leak_set, est = rowMeans(leak_sim),
                       truth = eff_true + leak_set)
leak_tab$bias <- leak_tab$est - leak_tab$truth
leak_tab$rel <- 100 * leak_tab$bias / leak_tab$truth

max_shift  <- max(abs(sweep(leak_sim, 2, leak_sim[1, ], "-")))
leak_slope <- coef(lm(bias ~ leak, data = leak_tab))[["leak"]]
leak_worst <- leak_tab$rel[length(leak_set)]; leak_mid <- leak_tab$rel[3]

## ---- fp-guard-1 ----
stopifnot(max_shift < 1e-10)

## ---- fig-leak ----
leak_long <- data.frame(leak = rep(leak_tab$leak, 2),
  value = c(leak_tab$truth, leak_tab$est),
  series = rep(c("true total effect", "front-door estimate"), each = nrow(leak_tab)))

p_gap <- ggplot(leak_long, aes(leak, value, colour = series)) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.6) +
  scale_colour_manual(values = c(te_forest, te_rust), name = NULL) +
  labs(x = "direct grazing effect that bypasses gaps",
       y = "seedlings per square metre", title = "The estimate does not move") +
  theme_datasheet() + theme(legend.position = "bottom")

p_bias <- ggplot(leak_tab, aes(leak, bias)) +
  geom_abline(intercept = 0, slope = -1, colour = te_line, linewidth = 1.4) +
  geom_point(size = 3, colour = te_ink) +
  scale_x_continuous(expand = expansion(mult = 0.1)) +
  scale_y_continuous(expand = expansion(mult = 0.12)) +
  labs(x = "direct grazing effect that bypasses gaps", y = "estimate minus truth",
       title = "So the bias is the leak", subtitle = "grey: a line of slope minus one") +
  theme_datasheet()

p_gap + p_bias + plot_annotation(theme = theme_datasheet())

## ---- probe ----
n_probe <- 400; n_prep <- 500; probe_leak <- 0.3; alpha_lev <- 0.05
probe_mcse <- 100 * sqrt(alpha_lev * (1 - alpha_lev) / n_prep)

probe_run <- function(via_dung, via_graze, rain_effect) {
  fert  <- rnorm(n_probe); rain <- rnorm(n_probe)
  graze <- g_ux * fert + rnorm(n_probe)
  gap   <- a_gap * graze + rnorm(n_probe)
  dung  <- 0.7 * graze + rnorm(n_probe)      # descendant of grazing, not of gap
  seedl <- b_rec * gap + via_dung * dung + via_graze * graze + rain_effect * rain +
           g_uy * fert + rnorm(n_probe)
  pv <- summary(lm(seedl ~ gap + graze + dung + rain))$coefficients[c("dung", "rain"), 4]
  c(p_dung = pv[[1]], p_rain = pv[[2]],
    fd = coef(lm(gap ~ graze))[["graze"]] * coef(lm(seedl ~ gap + graze))[["gap"]])
}

probe_rate <- function(via_dung, via_graze, rain_effect) {
  out <- replicate(n_prep, probe_run(via_dung, via_graze, rain_effect))
  c(rej_dung = 100 * mean(out["p_dung", ] < alpha_lev),
    rej_rain = 100 * mean(out["p_rain", ] < alpha_lev), fd = mean(out["fd", ]))
}

set.seed(7740)
probe_rain <- probe_rate(0, 0, 0.8)         # as drawn, plus a rainfall effect
probe_seen <- probe_rate(probe_leak, 0, 0)  # a leak running through dung
probe_hid  <- probe_rate(0, probe_leak, 0)  # a leak bypassing dung

## ---- sweep ----
n_sweep <- 300; quart <- c(0.25, 0.5, 0.75)
str_set <- c(0.05, 0.1, 0.2, 0.4, 0.8, 1.2)

set.seed(3310)
fd_sweep <- as.data.frame(t(vapply(str_set, function(a) {
  reps <- replicate(n_sweep, front_door(sim_plots(n_plot, a, eff_true / a)))
  qq <- quantile(reps, quart)
  c(strength = a, truth = eff_true, lo = qq[[1]], med = qq[[2]], hi = qq[[3]])
}, numeric(5))))
fd_sweep$width <- fd_sweep$hi - fd_sweep$lo; fd_sweep$relw <- fd_sweep$width / eff_true

set.seed(3311)
iv_sweep <- as.data.frame(t(vapply(str_set, function(cz) {
  reps <- replicate(n_sweep, {
    fert  <- rnorm(n_plot); inst <- rnorm(n_plot)
    graze <- cz * inst + g_ux * fert + rnorm(n_plot)
    gap   <- a_gap * graze + rnorm(n_plot)
    seedl <- b_rec * gap + g_uy * fert + rnorm(n_plot)
    cov(inst, seedl) / cov(inst, graze)
  })
  qq <- quantile(reps, quart)
  c(strength = cz, truth = eff_true, lo = qq[[1]], med = qq[[2]], hi = qq[[3]])
}, numeric(5))))
iv_sweep$width <- iv_sweep$hi - iv_sweep$lo; iv_sweep$relw <- iv_sweep$width / eff_true

weakest <- 1; strongest <- length(str_set)
fd_rel_ratio <- fd_sweep$relw[weakest] / fd_sweep$relw[strongest]
iv_rel_ratio <- iv_sweep$relw[weakest] / iv_sweep$relw[strongest]
iv_drift <- iv_sweep$med[weakest] / eff_true; naive_ratio <- naive_mean / eff_true
fd_ratio_lo  <- min(fd_sweep$med) / eff_true; fd_ratio_hi <- max(fd_sweep$med) / eff_true
b_weakest    <- eff_true / str_set[weakest]

## ---- fig-weak ----
scaled_band <- function(tab) data.frame(strength = tab$strength,
  med = tab$med / tab$truth, lo = tab$lo / tab$truth, hi = tab$hi / tab$truth)
fd_band <- scaled_band(fd_sweep); iv_band <- scaled_band(iv_sweep)

band_panel <- function(tab, shade, panel_title, panel_sub, xlab) {
  ggplot(tab, aes(strength, med)) +
    geom_ribbon(aes(ymin = lo, ymax = hi), fill = shade, alpha = 0.25) +
    geom_hline(yintercept = 1, linetype = "dashed", colour = te_ink, linewidth = 0.6) +
    geom_line(colour = shade, linewidth = 0.9) +
    scale_x_log10() + coord_cartesian(ylim = c(0, 2.4)) +
    labs(x = xlab, y = "estimate as a multiple of the truth",
         title = panel_title, subtitle = panel_sub) +
    theme_datasheet()
}

p_fd <- band_panel(fd_band, te_forest, "Front-door: multiply",
  "band: interquartile range", "grazing to gap coefficient")
p_iv <- band_panel(iv_band, te_rust, "Instrument: divide",
  "dotted: the naive slope", "instrument to grazing coefficient") +
  geom_hline(yintercept = naive_ratio, linetype = "dotted", colour = te_gold,
             linewidth = 0.8)

p_fd + p_iv + plot_annotation(theme = theme_datasheet())
