# Copyright (c) Microsoft Corporation.  All rights reserved.
#
# FUNCTIONS
#    Unit tests for rxBTrees
#
############################################################################################

.setUp <- function()
{
    .deactivate.rxBTrees.tests <<- FALSE
    #.maxRowsInMemory <<- 1e6
        
    rxOptions(reportProgress = 0) # don't report progress
	
	.n.trees <<- 2
    #.scheduleOnce <<- TRUE
	.dont.plot <<- TRUE
    
	#TODO: remove the following work-arounds for unexported rxBTrees functions.
	#if (!exists("rxBTrees")) rxBTrees <<- RevoScaleR:::rxBTrees
	#if (!exists("plot.rxBTrees")) plot.rxBTrees <<- RevoScaleR:::plot.rxBTrees
}

.tearDown <- function()
{
    .deactivate.rxBTrees.tests <<- FALSE
	if(exists(".maxRowsInMemory", where = ".GlobalEnv")) rm(".maxRowsInMemory", pos = ".GlobalEnv")

	rxOptions(TRUE)
	
	if(exists(".n.trees", where = ".GlobalEnv")) rm(".n.trees", pos = ".GlobalEnv")
	if(exists(".scheduleOnce", where = ".GlobalEnv")) rm(".scheduleOnce", pos = ".GlobalEnv")
	#if(exists(".dont.plot", where = ".GlobalEnv")) rm(".dont.plot", pos = ".GlobalEnv")
}

#######################################################################
# testing scope:
#
#	+ methods: classification (binary and multiclass) vs regression (continuous and 0/1)
#	+ randomization: randomize rows/obs vs randomize cols/vars
#		- randomize rows: no sampling, w/ and w/o replacement, stratefied sampling
#		- randomize cols: no sampling, w/o replacement (only), sampling all cols
#	+ data source: data.frame vs xdf file
#		- data.frame: single-thread vs multi-thread
#		- xdf file: single-block vs multi-block, multi-core vs multi-computer

##NOTE: the *.dataframe.xdffile.* tests are expected to fail (not error) 
##	with multiple compute nodes even though the xdf file has only one block.
##	This is because while we use only one node (the client) to process data.frame,
##	we use the server to process the xdf file. The client and server use different RNGs.

#######################################################################
## local functions

rxSplitDataFrameToXdf <- function(data, outFile, numBlocks = 1, checkAllEqual = FALSE) 
{
	if (file.exists(outFile)) unlink(outFile)
    if (rxIsExpressEdition())
    {
        numBlocks <- 1
    }
    	
	rowsTotal <- nrow(data)
	rowsMean <- rowsTotal %/% numBlocks
	rowsRemain <- rowsTotal %% numBlocks
	
	rowsPerBlocks <- rep(rowsMean, numBlocks)
	rowsPerBlocks[numBlocks] <- rowsPerBlocks[numBlocks] + rowsRemain
	rowsCumSum <- c(0, cumsum(rowsPerBlocks))
	append <- "none"
	for (i in seq(numBlocks))
	{
		rowStart <- rowsCumSum[i] + 1
		rowEnd <- rowsCumSum[i + 1]
		suppressWarnings(rxDataStep(data[rowStart:rowEnd,], outFile, append = append))
		append <- "rows"
	}

	ans <- TRUE
	if (checkAllEqual)
	{
		data2 <- rxDataStep(outFile)
		ans <- all.equal(data, data2, check.attributes = FALSE)
	}

	xdfInfo <- rxGetInfo(outFile, getVarInfo = TRUE, getBlockSizes = TRUE)
	ans && (xdfInfo$numRows == rowsTotal) && (xdfInfo$numBlocks == numBlocks) && (xdfInfo$rowsPerBlock == rowsPerBlocks)
}
	
compareBTreesResults <- function(gbm, btrees)
{
	lossFunction <- btrees$params$lossFunction
    nforest <- if (is.null(btrees$nforest)) 1 else btrees$nforest
	
	if (lossFunction == "multinomial")
	{
		checkEquals(length(gbm$trees), length(btrees$forest) / nforest)
	}
	else
	{
		checkEquals(gbm$initF, btrees$init.pred / nforest)
	}
}

#######################################################################
## regression

###################################
## continuous (gaussian: squared error)

