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

".rxSqliteConnectionStringFromFile" <- function()
{
    if (exists("rxSqliteConnectionStringFromFile", globalenv()))
        get("rxSqliteConnectionStringFromFile", globalenv())
    else
        RevoScaleR:::rxSqliteConnectionStringFromFile
}

"test.rxCovCor.args.blocksPerRead" <- function()
{
	test100r5b <- file.path(rxGetOption("unitTestDataDir"), "test100r5b")
	form <- ~ xnum1 + xnum2 + xnum2miss
	zCovBlocksDefault <- rxCovCor(form, data=test100r5b, blocksPerRead=-1)
	zCovBlocks1 <- rxCovCor(form, data=test100r5b, blocksPerRead=1)
	nocomp <- which(names(zCovBlocks1) %in% c("call","params"))
	checkTrue(all.equal(zCovBlocksDefault[-nocomp], zCovBlocks1[-nocomp], check.attributes=FALSE))
	
	zCovBlocks5 <- rxCovCor(form, data=test100r5b, blocksPerRead=5)
	checkTrue(all.equal(zCovBlocksDefault[-nocomp], zCovBlocks5[-nocomp], check.attributes=FALSE)) 
   	
	# Compare with compressed file
	test100r5bUC <- file.path(rxGetOption("unitTestDataDir"), "test100r5bUC")

	zCovBlocks1C <- rxCovCor(form, data=test100r5bUC, blocksPerRead=1)
	zCovBlocks5C <- rxCovCor(form, data=test100r5bUC, blocksPerRead=5)	
    
    # Test with data source
	out1 <- capture.output(
        zCovBlocks1 <- rxCovCor(form, data=test100r5b, blocksPerRead=2)
        )
    out2 <- capture.output(
	    zCovBlocks2 <- rxCovCor(form, data=RxXdfData(test100r5b), blocksPerRead=2)
	    )
    out3 <- capture.output(  
        zCovBlocks3 <- rxCovCor(form, data=RxXdfData(test100r5b, blocksPerRead=2))  
        )    
	
    checkEquals(length(out1), length(out2))
    checkEquals(length(out1), length(out3))
    
	checkTrue(all.equal(zCovBlocks1[-nocomp], zCovBlocks1C[-nocomp], check.attributes=FALSE)) 
	checkTrue(all.equal(zCovBlocks5[-nocomp], zCovBlocks5C[-nocomp], check.attributes=FALSE)) 		
}

"test.rxCovCor.args.type" <- function()
{
    form <- ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
    covSSCP <- rxCovCor(form, data = iris, type = "SSCP") 
    covCov <- rxCovCor(form, data = iris, type = "Cov") 
    covCor <- rxCovCor(form, data = iris, type = "Cor")
    
    # check for unsupported type
    checkException(rxCovCor(form, data = iris, type = "unsupported"), silent = TRUE)
}

"test.rxCovCor.args.data" <- function()
{
	form <- ~ height + weight
	DF <- women
	XDF <- tempfile( pattern = ".rxCovTemp", fileext = ".xdf")
	rxDataStep(DF, XDF)
	
	zCovDF <- rxCovCor(form, data=DF)
	zCovXDF <- rxCovCor(form, data=XDF)
	nocomp <- which(names(zCovXDF) %in% c("call","params"))
	checkTrue(all.equal(zCovDF[-nocomp], zCovXDF[-nocomp], check.attributes=FALSE))
    file.remove(XDF)
}

"test.rxCovCor.args.formula" <- function()
{
    # check for unsupported dependent variable specification
    checkException(rxCovCor(Sepal.Length ~ Sepal.Width, data = iris), silent = TRUE)
    
    # check for unsupported stripped intercept
    checkException(rxCovCor(~ Sepal.Length - 1, data = iris), silent = TRUE)
    
    # check for unsupported dot expansion
    checkException(rxCovCor(~., data = iris), silent = TRUE)
    
    # check for mixed categorical and continuous variables in formula
    covMixed <- rxCovCor(~ Plant:Type + conc + uptake, data = CO2)
    
    # check for categorical only
    covCat <- rxCovCor(~ Plant:Type:Treatment, data = CO2)

    # check for continuous only
    covNum <- rxCovCor(~ conc + uptake, data = CO2) 
}

"test.rxCovCor.args.fweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))
    
    weightsObj1 <- rxCovCor(form, data = DF, fweights = "weightVar")
	fw <- "weightVar"
	weightsObj2 <- rxCovCor(form, data = DF, fweights = fw)

	# Estimated variance-covariance matrices should be the same
    checkEquals(weightsObj1[["CovCor"]], weightsObj2[["CovCor"]])
    #TODO: ADD MORE CHECKS
}

"test.rxCovCor.args.keepAll" <- function()
{
    # obj returned by ExaStat as a scalar
    DF <- data.frame(sex=factor(c("Male","Female","Female")))

    # one category will be dropped and a single value returned
    # make sure that output is a matrix
    z <- rxCovCor(~ sex, data = DF, keepAll = FALSE)
    checkTrue(is.matrix(z[["CovCor"]]))
    checkEquals(dim(z[["CovCor"]]), c(1L, 1L))
    checkEquals(z[["DroppedVars"]], "sex=Male")
    checkEquals(z[["DroppedVarIndexes"]], 2L)
    
    # now keep all levels
    z <- rxCovCor(~ sex, data = DF, keepAll = TRUE)
    checkTrue(is.matrix(z[["CovCor"]]))
    checkEquals(dim(z[["CovCor"]]), c(2L, 2L))
    checkEquals(z[["DroppedVars"]], character(0))
    checkEquals(z[["DroppedVarIndexes"]], integer(0))
}

"test.rxCovCor.args.pweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))
    
    weightsObj1 <- rxCovCor(form, data = DF, pweights = "weightVar")
	pw <- "weightVar"
	weightsObj2 <- rxCovCor(form, data = DF, pweights = pw)

	# Estimated variance-covariance matrices should be the same
    checkEquals(weightsObj1[["CovCor"]], weightsObj2[["CovCor"]])
    #TODO: ADD MORE CHECKS
}

"test.rxCovCor.args.pweights.fweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))

    checkException(rxCovCor(form, data = DF, pweights = "weightVar", fweights = "weightVar"),
        silent = TRUE)
}

