# R code to dump fair test dataset to 
# checking compatibility.
#
# Usage:
#   Rscript test_get_R_tweedie_var_weight.R > res_R_var_weight.py
cat("# This file auto-generated by test_get_R_tweedie_var_weight.R\n")
cat(sprintf("# Using: %s\n", R.Version()$version.string))
cat("import numpy as np\n")
cat("import pandas as pd\n")
cat("import os\n\n")
cat("from statsmodels.tools.tools import Bunch\n\n")
cat("path = os.path.abspath(__file__)\n")
cat("dir_path = os.path.dirname(path)\n")

require(statmod)

options(digits=20)
x <- (1.5)^(0:19)

MISSING <- "MISSING"

is.missing <- function(obj) {
  length(obj) == 1 && obj == MISSING
}

pyprint <- function(arr, prefix=NULL, suffix=NULL) {
  if (!is.null(prefix)) {
    cat(prefix)
  }
  if (is.missing(arr)) {
    cat("None\n")
  } else {
    cat("np.array([")
    cat("\n    ")
    i <- 1
    for (val in arr) {
      cat(val)
      if (i == length(arr)) {
        if (i %% 3 != 1) {
          cat("\n")
        }
      }
      else if (i %% 3 == 0) {
        cat(",\n    ")
      }
      else {
        cat(", ")
      }
      i <- 1 + i
    }
    cat("])")
    if (!is.null(dim(arr))) {
      cat(".reshape((")
      j <- 1
      for (size in dim(arr)) {
        cat(sprintf("%s", size))
        if (j < length(dim(arr))) {
          cat(", ")
        }
        j <- 1 + j
      }
      cat("), order=\"F\")")
    }
  }
  if (!is.null(suffix)) {
    cat(sprintf("%s\n", suffix))
  }
  else {
    cat("\n")
  }
}

cat("

")

out2py <- function(model, name, resid_csv = FALSE){
  cat("\nres = dict()\n")
  pyprint(model$coefficients, prefix = "res['params'] = ")
  pyprint(diag(vcov(model))^0.5, prefix = "res['bse'] = ")
  cat(sprintf("res['deviance'] = %f\n", model$deviance))
  
  ll = logLik(model)
  
  if (is.na(ll)) {
    cat("res['ll'] = np.nan\n")
  } else {
    cat(sprintf("res['ll'] = %f\n", ll))
  }
  
  cat("res['resids_colnames'] = [\n    'resid_response', 'resid_pearson', 'resid_deviance', 'resid_working']\n" )
  
  r <- cbind(residuals.glm(model, 'response'),
             residuals.glm(model, 'pearson'),
             residuals.glm(model, 'deviance'),
             residuals.glm(model, 'working'))
  
  if (is.character(resid_csv)) {
    write.csv(r, resid_csv, row.names = FALSE)
    cat(sprintf("csv_path = os.path.join(dir_path, '%s')\n", resid_csv))
    cat(sprintf("resids = np.array(pd.read_csv(csv_path))\n"))
    cat(sprintf("res['resids'] = resids\n"))
  } else {
    pyprint(r, "res['resids'] = ")
  }
  cat(sprintf("%s = Bunch(**res)\n", name))
}

control <- glm.control(epsilon = 1e-25, maxit = 100)

data = read.csv('../../../datasets/fair/fair.csv')
data$weights <- rep(1, length(data$rate_marriage))
data$weights[seq(1, length(data$rate_marriage), 5)] <- 5
data$weights[seq(1, length(data$rate_marriage), 13)] <- 3

model <- glm(affairs ~ 1 + age + yrs_married,
             data = data,
             family = tweedie(var.power = 1.55, link.power = 0),
             weights = weights,
             control = control)

out2py(model, "results_tweedie_aweights_nonrobust", "results_tweedie_aweights_nonrobust.csv")

data <- read.csv('stata_cancer_glm.csv')
data$weights <- rep(1, length(data$studytime))
data$weights[seq(1, length(data$studytime), 5)] <- 5
data$weights[seq(1, length(data$studytime), 13)] <- 3
data$drug <- as.factor(data$drug)

model <- glm(studytime ~ 1 + age + drug,
             data = data,
             family = Gamma(link = "log"),
             weights = weights,
             control = control)

out2py(model, "results_gamma_aweights_nonrobust")

data <- read.csv('../../../datasets/cpunish/cpunish.csv')
data$INCOME <- data$INCOME / 1000
data$weight <- c(1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1)

model <- glm(EXECUTIONS ~ INCOME + SOUTH - 1,
             data = data,
             family = gaussian(link = "log"),
             weights = weight,
             control = control)

out2py(model, "results_gaussian_aweights_nonrobust")
