source("RemembR/R/RemembeR.R")
library(arrow)
library(data.table)
library(ggplot2)
library(filelock)
library(argparser)

parser <- arg_parser("Simulate data and fit corrected models.")
parser <- add_argument(parser, "--infile", default="robustness_3_dv.feather", help="name of the file to read.")
parser <- add_argument(parser, "--remember-file", default="remembr.RDS", help="name of the remember file.")
parser <- add_argument(parser, "--name", default="", help="The name to safe the data to in the remember file.")
args <- parse_args(parser)

## summarize.estimator <- function(df, suffix='naive', coefname='x'){

##     part <- df[,c('N',
##                   'm',
##                   'Bxy',
##                   paste0('B',coefname,'y.est.',suffix),
##                   paste0('B',coefname,'y.ci.lower.',suffix),
##                   paste0('B',coefname,'y.ci.upper.',suffix),
##                   'y_explained_variance',
##                   'Bzy'
##                   ),
##                with=FALSE]
    
##     true.in.ci <- as.integer((part$Bxy >= part[[paste0('B',coefname,'y.ci.lower.',suffix)]]) & (part$Bxy <= part[[paste0('B',coefname,'y.ci.upper.',suffix)]]))
##     zero.in.ci <- as.integer(0 >= part[[paste0('B',coefname,'y.ci.lower.',suffix)]]) & (0 <= part[[paste0('B',coefname,'y.ci.upper.',suffix)]])
##     bias <- part$Bxy - part[[paste0('B',coefname,'y.est.',suffix)]]
##     sign.correct <- as.integer(sign(part$Bxy) == sign(part[[paste0('B',coefname,'y.est.',suffix)]]))

##     part <- part[,':='(true.in.ci = true.in.ci,
##                        zero.in.ci = zero.in.ci,
##                        bias=bias,
##                        sign.correct =sign.correct)]

##     part.plot <- part[, .(p.true.in.ci = mean(true.in.ci),
##                           mean.bias = mean(bias),
##                           mean.est = mean(.SD[[paste0('B',coefname,'y.est.',suffix)]]),
##                           var.est = var(.SD[[paste0('B',coefname,'y.est.',suffix)]]),
##                           est.upper.95 = quantile(.SD[[paste0('B',coefname,'y.est.',suffix)]],0.95),
##                           est.lower.95 = quantile(.SD[[paste0('B',coefname,'y.est.',suffix)]],0.05),
##                           N.sims = .N,
##                           p.sign.correct = mean(as.integer(sign.correct & (! zero.in.ci))),
##                           variable=coefname,
##                           method=suffix
##                           ),
##                       by=c("N","m",'Bzy','y_explained_variance')
##                       ]
    
##     return(part.plot)
## }

source("summarize_estimator.R")

build_plot_dataset <- function(df){

    x.true <- summarize.estimator(df, 'true','x')
    z.true <- summarize.estimator(df, 'true','z')

    x.naive <- summarize.estimator(df, 'naive','x')
    z.naive <- summarize.estimator(df, 'naive','z')
    
    x.feasible <- summarize.estimator(df, 'feasible','x')
    z.feasible <- summarize.estimator(df, 'feasible','z')
    
    x.amelia.full <- summarize.estimator(df, 'amelia.full','x')
    z.amelia.full <- summarize.estimator(df, 'amelia.full','z')

    x.mle <- summarize.estimator(df, 'mle','x')
    z.mle <- summarize.estimator(df, 'mle','z')

    x.zhang <- summarize.estimator(df, 'zhang','x')
    z.zhang <- summarize.estimator(df, 'zhang','z')
    
    accuracy <- df[,mean(accuracy)]

    plot.df <- rbindlist(list(x.true, z.true, x.naive,z.naive,x.amelia.full,z.amelia.full,x.mle, z.mle, x.zhang, z.zhang, x.feasible, z.feasible),use.names=T)

    plot.df[,accuracy := accuracy]

    plot.df <- plot.df[,":="(sd.est=sqrt(var.est)/N.sims)]

    return(plot.df)
}

change.remember.file(args$remember_file, clear=TRUE)
sims.df <- read_feather(args$infile)
plot.df <- build_plot_dataset(sims.df)

remember(plot.df,args$name)

set.remember.prefix(gsub("plot.df.","",args$name))

remember(median(sims.df$cor.xz),'med.cor.xz')
remember(median(sims.df$accuracy),'med.accuracy')
remember(mean(sims.df$accuracy),'mean.accuracy')
remember(median(sims.df$error.cor.x),'med.error.cor.x')
remember(median(sims.df$error.cor.z),'med.error.cor.z')
remember(median(sims.df$lik.ratio),'med.lik.ratio')




## df[gmm.ER_pval<0.05]
## plot.df.test <- plot.df[,':='(method=factor(method,levels=c("Naive","Multiple imputation", "Multiple imputation (Classifier features unobserved)","Regression Calibration","2SLS+gmm","Bespoke MLE", "Feasible"),ordered=T),
##                                    N=factor(N),
##                                    m=factor(m))]


## plot.df.test <- plot.df.test[(variable=='z') & (m != 1000) & (m!=500) & !is.na(p.true.in.ci) & (method!="Multiple imputation (Classifier features unobserved)")]
## p <- ggplot(plot.df.test, aes(y=mean.est, ymax=mean.est + var.est/2, ymin=mean.est-var.est/2, x=method))
## p <- p + geom_hline(aes(yintercept=-0.05),linetype=2)

## p <- p + geom_pointrange() + facet_grid(m~N,as.table=F) + scale_x_discrete(labels=label_wrap_gen(4))
## print(p)
## ggplot(plot.df[variable=='x'], aes(y=mean.est, ymax=mean.est + var.est/2, ymin=mean.est-var.est/2, x=method)) + geom_pointrange() + facet_grid(-m~N) + scale_x_discrete(labels=label_wrap_gen(10))

## ggplot(plot.df,aes(y=N,x=m,color=p.sign.correct)) + geom_point() + facet_grid(variable ~ method) + scale_color_viridis_c(option='D') + theme_minimal() + xlab("Number of gold standard labels") + ylab("Total sample size") 

## ggplot(plot.df,aes(y=N,x=m,color=abs(mean.bias))) + geom_point() + facet_grid(variable ~ method) + scale_color_viridis_c(option='D') + theme_minimal() + xlab("Number of gold standard labels") + ylab("Total sample size") 
