# Copyright (c) Microsoft Corporation.  All rights reserved.
#
# FUNCTIONS
#    Unit tests for a variety of 'claims' data sources used in analysis functions
#    Unit tests for RxDataSource general constructor
#
############################################################################################

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

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

rxuTestAnalyzeDataSourcesUtil <-.rxuTestAnalyzeDataSourcesUtil()

"rxuTestCompareDataSources" <- function(ds1, ds2)
{
	if (class(ds1) != class(ds2))
	{
		stop("Classes must be the same.")
	}
		
	origSlots <- slotNames(ds1)
	for (iSlot in 1:length(origSlots))
    {
		thisSlot <- origSlots[iSlot]
		if (thisSlot != "id")
		{
			checkEquals(slot(ds1, thisSlot), slot(ds2, thisSlot), msg = paste(" Slot name:", thisSlot))
		}
    }
}


"test.RxDataSource.args.dataSource" <- function()
{
	tinyFileName <- file.path(rxGetOption("unitTestDataDir"), "tinyDatesData.txt")
	textDS1 <- RxTextData(tinyFileName, defaultDecimalColType = "numeric", 
		centuryCutoff = 5, stringsAsFactors = FALSE)
	textDS1A <- RxTextData(tinyFileName, defaultDecimalColType = "numeric", 
		centuryCutoff = 0, stringsAsFactors = TRUE)	
	textDS2 <- RxDataSource(dataSource = textDS1A, file = tinyFileName,
		defaultDecimalColType = "numeric", centuryCutoff = 5, stringsAsFactors = FALSE)
	rxuTestCompareDataSources(textDS1, textDS2)
}

"test.RxDataSource.args.class" <- function()
{
	tinyFileName <- file.path(rxGetOption("unitTestDataDir"), "tinyDatesData.txt")
	textDS1 <- RxTextData(tinyFileName, defaultDecimalColType = "numeric", 
		centuryCutoff = 0, stringsAsFactors = TRUE)
	textDS2 <- RxDataSource(class = "RxTextData", file = tinyFileName,
		defaultDecimalColType = "numeric", centuryCutoff = 0, stringsAsFactors = TRUE)
	rxuTestCompareDataSources(textDS1, textDS2)
	
	# Specify a class and a data source of a different class
	claimsSpssName <- file.path(rxGetOption("sampleDataDir"), "claims.sav")
	claimsTextName <- file.path(rxGetOption("sampleDataDir"), "claims.txt")
	claimsColInfo <- list( 
		age = list(type = "factor", levels = c("17-20", "21-24", "25-29", "30-34", "35-39", "40-49", "50-59", "60+")), 
		car.age = list(type = "factor", levels = c("0-3", "4-7", "8-9", "10+")), 
		type = list(type = "factor", levels = c("A", "B", "C", "D")) 
		) 
	textDS1 <- RxTextData(file = claimsTextName, colInfo = claimsColInfo, stringsAsFactors = TRUE)
	spssDS1 <- RxSpssData(file = claimsSpssName, colInfo = claimsColInfo, stringsAsFactors = TRUE)
	
	spssDS2 <-	RxDataSource(class = "RxSpssData", dataSource = textDS1,  file = claimsSpssName)
	rxuTestCompareDataSources(spssDS1, spssDS2)
	
	# RxOdbcData has required slots
	
	fakeOdbcTable <- "myFakeTable"
	fakeColInfo <- list( 
		age = list(type = "factor", levels = c("17-20", "21-24", "25-29", "30-34", "35-39", "40-49", "50-59", "60+")), 
		car.age = list(type = "factor", levels = c("0-3", "4-7", "8-9", "10+")), 
		type = list(type = "factor", levels = c("A", "B", "C", "D")) 
		) 
	teradataDS1 <- RxTeradata(table = fakeOdbcTable, colInfo = fakeColInfo, stringsAsFactors = TRUE)
	odbcDS1 <- RxOdbcData(table = fakeOdbcTable, colInfo = fakeColInfo, stringsAsFactors = TRUE)
	
	odbcDS2 <-	RxDataSource(class = "RxOdbcData", dataSource = teradataDS1)
	rxuTestCompareDataSources(odbcDS1, odbcDS2)	
	
	teradataDS2 <-	RxDataSource(class = "RxTeradata", dataSource = odbcDS1)
	rxuTestCompareDataSources(teradataDS1, teradataDS2)
}

"test.rxGetVarInfo.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
	rxuTestAnalyzeDataSourcesUtil( localComputeContext = localCC, dataSetName = "claims", 
		analysisName = "rxGetVarInfo", 
		analysisParams = list(computeInfo = TRUE),
		testValues = c("age", "type"))
	# Note that RowNum is a string is SAS and SPSS and car.age is named car_age
	# cost and number are stored as doubles in SAS and SPSS
}

