

# Copyright (c) Microsoft Corporation.  All rights reserved.
#
# Run tests using both RxHadoopMR and local compute contexts
#
############################################################################################

# HadoopIOQ_Setup.R creates the getOption("rxTestArgs") required by these functions

#############################################################################################
# Function to get compute contexts
#############################################################################################
"getHadoopComputeContext" <-
    function(rxTestArgs = getOption("rxTestArgs"))
    {
        if (is.null(rxTestArgs))
        {
            stop(
                "Compute context information must be in 'rxTestArgs' option.  See HadoopIOQ_SetupAndRun.R."
            )
        }
        if (!is.null(rxTestArgs$platform) &&
            rxTestArgs$platform == "spark") {
            RxSpark(
                nameNode     = rxTestArgs$nameNode,
                port         = rxTestArgs$port,
                hdfsShareDir = rxTestArgs$hdfsShareDir,
                shareDir     = rxTestArgs$shareDir,
                sshUsername  = rxTestArgs$sshUsername,
                sshHostname  = rxTestArgs$sshHostname,
                sshSwitches  = rxTestArgs$sshSwitches,
                wait = TRUE,
                consoleOutput = rxTestArgs$consoleOutput,
                fileSystem    = rxTestArgs$fileSystem,
                sshProfileScript = rxTestArgs$sshProfileScript,
                sshClientDir  = rxTestArgs$sshClientDir,
                jobTrackerURL = rxTestArgs$jobTrackerURL,
                onClusterNode = rxTestArgs$onClusterNode,
                showOutputWhileWaiting = rxTestArgs$showOutputWhileWaiting,
                autoCleanup = rxTestArgs$autoCleanup,
                workingDir  = rxTestArgs$workingDir,
                dataPath    = rxTestArgs$dataPath,
                outDataPath = rxTestArgs$outDataPath,
                packagesToLoad = rxTestArgs$packagesToLoad,
                numExecutors = rxTestArgs$numExecutors,
                executorCores = rxTestArgs$executorCores,
                executorMem = rxTestArgs$executorMem,
                driverMem = rxTestArgs$driverMem,
                executorOverheadMem = rxTestArgs$executorOverheadMem,
                resultsTimeout = rxTestArgs$resultsTimeout
            )
        } else {
            stop("RxParquetData is not supported on RxHadoopMR compute context.")
        }
        
    }

"getLocalComputeContext" <- function()
{
    RxLocalSeq()
}



#############################################################################################
# Functions to get data sources
#############################################################################################

"getAirDemoTextHdfsDS" <- function()
{
    rxTestArgs <- getOption("rxTestArgs")
    if (is.null(rxTestArgs))
    {
        stop(
            "Compute context information must be in 'rxTestArgs' option.  See HadoopIOQ_SetupAndRun.R."
        )
    }
    airColInfo <- list(
        ArrDelay = list(type = "integer"),
        DayOfWeek = list(
            type = "factor",
            levels = c(
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
            )
        )
    )
    # In .setup, a directory 'AirlineDemoSmallXdf' will be created with the file
    
    RxTextData(
        file = file.path(
            rxTestArgs$hdfsShareDir,
            rxTestArgs$myHdfsAirDemoCsvSubdir
        ),
        missingValueString = "M",
        colInfo = airColInfo,
        fileSystem = rxTestArgs$fileSystem
    )
}

"getAirDemoXdfHdfsDS" <- function()
{
    rxTestArgs <- getOption("rxTestArgs")
    if (is.null(rxTestArgs))
    {
        stop("Test settings must be in 'rxTestArgs' option.  See HadoopIOQ_SetupAndRun.R.")
    }
    # In the first test a directory 'IOQ\AirlineDemoSmallXdf' will be created with a composite xdf file
    RxXdfData(
        file = file.path(
            rxTestArgs$hdfsShareDir,
            rxTestArgs$myHdfsAirDemoXdfSubdir
        ),
        fileSystem = rxTestArgs$fileSystem
    )
}

"getAirDemoParquetHdfsDS" <- function()
{
    rxTestArgs <- getOption("rxTestArgs")
    if (is.null(rxTestArgs))
    {
        stop(
            "Compute context information must be in 'rxTestArgs' option.  See HadoopIOQ_SetupAndRun.R."
        )
    }
    airColInfo <- list(
        ArrDelay =  list(type = "integer"),
        DayOfWeek = list(
            type = "factor",
            levels = c(
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
            )
        )
    )
    
    
    RxParquetData(
        file = file.path(
            rxTestArgs$hdfsShareDir,
            rxTestArgs$myHdfsAirDemoParquetSubdir
        ),
        colInfo = airColInfo
    )
    
    
}

"getTestOutFileHdfsPath" <- function(fileName)
{
    file.path(rxTestArgs$myHdfsTestOuputSubdir, fileName)
}


"getTestOutFileHdfsDS" <- function(testFileDirName)
{
    rxTestArgs <- getOption("rxTestArgs")
    if (is.null(rxTestArgs))
    {
        stop(
            "Compute context information must be in 'rxTestArgs' option.  See HadoopIOQ_SetupAndRun.R."
        )
    }
    RxXdfData(
        file = file.path(
            rxTestArgs$hdfsShareDir,
            rxTestArgs$myHdfsTestOuputSubdir,
            testFileDirName
        ),
        fileSystem = rxTestArgs$fileSystem
    )
}