"test.rxBTrees.regression.gaussian" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 2
	DF <- airquality[!is.na(airquality$Ozone), ]	# missing values are not allowed in the response
	XDF <- tempfile( pattern = ".airquality", fileext = ".xdf")       
	rxSplitDataFrameToXdf(DF, XDF, numBlocks = numBlocks)
    on.exit(if(file.exists(XDF)) unlink(XDF), add = TRUE)
    nobs <- nrow(DF)
    
	##################################
	## parameters
	form <- Ozone ~ Solar.R + Wind + Temp + Month + Day
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 3	#1		#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "gaussian"

	##################################
	## gbm
	if (suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE)))
	{
		set.seed(seed)
		fit.gbm <- gbm(form, data = DF, distribution = distribution,
			n.trees = n.trees, shrinkage = shrinkage, bag.fraction = bag.fraction,
			interaction.depth = interaction.depth, n.minobsinnode = n.minobsinnode)
		if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.gbm$train.error)}
        
        ## predict.gbm
        pred.gbm <- predict(fit.gbm, newdata = DF,
                n.trees = n.trees
                #type = "link"   #"response"    #same
                #single.tree = FALSE
                )
            
        ## compute deviance
        (dev.gbm <- sum((pred.gbm - DF$Ozone)^2) / nobs)
        checkEquals(fit.gbm$train.error[n.trees], dev.gbm)
	}

	##################################
	## rxBTrees
	fit.btrees.xdf <- rxBTrees(form, data = XDF, lossFunction = distribution,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.btrees.xdf)}
	
	##############
	## check results
	if (gbm.installed)
	{
		compareBTreesResults(fit.gbm, fit.btrees.xdf)
	} else {
		checkTrue(TRUE)
	}
    
	##################################
	## rxPredict.rxBTrees
    
	##############
    ## predict with data.frame
    pred.btrees.df <- rxPredict(fit.btrees.xdf, data = DF,
        #type = "link",   #"response",    #same
        )
    
    ## compute deviance
    (dev.btrees <- sum((pred.btrees.df - DF$Ozone)^2) / nobs)   # should be comparable to dev.gbm
    
	##############
    ## predict with xdf file
	outData <- tempfile( pattern = ".rxBTrees", fileext = ".xdf")
    if (file.exists(outData)) file.remove(outData)
    on.exit(if(file.exists(outData)) unlink(outData), add = TRUE)
    
    pred.btrees.xdf <- rxPredict(fit.btrees.xdf, data = XDF, outData = outData,
            #type = "link",   #"response",    #same
            )
    pred.btrees.xdf <- rxDataStep(pred.btrees.xdf)

	##############
	## check results
    checkEquals(pred.btrees.df, pred.btrees.xdf)
}

"test.rxBTrees.regression.gaussian.dataframe.xdf" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 2
	DF <- airquality[!is.na(airquality$Ozone), ]	# missing values are not allowed in the response
	XDF <- tempfile( pattern = ".airquality", fileext = ".xdf")
	rxSplitDataFrameToXdf(DF, XDF, numBlocks = numBlocks)
    on.exit(if(file.exists(XDF)) unlink(XDF), add = TRUE)

	##################################
	## parameters
	form <- Ozone ~ Solar.R + Wind + Temp + Month + Day
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 3	#1		#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "gaussian"

	###############################
	## gbm
	if (suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE)))
	{
		set.seed(seed)
		fit.gbm <- gbm(form, data = DF, distribution = distribution,
			n.trees = n.trees, shrinkage = shrinkage, bag.fraction = bag.fraction,
			interaction.depth = interaction.depth, n.minobsinnode = n.minobsinnode)
		if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.gbm$train.error)}
	}

	##################################
	## rxBTrees with XDF
	fit.btrees.xdf <- rxBTrees(form, data = XDF, lossFunction = distribution,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.btrees.xdf)}
	
	###############################
	## rxBTrees with DF
	fit.btrees.df <- rxBTrees(form, data = DF, lossFunction = distribution,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.btrees.df)}
	
	###############################
	## check results
	checkEquals(fit.btrees.xdf$oob.err, fit.btrees.df$oob.err)
	
    checkEquals(rxTreeDepth(fit.btrees.xdf),  rxTreeDepth(fit.btrees.df))
    checkEquals(rxLeafSize(fit.btrees.xdf),  rxLeafSize(fit.btrees.df))
    
	if (gbm.installed)
	{
		compareBTreesResults(fit.gbm, fit.btrees.xdf)
	} else {
		checkTrue(TRUE)
	}
}

"test.rxBTrees.regression.gaussian.useWriteDataSource" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 2
	DF <- airquality[!is.na(airquality$Ozone), ]	# missing values are not allowed in the response
	XDF <- tempfile( pattern = ".airquality", fileext = ".xdf")
	rxSplitDataFrameToXdf(DF, XDF, numBlocks = numBlocks)
    on.exit(if(file.exists(XDF)) unlink(XDF), add = TRUE)

	##################################
	## parameters
	form <- Ozone ~ Solar.R + Wind + Temp + Month + Day
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 3	#2		#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "gaussian"

	###############################
	## gbm
	if (suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE)))
	{
		set.seed(seed)
		fit.gbm <- gbm(form, data = DF, distribution = distribution,
			n.trees = n.trees, shrinkage = shrinkage, bag.fraction = bag.fraction,
			interaction.depth = interaction.depth, n.minobsinnode = n.minobsinnode)
		if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.gbm$train.error)}
	}

	##################################
	## rxBTrees with useWriteDataSource = -1
	fit.btrees.useWriteDataSourceF <- rxBTrees(form, data = XDF, lossFunction = distribution,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		useWriteDataSource = -1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.btrees.useWriteDataSourceF)}
	
	###############################
	## rxBTrees with useWriteDataSource = 1
	fit.btrees.useWriteDataSourceT <- rxBTrees(form, data = XDF, lossFunction = distribution,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.btrees.useWriteDataSourceT)}
	
	###############################
	## check results
	checkEquals(fit.btrees.useWriteDataSourceF$oob.err, fit.btrees.useWriteDataSourceT$oob.err)
	
	if (gbm.installed)
	{
		compareBTreesResults(fit.gbm, fit.btrees.useWriteDataSourceT)
	} else {
		checkTrue(TRUE)
	}
}

