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

"test.rxReadXdf.args.rowVarName" <- function()
{
	rowNames <- c("Row1", "Row2", "Row3", "Row4", "Row5")
	mydata <- data.frame(x=1:5, y=1:5, row.names=rowNames)
	outFile <- ".rxTempRowNames.xdf"
    if (file.exists(outFile)) file.remove(outFile)
	# Transfer row names to a variable in the xdf file
	rxDataStep(data=mydata, outFile=outFile, rowVarName="RowNames")
	# Transfer the variable with row names back to the rownames in the data frame
	mydata1 <- rxReadXdf(outFile, rowVarName="RowNames")
	checkEquals(mydata, mydata1)
	
	# Specifiying a non-existant column should give warning
	# turn all warnings into errors and save old warning level
    oldWarn <- options(warn=2)
    on.exit(options(oldWarn), add = TRUE)
    
    warnRegExpr <- "could not be found"
	res <- try(mydata2 <- rxReadXdf(outFile, rowVarName="RowNumbers"), silent=TRUE)
	checkTrue(inherits(res,"try-error"))
    checkTrue(length(grep(warnRegExpr, as.character(res))) > 0)
	file.remove(outFile)
	
}
	
"test.rxReadXdf.args.numRows" <- function()
{
	rowstoRead <- 10
	inFile <- file.path(rxGetOption("sampleDataDir"), "AirlineDemoSmall.xdf")
	AirlineSub.block.read <- rxReadXdf(file=inFile, startRow=20, numRows=rowstoRead)	
    ## Check for correct values in imported dataframe
	checkEquals(AirlineSub.block.read[1,1],-2)
	checkEqualsNumeric(AirlineSub.block.read[10,2],20.166668)			
	## Check that number of rows is correct
	checkEquals(dim(AirlineSub.block.read)[1],rowstoRead)
	
	# Repeat with uncompressed file
	inFileC <- file.path(rxGetOption("sampleDataDir"), "AirlineDemoSmallUC.xdf")
	AirlineSub.block.read <- rxReadXdf(file=inFileC, startRow=20, numRows=rowstoRead)	
    ## Check for correct values in imported dataframe
	checkEquals(AirlineSub.block.read[1,1],-2)
	checkEqualsNumeric(AirlineSub.block.read[10,2],20.166668)			
	## Check that number of rows is correct
	checkEquals(dim(AirlineSub.block.read)[1],rowstoRead)	
	
}


