library(densratio)
source('./lib_functions_dre.R')

# Script Global Parameter
ALL_RHOS=c(0.0)
ALL_DIMS=c(10, 20, 30, 50, 100)

##### Script Run Setting #####
DATA_PARENT_DIR="DRE/data/"
OUT_DIR <- './out/Expr_Section_6_2'
MTHEOD_TYPE='uLSIF'
KERNEL_NUM=100
##############################


IsTest=FALSE
if(IsTest){
  ALL_DIMS <- ALL_DIMS[1:2]
  OUT_DIR <- file.path('./out', 'TEST', 'DRE')
}
for(i_rho in 1:length(ALL_RHOS)){
  rho <- ALL_RHOS[i_rho]
  data_rho_dir <- sprintf("rho_%02.0f", rho*10)
  res_df_all_DMs_list <- vector(
    mode = "list", length = length(ALL_DIMS))
  set.seed(2024)
  for(i_dim in 1:length(ALL_DIMS)){
    dim <- ALL_DIMS[i_dim]
    data_dim_dir <- sprintf("Dim_%03d", dim)
    exp_data_top_dir <- file.path(DATA_PARENT_DIR, 
                                  data_rho_dir,
                                  data_dim_dir)
    exp_data_dirs <- dir(exp_data_top_dir)
    if(IsTest){
      exp_data_dirs <- exp_data_dirs[1:3]
      ALL_DIMS <- ALL_DIMS[1:2]
    }  
    res_df_one_DM_list <-vector(
      mode = "list", length = length(exp_data_dirs))
    for(i_exp_dir in 1:length(exp_data_dirs)){
      exp_dir <- exp_data_dirs[i_exp_dir]

      res_mse <- pred_and_calc_mse_with_densratio(
        data_top_dir=exp_data_top_dir,
        experiment_dir=exp_dir,
        densratio_method=MTHEOD_TYPE,
        densratio_kernel_num=KERNEL_NUM
      )

      cat(data_rho_dir, data_dim_dir, exp_dir, res_mse, "\n")
      res_df <- data.frame(row.names=exp_dir, res_mse)
      colnames(res_df) <- c(data_dim_dir)
      res_df_one_DM_list[[i_exp_dir]] <- res_df
    }
    res_df_one_DM <- do.call("rbind", res_df_one_DM_list)
    res_df_all_DMs_list[[i_dim]] <- res_df_one_DM
  }
  all_resul_df <- do.call("cbind", res_df_all_DMs_list)
  dir.create(OUT_DIR, recursive=TRUE)
  out_file_name <- sprintf("%s_Dim_all.csv",
                           MTHEOD_TYPE)
  write.csv(all_resul_df, file.path(OUT_DIR, out_file_name))
}

  