# Copyright (c) Microsoft Corporation.  All rights reserved.

# Tests for basic functionality of rxFastTrees

"test.rxFastTrees.basic" <- function()
{
    # Create temporary data sources
    myIris = iris
    myIris$Setosa <- iris$Species == "setosa"
    myXdf <- tempfile(pattern = "myIris", fileext = ".xdf")
    on.exit(file.remove(myXdf), add = TRUE)
    rxDataStep(myIris, myXdf, rowsPerRead = 50, overwrite = TRUE)
    myXdfDS <- RxXdfData(file = myXdf)
    
    myCsv <- tempfile(pattern = "myIris", fileext = ".csv")
    on.exit(file.remove(myCsv), add = TRUE)
    myCsvDS <- RxTextData(file = myCsv, colInfo = rxCreateColInfo(iris))
    rxDataStep(myIris, myCsvDS, overwrite = TRUE)
    
    readVars <- c("Setosa", "Sepal.Length", "Petal.Length", "Sepal.Width")
    
    # Run examples
    myFormula <- Setosa ~ Sepal.Length + Petal.Length + Sepal.Width

    # xdf file
    res1 <- rxFastTrees(formula = myFormula, data = myXdfDS)
    checkEquals(res1$params$readVars, readVars)
    
    # data frame
    res2 <- rxFastTrees(formula = myFormula,
        data = myIris, 
	    reportProgress = 4)
    checkEquals(res2$params$readVars, readVars)
    
    res3 <- rxFastTrees(formula = myFormula,
        data = myCsvDS)
    checkEquals(res3$params$readVars, readVars) 

}

"test.rxFastTrees.args.formula" <- function()
{
    # Create temporary data sources
    myIris = iris
    myIris$isVersi <- iris$Species == "versicolor"
    myIris$Species <- NULL
    myXdf <- tempfile(pattern = "myIris", fileext = ".xdf")
    on.exit(file.remove(myXdf), add = TRUE)
    rxDataStep(myIris, myXdf, rowsPerRead = 50, overwrite = TRUE)
    myXdfDS <- RxXdfData(file = myXdf)
    
    myCsv <- tempfile(pattern = "myIris", fileext = ".csv")
    on.exit(file.remove(myCsv), add = TRUE)
    myCsvDS <- RxTextData(file = myCsv, colInfo = rxCreateColInfo(iris))
    rxDataStep(myIris, myCsvDS, overwrite = TRUE)
    
    # Run examples
    myFormula1 <- isVersi ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
    myFormula2 <- isVersi ~ .

    # xdf file
    resXdf1 <- rxFastTrees(formula = myFormula1, data = myXdfDS)
    resXdf2 <- rxFastTrees(formula = myFormula2, data = myXdfDS)
    
    scoreXdf1 <- rxPredict(resXdf1, data = myXdfDS)    
    scoreXdf2 <- rxPredict(resXdf2, data = myXdfDS)
    checkEquals(scoreXdf1, scoreXdf2)
    
    scoreXdf3 <- rxPredict(resXdf1, data = myXdfDS, writeModelVars = TRUE)    
    scoreXdf4 <- rxPredict(resXdf2, data = myXdfDS, writeModelVars = TRUE)
    checkEquals(scoreXdf3, scoreXdf4)  
    
    scoreXdf5 <- rxPredict(resXdf1, data = myXdfDS, extraVarsToWrite = "Sepal.Width")    
    scoreXdf6 <- rxPredict(resXdf2, data = myXdfDS, extraVarsToWrite = "Sepal.Width")
    checkEquals(scoreXdf5, scoreXdf6)         
    
    # data frame
    resDF1 <- rxFastTrees(formula = myFormula1,
        data = myIris)
    
    resDF2 <- rxFastTrees(formula = myFormula2,
        data = myIris) 
        
    scoreDF1 <- rxPredict(resDF1, data = myIris)    
    scoreDF2 <- rxPredict(resDF2, data = myIris)               
    checkEquals(scoreDF1, scoreDF2)
    
    scoreDF3 <- rxPredict(resDF1, data = myIris, writeModelVars = TRUE) 
    scoreDF4 <- rxPredict(resDF2, data = myIris, writeModelVars = TRUE)               
    checkEquals(scoreDF3, scoreDF4)    
    
    scoreDF5 <- rxPredict(resDF1, data = myIris, extraVarsToWrite = "Sepal.Width") 
    scoreDF6 <- rxPredict(resDF2, data = myIris, extraVarsToWrite = "Sepal.Width")               
    checkEquals(scoreDF5, scoreDF6) 
    checkTrue("Sepal.Width" %in% names(scoreDF5))  
    
    scoreDF7 <- rxPredict(resDF1, data = myIris, extraVarsToWrite = "isVersi") 
    scoreDF8 <- rxPredict(resDF2, data = myIris, extraVarsToWrite = "isVersi")               
    checkEquals(scoreDF7, scoreDF8)  
    checkTrue("isVersi" %in% names(scoreDF7))  
    
    myIrisScore <- myIris
    myIrisScore$rowNum <- 1:nrow(myIris)
    
    scoreDF9 <- rxPredict(resDF1, data = myIrisScore, writeModelVars = TRUE, extraVarsToWrite = "rowNum") 
    scoreDF10 <- rxPredict(resDF2, data = myIrisScore, writeModelVars = TRUE, extraVarsToWrite = "rowNum")               
    checkEquals(scoreDF9, scoreDF10) 
    checkTrue("rowNum" %in% names(scoreDF9))  
    checkTrue("Sepal.Width" %in% names(scoreDF9))               
    
    resCsv1 <- rxFastTrees(formula = myFormula1,
        data = myCsvDS)
    scoreCsv1 <- rxPredict(resCsv1, data = myCsvDS)
    resCsv2 <- rxFastTrees(formula = myFormula2,
        data = myCsvDS)  
    scoreCsv2 <- rxPredict(resCsv2, data = myCsvDS)    
    checkEquals(scoreCsv1, scoreXdf1) 
    checkEquals(scoreCsv2, scoreXdf1)       

}