"removeTestOutFileHdfsDS" <- function(testDS)
{
    rxTestArgs <- getOption("rxTestArgs")
    if (is.null(rxTestArgs$nameNode) ||
        rxTestArgs$nameNode == "default") {
        nameNodePrefix = ""
    } else {
        nameNodePrefix = rxTestArgs$nameNode
    }
    rxSetComputeContext(getHadoopComputeContext())
    rxHadoopRemoveDir(paste0(nameNodePrefix, testDS@file))
    rxSetComputeContext(getLocalComputeContext())
    
}

"getAirDemoTextLocalDS" <- function()
{
    airColInfo <- list(
        ArrDelay = list(type = "integer"),
        DayOfWeek = list(
            type = "factor",
            levels = c(
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
            )
        )
    )
    RxTextData(
        file = file.path(rxGetOption("sampleDataDir"), "AirlineDemoSmall.csv"),
        colInfo = airColInfo,
        missingValueString = "M",
        fileSystem = "native"
    )
}

"getAirDemoXdfLocalDS" <- function()
{
    RxXdfData(file = file.path(rxGetOption("sampleDataDir"), "AirlineDemoSmall.xdf"),
              fileSystem = "native")
}

"getTestLocalPath" <- function(testFileName)
{
    rxTestArgs <- getOption("rxTestArgs")
    file.path(rxTestArgs$localTestDataDir, testFileName)
}


"getTestOutFileLocalDS" <- function(testFileDirName)
{
    RxXdfData(
        file = file.path(
            getOption("rxTestArgs")$localTestDataDir,
            testFileDirName
        ),
        createCompositeSet = TRUE,
        fileSystem = "native"
    )
}

"getIsOnNode" <- function()
{
    rxTestArgs <- getOption("rxTestArgs")
    if (!is.null(rxTestArgs$onClusterNode) &&
        (rxTestArgs$onClusterNode == TRUE))
    {
        return(TRUE)
    }
    return(FALSE)
}

"removeTestOutFileLocalDS" <- function(testDS)
{
    unlink(testDS@file, recursive = TRUE)
}

#############################################################################################
# Tests to put data on Hadoop cluster
#############################################################################################

"test.hadoop.aaa.initializeHadoop.DF" <- function()
{
    rxTestArgs <- getOption("rxTestArgs")
    if (is.null(rxTestArgs$nameNode) ||
        rxTestArgs$nameNode == "default") {
        nameNodePrefix = ""
    } else {
        nameNodePrefix = rxTestArgs$nameNode
    }
    if (is.null(rxTestArgs)) {
        stop(
            "Compute context information must be in 'rxTestArgs' option. See HadoopIOQ_SetupAndRun.R.",
            call. = FALSE
        )
    }
    
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    rxSetComputeContext(getHadoopComputeContext())
    
    # Get the curent version from the Hadoop cluster
    versionOutput <- rxExec(function()
        Revo.version)
    cat("MRS version on Hadoop cluster: ",
        versionOutput$rxElem1$version.string,
        '\n')
    cat("Hadoop Compute Context being used: ",
        capture.output(print(getHadoopComputeContext())),
        '\n',
        sep = '\n')
    
    if (!rxHadoopFileExists(paste0(nameNodePrefix, rxTestArgs$hdfsShareDir))) {
        cat("WARNING: hdfsShareDir does not exist or problem with compute context.\n")
    }
    
    if (!rxTestArgs$createHadoopData)
        return(invisible(T))
    
    # ------------------------------------------------------------------
    
    # Destination path for files in Hadoop
    airDemoSmallCsvHdfsPath <-
        file.path(rxTestArgs$hdfsShareDir,
                  rxTestArgs$myHdfsAirDemoCsvSubdir)
    
    # --- Remove the directory if it's already there ---
    if (rxHadoopFileExists(paste0(nameNodePrefix, airDemoSmallCsvHdfsPath))) {
        cat("Removing `", airDemoSmallCsvHdfsPath, "'\n", sep = "")
        rxHadoopRemoveDir(paste0(nameNodePrefix, airDemoSmallCsvHdfsPath),
                          skipTrash = TRUE)
    }
    
    # ... and now re-create it so that we can copy files into it
    rxHadoopMakeDir(paste0(nameNodePrefix, airDemoSmallCsvHdfsPath))
    
    # --- copy split CSV data set ---
    airDemoSmallSplitDir <-
        file.path(rxGetOption("sampleDataDir"), "AirlineDemoSmallSplit")
    files <-
        list.files(
            airDemoSmallSplitDir,
            recursive = TRUE,
            include.dirs = FALSE,
            full.names = TRUE
        )
    checkEquals(length(files), 3)
    
    if (getIsOnNode()) {
        rc <- lapply(files, function(src) {
            rxHadoopCopyFromLocal(
                source = src,
                dest = paste0(nameNodePrefix, airDemoSmallCsvHdfsPath)
            )
        })
    }
    else
    {
        # Copy the file from local client
        rc <- lapply(files, function(src) {
            rxHadoopCopyFromClient(
                source = src,
                nativeTarget = rxTestArgs$myHdfsNativeDir,
                hdfsDest = paste0(nameNodePrefix, airDemoSmallCsvHdfsPath),
                computeContext = getHadoopComputeContext(),
                sshUsername = rxTestArgs$sshUsername,
                sshHostname = rxTestArgs$sshHostname,
                sshSwitches = rxTestArgs$sshSwitches
            )
        })
    }
    
    checkTrue(all(unlist(rc)))
    
    # ------------------------------------------------------------------
    
    # Destination path for files in Hadoop
    airDemoSmallParquetHdfsPath <-
        file.path(rxTestArgs$hdfsShareDir,
                  rxTestArgs$myHdfsAirDemoParquetSubdir)
    
    # --- Remove the directory if it's already there ---
    if (rxHadoopFileExists(paste0(nameNodePrefix, airDemoSmallParquetHdfsPath))) {
        cat("Removing `", airDemoSmallParquetHdfsPath, "'\n", sep = "")
        rxHadoopRemoveDir(paste0(nameNodePrefix, airDemoSmallParquetHdfsPath),
                          skipTrash = TRUE)
    }
    
    # ... and now re-create it so that we can copy files into it
    rxHadoopMakeDir(paste0(nameNodePrefix, airDemoSmallParquetHdfsPath))
    
    # --- copy Parquet data set ---
    airDemoSmallParquetDir <-
        file.path(rxGetOption("sampleDataDir"), "AirlineDemoSmallParquet")
    files <-
        list.files(
            airDemoSmallParquetDir,
            recursive = TRUE,
            include.dirs = FALSE,
            full.names = TRUE
        )
    checkEquals(length(files), 6)
    
    if (getIsOnNode()) {
        rc <- lapply(files, function(src) {
            rxHadoopCopyFromLocal(
                source = src,
                dest = paste0(nameNodePrefix, airDemoSmallParquetHdfsPath)
            )
        })
    }
    else
    {
        # Copy the file from local client
        rc <- lapply(files, function(src) {
            rxHadoopCopyFromClient(
                source = src,
                nativeTarget = rxTestArgs$myHdfsNativeDir,
                hdfsDest = paste0(nameNodePrefix, airDemoSmallParquetHdfsPath),
                computeContext = getHadoopComputeContext(),
                sshUsername = rxTestArgs$sshUsername,
                sshHostname = rxTestArgs$sshHostname,
                sshSwitches = rxTestArgs$sshSwitches
            )
        })
    }
    
    checkTrue(all(unlist(rc)))
    
}