"test.rxBTrees.regression.gaussian.outFile" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #library(RevoScaleR)
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 2
	DF <- airquality[!is.na(airquality$Ozone), ]	# missing values are not allowed in the response
	XDF <- tempfile( pattern = ".airquality", fileext = ".xdf")       
	rxSplitDataFrameToXdf(DF, XDF, numBlocks = numBlocks)
    on.exit(if(file.exists(XDF)) unlink(XDF), add = TRUE)
    nobs <- nrow(DF)
    
	##################################
	## parameters
	form <- Ozone ~ Solar.R + Wind + Temp + Month + Day
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 3	#1		#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "gaussian"

	##################################
	## rxBTrees
	outFile <- tempfile( pattern = ".rxBTrees", fileext = ".xdf")
	if (file.exists(outFile)) file.remove(outFile)
	on.exit(if (file.exists(outFile)) file.remove(outFile), add = TRUE)
    
    ## data frame input
	fit.btrees.df <- rxBTrees(form, data = DF, lossFunction = distribution,
        outFile = outFile, overwrite = TRUE,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
    
    checkTrue(!file.exists(outFile))
    
    ## xdf input
	fit.btrees.xdf <- rxBTrees(form, data = XDF, lossFunction = distribution,
        outFile = outFile, overwrite = TRUE,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
    
	##############
	## check results  
    outFile.df <- rxDataStep(outFile)    
    
    diff.all <- (outFile.df$Predicted - DF$Ozone)
    nobs.all <- length(diff.all)
    (dev.btrees.all <- sum(diff.all^2) / nobs.all)
    
    ## On 32-bit platforms, OOBTimes (typedef unsigned int CxIndex;) is treated as a factor without levels and thus is NA.
    ## On 64-bit platforms, OOBTimes (typedef unsigned long long CxIndex;) is not treated as a factor and thus is OK.
    diff.oob <- diff.all[as.integer(outFile.df$OOBTimes) == 1]   
    nobs.oob <- length(diff.oob)
    (dev.btrees.oob <- sum(diff.oob^2) / nobs.oob)
    
    checkEquals(nobs.all, nobs)
    checkEquals(nobs.oob, fit.btrees.xdf$oob.err$num.oob[n.trees])
    checkEquals(dev.btrees.oob, fit.btrees.xdf$oob.err$oob.err[n.trees], tolerance = 1e-6)
    
	##################################
	## rxPredict.rxBTrees
    pred.btrees.df <- rxPredict(fit.btrees.xdf, data = DF,
        #type = "link",   #"response",    #same
        )
    
    ## compute deviance
    (dev.btrees <- sum((pred.btrees.df - DF$Ozone)^2) / nobs)   # should be comparable to dev.gbm

	##############
	## check results
    checkEquals(dev.btrees, dev.btrees.all)
}

###################################
## 0-1 outcomes (bernoulli: logistic regression)

"test.rxBTrees.regression.bernoulli" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 2
	DF <- kyphosis	
	DF$Kyphosis <- as.numeric(DF$Kyphosis) - 1	# 0/1 response
	XDF <- tempfile( pattern = ".kyphosis", fileext = ".xdf")
	rxSplitDataFrameToXdf(DF, XDF, numBlocks = numBlocks)
    on.exit(if(file.exists(XDF)) unlink(XDF), add = TRUE)
    nobs <- nrow(DF)
        
	##################################
	## parameters
	form <- Kyphosis ~ Age + Number + Start
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 4	#1		#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "bernoulli"

	###############################
	## gbm
	if (suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE)))
	{
		set.seed(seed)
		fit.gbm <- gbm(form, data = DF, distribution = distribution,
			n.trees = n.trees, shrinkage = shrinkage, bag.fraction = bag.fraction,
			interaction.depth = interaction.depth, n.minobsinnode = n.minobsinnode)
		if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.gbm$train.error)}
        
        ## predict and compute deviance
        pred.gbm.link <- predict(fit.gbm, newdata = DF,
                n.trees = n.trees,
                type = "link"
                #single.tree = FALSE
                )
        (dev.gbm <- -2 * sum(DF$Kyphosis * pred.gbm.link - log(1 + exp(pred.gbm.link))) / nobs)
        checkEquals(fit.gbm$train.error[n.trees], dev.gbm)

        ## predict and compute error rate
        pred.gbm.resp <- predict(fit.gbm, newdata = DF,
                n.trees = n.trees,
                type = "response"
                #single.tree = FALSE
                )
        (mis.gbm <- sum((pred.gbm.resp > 0.5) != DF$Kyphosis) / nobs)
        
        checkEquals(pred.gbm.resp, 1.0 / (1 + exp(-pred.gbm.link)))
	}

	###############################
	## rxBTrees
	fit.btrees.xdf <- rxBTrees(form, data = XDF, lossFunction = distribution,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.btrees.xdf)}
	
	###############################
	## check results
	if (gbm.installed)
	{
		compareBTreesResults(fit.gbm, fit.btrees.xdf)
	} else {
		checkTrue(TRUE)
	}
    
	###############################
	## rxPredict.rxBTrees
    
	##############
    ## predict with data.frame and compute deviance
    pred.btrees.link <- rxPredict(fit.btrees.xdf, data = DF,
        #n.trees = n.trees,   
        type = "link"
        #single.tree = FALSE
        )
    (dev.btrees <- -2 * sum(DF$Kyphosis * pred.btrees.link - log(1 + exp(pred.btrees.link))) / nobs)    # should be comparable to dev.gbm
    
	##############
    ## predict with xdf file and compute error rate
	outData <- tempfile( pattern = ".rxBTrees", fileext = ".xdf")
    if (file.exists(outData)) file.remove(outData)
    on.exit(if(file.exists(outData)) unlink(outData), add = TRUE)
    
    pred.btrees.resp <- rxPredict(fit.btrees.xdf, data = XDF, outData = outData, overwrite = TRUE,
            #n.trees = n.trees,
            type = "response"
            #single.tree = FALSE
            )
    pred.btrees.resp <- rxDataStep(pred.btrees.resp)
    (mis.btrees <- sum((pred.btrees.resp > 0.5) != DF$Kyphosis) / nobs) # should be comparable to mis.gbm

	##############
	## check pred.btrees.resp and pred.btrees.link
    checkEquals(pred.btrees.resp, 1.0 / (1 + exp(-pred.btrees.link)), check.attributes = FALSE)
}