"test.rxFastTrees.args.transforms" <- function()
{
    # Create temporary data sources
    myIris = iris
    myIris$Setosa <- iris$Species == "setosa"
    myXdf <- tempfile(pattern = "myIris", fileext = ".xdf")
    on.exit(file.remove(myXdf), add = TRUE)
    rxDataStep(myIris, myXdf, rowsPerRead = 50, overwrite = TRUE)
    myXdfDS <- RxXdfData(file = myXdf)
    
    myCsv <- tempfile(pattern = "myIris", fileext = ".csv")
    on.exit(file.remove(myCsv), add = TRUE)
    myCsvDS <- RxTextData(file = myCsv, colInfo = rxCreateColInfo(iris))
    rxDataStep(myIris, myCsvDS, overwrite = TRUE)
       
    # Run examples
    myFormula1 <- Setosa ~ Sepal.Length + Petal.Length + Sepal.Width
    myFormula2 <- SetosaTran ~ Sepal.Length + Petal.Length + Sepal.Width

    # xdf file
    tree1 <- rxFastTrees(formula = myFormula1, data = myXdfDS)
    dfWithoutTransforms <- rxPredict( tree1, 
         data = myXdfDS, extraVarsToWrite = c("Setosa"),
         outData = NULL, overwrite = TRUE)
    
    # R transform with XDF
    tree2 <- rxFastTrees(formula = myFormula2, data = myXdfDS, 
        transforms = list(SetosaTran = Species == "setosa"))
    
    dfWithTransforms <- rxPredict( tree2, 
         data = myXdfDS, extraVarsToWrite = c("SetosaTran"),
         outData = NULL, overwrite = TRUE) 
        
    names(dfWithTransforms) <- names(dfWithoutTransforms)
    checkIdentical(dfWithTransforms, dfWithoutTransforms)
    
    # MAML transform with XDF
    tree3 <- rxFastTrees(formula = myFormula2, data = myXdfDS,
                 mlTransforms = list("Expr{col=SetosaTran:Setosa expr={x : x }} "),
                 mlTransformVars = "Setosa")
                 #mamlCode = "xf=Expr{col=SetosaTran:Setosa expr={x : x }} ",
                 #mamlTransformVars = "Setosa")     
    
    dfWithTransforms <- rxPredict( tree3, 
         data = myXdfDS, extraVarsToWrite = c("SetosaTran"),
         outData = NULL, overwrite = TRUE)
        
    names(dfWithTransforms) <- names(dfWithoutTransforms)
    checkEquals(dfWithTransforms, dfWithoutTransforms)    
    
    
    # data frame
    tree1 <- rxFastTrees(formula = myFormula1, data = myIris)
    dfWithoutTransforms <- rxPredict( tree1, 
         data = myXdfDS, extraVarsToWrite = c("Setosa"),
         outData = NULL, overwrite = TRUE)
    
    # R transform with data frame
    tree2 <- rxFastTrees(formula = myFormula2, data = myIris, 
        transforms = list(SetosaTran = Species == "setosa"))
    
    dfWithTransforms <- rxPredict( tree2, 
         data = myIris, extraVarsToWrite = c("SetosaTran"),
         outData = NULL, overwrite = TRUE)
        
    names(dfWithTransforms) <- names(dfWithoutTransforms)
    checkIdentical(dfWithTransforms, dfWithoutTransforms)
    
    # MAML transform with data frame
    tree3 <- rxFastTrees(formula = myFormula2, data = myIris, 
                 mlTransforms = list("Expr{col=SetosaTran:Setosa expr={x : x }} "),
                 mlTransformVars = "Setosa")     
    
    dfWithTransforms <- rxPredict( tree3, 
         data = myIris, extraVarsToWrite = c("SetosaTran"),
         outData = NULL, overwrite = TRUE)
        
    names(dfWithTransforms) <- names(dfWithoutTransforms)
    checkEquals(dfWithTransforms, dfWithoutTransforms)    
    
  # Text data source  
    tree1 <- rxFastTrees(formula = myFormula1, data = myCsvDS)
    dfWithoutTransforms <- rxPredict( tree1, 
         data = myCsvDS,, extraVarsToWrite = c("Setosa"),
         outData = NULL, overwrite = TRUE)
    
    # R transform with text data source
    tree2 <- rxFastTrees(formula = myFormula2, data = myCsvDS,
        transforms = list(SetosaTran = Species == "setosa"))
    
    dfWithTransforms <- rxPredict( tree2, 
         data = myCsvDS, extraVarsToWrite = c("SetosaTran"),
         outData = NULL, overwrite = TRUE)
        
    names(dfWithTransforms) <- names(dfWithoutTransforms)
    checkIdentical(dfWithTransforms, dfWithoutTransforms)
    
    # MAML transform with data frame
    tree3 <- rxFastTrees(formula = myFormula2, data = myCsvDS, 
                 mlTransforms = list("Expr{col=SetosaTran:Setosa expr={x : x }} "),
                 mlTransformVars = "Setosa")     
    
    dfWithTransforms <- rxPredict( tree3, 
         data = myCsvDS, extraVarsToWrite = c("SetosaTran"),
         outData = NULL, overwrite = TRUE)
        
    names(dfWithTransforms) <- names(dfWithoutTransforms)
    checkEquals(dfWithTransforms, dfWithoutTransforms)       
}

