library(Rmisc)
library(tidyverse)
library(stringr)
library(scales)
library(grid)
library(ggpubr)
library(MASS)
# library(lmerTest)
library(rsample)
library(lme4)
library(brms)
library(ppcor)
library(stats)
library(modelr)
library(plotrix)
library(mgcv)
library(hexbin)
library(formattable)

rm(list=ls())

d <- read.csv('model_output/Mindi_gpt2.csv')


############################
# Attraction Effects
############################

d.AA <- d %>% filter(Word_id == AA_Crit_pos)


summary.AA <- d.AA %>%
  group_by(Cond, Verb_number) %>%
  summarise(
    mean = mean(word_surprisal, na.rm = TRUE),
    se   = sd(word_surprisal, na.rm = TRUE) / sqrt(sum(!is.na(word_surprisal))),
    .groups = "drop"
  )%>%
  mutate(
    Distractor = ifelse(Cond%in%c('a', "c", "e", "h", "j", "l", 'n'), "singular", "plural")
    )%>%
  mutate(n_copies = if_else(Cond %in% c("e", "n"), 2L, 1L)) %>%
  uncount(n_copies, .id = "copy") %>%
  mutate(Cond2 = if_else(Cond %in% c("e", "n"), paste0(Cond, copy), Cond)) %>%
  dplyr::select(-copy) %>%
  mutate(Config = case_when(
    Cond2 %in% c("a", "b")   ~ "Retro, SRC_ShortObj",
    Cond2 %in% c("c", "d")   ~ "Retro, ORC_ShortSubj",
    Cond2 %in% c("e1", "f")  ~ "Retro, ORC_LongSubj_nonlocal",
    Cond2 %in% c("e2", "g")  ~ "Retro, ORC_LongSubj_local",
    Cond2 %in% c("h", "i")   ~ "Pro, MatrixSubj_active",
    Cond2 %in% c("j", "k")   ~ "Pro, MatrixSubj_inactive",
    Cond2 %in% c("l", "m")   ~ "Retro, ShortPP",
    Cond2 %in% c("n1", "o")  ~ "Retro, LongPP_nonlocal",
    Cond2 %in% c("n2", "p")  ~ "Retro, LongPP_local",
    .default = NA_character_
  )) %>%
  mutate(
    Config = factor(Config, levels=c("Retro, SRC_ShortObj", "Retro, ORC_ShortSubj",
                                     "Retro, ORC_LongSubj_nonlocal", "Retro, ORC_LongSubj_local",
                                     "Pro, MatrixSubj_active", "Pro, MatrixSubj_inactive",
                                     "Retro, ShortPP", "Retro, LongPP_nonlocal", "Retro, LongPP_local")),
    Distractor = factor(Distractor, levels=c('singular', 'plural')),
    Verb_number = factor(Verb_number, levels=c('singular', 'plural'))
    )


dodge <- position_dodge(width = 0.3)
ggplot(summary.AA, aes(x = Distractor, y = mean, color = Verb_number)) +
  geom_point(position = dodge, size=2) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
                position = dodge, width = 0) +
  facet_wrap(~ Config) +
  labs(x = "Distractor", y = "Verb Surprisal (± SE)", color = "Verb Number") +
  theme_bw() +
  theme(legend.position = "bottom")



############################
# Locality Effects
############################

d.LT <- d %>% filter(Word_id == LT_Crit_pos)



