library(predictionError)
library(mecor)
options(amelia.parallel="no",
        amelia.ncpus=1)
library(Amelia)
library(Zelig)
library(stats4)


## This uses the pseudolikelihood approach from Carroll page 349.
## assumes MAR
## assumes differential error, but that only depends on Y
## inefficient, because pseudolikelihood
logistic.correction.pseudo <- function(df){
    p1.est <- mean(df[w_pred==1]$y.obs==1,na.rm=T)
    p0.est <- mean(df[w_pred==0]$y.obs==0,na.rm=T)
    
    nll <- function(B0, Bxy, Bgy){
        probs <- (1 - p0.est) + (p1.est + p0.est - 1)*plogis(B0 + Bxy * df$x + Bgy * df$g)

        part1 = sum(log(probs[df$w_pred == 1]))
        part2 = sum(log(1-probs[df$w_pred == 0]))
        
        return(-1*(part1 + part2))
    }
    
    mlefit <- stats4::mle(minuslogl = nll, start = list(B0=0, Bxy=0.0, Bgy=0.0))
    return(mlefit)

}

## This uses the likelihood approach from Carroll page 353.
## assumes that we have a good measurement error model
logistic.correction.liklihood <- function(df){
    
    ## liklihood for observed responses
    nll <- function(B0, Bxy, Bgy, gamma0, gamma_y, gamma_g){
        df.obs <- df[!is.na(y.obs)]
        p.y.obs <- plogis(B0 + Bxy * df.obs$x + Bgy*df.obs$g)
        p.y.obs[df.obs$y==0] <- 1-p.y.obs[df.obs$y==0]
        p.s.obs <- plogis(gamma0 + gamma_y * df.obs$y + gamma_g*df.obs$g)
        p.s.obs[df.obs$w_pred==0] <- 1 - p.s.obs[df.obs$w_pred==0]
        
        p.obs <- p.s.obs * p.y.obs

        df.unobs <- df[is.na(y.obs)]

        p.unobs.1 <- plogis(B0 + Bxy * df.unobs$x + Bgy*df.unobs$g)*plogis(gamma0 + gamma_y + gamma_g*df.unobs$g)
        p.unobs.0 <- (1-plogis(B0 + Bxy * df.unobs$x + Bgy*df.unobs$g))*plogis(gamma0 + gamma_g*df.unobs$g)
        p.unobs <- p.unobs.1 + p.unobs.0
        p.unobs[df.unobs$w_pred==0] <- 1 - p.unobs[df.unobs$w_pred==0]

        p <- c(p.obs, p.unobs)

        return(-1*(sum(log(p))))
    }

    mlefit <- stats4::mle(minuslogl = nll, start = list(B0=1, Bxy=0,Bgy=0, gamma0=5, gamma_y=0, gamma_g=0))

    return(mlefit)
}


logistic <- function(x) {1/(1+exp(-1*x))}

