# Modeling public opinion over time and space: Trust in state institutions in Europe, 1989-2019
# 
# 31 January 2021
#
# Replication materials: Imputation of demographic data for post-stratification


# Packages
library(dplyr)
library(tidyr)
library(brms)

options(mc.cores = parallel::detectCores())

bind <- function(...) cbind(...)

nchains <- 4
niter <- 2000
nwarmup <- 1000

countries <- c("AT", "BE", "BG", "CH", "CZ", "DE", "DK", "EE", "ES", "FI", 
               "FR", "GB", "GR", "HU", "IE", "IT", "LT", "LU", "LV", "NL", 
               "NO", "PL", "PT", "RO", "SE", "SI", "SK")	

data <- readRDS("3_imputation_demographics/eurostat_ipums_20201020.rds") %>%
  filter(geo %in% countries) %>%
  spread(educ3, prop_cat, sep = "_")

data$educ3 <- with(data, cbind(educ3_1, educ3_2, educ3_3))


ms <- list()

for (cntry in countries) {
  
  ms[[cntry]] <- brm(bind(educ3_1, educ3_2, educ3_3) ~ s(time, age_cat, bs="fs") + s(time, sex, bs="fs"), 
                     family = dirichlet(), 
                     data = data[data$geo == cntry, ],
                     chains = nchains,
                     iter = niter,
                     warmup = nwarmup,
                     inits = 0)
}

saveRDS(ms, "3_imputation_demographics/models_cntry_spline_20201020.rds")

