# Copyright (c) Microsoft Corporation.  All rights reserved.
#
# FUNCTIONS
#    Unit tests to validate RevoScaleR and R results against published SAS results
#
############################################################################################

.setUp <- function()
{
}

.tearDown <- function()
{
}

# Creating and Redefining Variables: Mathematical expressions using variables and constants
"test.rxSASvalidation.Little.Ch3.1" <- function()
{
	unitTestDataDir <- rxGetOption("unitTestDataDir")
	gardenDAT <- file.path(unitTestDataDir, "Garden.dat")
	gardenDS <- RxTextData(file=gardenDAT, firstRowIsColNames = FALSE,
		missingValueString=".", 
		colInfo = list(list(index = 1, newName="Name"),
			list(index = 2, newName = "Tomato"),
			list(index = 3, newName = "Zucchini"),
			list(index = 4, newName = "Peas"),
			list(index = 5, newName = "Grapes")) )
		
	# Note: in SAS you can specify a scalar in a transformation expresssion
	rsrData <- rxImport(inData=gardenDS, 
		transforms = list( 
			Zone = rep(14, .rxNumRows),
			Type = rep("home", .rxNumRows),
			Zucchini = Zucchini * 10,
			Total = Tomato  + Zucchini + Peas + Grapes,
			PerTom = 100*(Tomato/Total))
		)
		
	
	# Compare with published SAS data
	Name <- c("Gregor", "Molly", "Luther", "Susan")
	Tomato <- c(10, 15, 50, 20)
	Zucchini <- c(20, 50, 100, 0)
	Peas <- c(40, 10, 15, NA)
	Grapes <- c(0, 1000, 50, 20)
	Zone <- c(14, 14, 14, 14)
	Type <- c("home", "home", "home", "home")
	Total <- c( 70, 1075, 215, NA)
	PerTom <- c(14.2857, 1.3953, 23.2558, NA)
	littleData <- data.frame(Name, Tomato, Zucchini, Peas, Grapes, Zone, Type,
		Total, PerTom, stringsAsFactors=FALSE)
	
	checkEquals( rsrData, littleData, tolerance= .0001)
	        
}

# Creating and Redefining Variables: Using variables and R functions
"test.rxSASvalidation.Little.Ch3.2" <- function()
{
	unitTestDataDir <- rxGetOption("unitTestDataDir")
	pumpkinDAT <- file.path(unitTestDataDir, "Pumpkin.dat")
	
	# Note: SAS import does sniffing of variable types for fixed format data.
	# Location information can also be specified in a summary form across columns.
	pumpkinDS <- RxTextData(file=pumpkinDAT, firstRowIsColNames = FALSE,
		missingValueString=".", 
		readDateFormat = "%m-%d-%Y",
		colInfo = list(
			Name = list( start=1, width=17),
			Age  = list( type="integer", start=18, width=2),
			Type = list( start=21, width=1),
			Date = list( type="Date", start=23, width=10),
			Scr1 = list( type="numeric", start=33, width=4),
			Scr2 = list( type="numeric", start=37, width=4),
			Scr3 = list( type="numeric", start=41, width=4),
			Scr4 = list( type="numeric", start=45, width=4),
			Scr5 = list( type="numeric", start=49, width=4)
			) )
		
	rsrData <- rxImport(inData=pumpkinDS, 
		transforms = list( 
			AvgScore = rowMeans(data.frame( Scr1, Scr2, Scr3, Scr4, Scr5), na.rm=TRUE),
			DayEntered = (as.POSIXlt(Date))$mday,
			Type = toupper(Type)
		)
	)
	
	# Note: The book says SAS prints Date data as days since Jan 1, 1960 
	# but it appears to be since Jan. 1, 1961
	
	# Compare imported dates with text
	myDate <- c("2008-10-28", "2008-10-30", "2008-10-29",
		"2008-10-30", "2008-10-31", "2008-10-29")
	checkEquals(myDate, as.character(rsrData$Date))
	
	# Do a quick sanity check on how many days since Jan 1 1960
	# to confirm that the book is incorrect
	numDays <- 365*length(1960:2007) + 30*10
	testDays <- mean(as.numeric(rsrData$Date - as.Date("1960-01-01")))
	checkEquals(numDays, testDays, tolerance=30)
	
	# Now convert to number of days since Jan 1 1961
	rsrData$Date <- as.numeric(rsrData$Date - as.Date("1961-01-01"))
	
	Name <- c("Alicia Grossman", "Matthew Lee", "Elizabeth Garcia",
 		"Lori Newcombe", "Jose Martinez", "Brian Williams")
	Age <- c(13, 9, 10, 6, 7, 11)
	Type <- c("C", "D", "C", "D", "D", "C")
	Date <- c(17467, 17469, 17468, 17469, 17470, 17468)
	Scr1 <- c(7.8, 6.5, 8.9, 6.7, 8.9, 7.8)
	Scr2 <- c(6.5, 5.9, 7.9, 5.6, 9.5, 8.4)
	Scr3 <- c(7.2, 6.8, 8.5, 4.9, 10.0, 8.5)
	Scr4 <- c(8.0, 6.0, 9.0, 5.2, 9.7, 7.9)
	Scr5 <- c(7.9, 8.1, 8.8, 6.1, 9.0, 8.0)
	AvgScore <- c(7.48, 6.66, 8.62, 5.7, 9.42, 8.12)
	DayEntered <- c(28,30, 29, 30, 31, 29)
	
	littleData <- data.frame(Name, Age, Type, Date, Scr1, Scr2,
		Scr3, Scr4, Scr5, AvgScore, DayEntered, stringsAsFactors=FALSE)

	checkEquals( rsrData, littleData, tolerance= .0001, check.attributes = FALSE)
	
}

