ET_OUT_START_QUERY_RECORDFILE060397977865792
tagNET_IN_PLAY_BACK_BY_TIME_INFO060397977865792
tagNET_OUT_PLAY_BACK_BY_TIME_INFO060397977865792
tagEM_PLAY_BACK_SPEED060397980465792
top987568981603979780257
top-432409973603979780256
tagNET_FILE_STREAM_TAG_INFO060397977865792
tagNET_FILE_STREAM_TYPE060397980465792
tagNET_FILE_STREAM_TAG_INFO_EX060397977865792
tagNET_IN_FILE_STREAM_TAGS_INFO060397977865792
tagNET_OUT_FILE_STREAM_TAGS_INFO060397977865792
tagNET_IN_FILE_STREAM_GET_TAGS_INFO060397977865792
tagNET_OUT_FILE_STREAM_GET_TAGS_INFO060397977865792
tagNET_IN_FILE_STREAM_FILTER_TAGS_INFO060397977865792
tagNET_TAGMANAGER_SUB_TAG_INFO060397977865792
tagNET_TAGMANAGER_TAG_INFO060397977865792
tagNET_FINDTAGS_CONDITION_INFO060397977865792
tagNET_IN_FINDTAGS_INFO060397977865792
tagNET_OUT_FINDTAGS_INFO060397977865792
tagNET_TAGMANAGER_TAGSTATE_INFO060397977865792
tagNET_IN_TAGMANAGER_GETTAGSTATE_INFO060397977865792
tagNET_OUT_TAGMANAGER_GETTAGSTATE_INFO# Copyright (c) Microsoft Corporation.  All rights reserved.
#
# FUNCTIONS
#    Unit tests for RevoScaleR formulas
#
############################################################################################
".rxLinkFormulaComponents" <- function()
{
    if (exists("rxLinkFormulaComponents", globalenv()))
        get("rxLinkFormulaComponents", globalenv())
    else
        RevoScaleR:::rxLinkFormulaComponents
}

".deblank" <- function(x) gsub("\\s*","",x)

"test.rxFormula.cbind.substitution" <- function()
{
    rxLinkFormulaComponents <- .rxLinkFormulaComponents()
    
    # define test formula
    form <- formula(cbind(snow*3, white, dwarfs^5, snow/3, snow^3) ~ foo : snow...3)
    rxCubeFormulaOptions <- new("RxFormulaOptions", allowPlusSymbols = FALSE, 
				splitMultipleDepvars = TRUE)
	
    # Type 1: cbind(x, y) ~ z -> "x ~ z;y ~ z"
    cbindType1 <- rxLinkFormulaComponents(formula = form, FUN="rxCube", formulaOptions = rxCubeFormulaOptions)
    cbindType1FormulaString <- .deblank(cbindType1$formulaString)
    checkIdentical(cbindType1FormulaString, 
        "snow...3.1~foo:snow...3;white~foo:snow...3;dwarfs.5~foo:snow...3;snow.3~foo:snow...3;snow.3.1~foo:snow...3")

    # Type 1 with pweights, fweights: cbind(x, y) ~ z -> "x ~ z;y ~ z"
    cbindType1Weights <- rxLinkFormulaComponents(formula = cbind(x,y) ~ z, FUN="rxCube", pweights="pwt", fweights="fwt",
		formulaOptions = rxCubeFormulaOptions)
    cbindType1WeightsFormulaString <- .deblank(cbindType1Weights$formulaString)
    checkIdentical(cbindType1WeightsFormulaString, 
        "x~z,fweight=fwt,pweight=pwt;y~z,fweight=fwt,pweight=pwt")
        
    # Type 2: cbind(x, y) ~ z -> "x,y ~ z"
    cbindType2 <- rxLinkFormulaComponents(formula = form, FUN="rxLinMod", formulaOptions = new("RxFormulaOptions"))
    cbindType2FormulaString <- .deblank(cbindType2$formulaString)
    checkIdentical(cbindType2FormulaString, "snow...3.1,white,dwarfs.5,snow.3,snow.3.1~foo:snow...3")
}
    
