
print(paste("Scenario name is:", Scenario_name))



# Create animated plot
# Convert the list into a dataframe for animation
N_df_all <- do.call(rbind, lapply(names(N_plot_list), function(name) {
  df <- N_plot_list[[name]]$data  # Extract the plot data
  df <- df %>%
    rename(
      Column = 1,
      Row = 2,
      Value = 3
    )
  df$Day <- as.numeric(gsub("plot_day", "", name))  # Extract day number
  return(df)
}))



saveRDS(N_df_all, paste0("Animate/Data_frames/", Scenario_name, "_N.RDS"))


Ad_well_df_all <- do.call(rbind, lapply(names(Ad_well_plot_list), function(name) {
  df <- Ad_well_plot_list[[name]]$data  # Extract the plot data
  df <- df %>%
    rename(
      Column = 1,
      Row = 2,
      Value = 3
    )
  df$Day <- as.numeric(gsub("plot_day", "", name))  # Extract day number
  return(df)
}))



saveRDS(Ad_well_df_all, paste0("Animate/Data_frames/", Scenario_name, "_well.RDS"))


Ad_ill_df_all <- do.call(rbind, lapply(names(Ad_ill_plot_list), function(name) {
  df <- Ad_ill_plot_list[[name]]$data  # Extract the plot data
  df <- df %>%
    rename(
      Column = 1,
      Row = 2,
      Value = 3
    )
  df$Day <- as.numeric(gsub("plot_day", "", name))  # Extract day number
  return(df)
}))


saveRDS(Ad_ill_df_all, paste0("Animate/Data_frames/", Scenario_name, "_ill.RDS"))



# Define color scale
# Scale for N_df (Larger Range: 0.01 - 3000)
color_scale_N <- scale_fill_gradientn(
  colors = c("blue", "green", "yellow", "red"),
  name = "Density",
  trans = "log", 
  limits = c(0.01, 3000),
  breaks = c(0.01, 0.1, 1, 10, 100, 1000),
  labels = function(x) ifelse(x < 1, 
                              format(x, digits = 2, scientific = FALSE), 
                              format(round(x), scientific = FALSE)))

# Scale for well-fed and ill-fed (Smaller Range: 0.001 - 3)
color_scale_well_ill <- scale_fill_gradientn(
  colors = c("blue", "green", "yellow", "red"),
  name = "Density",
  trans = "log", 
  limits = c(0.0001, 10),
  breaks = c(0.0001, 0.001, 0.01, 0.1, 1, 10),
  labels = function(x) ifelse(x < 1, 
                              format(x, digits = 3, scientific = FALSE), 
                              format(round(x), scientific = FALSE)))




# Animated plot for N_df (Larger scale)
animated_plot_N <- ggplot(N_df_all, aes(x = Column, y = Row, fill = Value)) +
  geom_tile() +
  color_scale_N +  # Use the larger scale
  theme_minimal() +
  labs(title = "Aphid density (Day: {closest_state})", fill = "Value") +
  scale_y_reverse(expand = c(0, 0)) +
  scale_x_continuous(expand = c(0, 0)) +
  theme(axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank(),
        panel.grid = element_blank()) +
  transition_states(Day, transition_length = 2, state_length = 1) +
  ease_aes('linear')




# Animated plot for well-fed hoverflies
animated_plot_well <- ggplot(Ad_well_df_all, aes(x = Column, y = Row, fill = Value)) +
  geom_tile() +
  color_scale_well_ill +  # Use the smaller scale
  theme_minimal() +
  labs(title = "Well-fed hoverfly density (Day: {closest_state})", fill = "Value") +
  scale_y_reverse(expand = c(0, 0)) +
  scale_x_continuous(expand = c(0, 0)) +
  theme(axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank(),
        panel.grid = element_blank()) +
  transition_states(Day, transition_length = 2, state_length = 1) +
  ease_aes('linear')

# Animated plot for ill-fed hoverflies
animated_plot_ill <- ggplot(Ad_ill_df_all, aes(x = Column, y = Row, fill = Value)) +
  geom_tile() +
  color_scale_well_ill +  # Use the smaller scale (same as well-fed)
  theme_minimal() +
  labs(title = "Ill-fed hoverfly density (Day: {closest_state})", fill = "Value") +
  scale_y_reverse(expand = c(0, 0)) +
  scale_x_continuous(expand = c(0, 0)) +
  theme(axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank(),
        panel.grid = element_blank()) +
  transition_states(Day, transition_length = 2, state_length = 1) +
  ease_aes('linear')




# Animate each plot separately
img_N <- animate(animated_plot_N, nframes = 42, fps = 1, duration = 40, renderer = magick_renderer())
img_well <- animate(animated_plot_well, nframes = 42, fps = 1, duration = 40, renderer = magick_renderer())
img_ill <- animate(animated_plot_ill, nframes = 42, fps = 1, duration = 40, renderer = magick_renderer())

# Ensure all animations have the same number of frames
n_frames <- min(length(img_N), length(img_well), length(img_ill))

# Create an empty list to store combined frames
combined_frames <- vector("list", n_frames)

# Loop through frames and combine them
for (i in 1:n_frames) {
  top_frame <- img_N[i]  # Aphid Density on top
  bottom_frame <- image_append(c(img_well[i], img_ill[i]), stack = FALSE)  # Well-fed & Ill-fed side-by-side
  combined_frames[[i]] <- image_append(c(top_frame, bottom_frame), stack = TRUE)  # Stack vertically
}

# Convert list to magick image sequence
img_combined <- image_join(combined_frames)

# Save the animation (gif)
image_write(img_combined, paste0("Animate/",Scenario_name, ".gif"))

#save animation (MP4), need to create gif first
#av_encode_video(paste0("Animate/", Scenario_name, ".gif"),
#                paste0("Animate/", Scenario_name, ".mp4"),
#                framerate = 1)

