# Copyright (c) Microsoft Corporation.  All rights reserved.
#
# FUNCTIONS
#    Unit tests for transform environment
#
############################################################################################# Unit tests for transform environments
.setUp <- function()
{
}

.tearDown <- function()
{
}

"rxVarianceXdf" <- function(XDF, varName,  biased = TRUE, blocksPerRead = 1, attach.attributes = TRUE)
{
    # The naive biased sample variance of a discrete uniformly sampled time series, X_t,
    # is calculated via
    #
    #   var{X_t} = sum(X_t^2)/N - (sum(X_t)/N)^2
    #
    # for t = 0, ..., N - 1. Therefore, we need to keep track of three parameters:
    # sum(X_t), sum(X_t^2), N. To obtain the unbiased variance estimate, multiply
    # var{X_t} by N / (N - 1).           
    rxCovarianceXdf(XDF, varNames = varName,  biased = biased, blocksPerRead = blocksPerRead, 
        attach.attributes = attach.attributes)
}

"rxCovarianceXdf" <- function(XDF, varNames,  biased = TRUE, blocksPerRead = 1, attach.attributes = TRUE)
{
    # The naive biased sample covariance of two discrete uniformly sampled time series, X_t and Y_t,
    # is calculated via
    #
    #   cov{X_t, Y_t} = [ sum(X_t * Y_t) - sum(X_t) * sum(Y_t) / N ] / N
    #
    # for t = 0, ..., N - 1. Therefore, we need to keep track of four parameters:
    # sum(X_t * Y_t), sum(X_t), sum(Y_t), and N. To obtain the unbiased variance estimate, multiply
    # cov{X_t, Y_t} by N / (N - 1). This algorithm also works for Y_t = X_t.
            
    "rxIsInteger" <- function(x) all(is.numeric(x)) && all(round(x, 0) == x)
    # check input arguments
    stopifnot(is.character(varNames), length(varNames) %in% 1:2, all(nzchar(varNames)))
    stopifnot(rxIsInteger(blocksPerRead), length(blocksPerRead) == 1L)
    
    # create a new data source object and open it for reading
    uniqueVars <- unique(varNames)
    DS <- RxXdfData(XDF, varsToKeep = uniqueVars, blocksPerRead = blocksPerRead, 
        returnDataFrame = TRUE)
    rxOpen(DS)     
    
    # initialize variables   
    univariate <- length(uniqueVars) == 1L
    sumXY <- 0
    sumXsumY <- if (univariate) 0 else rep(0, 2L)
    validObs <- missingObs <- 0L

    # process data
    while(NROW(TS <- rxReadNext(DS)))
    {
        # handle missing values: if NA in either variable or both, remove corresponding row(s)
        rowsWithMissingValues <- unique(which(is.na(TS), arr.ind=TRUE)[,"row"])
        nMissing <- length(rowsWithMissingValues)
        if (nMissing) TS <- TS[-rowsWithMissingValues,]
        
        # update summary statistics
        sumXY <- sumXY + if (univariate) sum(TS[[1L]]^2L) else sum(apply(TS, MARGIN = 1L, prod))
        sumXsumY <- sumXsumY + if (univariate) sum(TS[[1L]]) else colSums(TS)
        validObs <- validObs + NROW(TS)
        missingObs <- missingObs + nMissing
    }
    
    # close data source
    rxClose(DS)
    
    # master update
    sumXsumYprod <- if (univariate) sumXsumY^2L else prod(sumXsumY)
    covariance <- (sumXY - sumXsumYprod / validObs) / validObs
    if (!biased) covariance <- covariance * validObs / (validObs - 1L)
    
    # define attributes
    if (attach.attributes)
    {
        attr(covariance, "file") <- XDF
        attr(covariance, "mean") <- sumXsumY / validObs
        attr(covariance, "varNames") <- uniqueVars
        attr(covariance, "biased") <- biased
        attr(covariance, "validObs") <- validObs
        attr(covariance, "missingObs") <- missingObs 
    }

    covariance 
}

