# R code to dump the output from 'bs()' in many situations, for
# checking compatibility.
#
# Usage:
#   Rscript tools/get-R-bs-test-vectors.R > patsy/test_splines_bs_data.py
cat("# This file auto-generated by tools/get-R-bs-test-vectors.R\n")
cat(sprintf("# Using: %s\n", R.Version()$version.string))
cat("import numpy as np\n")

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

MISSING <- "MISSING"

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

pyprint <- function(arr) {
  if (is.missing(arr)) {
    cat("None\n")
  } else {
    cat("np.array([")
    for (val in arr) {
      cat(val)
      cat(", ")
    }
    cat("])")
    if (!is.null(dim(arr))) {
      cat(".reshape((")
      for (size in dim(arr)) {
        cat(sprintf("%s, ", size))
      }
      cat("), order=\"F\")")
    }
    cat("\n")
  }
}

num.tests <- 0
dump.bs <- function(degree, df, knots,
                    intercept, Boundary.knots) {
  cat("--BEGIN TEST CASE--\n")
  cat(sprintf("degree=%s\n", degree))
  cat(sprintf("df=%s\n", if (is.missing(df)) "None" else df))
  cat(sprintf("intercept=%s\n", intercept))
  cat("Boundary.knots=")
  pyprint(Boundary.knots)
  cat("knots=")
  pyprint(knots)

  args <- list(x=x, degree=degree, intercept=intercept)
  if (!is.missing(df)) {
    args$df <- df
  }
  if (!is.missing(knots)) {
    args$knots <- knots
  }
  if (!is.missing(Boundary.knots)) {
    args$Boundary.knots <- Boundary.knots
  }
  result <- do.call(bs, args)

  cat("output=")
  pyprint(result)
  cat("--END TEST CASE--\n")
  assign("num.tests", num.tests + 1, envir=.GlobalEnv)
}

cat("R_bs_test_x = ")
pyprint(x)
cat("R_bs_test_data = \"\"\"\n")

for (degree in c(1, 3, 5)) {
  for (intercept in c(TRUE, FALSE)) {
    for (Boundary.knots in list(MISSING, c(0, 3000))) {
      for (df in c(3, 5, 12)) {
        if (df < degree + 2) {
          next
        } else {
          dump.bs(degree, df, MISSING, intercept, Boundary.knots)
        }
      }
      for (knots in list(c(), c(100), c(1000), c(10, 100, 1000))) {
        dump.bs(degree, MISSING, knots, intercept, Boundary.knots)
      }
    }
  }
}
cat("\"\"\"\n")
cat(sprintf("R_bs_num_tests = %s\n", num.tests))
