# Copyright (c) Microsoft Corporation.  All rights reserved.
#
# FUNCTIONS
#    Unit tests for functions to coerce "rx" model objects to base R model objects
#
############################################################################################

.bHasPmml <- FALSE
.bLoadedPmml <- FALSE
.setUp <- function()
{

    if ("pmml" %in% .packages())
    {
        # pmml package is loaded
        .bHasPmml <<- TRUE
    }
    else
    {
        .bHasPmml <<- require(pmml)
        if (.bHasPmml == TRUE)
        {
          .bLoadedPmml <<- TRUE
        }
    }  
}

.tearDown <- function()
{
    if (.bLoadedPmml)
    {
        detach(package:pmml, unload = TRUE)
    }
}
".rxPmmlOutputDif" <- function( baseObj, rxObjCoerced)
{
    if (.bHasPmml)
    {
        outBase <- capture.output(pmml(baseObj))
        outCoerced <- capture.output(pmml(rxObjCoerced))

        for (i in 1:length(outCoerced))
        {
            if (outBase[i] != outCoerced[i])
            {
                if (!grepl(outBase[i], "Timestamp"))
                {
                    print(paste("Row number", i))
                    print(outBase[i])
                    print(outCoerced[i])
                }
            }
        }
        return(TRUE)
    }
    return(FALSE)
}

".rxCheckPmmlOutputDif" <- function( baseObj, rxObjCoerced)
{
    if (.bHasPmml)
    {
        outBase <- capture.output(pmml(baseObj))
        outCoerced <- capture.output(pmml(rxObjCoerced))
		# Remove timestamp
		outBase[5] <- ""
		outCoerced[5] <- ""
        return( checkEquals(outBase, outCoerced))
    }
    return(TRUE)
}

"test.as.lm.rxLinMod" <- function()
{
	# Use a simple model without factors
	
    form <- Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width
    linModObj <- rxLinMod(form, data=iris)
    lmObj <- lm(form, data=iris)
    lmCoerce <- as.lm(linModObj)
	
	checkEquals(as.vector(coef(lmObj)), as.vector(coef(lmCoerce)))
    # if pmml package is loaded, this will check for differences
    lmObj$coefficients <- signif(lmObj$coefficients, 6)
    lmCoerce$coefficients <- signif(lmCoerce$coefficients, 6)
    .rxCheckPmmlOutputDif(lmObj, lmCoerce)	
	
	# Try a log in the formula
    form <- log(Sepal.Length) ~ Sepal.Width + Petal.Length
    linModObj <- rxLinMod(form, data = iris)
    lmObj <- lm(form, data = iris)
    lmCoerce <- as.lm(linModObj)
	checkEquals(as.vector(coef(lmObj)), as.vector(coef(lmCoerce)))	
    # if pmml package is loaded, this will show the difference  
    lmObj$coefficients <- signif(lmObj$coefficients, 6)
    lmCoerce$coefficients <- signif(lmCoerce$coefficients, 6)  
    .rxCheckPmmlOutputDif(lmObj, lmCoerce)	    	
	
	# Add a factor variable
    form <- Sepal.Length ~ Sepal.Width + Species
    linModObj <- rxLinMod(form, data=iris)
    lmObj <- lm(form, data=iris, contrasts=list(Species=contr.SAS))
    lmCoerce <- as.lm(linModObj)
	checkEquals(as.vector(coef(lmObj)), as.vector(coef(lmCoerce)))
    # Looks like contr.SAS is not supported by pmml 
    # Try pmml(lmObj) and look at the coefficients
    
    # Test contrasts
     lmObj <- lm(form, data=iris)
     linModObj <- rxLinMod(form, data=iris, dropFirst = TRUE)
     lmCoerce <- as.lm(linModObj)
     checkEquals(lmObj$contrasts, lmCoerce$contrasts)
     checkEquals(lmObj$xlevels, lmCoerce$xlevels)
     checkEquals(lmObj$coefficients, lmCoerce$coefficients)
       
    # if pmml package is loaded, this will check for a difference 
    lmObj$coefficients <- signif(lmObj$coefficients, 6)
    lmCoerce$coefficients <- signif(lmCoerce$coefficients, 6)  
    .rxCheckPmmlOutputDif(lmObj, lmCoerce)	    
    
    # Make sure it works with .xdf
    xdfFile <- tempfile(pattern = ".rxCoerce1", fileext = ".xdf")
    rxDataStep(inData = iris, outFile = xdfFile)
    linModObj <- rxLinMod(form, data=xdfFile, dropFirst = TRUE)
    lmCoerce <- as.lm(linModObj)
    lmCoerce$coefficients <- signif(lmCoerce$coefficients, 6)  
    .rxCheckPmmlOutputDif(lmObj, lmCoerce)	
    
    file.remove(xdfFile)
    
}

"test.as.glm.rxLogit" <- function()
{
    form <- case ~ age + parity + spontaneous + induced
    logitObj <- rxLogit(form, data=infert, reportProgress = 0)
    glmObj <- glm(form, data = infert, family = binomial())
    glmCoerce <- as.glm(logitObj) 
    checkEquals(coef(glmObj), coef(glmCoerce))
	checkEquals(glmObj$aic, glmCoerce$aic)
	
    # if pmml package is loaded, this will checkEquals the output
    glmObj$coefficients <- signif(glmObj$coefficients, 6)
    glmCoerce$coefficients <- signif(glmCoerce$coefficients, 6)  
    .rxCheckPmmlOutputDif(glmObj, glmCoerce)
	
    # Try a factor
    
    form <- case ~ age + education + spontaneous + induced
    logitObj <- rxLogit(form, data=infert, reportProgress = 0, dropFirst = TRUE)
    glmObj <- glm(form, data = infert, family = binomial())
    glmCoerce <- as.glm(logitObj) 
    checkEquals(coef(glmObj), coef(glmCoerce))
	checkEquals(glmObj$aic, glmCoerce$aic)
	
    # if pmml package is loaded, this will checkEquals the output
    glmObj$coefficients <- signif(glmObj$coefficients, 6)
    glmCoerce$coefficients <- signif(glmCoerce$coefficients, 6)  
    .rxCheckPmmlOutputDif(glmObj, glmCoerce)    
    
    # Try an xdf file
    xdfFile <- tempfile(pattern = ".rxCoerce2", fileext = ".xdf")
    if (file.exists(xdfFile)) file.remove(xdfFile)
    rxDataStep(inData = infert, outFile = xdfFile)
    logitObj <- rxLogit(form, data=xdfFile, reportProgress = 0, dropFirst = TRUE)
    glmCoerce <- as.glm(logitObj) 
    glmCoerce$coefficients <- signif(glmCoerce$coefficients, 6)  
    checkEquals(coef(glmObj), coef(glmCoerce))
	checkEquals(glmObj$aic, glmCoerce$aic)
	
    # if pmml package is loaded, this will checkEquals the output
    .rxCheckPmmlOutputDif(glmObj, glmCoerce)    	
    
    file.remove(xdfFile)    
            
}