"test.rxBTrees.regression.bernoulli.classification" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 2
	DF <- kyphosis	
	#DF$Kyphosis <- as.numeric(DF$Kyphosis) - 1	# 0/1 response
	XDF <- tempfile( pattern = ".kyphosis", fileext = ".xdf")
	rxSplitDataFrameToXdf(DF, XDF, numBlocks = numBlocks)
    on.exit(if(file.exists(XDF)) unlink(XDF), add = TRUE)
    nobs <- nrow(DF)
        
	##################################
	## parameters
	form <- Kyphosis ~ Age + Number + Start
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 4	#1		#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "bernoulli"

	###############################
	## gbm
	if (suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE)))
	{
		set.seed(seed)
		fit.gbm <- try(gbm(form, data = DF, distribution = distribution,
			n.trees = n.trees, shrinkage = shrinkage, bag.fraction = bag.fraction,
			interaction.depth = interaction.depth, n.minobsinnode = n.minobsinnode), silent = TRUE)
        checkTrue(inherits(fit.gbm, "try-error"))
        
		#if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.gbm$train.error)}
        #
        ### predict and compute deviance
        #pred.gbm.link <- predict(fit.gbm, newdata = DF,
                #n.trees = n.trees,
                #type = "link"
                ##single.tree = FALSE
                #)
        #(dev.gbm <- -2 * sum(DF$Kyphosis * pred.gbm.link - log(1 + exp(pred.gbm.link))) / nobs)
        #checkEquals(fit.gbm$train.error[n.trees], dev.gbm)
#
        ### predict and compute error rate
        #pred.gbm.resp <- predict(fit.gbm, newdata = DF,
                #n.trees = n.trees,
                #type = "response"
                ##single.tree = FALSE
                #)
        #(mis.gbm <- sum((pred.gbm.resp > 0.5) != DF$Kyphosis) / nobs)
        #
        #checkEquals(pred.gbm.resp, 1.0 / (1 + exp(-pred.gbm.link)))
	}

	###############################
	## rxBTrees
	fit.btrees.xdf <- rxBTrees(form, data = XDF, lossFunction = distribution,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.btrees.xdf)}
	
	###############################
	## check results
	#if (gbm.installed)
	#{
		#compareBTreesResults(fit.gbm, fit.btrees.xdf)
	#} else {
		#checkTrue(TRUE)
	#}
    
	###############################
	## rxPredict.rxBTrees
    
	##############
    ## predict with data.frame and compute deviance
    pred.btrees.link <- rxPredict(fit.btrees.xdf, data = DF,
        #n.trees = n.trees,   
        type = "link"
        #single.tree = FALSE
        )
    #(dev.btrees <- -2 * sum(DF$Kyphosis * pred.btrees.link - log(1 + exp(pred.btrees.link))) / nobs)    # should be comparable to dev.gbm
    (dev.btrees <- -2 * sum((as.integer(DF$Kyphosis) - 1) * pred.btrees.link - log(1 + exp(pred.btrees.link))) / nobs)    # should be comparable to dev.gbm
    
	##############
    ## predict with xdf file and compute error rate
	outData <- tempfile( pattern = ".rxBTrees", fileext = ".xdf")
    if (file.exists(outData)) file.remove(outData)
    on.exit(if(file.exists(outData)) unlink(outData), add = TRUE)
    
    pred.btrees.resp <- rxPredict(fit.btrees.xdf, data = XDF, outData = outData,
            #n.trees = n.trees,
            type = "response",
            #single.tree = FALSE
            )
    pred.btrees.resp <- rxDataStep(pred.btrees.resp)
    (mis.btrees <- sum((pred.btrees.resp > 0.5) != as.integer(DF$Kyphosis) - 1) / nobs) # should be comparable to mis.gbm

	##############
	## check pred.btrees.resp and pred.btrees.link
    checkEquals(pred.btrees.resp, 1.0 / (1 + exp(-pred.btrees.link)), check.attributes = FALSE)
}