"test.rxFormula.F.substitution" <- function()
{
    rxLinkFormulaComponents <- .rxLinkFormulaComponents()
    
    F1 <- rxLinkFormulaComponents(formula = ~ F(log(y)))
    checkIdentical(.deblank(F1$formulaString), "F(log.y.)")

    F2 <- rxLinkFormulaComponents(formula = ~ F(log(y)) : log(y))
    checkIdentical(.deblank(F2$formulaString), "F(log.y.):log.y.")

    F3 <- rxLinkFormulaComponents(formula = ~ log(y) : F(log(y)))
    checkIdentical(.deblank(F3$formulaString), "log.y.:F(log.y.)")

    F4 <- rxLinkFormulaComponents(formula = ~ F(x,1,2,T) : F(y,1,2,F))
    checkIdentical(.deblank(F4$formulaString), "F(x,1,2,T):F(y,1,2,F)")

    F5 <- rxLinkFormulaComponents(formula = ~ F(x,low=1,high=2,exclude=TRUE))
    checkIdentical(.deblank(F5$formulaString), "F(x,1,2,T)")

    F6 <- rxLinkFormulaComponents(formula = ~ F(x,exclude=TRUE,high=2,low=1))
    checkIdentical(.deblank(F6$formulaString), "F(x,1,2,T)")

    F7 <- rxLinkFormulaComponents(formula = ~ F(x,exclude=FALSE,low=2,high=10))
    checkIdentical(.deblank(F7$formulaString), "F(x,2,10,F)")

    F8 <- rxLinkFormulaComponents(formula = ~ F(sin(log(x)),exclude=FALSE,low=2,high=10))
    checkIdentical(.deblank(F8$formulaString), "F(sin.log.x..,2,10,F)")

    F9 <- rxLinkFormulaComponents(formula = ~ sin.log.x.. : F(sin(log(x)),exclude=FALSE,low=2,high=10))
    checkIdentical(.deblank(F9$formulaString), "sin.log.x..:F(sin.log.x...1,2,10,F)")

    F10 <- rxLinkFormulaComponents(formula = ~ sin.log.x.. : F(sin(log(x)),exclude=FALSE,low=-2,high=10))
    checkIdentical(.deblank(F10$formulaString), "sin.log.x..:F(sin.log.x...1,rxMinus2,10,F)") 

    F11 <- rxLinkFormulaComponents(formula = ~ sin.log.x.. : F(sin(log(x)),exclude=FALSE,low=-20.3,high=-1.2345))
    checkIdentical(.deblank(F11$formulaString), "sin.log.x..:F(sin.log.x...1,rxMinus20.3,rxMinus1.2345,F)") 

    F12 <- rxLinkFormulaComponents(formula = ~ sin.log.x.. : F(sin(log(x)),exclude=FALSE,low=-20.3,high=-1.2345) - 1)
    checkIdentical(.deblank(F12$formulaString), "sin.log.x..:F(sin.log.x...1,rxMinus20.3,rxMinus1.2345,F)-1") 

    F13 <- rxLinkFormulaComponents(formula = ~ F(x) : F(y) : F(z))
    checkIdentical(.deblank(F13$formulaString), "F(x):F(y):F(z)") 

    F14 <- rxLinkFormulaComponents(formula = ~ F(log(x)) : F(logx) : log(x) : log.x.)
    checkIdentical(.deblank(F14$formulaString), "F(log.x..1):F(logx):log.x..1:log.x.") 

    F15 <- rxLinkFormulaComponents(formula = ~ F(log(x)) : F(logx) : F(log.x.) : log(x))
    checkIdentical(.deblank(F15$formulaString), "F(log.x..1):F(logx):F(log.x.):log.x..1") 

    F16 <- rxLinkFormulaComponents(formula = ~ F(logx) : F(log(x)) : F(log.x.))
    checkIdentical(.deblank(F16$formulaString), "F(logx):F(log.x..1):F(log.x.)") 

    F17 <- rxLinkFormulaComponents(formula = ~ F(logx) : F(log.x.) : F(log(x)))
    checkIdentical(.deblank(F17$formulaString), "F(logx):F(log.x.):F(log.x..1)") 
}
"test.rxFormula.F.factor.illegal" <- function()
{
	# Should not allow F with factors
	xdfFile <- file.path(rxGetOption("unitTestDataDir"), "test100r5b.xdf")
	res <- try(
		rxCrossTabs(~F(xfac1, low = 7, high = 12), data = xdfFile)
	)
	checkTrue(is(res, "try-error"))
		
}