"test.rxCovCor.args.reportProgress" <- function()
{
	# reportProgress argument stress tests
	form <- ~ conc + uptake
	DF <- CO2
	
	#reportProgress: logical, character string or integer: 
	#  0: no progress is reported. 
	#  1: the number of processed rows is printed and updated. 
	#  2: rows processed and timings are reported. 
	#  3: rows processed and all timings are reported. 

	variations <- list(0,1,2,3)	
	results <- printOutput <- vector("list", length=length(variations))
	
	for (i in seq_along(variations))
	{
		printOutput[[i]] <- capture.output(results[[i]] <- 
            rxCovCor(form=form, data=DF, reportProgress=variations[[i]]))
	}

	# check that all values are the same
	nocomp <- which(names(results[[1]]) %in% c("call","params"))
	checkTrue(all(unlist(lapply(results[-1], 
		function(x,y,nocomp){all.equal(x[-nocomp], y[-nocomp], check.attributes=FALSE)}, 
		y=results[[1]], nocomp=nocomp))))

	names(printOutput) <- as.character(variations)
	noResponseExpected <- c("0")
	equalLengthExpected <- c("2")
	equalLengthExpected1 <- c("1")
	
	checkTrue(length(unlist(printOutput[noResponseExpected])) == 0)
	
	# just rows
	checkTrue(all(unlist(lapply(printOutput[equalLengthExpected1],length)) == 1))
	
	# all these outputs should be the same
	checkTrue(all(unlist(lapply(printOutput[equalLengthExpected],length)) == 2))
	
	# details gives us the goods
	checkTrue(length(grep("ReadNum=1, CurrentBlockNum=1, CurrentNumRows=84, TotalRowsProcessed=84, ReadTime", 
		printOutput[["3"]][1])) > 0)
	
	# time
	checkTrue(length(grep("^Computation time:", printOutput[["2"]][2])) > 0)
}

"test.rxCovCor.args.rowSelection" <- function()
{
	# initialization
    set.seed(100)
    DF <- data.frame(x = rnorm(20), y = rnorm(20))
	DF$selectVar <- DF$y > 0.0
    rowSelection <- expression(y > 0.0)
    form <- ~ x + y
	
	# test various schemes for row selection and compare to results
	selectRowsObj1 <- rxCovCor(form, data = DF, rowSelection = rowSelection)
	selectRowsObj2 <- rxCovCor(form, data = DF, rowSelection = selectVar)
	selectRowsObj3 <- rxCovCor(form, data = DF, rowSelection = y > 0.0)
    checkEquals(cov(subset(DF[c("x","y")], y > 0.0)), selectRowsObj1[["CovCor"]])
    nocomp <- which(names(selectRowsObj1) %in% c("call","params"))
	checkEquals(selectRowsObj1[-nocomp], selectRowsObj2[-nocomp], check.attributes=FALSE)
	checkEquals(selectRowsObj2[-nocomp], selectRowsObj3[-nocomp], check.attributes=FALSE)
}

"test.rxCovCor.args.transformFunc" <- function()
{
    xform <- function(x)
    {
      x$area <- x$Sepal.Length * x$Sepal.Width
      x
    }

    res <- try(rxCovCor(~ Petal.Length + area, data=iris, transformFunc=xform, 
      transformVars=c("Sepal.Length","Sepal.Width")))
		
    # return for no errors encountered during execution
	checkTrue(!is(res, "try-error"))
	area <- iris$Sepal.Length * iris$Sepal.Width
	checkEqualsNumeric(res[["CovCor"]], cov(cbind(iris["Petal.Length"], area)), tolerance=1e-6)
}

"test.rxCovCor.args.transforms" <- function()
{
    # Create local data source
    # Create transforms variables.
    # New variables: HalfTime, concDouble
    # Deleted variables: time, conc
    transforms <- expression(list(
        HalfTime = time / 2,
        time = NULL,
        concDouble = conc * 2,
        conc = NULL))

	# var{k*x} = k^2 * var{x}, where k a scalar in R and x a vector in R
	cov1 <- rxCovCor(~ HalfTime + concDouble, data = Indometh, transforms = transforms, type = "Cov")
    checkEqualsNumeric(diag(cov1[["CovCor"]]), c(var(Indometh$time)/4, var(Indometh$conc)*4))
}

"test.rxCovCor.args.transformVars" <- function()
{
    # Create local data source
    # Create transforms variables.
    # New variables: HalfTime, concDouble
    # Deleted variables: time, conc
    xform <- 
    function(dataList)
    {
        dataList$HalfTime <- dataList$time / 2
        dataList$time <- NULL
        dataList$concDouble <- dataList$conc * 2
        dataList$conc <- NULL
        dataList
    }

	# var{k*x} = k^2 * var{x}, where k a scalar in R and x a vector in R
	cov1 <- rxCovCor(~ HalfTime + concDouble, data = Indometh, 
        transformFunc = xform, transformVars = c("time", "conc"), type = "Cov")
    checkEqualsNumeric(diag(cov1[["CovCor"]]), c(var(Indometh$time)/4, var(Indometh$conc)*4))    
}

"test.rxCovCor.args.verbose" <- function()
{
    form <- ~ Sepal.Width + Petal.Length + Petal.Width 
    o1 <- capture.output(rxCovCor.test1 <- rxCovCor(form, data=iris, reportProgress=0))
    o2 <- capture.output(rxCovCor.test2 <- rxCovCor(form, data=iris, verbose=0, reportProgress=0))
    o3 <- capture.output(rxCovCor.test3 <- rxCovCor(form, data=iris, verbose=1, reportProgress=0))

    checkEquals(length(o1), 0)
    checkEquals(length(o2), 0)
    checkTrue(length(o3) > 1)
}

"test.rxCovCor.args.varTol" <- function()
{
    # create variables
    varTol <- 1e-12
    set.seed(100)
    x <- rnorm(10, mean = 10, sd = sqrt(varTol) / 2)
    y <- rnorm(10, sd = 1)
    z <- rnorm(10, sd = sqrt(varTol) * 2)
    DF <- data.frame(x = x, y = y, z = z)
     
    # should lose one variable due to weak variance
    covCor <- rxCovCor(~ x + y + z, data = DF, keepAll = FALSE, varTol = varTol, 
                       type = "Cov")
    checkTrue(all(diag(covCor[["CovCor"]]) > varTol))
    
    checkEquals(dim(covCor[["CovCor"]]), c(2L, 2L))
    checkEquals(covCor[["DroppedVars"]], "x")
    checkEquals(covCor[["DroppedVarIndexes"]], 1L)
}

###
# rxCov
###

"test.rxCov.args.blocksPerRead" <- function()
{
	test100r5b <- file.path(rxGetOption("unitTestDataDir"), "test100r5b")
	form <- ~ xnum1 + xnum2 + xnum2miss
	zCovBlocksDefault <- rxCov(form, data=test100r5b, blocksPerRead=-1)
	zCovBlocks1 <- rxCov(form, data=test100r5b, blocksPerRead=1)
	nocomp <- which(names(zCovBlocks1) %in% c("call","params"))
	checkTrue(all.equal(zCovBlocksDefault[-nocomp], zCovBlocks1[-nocomp], check.attributes=FALSE))
	
	zCovBlocks5 <- rxCov(form, data=test100r5b, blocksPerRead=5)
	checkTrue(all.equal(zCovBlocksDefault[-nocomp], zCovBlocks5[-nocomp], check.attributes=FALSE))    
}