"test.rxEnvironment.naive.sample.covariance.serialized" <- function()
{
    test100r5b <- file.path(rxGetOption("unitTestDataDir"), "test100r5b.xdf")
    yvar <- sapply(2^(0:3), function(b, file)
        {
            rxVarianceXdf(file, varName = "y", biased = FALSE, blocksPerRead = b)
        }, file = test100r5b)
        
    checkTrue(length(unique(yvar)) == 1)
    DF <- rxReadXdf(test100r5b, varsToKeep="y")
    checkEquals(yvar[1], var(DF$y))
    
    DF$x<- DF$y
    XDF <- file.path(tempdir(),"bothXandY.xdf")
    rxDataStep(DF, XDF, overwrite=TRUE)
    xxcovar <- rxCovarianceXdf(XDF, varNames = "x", biased = FALSE)
    yycovar <- rxCovarianceXdf(XDF, varNames = "y", biased = FALSE)
    xycovar <- rxCovarianceXdf(XDF, varNames = c("x","y"), biased = FALSE)
    checkEquals(yvar[1], xycovar, check.attributes=FALSE)
    checkEquals(xxcovar, xycovar, check.attributes=FALSE)
    checkEquals(yycovar, xycovar, check.attributes=FALSE)
    file.remove(XDF)
}



###
# TRANSFORMS/CLOSURE/ENVIRONMENT TESTS
###

"test.rxEnvironment.transform.no.double.colon" <- function()
{
	set.seed(100)
	myData <- data.frame(x = 1:100, y = rep(c("a", "b", "c", "d"), 25),
		z = rnorm(100), w = runif(100))

	inputFile <- file.path(tempdir(), "testEnvInput.xdf")
	rxDataStep(myData, inputFile, overwrite = TRUE)

	outputFile <- file.path(tempdir(), "testEnvOutput.xdf")
	outputFile2 <- file.path(tempdir(), "testEnvOutput2.xdf")

	set.seed(100)
	rxDataStep(inData = inputFile, outFile = outputFile2, rowSelection = selVar,
		transforms = list(
			selVar = as.logical(rbinom(length(x), 1, .25))
		), overwrite = TRUE)

	set.seed(100)
	rxDataStep(inData = inputFile, outFile = outputFile, rowSelection = selVar,
		transforms = list(
			selVar = as.logical(stats::rbinom(length(x), 1, .25))
		), overwrite = TRUE)

	z1 <- rxGetInfo(outputFile)
	z2 <- rxGetInfo(outputFile2)

	nocomp <- which(names(z1) %in% c("fileName"))
	checkEquals(z1[-nocomp], z2[-nocomp])

	if (file.exists(inputFile)) unlink(inputFile)
	if (file.exists(outputFile)) unlink(outputFile)
	if (file.exists(outputFile2)) unlink(outputFile2)
}

"test.rxEnvironment.computeContext.global.override" <- function()
{
    rxOptions(computeContext = "local")
    form <- ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
    covLocal <- rxCovCor(form, data = iris, type = "Cov", computeContext = "local")
    
    hpc <- RxHpcServer(headNode = "myNonExistentHeadNode", nodes = c("sis","boom","bah"))
    oldComputeContext <- rxGetOption("computeContext")
    rxOptions(computeContext = hpc)
    on.exit(rxOptions(computeContext = oldComputeContext), add = TRUE)
    
    covLocalOverride <- rxCovCor(form, data = iris, type = "Cov", computeContext = "local")
    checkEquals(covLocal, covLocalOverride)
}

"test.rxEnvironment.transformPackages" <- function()
{
    form <- ~ Sepal.Length + Sepal.Width.Doubled + Petal.Length + Petal.Width
    checkException(rxCovCor(form, data = iris, type = "Cov", 
        transformPackages = c("myNonExistentPackageNumber1", "myNonExistentPackageNumber2"),
        transforms = list(Sepal.Width.Doubled = Sepal.Width * 2)),
        silent = TRUE)
    
    form <- ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
    checkException(rxCovCor(form, data = iris, type = "Cov", 
        transformPackages = c("myNonExistentPackageNumber1", "myNonExistentPackageNumber2")),
        silent = TRUE)
}
 