# Creating and Redefining Variables: Using conditional statements
"test.rxSASvalidation.Little.Ch3.5" <- function()
{
	unitTestDataDir <- rxGetOption("unitTestDataDir")
	usedCarDAT <- file.path(unitTestDataDir, "UsedCar.dat")
	usedCarXDF <- file.path(tempdir(), ".rxOutFileTemp1.xdf")
	usedCarDS <- RxTextData(file=usedCarDAT, firstRowIsColNames = FALSE,
		missingValueString=".", 
		colInfo = list(
			list(index = 1, newName = "Model"),
			list(index = 2, newName = "Year"),
			list(index = 3, newName = "Make"),
			list(index = 4, newName = "Seats"),
			list(index = 5, newName = "Color")) )
		
	rxImport(inData=usedCarDS, outFile=usedCarXDF, overwrite=TRUE,
		transforms = list( 
			Status = ifelse(Year < 1975, "classic", " "),
			Make = ifelse(Model == 'Corvette' | Model == 'Camaro', 'Chevy', Make),
			Make = ifelse(Model == 'Miata', 'Mazda', Make),
			Seats = ifelse(Model == 'Miata', 2, Seats)
		)
	)
		
	rsrData <- rxReadXdf(usedCarXDF)
	
	# Compare with published SAS data
	Model = c("Corvette", "XJ6", "Mustang", "Miata", "CRX", "Camaro")
	Year = c( 1955, 1995, 1966, 2002, 2001, 2000)
	Make = c("Chevy", "Jaguar", "Ford", "Mazda", "Honda", "Chevy")
	Seats = c( 2,2,4,2,2,4)
	Color = c("black", "teal", "red", "silver", "black", "red")
	Status = c("classic", " ", "classic", " ", " ", " ")
	
	littleData <- data.frame(Model, Year, Make, Seats, Color, Status, stringsAsFactors=FALSE)
	
	checkEquals( rsrData, littleData, tolerance= .0001)
	
	if (file.exists(usedCarXDF)) file.remove(usedCarXDF)
        
}

