# SMA or OLS for a scaling exponent?
# https://tidyecology.com/posts/sma-versus-ols-for-scaling-exponents/
#
# 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-15

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

deming_slope <- function(x, y, delta) {
  sxx <- var(x); syy <- var(y); sxy <- cov(x, y)
  (syy - delta * sxx + sqrt((syy - delta * sxx)^2 + 4 * delta * sxy^2)) / (2 * sxy)
}

set.seed(380)
n_sp <- 300
x_obs <- rnorm(n_sp, 3, 0.8)
y_obs <- 0.75 * x_obs + rnorm(n_sp, 0, 0.45)

b_ols <- unname(coef(lm(y_obs ~ x_obs))[2])
b_sma <- sma_slope(x_obs, y_obs)
r_obs <- cor(x_obs, y_obs)
c(ols = b_ols, sma = b_sma, r = r_obs,
  ols_over_r = b_ols / r_obs,
  gap = abs(b_sma - b_ols / r_obs))

## ---- ratio-table ----
rr <- c(0.99, 0.95, 0.90, 0.80, 0.70, 0.50)
data.frame(correlation = rr, sma_over_ols = round(1 / rr, 3))

## ---- fig-two-lines ----
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)
    )
}
dd <- data.frame(x = x_obs, y = y_obs)
int_ols <- mean(y_obs) - b_ols * mean(x_obs)
int_sma <- mean(y_obs) - b_sma * mean(x_obs)
ggplot(dd, aes(x, y)) +
  geom_point(colour = "#275139", alpha = 0.4, size = 1.6) +
  geom_abline(aes(slope = b_ols, intercept = int_ols, colour = "OLS"), linewidth = 0.9) +
  geom_abline(aes(slope = b_sma, intercept = int_sma, colour = "SMA"), linewidth = 0.9) +
  scale_colour_manual(values = c(OLS = "#c9b458", SMA = "#b5534e")) +
  labs(x = "log body size", y = "log trait",
       title = "Two lines through one cloud",
       subtitle = sprintf("r = %.3f, so the SMA slope is exactly 1/r times the OLS slope", r_obs)) +
  theme_te() + theme(legend.position = "top")

## ---- sma-is-deming ----
delta_obs <- var(y_obs) / var(x_obs)
c(sma = b_sma,
  deming_at_var_ratio = deming_slope(x_obs, y_obs, delta_obs),
  gap = abs(b_sma - deming_slope(x_obs, y_obs, delta_obs)))

## ---- sma-condition ----
b_str <- 0.75
n_str <- 400
n_mc <- 2000

run_config <- function(sd_ex, sd_ey, seed) {
  set.seed(seed)
  out <- t(vapply(seq_len(n_mc), function(i) {
    xt <- rnorm(n_str, 3, 0.8)
    x <- xt + rnorm(n_str, 0, sd_ex)
    y <- b_str * xt + rnorm(n_str, 0, sd_ey)
    c(unname(coef(lm(y ~ x))[2]),
      sma_slope(x, y),
      deming_slope(x, y, sd_ey^2 / sd_ex^2))
  }, numeric(3)))
  colMeans(out)
}

cfg <- list(c(0.30, 0.225), c(0.30, 0.300), c(0.30, 0.100), c(0.30, 0.450))
tab <- do.call(rbind, lapply(seq_along(cfg), function(k) {
  m <- run_config(cfg[[k]][1], cfg[[k]][2], 4380 + k)
  data.frame(sd_ex = cfg[[k]][1], sd_ey = cfg[[k]][2],
             err_ratio = round(cfg[[k]][2]^2 / cfg[[k]][1]^2, 3),
             ols = round(m[1], 4), sma = round(m[2], 4),
             deming_true = round(m[3], 4))
}))
tab

## ---- fig-sweep ----
set.seed(4390)
sd_ex_fix <- 0.30
ratios <- c(0.08, 0.15, 0.30, 0.5625, 1.0, 1.8, 3.2)
swp <- do.call(rbind, lapply(ratios, function(rt) {
  sd_ey <- sd_ex_fix * sqrt(rt)
  o <- t(vapply(seq_len(700), function(i) {
    xt <- rnorm(n_str, 3, 0.8)
    x <- xt + rnorm(n_str, 0, sd_ex_fix)
    y <- b_str * xt + rnorm(n_str, 0, sd_ey)
    c(unname(coef(lm(y ~ x))[2]), sma_slope(x, y))
  }, numeric(2)))
  data.frame(ratio = rt, method = c("OLS", "SMA"), est = colMeans(o))
}))
ggplot(swp, aes(ratio, est, colour = method)) +
  geom_hline(yintercept = b_str, colour = "#93a87f", linewidth = 0.5, linetype = "dashed") +
  geom_line(linewidth = 0.9) + geom_point(size = 2) +
  scale_x_log10() +
  scale_colour_manual(values = c(OLS = "#c9b458", SMA = "#b5534e")) +
  labs(x = "error variance ratio, var(e_y) / var(e_x)", y = "mean estimated exponent",
       title = "Only one ratio makes the SMA unbiased",
       subtitle = sprintf("dashed line: true exponent %.2f; the crossing sits at b squared = %.4f",
                          b_str, b_str^2)) +
  theme_te() + theme(legend.position = "top")

## ---- equation-error ----
set.seed(3801)
xt <- rnorm(n_str, 3, 0.8)
x_clean <- xt
y_eqn <- b_str * xt + rnorm(n_str, 0, 0.30)
c(true_b = b_str,
  ols = unname(coef(lm(y_eqn ~ x_clean))[2]),
  sma = sma_slope(x_clean, y_eqn))