"test.rxEnvironment.transformObjects.versus.transformEnvir" <- function()
{
    # define local function that we wish to pack into the
    # environment we ship off to exastat and use it for defining
    # a new variable in a transform
    hmsToSeconds <- function(hmsStrings)
    {
        # Time data in "H:M:S" format converted to seconds
        sapply(strsplit(hmsStrings, ":"), function(x){sum(as.numeric(x) * c(3600, 60, 1))})
    }

    # create some faux race data
    set.seed(100)
    N <- 100
    H <- sample.int(5, N, replace = TRUE)
    M <- sample.int(60, N, replace = TRUE)
    S <- sample.int(60, N, replace = TRUE)
    HMS <- paste(H, M, S, sep=":")
    division <- factor(sample(LETTERS[1:4], N, replace = TRUE))
    sex <- factor(sample(c("Male","Female"), N, replace = TRUE))
    DF <- data.frame(HMS = HMS, Division = division, Sex = sex, stringsAsFactors = FALSE)
    transforms <- expression(list(Minutes = foo(HMS) / 60))

    # now for some fun. perform a cube on the data, converting
    # the HMS string data to seconds along the way
    z1 <- rxCube(Minutes ~ Division : Sex, data = DF, 
        transforms = transforms,
        transformObjects = list(foo = hmsToSeconds))

    # validate one of the results
    AFemaleMean <- mean(hmsToSeconds(subset(DF, Division == "A" & Sex == "Female")[["HMS"]]) / 60)
    AFemaleMeanCube <- subset(z1, Division == "A" & Sex == "Female")[["Minutes"]]
    checkEqualsNumeric(AFemaleMean, AFemaleMeanCube)
    
    #####
    # Compare to environment packed with function 'foo'
    myEnv <- new.env(hash = TRUE, parent = baseenv())
    assign("foo", hmsToSeconds, envir = myEnv)
    
    z2 <- rxCube(Minutes ~ Division : Sex, data = DF, 
        transforms = transforms,
        transformEnvir = myEnv)
   
	all.equal(z1, z2, check.attributes = FALSE)
    
    #####
    # Compare to new hash environment, packing 'foo' behind the scenes
    # through 'transformObjects'
    myEnv <- new.env(hash = TRUE, parent = baseenv())
    
    z3 <- rxCube(Minutes ~ Division : Sex, data = DF, 
        transforms = transforms,
        transformEnvir = myEnv,
        transformObjects = list(foo = hmsToSeconds))
   
	all.equal(z2, z3, check.attributes = FALSE)
}