# Creating and Redefining Variables: Grouping observations
"test.rxSASvalidation.Little.Ch3.6" <- function()
{
	unitTestDataDir <- rxGetOption("unitTestDataDir")
	homeDAT <- file.path(unitTestDataDir, "Home.dat")
	homeXDF <- file.path(tempdir(), ".rxOutFileTemp1.xdf")
	homeDS <- RxTextData(file=homeDAT, firstRowIsColNames = FALSE,
		missingValueString=".", 
		colInfo = list(
			Col1 = list(newName = "Owner", start=1, width=7),
			Col2 = list(newName = "Description", start=9, width=25),
			Col3 = list(newName = "Cost", start=35, width=8, type="numeric")
			) )
		
	rxImport(inData=homeDS, outFile=homeXDF, overwrite=TRUE,
		transforms = list( 
			CostGroup = cut(Cost, breaks=c(0, 2000, 10000, 100000), 
				labels=c("low", "medium", "high"), right=FALSE)

		)
	)
		
	rsrData <- rxReadXdf(homeXDF)
	
	# Compare with published SAS data
	Owner <- c("Bob", "Shirley", "Silvia", "Al", "Norm", "Kathy")
	Description <- c("kitchen cabinet face-lift",
		"bathroom addition", "paint exterior",                 
		"backyard gazebo", "paint interior",
        "second floor addition")
	Cost <- c(1253, 11350.7, NA, 3098.63, 647.77, 75362.93)
	CostGroup <- factor(c("low", "high", NA, "medium", "low", "high"), 
		levels=c("low", "medium", "high"))
	
	littleData <- data.frame(Owner, Description, Cost, CostGroup, stringsAsFactors=FALSE)
	
	checkEquals( rsrData, littleData, tolerance= .0001, check.attributes = FALSE)
	
	if (file.exists(homeXDF)) file.remove(homeXDF)
        
}

# Creating and Redefining Variables: Subsetting Data
"test.rxSASvalidation.Little.Ch3.7" <- function()
{
	unitTestDataDir <- rxGetOption("unitTestDataDir")
	spDAT <- file.path(unitTestDataDir, "Shakespeare.dat")
	spXDF <- file.path(tempdir(), ".rxOutFileTemp1.xdf")
	spDS <- RxTextData(file=spDAT, firstRowIsColNames = FALSE,
		missingValueString=".", 
		colInfo = list(
			Col1 = list(newName = "Title", start=1, width=25),
			Col2 = list(newName = "Year", start=27, width=4, type="integer"),
			Col3 = list(newName = "Type", start=32, width=7, type="factor",
				levels=c("comedy", "history", "romance", "tragedy"))
			) )
		
	rxImport(inData=spDS, outFile=spXDF, overwrite=TRUE,
		rowSelection = Type == "comedy" )
		
	rsrData <- rxReadXdf(spXDF)
	
	# Compare with published SAS data
	Title <- c("A Midsummer Night's Dream", "Comedy of Errors",
		"Taming of the Shrew")
	Year <- as.integer(c(1595, 1590, 1593))
	Type <- factor(rep("comedy", 3), levels=c("comedy", "history", "romance", "tragedy"))  
	
	littleData <- data.frame(Title, Year, Type, stringsAsFactors=FALSE)
	
	checkEquals( rsrData, littleData, check.attributes = FALSE)
	
	if (file.exists(spXDF)) file.remove(spXDF)
        
}

# Section 3.8 postponed

# Creating and Redefining Variables: Cumulative Data
"test.rxSASvalidation.Little.Ch3.10" <- function()
{
	unitTestDataDir <- rxGetOption("unitTestDataDir")
	gamesDAT <- file.path(unitTestDataDir, "Games.dat")
	gamesXDF <- file.path(tempdir(), ".rxOutFileTemp1.xdf")
	
	# Create an data set with two blocks to test cumulative values
	gamesDS <- RxTextData(file=gamesDAT, firstRowIsColNames = FALSE,
		missingValueString=".", rowsPerRead = 5,
		colInfo = list(
			Col1 = list(newName = "Month", start=1, width=1, type="integer"),
			Col2 = list(newName = "Day", start=3, width=2, type="integer"),
			Col3 = list(newName = "Team", start=6, width=19 ),
			Col4 = list(newName = "Hits", start=26, width=2, type="integer"),
			Col5 = list(newName = "Runs", start=29, width=2, type="integer")
			) )
		
	myTransforms <- function( dataList )
	{
		dataList$MaxRuns <- cummax(dataList$Runs)
		dataList$RunsToDate <- cumsum(dataList$Runs)
		if (.rxChunkNum > 1)
		{
			dataList$RunsToDate <- dataList$RunsToDate + previousRuns;
			
			dataList$MaxRuns <- ifelse(dataList$MaxRuns < previousMaxRuns,
				 previousMaxRuns, dataList$MaxRuns )	 
		}
		if (!.rxIsTestChunk)
		{
			previousRuns <<- dataList$RunsToDate[length(dataList$RunsToDate)]
			previousMaxRuns <<- max(dataList$MaxRuns)
		}
		return (dataList)
	}
	
	rxImport(inData=gamesDS, outFile=gamesXDF, overwrite=TRUE,
		transformFunc = myTransforms, 
		transformObjects = list(previousRuns=0, previousMaxRuns=0))
		
	rsrData <- rxReadXdf(gamesXDF)
	
	# Compare with published SAS data
	Month <- as.integer(c(rep(6,6), rep(7,4)))
	Day <- as.integer(c( 19, 20, 23,24,25,30,1,4,4,5))
		
	Team <- c("Columbia Peaches", "Columbia Peaches",
    		"Plains Peanuts", "Plains Peanuts", "Plains Peanuts",
      		"Gilroy Garlics", "Gilroy Garlics", 
			"Sacramento Tomatoes", "Sacramento Tomatoes",
			"Sacramento Tomatoes")
	Hits <- as.integer(c(8,10,3,7,12,4,9,15,10,2))
	Runs <- as.integer(c(3, 5, 4, 2, 8, 4, 4, 9, 10, 3) )
	MaxRuns <- as.integer(c(3,5,5,5,8,8,8,9,10,10))
	RunsToDate <- as.integer(c(3,8,12,14,22,26,30,39,49,52))
	
	
	littleData <- data.frame(Month, Day, Team, Hits, Runs, MaxRuns, RunsToDate,
		stringsAsFactors=FALSE)
	
	checkEquals( rsrData, littleData, check.attributes = FALSE)
	
	if (file.exists(gamesXDF)) file.remove(gamesXDF)
        
}


