
suppressMessages(library(RKernel))

# ## Preparing the data
# The data we are using are in the file "ESS-relig-CHES.RData".

suppressMessages(library(memisc))
library(magrittr)


load(file="ESS-relig-CHES.RData")

# We restrict our analysis to the denominationally mixed countries in Western
# Europe, that is, Germany, the Netherlands, Switzerland, and the United Kingdom.

ESS_denom_west <- subset(ESS_denom_CHES,
    country2 %in% c(
        "Austria",
        "Belgium/Wallonia","Belgium/Flanders","Belgium/Brussels",
        "Denmark",
        "France",
        "Germany (West)","Germany/Bavaria",
        "Ireland",
        "Italy",
        "Luxembourg",
        "Netherlands",
        "Norway",
        "Portugal",
        "Spain/Castilia","Spain/Catalunia","Spain/Basque",
        "Sweden",
        "Switzerland",
        "United Kingdom/England",
        "United Kingdom/Scotland",
        "United Kingdom/Wales"
    ),
    select=c(CHES_id,
             year,
             essround,
             denom,
             oesch8,
             wgt,
             id,
             country2,
             lrecon,
             galtan,
             spendvtax,
             deregulation,
             redistribution,
             civlib_laworder,
             sociallifestyle,
             religious_principles,
             immigration))


ESS_denom_west %<>% as.data.frame()

# The information about religious denomination appears to be incorrect or misleading 
# in France until 2005 and in the United Kingdom from 2004 to 2007 and after 2020.

options(contrasts=c("contr.sum","contr.sum"))


ESS_denom_west %<>% within({
    Country <- recode(as.character(country2),
                      c("Belgium/Wallonia","Belgium/Flanders","Belgium/Brussels") -> "Belgium",
                      c("Germany (West)","Germany/Bavaria") -> "Germany",
                      c("Spain/Castilia","Spain/Catalunia","Spain/Basque") -> "Spain",
                      c("United Kingdom/England","United Kingdom/Scotland","United Kingdom/Wales") 
                          -> "United Kingdom",
                      copy=TRUE)
    Country <- factor(Country,levels=sort(levels(Country)))
    denom[Country=="France" & year <= 2005 | 
         Country=="United Kingdom" & year >= 2004 & year <= 2007] <- NA
    relmemb <- recode(as.numeric(denom),
                      "Christian"     <- 1:4,
                      "Non-Christian" <- 5,
                      "No religion"   <- 6
                     )
})


ESS_denom_west %<>% within({
    foreach(x = c(lrecon,
                  galtan,
                  spendvtax,
                  deregulation,
                  redistribution,
                  civlib_laworder,
                  sociallifestyle,
                  religious_principles,
                  immigration),
            y = c(lrecon.sq,
                  galtan.sq,
                  spendvtax.sq,
                  deregulation.sq,
                  redistribution.sq,
                  civlib_laworder.sq,
                  sociallifestyle.sq,
                  religious_principles.sq,
                  immigration.sq),
            {
                x <- (x-5)/10
                y <- x^2
            })
    oesch8 <- factor(oesch8,levels=levels(oesch8)[c(3,1:2,4:8)]) # Production workers as baseline
    country <- factor(country2) # Drop countries not included in this subset
    time <- (year - 2010)/10
    contrasts(relmemb) <- contr("sum", base = 1)
    contrasts(oesch8) <- contr("sum", base = 1)
    })


subset(ESS_denom_west, is.finite(galtan)) %$% range(year)


subset(ESS_denom_west, is.finite(religious_principles)) %$% range(year)


subset(ESS_denom_west, is.finite(sociallifestyle)) %$% range(year)

# ## Loading the models

library(mclogit)


load("model-relmemb-relprin-context.RData")
load("model-relmemb-soclife-context.RData")
load("model-relmemb-galtan-context.RData")

# ## Visualisation: Comparing all three dimensions

source("vis-helpers.R")


predigrid.relprin <- prob_grid_create(model=model_relprin,
                                      data=subset(ESS_denom_west,is.finite(religious_principles)),
                                      relmemb=levels(relmemb),
                                      oesch8=levels(oesch8),
                                      lrecon=0,
                                      religious_principles=.25,
                                      immigration=0,
                                      Secularization=0,
                                      year=2014,
                                      center_time=2014,
                                      reference=c(religious_principles=0))
predigrid.relprin %<>% subset(oesch8=="Clerks")


predigrid.soclife <- prob_grid_create(model=model_soclife,
                                      data=subset(ESS_denom_west,is.finite(sociallifestyle)),
                                      relmemb=levels(relmemb),
                                      oesch8=levels(oesch8),
                                      lrecon=0,
                                      sociallifestyle=.25,
                                      immigration=0,
                                      Secularization=0,
                                      year=2014,
                                      center_time=2014,
                                      reference=c(sociallifestyle=0))
predigrid.soclife %<>% subset(oesch8=="Clerks")


predigrid.galtan <- prob_grid_create(model=model_galtan,
                                      data=subset(ESS_denom_west,is.finite(galtan)),
                                      relmemb=levels(relmemb),
                                      oesch8=levels(oesch8),
                                      lrecon=0,
                                      Secularization=0,
                                      galtan=.25,
                                      year=2014,
                                      center_time=2010,
                                      reference=c(galtan=0))
predigrid.galtan %<>% subset(oesch8=="Clerks")


library(ggplot2)


percdiff_predigrid <- function(predigrid,i1=1,i2=3) {
    with(predigrid,(100*(prob[i1] - prob[i2])))
}


percdiff_predigrid(predigrid.relprin)
percdiff_predigrid(predigrid.soclife)
percdiff_predigrid(predigrid.galtan)


library(gridExtra)


source("vis-helpers.R")


(g.relprin.relmemb <- ggpoints(data=predigrid.relprin,
         x=relmemb,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         labels=c(title="Religious principles",y="Predicted probability",x=""),
         ylim=c(.25,.75),
         percentages=TRUE
         ))


(g.soclife.relmemb <- ggpoints(data=predigrid.soclife,
         x=relmemb,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         labels=c(title="Social life style",y="Predicted probability",x=""),
         ylim=c(.25,.75),
         percentages=TRUE
         ))


(g.galtan.relmemb <- ggpoints(data=predigrid.galtan,
         x=relmemb,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         labels=c(title="GAL/TAN",y="Predicted probability",x=""),
         ylim=c(.25,.75),
         percentages=TRUE
         ))


#!cell_opt: jupyter.plot.width=7,jupyter.plot.height=4
(gg <- grid.arrange(
    g.relprin.relmemb,
    drop_annot_y(g.soclife.relmemb),
    drop_annot_y(g.galtan.relmemb),
    nrow=1,
    widths=c(4,3,3)+1
))


ggsave(gg,file="relmemb-context-comparison/compare-relmemb-dimensions.pdf")
ggsave(gg,file="relmemb-context-comparison/compare-relmemb-dimensions.png")