"test.rxBTrees.regression.bernoulli.outFile" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 2
	DF <- kyphosis	
	DF$Kyphosis <- as.numeric(DF$Kyphosis) - 1	# 0/1 response
	XDF <- tempfile( pattern = ".kyphosis", fileext = ".xdf")
	rxSplitDataFrameToXdf(DF, XDF, numBlocks = numBlocks)
    on.exit(if(file.exists(XDF)) unlink(XDF), add = TRUE)
    nobs <- nrow(DF)
        
	##################################
	## parameters
	form <- Kyphosis ~ Age + Number + Start
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 4	#1		#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "bernoulli"

	###############################
	## rxBTrees
    
	outFile <- tempfile( pattern = ".rxBTrees", fileext = ".xdf")
	if (file.exists(outFile)) file.remove(outFile)
	on.exit(if (file.exists(outFile)) file.remove(outFile), add = TRUE)
    
    ## df input
	fit.btrees.df <- rxBTrees(form, data = DF, lossFunction = distribution,
        outFile = outFile, overwrite = TRUE,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
    
    checkTrue(!file.exists(outFile))
    
    ## xdf input
	fit.btrees.xdf <- rxBTrees(form, data = XDF, lossFunction = distribution,
        outFile = outFile, overwrite = TRUE,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	
	##############
	## check results  
    outFile.df <- rxDataStep(outFile)
    
    ## On 32-bit platforms, OOBTimes (typedef unsigned int CxIndex;) is treated as a factor without levels and thus is NA.
    ## On 64-bit platforms, OOBTimes (typedef unsigned long long CxIndex;) is not treated as a factor and thus is OK.
    oob.idx <- (as.integer(outFile.df$OOBTimes) == 1)
    nobs.all <- length(oob.idx)
    nobs.oob <- sum(oob.idx)
    
    fit.btrees.pred <- outFile.df$Predicted
    dev <- DF$Kyphosis * fit.btrees.pred - log(1 + exp(fit.btrees.pred))
    (dev.btrees.oob <- -2 * sum(dev[oob.idx]) / nobs.oob)
    
    checkEquals(nobs.all, nobs)
    checkEquals(nobs.oob, fit.btrees.xdf$oob.err$num.oob[n.trees])
    checkEquals(dev.btrees.oob, fit.btrees.xdf$oob.err$oob.err[n.trees], tolerance = 1e-6)
    
	###############################
	## rxPredict.rxBTrees
    
	##############
    ## predict with data.frame
    pred.btrees.link <- rxPredict(fit.btrees.xdf, data = DF,
        #n.trees = n.trees,   
        type = "link"
        #single.tree = FALSE
        )

	##############
	## check fit.btrees.pred and pred.btrees.link
    checkEquals(unlist(pred.btrees.link), fit.btrees.pred, check.attributes = FALSE)
}

#######################################################################
## classification (multinomial)

###################################
## binary (2-class)

"test.rxBTrees.classification.multinomial.2class" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 2
	DF <- kyphosis
	XDF <- tempfile( pattern = ".kyphosis", fileext = ".xdf")
	rxSplitDataFrameToXdf(DF, XDF, numBlocks = numBlocks)
    on.exit(if(file.exists(XDF)) unlink(XDF), add = TRUE)
    nobs <- nrow(DF)
    
	##################################
	## parameters
	form <- Kyphosis ~ Age + Number + Start
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 3	#1		#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "multinomial"

	###############################
	## gbm
	if (suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE)))
	{
		set.seed(seed)
		fit.gbm <- gbm(form, data = DF, distribution = distribution,
			n.trees = n.trees, shrinkage = shrinkage, bag.fraction = bag.fraction,
			interaction.depth = interaction.depth, n.minobsinnode = n.minobsinnode)
		if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.gbm$train.error)}
        
        ## predict and compute deviance
        pred.gbm.link <- predict(fit.gbm, newdata = DF,
            n.trees = n.trees - 1,  # NOTE: train.error is computed based on the prob data of the last step!
            type = "link"
            #single.tree = FALSE
            )
        pred.gbm.exp <- exp(drop(pred.gbm.link))
        pred.gbm.prob <- pred.gbm.exp / rowSums(pred.gbm.exp)
        (dev.gbm <- sum(-outer(DF$Kyphosis, levels(DF$Kyphosis), "==") * log(pred.gbm.prob)) / nobs)
        checkEquals(fit.gbm$train.error[n.trees], dev.gbm)

        ## predict and compute error rate
        pred.gbm.resp <- predict(fit.gbm, newdata = DF,
            n.trees = n.trees,
            type = "response"
            #single.tree = FALSE
            )
        (mis.gbm <- sum(max.col(drop(pred.gbm.resp)) != as.numeric(DF$Kyphosis)) / nobs)

        ###############
        pred.gbm.link <- predict(fit.gbm, newdata = DF,
            n.trees = n.trees,
            type = "link"
            #single.tree = FALSE
            )
        pred.gbm.exp <- exp(drop(pred.gbm.link))
        pred.gbm.prob <- pred.gbm.exp / rowSums(pred.gbm.exp)
        checkEquals(pred.gbm.prob, drop(pred.gbm.resp))
	}

	##################################
	## rxBTrees
	fit.btrees.xdf <- rxBTrees(form, data = XDF, lossFunction = distribution,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.btrees.xdf)}
	
	###############################
	## check results
	if (gbm.installed)
	{
		compareBTreesResults(fit.gbm, fit.btrees.xdf)
	} else {
		checkTrue(TRUE)
	}
    
	###############################
	## rxPredict.rxBTrees
    
	##############
    ## predict with data.frame and compute deviance
    pred.btrees.link <- rxPredict(fit.btrees.xdf, DF,
        #n.trees = n.trees,   
        type = "link"
        #single.tree = FALSE
        )
    pred.btrees.exp <- exp(drop(pred.btrees.link)[, -3])
    pred.btrees.prob <- pred.btrees.exp / rowSums(pred.btrees.exp)
    (dev.btrees <- sum(-outer(DF$Kyphosis, levels(DF$Kyphosis), "==") * log(pred.btrees.prob)) / nobs)    # should be comparable to dev.gbm

	##############
    ## predict with xdf file and compute error rate
	outData <- tempfile( pattern = ".rxBTrees", fileext = ".xdf")
    if (file.exists(outData)) file.remove(outData)
    on.exit(if(file.exists(outData)) unlink(outData), add = TRUE)
    
    pred.btrees.resp <- rxPredict(fit.btrees.xdf, data = XDF, outData = outData,
        #n.trees = n.trees,
        type = "response"
        #single.tree = FALSE
        )
    pred.btrees.resp <- rxDataStep(pred.btrees.resp)
    (mis.btrees <- sum(max.col(pred.btrees.resp[, -3]) != as.numeric(DF$Kyphosis)) / nobs)   # should be comparable to mis.gbm

    ###############
	## check pred.btrees.resp and pred.btrees.link
    checkEquals(pred.btrees.prob, pred.btrees.resp[, -3], check.attributes = FALSE)
}