run_simulation_depvar <- function(df, result){

    accuracy <- df[,mean(w_pred==y)]
    result <- append(result, list(accuracy=accuracy))

    (model.true <- glm(y ~ x + g, data=df,family=binomial(link='logit')))
    true.ci.Bxy <- confint(model.true)['x',]
    true.ci.Bgy <- confint(model.true)['g',]

    result <- append(result, list(Bxy.est.true=coef(model.true)['x'],
                                  Bgy.est.true=coef(model.true)['g'],
                                  Bxy.ci.upper.true = true.ci.Bxy[2],
                                  Bxy.ci.lower.true = true.ci.Bxy[1],
                                  Bgy.ci.upper.true = true.ci.Bgy[2],
                                  Bgy.ci.lower.true = true.ci.Bgy[1]))
                                  
    (model.feasible <- glm(y.obs~x+g,data=df,family=binomial(link='logit')))

    feasible.ci.Bxy <- confint(model.feasible)['x',]
    result <- append(result, list(Bxy.est.feasible=coef(model.feasible)['x'],
                                  Bxy.ci.upper.feasible = feasible.ci.Bxy[2],
                                  Bxy.ci.lower.feasible = feasible.ci.Bxy[1]))

    feasible.ci.Bgy <- confint(model.feasible)['g',]
    result <- append(result, list(Bgy.est.feasible=coef(model.feasible)['g'],
                                  Bgy.ci.upper.feasible = feasible.ci.Bgy[2],
                                  Bgy.ci.lower.feasible = feasible.ci.Bgy[1]))

    (model.naive <- glm(w_pred~x+g, data=df, family=binomial(link='logit')))

    naive.ci.Bxy <- confint(model.naive)['x',]
    naive.ci.Bgy <- confint(model.naive)['g',]

    result <- append(result, list(Bxy.est.naive=coef(model.naive)['x'],
                                  Bgy.est.naive=coef(model.naive)['g'],
                                  Bxy.ci.upper.naive = naive.ci.Bxy[2],
                                  Bxy.ci.lower.naive = naive.ci.Bxy[1],
                                  Bgy.ci.upper.naive = naive.ci.Bgy[2],
                                  Bgy.ci.lower.naive = naive.ci.Bgy[1]))


    (model.naive.cont <- lm(w~x+g, data=df))
    naivecont.ci.Bxy <- confint(model.naive.cont)['x',]
    naivecont.ci.Bgy <- confint(model.naive.cont)['g',]

    ## my implementatoin of liklihood based correction
    mod.caroll.lik <- logistic.correction.liklihood(df)
    coef <- coef(mod.caroll.lik)
    ci <- confint(mod.caroll.lik)

    result <- append(result,
                     list(Bxy.est.mle = coef['Bxy'],
                          Bxy.ci.upper.mle = ci['Bxy','97.5 %'],
                          Bxy.ci.lower.mle = ci['Bxy','2.5 %'],
                          Bgy.est.mle = coef['Bgy'],
                          Bgy.ci.upper.mle = ci['Bgy','97.5 %'],
                          Bgy.ci.lower.mle = ci['Bgy','2.5 %']))
                          

    ## my implementatoin of liklihood based correction
    mod.caroll.pseudo <- logistic.correction.pseudo(df)
    coef <- coef(mod.caroll.pseudo)
    ci <- confint(mod.caroll.pseudo)

    result <- append(result,
                     list(Bxy.est.pseudo = coef['Bxy'],
                          Bxy.ci.upper.pseudo = ci['Bxy','97.5 %'],
                          Bxy.ci.lower.pseudo = ci['Bxy','2.5 %'],
                          Bgy.est.pseudo = coef['Bgy'],
                          Bgy.ci.upper.pseudo = ci['Bgy','97.5 %'],
                          Bgy.ci.lower.pseudo = ci['Bgy','2.5 %']))
                          

    # amelia says use normal distribution for binary variables.
    amelia.out.k <- amelia(df, m=200, p2s=0, idvars=c('y','ystar','w_pred'))
    mod.amelia.k <- zelig(y.obs~x+g, model='ls', data=amelia.out.k$imputations, cite=FALSE)
    (coefse <- combine_coef_se(mod.amelia.k, messages=FALSE))

    est.x.mi <- coefse['x','Estimate']
    est.x.se <- coefse['x','Std.Error']
    result <- append(result,
                     list(Bxy.est.amelia.full = est.x.mi,
                          Bxy.ci.upper.amelia.full = est.x.mi + 1.96 * est.x.se,
                          Bxy.ci.lower.amelia.full = est.x.mi - 1.96 * est.x.se
                          ))

    est.g.mi <- coefse['g','Estimate']
    est.g.se <- coefse['g','Std.Error']

    result <- append(result,
                     list(Bgy.est.amelia.full = est.g.mi,
                          Bgy.ci.upper.amelia.full = est.g.mi + 1.96 * est.g.se,
                          Bgy.ci.lower.amelia.full = est.g.mi - 1.96 * est.g.se
                          ))

    return(result)

}

