### EXAMPLE 1: demonstrates how measurement error can lead to a type sign error in a covariate
### What kind of data invalidates fong + tyler?
### Even when you have a good predictor, if it's biased against a covariate you can get the wrong sign.
### Even when you include the proxy variable in the regression.
### But with some ground truth and multiple imputation, you can fix it.

library(argparser)
library(mecor)
library(ggplot2)
library(data.table)
library(filelock)
library(arrow)
library(Amelia)
library(Zelig)
library(predictionError)
options(amelia.parallel="no",
        amelia.ncpus=1)
setDTthreads(40)

source("simulation_base.R")

## SETUP:
### we want to estimate x -> y; x is MAR
### we have x -> k; k -> w; x -> w is used to predict x via the model w.
### A realistic scenario is that we have an NLP model predicting something like "racial harassment" in social media comments
### The labels x are binary, but the model provides a continuous predictor

### simulation:
#### how much power do we get from the model in the first place? (sweeping N and m)
#### 

## one way to do it is by adding correlation to x.obs and y that isn't in w.
## in other words, the model is missing an important feature of x.obs that's related to y.
simulate_data <- function(N, m, B0, Bxy, Bzx, Bzy, seed, y_explained_variance=0.025, prediction_accuracy=0.73, y_bias=-0.8,z_bias=0,accuracy_imbalance_difference=0.3){
    set.seed(seed)
    # make w and y dependent
    z <- rnorm(N,sd=0.5)
    x <- rbinom(N, 1, plogis(Bzx * z))

    y.var.epsilon <- (var(Bzy * z) + var(Bxy *x) + 2*cov(Bzy*z,Bxy*x)) * ((1-y_explained_variance)/y_explained_variance)
    y.epsilon <- rnorm(N, sd = sqrt(y.var.epsilon))
    y <- Bzy * z + Bxy * x + y.epsilon
    
    df <- data.table(x=x,y=y,z=z)

    if(m < N){
        df <- df[sample(nrow(df), m), x.obs := x]
    } else {
        df <- df[, x.obs := x]
    }

    ## probablity of an error is correlated with y
    ## pz <- mean(z)
    ## accuracy_imbalance_ratio <- (prediction_accuracy + accuracy_imbalance_difference/2) / (prediction_accuracy - accuracy_imbalance_difference/2)

    ## # this works because of conditional probability
    ## accuracy_z0 <- prediction_accuracy / (pz*(accuracy_imbalance_ratio) + (1-pz))
    ## accuracy_z1 <- accuracy_imbalance_ratio * accuracy_z0

    ## z0x0 <- df[(z==0) & (x==0)]$x
    ## z0x1 <- df[(z==0) & (x==1)]$x
    ## z1x0 <- df[(z==1) & (x==0)]$x
    ## z1x1 <- df[(z==1) & (x==1)]$x

    ## yz0x0 <- df[(z==0) & (x==0)]$y
    ## yz0x1 <- df[(z==0) & (x==1)]$y
    ## yz1x0 <- df[(z==1) & (x==0)]$y
    ## yz1x1 <- df[(z==1) & (x==1)]$y

    ## nz0x0 <- nrow(df[(z==0) & (x==0)])
    ## nz0x1 <- nrow(df[(z==0) & (x==1)])
    ## nz1x0 <- nrow(df[(z==1) & (x==0)])
    ## nz1x1 <- nrow(df[(z==1) & (x==1)])

    ## yz1 <- df[z==1]$y 
    ## yz1 <- df[z==1]$y 

    ## # tranform yz0.1 into a logistic distribution with mean accuracy_z0
    ## acc.z0x0 <- plogis(0.5*scale(yz0x0) + qlogis(accuracy_z0))
    ## acc.z0x1 <- plogis(0.5*scale(yz0x1) + qlogis(accuracy_z0))
    ## acc.z1x0 <- plogis(1.5*scale(yz1x0) + qlogis(accuracy_z1))
    ## acc.z1x1 <- plogis(1.5*scale(yz1x1) + qlogis(accuracy_z1))

    ## w0z0x0 <- (1-z0x0)**2 + (-1)**(1-z0x0) * acc.z0x0
    ## w0z0x1 <- (1-z0x1)**2 + (-1)**(1-z0x1) * acc.z0x1
    ## w0z1x0 <- (1-z1x0)**2 + (-1)**(1-z1x0) * acc.z1x0
    ## w0z1x1 <- (1-z1x1)**2 + (-1)**(1-z1x1) * acc.z1x1

    ## ##perrorz0 <- w0z0*(pyz0)
    ## ##perrorz1 <- w0z1*(pyz1)

    ## w0z0x0.noisy.odds <- rlogis(nz0x0,qlogis(w0z0x0))
    ## w0z0x1.noisy.odds <- rlogis(nz0x1,qlogis(w0z0x1))
    ## w0z1x0.noisy.odds <- rlogis(nz1x0,qlogis(w0z1x0))
    ## w0z1x1.noisy.odds <- rlogis(nz1x1,qlogis(w0z1x1))

    ## df[(z==0)&(x==0),w:=plogis(w0z0x0.noisy.odds)]
    ## df[(z==0)&(x==1),w:=plogis(w0z0x1.noisy.odds)]    
    ## df[(z==1)&(x==0),w:=plogis(w0z1x0.noisy.odds)]    
    ## df[(z==1)&(x==1),w:=plogis(w0z1x1.noisy.odds)]    

    ## df[,w_pred:=as.integer(w > 0.5)]
    ## print(mean(df[z==0]$x == df[z==0]$w_pred))
    ## print(mean(df[z==1]$x == df[z==1]$w_pred))
    ## print(mean(df$w_pred == df$x))

    resids <- resid(lm(y~x + z))
    odds.x1 <- qlogis(prediction_accuracy) + y_bias*qlogis(pnorm(resids[x==1])) + z_bias * qlogis(pnorm(z,sd(z)))
    odds.x0 <- qlogis(prediction_accuracy,lower.tail=F) + y_bias*qlogis(pnorm(resids[x==0])) + z_bias * qlogis(pnorm(z,sd(z)))

    ## acc.x0 <- p.correct[df[,x==0]]
    ## acc.x1 <- p.correct[df[,x==1]]

    df[x==0,w:=plogis(rlogis(.N,odds.x0))]
    df[x==1,w:=plogis(rlogis(.N,odds.x1))]

    df[,w_pred := as.integer(w > 0.5)]


    print(mean(df$w_pred == df$x))
    print(mean(df[y>=0]$w_pred == df[y>=0]$x))
    print(mean(df[y<=0]$w_pred == df[y<=0]$x))
    return(df)
}