#############################################################################################
# Test data generation
#############################################################################################

"test.hadoop.dataGeneration.DF" <- function ()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    rxTestArgs <- getOption("rxTestArgs")
    if (is.null(rxTestArgs$nameNode) ||
        rxTestArgs$nameNode == "default") {
        nameNodePrefix = ""
    } else {
        nameNodePrefix = rxTestArgs$nameNode
    }
    
    rxTestArgs <- getOption("rxTestArgs")
    if (is.null(rxTestArgs)) {
        stop(
            "Compute context information must be in 'rxTestArgs' option. See HadoopIOQ_SetupAndRun.R.",
            call. = FALSE
        )
    }
    
    # compare both data frames to make sure the generated data matches
    # the pre-generated one
    compareFrames <- function (new_df, old_df)
    {
        if (!checkEquals(ncol(new_df), ncol(old_df)) ||
            !checkEquals(nrow(new_df), nrow(old_df)) ||
            !checkEquals(sort(names(new_df)), sort(names(old_df))))
            return(FALSE)
        
        rc <- lapply(names(new_df), function (nm) {
            new_col <- new_df[[nm]]
            old_col <- old_df[[nm]]
            if (!checkEquals(typeof(old_col), typeof(new_col)))
                return(FALSE)
            
            if (is.numeric(old_col))
                checkEquals(mean(old_col), mean(new_col))
            else if (is.character(old_col)) {
                checkEquals(table(old_col, dnn = NULL),
                            table(new_col, dnn = NULL))
            }
        })
        
        return(all(unlist(rc)))
    }
    
    
    
    rxSetComputeContext(getHadoopComputeContext())
    
    # --- Make directory in HDFS for writing temporary test data -------
    outDS <- getTestOutFileHdfsDS(rxTestArgs$myHdfsTestOuputSubdir)
    rxHadoopMakeDir(paste0(nameNodePrefix, outDS@file))
    
    # Import the Parquet files to a composite xdf file in HDFS
    rxImport(
        inData = getAirDemoParquetHdfsDS(),
        outFile = outDS,
        rowsPerRead = 200000,
        overwrite = TRUE
    )
    
    checkFilesNo <- function (ds) {
        files <-
            rxHadoopListFiles(paste0(nameNodePrefix, ds@file),
                              recursive = TRUE,
                              print = FALSE)
        # filter out the line of "Authorized uses only" in some cluster scenarios.
        files <-
            files[lapply(files, function(x)
                length(grep("Authorized uses only", x, value = FALSE))) == 0]
        checkEquals(length(files), 6)
    }
    
    
    # Disable file count check, as Spark does NOT guarantee the same number of partitions at different runs.
    # In other words, the number of generated xdfd files may diff at different cluster settings.
    # checkFilesNo(outDS)
    
    new_df <- rxImport(outDS, reportProgress = 0)
    old_df <-
        rxImport(getAirDemoParquetHdfsDS(), reportProgress = 0)
    checkTrue(compareFrames(new_df, old_df))
    
    rxSetComputeContext(getLocalComputeContext())
} # test.hadoop.dataGeneration()



#############################################################################################
# Tests for getting file information
#############################################################################################

