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

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


ESS_work_west <- subset(ESS_relatt_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(religious_principles),
    select=c(CHES_id,
             year,
             essround,
             denom,
             relatt,
             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",
                      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
    cathprot <- recode(as.numeric(denom),
                      "Catholic"     <- 1,
                      "Protestant"   <- 2
                     )
})


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(cathprot) <- contr("sum", base = 1)
    contrasts(oesch8) <- contr("sum", base = 1)
    contrasts(relatt) <- contr("sum", base = 1)
    No_religion <- (No_religion - 50)/100
    Denom_Het <- 2*(1-(Cath_Prot/100)^2-(1-Cath_Prot/100)^2)
    })


library(mclogit)


load("model-churchat-cathprot-relprin-context.RData")


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


source("vis-helpers.R")


#debug(prob_grid_create)
options(error=NULL)


predigrid.relprin <- prob_grid_create(model=model_relprin,
                                      data=ESS_work_west,
                                      relatt=levels(relatt),
                                      cathprot=levels(cathprot),
                                      oesch8=levels(oesch8),
                                      lrecon=0,
                                      religious_principles=gridpoints,
                                      immigration=0,
                                      No_religion=0,
                                      Cath_Prot = c(95,50,5),
                                      reference=c(religious_principles=0),
                                      transformations=list(
                                          Denom_Het = 2*(1-(Cath_Prot/100)^2-(1-Cath_Prot/100)^2),
                                          Cath_Prot = (Cath_Prot-50)/100
                                      ))


predigrid.relprin %$$% {
    Cath_Prot <- Cath_Prot*100 + 50
    Cath_Prot <- recode(Cath_Prot,
                         "Mostly Catholic" <- 95,
                         "Mixed" <- 50,
                         "Mostly Protestant" <- 5) 
}


predigrid.relprin.relatt.aver <- subset(predigrid.relprin, time == 0 & oesch8 == "Clerks" & 
                                          relatt %in% c("Never","Monthly","Weekly") & Cath_Prot == "Mixed")
predigrid.relprin.relatt.time <- subset(predigrid.relprin, religious_principles == 7.5 & oesch8 == "Clerks" & 
                                          relatt %in% c("Never","Monthly","Weekly") & Cath_Prot == "Mixed")


predigrid.relprin.context.aver <- subset(predigrid.relprin, time == 0 & oesch8 == "Clerks" & 
                                          relatt == "Weekly")
predigrid.relprin.context.time <- subset(predigrid.relprin, religious_principles == 7.5 & oesch8 == "Clerks" & 
                                          relatt == "Weekly")


library(ggplot2)


add_pray <- function(string) paste("Prays:",string)
add_country <- function(string) paste("Country:",string)


#!cell_opt: jupyter.plot.width=4.5, jupyter.plot.height=4.5
(g.relprin.relatt.catholic.aver <- ggcurves(data=subset(predigrid.relprin.relatt.aver, cathprot=="Catholic"),
         x=religious_principles,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         grp=relatt,
         labels=c(x="Religious Principles position",y="Predicted probability",linetype="Attends church:"),
         vline=7.5,
         percentages=TRUE                   
         ))
ggsave(g.relprin.relatt.catholic.aver,file="churchat-context-relprin/churchat-context-relprin-catholic-aver.pdf")
ggsave(g.relprin.relatt.catholic.aver,file="churchat-context-relprin/churchat-context-relprin-catholic-aver.png")


#!cell_opt: jupyter.plot.width=4.5, jupyter.plot.height=4.5
(g.relprin.relatt.protestant.aver <- ggcurves(data=subset(predigrid.relprin.relatt.aver, cathprot=="Protestant"),
         x=religious_principles,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         grp=relatt,
         labels=c(x="Religious Principles position",y="Predicted probability",linetype="Attends church:"),
         vline=7.5,
         percentages=TRUE                   
         ))
ggsave(g.relprin.relatt.protestant.aver,file="churchat-context-relprin/churchat-context-relprin-protestant-aver.pdf")
ggsave(g.relprin.relatt.protestant.aver,file="churchat-context-relprin/churchat-context-relprin-protestant-aver.png")


#!cell_opt: jupyter.plot.width=7, jupyter.plot.height=4.5
(g.relprin.relatt.protestant.aver <- ggcurves(data=predigrid.relprin.relatt.aver,
         x=religious_principles,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         grp=relatt,
         labels=c(x="Religious Principles position",y="Predicted probability",linetype="Attends church:"),
         vline=7.5,
         percentages=TRUE                   
         ) + facet_wrap(~cathprot))
ggsave(g.relprin.relatt.protestant.aver,file="churchat-context-relprin/churchat-context-relprin-cathprot-aver.pdf")
ggsave(g.relprin.relatt.protestant.aver,file="churchat-context-relprin/churchat-context-relprin-cathprot-aver.png")


#!cell_opt: jupyter.plot.width=4.5, jupyter.plot.height=4.5
(g.relprin.relatt.catholic.time <- ggcurves(data=subset(predigrid.relprin.relatt.time,cathprot=="Catholic"),
         x=year,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         grp=relatt,
         labels=c(x="Religious Principles position",y="Predicted probability",linetype="Attends church:"),
         vline=2014,
         percentages=TRUE                   
         ))

ggsave(g.relprin.relatt.catholic.time,file="churchat-context-relprin/churchat-context-relprin-catholic-time.pdf")
ggsave(g.relprin.relatt.catholic.time,file="churchat-context-relprin/churchat-context-relprin-catholic-time.png")


#!cell_opt: jupyter.plot.width=4.5, jupyter.plot.height=4.5
(g.relprin.relatt.catholic.aver <- ggcurves(data=subset(predigrid.relprin.relatt.aver, cathprot=="Catholic"),
         x=religious_principles,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         grp=relatt,
         labels=c(x="Religious Principles position",y="Predicted probability",linetype="Attends church:"),
         vline=7.5,
         percentages=TRUE                   
         ))
ggsave(g.relprin.relatt.catholic.aver,file="churchat-context-relprin/churchat-context-relprin-catholic-aver.pdf")
ggsave(g.relprin.relatt.catholic.aver,file="churchat-context-relprin/churchat-context-relprin-catholic-aver.png")


#!cell_opt: jupyter.plot.width=4.5, jupyter.plot.height=4.5
(g.relprin.relatt.protestant.time <- ggcurves(data=subset(predigrid.relprin.relatt.time,cathprot=="Protestant"),
         x=year,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         grp=relatt,
         labels=c(x="Religious Principles position",y="Predicted probability",linetype="Attends church:"),
         vline=2014,
         percentages=TRUE                   
         ))

ggsave(g.relprin.relatt.protestant.time,file="churchat-context-relprin/churchat-context-relprin-protestant-time.pdf")
ggsave(g.relprin.relatt.protestant.time,file="churchat-context-relprin/churchat-context-relprin-protestant-time.png")


#!cell_opt: jupyter.plot.width=7, jupyter.plot.height=4.5
(g.relprin.relatt.protestant.time <- ggcurves(data=predigrid.relprin.relatt.time,
         x=year,
         y=prob,
         ymin=prob.lower,
         ymax=prob.upper,
         grp=relatt,
         labels=c(x="Religious Principles position",y="Predicted probability",linetype="Attends church:"),
         vline=2014,
         percentages=TRUE                   
         ) + facet_wrap(~cathprot))

ggsave(g.relprin.relatt.protestant.time,file="churchat-context-relprin/churchat-context-relprin-cathprot-time.pdf")
ggsave(g.relprin.relatt.protestant.time,file="churchat-context-relprin/churchat-context-relprin-cathprot-time.png")




