source("testfunctions.r")
wd <- getwd()
setwd("../..")
source("knnImpute.r")
source("util.r")
setwd(wd)

remove.impute.package <- function() {
  err <- NULL
  if(file.access(knnimp.pkgdir, 0) == 0)
    tryCatch(remove.packages("impute", lib=knnimp.pkgdir), error=function(e) err <<-e)
}

test.load.impute.package.1 <- function() {
  ## Remove the impute package if it is loaded
  remove.impute.package()
  oldWarn = getOption("warn")
  options(warn = -1)
  pdesc <- packageDescription("impute", lib.loc=knnimp.pkgdir)
  assert(class(pdesc) != "packageDescription")
  tryCatch(assert(is.na(pdesc)), finally=options(warn = oldWarn))
  
  ## Load impute package
  load.impute.package()
  desc <- packageDescription("impute", lib.loc=knnimp.pkgdir)
  assert(class(desc)=="packageDescription")
  assert(compareVersion(desc$Version, "1.0-4") == 0)
}

## brca_small_missing is missing gene 2, arrays 1 and 7
test.impute.1 <- function() {
  ## Make sure we don't download the package
  oldurl <- knnimp.pkgurl
  knnimp.pkgurl <- "INVALID"
#  tryCatch(test.impute.1.int(), error=function(e) stop(e), finally= knnimp.pkgurl<-oldurl )
}

test.impute.1.int <- function()
{
  expr.data <<- readexpr.func("data/brca_small_missing.txt")$exprs

  ## Dataset sanity check: It has NAs...
  assert(is.na(expr.data[2,1]))
  assert(is.na(expr.data[2,7]))
  assert(sum(is.na(expr.data)) == 2)

  ## Impute NA data.
  expr.data.imputed <- do.impute.knn(dat=expr.data, 2, rowmax=1, colmax=1, maxp=1500)

  ## Check that there aren't any NAs in the imputed dataset
  assert(!any(is.na(expr.data.imputed)))

  ## Check that all non-NA values were left as-is
  assert(all(expr.data[!is.na(expr.data)] == expr.data.imputed[!is.na(expr.data)]))
  print(expr.data.imputed[is.na(expr.data)])
} 