"test.hadoop.rxGetInfo.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # Test simple case
    rxSetComputeContext(getLocalComputeContext())
    localInfo <- rxGetInfo(data = getAirDemoTextLocalDS())
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopInfo <- rxGetInfo(data = getAirDemoParquetHdfsDS())
    
    checkEquals(localInfo$numRows, hadoopInfo$numRows)
    checkEquals(localInfo$numVars, hadoopInfo$numVars)
    
    # Test with arguments
    rxSetComputeContext(getLocalComputeContext())
    localInfoArgs <- rxGetInfo(
        data = getAirDemoTextLocalDS(),
        getVarInfo = TRUE,
        getBlockSizes = TRUE,
        computeInfo = TRUE,
        numRows = 5
    )
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopInfoArgs <- rxGetInfo(
        data = getAirDemoParquetHdfsDS(),
        getVarInfo = TRUE,
        getBlockSizes = TRUE,
        computeInfo = TRUE,
        numRows = 5
    )
    
    checkIdentical(localInfoArgs$varInfo, hadoopInfoArgs$varInfo)
    # rowsPerBlock only be equal if there is only one composite data file
    # data is generally retrieved in a different order
    checkEquals(nrow(localInfoArgs$data), nrow(hadoopInfoArgs$data))
    checkEquals(names(localInfoArgs$data), names(hadoopInfoArgs$data))
    rxSetComputeContext(getLocalComputeContext())
}


"test.hadoop.rxGetVarInfo.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    rxSetComputeContext(getLocalComputeContext())
    localVarInfo <-
        rxGetVarInfo(getAirDemoTextLocalDS(), computeInfo = TRUE)
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopVarInfo <-
        rxGetVarInfo(getAirDemoParquetHdfsDS(), computeInfo = TRUE)
    
    checkIdentical(localVarInfo, hadoopVarInfo)
    
    rxSetComputeContext(getLocalComputeContext())
}

"test.hadoop.rxGetVarNames.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    rxSetComputeContext(getLocalComputeContext())
    localVarNames <- rxGetVarNames(getAirDemoTextLocalDS())
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopVarNames <- rxGetVarNames(getAirDemoParquetHdfsDS())
    
    checkEquals(localVarNames, hadoopVarNames)
    
    rxSetComputeContext(getLocalComputeContext())
}

"test.hadoop.rxLocateFile.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # Hadoop
    # Parquet
    rxSetComputeContext(getHadoopComputeContext())
    dataSource <- getAirDemoParquetHdfsDS()
    hadoopFileName <- basename(dataSource@file)
    hadoopDir <- dirname(dataSource@file)
    hadoopLocated <-
        rxLocateFile(
            file = hadoopFileName,
            pathsToSearch = hadoopDir,
            defaultExt = "",
            fileSystem = dataSource@fileSystem
        )
    checkEquals(hadoopLocated, dataSource@file)
    
    
    rxSetComputeContext(getLocalComputeContext())
}



#############################################################################################
# Tests for plotting functions
#############################################################################################
"test.hadoop.rxHistogram.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    rxSetComputeContext(getLocalComputeContext())
    localHistogram <-
        rxHistogram(
            ~ ArrDelay,
            data = getAirDemoTextLocalDS(),
            rowSelection = ArrDelay > 0,
            title = "Local Histogram"
        )
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopHistogram <-
        rxHistogram(
            ~ ArrDelay,
            data = getAirDemoParquetHdfsDS(),
            rowSelection = ArrDelay > 0,
            title = "Hadoop Histogram"
        )
    
    checkIdentical(localHistogram$panel.args, hadoopHistogram$panel.args)
    checkIdentical(localHistogram$call, hadoopHistogram$call)
    
    rxSetComputeContext(getLocalComputeContext())
}

"test.hadoop.rxLinePlot.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    rxSetComputeContext(getLocalComputeContext())
    localLinePlot <-
        rxLinePlot(
            ArrDelay ~ CRSDepTime,
            data = getAirDemoTextLocalDS(),
            rowSelection = ArrDelay > 60,
            type = "p",
            title = "Local Line Plot"
        )
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopLinePlot <-
        rxLinePlot(
            ArrDelay ~ CRSDepTime,
            ,
            data = getAirDemoParquetHdfsDS(),
            rowSelection = ArrDelay > 60,
            type = "p",
            title = "Hadoop Line Plot"
        )
    localLinePlot$panel.args[[1]]$x <-
        sort(localLinePlot$panel.args[[1]]$x)
    localLinePlot$panel.args[[1]]$y <-
        sort(localLinePlot$panel.args[[1]]$y)
    hadoopLinePlot$panel.args[[1]]$x <-
        sort(hadoopLinePlot$panel.args[[1]]$x)
    hadoopLinePlot$panel.args[[1]]$y <-
        sort(hadoopLinePlot$panel.args[[1]]$y)
    checkIdentical(localLinePlot$panel.args, hadoopLinePlot$panel.args)
    
    
    rxSetComputeContext(getLocalComputeContext())
}

#############################################################################################
# Tests for data step
#############################################################################################
"test.hadoop.rxDataStep.data.TextToXdf.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # Run example locally
    rxSetComputeContext(getLocalComputeContext())
    outLocalDS <- getTestOutFileLocalDS("DataStepTest")
    rxDataStep(inData = getAirDemoTextLocalDS(),
               outFile = outLocalDS,
               overwrite = TRUE)
    on.exit(removeTestOutFileLocalDS(outLocalDS), add = TRUE)
    localInfo <- rxGetInfo(data = outLocalDS, getVarInfo = TRUE)
    
    rxSetComputeContext(getHadoopComputeContext())
    outHdfsDS <- getTestOutFileHdfsDS("DataStepTest")
    rxDataStep(inData = getAirDemoParquetHdfsDS(),
               outFile = outHdfsDS,
               overwrite = TRUE)
    hadoopInfo = rxGetInfo(data = outHdfsDS, getVarInfo = TRUE)
    
    checkEquals(localInfo$numRows, hadoopInfo$numRows)
    checkIdentical(localInfo$varInfo, hadoopInfo$varInfo)
    
    # Clean-up
    removeTestOutFileHdfsDS(outHdfsDS)
    
    rxSetComputeContext(getLocalComputeContext())
    removeTestOutFileLocalDS(outLocalDS)
}

