
suppressMessages(library(RKernel))
options(width=200)

# ## 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")


load(file="perc-denom-country-wide.RData")

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

ESS_work_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"
    ) & !is.na(sociallifestyle),
    select=c(CHES_id,
             year,
             essround,
             denom,
             oesch8,
             wgt,
             id,
             country2,
             lrecon,
             galtan,
             spendvtax,
             deregulation,
             redistribution,
             civlib_laworder,
             sociallifestyle,
             religious_principles,
             immigration))


ESS_work_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_work_west %<>% within({
    Country <- recode(as.character(country2),
                      c("Belgium/Wallonia","Belgium/Flanders","Belgium/Brussels") -> "Belgium",
                      c("Germany (West)","Germany/Bavaria") -> "Germany (West)",
                      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_work_west <- merge(ESS_work_west, perc.denom.country.wide,
                       by.x = 'Country',
                       by.y = 'country',
                       all.x = TRUE,
                       all.y = FALSE)


ESS_work_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)
    Secularization <- (No_religion - 50)/100
    Cath_Prot <- (Cath_Prot - 50)/100
    })


library(mclogit)


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

# ## Visualisation

source("vis-helpers.R")


gridpoints <- sort(unique(c(-.25,.25,seq(from=-.5,to=.5,length=21))))


predigrid.soclife <- prob_grid_create(model=model_soclife,
                                      data=ESS_work_west,
                                      relmemb=levels(relmemb),
                                      oesch8=levels(oesch8),
                                      lrecon=0,
                                      sociallifestyle=gridpoints,
                                      immigration=0,
                                      Secularization=c(-.4,0,.4),
                                      reference=c(sociallifestyle=0))


predigrid.soclife %$$% {
    Secularization <- Secularization*100 + 50
    Secularization <- recode(Secularization,
                             "Low (10%)" <- 10,
                             "Medium (50%)" <- 50,
                             "High (90%)" <- 90)
}


predigrid.soclife.aver <- subset(predigrid.soclife, time == 0 & oesch8 == "Clerks")
predigrid.soclife.time <- subset(predigrid.soclife, sociallifestyle == 7.5 & oesch8 == "Clerks")


library(ggplot2)


#!cell_opt: jupyter.plot.width=10, jupyter.plot.height=4.5
(g.soclife.relmemb.aver <- ggcurves(data=predigrid.soclife.aver,
         x=sociallifestyle,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         grp=relmemb,
         labels=c(x="Social Lifestyle position",y="Predicted probability",linetype=""),
         percentages=TRUE,
         vline=7.5                   
         ) + facet_wrap(~Secularization, labeller="label_both"))
ggsave(g.soclife.relmemb.aver, file="relmemb-context-soclife/relmemb-context-soclife.pdf")
ggsave(g.soclife.relmemb.aver, file="relmemb-context-soclife/relmemb-context-soclife.png")


#!cell_opt: jupyter.plot.width=10, jupyter.plot.height=4.5
(g.soclife.relmemb.time <- ggcurves(data=predigrid.soclife.time,
         x=year,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         grp=relmemb,
         labels=c(x="Social Lifestyle position",y="Predicted probability",linetype=""),
         percentages=TRUE,
         vline=2014                   
         ) + facet_wrap(~Secularization, labeller="label_both"))
ggsave(g.soclife.relmemb.time, file="relmemb-context-soclife/relmemb-context-soclife-time.pdf")
ggsave(g.soclife.relmemb.time, file="relmemb-context-soclife/relmemb-context-soclife-time.png")