###################################
## multiclass (> 2-class)

"test.rxBTrees.classification.multinomial.3class" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 2
	DF <- iris
	XDF <- tempfile( pattern = ".iris", fileext = ".xdf")
	rxSplitDataFrameToXdf(DF, XDF, numBlocks = numBlocks)
    on.exit(if(file.exists(XDF)) unlink(XDF), add = TRUE)
    nobs <- nrow(DF)

	##################################
	## parameters
	form <- Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 1		#3	#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "multinomial"

	###############################
	## gbm
	if (suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE)))
	{
		set.seed(seed)
		fit.gbm <- gbm(form, data = DF, distribution = distribution,
			n.trees = n.trees, shrinkage = shrinkage, bag.fraction = bag.fraction,
			interaction.depth = interaction.depth, n.minobsinnode = n.minobsinnode)
		if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.gbm$train.error)}
        
        ## predict and compute deviance
        pred.gbm.link <- predict(fit.gbm, newdata = DF,
            n.trees = n.trees - 1,  # NOTE: train.error is computed based on the prob data of the last step!
            type = "link"
            #single.tree = FALSE
            )
        pred.gbm.exp <- exp(drop(pred.gbm.link))
        pred.gbm.prob <- pred.gbm.exp / rowSums(pred.gbm.exp)
        (dev.gbm <- sum(-outer(DF$Species, levels(DF$Species), "==") * log(pred.gbm.prob)) / nobs)
        checkEquals(fit.gbm$train.error[n.trees], dev.gbm)

        ## predict and compute error rate
        pred.gbm.resp <- predict(fit.gbm, newdata = DF,
            n.trees = n.trees,
            type = "response"
            #single.tree = FALSE
            )
        (mis.gbm <- sum(max.col(drop(pred.gbm.resp)) != as.numeric(DF$Species)) / nobs)

        ###############
        pred.gbm.link <- predict(fit.gbm, newdata = DF,
            n.trees = n.trees,
            type = "link"
            #single.tree = FALSE
            )
        pred.gbm.exp <- exp(drop(pred.gbm.link))
        pred.gbm.prob <- pred.gbm.exp / rowSums(pred.gbm.exp)
        checkEquals(pred.gbm.prob, drop(pred.gbm.resp))
	}

	##################################
	## rxBTrees
	fit.btrees.xdf <- rxBTrees(form, data = XDF, lossFunction = distribution,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.btrees.xdf)}
	
	###############################
	## check results
	if (gbm.installed)
	{
		compareBTreesResults(fit.gbm, fit.btrees.xdf)
	} else {
		checkTrue(TRUE)
	}
    
	###############################
	## rxPredict.rxBTrees
    
	##############
    ## predict with data.frame and compute deviance
    pred.btrees.link <- rxPredict(fit.btrees.xdf, DF,
        #n.trees = n.trees,   
        type = "link"
        #single.tree = FALSE
        )
    pred.btrees.exp <- exp(drop(pred.btrees.link)[, -4])
    pred.btrees.prob <- pred.btrees.exp / rowSums(pred.btrees.exp)
    (dev.btrees <- sum(-outer(DF$Species, levels(DF$Species), "==") * log(pred.btrees.prob)) / nobs)    # should be comparable to dev.gbm

	##############
    ## predict with xdf file and compute error rate
	outData <- tempfile( pattern = ".rxBTrees", fileext = ".xdf")
    if (file.exists(outData)) file.remove(outData)
    on.exit(if(file.exists(outData)) unlink(outData), add = TRUE)
    
    pred.btrees.resp <- rxPredict(fit.btrees.xdf, data = XDF, outData = outData,
        #n.trees = n.trees,
        type = "response", overwrite = TRUE,
        #single.tree = FALSE
        )
    pred.btrees.resp <- rxDataStep(pred.btrees.resp)
    (mis.btrees <- sum(max.col(pred.btrees.resp[, -4]) != as.numeric(DF$Species)) / nobs)   # should be comparable to mis.gbm

    ###############
	## check pred.btrees.resp and pred.btrees.link
    checkEquals(pred.btrees.prob, pred.btrees.resp[, -4], check.attributes = FALSE)
}

