# Reproducible known-truth figures for the ordination lesson.
# Run from the repository root:
#   Rscript tutorial/downloads/make-ordination-teaching.R

library(ggplot2)
library(patchwork)

set.seed(20260911)

out_fig <- file.path("tutorial", "figures")
out_data <- file.path("tutorial", "downloads")
dir.create(out_fig, recursive = TRUE, showWarnings = FALSE)
dir.create(out_data, recursive = TRUE, showWarnings = FALSE)

traits <- c("mass", "gizzard", "BMR", "activity", "feeding", "exploration")

simulate_two_level <- function(lambda_B, lambda_W, psi_B, psi_W,
                               n_individual = 80L, n_occasion = 6L) {
  n_trait <- nrow(lambda_B)
  d_B <- ncol(lambda_B)
  d_W <- ncol(lambda_W)
  z_B <- matrix(rnorm(n_individual * d_B), ncol = d_B)
  z_W <- matrix(rnorm(n_individual * n_occasion * d_W), ncol = d_W)
  s_B <- matrix(rnorm(n_individual * n_trait,
                       sd = rep(sqrt(diag(psi_B)), each = n_individual)),
                ncol = n_trait)
  s_W <- matrix(rnorm(n_individual * n_occasion * n_trait,
                       sd = rep(sqrt(diag(psi_W)),
                                each = n_individual * n_occasion)),
                ncol = n_trait)

  records <- expand.grid(
    individual = seq_len(n_individual), occasion = seq_len(n_occasion),
    KEEP.OUT.ATTRS = FALSE
  )
  records <- records[order(records$individual, records$occasion), ]
  records$occasion_id <- seq_len(nrow(records))
  y <- matrix(NA_real_, nrow(records), n_trait)
  for (row in seq_len(nrow(records))) {
    i <- records$individual[row]
    j <- records$occasion_id[row]
    y[row, ] <- lambda_B %*% z_B[i, ] + s_B[i, ] +
      lambda_W %*% z_W[j, ] + s_W[j, ]
  }
  colnames(y) <- traits
  list(
    data = cbind(records, as.data.frame(y)),
    z_B = z_B, z_W = z_W,
    sigma_B = lambda_B %*% t(lambda_B) + psi_B,
    sigma_W = lambda_W %*% t(lambda_W) + psi_W
  )
}

make_score_strip <- function(scores, title, xlab) {
  dat <- data.frame(score = scores[, 1L], y = 0)
  ggplot(dat, aes(x = score, y = y)) +
    geom_vline(xintercept = 0, linewidth = 0.35, linetype = "dashed", colour = "grey45") +
    geom_jitter(width = 0, height = 0.11, alpha = 0.35, size = 1.15,
                colour = "#173f5f") +
    scale_y_continuous(NULL, breaks = NULL) +
    labs(title = title, x = xlab) +
    theme_minimal(base_size = 11) +
    theme(plot.title = element_text(face = "bold"), panel.grid.minor = element_blank())
}

make_lollipop <- function(loadings, title) {
  dat <- data.frame(trait = factor(traits, levels = rev(traits)),
                    loading = as.numeric(loadings[, 1L]))
  ggplot(dat, aes(x = loading, y = trait)) +
    geom_vline(xintercept = 0, linewidth = 0.35, linetype = "dashed", colour = "grey45") +
    geom_segment(aes(x = 0, xend = loading, yend = trait), linewidth = 0.7,
                 colour = "#e48624") +
    geom_point(size = 2.2, colour = "#e48624") +
    labs(title = title, x = "Known loading", y = NULL) +
    theme_minimal(base_size = 11) +
    theme(plot.title = element_text(face = "bold"), panel.grid.minor = element_blank())
}

make_biplot <- function(scores, loadings, title, point_label) {
  score <- data.frame(axis_1 = scores[, 1L], axis_2 = scores[, 2L])
  scale_arrow <- 0.72 * min(
    diff(range(score$axis_1)) / diff(range(loadings[, 1L])),
    diff(range(score$axis_2)) / diff(range(loadings[, 2L]))
  )
  arrow <- data.frame(
    trait = traits,
    axis_1 = loadings[, 1L] * scale_arrow,
    axis_2 = loadings[, 2L] * scale_arrow
  )
  ggplot(score, aes(x = axis_1, y = axis_2)) +
    geom_hline(yintercept = 0, linewidth = 0.3, colour = "grey65") +
    geom_vline(xintercept = 0, linewidth = 0.3, colour = "grey65") +
    geom_point(alpha = 0.32, size = 1.15, colour = "#173f5f") +
    geom_segment(data = arrow, inherit.aes = FALSE,
                 aes(x = 0, y = 0, xend = axis_1, yend = axis_2),
                 arrow = grid::arrow(length = grid::unit(2.4, "mm")),
                 linewidth = 0.7, colour = "#e48624") +
    geom_text(data = arrow, inherit.aes = FALSE,
              aes(x = axis_1, y = axis_2, label = trait),
              hjust = 0.5, vjust = -0.55, size = 2.8, colour = "#7a3e00") +
    labs(title = title, x = "Latent axis 1", y = "Latent axis 2") +
    coord_equal() +
    theme_minimal(base_size = 10) +
    theme(plot.title = element_text(face = "bold"),
          panel.grid.minor = element_blank())
}

