---
title: "Pilot Stimuli"
output: html_document
date: "2023-06-05"
---

```{r setup, include=FALSE}

library(tidyverse)
library(ggdist)
library(xts)
library(distributional)
library(moments)
library(ggfx)
library(ggbeeswarm)

# Set random seed
set.seed(2)

# Set up the theme for image export
theme_set(theme_classic() + 
            theme(plot.title = element_text(size = 10, color = "#333333"),
                  axis.title = element_text(size = 7, color = "#262626"),
                  axis.text = element_text(size = 5, color = "#1B1B1B"),
                  axis.line = element_line(linewidth = 0.25, color = "#1B1B1B"),
                  axis.ticks = element_line(linewidth = 0, color = "#1B1B1B"),
                  axis.line.y = element_blank(),
                  axis.text.y = element_blank(),
                  axis.ticks.y = element_blank(),
                  axis.title.y = element_blank()))

# Variable for setting the x-axis range on either side of the mean
x_range <- 4

```

# Generating Distributions

```{r distribution generator}

## set values

n <- 13 # number of stimuli to generate
target <- 32 # target value of interest
range <- 2 # range for distance from target value
min_mean <- target - range # lower end of possible mean values
max_mean <- target + range # higher end of possible mean values
sd <- 1 # set value for standard deviation of the distributions - set based on the uncertain about uncertainty. sd = 1 led to slight increase in crossover, sd = 2 led to slight decrease in crossover. sd = 1.5 to balance that? or should just pick one - probably sd = 1
dist_n <- 100 # number of values in the distribution
tail_pct <- 0 # pct likelihood of tail value


## create data frame

df <- data.frame(
  trial = 0:(n-1),
  mean = NA,
  sd = sd,
  freeze.pct = NA,
  min = NA,
  max = NA, 
  fifty.1 = NA,
  fifty.2 = NA,
  tail.value = NA,
  tail.pct = NA,
  distribution = NA,
  skew = NA
)

allDists <- data.frame(
  1:100
)

## generate distributions

for (i in 1:n) {
  
  mean <- sample(seq(min_mean, max_mean), 1) # randomly select the mean of the distribution
  df$mean[i] <- mean # add to the data frame
  data <- rnorm(dist_n, mean, sd) # create distribution
  df$distribution[i] <- list(data) # add to the data frame
  
  allDists <- cbind(allDists, data)  # save data into df for use in prototyping
  colnames(allDists)[ncol(allDists)] <- paste0("t", i-1)
  
  prob_target <- sum(data <= target) / length(data)
  df$freeze.pct[i] <- prob_target # add to the data frame
  
  df$min[i] <- round(min(data), 0)
  
  df$max[i] <- round(max(data), 0)
  
  df$fifty.1[i] <-  round(quantile(data, 0.25), 0) # first value in the 50% confidence interval
  df$fifty.2[i] <-  round(quantile(data, 0.75), 0) # second value in the 50% confidence interval
  
  tail_value <- floor(min(data)) - 1 # get a value with 0% chance of occurring for attention checks
  df$tail.value[i] <- tail_value # add to the data frame
  
  prob_tail <- sum(data <= round(tail_value, 0)) / length(data) # confirm this value has a 0% likelihood
  df$tail.pct[i] <- prob_tail # add to the data frame
  
  df$skew[i] <- skewness(data) # calculate and store the skew value for the distribution
  
  
}

allDists <- allDists %>% select(contains("t"))

write_excel_csv(df %>% select(-distribution), "E2_stimuli_data.csv") # export this data for later use

write_excel_csv(allDists, "all_dists_long.csv")

```

# Visual Stimuli

```{r plots, echo = FALSE}

for (i in 1:n) {
  
  trial_data <- df[i,]
  mean <- trial_data$mean
  data <- data.frame(distribution = unlist(trial_data$distribution))
  
  cat("\n\n## Trial ", trial_data$trial, ":\n\n")
  
  # forecast 1 (most concrete, quantile 20)
  forecast_1 <- 
    ggplot(data, aes(x = distribution)) +
    stat_dots(position = "dodgejust",
              quantiles = 20,
              color = NA, 
              size = 5,
              fill = "#606B76", alpha = 0.62)+
    scale_x_continuous(breaks = seq(mean - x_range, mean + x_range),
                       limits = c(mean - x_range, mean + x_range))+
    labs(x = "\nºF",
         title = "Estimated Temperature")
  print(forecast_1)
  path_and_filename <- paste0("img/", "forecast_1.", trial_data$trial, ".png")
  ggsave(path_and_filename,
         plot = forecast_1,
         width = 1200, height = 800, units = "px")
  dir.create(dirname(path_and_filename), showWarnings = FALSE)
  
  
  # forecast 2 (density plot)
  forecast_2 <- 
    ggplot(data, aes(x = distribution)) +
    stat_slab(show.legend = c(size = FALSE,
                              slab_alpha = FALSE), fill = "#606B76", alpha = 0.62) +
    scale_x_continuous(breaks = seq(mean - x_range, mean + x_range),
                       limits = c(mean - x_range, mean + x_range))+
    labs(x = "\nºF",
         title = "Estimated Temperature")
  path_and_filename <- paste0("img/", "forecast_2.", trial_data$trial, ".png")
  print(forecast_2)
  ggsave(path_and_filename,
         plot = forecast_2,
         width = 1200, height = 800, units = "px")
  dir.create(dirname(path_and_filename), showWarnings = FALSE)
  
  # forecast 3 (beeswarm)
  forecast_3 <- 
    ggplot(data, aes(x = distribution, y = ".")) +
    geom_beeswarm(size = 1.5, fill = "#9DA3AA", color= "#9DA3AA", cex = 9, side = 1L, priority = "random") +
    scale_x_continuous(breaks = seq(mean - x_range, mean + x_range),
                       limits = c(mean - x_range, mean + x_range))+
    scale_y_discrete(limits = c(".", rep("",6)))+
    labs(x = "\nºF",
         title = "Estimated Temperature")
  path_and_filename <- paste0("img/", "forecast_3.", trial_data$trial, ".png")
  print(forecast_3)
  ggsave(path_and_filename,
         plot = forecast_3,
         width = 1200, height = 800, units = "px")
  dir.create(dirname(path_and_filename), showWarnings = FALSE)
  
  # forecast 4 made using Figma
  # forecast 5 (most fuzzy) made using Figma
  
  
}

```

