
# ============================================================
# 1. CALCULATE MEAN GENETIC VALUES
# ============================================================

mean_gv <- results_df %>%
  group_by(scenario, rep, cycle, environment) %>%
  summarise(
    mean_gv = mean(gv),
    .groups = "drop"
  )

# ============================================================
# 2. CALCULATE GENETIC GAIN RELATIVE TO CYCLE 0
# ============================================================

gain_df <- mean_gv %>%
  group_by(scenario, rep, environment) %>%
  dplyr::mutate(
    genetic_gain = mean_gv - mean_gv[cycle == 0]
  ) %>%
  ungroup()

# Add TPE average (equal weighting across environments)
gain_tpe <- gain_df %>%
  group_by(scenario, rep, cycle) %>%
  summarise(
    genetic_gain = mean(genetic_gain),
    .groups = "drop"
  ) %>%
  dplyr::mutate(environment = "TPE")

gain_df <- bind_rows(gain_df, gain_tpe)

# Order environments
gain_df$environment <- factor(
  gain_df$environment,
  levels = c(paste0("Env", seq_len(nEnv)), "TPE")
)

# Average across replicates
gain_summary <- gain_df %>%
  group_by(scenario, cycle, environment) %>%
  summarise(
    mean_gain = mean(genetic_gain),
    sd_gain = sd(genetic_gain),
    .groups = "drop"
  )

# ============================================================
# 3. GENETIC GAIN OVER CYCLES
# ============================================================

gain_cycles <- ggplot(
  gain_summary,
  aes(x = cycle, y = mean_gain, colour = scenario)
) +
  geom_line(linewidth = 1) +
  geom_point(size = 1.5) +
  facet_wrap(~ environment) +
  labs(
    x = "Selection cycle",
    y = "Mean genetic gain",
    colour = "Selection scenario",
    title = "Genetic gain across selection cycles"
  ) +
  theme_bw()

# ============================================================
# 4. FINAL GENETIC GAIN ACROSS ENVIRONMENTS + TPE
# ============================================================

gain_final <- gain_summary %>%
  filter(cycle == max(cycle)) %>%
  ggplot(
    aes(x = environment, y = mean_gain,
        colour = scenario, group = scenario)
  ) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2.5) +
  labs(
    x = "Environment",
    y = "Mean genetic gain",
    colour = "Selection scenario",
    title = "Final genetic gain across environments and TPE"
  ) +
  theme_bw()


# ============================================================
# 5. STABILITY ACROSS SELECTION CYCLES
# ============================================================

# Calculate mean stability (SD across environments) of genotypes
stability_df <- results_df %>%
  group_by(scenario, rep, cycle) %>%
  summarise(
    mean_stability = mean(apply(matrix(gv, ncol = nEnv), 1, sd)),
    .groups = "drop"
  )

# Average across replicates
stability_summary <- stability_df %>%
  group_by(scenario, cycle) %>%
  summarise(
    mean_stability = mean(mean_stability),
    sd_stability = sd(mean_stability),
    .groups = "drop"
  )

# Plot stability over cycles
stability_cycles <- ggplot(
  stability_summary,
  aes(x = cycle, y = mean_stability, colour = scenario)
) +
  geom_line(linewidth = 1) +
  geom_point(size = 1.5) +
  labs(
    x = "Selection cycle",
    y = "Mean stability (SD across environments)",
    colour = "Selection scenario",
    title = "Stability across selection cycles"
  ) +
  theme_bw()

# ============================================================
# 6. FINAL POPULATION STABILITY
# ============================================================

stability_final <- stability_summary %>%
  filter(cycle == max(cycle)) %>%
  ggplot(
    aes(x = scenario, y = mean_stability, fill = scenario)
  ) +
  geom_col() +
  labs(
    x = "Selection scenario",
    y = "Mean stability (SD across environments)",
    title = "Final population stability"
  ) +
  theme_bw() +
  theme(legend.position = "none")


# ============================================================
# 7. POPULATION PERFORMANCE UNDER DIFFERENT STABILITY INDICES
# ============================================================

# Colours for each breeding population
pop_colours <- c(
  zero = "steelblue",
  low  = "forestgreen",
  med  = "orange",
  high = "firebrick"
)




# Calculate mean index values for each population under each lambda
index_df <- results_df %>%
  group_by(scenario, rep, cycle) %>%
  group_modify(~ {
    
    # Reconstruct genetic values across environments
    gv_mat <- matrix(.x$gv, ncol = nEnv)
    
    # Evaluate each population using all four indices
    bind_rows(lapply(names(lambda_scenarios), function(x) {
      
      lambda <- lambda_scenarios[[x]]
      
      index <- rowMeans(gv_mat) -
        lambda * apply(gv_mat, 1, sd)
      
      data.frame(
        index_scenario = x,
        mean_index = mean(index)
      )
    }))
  }) %>%
  ungroup()

# Calculate gain relative to cycle 0
index_gain <- index_df %>%
  group_by(scenario, rep, index_scenario) %>%
  mutate(
    index_gain = mean_index - mean_index[cycle == 0]
  ) %>%
  ungroup()

# Summarise final index gain across replicates
index_final_summary <- index_gain %>%
  filter(cycle == max(cycle)) %>%
  group_by(index_scenario, scenario) %>%
  summarise(
    mean_index = mean(index_gain),
    se_index = sd(index_gain) / sqrt(n()),
    .groups = "drop"
  ) %>%
  mutate(
    index_scenario = factor(
      index_scenario,
      levels = c("zero", "low", "med", "high")
    ),
    scenario = factor(
      scenario,
      levels = c("zero", "low", "med", "high")
    )
  )

# Plot population gain under each index
index_responses <- ggplot(
  index_final_summary,
  aes(x = index_scenario, y = mean_index,
      colour = scenario, group = scenario)
) +
  geom_point(
    size = 3,
    position = position_dodge(width = 0.5)
  ) +
  geom_errorbar(
    aes(ymin = mean_index - se_index,
        ymax = mean_index + se_index),
    width = 0.15,
    position = position_dodge(width = 0.5)
  ) +
  scale_colour_manual(values = pop_colours) +
  labs(
    x = "Stability index evaluated",
    y = "Mean population index gain",
    colour = "Breeding population",
    title = "Does selecting for stability improve population performance?"
  ) +
  theme_bw()