"test.rxCov.args.data" <- function()
{
	form <- ~ height + weight
	DF <- women
	XDF <- tempfile( pattern = ".rxCovTemp1", fileext = ".xdf")
	rxDataStep(DF, XDF)
	
	zCovDF <- rxCov(form, data=DF)
	zCovXDF <- rxCov(form, data=XDF)
	nocomp <- which(names(zCovXDF) %in% c("call","params"))
	checkTrue(all.equal(zCovDF[-nocomp], zCovXDF[-nocomp], check.attributes=FALSE))
    file.remove(XDF)
}

"test.rxCov.args.formula" <- function()
{
    # check for unsupported dependent variable specification
    checkException(rxCov(Sepal.Length ~ Sepal.Width, data = iris), silent = TRUE)
    
    # check for unsupported stripped intercept
    checkException(rxCov(~ Sepal.Length - 1, data = iris), silent = TRUE)
    
    # check for unsupported dot expansion
    checkException(rxCov(~., data = iris), silent = TRUE)
    
    # check for mixed categorical and continuous variables in formula
    covMixed <- rxCov(~ Plant:Type + conc + uptake, data = CO2)
    
    # check for categorical only
    covCat <- rxCov(~ Plant:Type:Treatment, data = CO2)

    # check for continuous only
    covNum <- rxCov(~ conc + uptake, data = CO2) 
}

"test.rxCov.args.fweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))
    
    weightsObj1 <- rxCov(form, data = DF, fweights = "weightVar")
	fw <- "weightVar"
	weightsObj2 <- rxCov(form, data = DF, fweights = fw)

	# Estimated variance-covariance matrices should be the same
    checkEquals(weightsObj1, weightsObj2)
}

"test.rxCov.args.pweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))
    
    weightsObj1 <- rxCov(form, data = DF, pweights = "weightVar")
	pw <- "weightVar"
	weightsObj2 <- rxCov(form, data = DF, pweights = pw)

	# Estimated variance-covariance matrices should be the same
    checkEquals(weightsObj1, weightsObj2)
}

"test.rxCov.args.pweights.fweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))

    checkException(rxCov(form, data = DF, pweights = "weightVar", fweights = "weightVar"),
        silent = TRUE)
}

"test.rxCov.args.reportProgress" <- function()
{
	# reportProgress argument stress tests
	form <- ~ conc + uptake
	DF <- CO2
	
	#reportProgress: logical, character string or integer: 
	#  0: no progress is reported. 
	#  1: the number of processed rows is printed and updated. 
	#  2: rows processed and timings are reported. 
	#  3: rows processed and all timings are reported. 

	variations <- list(0,1,2,3)	
	results <- printOutput <- vector("list", length=length(variations))
	
	for (i in seq_along(variations))
	{
		printOutput[[i]] <- capture.output(results[[i]] <- 
            rxCov(form=form, data=DF, reportProgress=variations[[i]]))
	}

	# check that all values are the same
	nocomp <- which(names(results[[1]]) %in% c("call","params"))
	checkTrue(all(unlist(lapply(results[-1], 
		function(x,y,nocomp){all.equal(x[-nocomp], y[-nocomp], check.attributes=FALSE)}, 
		y=results[[1]], nocomp=nocomp))))

	names(printOutput) <- as.character(variations)
	noResponseExpected <- c("0")
	equalLengthExpected <- c("2")
	equalLengthExpected1 <- c("1")
	
	checkTrue(length(unlist(printOutput[noResponseExpected])) == 0)
	
	# just rows
	checkTrue(all(unlist(lapply(printOutput[equalLengthExpected1],length)) == 1))
	
	# all these outputs should be the same
	checkTrue(all(unlist(lapply(printOutput[equalLengthExpected],length)) == 2))
	
	# details gives us the goods
	checkTrue(length(grep("ReadNum=1, CurrentBlockNum=1, CurrentNumRows=84, TotalRowsProcessed=84, ReadTime", 
		printOutput[["3"]][1])) > 0)
	
	# time
	checkTrue(length(grep("^Computation time:", printOutput[["2"]][2])) > 0)
}

"test.rxCov.args.rowSelection" <- function()
{
	# initialization
    set.seed(100)
    DF <- data.frame(x = rnorm(20), y = rnorm(20))
	DF$selectVar <- DF$y > 0.0
    rowSelection <- expression(y > 0.0)
    form <- ~ x + y
	
	# test various schemes for row selection and compare to results
	selectRowsObj1 <- rxCov(form, data = DF, rowSelection = rowSelection)
	selectRowsObj2 <- rxCov(form, data = DF, rowSelection = selectVar)
	selectRowsObj3 <- rxCov(form, data = DF, rowSelection = y > 0.0)
    checkEquals(cov(subset(DF[c("x","y")], y > 0.0)), selectRowsObj1)
    nocomp <- which(names(selectRowsObj1) %in% c("call","params"))
	checkEquals(selectRowsObj1[-nocomp], selectRowsObj2[-nocomp], check.attributes=FALSE)
	checkEquals(selectRowsObj2[-nocomp], selectRowsObj3[-nocomp], check.attributes=FALSE)
}

"test.rxCov.args.transformFunc" <- function()
{
    xform <- function(x)
    {
      x$area <- x$Sepal.Length * x$Sepal.Width
      x
    }

    res <- try(rxCov(~ Petal.Length + area, data=iris, transformFunc=xform, 
      transformVars=c("Sepal.Length","Sepal.Width")))
		
    # return for no errors encountered during execution
	checkTrue(!is(res, "try-error"))
	area <- iris$Sepal.Length * iris$Sepal.Width
	checkEqualsNumeric(res, cov(cbind(iris["Petal.Length"], area)), tolerance=1e-6)
}

"test.rxCov.args.transforms" <- function()
{
    # Create local data source
    # Create transforms variables.
    # New variables: HalfTime, concDouble
    # Deleted variables: time, conc
    transforms <- expression(list(
        HalfTime = time / 2,
        time = NULL,
        concDouble = conc * 2,
        conc = NULL))

	# var{k*x} = k^2 * var{x}, where k a scalar in R and x a vector in R
	cov1 <- rxCov(~ HalfTime + concDouble, data = Indometh, transforms = transforms)
    checkEqualsNumeric(diag(cov1), c(var(Indometh$time)/4, var(Indometh$conc)*4))
}

