# Manuel Dahnert
# User study: Looking beyond the horizon: Evaluation of four compact visualization techniques for time series in a spatial context
# Evaluation of timings
# Generate boxplots
# Generate summary statistics
# Assume log-normal distribution

source("eval-functions.R")

# Load necessary librarys
loadLibrary("RColorBrewer")
loadLibrary("data.table")
loadLibrary("ggplot2")

# Load raw study data and perform general filtering
data.csv <- read.csv("rawdata_study.csv", header = TRUE, sep =";")
data <- filterData(data.csv, max.skips = 10, min.time = 30)

# Exclude trainings, demography and post tasks
data <- data[data$Training == "null" & data$skipped == "false" &
               ! data$task %in% c("demography", "postTask"), ]
data <- data[, c(1, 6, 12, 16, 18)] # Exclude unnecessary columns

# Average duration and error of all repetitions per participant
data.dt <- data.table(data)
data.dt <- data.dt[, .("duration_ms" = mean(duration_ms), "error" = mean(error)), 
                   by = c("participant", "task.1", "technique")]
data <- data.dt


data2 <- data.table()
for(index in tasks.index) {
  task.name <- paste("task", index, sep = "")
  
  task.dt <- data[task.1 == task.name, ]
  task.techs <- task.dt[, .("tech" = length(technique)), by = c("participant", "task.1")]
  
  if (index == 3) {
    task.techs <- task.techs[tech == 1, ]
  } else {
    task.techs <- task.techs[tech == 4, ]
  }
  
  task.data <- task.dt[task.techs, participant : error, on = "participant"]
  data2 <- rbind(data2, task.data)
}
data <- data2

# Define output directory
export.root <- "export/timings/"
dir.create(export.root, showWarnings = FALSE) # Create directory

# ------------------------------------------------------------------------------
#  BOXPLOTS
# ------------------------------------------------------------------------------

# Generate boxplots for task 1,4-10
output.dir <- paste(export.root, "boxplots/", sep = "") # Assume folder exists
dir.create(output.dir, showWarnings = FALSE) # Create directory
output.width <- 560
output.height <- 325

for (index in c(1,4,5,6,7,8,9,10)) {
  task.name <- paste("task", index, sep = "")
  task.data <- data[data$task.1 == task.name, ]
  task.data$duration_ms <- log10(task.data$duration_ms)
  
  # Start output rendering
  png(paste(output.dir, task.name, ".png", sep = ""), w = output.width, h = output.height) 
  boxplot(task.data$duration_ms ~ factor(task.data$technique), horizontal = TRUE, 
          outline = TRUE, names = c("BP", "BHG", "CHG", "HG"), las = TRUE,
          notch = FALSE, ylim = c(3, 5),
          col = brewer.pal(4, "Set2"), outcol = brewer.pal(4, "Set2"), outpch = 16,
          xlab = "log10(time) [s]", main = paste(index, "-", tasks.names[[index]]))
  dev.off()
}


# Special case task 2 & 3
# Combine both in one plot
task.data.t3 <- data[data$task.1 == "task3", ]
task.data.t3$technique <- "colhorgraphs2"
task.data <- data[data$task.1 == "task2", ] 
task.data <- rbind(task.data, task.data.t3) # Combine both data sets
task.data$duration_ms <- log10(task.data$duration_ms)

# Sort data such that chg and chg2 are next to each other
task.data$technique <- factor(task.data$technique, c("boxplots", "braidedgraphs",
                                                     "colhorgraphs", "colhorgraphs2",
                                                     "horizongraphs"))

boxplot.cols <- brewer.pal(5, "Set2") # Same color for chg and chg2
boxplot.cols[5] <- boxplot.cols[4]
boxplot.cols[4] <- boxplot.cols[3]
png(paste(output.dir, "task2.png", sep = ""), w = output.width, h = output.height)
boxplot(task.data$duration_ms ~ factor(task.data$technique), horizontal = TRUE, 
        outline = TRUE, las = TRUE, names = c("bp", "bhg", "chg", "chg2", "hg"),
        notch = FALSE,
        col = boxplot.cols, outcol = boxplot.cols, outpch = 16,
        xlab = "log10(time) [s]", main = "2/3 - Slope increase / decrease")
dev.off()


# Create summary plot for all tasks
output.dir <- paste(export.root, "boxplots/", sep = "")
dir.create(output.dir, showWarnings = FALSE) # Create directory
output.width <- 1000
output.height <- 400

task.data <- data
task.data$duration_ms <- log10(task.data$duration_ms)
task.data[task.1 == "task3",]$technique <- "colhorgraphs2"
task.data[task.1 == "task3",]$task.1 <- "task2"

task.chg <- task.data[task.1 == "task2" & technique == "colhorgraphs",]
task.chg$task.1 <- "task3"
fac <- factor(task.data$technique, c("boxplots", "horizongraphs", 
                                     "colhorgraphs", "colhorgraphs2", "braidedgraphs"))

for(index in tasks.index)
{
  task.name <- paste("task", index, sep = "")
  task.new_name <- as.character(index)
  task.data[task.1 == task.name,]$task.1 <- task.new_name
}

boxplot.cols <- c("#66C2A3", "#E78AC3", "#8DA0CB", "#64ACC9", "#FC8D62")
ylim1 = boxplot.stats(task.data$duration_ms)$stats[c(1, 5)]

bp <- ggplot(aes(y = duration_ms, x = factor(task.1), 
                 fill = fac), data = task.data) + 
  labs(x = "Task", y="Completion Time [s]") + 
  geom_boxplot(outlier.shape = NA) +
  coord_cartesian(ylim = c(3.1, 4.95))

bp <- bp + scale_fill_manual(values = boxplot.cols, name ="",
                             labels = c("CBP", "HG", "CHG", "CHG2", "BHG"),
                             breaks = c("boxplots", "horizongraphs", "colhorgraphs",
                                        "colhorgraphs2", "braidedgraphs"))
bp <- bp + theme(legend.background = element_rect(fill=alpha('gray', 0.0)),
                 legend.direction = "horizontal", legend.position = c(0.5,0), 
                 legend.justification=c(0.5,0), panel.background = element_blank() ,
                 panel.border = element_rect(fill = NA, colour = "black"))
ggsave(paste(output.dir, "timings.png", sep = ""), device = "png", 
       w = 10.42, h = 4.17, units = "in", plot = bp)

# ------------------------------------------------------------------------------
#  SUMMARY
# ------------------------------------------------------------------------------

output.file <- paste(export.root, "summary.txt", sep = "")
sink(output.file)

for (index in tasks.index) {
  task.name <- paste("task", index, sep = "")
  task.data <- data[data$task.1 == task.name, ]
  task.data$duration_ms <- log10(task.data$duration_ms)
  summary.table <- unclass(as.table(summary(task.data$duration_ms)))
  
  # Write header and task summary
  cat("\t ", paste0(names(summary(0)), sep = "\t"), "\n", sep = "")
  cat(sprintf("%02d",index), ": ")
  cat(paste0(sprintf("%0.2f",summary.table)), "\n", sep ="\t")
  
  # Write technique summaries
  for (tech in techniques.long) {
    tech.data <- task.data[task.data$technique == tech, ]

    if (nrow(tech.data) == 0) next
    
    summary.table <- unclass(as.table(summary(tech.data$duration_ms)))
    tech.short <- techniques[which(techniques.long == tech)]
    cat(sprintf("%-3s",tech.short), ": ", sep = "")
    cat(paste0(sprintf("%0.2f",summary.table)), "\n", sep ="\t")
  }
  cat("\n")
}
sink()

