# Copyright (c) Microsoft Corporation.  All rights reserved.
#
# FUNCTIONS
#    Unit tests for RxComputeContext and related functions
#
############################################################################################

"test.RxComputeContext.args.context" <- function()
{
	testCC1 <- RxLocalSeq()
	testCC2 <- RxComputeContext( "RxLocalSeq" )
	testCC3 <- RxComputeContext( "local" )
	testCC4 <- RxComputeContext( testCC1 )
	checkEquals( testCC1, testCC2 )
	checkEquals( testCC1, testCC3 )
	checkEquals( testCC1, testCC4 )
	checkTrue( is( testCC1, "RxComputeContext") )
	checkTrue( !is( testCC1, "RxDistributedHpa") )
	
	testCC1 <- RxLocalParallel()
	testCC2 <- RxComputeContext( "RxLocalParallel" )
	testCC3 <- RxComputeContext( "localpar" )
	testCC4 <- RxComputeContext( testCC1 )
	checkEquals( testCC1, testCC2 )
	checkEquals( testCC1, testCC3 )
	checkEquals( testCC1, testCC4 )
	checkTrue( is( testCC1, "RxComputeContext") )		
    checkTrue( !is( testCC1, "RxDistributedHpa") )	
	
	testCC1 <- RxForeachDoPar()
	testCC2 <- RxComputeContext( "RxForeachDoPar" )
	testCC3 <- RxComputeContext( "dopar" )
	testCC4 <- RxComputeContext( testCC1 )
	checkEquals( testCC1, testCC2 )
	checkEquals( testCC1, testCC3 )
	checkEquals( testCC1, testCC4 )
	checkTrue( is( testCC1, "RxComputeContext") )		
    checkTrue( !is( testCC1, "RxDistributedHpa") )
		
	testCC1 <- RxInTeradata()
	testCC2 <- RxComputeContext( "RxInTeradata" )
	testCC3 <- RxComputeContext( "teradata" )
	testCC4 <- RxComputeContext( testCC1 )
  	
	# re-create with dataSource = NULL, otherwise checkEquals() will try to access the
	# data in the source to do comparison
	testCC5 <- RxComputeContext( testCC1, remoteShareDir = "/blah/blah/blah" )
	testCC6 <- RxInTeradata( remoteShareDir = "/blah/blah/blah" )
	
	checkEquals( testCC1, testCC2 )
	checkEquals( testCC1, testCC3 )
	checkEquals( testCC1, testCC4 )
	checkEquals( testCC5, testCC6 )
	testCC5@remoteShareDir = "/tmp"
	checkEquals(testCC1, testCC5)
	checkTrue( inherits( testCC1, "RxComputeContext") )
	checkTrue( inherits( testCC1, "RxDistributedHpa") )
	checkTrue( inherits( testCC1, "RxInTeradata") )			
	
	## RxHadoopMR

	testCC1 <- RxHadoopMR()
	testCC2 <- RxComputeContext( "RxHadoopMR" )
	testCC3 <- RxComputeContext( "hadoopmr" )
	testCC4 <- RxComputeContext( testCC1 )
	testCC5 <- RxComputeContext( testCC1, nameNode = "blahblah")
	testCC6 <- RxHadoopMR( nameNode = "blahblah" )
	checkEquals( testCC1, testCC2 )
	checkEquals( testCC1, testCC3 )
	checkEquals( testCC1, testCC4 )
	checkEquals( testCC5, testCC6 )
	testCC5@nameNode = "default"
	checkEquals(testCC1, testCC5)
	checkTrue( inherits( testCC1, "RxComputeContext") )
	checkTrue( inherits( testCC1, "RxDistributedHpa") )
	checkTrue( inherits( testCC1, "RxHadoopMR") )				
	
    ## RxSpark

	testCC1 <- RxSpark()
    testCC1@appId <- "1"
	testCC2 <- RxComputeContext( "RxSpark" )       
    testCC2@appId <- "1"
	testCC3 <- RxComputeContext( "spark" )
    testCC3@appId <- "1"
	testCC4 <- RxComputeContext( testCC1 )
    testCC4@appId <- "1"
	testCC5 <- RxComputeContext( testCC1, nameNode = "blahblah")
    testCC5@appId <- "1"
	testCC6 <- RxSpark( nameNode = "blahblah" )
    testCC6@appId <- "1"
	checkEquals( testCC1, testCC2 )
	checkEquals( testCC1, testCC3 )
	checkEquals( testCC1, testCC4 )
	checkEquals( testCC5, testCC6 )
	testCC5@nameNode = "default"
	checkEquals(testCC1, testCC5)
	checkTrue( inherits( testCC1, "RxComputeContext") )
	checkTrue( inherits( testCC1, "RxDistributedHpa") )
	checkTrue( inherits( testCC1, "RxSpark") )	
	
}