run_simulation <-  function(df, result){

    accuracy <- df[,mean(w_pred==x)]
    result <- append(result, list(accuracy=accuracy))

    (model.true <- lm(y ~ x + g, data=df))
    true.ci.Bxy <- confint(model.true)['x',]
    true.ci.Bgy <- confint(model.true)['g',]

    result <- append(result, list(Bxy.est.true=coef(model.true)['x'],
                                  Bgy.est.true=coef(model.true)['g'],
                                  Bxy.ci.upper.true = true.ci.Bxy[2],
                                  Bxy.ci.lower.true = true.ci.Bxy[1],
                                  Bgy.ci.upper.true = true.ci.Bgy[2],
                                  Bgy.ci.lower.true = true.ci.Bgy[1]))
                                  
    (model.feasible <- lm(y~x.obs+g,data=df))

    feasible.ci.Bxy <- confint(model.feasible)['x.obs',]
    result <- append(result, list(Bxy.est.feasible=coef(model.feasible)['x.obs'],
                                  Bxy.ci.upper.feasible = feasible.ci.Bxy[2],
                                  Bxy.ci.lower.feasible = feasible.ci.Bxy[1]))

    feasible.ci.Bgy <- confint(model.feasible)['g',]
    result <- append(result, list(Bgy.est.feasible=coef(model.feasible)['g'],
                                  Bgy.ci.upper.feasible = feasible.ci.Bgy[2],
                                  Bgy.ci.lower.feasible = feasible.ci.Bgy[1]))

    (model.naive <- lm(y~w+g, data=df))
    
    naive.ci.Bxy <- confint(model.naive)['w',]
    naive.ci.Bgy <- confint(model.naive)['g',]

    result <- append(result, list(Bxy.est.naive=coef(model.naive)['w'],
                                  Bgy.est.naive=coef(model.naive)['g'],
                                  Bxy.ci.upper.naive = naive.ci.Bxy[2],
                                  Bxy.ci.lower.naive = naive.ci.Bxy[1],
                                  Bgy.ci.upper.naive = naive.ci.Bgy[2],
                                  Bgy.ci.lower.naive = naive.ci.Bgy[1]))
                                  

    amelia.out.k <- amelia(df, m=200, p2s=0, idvars=c('x','w_pred'))
    mod.amelia.k <- zelig(y~x.obs+g, model='ls', data=amelia.out.k$imputations, cite=FALSE)
    (coefse <- combine_coef_se(mod.amelia.k, messages=FALSE))

    est.x.mi <- coefse['x.obs','Estimate']
    est.x.se <- coefse['x.obs','Std.Error']
    result <- append(result,
                     list(Bxy.est.amelia.full = est.x.mi,
                          Bxy.ci.upper.amelia.full = est.x.mi + 1.96 * est.x.se,
                          Bxy.ci.lower.amelia.full = est.x.mi - 1.96 * est.x.se
                          ))

    est.g.mi <- coefse['g','Estimate']
    est.g.se <- coefse['g','Std.Error']

    result <- append(result,
                     list(Bgy.est.amelia.full = est.g.mi,
                          Bgy.ci.upper.amelia.full = est.g.mi + 1.96 * est.g.se,
                          Bgy.ci.lower.amelia.full = est.g.mi - 1.96 * est.g.se
                          ))

    ## What if we can't observe k -- most realistic scenario. We can't include all the ML features in a model.
    ## amelia.out.nok <- amelia(df, m=200, p2s=0, idvars=c("x","w_pred"), noms=noms)
    ## mod.amelia.nok <- zelig(y~x.obs+g, model='ls', data=amelia.out.nok$imputations, cite=FALSE)
    ## (coefse <- combine_coef_se(mod.amelia.nok, messages=FALSE))

    ## est.x.mi <- coefse['x.obs','Estimate']
    ## est.x.se <- coefse['x.obs','Std.Error']
    ## result <- append(result,
    ##                  list(Bxy.est.amelia.nok = est.x.mi,
    ##                       Bxy.ci.upper.amelia.nok = est.x.mi + 1.96 * est.x.se,
    ##                       Bxy.ci.lower.amelia.nok = est.x.mi - 1.96 * est.x.se
    ##                       ))

    ## est.g.mi <- coefse['g','Estimate']
    ## est.g.se <- coefse['g','Std.Error']

    ## result <- append(result,
    ##                  list(Bgy.est.amelia.nok = est.g.mi,
    ##                       Bgy.ci.upper.amelia.nok = est.g.mi + 1.96 * est.g.se,
    ##                       Bgy.ci.lower.amelia.nok = est.g.mi - 1.96 * est.g.se
    ##                       ))

    N <- nrow(df)
    m <- nrow(df[!is.na(x.obs)])
    p <- v <- train <- rep(0,N)
    M <- m
    p[(M+1):(N)] <- 1
    v[1:(M)] <- 1
    df <- df[order(x.obs)]
    y <- df[,y]
    x <- df[,x.obs]
    g <- df[,g]
    w <- df[,w]
    # gmm gets pretty close
    (gmm.res <- predicted_covariates(y, x, g, w, v, train, p, max_iter=100, verbose=TRUE))

    result <- append(result,
                     list(Bxy.est.gmm = gmm.res$beta[1,1],
                          Bxy.ci.upper.gmm = gmm.res$confint[1,2],
                          Bxy.ci.lower.gmm = gmm.res$confint[1,1],
                          gmm.ER_pval = gmm.res$ER_pval
                          ))

    result <- append(result,
                     list(Bgy.est.gmm = gmm.res$beta[2,1],
                          Bgy.ci.upper.gmm = gmm.res$confint[2,2],
                          Bgy.ci.lower.gmm = gmm.res$confint[2,1]))


    mod.calibrated.mle <- mecor(y ~ MeasError(w, reference = x.obs) + g, df, B=400, method='efficient')
    (mod.calibrated.mle)
    (mecor.ci <- summary(mod.calibrated.mle)$c$ci['x.obs',])
    result <- append(result, list(
                                 Bxy.est.mecor = mecor.ci['Estimate'],
                                 Bxy.upper.mecor = mecor.ci['UCI'],
                                 Bxy.lower.mecor = mecor.ci['LCI'])
                     )

    (mecor.ci <- summary(mod.calibrated.mle)$c$ci['g',])

    result <- append(result, list(
                                 Bgy.est.mecor = mecor.ci['Estimate'],
                                 Bgy.upper.mecor = mecor.ci['UCI'],
                                 Bgy.lower.mecor = mecor.ci['LCI'])
                     )

##    clean up memory
##    rm(list=c("df","y","x","g","w","v","train","p","amelia.out.k","amelia.out.nok", "mod.calibrated.mle","gmm.res","mod.amelia.k","mod.amelia.nok", "model.true","model.naive","model.feasible"))
    
##    gc()
    return(result)
}