"test.rxFormula.N.substitution" <- function()
{
    rxLinkFormulaComponents <- .rxLinkFormulaComponents()
    
    N1 <- rxLinkFormulaComponents(formula = N(x) ~ y)
    checkIdentical(.deblank(N1$formulaString), "#x~y")

    N2 <- rxLinkFormulaComponents(formula = N(as.factor(x)) ~ y)
    checkIdentical(.deblank(N2$formulaString), "#as.factor.x.~y")
}
    
"test.rxFormula.mixed.special.substitution.expansion" <- function()
{
    rxLinkFormulaComponents <- .rxLinkFormulaComponents()
    
    form <- cbind(snow*3, white, dwarfs^5, snow/3, snow^3) ~ F(x,1,3,T) + F(log(y/2)) + log(p/2) + I(x/2+q^4) + 
        foo : bar + F(sin(x)) + sin(x) + sinx + (r + s)^2 - 1
    MIX1TYPE2 <- rxLinkFormulaComponents(formula = form)
    checkIdentical(.deblank(MIX1TYPE2$formulaString), 
        "snow...3,white,dwarfs.5,snow.3,snow.3.1~F(x,1,3,T)+F(log.y.2.)+log.p.2.+I.x.2...q.4.+foo:bar+F(sin.x.)+sin.x.+sinx+r+r:s+s-1")
} 

"test.rxFormula.dot.expansion" <- function()
{
    rxLinkFormulaComponents <- .rxLinkFormulaComponents()
        
    checkException(rxLinkFormulaComponents(formula = ~.), 
        msg="Caught unsupported formula dot expansion")
    checkException(rxLinkFormulaComponents(formula = ~.^2), 
        msg="Caught unsupported formula dot expansion")
    checkException(rxLinkFormulaComponents(formula = y ~.^3), 
        msg="Caught unsupported formula dot expansion")
    checkException(rxLinkFormulaComponents(formula = cbind(x,y) ~.^3), 
        msg="Caught unsupported formula dot expansion")
}

###
# Output Variable Name Tests
###