"test.RxLocalSeq.args.empty" <- function()
{
	testCC <- RxLocalSeq()
	checkEquals(testCC@description, "local")
	checkEquals(testCC@version, "1.0-1")
    checkTrue(is.null(testCC@dataPath))
    checkTrue(is.null(testCC@outDataPath))
	
	# Check a few functions to see if they behave reasonably
	# expect warnings
 
	suppressWarnings(nodeInfo <- rxGetNodeInfo( testCC ))
	checkTrue(is.null(nodeInfo))
	
	currentContext <- rxGetOption("computeContext")
	rxOptions(computeContext = "local")
	
	x <- 1:10
	rxExec(print, x, elemType = "cores", timesToRun = 10)

	y <- x + rep(c(1,2), times = 5)
	testData <- data.frame(x, y)
	rxLinMod(y~x, data = testData)
	
	rxOptions(computeContext = currentContext)	
}

"test.RxLocalSeq.args.object" <- function()
{
	sampleDataDir <- rxGetOption("sampleDataDir")
	testDir <- tempdir()
	cc1 <- RxLocalSeq(dataPath = sampleDataDir, outDataPath = testDir)
	cc2 <- RxLocalSeq(cc1)
	checkEquals(cc1@dataPath, cc2@dataPath)
	checkEquals(cc1@outDataPath, cc2@outDataPath)
	
    cc3 <- RxLocalParallel(dataPath = sampleDataDir, outDataPath = testDir)
	cc4 <- RxLocalSeq(cc3)
	checkEquals(cc1@dataPath, cc4@dataPath)
	checkEquals(cc1@outDataPath, cc4@outDataPath)	
}


"test.RxLocalParallel.args.empty" <- function()
{
	testCC <- RxLocalParallel()
	checkEquals(testCC@description, "localpar")
	checkEquals(testCC@version, "1.0-1")
	
	# Check a few functions to see if they behave reasonably
	# Should get NULL and warning message
 	suppressWarnings(nodeInfo <- rxGetNodeInfo( testCC ))	
	checkTrue(is.null(nodeInfo))
	
	currentContext <- rxGetOption("computeContext")
	rxOptions(computeContext = "localpar")
	
	x <- 1:10
	rxExec(print, x, elemType = "cores", timesToRun = 10)

	y <- x + rep(c(1,2), times = 5)
	testData <- data.frame(x, y)
	rxLinMod(y~x, data = testData)
	
	rxOptions(computeContext = currentContext)
}


"test.rxGetSetComputeContext.args.all" <- function()
{
	context1 <- rxGetComputeContext()
	
	# Set a new context
	context2 <- RxHpcServer( headNode = "blahblah" )
	context3 <- rxSetComputeContext(context2, headNode = "dodah")
	
	# Check that original context is returned
	checkEquals(context1, context3)
	context4 <- rxGetComputeContext()
	
	# Check that additional arguments are passed through
	checkEquals(tolower(context4@headNode), "dodah")
	
	# Reset original context
	rxSetComputeContext(context1)
}

"test.rxCreateDistributedJob" <- function()
{
	testCC <- RxHpcServer()
	testJob <- RevoScaleR:::rxCreateDistributedJob(testCC)
	checkTrue(all.equal(class(testJob), "RxDistributedJob", check.attributes=FALSE))	
	
	#testCC <- RxAzureBurst()
	#testJob <- RevoScaleR:::rxCreateDistributedJob(testCC)
	#checkTrue(all.equal(class(testJob), "RxDistributedJob", check.attributes=FALSE))	
	
	#testCC <- RxLsfCluster()
	#testJob <- RevoScaleR:::rxCreateDistributedJob(testCC)
	#checkTrue(all.equal(class(testJob), "RxDistributedJob", check.attributes=FALSE))	
	
	
	# this block currently commented out because RxHadoopMR object
	# cannot be constructed without a nameNode parameter - and so does
	# not seem to conform to our standards for compute context classes
	# Lee (or whoever works on RxHadoopMR()) can look at this further in the future
	#testCC <- RxHadoopMR()
	#testJob <- RevoScaleR:::rxCreateDistributedJob(testCC)
	#checkTrue(all.equal(class(testJob), "RxDistributedHadoopMRJob", check.attributes=FALSE))	
	
	testCC <- RxInTeradata()
	testJob <- RevoScaleR:::rxCreateDistributedJob(testCC)
	checkTrue(all.equal(class(testJob), "RxDistributedTeradataJob", check.attributes=FALSE))	
	
	# TODO: enable when distributed jobs are suppored on RxInSqlServer
	# testCC <- RxInSqlServer()
	# testJob <- RevoScaleR:::rxCreateDistributedJob(testCC)
	# checkTrue(all.equal(class(testJob), "RxDistributedSqlServerJob", check.attributes=FALSE))	
}