"test.hadoop.rxDataStep.data.TextToDataFrame.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # Note: row order in data frames will differ
    rxSetComputeContext(getLocalComputeContext())
    localDataFrame <- rxDataStep(inData = getAirDemoTextLocalDS())
    rowOrder <-
        order(localDataFrame$ArrDelay,
              localDataFrame$CRSDepTime,
              localDataFrame$DayOfWeek)
    localDataFrame <- localDataFrame[rowOrder, ]
    row.names(localDataFrame) <- NULL
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopDataFrame <-
        rxDataStep(inData = getAirDemoParquetHdfsDS())
    rowOrder <-
        order(
            hadoopDataFrame$ArrDelay,
            hadoopDataFrame$CRSDepTime,
            hadoopDataFrame$DayOfWeek
        )
    hadoopDataFrame <- hadoopDataFrame[rowOrder, ]
    row.names(hadoopDataFrame) <- NULL
    checkIdentical(localDataFrame, hadoopDataFrame)
    
    rxSetComputeContext(getLocalComputeContext())
}



#############################################################################################
# Tests for analysis functions that read data
#############################################################################################
"test.hadoop.rxCube.data.Text.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # rxCube with input xdf file
    rxSetComputeContext(getLocalComputeContext())
    localCube <-
        rxCube(ArrDelay ~ DayOfWeek, data = getAirDemoTextLocalDS())
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopCube <-
        rxCube(ArrDelay ~ DayOfWeek, data = getAirDemoParquetHdfsDS())
    
    checkIdentical(localCube$Counts, hadoopCube$Counts)
    
    rxSetComputeContext(getLocalComputeContext())
}

"test.hadoop.rxCrossTabs.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # rxCrosstabs with input xdf file
    rxSetComputeContext(getLocalComputeContext())
    localCrossTabs <-
        rxCrossTabs(
            ArrDelay10 ~ DayOfWeek,
            data = getAirDemoTextLocalDS(),
            rowSelection = CRSDepTime > 10,
            transforms = list(ArrDelay10 = ArrDelay * 10)
        )
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopCrossTabs <-
        rxCrossTabs(
            ArrDelay10 ~ DayOfWeek,
            data = getAirDemoParquetHdfsDS(),
            rowSelection = CRSDepTime > 10,
            transforms = list(ArrDelay10 = ArrDelay * 10)
        )
    
    checkIdentical(localCrossTabs$sums, hadoopCrossTabs$sums)
    checkIdentical(localCrossTabs$counts, hadoopCrossTabs$counts)
    checkIdentical(localCrossTabs$chisquare, hadoopCrossTabs$chisquare)
    
    rxSetComputeContext(getLocalComputeContext())
}

"test.hadoop.rxSummary.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # rxSummary with input xdf file
    rxSetComputeContext(getLocalComputeContext())
    localSummary <-
        rxSummary(
            ArrDelay10 ~ DayOfWeek,
            data = getAirDemoTextLocalDS(),
            rowSelection = CRSDepTime > 10,
            transforms = list(ArrDelay10 = 10 * ArrDelay)
        )
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopSummary <-
        rxSummary(
            ArrDelay10 ~ DayOfWeek,
            data = getAirDemoParquetHdfsDS(),
            rowSelection = CRSDepTime > 10,
            transforms = list(ArrDelay10 = 10 * ArrDelay)
        )
    
    
    checkEquals(localSummary$categorical[[1]], hadoopSummary$categorical[[1]])
    
    rxSetComputeContext(getLocalComputeContext())
}

"test.hadoop.rxQuantile.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # rxQuantile with input xdf file
    rxSetComputeContext(getLocalComputeContext())
    localQuantile <-
        rxQuantile("ArrDelay", data = getAirDemoTextLocalDS())
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopQuantile <-
        rxQuantile("ArrDelay", data = getAirDemoParquetHdfsDS())
    
    checkEquals(localQuantile, hadoopQuantile)
    
    rxSetComputeContext(getLocalComputeContext())
}


##############################################
#####THe above is done########################
##############################################

"test.hadoop.rxLinMod.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # rxLinMod with input xdf file
    rxSetComputeContext(getLocalComputeContext())
    localLinMod <-
        rxLinMod(ArrDelay ~ DayOfWeek,
                 data = getAirDemoTextLocalDS(),
                 rowSelection = CRSDepTime > 10)
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopLinMod <-
        rxLinMod(ArrDelay ~ DayOfWeek,
                 data = getAirDemoParquetHdfsDS(),
                 rowSelection = CRSDepTime > 10)
    
    checkEquals(localLinMod$coefficients, hadoopLinMod$coefficients)
    
    rxSetComputeContext(getLocalComputeContext())
}

"test.hadoop.rxLinMod.data.csv.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # rxLinMod with input xdf file
    rxSetComputeContext(getLocalComputeContext())
    localLinMod <-
        rxLinMod(ArrDelay ~ DayOfWeek,
                 data = getAirDemoTextLocalDS(),
                 rowSelection = CRSDepTime > 10)
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopLinMod <-
        rxLinMod(ArrDelay ~ DayOfWeek,
                 data = getAirDemoParquetHdfsDS(),
                 rowSelection = CRSDepTime > 10)
    
    checkEquals(localLinMod$coefficients, hadoopLinMod$coefficients)
    
    rxSetComputeContext(getLocalComputeContext())
}