# Text Stimuli

```{r}

df_text <- data.frame(
  trial = 0:(n-1),
  forecast_1 = NA, # most concrete
  forecast_2 = NA,
  forecast_3 = NA,
  forecast_4 = NA,
  forecast_5 = NA # most fuzzy
)


# Define intervals and labels for skew
skew_likelihood_intervals <- c(0, 0.1, 0.3, 0.5, 1)
skew_likelihood_label <- 
  c(
    "slightly ",
    "somewhat ",
    "",
    "significantly "
  )

skew_direction_intervals <- c(-1, 0, 1)
skew_direction_label <- 
  c(
    "warmer than cooler",
    "cooler than warmer"
  )

for (i in 1:n) {
  
  data <- unlist(df$distribution[i])
  
  skew_likelihood <- cut(abs(df$skew[i]), 
                         breaks = skew_likelihood_intervals, 
                         labels = skew_likelihood_label, 
                         right = TRUE)
  skew_direction <- cut(df$skew[i], 
                        breaks = skew_direction_intervals, 
                        labels = skew_direction_label, 
                        right = TRUE)
  
  # concrete
  df_text$forecast_1[i] <- paste0(
    "The most likely temperature low tonight is ",
    df$mean[i],
    "ºF. There is a 50% chance that the temperature will fall between ",
    round(quantile(data, 0.25), 0),
    " and ",
    round(quantile(data, 0.75), 0),
    "ºF. While the range of possible lows spans ",
    df$min[i],
    " to ",
    df$max[i],
    "ºF, those extremes are less likely. It is also ",
    skew_likelihood,
    "more likely to be ",
    skew_direction,
    " within that range."
  )
  
  
  # minor hedges
  df_text$forecast_2[i] <- paste0(
    "The most likely temperature low tonight might be ",
    df$mean[i],
    "ºF. There is a 50% chance that the temperature could fall between ",
    round(quantile(data, 0.25), 0),
    " and ",
    round(quantile(data, 0.75), 0),
    "ºF. While the range of possible lows could span ",
    df$min[i],
    " to ",
    df$max[i],
    "ºF, those extremes are less likely. It is also ",
    skew_likelihood,
    "more likely to be ",
    skew_direction,
    " within that range."
  )
  
  
  # moderate hedges
  df_text$forecast_3[i] <- paste0(
    "The most likely temperature low tonight might be around ",
    df$mean[i],
    "ºF. There is a 50% chance that the temperature could fall between ",
    round(quantile(data, 0.25), 0),
    " and ",
    round(quantile(data, 0.75), 0),
    "ºF. While the range of possible lows could potentially span ",
    df$min[i],
    " to ",
    df$max[i],
    "ºF, those extremes are less likely. It also appears ",
    skew_likelihood,
    "more likely to be ",
    skew_direction,
    " within that range."
  )
  
  # increased hedges
  df_text$forecast_4[i] <- paste0(
    "The most likely temperature low tonight could potentially hover somewhere around ",
    df$mean[i],
    "ºF. There may be a 50% chance that the temperature could fall between ",
    round(quantile(data, 0.25), 0),
    " and ",
    round(quantile(data, 0.75), 0),
    "ºF. While the range of possible lows could, in theory, span ",
    df$min[i],
    " to ",
    df$max[i],
    "ºF, those extremes seem far less likely. There also seems to be some indication that it could be ",
    skew_likelihood,
    skew_direction,
    " within that range."
  )
  
  
  # increased hedges italics
  df_text$forecast_5[i] <- paste0(
    "The most likely temperature low tonight <i>could potentially</i> hover <i>somewhere around</i> ",
    df$mean[i],
    "ºF. There <i>may</i> be a 50% chance that the temperature <i>could</i> fall between ",
    round(quantile(data, 0.25), 0),
    " and ",
    round(quantile(data, 0.75), 0),
    "ºF. While the range of possible lows <i>could, in theory</i>, span ",
    df$min[i],
    " to ",
    df$max[i],
    "ºF, those extremes <i>seem</i> far less likely. There also <i>seems</i> to be some indication that it <i>could</i> be ",
    skew_likelihood,
    skew_direction,
    " within that range."
  )
  
}

# Open a new file for writing
fileConn <- file("forecasts_text.js", open = "w")

# Iterate over each row of the data frame
for(i in 1:nrow(df_text)) {
  # Write a comment with the trial number
  writeLines(paste0("// trial ", i - 1), fileConn)
  
  # Iterate over each column and write a line for each forecast
  for(j in 1:ncol(df_text)) {
    # Skip the trial column
    if(names(df_text)[j] != "trial") {
      writeLines(paste0("var ", names(df_text)[j], ' = "', df_text[i, j], '";'), fileConn)
    }
  }
  
  # Write a blank line after each trial
  writeLines("\n", fileConn)
}

# Close the file connection
close(fileConn)

```