"test.rxCov.args.transformVars" <- function()
{
    # Create local data source
    # Create transforms variables.
    # New variables: HalfTime, concDouble
    # Deleted variables: time, conc
    xform <- 
    function(dataList)
    {
        dataList$HalfTime <- dataList$time / 2
        dataList$time <- NULL
        dataList$concDouble <- dataList$conc * 2
        dataList$conc <- NULL
        dataList
    }

	# var{k*x} = k^2 * var{x}, where k a scalar in R and x a vector in R
	cov1 <- rxCov(~ HalfTime + concDouble, data = Indometh, 
        transformFunc = xform, transformVars = c("time", "conc"))
    checkEqualsNumeric(diag(cov1), c(var(Indometh$time)/4, var(Indometh$conc)*4))    
}

"test.rxCov.args.verbose" <- function()
{
    form <- ~ Sepal.Width + Petal.Length + Petal.Width 
    o1 <- capture.output(rxCov.test1 <- rxCov(form, data=iris, reportProgress=0))
    o2 <- capture.output(rxCov.test2 <- rxCov(form, data=iris, verbose=0, reportProgress=0))
    o3 <- capture.output(rxCov.test3 <- rxCov(form, data=iris, verbose=1, reportProgress=0))

    checkEquals(length(o1), 0)
    checkEquals(length(o2), 0)
    checkTrue(length(o3) > 1)
}

###
# rxCor
###

"test.rxCor.args.blocksPerRead" <- function()
{
	test100r5b <- file.path(rxGetOption("unitTestDataDir"), "test100r5b")
	form <- ~ xnum1 + xnum2 + xnum2miss
	zCovBlocksDefault <- rxCor(form, data=test100r5b, blocksPerRead=-1)
	zCovBlocks1 <- rxCor(form, data=test100r5b, blocksPerRead=1)
	nocomp <- which(names(zCovBlocks1) %in% c("call","params"))
	checkTrue(all.equal(zCovBlocksDefault[-nocomp], zCovBlocks1[-nocomp], check.attributes=FALSE))
	
	zCovBlocks5 <- rxCor(form, data=test100r5b, blocksPerRead=5)
	checkTrue(all.equal(zCovBlocksDefault[-nocomp], zCovBlocks5[-nocomp], check.attributes=FALSE))    
}

"test.rxCor.args.data" <- function()
{
	form <- ~ height + weight
	DF <- women
	XDF <- tempfile( pattern = ".rxCovTemp2", fileext = ".xdf")
	rxDataStep(DF, XDF)
	
	zCovDF <- rxCor(form, data=DF)
	zCovXDF <- rxCor(form, data=XDF)
	nocomp <- which(names(zCovXDF) %in% c("call","params"))
	checkTrue(all.equal(zCovDF[-nocomp], zCovXDF[-nocomp], check.attributes=FALSE))
    file.remove(XDF)
}

"test.rxCor.args.formula" <- function()
{
    # check for unsupported dependent variable specification
    checkException(rxCor(Sepal.Length ~ Sepal.Width, data = iris), silent = TRUE)
    
    # check for unsupported stripped intercept
    checkException(rxCor(~ Sepal.Length - 1, data = iris), silent = TRUE)
    
    # check for unsupported dot expansion
    checkException(rxCor(~., data = iris), silent = TRUE)
    
    # check for mixed categorical and continuous variables in formula
    covMixed <- rxCor(~ Plant:Type + conc + uptake, data = CO2)
    
    # check for categorical only
    covCat <- rxCor(~ Plant:Type:Treatment, data = CO2)

    # check for continuous only
    covNum <- rxCor(~ conc + uptake, data = CO2)
}

"test.rxCor.args.fweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))
    
    weightsObj1 <- rxCor(form, data = DF, fweights = "weightVar")
	fw <- "weightVar"
	weightsObj2 <- rxCor(form, data = DF, fweights = fw)

	# Estimated variance-covariance matrices should be the same
    checkEquals(weightsObj1, weightsObj2)
}

"test.rxCor.args.pweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))
    
    weightsObj1 <- rxCor(form, data = DF, pweights = "weightVar")
	pw <- "weightVar"
	weightsObj2 <- rxCor(form, data = DF, pweights = pw)

	# Estimated variance-covariance matrices should be the same
    checkEquals(weightsObj1, weightsObj2)
}

"test.rxCor.args.pweights.fweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))

    checkException(rxCor(form, data = DF, pweights = "weightVar", fweights = "weightVar"),
        silent = TRUE)
}

"test.rxCor.args.reportProgress" <- function()
{
	# reportProgress argument stress tests
	form <- ~ conc + uptake
	DF <- CO2
	
	#reportProgress: logical, character string or integer: 
	#  0: no progress is reported. 
	#  1: the number of processed rows is printed and updated. 
	#  2: rows processed and timings are reported. 
	#  3: rows processed and all timings are reported. 

	variations <- list(0,1,2,3)	
	results <- printOutput <- vector("list", length=length(variations))
	
	for (i in seq_along(variations))
	{
		printOutput[[i]] <- capture.output(results[[i]] <- 
            rxCor(form=form, data=DF, reportProgress=variations[[i]]))
	}

	# check that all values are the same
	nocomp <- which(names(results[[1]]) %in% c("call","params"))
	checkTrue(all(unlist(lapply(results[-1], 
		function(x,y,nocomp){all.equal(x[-nocomp], y[-nocomp], check.attributes=FALSE)}, 
		y=results[[1]], nocomp=nocomp))))

	names(printOutput) <- as.character(variations)
	noResponseExpected <- c("0")
	equalLengthExpected <- c("2")
	equalLengthExpected1 <- c("1")
	
	checkTrue(length(unlist(printOutput[noResponseExpected])) == 0)
	
	# just rows
	checkTrue(all(unlist(lapply(printOutput[equalLengthExpected1],length)) == 1))
	
	# all these outputs should be the same
	checkTrue(all(unlist(lapply(printOutput[equalLengthExpected],length)) == 2))
	
	# details gives us the goods
	checkTrue(length(grep("ReadNum=1, CurrentBlockNum=1, CurrentNumRows=84, TotalRowsProcessed=84, ReadTime", 
		printOutput[["3"]][1])) > 0)
	
	# time
	checkTrue(length(grep("^Computation time:", printOutput[["2"]][2])) > 0)
}

