source("testfunctions.r")
wd <- getwd()
setwd("../..")
### source edge files here
source("cluster.r")
source("thread.r")
setwd(wd)

verylargematrix <- NULL
vlmrows <- 20000
vlmcols <- 228


test.cluster.setup <- function() {
  if (is.null(verylargematrix)) {
    seed <- 5257122
    
    ## Set random seed
    set.seed(seed)
    
    ## Generate very large matrix
    print("Generating large matrix...")
    verylargematrix <<- matrix(rnorm(vlmrows*vlmcols), ncol=vlmcols)
    print("Matrix generated.")
  }
}

### Try to cluster an extremely large matrix
test.cluster.1 <- function() {
  test.cluster.setup()
  
  ## Expect an out of memory error
  err <- NULL
  tryCatch(storeyclust.func(verylargematrix), error=function(e) err <<- e)
  expected = "Not enough memory."
  if(is.null(err)) {
    stop("Expected an error but didn't get one")
  } else {
    if (substr(err$message, 0, nchar(expected)) != expected)
      stop(paste("Got a different error than expected: ", err))
  }
}

### Try to cluster an extremely large matrix in a background thread.
test.cluster.2 <- function() {
  test.cluster.setup()
  
  print("Start clustering...")
  params <- list()
  params$m <- verylargematrix
  params$distance <- "euclidean"
  params$orderfunc <- "none"

  ## Expect an out of memory error
  err <- NULL
  tid <- NULL
  tryCatch(tid <- storeyclust.start.func(params), error=function(e) err <<- e)
  expected = "Not enough memory."
  if(is.null(err)) {
    stop("Expected an error but didn't get one")
  } else {
    if (substr(err$message, 0, nchar(expected)) != expected)
      stop(paste("Got a different error than expected: ", err))
  }
  if(!is.null(tid))
    thread.stop.func(tid)
}

## Test a successful cluster
test.cluster.3 <- function() {
  m <- matrix(c(3, 7, 6, 8), ncol=1)
  hc <- storeyclust.func(m, 0, "euclidean")
  expOrd = c(0, 3, 1, 2)
  if(!all(hc$order == expOrd)) {
    eos <- paste(expOrd, collapse=" ")
    hcs <- paste(hc$order, collapse=" ")
    stop(paste("Expected order", eos, "got", hcs))
  }
}