"test.rxBTrees.classification.multinomial.4class" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 4
	XDF <- file.path(rxGetOption("sampleDataDir"), "claims4blocks.xdf")
	DF <- rxDataStep(XDF)
    nobs <- nrow(DF)
    
	##################################
	## parameters
	form <- type ~ car.age + age + cost + number
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 3	#1		#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "multinomial"

	###############################
	## gbm
	if (suppressWarnings(gbm.installed <- require(gbm, quietly = TRUE)))
	{
		set.seed(seed)
		fit.gbm <- gbm(form, data = DF, distribution = distribution,
			n.trees = n.trees, shrinkage = shrinkage, bag.fraction = bag.fraction,
			interaction.depth = interaction.depth, n.minobsinnode = n.minobsinnode)
		if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.gbm$train.error)}
        
        ## predict and compute deviance
        pred.gbm.link <- predict(fit.gbm, newdata = DF,
            n.trees = n.trees - 1,  # NOTE: train.error is computed based on the prob data of the last step!
            type = "link"
            #single.tree = FALSE
            )
        pred.gbm.exp <- exp(drop(pred.gbm.link))
        pred.gbm.prob <- pred.gbm.exp / rowSums(pred.gbm.exp)
        (dev.gbm <- sum(-outer(DF$type, levels(DF$type), "==") * log(pred.gbm.prob)) / nobs)
        checkEquals(fit.gbm$train.error[n.trees], dev.gbm)

        ## predict and compute error rate
        pred.gbm.resp <- predict(fit.gbm, newdata = DF,
            n.trees = n.trees,
            type = "response"
            #single.tree = FALSE
            )
        (mis.gbm <- sum(max.col(drop(pred.gbm.resp)) != as.numeric(DF$type)) / nobs)

        ###############
        pred.gbm.link <- predict(fit.gbm, newdata = DF,
            n.trees = n.trees,
            type = "link"
            #single.tree = FALSE
            )
        pred.gbm.exp <- exp(drop(pred.gbm.link))
        pred.gbm.prob <- pred.gbm.exp / rowSums(pred.gbm.exp)
        checkEquals(pred.gbm.prob, drop(pred.gbm.resp))
	}

	##################################
	## rxBTrees
	fit.btrees.xdf <- rxBTrees(form, data = XDF, lossFunction = distribution,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
	if (!exists(".dont.plot") || !.dont.plot) {dev.new(); plot(fit.btrees.xdf)}
	
	###############################
	## check results
	if (gbm.installed)
	{
		compareBTreesResults(fit.gbm, fit.btrees.xdf)
	} else {
		checkTrue(TRUE)
	}
    
	###############################
	## rxPredict.rxBTrees
    
	##############
    ## predict with data.frame and compute deviance
    pred.btrees.link <- rxPredict(fit.btrees.xdf, DF,
        #n.trees = n.trees,   
        type = "link"
        #single.tree = FALSE
        )
    pred.btrees.exp <- exp(drop(pred.btrees.link)[, -5])
    pred.btrees.prob <- pred.btrees.exp / rowSums(pred.btrees.exp)
    (dev.btrees <- sum(-outer(DF$type, levels(DF$type), "==") * log(pred.btrees.prob)) / nobs)    # should be comparable to dev.gbm

	##############
    ## predict with xdf file and compute error rate
	outData <- tempfile( pattern = ".rxBTrees", fileext = ".xdf")
    if (file.exists(outData)) file.remove(outData)
    on.exit(if(file.exists(outData)) unlink(outData), add = TRUE)
    
    pred.btrees.resp <- rxPredict(fit.btrees.xdf, data = XDF, outData = outData,
        #n.trees = n.trees,
        type = "response"
        #single.tree = FALSE
        )
    pred.btrees.resp <- rxDataStep(pred.btrees.resp)
    (mis.btrees <- sum(max.col(pred.btrees.resp[, -5]) != as.numeric(DF$type)) / nobs)   # should be comparable to mis.gbm

    ###############
	## check pred.btrees.resp and pred.btrees.link
    checkEquals(pred.btrees.prob, pred.btrees.resp[, -5], check.attributes = FALSE)
}