# Creating and Redefining Variables: Operating on Multiple Variables
"test.rxSASvalidation.Little.Ch3.11" <- function()
{
	unitTestDataDir <- rxGetOption("unitTestDataDir")
	radioDAT <- file.path(unitTestDataDir, "WBRK.dat")
	radioXDF <- file.path(tempdir(), ".rxOutFileTemp1.xdf")
	radioDS <- RxTextData(file=radioDAT, firstRowIsColNames = FALSE,
		missingValueString=".", 
		colInfo = list(
			list(index = 1, newName = "City"),
			list(index = 2, newName = "Age"),
			list(index = 3, newName = "domk"),
			list(index = 4, newName = "wj"),
			list(index = 5, newName = "hwow"),
			list(index = 6, newName = "simbh"),
			list(index = 7, newName = "kt"),
			list(index = 8, newName = "aomm"),
			list(index = 9, newName = "libm"),
			list(index = 10, newName = "tr"),
			list(index = 11, newName = "filp"),
			list(index = 12, newName = "ttr")
			) )
		
	
	multTransforms <- function(dataList)
	{
		changeIdx <- match(vars, names(dataList))
		dataList[changeIdx] <-
			lapply(dataList[changeIdx], FUN = transform)
		dataList
    }

	rxImport(inData=radioDS, outFile=radioXDF, overwrite=TRUE,
		transformFunc=multTransforms, transformObjects = list( 
			vars = c("domk", "wj", "hwow", "simbh", "kt",
				"aomm", "libm", "tr", "filp", "ttr"),
			transform = function(x) {ifelse(x == 9, NA, x)})
		)
		
	rsrData <- rxReadXdf(radioXDF)
	
	# Compare with published SAS data
	City <- c("Albany", "Richmond", "Oakland", "Richmond", "Berkeley")
	Age <- as.integer(c(54, 33,27,41, 18))
	domk <- as.integer(c(4,5,1,4,3))
	wj <- as.integer(c(3,2,3,3,4))
	hwow <- as.integer(c(5,4,2,5,NA))
	simbh <- as.integer(c(NA,3,NA,5,1))
	kt <- as.integer(c(NA, NA, NA, 5,4))
	aomm <- as.integer(c(2,2, NA, 2, NA))
	libm <- as.integer(c(1, NA, 3, NA, 3))
	tr <- as.integer(c(4,3,4,4,NA))
	filp <- as.integer(c(4,3,2,5,3))
	ttr <- as.integer(c(NA, 3,3,5,2))
		
	littleData <- data.frame(City,Age, domk, wj, hwow, simbh, kt,
		aomm, libm, tr, filp, ttr, stringsAsFactors=FALSE)
	
	checkEquals( rsrData, littleData, tolerance= .0001)
	
	if (file.exists(radioXDF)) file.remove(radioXDF)
        
}