"test.rxCor.args.rowSelection" <- function()
{
	# initialization
    set.seed(100)
    DF <- data.frame(x = rnorm(20), y = rnorm(20))
	DF$selectVar <- DF$y > 0.0
    rowSelection <- expression(y > 0.0)
    form <- ~ x + y
	
	# test various schemes for row selection and compare to results
	selectRowsObj1 <- rxCor(form, data = DF, rowSelection = rowSelection)
	selectRowsObj2 <- rxCor(form, data = DF, rowSelection = selectVar)
	selectRowsObj3 <- rxCor(form, data = DF, rowSelection = y > 0.0)
    checkEquals(cor(subset(DF[c("x","y")], y > 0.0)), selectRowsObj1)
    nocomp <- which(names(selectRowsObj1) %in% c("call","params"))
	checkEquals(selectRowsObj1[-nocomp], selectRowsObj2[-nocomp], check.attributes=FALSE)
	checkEquals(selectRowsObj2[-nocomp], selectRowsObj3[-nocomp], check.attributes=FALSE)
}

"test.rxCor.args.transformFunc" <- function()
{
    xform <- function(x)
    {
      x$area <- x$Sepal.Length * x$Sepal.Width
      x
    }

    res <- try(rxCor(~ Petal.Length + area, data=iris, transformFunc=xform, 
      transformVars=c("Sepal.Length","Sepal.Width")))
		
    # return for no errors encountered during execution
	checkTrue(!is(res, "try-error"))
	area <- iris$Sepal.Length * iris$Sepal.Width
	checkEqualsNumeric(res, cor(cbind(iris["Petal.Length"], area)), tolerance=1e-6)
}

"test.rxCor.args.transforms" <- function()
{
    # Create local data source
    # Create transforms variables.
    # New variables: HalfTime, concDouble
    # Deleted variables: time, conc
    transforms <- expression(list(
        HalfTime = time / 2,
        time = NULL,
        concDouble = conc * 2,
        conc = NULL))

	# var{k*x} = k^2 * var{x}, where k a scalar in R and x a vector in R
	cor1 <- rxCor(~ HalfTime + concDouble, data = Indometh, transforms = transforms)
    checkEqualsNumeric(diag(cor1), rep(1,NROW(cor1)))
}

"test.rxCor.args.transformVars" <- function()
{
    # Create local data source
    # Create transforms variables.
    # New variables: HalfTime, concDouble
    # Deleted variables: time, conc
    xform <- 
    function(dataList)
    {
        dataList$HalfTime <- dataList$time / 2
        dataList$time <- NULL
        dataList$concDouble <- dataList$conc * 2
        dataList$conc <- NULL
        dataList
    }

	# var{k*x} = k^2 * var{x}, where k a scalar in R and x a vector in R
	cor1 <- rxCor(~ HalfTime + concDouble, data = Indometh, 
        transformFunc = xform, transformVars = c("time", "conc"))
    checkEqualsNumeric(diag(cor1), rep(1,NROW(cor1)))    
}

"test.rxCor.args.verbose" <- function()
{
    form <- ~ Sepal.Width + Petal.Length + Petal.Width 
    o1 <- capture.output(rxCor.test1 <- rxCor(form, data=iris, reportProgress=0))
    o2 <- capture.output(rxCor.test2 <- rxCor(form, data=iris, verbose=0, reportProgress=0))
    o3 <- capture.output(rxCor.test3 <- rxCor(form, data=iris, verbose=1, reportProgress=0))

    checkEquals(length(o1), 0)
    checkEquals(length(o2), 0)
    checkTrue(length(o3) > 1)
}

###
# rxSSCP
###

"test.rxSSCP.args.blocksPerRead" <- function()
{
	test100r5b <- file.path(rxGetOption("unitTestDataDir"), "test100r5b")
	form <- ~ xnum1 + xnum2 + xnum2miss
	zCovBlocksDefault <- rxSSCP(form, data=test100r5b, blocksPerRead=-1)
	zCovBlocks1 <- rxSSCP(form, data=test100r5b, blocksPerRead=1)
	nocomp <- which(names(zCovBlocks1) %in% c("call","params"))
	checkTrue(all.equal(zCovBlocksDefault[-nocomp], zCovBlocks1[-nocomp], check.attributes=FALSE))
	
	zCovBlocks5 <- rxSSCP(form, data=test100r5b, blocksPerRead=5)
	checkTrue(all.equal(zCovBlocksDefault[-nocomp], zCovBlocks5[-nocomp], check.attributes=FALSE))    
}

"test.rxSSCP.args.data" <- function()
{
	form <- ~ height + weight
	DF <- women 
	XDF <- tempfile( pattern = ".rxCovTemp3", fileext = ".xdf")
	rxDataStep(DF, XDF)
	
	zSSCPDF <- rxSSCP(form, data=DF)
	zSSCPXDF <- rxSSCP(form, data=XDF)
	nocomp <- which(names(zSSCPXDF) %in% c("call","params"))
	checkTrue(all.equal(zSSCPDF[-nocomp], zSSCPXDF[-nocomp], check.attributes=FALSE))
    file.remove(XDF)
}

"test.rxSSCP.args.formula" <- function()
{
    # check for unsupported dependent variable specification
    checkException(rxSSCP(Sepal.Length ~ Sepal.Width, data = iris), silent = TRUE)
    
    # check for unsupported stripped intercept
    checkException(rxSSCP(~ Sepal.Length - 1, data = iris), silent = TRUE)
    
    # check for unsupported dot expansion
    checkException(rxSSCP(~., data = iris), silent = TRUE)
    
    # check for mixed categorical and continuous variables in formula
 	#TODO: do we allow purely categorical interactions
    #checkException(rxSSCP(~ Plant:Type + conc + uptake, data = CO2), silent = TRUE)
    
    # check for categorical only
	#TODO: do we allow purely categorical interactions
    #checkException(rxSSCP(~ Plant:Type:Treatment, data = CO2), silent = TRUE)

    # check for continuous only
    covNum <- rxSSCP(~ conc + uptake, data = CO2) 
    checkTrue(all(dim(covNum) == c(3L, 3L)))
    nms <- c("Constant", "conc", "uptake")
    checkEquals(dimnames(covNum), list(nms, nms))
}

"test.rxSSCP.args.fweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))
    
    weightsObj1 <- rxSSCP(form, data = DF, fweights = "weightVar")
	fw <- "weightVar"
	weightsObj2 <- rxSSCP(form, data = DF, fweights = fw)

	# Estimated variance-covariance matrices should be the same
    checkEquals(weightsObj1, weightsObj2)
    #TODO: ADD MORE CHECKS
}

"test.rxSSCP.args.pweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))
    
    weightsObj1 <- rxSSCP(form, data = DF, pweights = "weightVar")
	pw <- "weightVar"
	weightsObj2 <- rxSSCP(form, data = DF, pweights = pw)

	# Estimated variance-covariance matrices should be the same
    checkEquals(weightsObj1, weightsObj2)
    #TODO: ADD MORE CHECKS
}