"test.rxReadXdf.args.startRow" <- function()
{
    inFile <- file.path(rxGetOption("unitTestDataDir"), "AirlineArrDelayGT240.xdf")
	# Obtain information from the XDF file via rxGetInfo()					
    infoObj <- rxGetInfo(inFile, numRows = 0, startRow = 1, getBlockSizes = FALSE)
	varInfoObj <- rxGetVarInfo(inFile)
	checkEquals(infoObj$fileName, normalizePath(inFile))
	checkEquals(infoObj$numRows, 2301)
	checkEquals(infoObj$numVars, 3)
	checkEquals(infoObj$numBlocks, 3)
	checkEquals(varInfoObj[["ArrDelay"]], structure(list(description = "arrival delay, in minutes", varType = "integer", storage = "int32", low = -1437, high = 2598), .Names = c("description", "varType", "storage", "low", "high"), class = "rxVarInfo"))
	checkEquals(varInfoObj[["CRSDepTime"]], structure(list(description = "scheduled departure time", varType = "numeric", storage = "float32", low = 0, high = 24), .Names = c("description", "varType", "storage", "low", "high"), class = "rxVarInfo"))
	checkEquals(varInfoObj[["DayOfWeek"]], structure(list(varType = "factor", storage = "uint32", low = 1, high = 7, levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")), .Names = c("varType", "storage", "low", "high", "levels"), class = "rxVarInfo")) 
    
    # Read fixed number of rows of a single XDF file using rxReadXdf starting at different row numbers. 
    # Verify the summary information about each data frame read from the XDF.
    colNamesToRead <- c("ArrDelay", "CRSDepTime")
    
    # 50 rows starting at the beginning
	airlineDF <- rxReadXdf(file=inFile, varsToKeep = colNamesToRead, startRow = 1, numRows = 50)
	x1 <- summary(airlineDF)
    
    checkEquals(x1[1],    "Min.   :241.0  ") 
    checkEquals(x1[3],    "Median :277.5  ") 
    checkEquals(x1[4],    "Mean   :281.9  ") 
    checkEquals(x1[6],    "Max.   :423.0  ") 
    
    # 50 rows starting at row number 1000
    airlineDF <- rxReadXdf(file=inFile, varsToKeep = colNamesToRead, startRow = 1000, numRows = 50)
	x2 <- summary(airlineDF)
    
    checkEquals(x2[1],    "Min.   :240.0  ") 
    checkEquals(x2[3],    "Median :302.5  ") 
    checkEquals(x2[4],    "Mean   :334.6  ") 
    checkEquals(x2[6],    "Max.   :659.0  ") 

    # 50 rows starting at row number 2000
    airlineDF <- rxReadXdf(file=inFile, varsToKeep = colNamesToRead, startRow = 2000, numRows = 50)    
	x3<-summary(airlineDF)

    checkEquals(x3[1],    "Min.   :242.0  ") 
    checkEquals(x3[3],    "Median :279.0  ") 
    checkEquals(x3[4],    "Mean   :329.2  ") 
    checkEquals(x3[6],    "Max.   :666.0  ") 				
}

"test.rxReadXdf.args.maxRowsByCols" <- function()
{
	dataFileName <- file.path(rxGetOption("sampleDataDir"),"mortDefaultSmall")
	
	myData <- rxReadXdf(dataFileName);
    checkEquals(nrow(myData), 100000)
     
    oldWarn = options(warn=-1)
    on.exit(options(oldWarn), add = TRUE)
    # Will get warning, but data is returned. Warnings turned off above
	myData <- rxReadXdf(dataFileName, maxRowsByCols = 36)
	checkEquals(nrow(myData), 6)
	rm(myData)
    
	myData <- rxReadXdf(dataFileName, varsToKeep=c("creditScore", "ccDebt", "year"),
	    maxRowsByCols = 36)
    checkEquals(nrow(myData), 12)
    rm(myData)
    
    myData <- rxReadXdf(dataFileName, varsToKeep=c("creditScore", "ccDebt", "year"),
	   maxRowsByCols = 36, numRows=10)
    checkEquals(nrow(myData), 10)
    rm(myData)  
}


#
#
# This unit test verifies the ability 
#   - to convert CSV to XDF (using the colInfo parameter to input factor levels)
#   - to read multiple files using rxTextToXdf, and appending the result to a single XDF
#   - to extract XDF file information using rxGetInfo
#   - to read selected rows from the XDF using rxReadXdf
#
# This unit test draws heavily from the "mortDefault.R" demo script.
#
"test.rxReadXdf.data.mortDefaultSmall" <- function()
{
    # Define parameters
    dataFileName <- file.path(rxGetOption("sampleDataDir"),"mortDefaultSmall")
	newFileName <- ".rxTempMortSmall.xdf"
    defaultReadBufferSize <- 10000
    if (file.exists(newFileName)) file.remove(newFileName)

    # factor levels for age
    ageLevels <- c(0:40)
    for (i in 1:41)
	    ageLevels[i] <- paste(ageLevels[i], sep="")

    # factor levels for years
    yearLevels <- c(2000:2004)				
    for (i in 1:5)
	    yearLevels[i] <- paste(yearLevels[i], sep="")	
	
    # colInfo for rxTextToXdf
    colInfo=list(houseAge=list(type="factor", levels=ageLevels),
                 year=list(type="factor", levels=yearLevels))
    append = "none"

    # Read multiple data files in a loop
    for (i in 2000:2004)
    {
        # Construct the input file path
	    importFile <- paste(dataFileName, i, ".csv", sep="")			
        # Convert each CSV data file into XDF format and append it to a single XDF
	    rxTextToXdf(importFile, outFile=newFileName, colInfo=colInfo, 
	        append=append, defaultReadBufferSize=defaultReadBufferSize)
	    if (i == 2000)
		    append="rows"								
    }   

    # Verify number of rows and number of columns being read
    infoObj <- rxGetInfo(newFileName, numRows = 0, startRow = 1, getBlockSizes = FALSE)
	varInfoObj <- rxGetVarInfo(newFileName)
	checkEquals(infoObj$fileName, normalizePath(newFileName))
	checkEquals(infoObj$numRows, 50000)
	checkEquals(infoObj$numVars, 6)
	checkEquals(infoObj$numBlocks, 5)
	checkEquals(varInfoObj[["creditScore"]], structure(list(varType = "integer", storage = "int32", low = 486, high = 895), .Names = c("varType", "storage", "low", "high"), class = "rxVarInfo"))
	checkEquals(varInfoObj[["houseAge"]], structure(list(varType = "factor", storage = "uint32", low = 1, high = 41, levels = c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40")), .Names = c("varType", "storage", "low", "high", "levels"), class = "rxVarInfo"))
	checkEquals(varInfoObj[["yearsEmploy"]], structure(list(varType = "integer", storage = "int32", low = 0, high = 14), .Names = c("varType", "storage", "low", "high"), class = "rxVarInfo"))
	checkEquals(varInfoObj[["ccDebt"]], structure(list(varType = "integer", storage = "int32", low = 0, high = 13384), .Names = c("varType", "storage", "low", "high"), class = "rxVarInfo"))
	checkEquals(varInfoObj[["year"]], structure(list(varType = "factor", storage = "uint32", low = 1, high = 5, levels = c("2000", "2001", "2002", "2003", "2004" )), .Names = c("varType", "storage", "low", "high", "levels"), class = "rxVarInfo"))
	checkEquals(varInfoObj[["default"]], structure(list(varType = "integer", storage = "int32", low = 0, high = 1), .Names = c("varType", "storage", "low", "high"), class = "rxVarInfo")) 

	#The output for R-2.11.1 is correct. To rectify this bug, I simply will add a switch statement to the offending lines of the RUnit test. 
	isRVersionGE.2.11.1 <- compareVersion(paste(R.version[c("major","minor")], collapse="."),"2.11.1") >= 0	
	
    # Read 10 rows starting from the beginning
    mortDF <- rxReadXdf(file=newFileName, varsToKeep = c("creditScore", "yearsEmploy", "ccDebt"), startRow = 1, numRows=10)
	x1<-summary(mortDF)
    checkEquals(colnames(x1)[1], " creditScore")
    checkEquals(colnames(x1)[2], " yearsEmploy")
    checkEquals(colnames(x1)[3], "    ccDebt")

    checkEquals(x1[1,1], "Min.   :539.0  ")
    checkEquals(x1[3,1], "Median :705.5  ")
    checkEquals(x1[6,1], "Max.   :745.0  ")

    checkEquals(x1[1,2], "Min.   :1.00  ")
    checkEquals(x1[3,2], "Median :3.00  ")
    checkEquals(x1[6,2], "Max.   :9.00  ")

    checkEquals(x1[1,3], "Min.   :1861  ")
    checkEquals(x1[3,3], ifelse(isRVersionGE.2.11.1, "Median :4456  ", "Median :4457  "))
    checkEquals(x1[6,3], "Max.   :6725  ")

    # Read 10 rows starting from row number 1000
    mortDF <- rxReadXdf(file=newFileName, varsToKeep = c("creditScore", "yearsEmploy", "ccDebt"), startRow = 1000, numRows=10)
	x2<-summary(mortDF)

    checkEquals(x2[1,1], "Min.   :595.0  ")
    checkEquals(x2[3,1], "Median :728.0  ")
    checkEquals(x2[6,1], "Max.   :793.0  ")

    checkEquals(x2[1,2], "Min.   :3.0  ")
    checkEquals(x2[3,2], "Median :5.0  ")
    checkEquals(x2[6,2], "Max.   :7.0  ")

    checkEquals(x2[1,3], "Min.   : 917  ")
    checkEquals(x2[3,3], ifelse(isRVersionGE.2.11.1, "Median :3062  ", "Median :3063  "))
    checkEquals(x2[6,3], "Max.   :7588  ")

    # Read 10 rows starting from row number 5000
    mortDF <- rxReadXdf(file=newFileName, varsToKeep = c("creditScore", "yearsEmploy", "ccDebt"), startRow = 5000, numRows=10)
	x3<-summary(mortDF)

    checkEquals(x3[1,1], "Min.   :654.0  ")
    checkEquals(x3[3,1], "Median :735.0  ")
    checkEquals(x3[6,1], "Max.   :791.0  ")

    checkEquals(x3[1,2], "Min.   :2.00  ")
    checkEquals(x3[3,2], "Median :5.00  ")
    checkEquals(x3[6,2], "Max.   :6.00  ")

    checkEquals(x3[1,3], "Min.   :1457  ")
    checkEquals(x3[3,3], "Median :4884  ")
    checkEquals(x3[6,3], "Max.   :7251  ")

    # Read 10 rows starting from row number 10000
    mortDF <- rxReadXdf(file=newFileName, varsToKeep = c("creditScore", "yearsEmploy", "ccDebt"), startRow = 10000, numRows=10)
	x4<-summary(mortDF)

    checkEquals(x4[1,1], "Min.   :628.0  ")
    checkEquals(x4[3,1], "Median :713.5  ")
    checkEquals(x4[6,1], "Max.   :792.0  ")

    checkEquals(x4[1,2], "Min.   :2.00  ")
    checkEquals(x4[3,2], "Median :5.00  ")
    checkEquals(x4[6,2], "Max.   :7.00  ")

    checkEquals(x4[1,3], "Min.   : 986  ")
    checkEquals(x4[3,3], "Median :5605  ")
    checkEquals(x4[6,3], "Max.   :7884  ")

    # Verify the summary information
    x5<-rxSummary(~creditScore + yearsEmploy + ccDebt + year, data=newFileName)
    checkEquals(x5$nobs.valid, 50000, msg="Number of observations")
    checkEquals(x5$sDataFrame[1,3], 50.25, msg="creditScore StdDev", tolerance=0.01)
    checkEquals(x5$sDataFrame[1,4], 486,   msg="creditScore Min")
    checkEquals(x5$sDataFrame[1,5], 895,   msg="creditScore Max")

    checkEquals(x5$sDataFrame[2,3], 1.99, msg="yearsEmploy StdDev", tolerance=0.01)
    checkEquals(x5$sDataFrame[2,4],    0, msg="yearsEmploy Min")
    checkEquals(x5$sDataFrame[2,5],   14, msg="yearsEmploy Max")

    checkEquals(x5$sDataFrame[3,3], 1991.57, msg="ccDebt StdDev", tolerance=0.01)
    checkEquals(x5$sDataFrame[3,4],       0, msg="ccDebt Min")
    checkEquals(x5$sDataFrame[3,5],   13384, msg="ccDebt Max")
	
	file.remove(newFileName)
}