"test.as.glm.rxGlm" <- function()
{
    form <- case ~ age + parity + spontaneous + induced
    rxGlmObj <- rxGlm(form, data=infert, family = binomial(), reportProgress = 0)
    glmObj <- glm(form, data = infert, family = binomial())
    glmCoerce <- as.glm(rxGlmObj) 
    checkEquals(coef(glmObj), coef(glmCoerce))
    
    # if pmml package is loaded, this will check to make sure they're the same  
    glmObj$coefficients <- signif(glmObj$coefficients, 6)
    glmCoerce$coefficients <- signif(glmCoerce$coefficients, 6)  
    .rxCheckPmmlOutputDif(glmObj, glmCoerce)	    
}    

"test.as.rpart.rxDTree.factor" <- function()
{
    if ("rpart" %in% .packages())
    {
        #infert.rparttree <- rpart(case ~ education , data = infert,control = rpart.control(cp = 0)) 
        form        <- case ~ education
        control     <- rpart.control(cp = 0)
        
        ## build the models
        rpartObj <- rpart(
            formula = form, data = infert,
            control = control)
        rxObj <- rxDTree(
            formula = form, data = infert,
            control = control)
        
        coerceObj <- as.rpart(rxObj)
      
        checkEquals(rpartObj$frame, coerceObj$frame)
        checkEquals(rpartObj$where, coerceObj$where)
        checkEquals(rpartObj$terms, coerceObj$terms)
        rpartAttr <- attributes(rpartObj$terms)
        coerceAttr <- attributes(coerceObj$terms)
        checkEquals(rpartAttr$variables, coerceAttr$variables)
        checkEquals(rpartAttr$factors, coerceAttr$factors)
        checkEquals(rpartAttr$term.labels, coerceAttr$term.labels)
        checkEquals(rpartAttr$order, coerceAttr$order)
        checkEquals(rpartAttr$intercept, coerceAttr$intercept)
        checkEquals(rpartAttr$response, coerceAttr$response)
        checkEquals(rpartAttr$class, coerceAttr$class)
        checkEquals(rpartAttr$dataClasses, coerceAttr$dataClasses)       
        checkEquals(rpartObj$method, coerceObj$method)   
        checkEquals(rpartObj$parms, coerceObj$parms)   
        checkEquals(rpartObj$control, coerceObj$control) 
        checkEquals(rpartObj$splits, coerceObj$splits) 
        checkEquals(rpartObj$csplit, coerceObj$csplit) 
        checkEquals(rpartObj$variable.importance, coerceObj$variable.importance)
        checkEquals(rpartObj$ordered, coerceObj$ordered)
        
        coerceObj$frame$complexity <- signif(coerceObj$frame$complexity, 6)
        rpartObj$frame$complexity <- signif(rpartObj$frame$complexity, 6)
        coerceObj$frame$dev <- signif(coerceObj$frame$dev, 6)
        rpartObj$frame$dev <- signif(rpartObj$frame$dev, 6)

        # if pmml package is loaded, this will check for differences 
        .rxCheckPmmlOutputDif(rpartObj, coerceObj)	
    }
}


"test.as.rpart.rxDTree" <- function()
{
    if ("rpart" %in% .packages())
    {
        method      <- "class"
        form        <- Kyphosis ~ Number + Start
        parms       <- list(prior = c(0.8, 0.2), loss = c(0, 2, 3, 0), split = "gini")
        control     <- rpart.control(
                        minsplit = 5, minbucket = 2, cp = 0.01, maxdepth = 10, maxcompete = 4,
                        maxsurrogate = 5, usesurrogate = 2, surrogatestyle = 0, xval = 0)
        cost        <- 1 + seq(length(attr(terms(form), "term.labels")))
        
        ## build the models
        rpartObj <- rpart(
            formula = form, data = kyphosis,
            method = method, parms = parms, control = control, cost = cost)
        rxObj <- rxDTree(
            formula = form, data = kyphosis,
            method = method, parms = parms, control = control, cost = cost)
        
        coerceObj <- as.rpart(rxObj)
        
        checkEquals(rpartObj$frame, coerceObj$frame)
        checkEquals(rpartObj$where, coerceObj$where)
        checkEquals(rpartObj$terms, coerceObj$terms)
        rpartAttr <- attributes(rpartObj$terms)
        coerceAttr <- attributes(coerceObj$terms)
        checkEquals(rpartAttr$variables, coerceAttr$variables)
        checkEquals(rpartAttr$factors, coerceAttr$factors)
        checkEquals(rpartAttr$term.labels, coerceAttr$term.labels)
        checkEquals(rpartAttr$order, coerceAttr$order)
        checkEquals(rpartAttr$intercept, coerceAttr$intercept)
        checkEquals(rpartAttr$response, coerceAttr$response)
        checkEquals(rpartAttr$class, coerceAttr$class)
        checkEquals(rpartAttr$dataClasses, coerceAttr$dataClasses)       
        checkEquals(rpartObj$cptable, coerceObj$cptable)
        checkEquals(rpartObj$method, coerceObj$method)   
        checkEquals(rpartObj$parms, coerceObj$parms)   
        checkEquals(rpartObj$control, coerceObj$control) 
        checkEquals(rpartObj$splits, coerceObj$splits) 
        checkEquals(rpartObj$variable.importance, coerceObj$variable.importance)
        checkEquals(rpartObj$ordered, coerceObj$ordered)
        
        coerceObj$frame$complexity <- signif(coerceObj$frame$complexity, 6)
        rpartObj$frame$complexity <- signif(rpartObj$frame$complexity, 6)
        coerceObj$frame$dev <- signif(coerceObj$frame$dev, 6)
        rpartObj$frame$dev <- signif(rpartObj$frame$dev, 6)
        coerceObj$frame$yval2 <- signif(coerceObj$frame$yval2 , 6) 
        rpartObj$frame$yval2  <- signif(rpartObj$frame$yval2 , 6)

        # if pmml package is loaded, this will check for differences 
        .rxCheckPmmlOutputDif(rpartObj, coerceObj)	
        
        # Try for xdf file        
        xdfFile <- tempfile(pattern = ".rxCoerce3", fileext = ".xdf")
        if (file.exists(xdfFile)) file.remove(xdfFile)
        rxDataStep(inData = kyphosis, outFile = xdfFile)
        rxObj <- rxDTree(
            formula = Kyphosis ~ Number + Start, data = xdfFile, 
            method = method, parms = parms, control = control, cost = cost)
        
        coerceObj <- as.rpart(rxObj)
        
        coerceObj$frame$complexity <- signif(coerceObj$frame$complexity, 6)
        rpartObj$frame$complexity <- signif(rpartObj$frame$complexity, 6)
        coerceObj$frame$dev <- signif(coerceObj$frame$dev, 6)
        rpartObj$frame$dev <- signif(rpartObj$frame$dev, 6)
        coerceObj$frame$yval2 <- signif(coerceObj$frame$yval2 , 6) 
        rpartObj$frame$yval2  <- signif(rpartObj$frame$yval2 , 6)
                
       # if pmml package is loaded, this will check for differences 
        .rxCheckPmmlOutputDif(rpartObj, coerceObj)    
        file.remove(xdfFile)  		
    }
       
}