"test.rxFastTrees.type.regression" <- function()
{
    #  A Simple Regression Tree
    myFormula <- mpg ~ disp

    res1 <- rxFastTrees(formula = myFormula, data = mtcars, type = "regression")
    readVars <- c("mpg", "disp")
    checkEquals(res1$params$readVars, readVars)  
    
    checkTrue(is.list(coef(res1)))
}

"test.rxFastTrees.type.binary" <- function()
{
    dataFile <- file.path(rxGetOption("sampleDataDir"), "claims.txt")

    dataColInfo <- list(
        RowNum =list(type = "integer"),
        age = list( type = "factor",
            levels = c("17-20", "21-24", "25-29", "30-34", "35-39", "40-49", "50-59", "60+")),
        car.age = list(type = "factor",
            levels = c("0-3", "4-7", "8-9", "10+")),
        type = list(type = "factor",
            levels = c("A", "B", "C", "D")),
		cost = list(type = "float32"),
		number = list(type = "float32"))
	
	dataSource <- RxTextData(dataFile, colInfo = dataColInfo)
	
	type <- "binary"	
	form <- age30 ~ car.age + type + cost + number
	transforms <- quote(list(age30 = (age == "30-34" | age == "35-39")))
	rowSelection <- quote(number > 10)
	writeModelVars <- FALSE
    extraVarsToWrite <- c("RowNum", "age", "age30")
	
    rxSetComputeContext("local")
    model <- rxFastTrees(form, data = dataSource, type = type,
	    transforms = transforms, rowSelection = rowSelection
		)
    summ <- summary(model)
    score <- rxPredict(model, data = dataSource, 
		writeModelVars = writeModelVars, extraVarsToWrite = extraVarsToWrite)
    checkEquals(extraVarsToWrite, colnames(score)[seq_along(extraVarsToWrite)])
    
    checkTrue(is.list(coef(model)))
}


