# Manuel Dahnert
# User study: Looking beyond the horizon: Evaluation of four compact visualization techniques for time series in a spatial context
# Collection of constants and functions

# Constant vectors
techniques <- c("HG", "CHG", "BHG", "CBP")
techniques.long <- c("horizongraphs", "colhorgraphs", "braidedgraphs", "boxplots")
tasks.index <- (1:10)
tasks.names <- c("Maximum", "Slope increasing", "Slope decreasing",
                 "Discrimination", "Difference estimation",
                 "Time estimation", "Synoptic search", 
                 "Synoptic slope", "Classification", "Homogeneity")


# Filter data
# Exclude participants with less than min.time or more than max.skips
filterData <- function(data, max.skips, min.time) {
  
  # Prepare participant list
  participants <- as.data.frame(unique(data$participant))
  colnames(participants)[1] <- "participant"
  
  # Add columns for filtering the participant, the number of skips and the time
  participants <- cbind(participants, filter = rep(FALSE, nrow(participants)))
  participants <- cbind(participants, skips = rep(0, nrow(participants)))
  participants <- cbind(participants, time = rep(0, nrow(participants)))

  # Loop over all participants and check if the results are valid
  for (p in participants[[1]]) {
    p.data <- data[data$participant == p, ]  # Get all data belonging to the current participant
    p.data$startTime <- strptime(p.data$startTime, "%Y-%m-%d %T")  # Parse start time as date
    
    # Count skips
    skips <- nrow(p.data[p.data$Training == "null" & p.data$skipped == "true", ])
    participants[participants[[1]] == p , ]$skips <- skips # Add number of skips to table
    
    # Calculated elapsed time
    start <- p.data$startTime[1]  # Get the first time
    end <- tail(p.data$startTime, n = 1)  # Get the last time
    elapsed.time <- difftime(end, start, units = "mins")  # Calculate the difference
    delta <- as.numeric(elapsed.time)
    participants[participants[[1]] == p , ]$time <- elapsed.time  # Add elapsed time to table

    # More than max.skips or less than min.time are filtered out
    if (skips > max.skips | elapsed.time < min.time ) { # | elapsed.time > 2500) {
      participants[participants[[1]] == p , ]$filter <- TRUE  # Mark participant to filter out
      
      data <- data[data$participant != p, ]  # Remove entries of this participant
    }
  }
  
  data <- data[data$duration_ms < 1800000, ]
  
  return (data)
}


# Extract the demography fields from a collection file and aggregate by columns
extractDemography <- function(dataset) {
  # Define vectors with demographic questionIds
  ids <- c("gender", "age", "vision", "study", "experience")
  
  demography <- as.data.frame(dataset[dataset$questionId == "gender", 1])
  names(demography)[1] <- "participant" # Rename first column
  
  # Get the subset with the specific questionId and add it to demography
  for (id in ids) {
    field <- dataset[dataset$questionId == id, 13]
    demography[[id]] <- as.character(field)
  }
  
  # Correction: Transform age column to numeric values
  demography$age <- as.numeric(demography$age)
  
  # Correction: Split experience vector
  demography$experience <- strsplit(demography$experience, ",")
  
  for (r in 1:length(demography$experience)) {
    len <- length(unlist(demography$experience[r]))
    if (len == 0) {
      demography$experience[r] <- "None"
    }
  }
  
  return (demography)
}


# Install libraries if necessary and load
loadLibrary <- function(package.name)
{
  if (!require(package.name, character.only = TRUE))
  {
    install.packages(package.name, dep=TRUE)
    if (!require(package.name, character.only = TRUE)) {
      stop("Package not found")
    }
  }
}

# Not used
# Create boxplot for given data and save to file
saveBarplot <- function(data, filename, w, h, xlab, main, ylim) {
  png(filename, width = w, height = h)
  
  colors <- max(3, length(data))
  barplot(data, col = brewer.pal(colors, "Set2"), border = NA, ylim = ylim,
          xlab = xlab, main = main)
  
  dev.off()
}