"test.rxFormula.analysis.mapped.variable.names" <- function()
{
	# tests whether the original names were substituted for formulas
	# containing arithmetic expressions over various analytical functions
	set.seed(100)
	DF <- data.frame(
		f1=sample(letters,10,replace=TRUE),
		f2=sample(state.name,10,replace=TRUE),
		n1=as.numeric(10:19),
		n2=rnorm(10),
		z1=as.integer(rnorm(10) > 0))
		
	# rxCrossTabs (names in sums, counts, and means list remains unmapped, e.g., 'sin.x.'
	# but should resolve correctly when printed, e.g., 'sin(x)'
	zTabs <- rxCrossTabs(sin(n2) ~ f2 : f1, data=DF, means=TRUE)
	
 	oSumsPrint <- capture.output(print(zTabs, output="sums"))
 	oSumsSummary <- capture.output(summary(zTabs, output="sums"))
	sumStr <- c("Dependent variable(s): sin(n2)", "sin(n2) (sums):")
	checkTrue(all(sumStr %in% oSumsPrint))
	checkTrue(all(sumStr %in% oSumsSummary))
	
 	oMeansPrint <- capture.output(print(zTabs, output="means"))
 	oMeansSummary <- capture.output(summary(zTabs, output="means"))
	meanStr <- c("Dependent variable(s): sin(n2)", "sin(n2) (means):")
	checkTrue(all(meanStr %in% oMeansPrint))
	checkTrue(all(meanStr %in% oMeansSummary))
	
 	oCountsPrint <- capture.output(print(zTabs, output="counts"))
 	oCountsSummary <- capture.output(summary(zTabs, output="counts"))
	countStr <- c("Dependent variable(s): sin(n2)", "sin(n2) (counts):")
	checkTrue(all(countStr %in% oCountsPrint))
	checkTrue(all(countStr %in% oCountsSummary))

	# rxCube
	zCube <- rxCube(cbind(sin(n2), n2^2, n2/2, n2*2) ~ f2 : f1 : F(n1), data=DF)
	checkTrue(all(c("sin(n2)","n2^2","n2/2","n2*2") %in% names(zCube)))
	
	# rxLinMod
	zLinMod <- rxLinMod(cbind(sin(n2), n2^2, n2/2, n2*2) ~ f2 : f1 + I(z1*5), data=DF)
	zLinModDimnames <- dimnames(coef(zLinMod))
	levelNames <- gsub("\\s*","",unique(sub("=.*","",zLinModDimnames[[1]])))	
	checkTrue(all(c("sin(n2)","n2^2","n2/2","n2*2") %in% zLinModDimnames[[2]]))
	checkTrue("I(z1*5)" %in% levelNames)
	
	zLinModSummary <- summary(zLinMod)
	zLinModSummaryDimnames <- dimnames(coef(zLinMod))
	levelNamesSummary <- gsub("\\s*","",unique(sub("=.*","",zLinModSummaryDimnames[[1]])))	
	checkTrue(all(c("sin(n2)","n2^2","n2/2","n2*2") %in% zLinModDimnames[[2]]))
	checkTrue("I(z1*5)" %in% levelNamesSummary)

	# rxLogit
	zLogit <- rxLogit(I(n2/2) > 0 ~ I(z1*5) : f2 : f1, data=DF)
	zLogitDimnames <- dimnames(coef(zLogit))
	levelNames <- gsub("\\s*","",unique(sub(" for.*","",names(coef(zLogit)))))	
	checkTrue("I(n2/2) > 0" %in% zLogit$y.names)
	checkTrue("I(z1*5)" %in% levelNames)
}

"test.rxFormula.rxSummary.dot.expansion" <- function()
{
	set.seed(100)
	DF <- data.frame(
		f1=sample(letters,10,replace=TRUE),
		f2=sample(state.name,10,replace=TRUE),
		n1=as.numeric(1:10),
		n2=rnorm(10))

	zString <- rxSummary(".rxALL", DF)
	zFormula <- rxSummary(~., DF)
	nocomp <- which(names(zString) %in% c("call","formula"))
    zFormula$params$formulaVars <- NULL
    zString$params$formulaVars <- NULL
	checkEquals(zString[-nocomp], zFormula[-nocomp])
}

"test.rxFormula.catch.crosstabs.plus.symbol.warning" <- function()
{
    # turn all warnings into errors and save old warning level
    oldWarn <- options(warn=2)
    on.exit(options(oldWarn), add = TRUE)
	set.seed(100)
	DF <- data.frame(
		f1=sample(letters,10,replace=TRUE),
		f2=sample(state.name,10,replace=TRUE),
        n1=1:10)
    
    warnRegExpr <- "Please use ':' instead of '\\+' to separate the independent variables:"
    
    # rxCube
    for (FUN in c("rxCube","rxCrossTabs"))
    {
        res <- try(get(FUN)(n1 ~ f1 + f2, data=DF), silent=TRUE)
        checkTrue(inherits(res,"try-error"))
        checkTrue(length(grep(warnRegExpr, as.character(res))) > 0)
        res <- try(get(FUN)(n1 ~ f1 : f2, data=DF), silent=TRUE)
        checkTrue(inherits(res,FUN))
    }   
}
  
