#!/usr/bin/env Rscript
# Recreate manuscript Figure 2 (Arctic charr) from the bundled aggregate inputs.
# Run from the repository root: Rscript tutorial/downloads/figure-gallery/make-figure-2.R
# This script draws archived estimates; it does not refit models or rerun bootstraps.

suppressPackageStartupMessages({
  library(ggplot2)
  library(patchwork)
  library(ggrepel)
})

input_dir <- "tutorial/downloads/figure-gallery/data"
output_dir <- "tutorial/figures/figure-gallery"
dir.create(output_dir, recursive = TRUE, showWarnings = FALSE)

key <- read.csv(file.path(input_dir, "charr-trait-key.csv"),
                stringsAsFactors = FALSE)
corr <- read.csv(file.path(input_dir, "charr-correlations.csv"),
                 stringsAsFactors = FALSE)
comm <- read.csv(file.path(input_dir, "charr-communalities.csv"),
                 stringsAsFactors = FALSE)
rep <- read.csv(file.path(input_dir, "charr-repeatability.csv"),
                stringsAsFactors = FALSE)
ord <- read.csv(file.path(input_dir, "charr-ordination-coordinates.csv"),
                stringsAsFactors = FALSE)
load <- read.csv(file.path(input_dir, "charr-ordination-loadings.csv"),
                 stringsAsFactors = FALSE)

traits <- key$trait
stopifnot(nrow(key) == 9L, identical(key$trait_number, 1:9),
          nrow(corr) == 72L, nrow(comm) == 18L, nrow(rep) == 9L,
          all(corr$paired_refits == 1066L),
          all(comm$paired_refits == 1066L),
          all(rep$paired_refits == 1066L),
          nrow(subset(ord, level == "Between fish")) == 1185L,
          nrow(subset(ord, level == "Within fish")) == 2370L,
          nrow(load) == 18L,
          all(corr$trait_1 %in% traits), all(corr$trait_2 %in% traits),
          setequal(comm$trait, traits),
          setequal(comm$level, c("Between fish", "Within fish")),
          !anyDuplicated(comm[c("trait", "level")]),
          setequal(rep$trait, traits),
          all(is.finite(comm$lower_95)), all(is.finite(comm$upper_95)),
          all(comm$lower_95 < comm$upper_95),
          all(comm$lower_95 <= comm$estimate & comm$estimate <= comm$upper_95),
          all(is.finite(rep$lower_95)), all(is.finite(rep$upper_95)),
          all(rep$lower_95 < rep$upper_95),
          all(rep$lower_95 <= rep$estimate & rep$estimate <= rep$upper_95))

theme_set(theme_minimal(base_size = 9) +
            theme(panel.grid.minor = element_blank()))

matrix_panel <- function(level, title) {
  dat <- corr[corr$level == level, , drop = FALSE]
  i <- match(dat$trait_1, traits)
  j <- match(dat$trait_2, traits)
  stopifnot(nrow(dat) == 36L, !anyNA(i), !anyNA(j))
  upper <- data.frame(
    x = j, y = 10 - i, value = dat$correlation,
    label = sprintf("%.2f%s", dat$correlation,
                    ifelse(dat$lower_95 > 0 | dat$upper_95 < 0, "*", ""))
  )
  lower <- data.frame(x = i, y = 10 - j,
                      label = sprintf("%.2f\n%.2f", dat$lower_95,
                                      dat$upper_95))
  grid <- expand.grid(x = 1:9, y = 1:9)
  ggplot() +
    geom_tile(data = grid, aes(x, y), fill = "white", colour = "grey88") +
    geom_tile(data = upper, aes(x, y, fill = value), colour = "white") +
    geom_text(data = upper, aes(x, y, label = label), size = 3.0) +
    geom_text(data = lower, aes(x, y, label = label), size = 2.8,
              lineheight = 0.85) +
    scale_fill_gradient2(low = "#b54742", mid = "white", high = "#5684a6",
                         limits = c(-1, 1), name = "Correlation") +
    scale_x_continuous(breaks = 1:9, position = "top") +
    scale_y_continuous(breaks = 9:1, labels = 1:9) +
    coord_equal() +
    labs(title = title, x = NULL, y = NULL) +
    theme(panel.grid = element_blank(), legend.position = "none",
          axis.text = element_text(size = 7))
}