# Rank-one: suitable for the empirical examples. A plotted vertical position is
# intentionally only jitter; there is no second latent coordinate.
lambda_B1 <- matrix(c(0.85, 0.65, 0.45, 0.10, -0.35, -0.65), ncol = 1)
lambda_W1 <- matrix(c(0.30, 0.10, -0.25, 0.75, 0.55, -0.45), ncol = 1)
psi_B1 <- diag(c(0.28, 0.30, 0.32, 0.25, 0.35, 0.30))
psi_W1 <- diag(c(0.55, 0.50, 0.55, 0.48, 0.52, 0.58))
rank_one <- simulate_two_level(lambda_B1, lambda_W1, psi_B1, psi_W1)

rank_one_plot <-
  (make_score_strip(rank_one$z_B, "A. Between-individual axis",
                    "Known individual score on the one shared B axis") +
     make_lollipop(lambda_B1, "B. Between-individual loadings")) /
  (make_score_strip(rank_one$z_W, "C. Within-individual axis",
                    "Known occasion score on the one shared W axis") +
     make_lollipop(lambda_W1, "D. Within-individual loadings")) +
  plot_annotation(
    title = "One-dimensional ordination at two levels",
    subtitle = "Known values from a simulation. Vertical spread in score panels is visual jitter, not a second axis."
  )
ggsave(file.path(out_fig, "ordination-rank-one.png"), rank_one_plot,
       width = 10.5, height = 7, dpi = 300)
ggsave(file.path(out_fig, "ordination-rank-one.pdf"), rank_one_plot,
       width = 10.5, height = 7)

# Rank-two: a separate, six-trait simulation. The current four-trait empirical
# rank-one examples cannot provide an identifiable free-uniqueness rank-two fit.
lambda_B2 <- rbind(
  c(0.80, 0.05), c(0.70, 0.20), c(0.45, 0.65),
  c(0.10, 0.80), c(-0.35, 0.70), c(-0.65, -0.20)
)
lambda_W2 <- rbind(
  c(0.35, 0.70), c(0.20, 0.65), c(-0.25, 0.70),
  c(0.75, 0.20), c(0.65, -0.25), c(-0.55, 0.30)
)
psi_B2 <- diag(c(0.28, 0.30, 0.32, 0.25, 0.35, 0.30))
psi_W2 <- diag(c(0.55, 0.50, 0.55, 0.48, 0.52, 0.58))
rank_two <- simulate_two_level(lambda_B2, lambda_W2, psi_B2, psi_W2)

rank_two_plot <-
  make_biplot(rank_two$z_B, lambda_B2, "A. Between-individual two-axis space", "individual") +
  make_biplot(rank_two$z_W, lambda_W2, "B. Within-individual two-axis space", "occasion") +
  plot_layout(guides = "collect") +
  plot_annotation(
    title = "Two-dimensional ordination needs enough traits",
    subtitle = "Known values from a six-trait simulation; B and W shown separately."
  )
ggsave(file.path(out_fig, "ordination-rank-two.png"), rank_two_plot,
       width = 9.6, height = 5.2, dpi = 300)
ggsave(file.path(out_fig, "ordination-rank-two.pdf"), rank_two_plot,
       width = 9.6, height = 5.2)

# Public data for the optional fitting exercise. Truth records make the plotted
# teaching quantities auditable without claiming fitted recovery.
write.csv(rank_two$data, file.path(out_data, "ordination-teaching-data.csv"), row.names = FALSE)
truth <- rbind(
  data.frame(level = "B", trait = traits, axis_1 = lambda_B2[, 1], axis_2 = lambda_B2[, 2],
             unique_variance = diag(psi_B2)),
  data.frame(level = "W", trait = traits, axis_1 = lambda_W2[, 1], axis_2 = lambda_W2[, 2],
             unique_variance = diag(psi_W2))
)
write.csv(truth, file.path(out_data, "ordination-teaching-truth.csv"), row.names = FALSE)