"test.as.kmeans.rxKmeans" <- function()
{
	form <- ~ height + weight
    set.seed(17)
	irow <- unique(sample.int(nrow(women), 4L, replace = TRUE))[seq(2)]
	centers <- women[irow,, drop = FALSE]
	rxKmeansObj <- rxKmeans(form, data = women, centers = centers)
    coerceObj <- as.kmeans(rxKmeansObj)
    kmeansObj <- stats::kmeans(as.matrix(women), centers = as.matrix(centers),
        iter.max = 10, algorithm = "Lloyd", nstart = 1)
    
    checkEquals(coerceObj$cluster, kmeansObj$cluster) # Only with data frames
    checkEquals(coerceObj$centers, kmeansObj$centers) # Only with data frames
    checkEquals(coerceObj$totss, kmeansObj$totss) 
    checkEquals(coerceObj$withinss, kmeansObj$withinss) 
    checkEquals(coerceObj$tot.withinss, kmeansObj$tot.withinss)   
    checkEquals(coerceObj$betweenss, kmeansObj$betweenss) 
    checkEquals(coerceObj$size, kmeansObj$size) 

    # if pmml package is loaded, this will check for differences 
    .rxCheckPmmlOutputDif(kmeansObj, coerceObj)
    
}

"test.as.randomForest.regression" <- function()
{
    #require(RevoScaleR)
	#source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))    
    
    suppressWarnings(randomForest.installed <- require(randomForest, quietly = TRUE))
	if (!randomForest.installed)
	{
        DEACTIVATED("This optional test requires the third-party package 'randomForest', which is not installed on this system. To activate the test, run install.packages('randomForest') and then re-run the test.")
        #install.packages("randomForest")
	}

    ## setup
    set.seed(71)    # should be irrelevant as we de-randomize randomForest below
    mydata <- iris
    mydata$var0 <- rep(1, nrow(mydata)) # introduce a xvar with 0 variance
    
    vars <- colnames(mydata)
    yvar <- "Petal.Length"
    xvars <- setdiff(vars, yvar)
    nxvars <- length(xvars)
    form <- formula(paste(yvar, paste(xvars, collapse = " + "), sep = " ~ "))

    ## introduce missings
    ## For randomforest: the prediction will be NA if any splitting variable is NA.
    ## For rpart/rxDTree/rxDForest: the prediction won't be NA if any splitting variable is NA
    ##  as surrogate splits and/or majority rule will be used.
    mydata.missing <- mydata    
    mydata.missing$Sepal.Length[1]    <- NA
    mydata.missing$Sepal.Width[3]     <- NA
    mydata.missing$Petal.Width[5]     <- NA
    mydata.missing$Petal.Length[7]    <- NA
     
    ###############################
    ## randomForest
    mydata.rf <- randomForest(form, data = mydata, 
        ntree = 2, importance = FALSE, proximity = FALSE,
        nodesize = 1, maxnodes = 8, 
        mtry = nxvars, replace = FALSE, sampsize = nrow(mydata)    # de-randomize
	    )
    mydata.rf.pred <- predict(mydata.rf, newdata = mydata, type = "response") #c("response", "vote", "prob")
    mydata.rf.pred.missing <- predict(mydata.rf, newdata = mydata.missing, type = "response") #c("response", "vote", "prob")
    
    ###############################
    ## rpart
    require(rpart)
    mydata.rp <- rpart(form, data = mydata, 
	    minbucket = 1, maxdepth = 3, 
        cp = 0, xval = 0, maxcompete = 0, 
        maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0
        )
    mydata.rp.pred <- predict(mydata.rp, newdata = mydata, type = "vector") #c("vector", "prob", "class", "matrix")
    mydata.rp.pred.missing <- predict(mydata.rp, newdata = mydata.missing, type = "vector") #c("vector", "prob", "class", "matrix")

    ## compare the predictions
    diff.rf.rp <- mydata.rf.pred - mydata.rp.pred
    checkEquals(sum(diff.rf.rp^2), 0)    
    
    ## coerce and compare the predictions
    mydata.rp.rf <- as.randomForest(mydata.rp)
    mydata.rp.rf.pred <- predict(mydata.rp.rf, newdata = mydata, type = "response") #c("response", "vote", "prob")
    diff.rp.rf <- mydata.rp.rf.pred - mydata.rp.pred
    checkEquals(sum(diff.rp.rf^2), 0)
    
    ###############################
    ## rxDTree
    mydata.dt <- rxDTree(form, data = mydata,
	    minbucket = 1, maxdepth = 3,
        cp = 0, xval = 0, maxcompete = 0, 
        maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0
        )
    mydata.dt.pred <- rxPredict(mydata.dt, data = mydata, type = "vector") #c("vector", "prob", "class", "matrix")
    mydata.dt.pred.missing <- rxPredict(mydata.dt, data = mydata.missing, type = "vector") #c("vector", "prob", "class", "matrix")

    ## compare the predictions
    diff.rf.dt <- mydata.rf.pred - mydata.dt.pred
    checkEquals(sum(diff.rf.dt^2), 0)

    ## coerce and compare the predictions
    mydata.dt.rf <- as.randomForest(mydata.dt)
    mydata.dt.rf.pred <- predict(mydata.dt.rf, newdata = mydata, type = "response") #c("response", "vote", "prob")
    diff.dt.rf <- mydata.dt.rf.pred - mydata.dt.pred
    checkEquals(sum(diff.dt.rf^2), 0)
    
    ###############################
    ## rxDForest
    mydata.df <- rxDForest(form, data = mydata,
        nTree = 2, #importance = TRUE,
	    minbucket = 1, maxdepth = 3,
        cp = 0, xval = 0, maxcompete = 0, 
        maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0,
        mTry = 0, replace = FALSE, sampRate = 0    # de-randomize
        )
    mydata.df.pred <- rxPredict(mydata.df, data = mydata, type = "response")[["Petal.Length_Pred"]] #c("vector", "prob", "class", "matrix")
    mydata.df.pred.missing <- rxPredict(mydata.df, data = mydata.missing, type = "response")[["Petal.Length_Pred"]] #c("vector", "prob", "class", "matrix")

    ## compare the predictions
    diff.rf.df <- mydata.rf.pred - mydata.df.pred
    checkEquals(sum(diff.rf.df^2), 0)

    ## coerce and compare the predictions
    mydata.df.rf <- as.randomForest(mydata.df)
    mydata.df.rf.pred <- predict(mydata.df.rf, newdata = mydata, type = "response") #c("response", "vote", "prob")
    diff.df.rf <- mydata.df.rf.pred - mydata.df.pred
    checkEquals(sum(diff.df.rf^2), 0)
    
    ###############################
    ## rxDForest with scheduleOnce
    rxSetComputeContext("localpar")
    mydata.df.scheduleOnce <- rxDForest(form, data = mydata,
        nTree = 2, #importance = TRUE,
	    minbucket = 1, maxdepth = 3,
        cp = 0, xval = 0, maxcompete = 0, 
        maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0,
        mTry = 0, replace = FALSE, sampRate = 0,    # de-randomize
        scheduleOnce = TRUE
        )
    mydata.df.scheduleOnce.pred <- rxPredict(mydata.df.scheduleOnce, data = mydata, type = "response")[["Petal.Length_Pred"]] #c("vector", "prob", "class", "matrix")
    mydata.df.scheduleOnce.pred.missing <- rxPredict(mydata.df.scheduleOnce, data = mydata.missing, type = "response")[["Petal.Length_Pred"]] #c("vector", "prob", "class", "matrix")

    ## compare the predictions
    diff.rf.df <- mydata.rf.pred - mydata.df.scheduleOnce.pred
    checkEquals(sum(diff.rf.df^2), 0)

    ## coerce and compare the predictions
    mydata.df.scheduleOnce.rf <- as.randomForest(mydata.df.scheduleOnce)
    mydata.df.scheduleOnce.rf.pred <- predict(mydata.df.scheduleOnce.rf, newdata = mydata, type = "response") #c("response", "vote", "prob")
    diff.df.rf <- mydata.df.scheduleOnce.rf.pred - mydata.df.scheduleOnce.pred
    checkEquals(sum(diff.df.rf^2), 0)
    rxSetComputeContext("local")
    
    ## test pmml support
    suppressWarnings(pmml.installed <- require(pmml, quietly = TRUE))
	if (pmml.installed)
	{
		pmml.rf <- try(pmml(mydata.rf))
        pmml.rp.rf <- try(pmml(mydata.rp.rf))
        pmml.dt.rf <- try(pmml(mydata.dt.rf))
        pmml.df.rf <- try(pmml(mydata.df.rf))
        pmml.df.scheduleOnce.rf <- try(pmml(mydata.df.scheduleOnce.rf))
	}
}