"test.rxSSCP.args.pweights.fweights" <- function()
{
    set.seed(100)
    form <- ~ height + weight
    weightVar <- ceiling(runif(15,1,4))
    DF <- cbind(women, list(weightVar = weightVar))

    checkException(rxSSCP(form, data = DF, pweights = "weightVar", fweights = "weightVar"),
        silent = TRUE)
}

"test.rxSSCP.args.reportProgress" <- function()
{
	# reportProgress argument stress tests
	form <- ~ conc + uptake
	DF <- CO2
	
	#reportProgress: logical, character string or integer: 
	#  0: no progress is reported. 
	#  1: the number of processed rows is printed and updated. 
	#  2: rows processed and timings are reported. 
	#  3: rows processed and all timings are reported. 

	variations <- list(0,1,2,3)	
	results <- printOutput <- vector("list", length=length(variations))
	
	for (i in seq_along(variations))
	{
		printOutput[[i]] <- capture.output(results[[i]] <- 
            rxSSCP(form=form, data=DF, reportProgress=variations[[i]]))
	}

	# check that all values are the same
	nocomp <- which(names(results[[1]]) %in% c("call","params"))
	checkTrue(all(unlist(lapply(results[-1], 
		function(x,y,nocomp){all.equal(x[-nocomp], y[-nocomp], check.attributes=FALSE)}, 
		y=results[[1]], nocomp=nocomp))))

	names(printOutput) <- as.character(variations)
	noResponseExpected <- c("0")
	equalLengthExpected <- c("2")
	equalLengthExpected1 <- c("1")
	
	checkTrue(length(unlist(printOutput[noResponseExpected])) == 0)
	
	# just rows
	checkTrue(all(unlist(lapply(printOutput[equalLengthExpected1],length)) == 1))
	
	# all these outputs should be the same
	checkTrue(all(unlist(lapply(printOutput[equalLengthExpected],length)) == 2))
	
	# details gives us the goods
	checkTrue(length(grep("ReadNum=1, CurrentBlockNum=1, CurrentNumRows=84, TotalRowsProcessed=84, ReadTime", 
		printOutput[["3"]][1])) > 0)
	
	# time
	checkTrue(length(grep("^Computation time:", printOutput[["2"]][2])) > 0)
}

"test.rxSSCP.args.rowSelection" <- function()
{
	# initialization
    set.seed(100)
    DF <- data.frame(x = rnorm(20), y = rnorm(20))
	DF$selectVar <- DF$y > 0.0
    rowSelection <- expression(y > 0.0)
    form <- ~ x + y
	
	# test various schemes for row selection and compare to results
	selectRowsObj1 <- rxSSCP(form, data = DF, rowSelection = rowSelection)
	selectRowsObj2 <- rxSSCP(form, data = DF, rowSelection = selectVar)
	selectRowsObj3 <- rxSSCP(form, data = DF, rowSelection = y > 0.0)
    X <- as.matrix(subset(DF[c("x","y")], y > 0.0))
    checkEquals(t(X) %*% X, selectRowsObj1[-1L, -1L])
    nocomp <- which(names(selectRowsObj1) %in% c("call","params"))
	checkEquals(selectRowsObj1[-nocomp], selectRowsObj2[-nocomp], check.attributes=FALSE)
	checkEquals(selectRowsObj2[-nocomp], selectRowsObj3[-nocomp], check.attributes=FALSE)
}

"test.rxSSCP.args.transformFunc" <- function()
{
    xform <- function(x)
    {
      x$area <- x$Sepal.Length * x$Sepal.Width
      x
    }

    sscp <- try(rxSSCP(~ Petal.Length + area, data=iris, transformFunc=xform, 
      transformVars=c("Sepal.Length","Sepal.Width")))
		
    # return for no errors encountered during execution
	checkTrue(!is(sscp, "try-error"))
	area <- iris$Sepal.Length * iris$Sepal.Width
    X <- cbind(iris[["Petal.Length"]], area)
	checkEqualsNumeric(sscp[-1L, -1L], t(X) %*% X)
}

"test.rxSSCP.args.transforms" <- function()
{
    # Create local data source
    # Create transforms variables.
    # New variables: HalfTime, concDouble
    # Deleted variables: time, conc
    transforms <- expression(list(
        HalfTime = time / 2,
        time = NULL,
        concDouble = conc * 2,
        conc = NULL))

	sscp <- rxSSCP(~ HalfTime + concDouble, data = Indometh, transforms = transforms)
    X <- cbind(Indometh$time / 2, Indometh$conc * 2)
    checkEqualsNumeric(sscp[-1L, -1L], t(X) %*% X)
}

"test.rxSSCP.args.transformVars" <- function()
{
    # Create local data source
    # Create transforms variables.
    # New variables: HalfTime, concDouble
    # Deleted variables: time, conc
    xform <- 
    function(dataList)
    {
        dataList$HalfTime <- dataList$time / 2
        dataList$time <- NULL
        dataList$concDouble <- dataList$conc * 2
        dataList$conc <- NULL
        dataList
    }

	sscp <- rxSSCP(~ HalfTime + concDouble, data = Indometh, 
        transformFunc = xform, transformVars = c("time", "conc"))
    X <- cbind(Indometh$time / 2, Indometh$conc * 2)
    checkEqualsNumeric(sscp[-1L, -1L], t(X) %*% X)
}

"test.rxSSCP.args.verbose" <- function()
{
    form <- ~ Sepal.Width + Petal.Length + Petal.Width 
    o1 <- capture.output(rxSSCP.test1 <- rxSSCP(form, data=iris, reportProgress=0))
    o2 <- capture.output(rxSSCP.test2 <- rxSSCP(form, data=iris, verbose=0, reportProgress=0))
    o3 <- capture.output(rxSSCP.test3 <- rxSSCP(form, data=iris, verbose=1, reportProgress=0))

    checkEquals(length(o1), 0)
    checkEquals(length(o2), 0)
    checkTrue(length(o3) > 1)
}

"test.rxSSCP.output.noweights" <- function()
{
    DF <- data.frame(x = 1:5, y = 2:6)
    X <- as.matrix(DF)
    matSSCP <- rxSSCP(~ x + y, data = DF)
    checkEquals(matSSCP[-1L, -1L], t(X) %*% X)
    checkTrue(matSSCP[1L, 1L] == NROW(DF))
    checkTrue(matSSCP[2L, 1L] == sum(DF$x))
    checkTrue(matSSCP[3L, 1L] == sum(DF$y))
}

# constant variables test