"test.rxFastTrees.args.numTrees" <- function()
{
    #  A Simple Regression Tree
    # FIXME: What is reasonable range?
    myFormula <- mpg ~ disp
    checkException(
		res1 <- rxFastTrees(formula = myFormula, data = mtcars, type = "regression", numTrees = 0),
		'Error in processing machine learning request.')
    
    res2 <- rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
        numTrees = 1)  
    out2 <- rxPredict(res2, data = mtcars)      
}

"test.rxFastTrees.args.numLeaves" <- function()
{
    #  A Simple Regression Tree
    # FIXME: What is reasonable range?
    myFormula <- mpg ~ disp
    res1 <- rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
        numLeaves = 10)
    out1 <- rxPredict(res1, data = mtcars)      
}

"test.rxFastTrees.args.learningRate" <- function()
{
    #  A Simple Regression Tree
    # FIXME: What is reasonable range?
    myFormula <- mpg ~ disp
    res1 <- rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
        learningRate = 2)
    out1 <- rxPredict(res1, data = mtcars)      
}

"test.rxFastTrees.args.minSplit" <- function()
{
    #  A Simple Regression Tree
    # FIXME: What is reasonable range?
    myFormula <- mpg ~ disp
    res1 <- rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
        minSplit = 1000)
    out1 <- rxPredict(res1, data = mtcars)      
}

"test.rxFastTrees.args.exampleFraction" <- function()
{
   #  A Simple Regression Tree
   # Make sure it can be set to something other than default
    myFormula <- mpg ~ disp
    res1 <- rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
        exampleFraction = .2)
    
   # This should fail       
    res2 <- try(
        rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
            exampleFraction = 1.1), silent = TRUE)
        
    checkTrue(inherits( res2, "try-error")) 
    checkTrue(grepl("exampleFraction' must be", as.character(res2)))   
    
   # This should fail       
    res3 <- try(
        rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
            exampleFraction = -1), silent = TRUE)
        
    checkTrue(inherits( res3, "try-error")) 
    checkTrue(grepl("exampleFraction' must be", as.character(res3)))             
}

"test.rxFastTrees.args.featureFraction" <- function()
{
    #  A Simple Regression Tree
    #  Must be between 0 and 1
    myFormula <- mpg ~ disp
   
   # This should fail       
    res1 <- try(
        rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
            featureFraction = -1), silent = TRUE)
        
    checkTrue(inherits( res1, "try-error")) 
    checkTrue(grepl("featureFraction' must be", as.character(res1)))       
}

"test.rxFastTrees.args.splitFraction" <- function()
{
    # Must be between 0 and 1
    myFormula <- mpg ~ disp
    
   # This should fail       
    res1 <- try(
        rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
            splitFraction = -1), silent = TRUE)
        
    checkTrue(inherits( res1, "try-error")) 
    checkTrue(grepl("splitFraction' must be", as.character(res1)))      
}

"test.rxFastTrees.args.numBins" <- function()
{
    #  A Simple Regression Tree
    myFormula <- mpg ~ disp
    res1 <- rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
        numBins = 10000)
    out1 <- rxPredict(res1, data = mtcars)    
    
    # Must be > 0
    # This should fail       
    res2 <- try(
        rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
            numBins = 0), silent = TRUE)
        
    checkTrue(inherits( res2, "try-error")) 
    checkTrue(grepl("numBins' must be greater than 0", as.character(res2)))           
}

"test.rxFastTrees.args.firstUsePenalty" <- function()
{
    # Must be non-negative
    myFormula <- mpg ~ disp
    res1 <- rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
        firstUsePenalty = 1000)
    out1 <- rxPredict(res1, data = mtcars) 
    
    res2 <- try(
        rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
            firstUsePenalty = -1), silent = TRUE)
        
    checkTrue(inherits( res2, "try-error")) 
    checkTrue(grepl("firstUsePenalty' must be", as.character(res2)))             
}