"test.as.randomForest.classification" <- function()
{
    #require(RevoScaleR)
	#source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
    
    suppressWarnings(randomForest.installed <- require(randomForest, quietly = TRUE))
	if (!randomForest.installed)
	{
        DEACTIVATED("This optional test requires the third-party package 'randomForest', which is not installed on this system. To activate the test, run install.packages('randomForest') and then re-run the test.")
        #install.packages("randomForest")
	}

    ## setup
    set.seed(71)    # should be irrelevant as we de-randomize randomForest below
    mydata <- iris
    mydata$var0 <- rep(1, nrow(mydata)) # introduce a xvar with 0 variance
    
    vars <- colnames(mydata)
    yvar <- "Species"
    xvars <- setdiff(vars, yvar)
    nxvars <- length(xvars)
    form <- formula(paste(yvar, paste(xvars, collapse = " + "), sep = " ~ "))
    
    ###############################
    ## randomForest
    mydata.rf <- randomForest(form, data = mydata, 
        ntree = 2, importance = FALSE, proximity = FALSE,
        nodesize = 1, maxnodes = 8, 
        mtry = nxvars, replace = FALSE, sampsize = nrow(mydata)    # de-randomize
	    )
    mydata.rf.pred <- predict(mydata.rf, newdata = mydata, type = "response") #c("response", "vote", "prob")
    
    ###############################
    ## rpart
    require(rpart)
    mydata.rp <- rpart(form, data = mydata, 
	    minbucket = 1, maxdepth = 4, 
        cp = 0, xval = 0, maxcompete = 0, 
        maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0
        )
    mydata.rp.pred <- predict(mydata.rp, newdata = mydata, type = "class") #c("vector", "prob", "class", "matrix")
    
    ## compare the predictions
    confusion.rf.rp <- table(mydata.rf.pred, mydata.rp.pred)
    checkEquals(sum(diag(confusion.rf.rp)), nrow(mydata))    
    
    ## coerce and compare the predictions
    mydata.rp.rf <- as.randomForest(mydata.rp)
    mydata.rp.rf.pred <- predict(mydata.rp.rf, newdata = mydata, type = "response") #c("response", "vote", "prob")
    confusion.rp.rf <- table(mydata.rp.rf.pred, mydata.rp.pred)
    checkEquals(sum(diag(confusion.rp.rf)), nrow(mydata))
    
    ###############################
    ## rxDTree
    mydata.dt <- rxDTree(form, data = mydata, 
	    minbucket = 1, maxdepth = 4, 
        cp = 0, xval = 0, maxcompete = 0, 
        maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0
        )
    mydata.dt.pred <- rxPredict(mydata.dt, data = mydata, type = "class")[["Species_Pred"]] #c("vector", "prob", "class", "matrix")

    ## compare the predictions
    confusion.rf.dt <- table(mydata.rf.pred, mydata.dt.pred)
    checkEquals(sum(diag(confusion.rf.dt)), nrow(mydata))

    ## coerce and compare the predictions
    mydata.dt.rf <- as.randomForest(mydata.dt)
    mydata.dt.rf.pred <- predict(mydata.dt.rf, newdata = mydata, type = "response") #c("response", "vote", "prob")
    confusion.dt.rf <- table(mydata.dt.rf.pred, mydata.dt.pred)
    
    ## get more info for the intermittent failure
    print(mydata.dt)
    print(getTree(mydata.dt.rf))
    print(cbind(mydata.dt.rf.pred, mydata.dt.pred))
    print(which(mydata.dt.rf.pred != mydata.dt.pred))
    print(confusion.dt.rf)
    
    checkEquals(sum(diag(confusion.dt.rf)), nrow(mydata))

    ###############################
    ## rxDForest
    mydata.df <- rxDForest(form, data = mydata, 
        nTree = 2, #importance = TRUE,
	    minbucket = 1, maxdepth = 4, 
        cp = 0, xval = 0, maxcompete = 0, 
        maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0,
        mTry = 0, replace = FALSE, sampRate = 0    # de-randomize
        )
    mydata.df.pred <- rxPredict(mydata.df, data = mydata, type = "class")[["Species_Pred"]] #c("vector", "prob", "class", "matrix")

    ## compare the predictions
    confusion.rf.df <- table(mydata.rf.pred, mydata.df.pred)
    checkEquals(sum(diag(confusion.rf.df)), nrow(mydata))

    ## coerce and compare the predictions
    mydata.df.rf <- as.randomForest(mydata.df)
    mydata.df.rf.pred <- predict(mydata.df.rf, newdata = mydata, type = "response") #c("response", "vote", "prob")
    confusion.df.rf <- table(mydata.df.rf.pred, mydata.df.pred)
    checkEquals(sum(diag(confusion.df.rf)), nrow(mydata))
    
    ###############################
    ## rxDForest with scheduleOnce
    rxSetComputeContext("localpar")
    mydata.df.scheduleOnce <- rxDForest(form, data = mydata, 
        nTree = 2, #importance = TRUE,
	    minbucket = 1, maxdepth = 4, 
        cp = 0, xval = 0, maxcompete = 0, 
        maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0,
        mTry = 0, replace = FALSE, sampRate = 0,    # de-randomize
        scheduleOnce = TRUE
        )
    mydata.df.scheduleOnce.pred <- rxPredict(mydata.df.scheduleOnce, data = mydata, type = "class")[["Species_Pred"]] #c("vector", "prob", "class", "matrix")

    ## compare the predictions
    confusion.rf.df <- table(mydata.rf.pred, mydata.df.scheduleOnce.pred)
    checkEquals(sum(diag(confusion.rf.df)), nrow(mydata))

    ## coerce and compare the predictions
    mydata.df.scheduleOnce.rf <- as.randomForest(mydata.df.scheduleOnce)
    mydata.df.scheduleOnce.rf.pred <- predict(mydata.df.scheduleOnce.rf, newdata = mydata, type = "response") #c("response", "vote", "prob")
    confusion.df.rf <- table(mydata.df.scheduleOnce.rf.pred, mydata.df.scheduleOnce.pred)
    checkEquals(sum(diag(confusion.df.rf)), nrow(mydata))
    rxSetComputeContext("local")
    
    ## test pmml support
    suppressWarnings(pmml.installed <- require(pmml, quietly = TRUE))
	if (pmml.installed)
	{
		pmml.rf <- try(pmml(mydata.rf))
        pmml.rp.rf <- try(pmml(mydata.rp.rf))
        pmml.dt.rf <- try(pmml(mydata.dt.rf))
        pmml.df.rf <- try(pmml(mydata.df.rf))
        pmml.df.scheduleOnce.rf <- try(pmml(mydata.df.scheduleOnce.rf))
	}
}


