# Testing isometry and comparing slopes
# https://tidyecology.com/posts/testing-isometry-and-comparing-slopes/
#
# 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-15

## ---- pitman ----
sma_slope <- function(x, y) sign(cor(x, y)) * sd(y) / sd(x)

pitman_test <- function(x, y, b0) {
  resid_score <- y - b0 * x
  fit_score   <- y + b0 * x
  cor.test(resid_score, fit_score)
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- calib-slope ----
b_null <- 0.75
n_ind <- 60
n_mc <- 3000
sd_ex <- 0.30

set.seed(43811)
res <- t(vapply(seq_len(n_mc), function(i) {
  xt <- rnorm(n_ind, 3, 0.8)
  x <- xt + rnorm(n_ind, 0, sd_ex)
  y <- b_null * xt + rnorm(n_ind, 0, b_null * sd_ex)
  co <- summary(lm(y ~ x))$coefficients[2, ]
  p_ols <- 2 * pt(-abs((co[1] - b_null) / co[2]), n_ind - 2)
  c(p_ols, pitman_test(x, y, b_null)$p.value, co[1], sma_slope(x, y))
}, numeric(4)))
c(ols_reject = mean(res[, 1] < 0.05), pitman_reject = mean(res[, 2] < 0.05),
  mean_ols = mean(res[, 3]), mean_sma = mean(res[, 4]))

## ---- sweep-error ----
sweep_x <- c(0, 0.10, 0.20, 0.30, 0.40)
sw <- do.call(rbind, lapply(seq_along(sweep_x), function(k) {
  su <- sweep_x[k]
  set.seed(9000 + k)
  o <- t(vapply(seq_len(1500), function(i) {
    xt <- rnorm(n_ind, 3, 0.8)
    x <- xt + rnorm(n_ind, 0, su)
    y <- b_null * xt + rnorm(n_ind, 0, sqrt((b_null * su)^2 + 0.12^2))
    co <- summary(lm(y ~ x))$coefficients[2, ]
    c(2 * pt(-abs((co[1] - b_null) / co[2]), n_ind - 2),
      pitman_test(x, y, b_null)$p.value)
  }, numeric(2)))
  data.frame(sd_error_x = su,
             ols = round(mean(o[, 1] < 0.05), 3),
             pitman_sma = round(mean(o[, 2] < 0.05), 3))
}))
sw

## ---- fig-sizes ----
library(ggplot2)
theme_te <- function(base_size = 11) {
  theme_minimal(base_size = base_size) +
    theme(
      panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
      plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
      panel.background = element_rect(fill = "#f5f4ee", colour = NA),
      axis.title = element_text(colour = "#2c3a31"),
      axis.text  = element_text(colour = "#5d6b61"),
      legend.text = element_text(colour = "#2c3a31"), legend.title = element_blank(),
      plot.title = element_text(colour = "#16241d", face = "bold", size = base_size + 1),
      plot.subtitle = element_text(colour = "#5d6b61", size = base_size - 1)
    )
}
long <- rbind(data.frame(sd_error_x = sw$sd_error_x, rate = sw$ols, method = "OLS t-test"),
              data.frame(sd_error_x = sw$sd_error_x, rate = sw$pitman_sma, method = "Pitman / SMA"))
ggplot(long, aes(sd_error_x, rate, colour = method)) +
  geom_hline(yintercept = 0.05, colour = "#93a87f", linetype = "dashed", linewidth = 0.5) +
  geom_line(linewidth = 0.9) + geom_point(size = 2) +
  scale_colour_manual(values = c(`OLS t-test` = "#c9b458", `Pitman / SMA` = "#b5534e")) +
  labs(x = "standard deviation of measurement error in log body size",
       y = "rejection rate under a true null",
       title = "Two tests, two failure modes",
       subtitle = "dashed line: the nominal five per cent level") +
  theme_te() + theme(legend.position = "top")

## ---- common-slope ----
lr_common <- function(xs, ys) {
  pen <- function(b) {
    -sum(vapply(seq_along(xs), function(i) {
      rr <- cor(ys[[i]] - b * xs[[i]], ys[[i]] + b * xs[[i]])
      length(xs[[i]]) * log(1 - rr^2)
    }, numeric(1)))
  }
  own <- vapply(seq_along(xs), function(i) sma_slope(xs[[i]], ys[[i]]), numeric(1))
  op <- optimize(pen, c(min(own) * 0.5, max(own) * 1.5))
  list(stat = op$objective, common = op$minimum,
       p = pchisq(op$objective, length(xs) - 1, lower.tail = FALSE))
}

gen_group <- function(n, b, m, sd_size = 0.55, sd_err = 0.16) {
  xt <- rnorm(n, m, sd_size)
  list(x = xt + rnorm(n, 0, sd_err * 0.6),
       y = b * xt + rnorm(n, 0, b * sd_err * 0.6) + rnorm(n, 0, sd_err))
}

## ---- calib-common ----
set.seed(4382)
null_p <- replicate(1500, {
  g <- lapply(1:3, function(k) gen_group(45, 0.75, 3))
  lr_common(lapply(g, `[[`, "x"), lapply(g, `[[`, "y"))$p
})
set.seed(4383)
alt_p <- replicate(1000, {
  g <- list(gen_group(45, 0.75, 3), gen_group(45, 0.75, 3), gen_group(45, 0.92, 3))
  lr_common(lapply(g, `[[`, "x"), lapply(g, `[[`, "y"))$p
})
set.seed(4384)
naive_p <- replicate(1000, {
  g <- lapply(1:3, function(k) gen_group(45, 0.75, 3))
  d <- do.call(rbind, lapply(seq_along(g), function(i)
    data.frame(x = g[[i]]$x, y = g[[i]]$y, grp = factor(i))))
  anova(lm(y ~ x * grp, d))["x:grp", "Pr(>F)"]
})
c(lr_null = mean(null_p < 0.05), lr_power = mean(alt_p < 0.05),
  naive_interaction_null = mean(naive_p < 0.05))

## ---- elevation ----
set.seed(43822)
b_common <- 0.75
n_grp <- 70
sd_ex2 <- 0.1733
make_group <- function(mean_size) {
  xt <- rnorm(n_grp, mean_size, 0.45)
  list(x = xt + rnorm(n_grp, 0, sd_ex2),
       y = b_common * xt + rnorm(n_grp, 0, b_common * sd_ex2))
}
grp_a <- make_group(2.6)
grp_b <- make_group(3.4)

fit_common <- lr_common(list(grp_a$x, grp_b$x), list(grp_a$y, grp_b$y))
bc <- fit_common$common
res_score <- function(g) g$y - bc * g$x
fit_score <- function(g) g$y + bc * g$x

t_raw <- t.test(grp_a$y, grp_b$y)
t_elev <- t.test(res_score(grp_a), res_score(grp_b))
t_shift <- t.test(fit_score(grp_a), fit_score(grp_b))
c(common_slope = bc, p_raw_means = t_raw$p.value,
  p_elevation = t_elev$p.value, p_shift_along = t_shift$p.value)

## ---- fig-shift ----
dg <- rbind(data.frame(x = grp_a$x, y = grp_a$y, grp = "group A"),
            data.frame(x = grp_b$x, y = grp_b$y, grp = "group B"))
icept <- mean(dg$y) - bc * mean(dg$x)
shift_e <- formatC(t_shift$p.value, format = "e", digits = 1)
ggplot(dg, aes(x, y, colour = grp)) +
  geom_abline(slope = bc, intercept = icept, colour = "#93a87f", linewidth = 0.8) +
  geom_point(alpha = 0.65, size = 1.8) +
  scale_colour_manual(values = c(`group A` = "#275139", `group B` = "#c9b458")) +
  labs(x = "log body size", y = "log trait",
       title = "Same line, different place on it",
       subtitle = bquote(.(sprintf("common slope %.3f; elevation p = %.2f, shift along the axis p = ",
                                   bc, t_elev$p.value)) * .(sub("e.*", "", shift_e)) %*%
                           10^.(as.integer(sub(".*e", "", shift_e))))) +
  theme_te() + theme(legend.position = "top")
