# this is the file with the lmer multi-level rddAnalysis
library(tidyverse)
library(plyr) 
# 0 loading the readme data in 
try(setwd(dirname(rstudioapi::getActiveDocumentContext()$path)))
readme_df <- read_csv("../final_data/deb_readme_did.csv")
# 1 preprocessing 
#colnames(readme_df) <- c("upstream_vcs_link", "event_date", "event_hash", "before_all_ct", "before_mrg_ct", "after_all_ct", "after_mrg_ct", "before_auth_new", "after_commit_new", "after_auth_new", "before_commit_new")
col_order <- c("upstream_vcs_link", "age_in_days", "first_commit", "first_commit_dt", "event_gap", "event_date", "event_hash", "before_all_ct", "after_all_ct", "before_mrg_ct", "after_mrg_ct", "before_auth_new", "after_auth_new", "before_commit_new",  "after_commit_new")
readme_df <- readme_df[,col_order]
readme_df$ct_before_all <- str_split(gsub("[][]","", readme_df$before_all_ct), ", ")
readme_df$ct_after_all <- str_split(gsub("[][]","", readme_df$after_all_ct), ", ")
readme_df$ct_before_mrg <- str_split(gsub("[][]","", readme_df$before_mrg_ct), ", ")
readme_df$ct_after_mrg <- str_split(gsub("[][]","", readme_df$after_mrg_ct), ", ")
drop <- c("before_all_ct", "before_mrg_ct", "after_all_ct", "after_mrg_ct")
readme_df = readme_df[,!(names(readme_df) %in% drop)]
# 2 some expansion needs to happens for each project 
expand_timeseries <- function(project_row) {
  longer <- project_row |> 
    pivot_longer(cols = starts_with("ct"),
                 names_to = "window",
                 values_to = "count") |>
    unnest(count) 
  longer$observation_type <- gsub("^.*_", "", longer$window)
  longer <- ddply(longer, "observation_type", transform, week=seq(from=0, by=1, length.out=length(observation_type)))
  longer$count <- as.numeric(longer$count)
  #longer <- longer[which(longer$observation_type == "all"),]
  return(longer)
}
expanded_data <- expand_timeseries(readme_df[1,])
for (i in 2:nrow(readme_df)){
  expanded_data <- rbind(expanded_data, expand_timeseries(readme_df[i,]))
}
#filter out the windows of time that we're looking at
window_num <- 8
windowed_data <- expanded_data |>
  filter(week >= (27 - window_num) & week <= (27 + window_num)) |>
  mutate(D = ifelse(week > 27, 1, 0))
#scale the age numbers 
windowed_data$scaled_project_age <- scale(windowed_data$age_in_days)
windowed_data$scaled_event_gap <- scale(event_gap)
windowed_data$week_offset <- windowed_data$week - 27
#break out the different types of commit actions that are studied
all_actions_data <- windowed_data[which(windowed_data$observation_type == "all"),]
mrg_actions_data <- windowed_data[which(windowed_data$observation_type == "mrg"),]
#log the dependent 
all_actions_data$logged_count <- log(all_actions_data$count)
all_actions_data$log1p_count <- log1p(all_actions_data$count)
range(all_actions_data$log1p_count)
# 3 rdd in lmer analysis
# rdd: https://rpubs.com/phle/r_tutorial_regression_discontinuity_design
# lmer: https://www.youtube.com/watch?v=LzAwEKrn2Mc
# https://www.bristol.ac.uk/cmm/learning/videos/random-intercepts.html#exvar
library(lme4)
library(optimx)
library(lattice)
#some more EDA to go between Poisson and neg binomial
var(all_actions_data$log1p_count) # 1.125429
mean (all_actions_data$log1p_count) # 0.6426873
median(all_actions_data$log1p_count) #0
var(all_actions_data$count) # 268.4449
mean (all_actions_data$count) # 3.757298
median(all_actions_data$count) # 0
print("fitting model")
all_log1p_gmodel <- glmer.nb(log1p_count ~ D * week_offset+ scaled_project_age + scaled_event_gap + (D * week_offset | upstream_vcs_link), data=all_actions_data, nAGQ=1,  control=glmerControl(optimizer="bobyqa",
                         optCtrl=list(maxfun=1e5)))
#all_log1p_gmodel <- readRDS("0624_log1p_nagq_gmodel_backup.rda")
summary(all_log1p_gmodel)
saveRDS(all_log1p_gmodel, "0624_eventgap_rm_rdd.rda")
print("model fit")
#I grouped the ranef D effects on 0624
all_residuals <- residuals(all_log1p_gmodel)
qqnorm(all_residuals)
library(broom.mixed)
test_condvals <- broom.mixed::tidy(all_log1p_gmodel, effects = "ran_vals", conf.int = TRUE)
test_glmer_ranef_D <- test_condvals [which(test_condvals $term == "D"),]
has_zero <- function(estimate, low, high){
  return(ifelse((low < 0),ifelse((high > 0), 1, 0), 2))
}
test_glmer_ranef_D <- test_glmer_ranef_D |>
  mutate(ranef_grouping = has_zero(estimate, conf.low, conf.high)) |>
  mutate(rank = rank(estimate))
g <- test_glmer_ranef_D |> 
  ggplot(aes(x=rank, y=estimate, col = as.factor(ranef_grouping))) +
  geom_linerange(aes(ymin= conf.low, ymax= conf.high)) +
  theme_bw()
g
write.csv(test_glmer_ranef_D, "062424_readme_grouped_1.csv")
ggsave("0624caterpillar.png", g)
print("all pau")