"test.RxLocalSeq.args.dataPath" <- function()
{
	#origDataPath <- rxGetOption("dataPath")
    #on.exit(rxOptions(dataPath = origDataPath), add= TRUE)  
  
  #if(Sys.info()["nodename"] == "autotest14-cent63-64")  DEACTIVATED("Pending resolution of RA-11258")
  #if(Sys.info()["nodename"] == "autotest12-cent58-64")  DEACTIVATED("Pending resolution of RA-11258")
  #if((Sys.info()["nodename"] == "AT03-cent5") & (rxGetOption("numCoresToUse") == -1))  DEACTIVATED("Pending resolution of RA-11258")  
  
  # Reactivated by SFW, 10/31/2014 so we can troubleshoot why test is failing on only some systems.
  #DEACTIVATED("Pending resolution of RA-11258")
  
  origComputeContext <- rxGetComputeContext()
	on.exit(rxSetComputeContext(origComputeContext), add = TRUE)
	
    inFile <- "test100r5b.xdf"
    inCsv <- "test100r.txt"
    outFile <- ".rxLocalSeq1.xdf"
    fullOutFile <- file.path(tempdir(), outFile)
    fullInPath <- normalizePath(file.path(rxGetOption("unitTestDataDir"), inFile))
    fullCsvPath <- normalizePath(file.path(rxGetOption("unitTestDataDir"), inCsv))
    
    if (file.exists(fullOutFile)) file.remove(fullOutFile)
    
	testComputeContext <- RxComputeContext("local", dataPath = rxGetOption("sampleDataDir"),
		outDataPath = tempdir())
	rxSetComputeContext(testComputeContext)  
    
    # Compute Lorenz data - no xdf extension specified
    lorenzOut <- rxLorenz(orderVarName = "incwage", data = "CensusWorkers",
	    pweights = "perwt")  
    checkEquals(attr(lorenzOut, "description"), "Wage and salary income")
    
    # Try an rxKmeans
    # Comment out rxKmeans part of test - will investigate cause of failure - Steve W., 11/4/14.
    ##  kmeansOut <- rxKmeans(~cost, data= "claims.xdf", numClusters = 2, numStarts = 4,
    ##    outFile = outFile)
    ##  checkTrue(file.exists(fullOutFile))
        file.remove(fullOutFile) 
             
    # Reset context to read from unitTestDataDir  
	testComputeContext <- RxComputeContext("local", dataPath = rxGetOption("unitTestDataDir"),
		outDataPath = tempdir())
	rxSetComputeContext(testComputeContext)
        
    # Try an rxQuantile
    quantOut1 <- rxQuantile("xnum1", data = inFile)
    quantOut2 <- rxQuantile("xnum1", data = fullInPath)
    checkEquals(quantOut1, quantOut2)    
            
	# Try rxDataStep
    rxDataStep(inData = inFile, outFile = outFile)
    checkTrue(file.exists(fullOutFile))
	fullOutFile <- normalizePath(fullOutFile)
    file.remove(fullOutFile)
    
    # Try rxReadXdf
    myData <- rxReadXdf(file = inFile)
    checkEquals(nrow(myData), 100)
        
    # Try rxLocateFile
    xdfFound <- rxLocateFile(inFile, pathsToSearch = rxGetOption("unitTestDataDir"))
    checkEquals(fullInPath, xdfFound)
    
    csvFound <- rxLocateFile(inCsv, pathsToSearch = rxGetOption("unitTestDataDir"), defaultExt = "")
    checkEquals(fullCsvPath, csvFound)    
    
    # Try an rxImport
    rxImport(inData = inCsv, outFile = outFile)
    checkTrue(file.exists(fullOutFile))
    numVars <- rxGetInfo(fullOutFile)$numVars
    file.remove(fullOutFile)
    
    rxImport(inData = inCsv, outFile = outFile, varsToDrop = c("y", "xfac1"))
    checkTrue(file.exists(fullOutFile))
    checkEquals(rxGetInfo(fullOutFile)$numVars, numVars - 2)
    file.remove(fullOutFile)
    
    # Try rxTextToXdf
    rxTextToXdf(inFile = inCsv, outFile = outFile)
    checkTrue(file.exists(fullOutFile))
    numVars2 <- rxGetInfo(fullOutFile)$numVars
    checkEquals(numVars, numVars2)
    file.remove(fullOutFile)    
    
    # Try an rxMerge
	mergeDS <- rxMerge(inData1 = "test100r5b", inData2 = "test100r1b", outFile=outFile, matchVars = c("xnum2"))      
    checkTrue(file.exists(fullOutFile))
    fileInfo <- rxGetInfo(fullOutFile)
    checkEquals(fileInfo$numVars, 17)
    file.remove(fullOutFile)
    
    # Try an rxPredict
    linModOut <- rxLinMod(xnum1~xnum2, data = inFile)
    rxPredict(linModOut, data = inFile, outData = outFile, writeModelVars = TRUE)    
    checkTrue(file.exists(fullOutFile))
    varInfo <- rxGetVarInfo(fullOutFile)
    checkEquals(names(varInfo), c("xnum1_Pred", "xnum1", "xnum2"))
    file.remove(fullOutFile)
           
    # Try an rxFactors
    rxFactors(inData = inFile, outFile = outFile, sortLevels = TRUE)
	checkTrue(file.exists(fullOutFile))
           
	# Re-create compute context to read and write from temp
	testComputeContext <- RxComputeContext("local", dataPath = tempdir(),
		outDataPath = tempdir())
	rxSetComputeContext(testComputeContext)	
    
    # Try rxGetInfo
	fileInfo <- rxGetInfo(outFile)
	checkEquals(fileInfo$fileName, fullOutFile)
	
	# Try rxGetVarInfo
	varInfo <- rxGetVarInfo(outFile)
    varInfoFull <- rxGetVarInfo(fullOutFile)
    checkEquals(varInfo, varInfoFull)
    
    # Try rxGetVarNames
    varNames <- rxGetVarNames(outFile)
    checkEquals(length(varNames), 9)
    
    # Try a rxLinMod
    linModOut <- rxLinMod(xnum1~xnum2, data = outFile)
    checkEquals(linModOut$nValidObs, 100)
    
    # Try an rxHistogram
    rxHistogram(~xnum1, data = outFile)
    
    # Try a line plot
    rxLinePlot(xnum1~xnum2, type = "p", data = outFile)

    
    # Try a cube
    cubeOut <- rxCube(~xfac1, data = outFile)
    checkEquals(sum(cubeOut$Counts), 100)
    
    # Try a decision tree
	dtreeOut <- rxDTree(xfac1~xnum1 + xint1, data = outFile)    
    checkEquals(dtreeOut$valid.obs, 100)
    
    # Try compressing the file
    file.remove(fullOutFile)
    rxDataStep(inData = fullInPath, outFile = outFile, xdfCompressionLevel = 0, 
        blocksPerRead = 5, overwrite = TRUE)
    fileInfoOrig <- file.info(fullOutFile)
    outFile2 <- ".rxLocalSeq2.xdf"
    fullOutFile2 <- file.path(tempdir(), outFile2)    
    rxCompressXdf(inFile = outFile, outFile = outFile2, xdfCompressionLevel = 5, overwrite = TRUE)
    fileInfoCompressed <- file.info(fullOutFile2)
	checkTrue(fileInfoOrig$size > fileInfoCompressed$size)
    file.remove(fullOutFile2)
    
    # Try rxDataStep
    file.remove(fullOutFile) 
   	sampleDF <- data.frame(actual = c(0,0,0,0,0, 1,1,1,1,1))
	sampleDF$pred1 <- c(.6, .5, .4, .3, .2, .8, .7, .6, .5, .4)
	rxDataStep(sampleDF, outFile = outFile)
    checkTrue(file.exists(fullOutFile))
    checkEquals(rxGetInfo(fullOutFile)$numVars, 2) 
    
    # Now see if rxRoc can find the data   
	rxRocOut <- rxRoc(actualVarName = "actual", predVarNames = "pred1", 
		data = outFile, numBreaks = 10, removeDups = FALSE)
    checkEquals(ncol(rxRocOut), 4)  
    
    file.remove(fullOutFile)
    rxSetComputeContext(origComputeContext)
	
}

# Extra test code
#library(doRSR)
#registerDoRSR()
#foreach(i=1:3) %dopar% sqrt(i)
#
#require(doParallel) 
#cl2 <- makeCluster(2) 
#registerDoParallel(cl = cl2) 
#rxOptions(computeContext = "dopar") 
#
#rxExec(seq, 1, 10, 2) 
#
#library(rpart) 
#kyph.rxGlm1 <- rxGlm(Kyphosis ~ Age + Start + Number, family=binomial, data=kyphosis, dropFirst=TRUE)


	