"test.rxCovCor.constant.var.mix" <- function()
{
    set.seed(100)
    DF <- data.frame(x = rep(1.1, 100), 
	    y = rnorm(100), z = rep(1.1, 100), k = rnorm(100))
    comp <- c("CovCor","StdDevs","Means")
    form <- ~ x + y + z + k
    
    # Cov
    zVC <- rxCovCor(form, DF, type = "Cov")
    checkEquals(zVC[["CovCor"]], cov(DF))
    checkEquals(zVC[["StdDevs"]], apply(DF, MARGIN = 2L, sd))
    checkEquals(zVC[["Means"]], colMeans(DF))
    
    # Cor
    zCor <- rxCovCor(form, DF, type = "Cor")
    checkEquals(zCor[["CovCor"]], cor(DF))
    checkEquals(zCor[["StdDevs"]], c(0, sd(DF[["y"]]), 0, sd(DF[["k"]])), check.attributes = FALSE)
    checkEquals(zCor[["Means"]], colMeans(DF))
}

"test.rxCovCor.constant.var.all" <- function()
{
    # Cov
    DF <- data.frame(x = rep(1.1, 100), z = rep(1.1, 100))
    comp <- c("CovCor","StdDevs","Means")
    form <- ~ x + z
    zVC <- rxCovCor(form, DF, type = "Cov")
    checkEquals(zVC[["CovCor"]], cov(DF))
	checkEquals(zVC[["StdDevs"]], apply(DF, MARGIN = 2L, sd))
    checkEquals(zVC[["Means"]], rep(1.1, 2), check.attributes = FALSE)   
    
    # Cor
    zCor <- rxCovCor(form, DF, type = "Cor")
    checkEquals(zCor[["CovCor"]], cor(DF))
    checkEquals(zCor[["StdDevs"]], as.numeric(c(0, 0)), check.attributes = FALSE)
    checkEquals(zCor[["Means"]], rep(1.1, 2), check.attributes = FALSE)   
}


# userObjects now defunct
#"test.rxCovCor.userObject.transformObject.comparison" <- function()
#{
    #form <- ~ Sepal.Length + Sepal.Width + Petal.Length + PetalWidth2
    #transforms <- expression(list(PetalWidth2 = foo(Petal.Width)))
    #transformObjects <- list(foo = function(x) x * 2)
    #allCov1 <- rxCovCor(form, data = iris, type = "Cov", transforms = transforms, userObjects = transformObjects)
    #allCov2 <- rxCovCor(form, data = iris, type = "Cov", transforms = transforms, transformObjects = transformObjects)
    #allCov3 <- rxCovCor(form, data = iris, type = "Cov", userObjects = list(cow = pi), 
        #transforms = transforms, transformObjects = transformObjects)
    #checkEquals(allCov1[["CovCor"]], allCov2[["CovCor"]])
    #checkEquals(allCov2[["CovCor"]], allCov3[["CovCor"]])
    #checkException(rxCovCor(form, data = iris, type = "Cov", transforms = transforms), silent = TRUE)
#}


########	rxCovCor Analysis on Text datasource 	 OK 9/19
"test.rxCovCor.dataSource.Text" <- function()
{
    dsText <- RxTextData(file.path(rxGetOption("unitTestDataDir"), "test100r.txt"))
	form <- ~ xnum1 + xnum2 + xnum2miss
	result <- rxCovCor(form, data=dsText, blocksPerRead=-1)
		
    testFile <- tempfile(pattern = ".rxCovTempTest", fileext = ".xdf")
	rxImport(dsText, testFile, overwrite = TRUE, reportProgress = 0)	
	result2 <- rxCovCor(form, testFile)	
		
    checkEquals(result$coefficients, result2$coefficients)
    
    file.remove(testFile)
}


########	rxCovCor Analysis on ODBC datasource	
"test.rxCovCor.dataSource.ODBC.ST" <- function()
{			
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
	conString <- try(
					rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "claims.sqlite"),
                        useFastRead = FALSE),
					silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
	dsODBC <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                useFastRead = FALSE,
                connectionString = conString,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCovCor(~number+cost, data=dsODBC)
	
    testFile <- tempfile(pattern = ".rxCov1TempTest", fileext = ".xdf")
	rxImport(dsODBC, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCovCor(~number+cost, testFile)	
	
    checkEquals(result$coefficients, result2$coefficients)
    file.remove(testFile)
}

########	rxCovCor Analysis on Direct ODBC datasource	
"test.rxCovCor.dataSource.ODBC.useFastRead" <- function()
{			
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
	conString <- try(
					rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "claims.sqlite")),
					silent = TRUE)
  
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
	dsODBC <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                connectionString = conString,
				useFastRead = TRUE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCovCor(~number+cost, data=dsODBC)
	
    testFile <- tempfile(pattern = ".rxCov2TempTest", fileext = ".xdf")
	rxImport(dsODBC, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCovCor(~number+cost, testFile)	
	
    checkEquals(result$CovCor, result2$CovCor)
    file.remove(testFile)
}