"test.as.gbm.gaussian" <- function()
{
    #require(RevoScaleR)
	#source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))    
    
    suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE))
	if (!gbm.installed)
	{
        DEACTIVATED("This optional test requires the third-party package 'gbm', which is not installed on this system. To activate the test, run install.packages('gbm') and then re-run the test.")
        #install.packages("gbm")
	}

    ## setup
    mydata <- iris
    mydata$var0 <- rep(1, nrow(mydata)) # introduce a xvar with 0 variance
    
    vars <- colnames(mydata)
    yvar <- "Petal.Length"
    xvars <- setdiff(vars, yvar)
    nxvars <- length(xvars)
    form <- formula(paste(yvar, paste(xvars, collapse = " + "), sep = " ~ "))

    #form <- Petal.Length ~ Sepal.Length + Sepal.Width + Species + Petal.Width   #one factor predictor
    #form <- Petal.Length ~ Sepal.Length + Sepal.Width + Petal.Width            # no factor predictor

    distribution <- "gaussian"
    shrinkage <- 0.1    #1.0    #
    
    ntree <- 2      #1  #  
    maxdepth <- 2   #3  #
    minbucket <- 1
    
    seed <- 0   # should be irrelevant as we de-randomize gbm below
    bag.fraction <- 1.0 # de-randomize
    train.fraction <- 1.0
    
    ## introduce missings
    ## For gbm: the splitting process will be NA if the current splitting variable is missing.
    ## For rpart/rxDTree/rxBTrees: the prediction won't be NA if the current splitting variable is missing
    ##  as surrogate splits and/or majority rule will be used.
    mydata.missing <- mydata    
    mydata.missing$Sepal.Length[1]  <- NA
    mydata.missing$Sepal.Width[3]   <- NA
    mydata.missing$Species[5]       <- NA
    mydata.missing$Petal.Width[7]   <- NA

    ###############################
    ## gbm
    set.seed(seed)
    fit.gbm <- gbm(form, data = mydata, distribution = distribution, shrinkage = shrinkage, 
        n.trees = ntree, interaction.depth = maxdepth, n.minobsinnode = minbucket,
        bag.fraction = bag.fraction, train.fraction = train.fraction
	    )
    fit.gbm.pred <- predict(fit.gbm, newdata = mydata, n.trees = ntree, type = "response") #c("response", "link")
    fit.gbm.pred.missing <- predict(fit.gbm, newdata = mydata.missing, n.trees = ntree, type = "response") #c("response", "link")
    
    ###############################
    ## rpart
    require(rpart)
    set.seed(seed)
    fit.rp <- rpart(form, data = mydata, minbucket = minbucket, maxdepth = maxdepth, 
        cp = 0, xval = 0, maxcompete = 0, maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0
        )
    fit.rp.pred <- predict(fit.rp, newdata = mydata, type = "vector") #c("vector", "prob", "class", "matrix")
    fit.rp.pred.missing <- predict(fit.rp, newdata = mydata.missing, type = "vector") #c("vector", "prob", "class", "matrix")

    ## compare the predictions: the model might be different thus the predictions too.
    #checkEquals(fit.gbm.pred, fit.rp.pred, check.attributes = FALSE)    
    #checkEquals(fit.gbm.pred.missing, fit.rp.pred.missing, check.attributes = FALSE)    

    ## coerce and compare the predictions
    fit.rp.gbm <- as.gbm(fit.rp)
    fit.rp.gbm.pred <- predict(fit.rp.gbm, newdata = mydata, n.trees = 1, type = "response") #c("response", "link")
    fit.rp.gbm.pred.missing <- predict(fit.rp.gbm, newdata = mydata.missing, n.trees = 1, type = "response") #c("response", "link")
    
    checkEquals(fit.rp.gbm.pred, fit.rp.pred, check.attributes = FALSE)
    checkEquals(fit.rp.gbm.pred.missing, fit.rp.pred.missing, check.attributes = FALSE) 

    ###############################
    ## rxDTree
    fit.dt <- rxDTree(form, data = mydata, minbucket = minbucket, maxdepth = maxdepth,
        cp = 0, xval = 0, maxcompete = 0, maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0
        )
    fit.dt.pred <- rxPredict(fit.dt, data = mydata, type = "vector") #c("vector", "prob", "class", "matrix")
    fit.dt.pred.missing <- rxPredict(fit.dt, data = mydata.missing, type = "vector") #c("vector", "prob", "class", "matrix")

    ## compare the predictions
    #checkEquals(fit.gbm.pred, fit.dt.pred, check.attributes = FALSE)
    #checkEquals(fit.gbm.pred.missing, fit.dt.pred.missing, check.attributes = FALSE)

    ## coerce and compare the predictions
    fit.dt.gbm <- as.gbm(fit.dt)
    fit.dt.gbm.pred <- predict(fit.dt.gbm, newdata = mydata, n.trees = 1, type = "response") #c("response", "link")
    fit.dt.gbm.pred.missing <- predict(fit.dt.gbm, newdata = mydata.missing, n.trees = 1, type = "response") #c("response", "link")
    
    checkEquals(fit.dt.gbm.pred, fit.dt.pred[[1]], check.attributes = FALSE)
    checkEquals(fit.dt.gbm.pred.missing, fit.dt.pred.missing[[1]], check.attributes = FALSE)
    
    ###############################
    ## rxBTrees
    fit.bt <- rxBTrees(form, data = mydata, lossFunction = distribution, learningRate = shrinkage,
        nTree = ntree, minbucket = minbucket, maxdepth = maxdepth,
        cp = 0, xval = 0, maxcompete = 0, maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0,
        mTry = 0, replace = FALSE, sampRate = bag.fraction  #0    # de-randomize
        )
    fit.bt.pred <- rxPredict(fit.bt, data = mydata, type = "response")[["Petal.Length_Pred"]] #c("vector", "prob", "class", "matrix")
    fit.bt.pred.missing <- rxPredict(fit.bt, data = mydata.missing, type = "response")[["Petal.Length_Pred"]] #c("vector", "prob", "class", "matrix")

    ## compare the predictions
    #checkEquals(fit.gbm.pred, fit.bt.pred, check.attributes = FALSE)
    #checkEquals(fit.gbm.pred.missing, fit.bt.pred.missing, check.attributes = FALSE)

    ## coerce and compare the predictions
    fit.bt.gbm <- as.gbm(fit.bt)
    fit.bt.gbm.pred <- predict(fit.bt.gbm, newdata = mydata, n.trees = ntree, type = "response") #c("response", "link")
    fit.bt.gbm.pred.missing <- predict(fit.bt.gbm, newdata = mydata.missing, n.trees = ntree, type = "response") #c("response", "vote", "prob")
     
    checkEquals(fit.bt.gbm.pred, fit.bt.pred, check.attributes = FALSE)
    checkEquals(fit.bt.gbm.pred.missing, fit.bt.pred.missing, check.attributes = FALSE)
    
    ###############################
    ## rxBTrees with scheduleOnce
    rxSetComputeContext("localpar")
    fit.bt.scheduleOnce <- rxBTrees(form, data = mydata, lossFunction = distribution, learningRate = shrinkage,
        nTree = ntree, minbucket = minbucket, maxdepth = maxdepth,
        cp = 0, xval = 0, maxcompete = 0, maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0,
        mTry = 0, replace = FALSE, sampRate = bag.fraction,  #0    # de-randomize
        scheduleOnce = TRUE
        )
    fit.bt.scheduleOnce.pred <- rxPredict(fit.bt.scheduleOnce, data = mydata, type = "response")[["Petal.Length_Pred"]] #c("vector", "prob", "class", "matrix")
    fit.bt.scheduleOnce.pred.missing <- rxPredict(fit.bt.scheduleOnce, data = mydata.missing, type = "response")[["Petal.Length_Pred"]] #c("vector", "prob", "class", "matrix")

    ## compare the predictions
    #checkEquals(fit.gbm.pred, fit.bt.scheduleOnce.pred, check.attributes = FALSE)
    #checkEquals(fit.gbm.pred.missing, fit.bt.scheduleOnce.pred.missing, check.attributes = FALSE)

    ## coerce and compare the predictions
    fit.bt.scheduleOnce.gbm <- as.gbm(fit.bt.scheduleOnce)
    fit.bt.scheduleOnce.gbm.pred <- predict(fit.bt.scheduleOnce.gbm, newdata = mydata, n.trees = fit.bt.scheduleOnce$ntree, type = "response") #c("response", "link")
    fit.bt.scheduleOnce.gbm.pred.missing <- predict(fit.bt.scheduleOnce.gbm, newdata = mydata.missing, n.trees = fit.bt.scheduleOnce$ntree, type = "response") #c("response", "vote", "prob")
     
    checkEquals(fit.bt.scheduleOnce.gbm.pred, fit.bt.scheduleOnce.pred, check.attributes = FALSE)
    checkEquals(fit.bt.scheduleOnce.gbm.pred.missing, fit.bt.scheduleOnce.pred.missing, check.attributes = FALSE)
    rxSetComputeContext("local")

    ## test pmml support
    ## NOTE: Zementis seem not support gbm model in their OSR pmml package
    ##  but they do in a proprietary package according to their management.
    #suppressWarnings(pmml.installed <- require(pmml, quietly = TRUE))
	#if (pmml.installed)
	#{
		#pmml.gbm <- try(pmml(fit.gbm))
        #pmml.rp.gbm <- try(pmml(fit.rp.gbm))
        #pmml.dt.gbm <- try(pmml(fit.dt.gbm))
        #pmml.bt.gbm <- try(pmml(fit.bt.gbm))
        #pmml.bt.scheduleOnce.gbm <- try(pmml(fit.bt.scheduleOnce.gbm))
	#}
}