"test.rxBTrees.classification.multinomial.outFile" <- function()
{
    if(exists(".deactivate.rxBTrees.tests") && .deactivate.rxBTrees.tests) DEACTIVATED("rxBTrees not complete")
    #library(RevoScaleR)
    #source(file.path(Sys.getenv("RXSVNROOT"), "revoAnalytics\\init.R"))
	rxSetComputeContext("local")
	
	##################################
	## dataset
	numBlocks <- 2
	DF <- iris
	XDF <- tempfile( pattern = ".iris", fileext = ".xdf")
	rxSplitDataFrameToXdf(DF, XDF, numBlocks = numBlocks)
    on.exit(if(file.exists(XDF)) unlink(XDF), add = TRUE)
    nobs <- nrow(DF)

	##################################
	## parameters
	form <- Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
	seed <- 0

	n.trees <- if(exists(".n.trees")) .n.trees else 50
	interaction.depth <- 1		#3	#
	n.minobsinnode <- 1
	shrinkage <- 0.1
	bag.fraction <- 0.5	#1	#
	distribution <- "multinomial"

	##################################
	## rxBTrees
	outFile <- tempfile( pattern = ".rxBTrees", fileext = ".xdf")
	if (file.exists(outFile)) file.remove(outFile)
	on.exit(if (file.exists(outFile)) file.remove(outFile), add = TRUE)
    
    ## data frame input
	fit.btrees.df <- rxBTrees(form, data = DF, lossFunction = distribution,
        outFile = outFile, overwrite = TRUE,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
    
    checkTrue(!file.exists(outFile))
    
    ## xdf input
	fit.btrees.xdf <- rxBTrees(form, data = XDF, lossFunction = distribution,
        outFile = outFile, overwrite = TRUE,
		nTree = n.trees, learningRate = shrinkage, sampRate = bag.fraction, 
		maxdepth = interaction.depth, minbucket = n.minobsinnode,
		seed = seed, replace = FALSE, mTry = 0, maxNumBins = 200,	
		#useWriteDataSource = 1, #allowDiskWrite = FALSE,
		#blocksPerRead = numBlocks, numThreads = 1, 
		#reportProgress = 2, verbose = 2, 
        scheduleOnce = if(exists(".scheduleOnce")) .scheduleOnce else FALSE,
        maxRowsInMemory = if(exists(".maxRowsInMemory")) .maxRowsInMemory else -1,
		)
    
	##############
	## check results  
    outFile.df <- rxDataStep(outFile)    
    ylevels <- attr(fit.btrees.xdf$forest[[1]], "ylevels")
    nylevels <- length(ylevels)
    pred.names <- paste("Pred", ylevels, sep = "")
    prob.names <- paste("Prob", ylevels, sep = "")
    
    fit.btrees.pred <- outFile.df[pred.names]
    fit.btrees.prob <- outFile.df[prob.names]
    
    fit.btrees.pred.exp <- exp(fit.btrees.pred)
    fit.btrees.pred.prob <- fit.btrees.pred.exp / rowSums(fit.btrees.pred.exp)
    
    ## NOTE: fit.btrees.prob is computed from fit.btrees.pred of the previous iteration!
    #checkEquals(fit.btrees.prob, fit.btrees.pred.prob)
    
    ## On 32-bit platforms, OOBTimes (typedef unsigned int CxIndex;) is treated as a factor without levels and thus is NA.
    ## On 64-bit platforms, OOBTimes (typedef unsigned long long CxIndex;) is not treated as a factor and thus is OK.
    oob.idx <- (as.integer(outFile.df$OOBTimes) == 1)
    nobs.all <- length(oob.idx)
    nobs.oob <- sum(oob.idx)
    
    ## NOTE: deviance is computed from fit.btrees.prob of the current iteration!
    dev <- rowSums(-outer(DF$Species, levels(DF$Species), "==") * log(fit.btrees.prob))
    (dev.fit.btrees.oob <- sum(dev[oob.idx]) / nobs.oob)
    
    checkEquals(nobs.all, nobs)
    checkEquals(nobs.oob, fit.btrees.xdf$oob.err$num.oob[n.trees * nylevels])
    last.trees <- ((n.trees - 1) * nylevels + 1) : (n.trees * nylevels)
    checkEquals(dev.fit.btrees.oob, sum(fit.btrees.xdf$oob.err$oob.err[last.trees]),
      tolerance = 1e-7 )
    
	###############################
	## rxPredict.rxBTrees
    
	##############
    ## predict with data.frame and compute deviance
    pred.btrees.link <- rxPredict(fit.btrees.xdf, DF,
        #n.trees = n.trees,   
        type = "link"
        #single.tree = FALSE
        )
    pred.btrees.prob <- rxPredict(fit.btrees.xdf, DF,
        #n.trees = n.trees,   
        type = "prob"
        #single.tree = FALSE
        )

    ###############
	## check pred.btrees.prob and pred.btrees.link
    checkEquals(fit.btrees.pred, pred.btrees.link[, -(nylevels + 1)], check.attributes = FALSE)
    checkEquals(fit.btrees.pred.prob, pred.btrees.prob[, -(nylevels + 1)], check.attributes = FALSE)
}

#######################################################################
## bug fixes