########	rxCovCor Analysis on Fixed-Format Text datasource 		OK 9/22
"test.rxCovCor.dataSource.FixedText" <- function()
{				
    dsText <- RxTextData(file.path(rxGetOption("sampleDataDir"), "claims.sts"),
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCovCor(~number+cost, data=dsText)
	
    testFile <- tempfile(pattern = ".rxCov3TempTest", fileext = ".xdf")
	rxImport(dsText, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCovCor(~number+cost, testFile)	
	
    checkEquals(result$coefficients, result2$coefficients)
    file.remove(testFile)
}

########	rxCovCor Analysis on Fast Fixed-Format Text datasource 	- rxCovCorFastFF.log
"test.rxCovCor.dataSource.FastFixedText" <- function()
{				
    dsText <- RxTextData(file.path(rxGetOption("sampleDataDir"), "claims.sts"),
				useFastRead = TRUE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCovCor(~number+cost, data=dsText)
	
    testFile <- tempfile(pattern = ".rxCov3TempTest", fileext = ".xdf")
	rxImport(dsText, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCovCor(~number+cost, testFile)	
	
    checkEquals(result$coefficients, result2$coefficients)
    file.remove(testFile)
}

########	rxCov Analysis on  ODBC datasource	
"test.rxCov.dataSource.ODBC.ST" <- function()
{			
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
	conString <- try(
					rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "claims.sqlite"),
                        useFastRead = FALSE),
					silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
	dsODBC <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                connectionString = conString,
                useFastRead = FALSE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCov(~number+cost, data=dsODBC)
	
    testFile <- tempfile(pattern = ".rxCov4TempTest", fileext = ".xdf")
	rxImport(dsODBC, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCov(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}

########	rxCov Analysis on Direct ODBC datasource	
"test.rxCov.dataSource.useFastRead" <- function()
{			
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
	conString <- try(
					rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "claims.sqlite")),
					silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
	dsODBC <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                connectionString = conString,
				useFastRead = TRUE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCov(~number+cost, data=dsODBC)
	
    testFile <- tempfile(pattern = ".rxCov5TempTest", fileext = ".xdf")    
	rxImport(dsODBC, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCov(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}


########	rxCov Analysis on Fixed-Format Text datasource 		OK 9/22
"test.rxCov.dataSource.FixedText" <- function()
{				
    dsText <- RxTextData(file.path(rxGetOption("sampleDataDir"), "claims.sts"),
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCov(~number+cost, data=dsText)
	
    testFile <- tempfile(pattern = ".rxCov6TempTest", fileext = ".xdf")
	rxImport(dsText, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCov(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}

########	rxCov Analysis on Fast Fixed-Format Text datasource  	- rxCovFastFF.log
"test.rxCov.dataSource.FixedText" <- function()
{				
    dsText <- RxTextData(file.path(rxGetOption("sampleDataDir"), "claims.sts"),
				useFastRead = TRUE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCov(~number+cost, data=dsText)
	
    testFile <- tempfile(pattern = ".rxCov6TempTest", fileext = ".xdf")
	rxImport(dsText, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCov(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}

########	rxCor Analysis on ODBC datasource	
"test.rxCor.dataSource.ODBC.ST" <- function()
{			
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
	conString <- try(
					rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "claims.sqlite"),
                        useFastRead = FALSE),
					silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
	dsODBC <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                connectionString = conString,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"),
                        useFastRead = FALSE)					
    result <- rxCor(~number+cost, data=dsODBC)
    
	testFile <- tempfile(pattern = ".rxCov7TempTest", fileext = ".xdf")
	rxImport(dsODBC, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCor(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}

########	rxCor Analysis on Direct ODBC datasource
"test.rxCor.dataSource.ODBC.useFastRead" <- function()
{		
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()	
	conString <- try(
					rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "claims.sqlite")),
					silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
	dsODBC <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                connectionString = conString,
				useFastRead = TRUE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCor(~number+cost, data=dsODBC)
	
    testFile <- tempfile(pattern = ".rxCov8TempTest", fileext = ".xdf")
	rxImport(dsODBC, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCor(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}


########	rxCor Analysis on Fixed-Format Text datasource 		OK 9/22
"test.rxCor.dataSource.FixedText" <- function()
{				
    dsText <- RxTextData(file.path(rxGetOption("sampleDataDir"), "claims.sts"),
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCor(~number+cost, data=dsText)
	
    testFile <- tempfile(pattern = ".rxCov9TempTest", fileext = ".xdf")    
	rxImport(dsText, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCor(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}

########	rxCor Analysis on Fast Fixed-Format Text datasource 	- rxCorFastFF.log
"test.rxCor.dataSource.FixedText" <- function()
{				
    dsText <- RxTextData(file.path(rxGetOption("sampleDataDir"), "claims.sts"),
				useFastRead = TRUE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxCor(~number+cost, data=dsText)
	
    testFile <- tempfile(pattern = ".rxCov9TempTest", fileext = ".xdf")    
	rxImport(dsText, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxCor(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}

########	rxSSCP Analysis on ODBC datasource	
"test.rxSSCP.dataSource.ODBC.ST" <- function()
{		
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()	
	conString <- try(
					rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "claims.sqlite"),
                        useFastRead = FALSE),
					silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
	dsODBC <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                connectionString = conString,
                useFastRead = FALSE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxSSCP(~number+cost, data=dsODBC)
	
    testFile <- tempfile(pattern = ".rxCov10TempTest", fileext = ".xdf")    
	rxImport(dsODBC, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxSSCP(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}

########	rxSSCP Analysis on Direct ODBC datasource	
"test.rxSSCP.dataSource.useFastRead" <- function()
{			
	rxSqliteConnectionStringFromFile <- .rxSqliteConnectionStringFromFile()
	conString <- try(
					rxSqliteConnectionStringFromFile(file.path(rxGetOption("sampleDataDir"), "claims.sqlite")),
					silent = TRUE)
    if (inherits(conString, "try-error"))
        DEACTIVATED(strsplit(conString, "\n")[[1]][2])
		
	dsODBC <- RxOdbcData(
				sqlQuery = "SELECT * FROM claims",
                connectionString = conString,
				useFastRead = TRUE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxSSCP(~number+cost, data=dsODBC)
	
    testFile <- tempfile(pattern = ".rxCov11TempTest", fileext = ".xdf")    
	rxImport(dsODBC, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxSSCP(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}


########	rxSSCP Analysis on Fixed-Format Text datasource 		OK 9/22
"test.rxSSCP.dataSource.FixedText" <- function()
{				
    dsText <- RxTextData(file.path(rxGetOption("sampleDataDir"), "claims.sts"),
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxSSCP(~number+cost, data=dsText)
	
    testFile <- tempfile(pattern = ".rxCov12TempTest", fileext = ".xdf")
	rxImport(dsText, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxSSCP(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}

########	rxSSCP Analysis on Fast Fixed-Format Text datasource	- rxSSCPFastFF.log
"test.rxSSCP.dataSource.FixedText" <- function()
{				
    dsText <- RxTextData(file.path(rxGetOption("sampleDataDir"), "claims.sts"),
				useFastRead = TRUE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxSSCP(~number+cost, data=dsText)
	
    testFile <- tempfile(pattern = ".rxCov12TempTest", fileext = ".xdf")
	rxImport(dsText, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxSSCP(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}

########	rxSSCP Analysis on Fast Fixed-Format Text datasource	- rxSSCPFastFF2.log
"test.rxSSCP.dataSource.FixedText" <- function()
{				
    dsText <- RxTextData(file.path(rxGetOption("sampleDataDir"), "claims.sts"),
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))					
    result <- rxSSCP(~number+cost, data=dsText)
	
    dsText2 <- RxTextData(file.path(rxGetOption("sampleDataDir"), "claims.sts"),
				useFastRead = TRUE,
                colClasses = c("RowNum" = "integer", "age" = "character",
							   "car_age" = "character", "type" = "character",
							   "cost" = "integer", "number" = "integer"))				
    testFile <- tempfile(pattern = ".rxCov12TempTest", fileext = ".xdf")
	rxImport(dsText2, testFile, overwrite = TRUE, reportProgress = 0)
	result2 <- rxSSCP(~number+cost, testFile)	
	
    checkEquals(result, result2)
    file.remove(testFile)
}