"test.as.gbm.bernoulli" <- function()
{
    #require(RevoScaleR)
	#source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
    
    suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE))
	if (!gbm.installed)
	{
        DEACTIVATED("This optional test requires the third-party package 'gbm', which is not installed on this system. To activate the test, run install.packages('gbm') and then re-run the test.")
        #install.packages("gbm")
	}

    ## setup
    mydata <- kyphosis
    mydata$Kyphosis <- as.numeric(mydata$Kyphosis) - 1	# 0/1 response
    mydata$var0 <- rep(1, nrow(mydata)) # introduce a xvar with 0 variance
    
    vars <- colnames(mydata)
    yvar <- "Kyphosis"
    xvars <- setdiff(vars, yvar)
    nxvars <- length(xvars)
    form <- formula(paste(yvar, paste(xvars, collapse = " + "), sep = " ~ "))

    distribution <- "bernoulli"
    shrinkage <- 0.1    #1.0    #
    
    ntree <- 2  #1  #
    maxdepth <- 2   #3  #
    minbucket <- 1
    
    seed <- 0   # should be irrelevant as we de-randomize gbm below
    bag.fraction <- 1.0 # de-randomize
    train.fraction <- 1.0
    
    ## introduce missings
    ## For gbm: the prediction will be NA if any splitting variable is NA.
    ## For rpart/rxDTree/rxDForest: the prediction won't be NA if any splitting variable is NA
    ##  as surrogate splits and/or majority rule will be used.
    mydata.missing <- mydata    
    mydata.missing$Age[1]       <- NA
    mydata.missing$Number[3]    <- NA
    mydata.missing$Start[3]     <- NA
    mydata.missing$Start[5]     <- NA
    
    ###############################
    ## gbm
    set.seed(seed)
    fit.gbm <- gbm(form, data = mydata, distribution = distribution, shrinkage = shrinkage, 
        n.trees = ntree, interaction.depth = maxdepth, n.minobsinnode = minbucket,
        bag.fraction = bag.fraction, train.fraction = train.fraction
	    )
    fit.gbm.pred <- predict(fit.gbm, newdata = mydata, n.trees = ntree, type = "response") #c("response", "link")
    fit.gbm.pred.missing <- predict(fit.gbm, newdata = mydata.missing, n.trees = ntree, type = "response") #c("response", "link")

    ################################
    ## rxBTrees
    fit.bt <- rxBTrees(form, data = mydata, lossFunction = distribution, learningRate = shrinkage, 
        nTree = ntree, minbucket = minbucket, maxdepth = maxdepth, 
        cp = 0, xval = 0, maxcompete = 0, maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0,
        mTry = 0, replace = FALSE, sampRate = bag.fraction  # de-randomize
        )
    fit.bt.pred <- rxPredict(fit.bt, data = mydata, type = "response") #c("response", "link")
    fit.bt.pred.missing <- rxPredict(fit.bt, data = mydata.missing, type = "response") #c("response", "link")

    ## compare the predictions
    #checkEquals(fit.gbm.pred, fit.bt.pred, check.attributes = FALSE)
    #checkEquals(fit.gbm.pred.missing, fit.bt.pred.missing, check.attributes = FALSE)
    
    ## coerce and compare the predictions
    fit.bt.gbm <- as.gbm(fit.bt)
    fit.bt.gbm.pred <- predict(fit.bt.gbm, newdata = mydata, n.trees = ntree, type = "response") #c("response", "link")
    fit.bt.gbm.pred.missing <- predict(fit.bt.gbm, newdata = mydata.missing, n.trees = ntree, type = "response") #c("response", "vote", "prob")
    
    checkEquals(fit.bt.gbm.pred, fit.bt.pred[[1]])
    checkEquals(fit.bt.gbm.pred.missing, fit.bt.pred.missing[[1]])

    ################################
    ## rxBTrees with scheduleOnce
    rxSetComputeContext("localpar")
    fit.bt.scheduleOnce <- rxBTrees(form, data = mydata, lossFunction = distribution, learningRate = shrinkage, 
        nTree = ntree, minbucket = minbucket, maxdepth = maxdepth, 
        cp = 0, xval = 0, maxcompete = 0, maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0,
        mTry = 0, replace = FALSE, sampRate = bag.fraction,  # de-randomize
        scheduleOnce = TRUE
        )
    fit.bt.scheduleOnce.pred <- rxPredict(fit.bt.scheduleOnce, data = mydata, type = "response") #c("response", "link")
    fit.bt.scheduleOnce.pred.missing <- rxPredict(fit.bt.scheduleOnce, data = mydata.missing, type = "response") #c("response", "link")

    ## compare the predictions
    #checkEquals(fit.gbm.pred, fit.bt.scheduleOnce.pred, check.attributes = FALSE)
    #checkEquals(fit.gbm.pred.missing, fit.bt.scheduleOnce.pred.missing, check.attributes = FALSE)
    
    ## coerce and compare the predictions
    fit.bt.scheduleOnce.gbm <- as.gbm(fit.bt.scheduleOnce)
    fit.bt.scheduleOnce.gbm.pred <- predict(fit.bt.scheduleOnce.gbm, newdata = mydata, n.trees = fit.bt.scheduleOnce$ntree, type = "response") #c("response", "link")
    fit.bt.scheduleOnce.gbm.pred.missing <- predict(fit.bt.scheduleOnce.gbm, newdata = mydata.missing, n.trees = fit.bt.scheduleOnce$ntree, type = "response") #c("response", "vote", "prob")
    
    checkEquals(fit.bt.scheduleOnce.gbm.pred, fit.bt.scheduleOnce.pred[[1]])
    checkEquals(fit.bt.scheduleOnce.gbm.pred.missing, fit.bt.scheduleOnce.pred.missing[[1]])
    rxSetComputeContext("local")
    
    ## test pmml support
    ## NOTE: Zementis seem not support gbm model in their OSR pmml package
    ##  but they do in a proprietary package according to their management.
    #suppressWarnings(pmml.installed <- require(pmml, quietly = TRUE))
	#if (pmml.installed)
	#{
		#pmml.gbm <- try(pmml(fit.gbm))
        ##pmml.rp.gbm <- try(pmml(fit.rp.gbm))
        ##pmml.dt.gbm <- try(pmml(fit.dt.gbm))
        #pmml.bt.gbm <- try(pmml(fit.bt.gbm))
        #pmml.bt.scheduleOnce.gbm <- try(pmml(fit.bt.scheduleOnce.gbm))
	#}
}