"test.rxFormula.strings.rxCrossTabs" <- function()
{
    # Tests to ensure that formula can be specified as a string as a back door
    # to the computational engine. The print and print.summary methods are also
    # stress tested.
 	set.seed(100)
	DF <- data.frame(
		f1=sample(letters,10,replace=TRUE),
		f2=sample(state.name,10,replace=TRUE),
		n1=as.numeric(10:19),
		n2=rnorm(10),
		z1=as.integer(rnorm(10) > 0),
        fwt=1:10,
        pwt=1:10)
    
    # rxCrossTabs
    formulaStrCrossTabs <- "n1~f1:f2,fweight=fwt;n2~f1:f2,fweight=fwt"
    zCrossTabs <- try(rxCrossTabs(formulaStrCrossTabs, data=DF), silent=TRUE)
    checkTrue(!inherits(zCrossTabs,"try-error"))
    zCrossTabsPrint <- try(print(zCrossTabs), silent=TRUE)
    checkTrue(!inherits(zCrossTabsPrint,"try-error"))
    zCrossTabsSummary <- try(summary(zCrossTabs), silent=TRUE)
    checkTrue(!inherits(zCrossTabsSummary,"try-error"))
    zCrossTabsFormula <- rxCrossTabs(cbind(n1,n2)~f1:f2, fweight="fwt", data=DF)
    nocomp <- which(names(zCrossTabs) %in% c("call","formula"))
	# Remove readVars; formulaStrCrossTabs will not contain weights
	zCrossTabs$params$readVars <- NULL
	zCrossTabsFormula$params$readVars <- NULL
    checkEquals(zCrossTabs[-nocomp], zCrossTabsFormula[-nocomp])
    checkIdentical(zCrossTabs$params$Formula, formulaStrCrossTabs)
}

"test.rxFormula.strings.rxCube" <- function()
{
    # Tests to ensure that formula can be specified as a string as a back door
    # to the computational engine. The print and print.summary methods are also
    # stress tested.
 	set.seed(100)
	DF <- data.frame(
		f1=sample(letters,10,replace=TRUE),
		f2=sample(state.name,10,replace=TRUE),
		n1=as.numeric(10:19),
		n2=rnorm(10),
		z1=as.integer(rnorm(10) > 0),
        fwt=1:10,
        pwt=1:10)

    # rxCube
    formulaStrCube <- "n1~f1:f2,fweight=fwt;n2~f1:f2,fweight=fwt"
    zCube <- try(rxCube("n1~f1:f2,fweight=fwt;n2~f1:f2,fweight=fwt", data=DF), silent=TRUE)
    checkTrue(!inherits(zCube,"try-error"))
    zCubePrint <- try(print(zCube), silent=TRUE)
    checkTrue(!inherits(zCubePrint,"try-error"))
    zCubeSummary <- try(summary(zCube), silent=TRUE)
    checkTrue(!inherits(zCubeSummary,"try-error"))
    zCubeFormula <- rxCube(cbind(n1,n2)~f1:f2, fweight="fwt", data=DF)
    checkEquals(zCube, zCubeFormula, check.attributes=FALSE)
    checkIdentical(attr(zCube,"params")$Formula, formulaStrCube)
}

"test.rxFormula.strings.rxLinMod" <- function()
{
    # Tests to ensure that formula can be specified as a string as a back door
    # to the computational engine. The print and print.summary methods are also
    # stress tested.
 	set.seed(100)
	DF <- data.frame(
		f1=sample(letters,10,replace=TRUE),
		f2=sample(state.name,10,replace=TRUE),
		n1=as.numeric(10:19),
		n2=rnorm(10),
		z1=as.integer(rnorm(10) > 0),
        fwt=1:10,
        pwt=1:10)
    
    # rxLinMod
	formulaStrLinMod <- "n1,n2~f1:f2,fweight=fwt"
    zLinMod <- try(rxLinMod(formulaStrLinMod, fweight = "fwt", data=DF), silent=TRUE)
    checkTrue(!inherits(zLinMod,"try-error"))
    zLinModPrint <- try(print(zLinMod), silent=TRUE)
    checkTrue(!inherits(zLinModPrint,"try-error"))
    zLinModSummary <- try(summary(zLinMod), silent=TRUE)
    checkTrue(!inherits(zLinModSummary,"try-error"))
    zLinModFormula <- rxLinMod(cbind(n1,n2)~f1:f2, fweight="fwt", data=DF)
    nocomp <- which(names(zLinMod) %in% c("call","formula"))
	# readVars will be different because of weights
	zLinMod$params$readVars <- NULL
	zLinModFormula$params$readVars <- NULL
    checkEquals(zLinMod[-nocomp], zLinModFormula[-nocomp])
    checkIdentical(zLinModFormula$params$Formula, formulaStrLinMod)
}
    
