# Readme ----------------------------------------------------------------------------------------------------------

# 1.  **Info**:
#   This script will:
#   + Calculate two-way RM ANOVA on edges and plot heatmap for uncorrected and corrected p.val
#   + Calculate two-way RM ANOVA on nodes and plot bar graphs with strength
# 
# 2.  **Inputs**:
#   Config specification for output folders and file names. Single and grouped data frame from *Process inputs* script.
# 
# 3.  **Return**:
#   CSV tables and appropriate heatmaps:
#   + High/low impulsive interaction with BI compound 11/Vehicle using fisher r-to-z transform on *each edge*. This will report heatmap of corrected and uncorrected p values
#   + Unsure

# Interaction_edgewise-----------------------------------------------------------------------------------------------
# Run a 2-way edge wise 2-way RM ANOVA edgewise.

Interaction_edgewise <- function(Data.single, Heatmap.brains.sorted, 
                                 Interaction_p.correction, 
                                 Interaction_heatmap.p.filter,
                                 Interaction_heatmap,
                                 Interaction_make.heatmap) {
  tryCatch({
    
    # Run anova --------------------------------------    
    flog.debug("Running edge wise 2RM ANOVA", name = log.name)
    ANOVA <- Data.single %>%
      group_by(From, To) %>% nest() %>%
      mutate(ANOVA = future_map(data, TwowayRM_ANOVA)) %>%
      select(-data) %>% unnest() %>%
      mutate(p.value = `Pr(>F)`) %>%
      group_by(Stat) %>%
      mutate(corrected.p.value = two.step.BH(p.value , method = Interaction_p.correction))
    
    # write data to file
    flog.debug("Saving data", name = log.name)
    write_csv(x = ANOVA, path = paste0(output.folder, Interaction_heatmap, "_edge.csv"))
    
    ANOVA.full <- ANOVA %>% rename(From2 = From, To2 = To) %>%
      rename(From = To2, To = From2) %>%
      bind_rows(ANOVA, .) %>%
      arrange(From, To) %>%
      filter(Stat == "Impulsivity:Treatment")
    
    if (Interaction_make.heatmap) {
      # plot heatmap
      flog.debug("Plotting edge wise 2RM ANOVA data", name = log.name)
      plot_heatmap(ANOVA.full,
                   measure = "p.value",
                   breaks = c(0, Interaction_heatmap.p.filter, 1),
                   color = c("red", "black"),
                   plot.name = paste(Interaction_heatmap,
                                     "Interaction.p.value", sep = "_"),
                   Annotations.data = Heatmap.brains.sorted)
      
      plot_heatmap(ANOVA.full,
                   measure = "corrected.p.value",
                   breaks = c(0, Interaction_heatmap.p.filter, 1),
                   color = c("red", "black"),
                   plot.name = paste(Interaction_heatmap,
                                     "corrected.Interaction.p.value", sep = "_"),
                   Annotations.data = Heatmap.brains.sorted)
    }
    
    return(ANOVA.full)
    
  }, error = function(e) {
    flog.error("ERROR!", name = log.name)
    flog.error(e, name = log.name)
  })
}

# Interaction_nodewise-----------------------------------------------------------------------------------------------
# This will run the 2-way RM ANOVA on mean data, for each node seperatly.

Interaction_nodewise <- function(Data.single,
                                 Interaction_p.correction, 
                                 Interaction_heatmap.p.filter,
                                 Interaction_heatmap,
                                 Interaction_make.heatmap) {
  tryCatch({
    
    # Run anova --------------------------------------    
    flog.debug("Calculating node wise 2RM ANOVA data", name = log.name)
    Interaction.node <- Data.single %>%
      rename(From2 = From, To2 = To) %>%
      rename(From = To2, To = From2) %>%
      bind_rows(Data.single, .) %>%
      mutate(From_both = gsub(pattern = " L| R", replacement = "", From)) %>% # can be taken out to have split between hemispheres
      mutate(File = factor(paste(From, To, File, sep = "_"))) %>%
      group_by(From_both) %>%
      nest()  %>%
      mutate(ANOVA = future_map(data, TwowayRM_ANOVA)) %>%
      select(-data) %>% unnest() %>%
      mutate(p.value = `Pr(>F)`) %>%
      group_by(Stat) %>%
      mutate(corrected.p.value = two.step.BH(p.value , method = Interaction_p.correction)) %>%
      ungroup() %>%
      mutate(Stat = gsub(pattern = " ", replacement = "", Stat)) %>%
      mutate(Stat = gsub(pattern = ":", replacement = "_", Stat))
    
    flog.debug("Saving node wise 2RM ANOVA data", name = log.name)
    write_csv(x = Interaction.node, path = paste0(output.folder, Interaction_heatmap, "_node.csv"))

    if (Interaction_make.heatmap) {
      flog.debug("Plotting node wise 2RM ANOVA data", name = log.name)
      for (treat in unique(Interaction.node$Stat)) {
        
        Temp <- Interaction.node %>% filter(Stat == treat & corrected.p.value < 0.05)
        
        From.order <- Temp %>% group_by(From_both) %>% summarise(n = mean(`F value`))
        
        Temp <- Temp %>% mutate(From_both = factor(From_both, levels = From.order$From_both[order(-From.order$n)]))
        
        Bar_graph(Temp,
                  x.axis = "From_both",
                  y.axis = "`F value`",
                  y.axis.title = "2-way ANOVA F value",
                  color.fill = "`F value`",
                  filename = paste0("Interaction_OneSamplTtest", treat),
                  plot.title = paste0(treat, ": 2-way RM ANOVA for for High vs Low, only significant shown"),
                  plots.folder = plots.folder,
                  output.folder = output.folder)
      }
    }
    
    return(Interaction.node)
    
  }, error = function(e) {
    flog.error("ERROR!", name = log.name)
    flog.error(e, name = log.name)
  })
}