"test.rxFastTrees.args.gainConfLevel" <- function()
{
    #  A Simple Regression Tree
    # Range: [0,1)
       
    myFormula <- mpg ~ disp
    res1 <-
        rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
            gainConfLevel = 0)
    
    out1 <- rxPredict(res1, data = mtcars)  
    
    # This should fail       
    res2 <- try(
        rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
            gainConfLevel = 1), silent = TRUE)
        
    checkTrue(inherits( res2, "try-error")) 
    checkTrue(grepl("gainConfLevel' must be less than 1", as.character(res2)))      
}

"test.rxFastTrees.args.unbalancedSets" <- function()
{
    # Simple binary tree
    myIris <- iris
    myIris$isVersi <- iris$Species == "versicolor"
    irisFormula <- isVersi~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
    res1a <- rxFastTrees(formula = irisFormula, data = myIris, 
            unbalancedSets = TRUE)
        
    res1b <- rxFastTrees(formula = irisFormula, data = myIris, 
            unbalancedSets = FALSE)  
        
    sum1a <- summary(res1a)  
    sum1b <- summary(res1b) 
    # Check to make sure it makes a difference in the coefficients
    checkTrue(unlist(coef(sum1a)[2]) != unlist(coef(sum1b)[2]))      
  
    # A Simple Regression Tree
    # Set warnings to errors
    oldWarn <- options(warn = 2) 
    on.exit(options(oldWarn))  
    myFormula <- mpg ~ disp
    # This should give warning (converted to error)  
    res2 <- try(
        rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
           unbalancedSet = TRUE), silent = TRUE)
    checkTrue(inherits( res2, "try-error")) 
    checkTrue(grepl("'unbalancedSets' ignored for type 'regression'", as.character(res2)))  
    options(oldWarn)
         
}

"test.rxFastTrees.args.trainThreads" <- function()
{
    # Simple binary tree
    myIris <- iris
    myIris$isVersi <- iris$Species == "versicolor"
    irisFormula <- isVersi~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
    
    res1 <- try(
        rxFastTrees(formula = irisFormula, data = myIris, 
           trainThreads = -1), silent = TRUE)
    checkTrue(inherits( res1, "try-error")) 
    checkTrue(grepl("'trainThreads' must be", as.character(res1)))      
        
    tm1 <- system.time(
        res2 <- rxFastTrees(formula = irisFormula, data = myIris,
           trainThreads = 4, reportProgress = 0) )           
         
}

"test.rxFastTrees.args.verbose" <- function()
{
    # This should give no output
    out1 <- capture.output(
        res1 <- rxFastTrees(formula = mpg ~ disp, data = mtcars, type = "regression",
           verbose = 0, reportProgress = 0)
    )

    checkTrue(if (rxIsExpressEdition()) length(out1) > 0 else length(out1) == 0)    
    
    
    myIris <- iris
    myIris$isVersi <- iris$Species == "versicolor"
    irisFormula <- isVersi~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
    out2 <- capture.output(
        res2 <- rxFastTrees(formula = irisFormula, data = myIris, verbose = 0,
            reportProgress = 0)
        )
    checkTrue(if (rxIsExpressEdition()) length(out2) > 0 else length(out2) == 0)    
    
    # This should give  output
    out3 <- capture.output(
        res3 <- rxFastTrees(formula = mpg ~ disp, data = mtcars, type = "regression",
           verbose = 1, reportProgress = 0)
    )

    checkTrue(length(out3) > 0)
    
    
    myIris <- iris
    myIris$isVersi <- iris$Species == "versicolor"
    irisFormula <- isVersi~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
    out4 <- capture.output(
        res4 <- rxFastTrees(formula = irisFormula, data = myIris, verbose = 1,
            reportProgress = 0)
        )   
    checkTrue(length(out4) > 0)    
}