"test.rxGetVarNames.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
	rxuTestAnalyzeDataSourcesUtil( localComputeContext = localCC, dataSetName = "claims", 
		analysisName = "rxGetVarNames", 
		analysisParams = NULL, testOutputObjects = TRUE)
	# Note that RowNum is a string is SAS and SPSS and car.age is named car_age
	# cost and number are stored as doubles in SAS and SPSS
}

"test.rxDataStep.varsToKeep.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
    rxuGetTestReadDataSources <- .rxuGetTestReadDataSources()
    testDataSources <- rxuGetTestReadDataSources(localCC, dataSetName = "claims")
	res <- rxDataStep(testDataSources[[1]], varsToKeep = c("age", "type", "cost"))
	for (i in 2:length(testDataSources))
	{   
		# varsToKeep not supported for RxOdbcData
		if (!inherits(testDataSources[[i]], "RxOdbcData"))
		{
			thisRes <- rxDataStep(testDataSources[[i]], varsToKeep = c("age", "type", "cost"))
			checkEquals(thisRes, res)
		}
	}	
}


"test.rxSummary.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
    
    #rxuGetTestReadDataSources <- .rxuGetTestReadDataSources()
    #testDataSources <- rxuGetTestReadDataSources(localCC, dataSetName = "claims")
    #thisDataSource <- testDataSources[[1]]
    #sumOut <- rxSummary(~cost10+type, transforms = list(cost10 = cost*10), data = thisDataSource)
        
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, 
        dataSetName = "claims", 
		analysisName = "rxSummary", 
		analysisParams = list(
            formula = ~cost10+type, 
            transforms = substitute(list(cost10 = cost*10)),
            reportProgress = 0
            ),
		testValues = c("nobs.valid", "sDataFrame", "categorical"))
}

"test.rxQuantile.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
    
    #rxuGetTestReadDataSources <- .rxuGetTestReadDataSources()
    #testDataSources <- rxuGetTestReadDataSources(localCC, dataSetName = "claims")
    #thisDataSource <- testDataSources[[1]]
    #sumOut <- rxQuantile("cost", data = thisDataSource)
        
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, 
        dataSetName = "claims", 
		analysisName = "rxQuantile", 
		analysisParams = list(
            varName = "cost", 
            reportProgress = 0
            ),
		testOutputObjects = TRUE)
}

"test.rxLorenz.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
    
    #rxuGetTestReadDataSources <- .rxuGetTestReadDataSources()
    #testDataSources <- rxuGetTestReadDataSources(localCC, dataSetName = "claims")
    #thisDataSource <- testDataSources[[1]]
    #lorenzOut <- rxLorenz(orderVarName = "cost", data = thisDataSource)
    # plot(lorenzOut)    

	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, 
        dataSetName = "claims", 
		analysisName = "rxLorenz", 
		analysisParams = list(
            orderVarName = "cost", 
            reportProgress = 0
            ),
		testOutputObjects = TRUE)
}


"test.rxCube.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, 
        dataSetName = "claims", 
		analysisName = "rxCube", 
		analysisParams = list(
            formula = cost10~type, 
            transforms = substitute(list(cost10 = cost*10)),
            reportProgress = 0
            ),
		testValues = c("type", "cost10", "Counts"))
}

"test.rxCrossTabs.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
    
    #rxuGetTestReadDataSources <- .rxuGetTestReadDataSources()
    #testDataSources <- rxuGetTestReadDataSources(localCC, dataSetName = "claims")
    #thisDataSource <- testDataSources[[10]]
    #rxCrossTabs(~age:type, rowSelection = cost > 15, data = thisDataSource)
    
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, 
        dataSetName = "claims", 
		analysisName = "rxCrossTabs", 
		analysisParams = list(
            formula = ~age:type, 
            rowSelection = substitute(cost > 15),
            reportProgress = 0
            ),
		testValues = c("counts", "validObs"))
}

