library(tidyverse)
library(plyr) 
library(stringr)
try(setwd(dirname(rstudioapi::getActiveDocumentContext()$path)))
#load in data
contrib_df <- read_csv("../final_data/deb_contrib_pop_change.csv")
readme_df <- read_csv("../final_data/deb_readme_pop_change.csv")
#some expansion needs to happens for each project 
expand_timeseries <- function(project_row) {
  longer <- project_row |> 
    pivot_longer(cols = ends_with("new"),
                 names_to = "window",
                 values_to = "count") |>
    unnest(count) |>
    mutate(after_doc = as.numeric(str_detect(window, "after"))) |>
    mutate(is_collab = as.numeric(str_detect(window, "collab")))
  return(longer)
}
expanded_readme_data <- expand_timeseries(readme_df[1,])
for (i in 2:nrow(readme_df)){
  expanded_readme_data <- rbind(expanded_readme_data, expand_timeseries(readme_df[i,]))
}
expanded_contrib_data <- expand_timeseries(contrib_df[1,])
for (i in 2:nrow(contrib_df)){
  expanded_contrib_data <- rbind(expanded_contrib_data, expand_timeseries(contrib_df[i,]))
}
expanded_readme_data$log1pcount <- log1p(expanded_readme_data$count)
expanded_contrib_data$log1pcount <- log1p(expanded_contrib_data$count)
expanded_readme_data$logcount <- log(expanded_readme_data$count)
expanded_contrib_data$logcount <- log(expanded_contrib_data$count)
#breaking out the types of population counts
collab_pop_readme <- expanded_readme_data[which(expanded_readme_data$is_collab == 1),]
contrib_pop_readme <- expanded_readme_data[which(expanded_readme_data$is_collab == 0),]
collab_pop_contrib <- expanded_contrib_data[which(expanded_contrib_data$is_collab == 1),]
contrib_pop_contrib <- expanded_contrib_data[which(expanded_contrib_data$is_collab == 0),]
#import models 
library(lme4)
library(optimx)
collab_readme_model <- glmer.nb(log1pcount ~ after_doc + (after_doc| upstream_vcs_link), data=collab_pop_readme)
summary(collab_readme_model)
saveRDS(collab_readme_model, "0510_pop_rm_collab.rda")
crm_residuals <- residuals(collab_readme_model)
qqnorm(crm_residuals)
contrib_readme_model <- glmer.nb(log1pcount ~ after_doc + (after_doc| upstream_vcs_link), data=contrib_pop_readme)
summary(contrib_readme_model)
saveRDS(contrib_readme_model, "0510_pop_rm_contrib.rda")
conrm_residuals <- residuals(contrib_readme_model)
qqnorm(conrm_residuals)
collab_contrib_model <- glmer.nb(log1pcount ~ after_doc + (after_doc| upstream_vcs_link), data=collab_pop_contrib)
summary(collab_contrib_model)
saveRDS(collab_contrib_model, "0510_pop_contrib_collab.rda")
contrib_contrib_model <- glmer.nb(log1pcount ~ after_doc + (after_doc| upstream_vcs_link), data=contrib_pop_contrib)
summary(contrib_contrib_model)
saveRDS(contrib_contrib_model, "0510_pop_contrib_contrib.rda")

library(ggplot2)
expanded_readme_data |>
  ggplot(aes(x = after_doc, y = log1pcount, col = as.factor(is_collab))) +
  geom_point() + geom_jitter()

expanded_contrib_data |>
  ggplot(aes(x = after_doc, y = count, col = as.factor(is_collab))) +
  geom_point() + geom_jitter()