"test.rxFastTrees.args.hidden" <- function()
{
    #  A Simple Regression Tree
    myFormula <- mpg ~ disp
    res1 <- rxFastTrees(formula = myFormula, data = mtcars, type = "regression",
        #unbalancedSets = FALSE,
        baggingSize = 0,
        exampleFraction = 0.7,
        bestStepRankingRegressionTrees = FALSE,
        useLineSearch = FALSE,
        numPostBracketSteps = 0,
        minStepSize = 0,
        shrinkage = 1,
        dropoutRate = 0,
        getDerivativesSampleRate = 1,
        smoothing = 0,
        trainThreads = 8,
        diskTranspose = FALSE,
        sparsifyThreshold = 0.7,
        gainConfLevel = 0,
        softmaxTemperature = 0,
        executionTimes = FALSE)
    
    readVars <- c("mpg", "disp")
    checkEquals(res1$params$readVars, readVars) 
    checkTrue(grepl("dropoutRate=0", res1$mamlCode)) 
    checkTrue(grepl("useLineSearch=-", res1$mamlCode)) 
    checkTrue(grepl("executionTimes=-", res1$mamlCode)) 

}

"test.rxFastTrees.data.integer" <- function()
{
    DEACTIVATED("coefficients property needs to be enabled")
    inData <- file.path(rxGetOption("sampleDataDir"), "claims4blocks.xdf")
    rxGetVarInfo(inData)
    modelOut1 <- rxFastTrees(RowNum ~ age + cost, data = inData, type = "regression")
	sum1 <- summary(modelOut1)
	
	inDF <- rxDataStep(inData)
	inDF$RowNum <- as.numeric(inDF$RowNum)
    modelOut2 <- rxFastTrees(RowNum ~ age + cost, data = inDF, type = "regression")
    sum2 <- summary(modelOut2)

    # Check for non nulls
    checkTrue(!is.null(sum1$coefficients))
    checkTrue(!is.null(sum2$coefficients))

	# Check to make sure the results are the same
	checkEquals(sum1$coefficients, sum2$coefficients)
	
}

"test.rxFastTrees.args.env" <- function()
{
    myFun2 <- function(nLeaves = 10)
    {
        myIris <- iris
        myIris$isVersi <- iris$Species == "versicolor"    
        out <- rxFastTrees(isVersi~Petal.Length + Petal.Width, 
            numLeaves = nLeaves, data = myIris)
        return(out)
    }
    x <- myFun2()
}

"test.rxFastTrees.args.mlTransforms" <- function()
{
    set.seed(10)
    trainReviews <- data.frame(review = 
        rep(c("I love it", "I hate it", "I really hate it"), times = 20),
        like = rep(c(TRUE, FALSE, FALSE), times = 20),
        stringsAsFactors = FALSE) 

    # Use a categorical transform: the entire string is treated as a category
    outModel1 <- rxFastTrees(like~review, data = trainReviews, 
        mlTransforms = list(categorical(vars = "review")))
    coef1 <- coef(outModel1)
    checkEquals(names(coef1), c("I love it", "I hate it", "I really hate it"))
    
    # Words are treated separately
    outModel4 <- rxFastTrees(like~review, data = trainReviews, 
        mlTransforms = list(featurizeText(vars = "review")))
    coef4 <- coef(outModel4)
    checkEquals(names(coef4), c( "love", "hate", "i", "really"))
}

"test.rxFastTrees.args" <- function()
{   
    dataFile <- file.path(rxGetOption("sampleDataDir"), "claims.txt")

    dataColInfo <- list(
        RowNum =list(type = "integer"),
        age = list( type = "factor",
            levels = c("17-20", "21-24", "25-29", "30-34", "35-39", "40-49", "50-59", "60+")),
        car.age = list(type = "factor",
            levels = c("0-3", "4-7", "8-9", "10+")),
        type = list(type = "factor",
            levels = c("A", "B", "C", "D")),
		cost = list(type = "float32"),
		number = list(type = "float32"))
	
	dataSource <- RxTextData(dataFile, colInfo = dataColInfo)
	
	type = "regression"
	numTrees = 100
    numLeaves = 20
	learningRate = 0.1
    minSplit = 10
    exampleFraction = 0.7
    featureFraction = 1
    splitFraction = 1
    numBins = 255
    firstUsePenalty = 0
    gainConfLevel = 0
    unbalancedSets = FALSE	
    randomSeed = NULL
	
	form <- cost ~ age + car.age + type + number
	
    rxSetComputeContext("local")
    model <- rxFastTrees(form, data = dataSource, type = type,
        numTrees = numTrees, numLeaves = numLeaves, minSplit = minSplit, 
        exampleFraction = exampleFraction, featureFraction = featureFraction, splitFraction = splitFraction, 
        numBins = numBins, firstUsePenalty = firstUsePenalty, gainConfLevel = gainConfLevel, unbalancedSets = unbalancedSets,
        randomSeed = randomSeed
		)
    (summ <- summary(model))
    score <- rxPredict(model, data = dataSource)
}