"test.as.gbm.multinomial" <- function()
{
    #require(RevoScaleR)
	#source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
    
    suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE))
	if (!gbm.installed)
	{
        DEACTIVATED("This optional test requires the third-party package 'gbm', which is not installed on this system. To activate the test, run install.packages('gbm') and then re-run the test.")
        #install.packages("gbm")
	}

    ## setup
    mydata <- iris
    mydata$var0 <- rep(1, nrow(mydata)) # introduce a xvar with 0 variance
    
    vars <- colnames(mydata)
    yvar <- "Species"
    xvars <- setdiff(vars, yvar)
    nxvars <- length(xvars)
    form <- formula(paste(yvar, paste(xvars, collapse = " + "), sep = " ~ "))

    distribution <- "multinomial"
    shrinkage <- 0.1    #1.0    #
    
    ntree <- 2  #1  #
    maxdepth <- 2   #3  #
    minbucket <- 1
    
    seed <- 0   # should be irrelevant as we de-randomize gbm below
    bag.fraction <- 1.0 # de-randomize
    train.fraction <- 1.0
    
    ## introduce missings
    ## For gbm: the prediction will be NA if any splitting variable is NA.
    ## For rpart/rxDTree/rxDForest: the prediction won't be NA if any splitting variable is NA
    ##  as surrogate splits and/or majority rule will be used.
    mydata.missing <- mydata    
    mydata.missing$Sepal.Length[1]  <- NA
    mydata.missing$Sepal.Width[3]   <- NA
    mydata.missing$Petal.Length[5]  <- NA
    mydata.missing$Petal.Width[7]   <- NA
    
    ###############################
    ## gbm
    set.seed(seed)
    fit.gbm <- gbm(form, data = mydata, distribution = distribution, shrinkage = shrinkage, 
        n.trees = ntree, interaction.depth = maxdepth, n.minobsinnode = minbucket,
        bag.fraction = bag.fraction, train.fraction = train.fraction
	    )
    fit.gbm.pred <- predict(fit.gbm, newdata = mydata, n.trees = ntree, type = "response") #c("response", "link")
    fit.gbm.pred.missing <- predict(fit.gbm, newdata = mydata.missing, n.trees = ntree, type = "response") #c("response", "link")

    ################################
    ## rxBTrees
    fit.bt <- rxBTrees(form, data = mydata, lossFunction = distribution, learningRate = shrinkage, 
        nTree = ntree, minbucket = minbucket, maxdepth = maxdepth, 
        cp = 0, xval = 0, maxcompete = 0, maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0,
        mTry = 0, replace = FALSE, sampRate = bag.fraction  # de-randomize
        )
    fit.bt.pred <- rxPredict(fit.bt, data = mydata, type = "response") #c("response", "link")
    fit.bt.pred.missing <- rxPredict(fit.bt, data = mydata.missing, type = "response") #c("response", "link")

    ## compare the predictions
    ylevels <- attr(fit.bt$forest[[1]], "ylevels")
    pred.names <- paste(ylevels, "prob", sep = "_")
    #checkEquals(drop(fit.gbm.pred)[, ylevels], as.matrix(fit.bt.pred[, pred.names]), check.attributes = FALSE)
    #checkEquals(drop(fit.gbm.pred.missing)[, ylevels], as.matrix(fit.bt.pred.missing[, pred.names]), check.attributes = FALSE)

    ## coerce and compare the predictions
    fit.bt.gbm <- as.gbm(fit.bt)
    fit.bt.gbm.pred <- predict(fit.bt.gbm, newdata = mydata, n.trees = ntree, type = "response") #c("response", "vote", "prob")
    fit.bt.gbm.pred.missing <- predict(fit.bt.gbm, newdata = mydata.missing, n.trees = ntree, type = "response") #c("response", "vote", "prob")
    
    checkEquals(drop(fit.bt.gbm.pred)[, ylevels], as.matrix(fit.bt.pred[, pred.names]), check.attributes = FALSE)
    checkEquals(drop(fit.bt.gbm.pred.missing)[, ylevels], as.matrix(fit.bt.pred.missing[, pred.names]), check.attributes = FALSE)

    ################################
    ## rxBTrees with scheduleOnce
    rxSetComputeContext("localpar")
    fit.bt.scheduleOnce <- rxBTrees(form, data = mydata, lossFunction = distribution, learningRate = shrinkage, 
        nTree = ntree, minbucket = minbucket, maxdepth = maxdepth, 
        cp = 0, xval = 0, maxcompete = 0, maxsurrogate = 0, usesurrogate = 2, surrogatestyle = 0,
        mTry = 0, replace = FALSE, sampRate = bag.fraction,  # de-randomize
        scheduleOnce = TRUE
        )
    fit.bt.scheduleOnce.pred <- rxPredict(fit.bt.scheduleOnce, data = mydata, type = "response") #c("response", "link")
    fit.bt.scheduleOnce.pred.missing <- rxPredict(fit.bt.scheduleOnce, data = mydata.missing, type = "response") #c("response", "link")

    ## compare the predictions
    ylevels <- attr(fit.bt.scheduleOnce$forest[[1]], "ylevels")
    pred.names <- paste(ylevels, "prob", sep = "_")
    #checkEquals(drop(fit.gbm.pred)[, ylevels], as.matrix(fit.bt.scheduleOnce.pred[, pred.names]), check.attributes = FALSE)
    #checkEquals(drop(fit.gbm.pred.missing)[, ylevels], as.matrix(fit.bt.scheduleOnce.pred.missing[, pred.names]), check.attributes = FALSE)

    ## coerce and compare the predictions
    fit.bt.scheduleOnce.gbm <- as.gbm(fit.bt.scheduleOnce)
    fit.bt.scheduleOnce.gbm.pred <- predict(fit.bt.scheduleOnce.gbm, newdata = mydata, n.trees = fit.bt.scheduleOnce.gbm$n.trees, type = "response") #c("response", "vote", "prob")
    fit.bt.scheduleOnce.gbm.pred.missing <- predict(fit.bt.scheduleOnce.gbm, newdata = mydata.missing, n.trees = fit.bt.scheduleOnce.gbm$n.trees, type = "response") #c("response", "vote", "prob")
    
    checkEquals(drop(fit.bt.scheduleOnce.gbm.pred)[, ylevels], as.matrix(fit.bt.scheduleOnce.pred[, pred.names]), check.attributes = FALSE)
    checkEquals(drop(fit.bt.scheduleOnce.gbm.pred.missing)[, ylevels], as.matrix(fit.bt.scheduleOnce.pred.missing[, pred.names]), check.attributes = FALSE)
    rxSetComputeContext("local")

    ## test pmml support
    ## NOTE: Zementis seem not support gbm model in their OSR pmml package
    ##  but they do in a proprietary package according to their management.
    #suppressWarnings(pmml.installed <- require(pmml, quietly = TRUE))
	#if (pmml.installed)
	#{
		#pmml.gbm <- try(pmml(fit.gbm))
        ##pmml.rp.gbm <- try(pmml(fit.rp.gbm))
        ##pmml.dt.gbm <- try(pmml(fit.dt.gbm))
        #pmml.bt.gbm <- try(pmml(fit.bt.gbm))
        #pmml.bt.scheduleOnce.gbm <- try(pmml(fit.bt.scheduleOnce.gbm))
	#}
}