"test.rxEnvironment.transformEnvir.multiple.calls" <- function()
{
    # Tests the re-use of a user-specified environment, ensuring that the transform objects
    # we pack behind the scenes are removed properly inbetween calls
    transformEnvir <- new.env(hash = TRUE, parent = baseenv()) 
    assign("reallyLate", function(x) x > -2 & x < 2, envir = transformEnvir)
    assign("powtrans", function(x) x^2, envir = transformEnvir) 
    assign("halfValue", function(x) x / 2, envir = transformEnvir)
    assign("doubleValue", function(x) x * 2, envir = transformEnvir)
    
    # rxLinMod
    XDF <- file.path(rxGetOption("sampleDataDir"), "AirlineDemoSmall.xdf") 
    form <- ArrDelay ~ CRSDepTime + DayOfWeek
    transforms <- expression(list(CRSDepTime = powtrans(CRSDepTime))) 
    z1 <- rxLinMod(form = form, data = XDF, transforms = transforms, transformEnvir = transformEnvir)
    z2 <- rxLinMod(form = form, data = XDF, transforms = transforms, transformEnvir = transformEnvir)
    checkEquals(coef(z1), coef(z2))

    # rxLogit
    XDF <- file.path(rxGetOption("unitTestDataDir"), "AirlineArrDelayLT5s.xdf")
    transforms <- expression(list(ArrOnTime = reallyLate(ArrDelay)))
    form <- ArrOnTime ~ DayOfWeek + CRSDepTime
    z1 <- rxLogit(form, data = XDF, transforms = transforms, transformEnvir = transformEnvir)
    z2 <- rxLogit(form, data = XDF, transforms = transforms, transformEnvir = transformEnvir)
    checkEquals(coef(z1), coef(z2))
    
    # rxCovCor and family
    transforms <- expression(list(HalfTime = halfValue(time), concDouble = doubleValue(conc)))
    form <- ~ HalfTime + concDouble
	z1 <- rxCovCor(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir, type = "Cor")
	z2 <- rxCovCor(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir, type = "Cor")
    checkEquals(z1, z2)
	z1 <- rxCovCor(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir, type = "Cov")
	z2 <- rxCovCor(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir, type = "Cov")
    checkEquals(z1, z2)
	z1 <- rxCovCor(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir, type = "SSCP")
	z2 <- rxCovCor(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir, type = "SSCP")
    checkEquals(z1, z2)
	z1 <- rxCor(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir)
	z2 <- rxCor(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir)
    checkEquals(z1, z2)
	z1 <- rxCov(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir)
	z2 <- rxCov(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir)
    checkEquals(z1, z2)
	z1 <- rxSSCP(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir)
	z2 <- rxSSCP(form, data = Indometh, transforms = transforms, transformEnvir = transformEnvir)
    checkEquals(z1, z2)
    
    # rxCube / rxCrossTabs
    form <- ~ F(mySepalLength, low = 18, high = 60) : F(Petal.Length)
    assign("squareValue", function(x) x^2, envir = transformEnvir)
    transforms <- expression(list(mySepalLength = squareValue(Sepal.Length)))
    z1 <- rxCube(form, data = iris, transforms = transforms, transformEnvir = transformEnvir)
    z2 <- rxCube(form, data = iris, transforms = transforms, transformEnvir = transformEnvir)
    checkEquals(z1, z2)
    z1 <- rxCrossTabs(form, data = iris, transforms = transforms, transformEnvir = transformEnvir)
    z2 <- rxCrossTabs(form, data = iris, transforms = transforms, transformEnvir = transformEnvir)
    checkEquals(z1, z2)
   
    # rxSummary
    form <- ~ mySepalLength
    transforms <- expression(list(mySepalLength = squareValue(Sepal.Length)))
    z1 <- rxSummary(form, data = iris, transforms = transforms, transformEnvir = transformEnvir)
    z2 <- rxSummary(form, data = iris, transforms = transforms, transformEnvir = transformEnvir)
    checkEquals(z1, z2)
  
    # rxKmeans
    transforms <- expression(list(newTime = squareValue(time), time = NULL, newConc = doubleValue(conc), conc = NULL))
	seed <- 100
	maxIterations <- 1000L
	numClusters <- 3L
	algorithm <- "Lloyd"
	DF <- Indometh
    form <- ~ newTime + newConc
	z1 <- rxKmeans(form, data = DF, numClusters = numClusters, seed = seed, 
        transforms = transforms, algorithm = algorithm, maxIterations = maxIterations,
        transformEnvir = transformEnvir)
	z2 <- rxKmeans(form, data = DF, numClusters = numClusters, seed = seed, 
        transforms = transforms, algorithm = algorithm, maxIterations = maxIterations,
        transformEnvir = transformEnvir)
    checkEquals(z1, z2)
    
    # rxTextToXdf
	inFile <- file.path(rxGetOption("unitTestDataDir"), "test100r.txt")
	outFile <- file.path(tempdir(), ".rxTemp100.xdf")
	testColInfo <- list(ylogical = list(newName = "MyLogicalY"), xnum2 = list(newName = "MyXnum2"))
    transforms <- expression(list(MyNewX = doubleValue(MyXnum2) + 7.0))
	rxTextToXdf(inFile, outFile, colInfo = testColInfo, rowsPerRead = 25, overwrite = TRUE,
		 transforms = transforms, transformEnvir = transformEnvir)
	z1 <- rxGetVarNames(outFile)
    checkTrue("MyLogicalY" %in% z1)
    checkTrue("MyXnum2" %in% z1)
    checkTrue("MyNewX" %in% z1)
    
 	if (file.exists(outFile)) file.remove(outFile)
   
    # rxImport
	richDataSpss <- file.path(rxGetOption("unitTestDataDir"), "richTest100r.sav") 
	richData <- file.path(tempdir(), "richTest100r5b.xdf") 

	transformFunc <- function(datalist)
	{ 
        numRowsInChunk <- length(datalist[[1L]]) 
		datalist$Index <- .rxStartRow:(.rxStartRow + numRowsInChunk - 1) 
		datalist$Chunk <- rep(.rxChunkNum, numRowsInChunk)
		datalist$File <-  rep(.rxReadFileName, numRowsInChunk)
        datalist$MyVar <- doubleValue(rnorm(numRowsInChunk))
        datalist 
	} 

	spssDS <- RxSpssData(richDataSpss, rowsPerRead=20 )
	xdfDS <- RxXdfData(richData)
	
   outDS1 <- rxImport(inData = spssDS, outFile = xdfDS, 
		transformFunc=transformFunc, overwrite = TRUE,  reportProgress = 0,
        transformEnvir = transformEnvir)
    
    # otra vez
    outDS2 <- rxImport(inData = spssDS, outFile = xdfDS, 
		transformFunc=transformFunc, overwrite = TRUE,  reportProgress = 0,
        transformEnvir = transformEnvir)
    
	myData <- rxReadXdf(richData)
    checkTrue("MyVar" %in% names(myData))
	checkEquals(myData$Index, 1:100)
	if (rxIsExpressEdition())
	{
	    checkEquals(myData$Chunk, rep(1, each=100))
	} else
	{
		checkEquals(myData$Chunk, rep(1:5, each=20))
	}
	
	checkEquals(normalizePath(myData$File), rep(normalizePath(richDataSpss), 100))
	file.remove(richData)
    
    # rxSplitXdf (rxDataStepXdf is called by rxSplitXdf so we don't need to test it separately in this case
    inFile <- file.path(rxGetOption("sampleDataDir"), "CensusWorkers.xdf")
    transforms <- expression(list(myAge = doubleValue(age)))
    outFilesDir <- file.path(tempdir(), "byRowsDir")
    outFilesBase <- file.path(outFilesDir, "Census-byRows")
    rxSplitXdf(inFile, outFilesBase = outFilesBase,
	           numOutFiles = 5, splitBy = "rows", verbose = 1,
               transforms = transforms, transformEnvir = transformEnvir, overwrite = TRUE)
    rxSplitXdf(inFile, outFilesBase = outFilesBase,
           numOutFiles = 5, splitBy = "rows", verbose = 1,
           transforms = transforms, transformEnvir = transformEnvir, overwrite = TRUE)    
    byRowFiles <- list.files(dirname(outFilesBase), full = TRUE)
    infoByRows <- sapply(byRowFiles, rxGetVarInfo, simplify = FALSE)
    checkTrue(all(as.vector(sapply(infoByRows, function(x) "myAge" %in% names(x)))))
    if (file.exists(dirname(outFilesBase))) unlink(dirname(outFilesBase), recursive = TRUE)
   # if (file.exists(dirname(outFilesDir))) unlink(dirname(outFilesDir), recursive = TRUE)
 
    # rxXdfToText
    sampleDataDir <- rxGetOption("sampleDataDir")
    censusXdfFile <- file.path(rxGetOption("sampleDataDir"), "CensusWorkers.xdf")
    censusCsvFile <- file.path(tempdir(), "CensusWorkers.csv")
    rxXdfToText(inFile = censusXdfFile, outFile = censusCsvFile, overwrite = TRUE)
    rowSelection <- expression(age < 40)
    varsToKeep <- c("age", "incwage")
    transforms <- expression(list(logIncwage = doubleValue(log1p(incwage)), incwage = NULL))

    censusSubsetCsvFile <- file.path(tempdir(), "CensusSubset.csv")
    rxXdfToText(inFile = censusXdfFile, outFile = censusSubsetCsvFile,
                varsToKeep = varsToKeep,
                rowSelection = rowSelection,
                transforms = transforms,
                transformEnvir = transformEnvir,
                overwrite = TRUE)
    rxXdfToText(inFile = censusXdfFile, outFile = censusSubsetCsvFile,
                varsToKeep = varsToKeep,
                rowSelection = rowSelection,
                transforms = transforms,
                transformEnvir = transformEnvir,
                overwrite = TRUE)
    if (file.exists(censusSubsetCsvFile)) unlink(censusSubsetCsvFile)
	if (file.exists(censusCsvFile)) unlink(censusCsvFile)
}