"test.hadoop.rxCovCor.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # rxCovCor with input xdf file
    rxSetComputeContext(getLocalComputeContext())
    localCovCor <-
        rxCovCor(
            ~ ArrDelay + DayOfWeek + CRSDepTime10,
            data = getAirDemoTextLocalDS(),
            transforms = list(CRSDepTime10 = 10 * CRSDepTime)
        )
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopCovCor <-
        rxCovCor(
            ~ ArrDelay + DayOfWeek + CRSDepTime10,
            data = getAirDemoParquetHdfsDS(),
            transforms = list(CRSDepTime10 = 10 * CRSDepTime)
        )
    
    checkEquals(localCovCor$CovCor, hadoopCovCor$CovCor)
    checkEquals(localCovCor$StdDevs, hadoopCovCor$StdDevs)
    checkEquals(localCovCor$Means, hadoopCovCor$Means)
    
    rxSetComputeContext(getLocalComputeContext())
}

"test.hadoop.rxGlm.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    # rxGlm with input xdf file
    rxSetComputeContext(getLocalComputeContext())
    
    localRxGlm <-
        rxGlm(
            ArrOnTime ~ CRSDepTime,
            data = getAirDemoTextLocalDS(),
            family = binomial(link = "probit"),
            transforms = list(ArrOnTime = ArrDelay < 2)
        )
    
    rxSetComputeContext(getHadoopComputeContext())
    hadoopRxGlm <-
        rxGlm(
            ArrOnTime ~ CRSDepTime,
            data = getAirDemoParquetHdfsDS(),
            family = binomial(link = "probit"),
            transforms = list(ArrOnTime = ArrDelay < 2)
        )
    
    checkEquals(localRxGlm$coefficients, hadoopRxGlm$coefficients)
    checkEquals(localRxGlm$coef.std.error, hadoopRxGlm$coef.std.error)
    checkEquals(localRxGlm$df, hadoopRxGlm$df)
    
    rxSetComputeContext(getLocalComputeContext())
}


#############################################################################################
# Tests for analysis functions that write data
#############################################################################################

"test.hadoop.rxLogit.rxPredict.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    ### Local computations
    rxSetComputeContext(getLocalComputeContext())
    inLocalDS <- getAirDemoTextLocalDS()
    outLocalDS <- getTestOutFileLocalDS("LogitDFPred")
    
    # Logistic regression
    localLogit <- rxLogit(
        ArrDel15 ~ DayOfWeek,
        data = inLocalDS,
        transforms = list(ArrDel15 = ArrDelay > 15),
        maxIterations = 6
    )
    
    # Predictions
    localPredOut <-
        rxPredict(
            modelObject = localLogit,
            data = inLocalDS,
            writeModelVars = TRUE,
            predVarNames = "delayPred1",
            outData = outLocalDS,
            overwrite = TRUE
        )
    
    outLocalVarInfo <- rxGetVarInfo(outLocalDS)
    
    localPredOut2 <-
        rxPredict(
            modelObject = localLogit,
            data = inLocalDS,
            writeModelVars = TRUE,
            predVarNames = "delayPred1",
            extraVarsToWrite = "CRSDepTime",
            outData = outLocalDS,
            overwrite = TRUE
        )
    
    outLocalVarInfo2 <- rxGetVarInfo(outLocalDS)
    
    localPredOut3 <-
        rxPredict(
            modelObject = localLogit,
            data = inLocalDS,
            writeModelVars = FALSE,
            predVarNames = "delayPred1",
            extraVarsToWrite = c("ArrDelay", "CRSDepTime"),
            outData = outLocalDS,
            overwrite = TRUE
        )
    
    outLocalVarInfo3 <- rxGetVarInfo(outLocalDS)
    
    ### Hadoop computations
    rxSetComputeContext(getHadoopComputeContext())
    inHadoopDS <- getAirDemoParquetHdfsDS()
    outHadoopDS <- getTestOutFileHdfsDS("LogitDFPred")
    
    # Logistic regression
    hadoopLogit <- rxLogit(
        ArrDel15 ~ DayOfWeek,
        data = inHadoopDS,
        transforms = list(ArrDel15 = ArrDelay > 15),
        maxIterations = 6
    )
    
    colInfo = list(DayOfWeek = list(type = "factor"))
    
    df <- getAirDemoParquetHdfsDS()
    hadoopLogit <- rxLogit(
        ArrDel15 ~ DayOfWeek,
        data = df,
        transforms = list(ArrDel15 = ArrDelay > 15),
        maxIterations = 6
    )
    
    
    checkEquals(hadoopLogit$coefficients,   localLogit$coefficients)
    checkEquals(hadoopLogit$coef.std.error, localLogit$coef.std.error)
    
    
    
    # Predictions
    hadoopPredOut <-
        rxPredict(
            modelObject = hadoopLogit,
            data = inHadoopDS,
            writeModelVars = TRUE,
            predVarNames = "delayPred1",
            outData = outHadoopDS,
            overwrite = TRUE
        )
    
    outHadoopVarInfo <- rxGetVarInfo(outHadoopDS)
    
    hadoopPredOut2 <-
        rxPredict(
            modelObject = hadoopLogit,
            data = inHadoopDS,
            writeModelVars = TRUE,
            predVarNames = "delayPred1",
            extraVarsToWrite = "CRSDepTime",
            outData = outHadoopDS,
            overwrite = TRUE
        )
    
    outHadoopVarInfo2 <- rxGetVarInfo(outHadoopDS)
    
    hadoopPredOut3 <-
        rxPredict(
            modelObject = hadoopLogit,
            data = inHadoopDS,
            writeModelVars = FALSE,
            predVarNames = "delayPred1",
            extraVarsToWrite = c("ArrDelay", "CRSDepTime"),
            outData = outHadoopDS,
            overwrite = TRUE
        )
    
    outHadoopVarInfo3 <- rxGetVarInfo(outHadoopDS)
    
    checkEquals(outHadoopVarInfo$delayPred1, outLocalVarInfo$delayPred1)
    checkEquals(outHadoopVarInfo$ArrDelay, outLocalVarInfo$ArrDelay)
    
    checkEquals(length(outHadoopVarInfo2), length(outLocalVarInfo2))
    checkEquals(outHadoopVarInfo2$ArrDelay, outLocalVarInfo2$ArrDelay)
    
    checkEquals(length(outHadoopVarInfo3), length(outLocalVarInfo3))
    checkEquals(outHadoopVarInfo3$ArrDelay, outLocalVarInfo3$ArrDelay)
    checkEquals(outHadoopVarInfo3$CRSDepTime,
                outLocalVarInfo3$CRSDepTime)
    
    # Clean-up
    removeTestOutFileHdfsDS(outHadoopDS)
    
    rxSetComputeContext(getLocalComputeContext())
    removeTestOutFileLocalDS(outLocalDS)
    
}