"test.as.naiveBayes.rxNaiveBayes" <- function(){
    suppressWarnings(rpart.installed <- require(rpart, quietly = TRUE))
    if (!rpart.installed)
    {
        DEACTIVATED("This optional test requires the third-party package 'rpart', which is not installed on this system. To activate the test, run install.packages('rpart') and then re-run th
e test.")
    }
    
    suppressWarnings(naiveBayes.installed <- require(e1071, quietly = TRUE))
    if (!naiveBayes.installed)
    {
        DEACTIVATED("This optional test requires the third-party package 'e1071', which is not installed on this system. To activate the test, run install.packages('e1071') and then re-run the test.")
    }
    "checkNaiveBayesEquals" <- function(rxNaiveBayesObj_Coerce, naiveBayesObj){
        tabs <- naiveBayesObj$tables
        checkEquals( as.vector(rxNaiveBayesObj_Coerce$apriori), as.vector(naiveBayesObj$apriori) )
        checkEquals( as.vector(rxNaiveBayesObj_Coerce$levels), as.vector(naiveBayesObj$levels) )
        checkEquals( length(rxNaiveBayesObj_Coerce$tables), length(rxNaiveBayesObj_Coerce$tables) )
        for (i in 1:length(tabs)){
            checkEquals( as.vector(rxNaiveBayesObj_Coerce$tables[[i]]), as.vector(naiveBayesObj$tables[[i]]) )
        }
    }

    ##test case 1:
    rxBayes1 <- rxNaiveBayes(Kyphosis ~ Start + Age + Number + Start, data = kyphosis)
    e1071Bayes1 <- naiveBayes(Kyphosis ~ Start + Age + Number + Start, data = kyphosis)
    rxBayes1_Coerce <- as.naiveBayes(rxBayes1)
    checkNaiveBayesEquals(rxBayes1_Coerce, e1071Bayes1)
    checkEquals(predict(rxBayes1_Coerce,newdata=kyphosis), predict(e1071Bayes1,newdata=kyphosis))
    ##test case 2:
    rxBayes2  <- rxNaiveBayes(education ~ parity + induced + case + spontaneous + stratum, data = infert)
    e1071Bayes2 <- naiveBayes(education ~ parity + induced + case + spontaneous + stratum, data = infert)
    rxBayes2_Coerce <- as.naiveBayes(rxBayes2)
    checkNaiveBayesEquals(rxBayes2_Coerce, e1071Bayes2)
    checkEquals(predict(rxBayes2_Coerce,newdata=infert), predict(e1071Bayes2,newdata=infert))
}