parser <- arg_parser("Simulate data and fit corrected models")
parser <- add_argument(parser, "--N", default=5000, help="number of observations of w")
parser <- add_argument(parser, "--m", default=500, help="m the number of ground truth observations")
parser <- add_argument(parser, "--seed", default=51, help='seed for the rng')
parser <- add_argument(parser, "--outfile", help='output file', default='example_2.feather')
parser <- add_argument(parser, "--y_explained_variance", help='what proportion of the variance of y can be explained?', default=0.1)
parser <- add_argument(parser, "--prediction_accuracy", help='how accurate is the predictive model?', default=0.75)
parser <- add_argument(parser, "--accuracy_imbalance_difference", help='how much more accurate is the predictive model for one class than the other?', default=0.3)
parser <- add_argument(parser, "--Bzx", help='Effect of z on x', default=0.3)
parser <- add_argument(parser, "--Bzy", help='Effect of z on y', default=-0.3)
parser <- add_argument(parser, "--Bxy", help='Effect of z on y', default=0.3)
parser <- add_argument(parser, "--outcome_formula", help='formula for the outcome variable', default="y~x+z")
parser <- add_argument(parser, "--proxy_formula", help='formula for the proxy variable', default="w_pred~y*z*x")
parser <- add_argument(parser, "--y_bias", help='coefficient of y on the probability a classification is correct', default=-0.5)
parser <- add_argument(parser, "--z_bias", help='coefficient of z on the probability a classification is correct', default=0)
parser <- add_argument(parser, "--truth_formula", help='formula for the true variable', default="x~z")

args <- parse_args(parser)

B0 <- 0
Bxy <- args$Bxy
Bzy <- args$Bzy
Bzx <- args$Bzx

if(args$m < args$N){

    df <- simulate_data(args$N, args$m, B0, Bxy, Bzx, Bzy, args$seed, args$y_explained_variance, args$prediction_accuracy, y_bias=args$y_bias)

    ## df.pc <- df[,.(x,y,z,w_pred,w)]
    ##                                     #    df.pc <- df.pc[,err:=x-w_pred]
    ## pc.df <- pc(suffStat=list(C=cor(df.pc),n=nrow(df.pc)),indepTest=gaussCItest,labels=names(df.pc),alpha=0.05)
    ## plot(pc.df)

    result <- list('N'=args$N,'m'=args$m,'B0'=B0,'Bxy'=Bxy, Bzx=args$Bzx, 'Bzy'=Bzy, 'seed'=args$seed, 'y_explained_variance'=args$y_explained_variance, 'prediction_accuracy'=args$prediction_accuracy, 'accuracy_imbalance_difference'=args$accuracy_imbalance_difference, 'y_bias'=args$y_bias,'outcome_formula'=args$outcome_formula, 'proxy_formula'=args$proxy_formula,truth_formula=args$truth_formula, error='')

    outline <- run_simulation(df, result, outcome_formula=as.formula(args$outcome_formula), proxy_formula=as.formula(args$proxy_formula), truth_formula=as.formula(args$truth_formula))
    
   
 outfile_lock <- lock(paste0(args$outfile, '_lock'),exclusive=TRUE)
    if(file.exists(args$outfile)){
        logdata <- read_feather(args$outfile)
        logdata <- rbind(logdata,as.data.table(outline), fill=TRUE)
    } else {
        logdata <- as.data.table(outline)
    }

    print(outline)
    write_feather(logdata, args$outfile)
    unlock(outfile_lock)
}
