# Manuel Dahnert
# User study: Looking beyond the horizon: Evaluation of four compact visualization techniques for time series in a spatial context
# Evaluation of errors
# Check for normality / log-normality visually (histograms, qq-plots)
# Check for normality / log-normality with test (Shapiro-Wilk)

# Load common functions and constants
source("eval-functions.R")

# Load necessary librarys
loadLibrary("RColorBrewer")
loadLibrary("data.table")

# 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)]

# Special case 4, Error(0) = TRUE, else FALSE
data.dt <- data.table(data)
data.dt[task.1 == "task4", ]$error <- as.numeric(data.dt[task.1 == "task4", ]$error != 0)

# Average duration and error of all repetitions per participant
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/errors/"
dir.create(export.root, showWarnings = FALSE) # Create directory

# ------------------------------------------------------------------------------
#  NORMALITY (Histograms, QQ-plots, Shapiro-Wilk)
# ------------------------------------------------------------------------------
output.width <- 600
output.height <- 600

# Create histogram matrix for each task to check for normality
output.dir <- paste(export.root, "histograms/", sep = "") # Assume folder exists
dir.create(output.dir, showWarnings = FALSE) # Create directory

for (index in tasks.index) {
  task.name <- paste("task", index, sep = "")
  output.name <- paste(output.dir, index, ".png", sep = "")
  
  png(output.name, w = output.width, h = output.height) # Start output rendering
  par(mfrow = c(2,2)) # Define matrix
  
  # Generate a histogram for each technique
  for (tech in techniques.long) {
    tech.data <- data[data$task.1 == task.name & data$technique == tech, ]
    
    if (nrow(tech.data) == 0) next # Skip for task 3
    
    hist(tech.data$error, main = paste(task.name, tech, sep = " - "), xlab = "error")
  }
  
  dev.off() # End output rendering
}

# Create QQ-plots matrix for each task to check for normality
output.dir <- paste(export.root, "qq-plots/", sep = "") # Assume folder exists
dir.create(output.dir, showWarnings = FALSE) # Create directory

for (index in tasks.index) {
  task.name <- paste("task", index, sep = "")
  output.name <- paste(output.dir, index, ".png", sep = "")
  
  png(output.name, w = output.width, h = output.height) # Start output rendering
  par(mfrow = c(2,2)) # Define matrix
  
  # Generate a histogram for each technique
  for (tech in techniques.long) {
    tech.data <- data[data$task.1 == task.name & data$technique == tech, ]
    
    if (nrow(tech.data) == 0) next # Skip for task 3
    
    qqnorm(tech.data$error, main = paste(task.name, tech), xlab = "error")
    qqline(tech.data$error)
  }
  
  dev.off() # End output rendering
}


# Perform Shapiro-Wilk test and save results in file
output.file <- paste(export.root, "shapiro.txt", sep = "")

sink(output.file)
cat("Shapiro-Wilk test for normality test\n")
cat("Task \t", paste0(techniques, sep = "\t\t\t"), "\n", sep = "") # Add headlines
for (index in tasks.index) {
  
  cat(sprintf("%02d", index), " ->\t", sep = "")
  for (tech in techniques.long) {
    task.name <- paste("task", index, sep = "")
    tech.data <- data[data$task.1 == task.name & data$technique == tech, ]
    
    if (nrow(tech.data) == 0) {
      cat("\t\t\t")
      next # Skip for task 3
    }
    
    tech.short <- techniques[which(techniques.long == tech)] # Get abbr of tech name
    shapiro.result <- shapiro.test(tech.data$error) # Perform test
    cat(sprintf("%.6f", shapiro.result$p.value), "\t")
  }
  cat("\n")
}
sink()
# -> not normal distributed


# ------------------------------------------------------------------------------
#  LOG-NORMALITY (Histograms, QQ-plots, Shapiro-Wilk)
# ------------------------------------------------------------------------------
output.width <- 600
output.height <- 600

# Create histogram matrix for each task to check for log-normality
output.dir <- paste(export.root, "histograms-log/", sep = "") # Assume folder exists
dir.create(output.dir, showWarnings = FALSE) # Create directory

for (index in tasks.index) {
  task.name <- paste("task", index, sep = "")
  output.name <- paste(output.dir, index, ".png", sep = "")
  
  png(output.name, w = output.width, h = output.height) # Start output rendering
  par(mfrow = c(2,2)) # Define matrix
  
  # Generate a histogram for each technique
  for (tech in techniques.long) {
    tech.data <- data[data$task.1 == task.name & data$technique == tech, ]
    
    if (nrow(tech.data) == 0) next # Skip for task 3
    
    hist(log10(tech.data$error+1), # Use log transformation
         main = paste(task.name, tech, sep = " - "), xlab = "log10(error)")
  }
  
  dev.off() # End output rendering
}

# Create QQ-plots matrix for each task to check for log-normality
output.dir <- paste(export.root, "qq-plots-log/", sep = "") # Assume folder exists
dir.create(output.dir, showWarnings = FALSE) # Create directory

for (index in tasks.index) {
  task.name <- paste("task", index, sep = "")
  output.name <- paste(output.dir, index, ".png", sep = "")
  
  png(output.name, w = output.width, h = output.height) # Start output rendering
  par(mfrow = c(2,2)) # Define matrix
  
  # Generate a histogram for each technique
  for (tech in techniques.long) {
    tech.data <- data[data$task.1 == task.name & data$technique == tech, ]
    
    if (nrow(tech.data) == 0) next # Skip for task 3
    
    qqnorm(log10(tech.data$error+1), # Use log transformation
           main = paste(task.name, tech, sep = " - "), xlab = "log10(error)")
    qqline(log10(tech.data$error+1)) # Use log transformation
  }
  
  dev.off() # End output rendering
}

# Perform Shapiro-Wilk test and save results in file
output.file <- paste(export.root, "shapiro.txt", sep = "")

sink(output.file, append = TRUE)
cat("Shapiro-Wilk test for normality test\n")
cat("Task \t", paste0(techniques, sep = "\t\t\t"), "\n", sep = "") # Add headlines
for (index in tasks.index) {
  
  cat(sprintf("%02d", index), " ->\t", sep = "")
  for (tech in techniques.long) {
    task.name <- paste("task", index, sep = "")
    tech.data <- data[data$task.1 == task.name & data$technique == tech, ]
    
    if (nrow(tech.data) == 0) {
      cat("\t\t\t")
      next # Skip for task 3
    }
    
    tech.short <- techniques[which(techniques.long == tech)] # Get abbr of tech name
    shapiro.result <- shapiro.test(log10(tech.data$error+1)) # Perform test
    cat(sprintf("%.6f", shapiro.result$p.value), "\t")
  }
  cat("\n")
}
sink()
# -> not log-normal distributed