"test.rxFastTrees.data.mortDefault" <- function()
{
    mortXdf <- file.path(rxGetOption("sampleDataDir"), "mortDefaultSmall")
    mortDF <- rxDataStep(mortXdf)
    mortDF$default <- mortDF$default == 1
    set.seed(37)
    isTest <- rnorm(nrow(mortDF)) > 0
    mortTest <- mortDF[isTest,]
    mortTrain <- mortDF[!isTest,]

    # Specify the formula to use 
    binaryFormula <- default ~ creditScore + yearsEmploy + ccDebt
    fastTreeModel <- rxFastTrees(binaryFormula, data = mortTrain)
    
    fastTreeScore <- rxPredict(fastTreeModel, data = mortTest, 
        extraVarsToWrite = "default")
    rocOut <- rxRoc(actualVarName = "default", predVarNames = "Probability",    
        data = fastTreeScore)    
    auc1 <- rxAuc(rocOut)
    
    rxFastForestModel <- rxFastForest(binaryFormula, data = mortTrain)
    
    rxFastForestScore <- rxPredict(rxFastForestModel, data = mortTest, 
        extraVarsToWrite = "default")
    rocOut2 <- rxRoc(actualVarName = "default", predVarNames = "Probability",    
        data = rxFastForestScore)    
    auc2 <- rxAuc(rocOut2) 
    checkEquals(auc1, auc2, tolerance = 2.1E-01)  
}

"test.rxFastTrees.binary.factor.label" <- function()
{
	## simulate data
	nvar <- 2
	nobs <- 10
	y <- as.factor(c(rep("a", nobs), rep("b", nobs))) 
	offset <- 5
	c1 <- matrix(rnorm(nobs * nvar, mean = offset), nrow = nobs)
	c2 <- matrix(rnorm(nobs * nvar, mean = -offset), nrow = nobs)
	x <- rbind(c1, c2)
	cnames <- paste0("x", seq.int(nvar))
	colnames(x) <- cnames
	(yx <- cbind.data.frame(y, x))
	
	## modeling and prediction
	form <- paste("y", paste(cnames, collapse = "+"), sep = "~") 
	fit <- rxFastTrees(form, yx, type = "binary")
	(pred <- rxPredict(fit, data = yx, extraVarsToWrite="y"))
	
	checkEquals(pred$y, pred$PredictedLabel)
	
	checkTrue("Score.b" %in% names(pred))
	checkTrue("Probability.b" %in% names(pred))
}

"test.rxFastTrees.binary.integer.label" <- function()
{
	## simulate data
	nvar <- 2
	nobs <- 10
	y <- c(rep(3, nobs), rep(5, nobs)) 
	offset <- 5
	c1 <- matrix(rnorm(nobs * nvar, mean = offset), nrow = nobs)
	c2 <- matrix(rnorm(nobs * nvar, mean = -offset), nrow = nobs)
	x <- rbind(c1, c2)
	cnames <- paste0("x", seq.int(nvar))
	colnames(x) <- cnames
	(yx <- cbind.data.frame(y, x))
	
	## modeling and prediction
	form <- paste("y", paste(cnames, collapse = "+"), sep = "~") 
	fit <- rxFastTrees(form, yx, type = "binary")
	(pred <- rxPredict(fit, data = yx, extraVarsToWrite="y"))
	
	checkEquals(pred$y, as.numeric(as.character(pred$PredictedLabel)))
	
	checkTrue("Score.5" %in% names(pred))
	checkTrue("Probability.5" %in% names(pred))
}

