# Granger-causality teaching helpers for Module 9. Base R only.

# Compare the unweighted, full-rank, nested OLS fits used in the notes.
granger_nested_test <- function(restricted, unrestricted) {
  r <- model.frame(restricted)
  u <- model.frame(unrestricted)
  xr <- model.matrix(restricted)
  xu <- model.matrix(unrestricted)
  stopifnot(inherits(restricted, "lm"), inherits(unrestricted, "lm"),
            is.null(restricted$weights), is.null(unrestricted$weights),
            identical(rownames(r), rownames(u)),
            isTRUE(all.equal(model.response(r), model.response(u))),
            all(colnames(xr) %in% colnames(xu)),
            isTRUE(all.equal(as.vector(xr), as.vector(xu[, colnames(xr), drop = FALSE]))),
            restricted$rank == ncol(xr), unrestricted$rank == ncol(xu))
  n <- nobs(unrestricted)
  k_u <- unrestricted$rank
  q <- k_u - restricted$rank
  rss_r <- sum(residuals(restricted)^2)
  rss_u <- sum(residuals(unrestricted)^2)
  stopifnot(q > 0, n > k_u, rss_u > 0, rss_r >= rss_u - 1e-10)
  statistic <- ((rss_r - rss_u) / q) / (rss_u / (n - k_u))
  data.frame(n = n, q = q, k_U = k_u, RSS_R = rss_r, RSS_U = rss_u,
             F = statistic, df2 = n - k_u,
             p_value = pf(statistic, q, n - k_u, lower.tail = FALSE))
}

# BG auxiliary regression: drop the first 'order' rows for all its columns.
# This is an asymptotic diagnostic, not evidence of exogeneity.
granger_bg_test <- function(fit, order = 12L) {
  e <- as.numeric(residuals(fit))
  x <- model.matrix(fit)
  stopifnot(order >= 1, order == as.integer(order), length(e) > order,
            "(Intercept)" %in% colnames(x))
  lagged <- sapply(seq_len(order), function(j) c(rep(NA_real_, j), head(e, -j)))
  keep <- (order + 1L):length(e)
  design <- cbind(x[keep, , drop = FALSE], lagged[keep, , drop = FALSE])
  auxiliary <- lm.fit(design, e[keep])
  stopifnot(auxiliary$rank == ncol(design), nrow(design) > ncol(design))
  r_squared <- 1 - sum(auxiliary$residuals^2) / sum((e[keep] - mean(e[keep]))^2)
  lm_statistic <- length(keep) * r_squared
  data.frame(LM = lm_statistic, order = order,
             p_value = pchisq(lm_statistic, order, lower.tail = FALSE))
}