ordination_panel <- function(level, title) {
  points <- ord[ord$level == level, , drop = FALSE]
  arrows <- load[load$level == level, , drop = FALSE]
  scale_factor <- 0.75 * min(diff(range(points$axis1)),
                            diff(range(points$axis2))) /
    max(abs(as.matrix(arrows[, c("axis1", "axis2")])))
  arrows$x <- arrows$axis1 * scale_factor
  arrows$y <- arrows$axis2 * scale_factor
  arrows$label <- sprintf("%d", arrows$trait_number)
  arrows$nudge_x <- ifelse(level == "Between fish" & arrows$label == "7", 0.55, 0)
  arrows$nudge_y <- ifelse(level == "Between fish" & arrows$label == "7", -0.55, 0)
  xr <- range(c(points$axis1, arrows$x))
  yr <- range(c(points$axis2, arrows$y))
  xr <- xr + c(-1, 1) * diff(xr) * 0.14
  yr <- yr + c(-1, 1) * diff(yr) * 0.14
  ggplot(points, aes(axis1, axis2)) +
    geom_hline(yintercept = 0, colour = "grey82") +
    geom_vline(xintercept = 0, colour = "grey82") +
    geom_point(alpha = 0.12, size = 0.45, colour = "grey35") +
    geom_segment(data = arrows, aes(x = 0, y = 0, xend = x, yend = y),
                 inherit.aes = FALSE, colour = "#0072B2", linewidth = 0.45,
                 arrow = grid::arrow(length = grid::unit(1.4, "mm"))) +
    geom_text_repel(data = arrows, aes(x, y, label = label),
                    inherit.aes = FALSE, nudge_x = arrows$nudge_x,
                    nudge_y = arrows$nudge_y, seed = 13, size = 3,
                    colour = "#0072B2", max.overlaps = Inf,
                    min.segment.length = 0) +
    coord_equal(xlim = xr, ylim = yr, clip = "off") +
    labs(title = title, x = "Axis 1", y = "Axis 2")
}

comm$trait_number <- key$trait_number[match(comm$trait, traits)]
comm$y <- 10 - comm$trait_number +
  ifelse(comm$level == "Between fish", 0.13, -0.13)
comm$level <- factor(comm$level, levels = c("Between fish", "Within fish"))
communality_panel <- ggplot(comm, aes(estimate, y, colour = level,
                                     shape = level)) +
  geom_point(size = 1.6) +
  geom_errorbar(aes(xmin = lower_95, xmax = upper_95), orientation = "y",
                width = 0.09, linewidth = 0.65) +
  scale_colour_manual(values = c("Between fish" = "#0072B2",
                                 "Within fish" = "#D55E00")) +
  scale_shape_manual(values = c("Between fish" = 16, "Within fish" = 17)) +
  scale_x_continuous(breaks = seq(0, 1, 0.25),
                     expand = expansion(mult = c(0, 0))) +
  coord_cartesian(xlim = c(0, 1.04)) +
  scale_y_continuous(breaks = 9:1, labels = 1:9) +
  labs(title = "E  Communality", x = "Shared variance / variance at this level",
       y = "Trait number", colour = NULL, shape = NULL) +
  theme(legend.position = "bottom", legend.direction = "horizontal")

rep$trait_number <- key$trait_number[match(rep$trait, traits)]
rep$y <- 10 - rep$trait_number
repeatability_panel <- ggplot(rep, aes(estimate, y)) +
  geom_segment(aes(x = lower_95, xend = upper_95, yend = y),
               colour = "#0072B2", linewidth = 0.65) +
  geom_point(colour = "#25333D", shape = 18, size = 1.8) +
  scale_x_continuous(breaks = seq(0, 1, 0.25),
                     expand = expansion(mult = c(0, 0))) +
  coord_cartesian(xlim = c(0, 1.04)) +
  scale_y_continuous(breaks = 9:1, labels = 1:9) +
  labs(title = "F  Repeatability", x = "Between / (between + within)",
       y = "Trait number")

figure <-
  (matrix_panel("Between fish", "A  Between-fish correlations") |
     matrix_panel("Within fish", "B  Within-fish correlations")) /
  (ordination_panel("Between fish", "C  Between-fish ordination") |
     ordination_panel("Within fish", "D  Within-fish ordination")) /
  (communality_panel | repeatability_panel) +
  plot_layout(heights = c(1.15, 1, 0.78))

ggsave(file.path(output_dir, "figure-2-charr.png"), figure,
       width = 8.1, height = 11.4, dpi = 300, bg = "white")
ggsave(file.path(output_dir, "figure-2-charr.pdf"), figure,
       width = 8.1, height = 11.4, device = cairo_pdf, bg = "white")
cat("PASS FIGURE 2: nine traits; 1,066 paired refits; E communality; F repeatability\n")