"test.rxFastTrees.binary.logical.label" <- function()
{
	## simulate data
	nvar <- 2
	nobs <- 10
	y <- c(rep(FALSE, nobs), rep(TRUE, nobs)) 
	offset <- 5
	c1 <- matrix(rnorm(nobs * nvar, mean = offset), nrow = nobs)
	c2 <- matrix(rnorm(nobs * nvar, mean = -offset), nrow = nobs)
	x <- rbind(c1, c2)
	cnames <- paste0("x", seq.int(nvar))
	colnames(x) <- cnames
	(yx <- cbind.data.frame(y, x))
	
	## modeling and prediction
	form <- paste("y", paste(cnames, collapse = "+"), sep = "~") 
	fit <- rxFastTrees(form, yx, type = "binary")
	(pred <- rxPredict(fit, data = yx, extraVarsToWrite="y"))
	
	checkEquals(pred$y, pred$PredictedLabel)

	checkTrue("Score" %in% names(pred))
	checkTrue("Probability" %in% names(pred))
}

"test.rxFastTrees..MAML.code.check.optional.params" <- function() 
{
    myIris = iris
    myIris$Setosa <- iris$Species == "setosa"
    defaultMamlCode <- "lab={Setosa} feat={Sepal.Length} feat={Petal.Length} feat={Sepal.Width}   normalize=Auto trainer=FastTreeBinaryClassification{ unbalancedSets=- featureFraction=1 baggingSize=0 baggingTrainFraction=0.7 bestStepRankingRegressionTrees=- useLineSearch=- numPostBracketSteps=0 minStepSize=0 optimizationAlgorithm=GradientDescent earlyStoppingMetrics=0 enablePruning=- useTolerantPruning=- pruningThreshold=0.004 pruningWindowSize=5 testFrequency=2147483647 learningRates=0.2 shrinkage=1 dropoutRate=0 splitFraction=1 getDerivativesSampleRate=1 writeLastEnsemble=- smoothing=0 maxTreeOutput=100 numThreads=8 rngSeed=123 entropyCoefficient=0 histogramPoolSize=-1 diskTranspose=- maxBins=255 sparsifyThreshold=0.7 featureFirstUsePenalty=0 featureReusePenalty=0 gainConfidenceLevel=0 softmaxTemperature=0 executionTimes=- numLeaves=20 minDocumentsInLeafs=10 numTrees=100} calibrator=sigmoid"
    allParamsChanged <-"lab={Setosa} feat={Sepal.Length} feat={Petal.Length} feat={Sepal.Width}   normalize=Auto trainer=FastTreeBinaryClassification{ unbalancedSets=+ featureFraction=0.5 baggingSize=0 baggingTrainFraction=0.8 bestStepRankingRegressionTrees=- useLineSearch=- numPostBracketSteps=0 minStepSize=0 optimizationAlgorithm=GradientDescent earlyStoppingMetrics=0 enablePruning=- useTolerantPruning=- pruningThreshold=0.004 pruningWindowSize=5 testFrequency=2147483647 learningRates=0.3 shrinkage=1 dropoutRate=0 splitFraction=0.5 getDerivativesSampleRate=1 writeLastEnsemble=- smoothing=0 maxTreeOutput=100 numThreads=1 rngSeed=123 entropyCoefficient=0 histogramPoolSize=-1 diskTranspose=- maxBins=254 sparsifyThreshold=0.7 featureFirstUsePenalty=1 featureReusePenalty=0 gainConfidenceLevel=0.5 softmaxTemperature=0 executionTimes=- numLeaves=25 minDocumentsInLeafs=11 numTrees=110} calibrator=sigmoid randomSeed=5"
    
    # Run examples
    myFormula <- Setosa ~ Sepal.Length + Petal.Length + Sepal.Width
       
    resDefault <- rxFastTrees(formula = myFormula, data = myIris)
    resAllParamsChanged <- rxFastTrees(formula = myFormula, data = myIris, numTrees = 110, numLeaves = 25, learningRate = 0.3, minSplit = 11, exampleFraction = 0.8, featureFraction = 0.5, splitFraction = 0.5, numBins = 254, firstUsePenalty = 1, gainConfLevel = 0.5, unbalancedSets = TRUE, trainThreads = 1, randomSeed = 5)

    checkEquals(resDefault$mamlCode, defaultMamlCode)
    checkEquals(resAllParamsChanged$mamlCode,allParamsChanged)
}