"test.rxFormula.strings.rxSummary" <- function()
{
    # Tests to ensure that formula can be specified as a string as a back door
    # to the computational engine. The print and print.summary methods are also
    # stress tested.
 	set.seed(100)
	DF <- data.frame(
		f1=sample(letters,10,replace=TRUE),
		f2=sample(state.name,10,replace=TRUE),
		n1=as.numeric(10:19),
		n2=rnorm(10),
		z1=as.integer(rnorm(10) > 0),
        fwt=1:10,
        pwt=1:10)
    
    # rxSummary
    formulaStrSummary <- "f1:f2,fweight=fwt"
    zSummary <- try(rxSummary(formulaStrSummary, data=DF), silent=TRUE)
    checkTrue(!inherits(zSummary,"try-error"))
    zSummaryPrint <- try(print(zSummary), silent=TRUE)
    checkTrue(!inherits(zSummaryPrint,"try-error"))
    zSummarySummary <- try(summary(zSummary), silent=TRUE)
    checkTrue(!inherits(zSummarySummary,"try-error"))
    zSummaryFormula <- rxSummary(~f1:f2, fweight="fwt", data=DF)
    nocomp <- which(names(zSummary) %in% c("call","formula"))
	# readVars will be different because of weights
	zSummary$params$readVars <- NULL
	zSummaryFormula$params$readVars <- NULL	
    checkEquals(zSummary[-nocomp], zSummaryFormula[-nocomp])
    checkIdentical(zSummaryFormula$params$Formula, formulaStrSummary)
}

"test.rxFormula.colInfo.high.low" <- function()
{
    # Test use of F in formula when high low is specifed in colInfo
    
    claimsTxt <- file.path(rxGetOption("sampleDataDir"), "claims.txt")
    
    claimsTxtDS1 <- RxTextData(claimsTxt, varsToKeep = c("cost", "number"))
    
    sumOutNoLowHigh <- rxSummary(~number + F(cost), data = claimsTxtDS1, removeZeroCounts = TRUE)
    sumOutNoLowHigh$categorical[[1]]
    
    claimsTxtDS2 <- RxTextData(claimsTxt, varsToKeep = c("cost", "number"),
        colInfo = list(cost = list(low = 11, high = 850)))  
    
    sumWithLowHigh <- rxSummary(~number + F(cost), data = claimsTxtDS2, removeZeroCounts = TRUE) 
    checkEquals( sumOutNoLowHigh$categorical[[1]], sumWithLowHigh$categorical[[1]])  
    
    testTxt <- file.path(rxGetOption("unitTestDataDir"), "test100r.txt")  
    textDS <- RxTextData(testTxt, colInfo = list(ybinint = list(type = "logical"),
        xnum2 = list(type = "numeric")))
    logitObj1 <- rxLogit(ybinint~ F(xnum2), data = textDS) 
    
    testTxt <- file.path(rxGetOption("unitTestDataDir"), "test100r.txt")  
    textDS <- RxTextData(testTxt, colInfo = list(ybinint = list(type = "logical"),
        xnum2 = list(type = "numeric", low = -2, high = 2)))
    logitObj2 <- rxLogit(ybinint~ F(xnum2), data = textDS)
    
    checkEquals(coef(logitObj1), coef(logitObj2))
    
    # High low values out of range
    # DEACTIVATED("Pending fix to rxLogit with F low/high values not inclusive.")
    testTxt <- file.path(rxGetOption("unitTestDataDir"), "test100r.txt")  
    textDS <- RxTextData(testTxt, colInfo = list(ybinint = list(type = "logical"),
        xnum2 = list(type = "numeric")))
    logitObj1 <- rxLogit(ybinint~ F(xnum2, low = -1, high = 2), data = textDS) 
        
    testTxt <- file.path(rxGetOption("unitTestDataDir"), "test100r.txt")  
    textDS <- RxTextData(testTxt, colInfo = list(ybinint = list(type = "logical"),
        xnum2 = list(type = "numeric", low = -1, high = 2)))
    logitObj2 <- rxLogit(ybinint~ F(xnum2), data = textDS)
    checkEquals(as.vector(coef(logitObj1)), as.vector(coef(logitObj2)))
    
    
}