"test.rxLinMod.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, dataSetName = "claims", 
		analysisName = "rxLinMod", 
		analysisParams = list(
            formula = cost10~number, 
            transforms = substitute(list(cost10 = cost*10)),
            reportProgress = 0
            ),
		testValues = c("nValidObs", "coefficients", "r.squared", "coef.std.error"))
}
"test.rxPredict.dataSources" <- function()
{
    localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
    rxuGetTestReadDataSources <- .rxuGetTestReadDataSources()
    testDataSources <- rxuGetTestReadDataSources(localCC, dataSetName = "claims")
    #thisDataSource <- testDataSources[[5]]
    #rxGetVarInfo(thisDataSource)
    
    linModObj <- rxLinMod(cost~age, data = testDataSources[[1]])
    
    outFile <- tempfile(pattern = ".rxPredDS", fileext = ".xdf")
    on.exit(if (file.exists(outFile)) file.remove(outFile))
    
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, dataSetName = "claims", 
		analysisName = "rxPredict", 
		analysisParams = list(
            modelObject = linModObj, 
            outData = outFile,
            overwrite = TRUE,
            writeModelVars = TRUE,
            reportProgress = 0
            ),
		testValues = c("file", "fileSystem"))
    
    if (length(testDataSources) > 8)
    {
        odbcFastDS <- testDataSources[[9]]
        newAgeLevels <-   c("17to20", "21to24", "25to29", "30to34", "35to39", "40to49", "50to59", "60+")

        odbcFastDS@colInfo = list(
            age = list(type = "factor", levels = c("17-20", "21-24", "25-29", "30-34", "35-39", "40-49", "50-59", "60+"),
                 newLevels = newAgeLevels ))
        odbcFastDS@stringsAsFactors = FALSE 
        # Test use of new levels for ODBC
        linModObj <- rxLinMod(cost~age, data = odbcFastDS)
    
        predOut <- rxPredict(linModObj, data = odbcFastDS, outData = outFile, 
            writeModelVars = TRUE, overwrite = TRUE) 
        varInfo <- rxGetVarInfo(predOut) 
        checkEquals(varInfo$age$levels, newAgeLevels)
    }
    
}

"test.rxLogit.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
    
    #rxuGetTestReadDataSources <- .rxuGetTestReadDataSources()
    #testDataSources <- rxuGetTestReadDataSources(localCC, dataSetName = "claims")
    #thisDataSource <- testDataSources[[10]]
    #rxLogit(cost > 200 ~number, data = thisDataSource)
    
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, dataSetName = "claims", 
		analysisName = "rxLogit", 
		analysisParams = list(
            formula = cost > 200 ~number,
            reportProgress = 0
            ),
		testValues = c("nValidObs", "coefficients", "aic", "coef.std.error", "rank"))
}

"test.rxGlm.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
    
   # rxuGetTestReadDataSources <- .rxuGetTestReadDataSources()
   # testDataSources <- rxuGetTestReadDataSources(localCC, dataSetName = "claims")
   # thisDataSource <- testDataSources[[10]]
   # rxGlm(highCost ~number + age, transforms = list(highCost = cost > 200),
   #    family = binomial(link = "logit"), data = thisDataSource)
        
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, 
        dataSetName = "claims", 
		analysisName = "rxGlm", 
		analysisParams = list(
            formula = highCost ~number + age,
            transforms = substitute(list(highCost = cost > 200)),
            family = binomial(link = "logit"),
            reportProgress = 0
            ),
		testValues = c("nValidObs", "coefficients", "dispersion", "coef.std.error", "df"))
}

"test.rxKmeans.dataSources" <- function()
{
    # Without outFile
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, 
        dataSetName = "claims", 
		analysisName = "rxKmeans", 
		analysisParams = list(
            formula = ~cost,
            centers = matrix(c(220, 700), ncol = 1),
            reportProgress = 0
            ),
		testValues = c("centers", "withinss", "betweenss", "valid.obs",  "size"))
}

"test.rxLinePlot.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
    
    # Sample code: comment out
    #rxuGetTestReadDataSources<- .rxuGetTestReadDataSources()
    #testDataSources <- rxuGetTestReadDataSources(localCC, dataSetName = "claims")
    #thisDataSource <- testDataSources[[4]]
    #plotOut <- rxLinePlot(cost~number, 
        ##transforms = list(cost10 = cost*10), 
        #type = "p", data = thisDataSource)    
    
    # Test code
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, 
        dataSetName = "claims", 
		analysisName = "rxLinePlot", 
		analysisParams = list(
            formula = cost10~number|type, 
            transforms = substitute(list(cost10 = cost*10)),
            groups = substitute(age),
            type = "p",
            reportProgress = 0
            ),
		testValues = c("panel.args"))
}

"test.rxHistogram.dataSources" <- function()
{
	localCC <- RxLocalSeq(dataPath = rxGetOption("sampleDataDir"))
    
    # Sample code: comment out
    #rxuGetTestReadDataSources<- .rxuGetTestReadDataSources()
    #testDataSources <- rxuGetTestReadDataSources(localCC, dataSetName = "claims")
    #thisDataSource <- testDataSources[[4]]
    #plotOut <- rxHistogram(~cost10|type, 
        #transforms = list(cost10 = cost*10), 
        # data = thisDataSource)    
    #
    # Test code
	rxuTestAnalyzeDataSourcesUtil( 
        localComputeContext = localCC, 
        dataSetName = "claims", 
		analysisName = "rxHistogram", 
		analysisParams = list(
            formula = ~cost10|type, 
            transforms = substitute(list(cost10 = cost*10)),
            reportProgress = 0
            ),
		testValues = c("panel.args"))
}	