"test.hadoop.rxKmeans.args.outFile.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    testCenters <- matrix(c(13, 20, 7, 17, 10), ncol = 1)
    
    ### Local computations
    rxSetComputeContext(getLocalComputeContext())
    outLocalDS <- getTestOutFileLocalDS("KmeansDFOut")
    
    localKmeans <-
        rxKmeans(
            ~ CRSDepTime,
            data = getAirDemoTextLocalDS(),
            outFile = outLocalDS,
            centers = testCenters,
            writeModelVars = TRUE,
            overwrite = TRUE,
            maxIterations = 3
        )
    
    localInfo <- rxGetInfo(outLocalDS, getVarInfo = TRUE)
    
    ### Hadoop computations
    rxSetComputeContext(getHadoopComputeContext())
    outHadoopDS <- getTestOutFileHdfsDS("KmeansDFOut")
    
    hadoopKmeans <-
        rxKmeans(
            ~ CRSDepTime,
            data = getAirDemoParquetHdfsDS(),
            outFile = outHadoopDS,
            centers = testCenters,
            writeModelVars = TRUE,
            overwrite = TRUE,
            maxIterations = 3
        )
    
    hadoopInfo <- rxGetInfo(outHadoopDS, getVarInfo = TRUE)
    
    # Comparison tests
    checkEquals(hadoopInfo$numRows, localInfo$numRows)
    checkIdentical(hadoopInfo$varInfo, localInfo$varInfo)
    checkEquals(hadoopKmeans$centers, localKmeans$centers)
    
    # Clean-up
    removeTestOutFileHdfsDS(outHadoopDS)
    
    rxSetComputeContext(getLocalComputeContext())
    removeTestOutFileLocalDS(outLocalDS)
}


# Purpose:   Test basic regression tree functionality on Hadoop
"test.hadoop.rxDTree.regression.DF" <- function()
{
    checkTrue(require(rpart), "rpart package not found")
    
    formula <- as.formula("ArrDelay ~ CRSDepTime + DayOfWeek")
    
    ### Local computations
    rxSetComputeContext(getLocalComputeContext())
    inLocalDS <- getAirDemoXdfLocalDS()
    outLocalDS <- getTestOutFileLocalDS("DTreeDFOut")
    localDTree <- rxDTree(
        formula,
        data  = inLocalDS,
        blocksPerRead  = 30,
        minBucket      = 500,
        maxDepth       = 10,
        cp             = 0,
        xVal           = 0,
        maxCompete     = 0,
        maxSurrogate   = 0,
        maxNumBins     = 101,
        verbose        = 1,
        reportProgress = 0
    )
    
    # Compute predictions
    localPred <-
        rxPredict(
            localDTree,
            data = inLocalDS,
            outData = outLocalDS,
            overwrite = TRUE,
            verbose = 1,
            reportProgress = 0
        )
    localPredSum <- rxSummary(~ ArrDelay_Pred, data = outLocalDS)
    
    
    ### Hadoop computations
    rxSetComputeContext(getHadoopComputeContext())
    inHadoopDS <- getAirDemoParquetHdfsDS()
    outHadoopDS <- getTestOutFileHdfsDS("DTreeDFOut")
    hadoopDTree <- rxDTree(
        formula,
        data  = inHadoopDS,
        blocksPerRead  = 30,
        minBucket      = 500,
        maxDepth       = 10,
        cp             = 0,
        xVal           = 0,
        maxCompete     = 0,
        maxSurrogate   = 0,
        maxNumBins     = 101,
        verbose        = 1,
        reportProgress = 0
    )
    
    # Compute predictions
    
    hadoopPred <-
        rxPredict(
            hadoopDTree,
            data = inHadoopDS,
            outData = outHadoopDS,
            overwrite = TRUE,
            verbose = 1,
            reportProgress = 0
        )
    hadoopPredSum <-
        rxSummary(~ ArrDelay_Pred, data = outHadoopDS)
    
    # Perform checks
    
    #checkEquals( sum( ADSrxdt$splits[ , "improve" ] ), 0.181093099185139 )
    checkEquals(sum(localDTree$splits[, "improve"]), sum(hadoopDTree$splits[, "improve"]))
    
    localPrune <- prune(localDTree,  cp = 1e-6)
    hadoopPrune <- prune(hadoopDTree,  cp = 1e-6)
    checkEquals(sum(localPrune$splits[, "improve"]), sum(hadoopPrune$splits[, "improve"]))
    
    checkEquals(localPredSum$sDataFrame, hadoopPredSum$sDataFrame)
    
    # Clean-up
    removeTestOutFileHdfsDS(outHadoopDS)
    
    rxSetComputeContext(getLocalComputeContext())
    removeTestOutFileLocalDS(outLocalDS)
}

#############################################################################################
# rxExec Example
#############################################################################################
##??? Can data frame be passed to rxExec
# "test.hadoop.rxExec" <- function()
#{
#	playCraps <- function()
#    {
#	    result <- NULL
#	    point <- NULL
#	    count <- 1
#	    while (is.null(result))
#	    {
#		    roll <- sum(sample(6, 2, replace=TRUE))

#		    if (is.null(point))
#		    {
#			    point <- roll
#		    }
#		    if (count == 1 && (roll == 7 || roll == 11))
#		    {
#			    result <- "Win"
#		    }
#		    else if (count == 1 && (roll == 2 || roll == 3 || roll == 12))
#		    {
#			    result <- "Loss"
#		    }
#		    else if (count > 1 && roll == 7 )
#		    {
#			    result <- "Loss"
#		    }
#		    else if (count > 1 && point == roll)
#		    {
#			    result <- "Win"
#		    }
#		    else
#		    {
#			    count <- count + 1
#		    }
#	    }
#	    result
#    }
### Local computations
#    rxSetComputeContext( getLocalComputeContext() )
#    localExec <- rxExec(playCraps, timesToRun=100, taskChunkSize=25)

#	rxSetComputeContext( getHadoopComputeContext() )
#	hadoopExec <- rxExec(playCraps, timesToRun=100, taskChunkSize=25)
#	checkEquals(length(localExec), length(hadoopExec))
#	checkEquals(length(localExec[[1]]), length(hadoopExec[[1]]))

#}

"test.hadoop.dataPath.DF" <- function()
{
    on.exit(rxSetComputeContext(getLocalComputeContext()), add = TRUE)
    
    localComputeContext <- getLocalComputeContext()
    localAirDS <- getAirDemoTextLocalDS()
    localAirBase <- basename(localAirDS@file)
    localAirDir <- dirname(localAirDS@file)
    localComputeContext@dataPath <- localAirDir
    localAirDS@file <- localAirBase
    
    # rxSummary with input csv file
    rxSetComputeContext(localComputeContext)
    localSummary <-
        rxSummary(
            ArrDelay10 ~ DayOfWeek,
            data = localAirDS,
            rowSelection = CRSDepTime > 10,
            transforms = list(ArrDelay10 = 10 * ArrDelay)
        )
    
    hadoopComputeContext <- getHadoopComputeContext()
    hadoopAirDS <- getAirDemoParquetHdfsDS()
    hadoopAirBase <- basename(hadoopAirDS@file)
    hadoopAirDir <- dirname(hadoopAirDS@file)
    hadoopComputeContext@dataPath <- hadoopAirDir
    hadoopAirDS@file <- hadoopAirBase
    rxSetComputeContext(hadoopComputeContext)
    hadoopSummary <-
        rxSummary(
            ArrDelay10 ~ DayOfWeek,
            data = hadoopAirDS,
            rowSelection = CRSDepTime > 10,
            transforms = list(ArrDelay10 = 10 * ArrDelay)
        )
    
    checkEquals(localSummary$categorical[[1]], hadoopSummary$categorical[[1]])
    
    rxSetComputeContext(getLocalComputeContext())
}



#############################################################################################
# Always run last: Test to remove data from Hadoop cluster
#############################################################################################

"test.hadoop.zzz.removeHadoopData.DF" <- function()
{
    rxTestArgs <- getOption("rxTestArgs")
    if (is.null(rxTestArgs$nameNode) ||
        rxTestArgs$nameNode == "default") {
        nameNodePrefix = ""
    } else {
        nameNodePrefix = rxTestArgs$nameNode
    }
    # Always remove temp data
    rxSetComputeContext(getHadoopComputeContext())
    testOutputDir <- file.path(
        getOption("rxTestArgs")$hdfsShareDir,
        getOption("rxTestArgs")$myHdfsTestOuputSubdir
    )
    rxHadoopRemoveDir(paste0(nameNodePrefix, testOutputDir))
    if (getOption("rxTestArgs")$removeHadoopDataOnCompletion)
    {
        # Remove air data from Hadoop cluster
        
        airDemoSmallCsvHdfsPath <-
            file.path(
                getOption("rxTestArgs")$hdfsShareDir,
                getOption("rxTestArgs")$myHdfsAirDemoCsvSubdir
            )
        rxHadoopRemoveDir(paste0(nameNodePrefix, airDemoSmallCsvHdfsPath))
        
        #airDemoSmallXdfHdfsPath <- file.path(getOption("rxTestArgs")$hdfsShareDir,
        #    getOption("rxTestArgs")$myHdfsAirDemoXdfSubdir)
        #rxHadoopRemoveDir(paste0(nameNodePrefix, airDemoSmallXdfHdfsPath))
        
        airDemoSmallParquetHdfsPath <-
            file.path(
                getOption("rxTestArgs")$hdfsShareDir,
                getOption("rxTestArgs")$myHdfsAirDemoParquetSubdir
            )
        rxHadoopRemoveDir(paste0(nameNodePrefix, airDemoSmallParquetHdfsPath))
        
    }
    else
    {
        rxHadoopMakeDir(paste0(nameNodePrefix, testOutputDir))
    }
    rxSetComputeContext(getLocalComputeContext())
}
