# Copyright (c) Microsoft Corporation.  All rights reserved.

source(file.path(path.package("MicrosoftML"), "unitTests/common", "runit-mlUtils.R"))

"test.mlModel.methods.summary.ExpressEdition" <- function()
{
    utils.run.ExpressEdition(run.mlModel.methods.summary.ExpressEdition)
}

"run.mlModel.methods.summary.ExpressEdition" <- function()
{
    checkTrue(rxIsExpressEdition())
	
    oldWidth <- options(width = 120)
    on.exit(options(oldWidth), add = TRUE)
    myIris <- iris
    myIris$IsVersi <- myIris$Species == 'versicolor'
    trainRows <- c(1:30, 51:80, 101:130)
    testRows = !(1:150 %in% trainRows)
    trainIris <- myIris[trainRows,]
    testIris <- myIris[testRows,]
    irisFormula <- IsVersi~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
       
    # rxLogisticRegression binary classification
    logitBinary <- rxLogisticRegression(irisFormula, data = trainIris)

    logitRSR <- rxLogit(irisFormula, data = trainIris)

    # rxFastTrees binary classification
    fastTreeBinary <- rxFastTrees(irisFormula, data = trainIris)
       
    # rxFastForest binary classification 
    rxFastForestBinary <- rxFastForest(irisFormula, data = trainIris)

    # rxNeuralNet binary classification 
    rxNeuralNetBinary <- rxNeuralNet(irisFormula, data = trainIris,
       numHiddenNodes = 3)
      
    ##########################################################
    # Anomaly Detection
    ##########################################################  

    # Setting up the data
       
    trainIrisA <- trainIris
    trainIrisA$isIris <- 1
    testIrisA <- testIris
    irisVars <- c("Sepal.Length", "Sepal.Width",  "Petal.Length", "Petal.Width")
    testIrisA <- testIris[, irisVars]
    testIrisA$isIris <- 1
        
    daffodils <- data.frame(
            Sepal.Length = c(2.5, 2.6),
            Sepal.Width = c(.75, .9),
            Petal.Length = c(2.5, 2.5),
            Petal.Width = c(.8, .7),
            isIris = 0)
    testIrisA <- rbind(testIrisA, daffodils)  
          
    # rxOneClassSvm anomaly detection
    ocSvmFormula = isIris~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width 
    rxOneClassSvm <- rxOneClassSvm(formula = ocSvmFormula,
            data = trainIrisA)       

    ###########################################################
    # Multi-classification
    ########################################################### 
     
    multiFormula <- Species ~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
     
    # multiClass with rxLogisticRegression
    logitMulti <- rxLogisticRegression(multiFormula, type = "multiClass", 
        data = trainIris)


    # multiClass with rxNeuralNet
    rxNeuralNetMulti <- rxNeuralNet(multiFormula, type = "multiClass", 
        numHiddenNodes = 3, data = trainIris)

    #######################################################################
    # Regression
    #######################################################################

    # Use the built-in data set 'airquality'
    set.seed(10)
    
    DF <- airquality[!is.na(airquality$Ozone), ]	
    DF$Ozone <- as.numeric(DF$Ozone)
    randomSplit <- rnorm(nrow(DF))
    trainAir <- DF[randomSplit >= 0,]
    testAir <- DF[randomSplit < 0,]
    airFormula <- Ozone ~ Solar.R + Wind + Temp       

    # Regression Fast Tree
    fastTreeReg <- rxFastTrees(airFormula, type = "regression", 
        data = trainAir, randomSeed = 37)  
    # Regression Fast Forest
    rxFastForestReg <- rxFastForest(airFormula, type = "regression", 
        data = trainAir, randomSeed = 37)
    # Regression Neural Net
    rxNeuralNetReg <- rxNeuralNet(airFormula, type = "regression", 
        data = trainAir)

    # Tests for summary and coef
    sumLogitBinary <- summary(logitBinary, digits = 5)
    coefLogitBinary <- coef(logitBinary)
    checkEquals(names(coefLogitBinary), c("(Bias)", "Sepal.Width", "Petal.Length"))
    checkEquals(as.integer(100 * unlist(coefLogitBinary)), c(-56, -59, 50))
    out1 <- capture.output(print(sumLogitBinary))
    CheckStringsFound(out1, c("Call:", "Data: trainIris", "Sepal.Width"))

    sumFastTreeBinary <- summary(fastTreeBinary, digits = 5)
    coefFastTreeBinary <- coef(fastTreeBinary)
    checkEquals(names(coefFastTreeBinary), c("Petal.Width", "Petal.Length", "Sepal.Length", "Sepal.Width"))
    checkEquals(as.integer(100 * unlist(coefFastTreeBinary) + 1e-7), c(100, 88, 20, 19))
    checkEquals(sumFastTreeBinary$digits, 5)
    out2 <- capture.output(print(sumFastTreeBinary))
    CheckStringsFound(out2, c("Call:", "Data: trainIris", "Sepal.Width"))

    sumFastForestBinary <- summary(rxFastForestBinary, digits = 6)
    coefFastForestBinary <- coef(rxFastForestBinary)
    checkEquals(names(coefFastForestBinary), c("Petal.Width", "Petal.Length", "Sepal.Length", "Sepal.Width"))
    checkEquals(as.integer(100 * unlist(coefFastForestBinary) + 1e-7), c(100, 99, 36, 30))
    checkEquals(sumFastForestBinary$digits, 6)
    out3 <- capture.output(print(sumFastForestBinary))
    CheckStringsFound(out3, c("Call:", "Data: trainIris", "Sepal.Width"))
		
    sumNeuralNetBinary <- summary(rxNeuralNetBinary)
    checkEquals(as.integer(100*sumNeuralNetBinary$summary$Weights_0), 
        c(-1, 0, -2, 0, 2, 5, 3, 1, 0, -2, -5, 3))
	out4 <- capture.output(print(sumNeuralNetBinary))
    CheckStringsFound(out4, c("Call:", "Weights_0:", "Biases_0:"))
	
    sumOneClassSvm <- summary(rxOneClassSvm)
    coefOneClassSvm <- coef(rxOneClassSvm)
    checkEquals(as.integer(100*coefOneClassSvm), 
        c(61, 100, 100,  95, 100, 100, 100, 100, 100,  43))
	out5 <- capture.output(print(sumOneClassSvm))
    CheckStringsFound(out5, c("Call:", "Coefficients:", "Support vectors:"))
	
    sumLogitMulti <- summary(logitMulti)
    coefLogitMulti <- coef(logitMulti)
    checkEquals(as.integer(100*unlist(coefLogitMulti)), 
            c( 189,   26, -215, -252, -225,   22,  -21,  218,  136))
	out6 <- capture.output(print(sumLogitMulti))
    CheckStringsFound(out6, c("Call:", "Data: trainIris", "Sepal.Width"))
		
    sumNeuralNetMulti <- summary(rxNeuralNetMulti)
    checkEquals(as.integer(100*sumNeuralNetMulti$summary$Weights_0), 
        c(-1, 0, -3, 0, 2, 4, 4, 2, 0, -3, -3, 5))
	out7 <- capture.output(print(sumNeuralNetMulti))
    CheckStringsFound(out7, c("Call:", "Weights_0:", "Biases_0:"))
		
    sumFastTreeReg <- summary(fastTreeReg)
    coefFastTreeReg <- coef(fastTreeReg)
    # FIXME: Don't get consistent results
	#checkEquals(names(coefFastTreeReg), c(  "Temp", "Wind", "Solar.R"))
    #checkEquals(as.integer(100*coefFastTreeReg), c(100, 65, 52))    
	out8 <- capture.output(print(sumFastTreeReg))
    CheckStringsFound(out8, "Call:")
	
    sumFastForestReg <- summary(rxFastForestReg)
    coefFastForestReg <- coef(rxFastForestReg)
	#checkEquals(names(coefFastForestReg), c("Temp", "Wind", "Solar.R"))
    #checkEquals(as.integer(100*coefFastForestReg), c(100, 87, 33))     
	out9 <- capture.output(print(sumFastForestReg))
    CheckStringsFound(out9, c("Call:", "Data: trainAir"))
		
    sumNeuralNetReg <- summary(rxNeuralNetReg)
	out10 <- capture.output(print(sumNeuralNetReg))
    CheckStringsFound(out10, "Call:")
	#checkEquals(out10[64], "$Biases_1")		
}

"test.mlModel.methods.summary" <- function()
{
    if (rxIsExpressEdition())
        DEACTIVATED("Not running multi-thread testing for express edition.")

    oldWidth <- options(width = 120)
    on.exit(options(oldWidth), add = TRUE)
    myIris <- iris
    myIris$IsVersi <- myIris$Species == 'versicolor'
    trainRows <- c(1:30, 51:80, 101:130)
    testRows = !(1:150 %in% trainRows)
    trainIris <- myIris[trainRows,]
    testIris <- myIris[testRows,]
    irisFormula <- IsVersi~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
       
    # rxLogisticRegression binary classification
    logitBinary <- rxLogisticRegression(irisFormula, data = trainIris)
    logitBinaryWithStats <- rxLogisticRegression(irisFormula, data = trainIris, showTrainingStats = TRUE)

    logitRSR <- rxLogit(irisFormula, data = trainIris)

    # rxFastTrees binary classification
    fastTreeBinary <- rxFastTrees(irisFormula, data = trainIris)
       
    # rxFastForest binary classification 
    rxFastForestBinary <- rxFastForest(irisFormula, data = trainIris)

    # rxNeuralNet binary classification 
    rxNeuralNetBinary <- rxNeuralNet(irisFormula, data = trainIris,
       numHiddenNodes = 3)
      
    ##########################################################
    # Anomaly Detection
    ##########################################################  

    # Setting up the data
       
    trainIrisA <- trainIris
    trainIrisA$isIris <- 1
    testIrisA <- testIris
    irisVars <- c("Sepal.Length", "Sepal.Width",  "Petal.Length", "Petal.Width")
    testIrisA <- testIris[, irisVars]
    testIrisA$isIris <- 1
        
    daffodils <- data.frame(
            Sepal.Length = c(2.5, 2.6),
            Sepal.Width = c(.75, .9),
            Petal.Length = c(2.5, 2.5),
            Petal.Width = c(.8, .7),
            isIris = 0)
    testIrisA <- rbind(testIrisA, daffodils)  
          
    # rxOneClassSvm anomaly detection
    ocSvmFormula = isIris~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width 
    rxOneClassSvm <- rxOneClassSvm(formula = ocSvmFormula,
            data = trainIrisA)       

    ###########################################################
    # Multi-classification
    ########################################################### 
     
    multiFormula <- Species ~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
     
    # multiClass with rxLogisticRegression
    logitMulti <- rxLogisticRegression(multiFormula, type = "multiClass", 
        data = trainIris)


    # multiClass with rxNeuralNet
    rxNeuralNetMulti <- rxNeuralNet(multiFormula, type = "multiClass", 
        numHiddenNodes = 3, data = trainIris)

    #######################################################################
    # Regression
    #######################################################################

    # Use the built-in data set 'airquality'
    set.seed(10)
    
    DF <- airquality[!is.na(airquality$Ozone), ]	
    DF$Ozone <- as.numeric(DF$Ozone)
    randomSplit <- rnorm(nrow(DF))
    trainAir <- DF[randomSplit >= 0,]
    testAir <- DF[randomSplit < 0,]
    airFormula <- Ozone ~ Solar.R + Wind + Temp       

    # Regression Fast Tree
    fastTreeReg <- rxFastTrees(airFormula, type = "regression", 
        data = trainAir, randomSeed = 37)  
    # Regression Fast Forest
    rxFastForestReg <- rxFastForest(airFormula, type = "regression", 
        data = trainAir, randomSeed = 37)
    # Regression Neural Net
    rxNeuralNetReg <- rxNeuralNet(airFormula, type = "regression", 
        data = trainAir)

    # Tests for summary and coef
    sumLogitBinary <- summary(logitBinary, digits = 5)
    coefLogitBinary <- coef(logitBinary)
    checkEquals(names(coefLogitBinary), c("(Bias)", "Sepal.Width", "Petal.Length"))
    checkEquals(as.integer(100 * coefLogitBinary), c(-56, -59, 50))
    out1 <- capture.output(print(sumLogitBinary))
    CheckStringsFound(out1, c("Call:", "Data: trainIris", "Sepal.Width"))

    # Tests for AIC
    sumLogitBinaryWithStats <- summary(logitBinaryWithStats)
    aicFromObject <- sumLogitBinaryWithStats$summary$AIC
    aicFromFunctionCall <- AIC(logitBinaryWithStats)
    aicFromSummaryFunctionCall <- AIC(sumLogitBinaryWithStats)
    checkEquals(aicFromObject, aicFromFunctionCall)
    checkEquals(aicFromObject, aicFromSummaryFunctionCall)

    # Tests for deviance
    sumLogitBinaryWithStats <- summary(logitBinaryWithStats)
    devianceFromObject <- sumLogitBinaryWithStats$summary$`Residual Deviance`
    devianceFromFunctionCall <- deviance(logitBinaryWithStats)
    devianceFromSummaryFunctionCall <- deviance(sumLogitBinaryWithStats)
    checkEquals(devianceFromObject, devianceFromFunctionCall)
    checkEquals(devianceFromObject, devianceFromSummaryFunctionCall)

    # Verify AIC with k = 0 equals deviance
    checkEquals(AIC(logitBinaryWithStats, k = 0), deviance(logitBinaryWithStats))

    sumFastTreeBinary <- summary(fastTreeBinary, digits = 5)
    coefFastTreeBinary <- coef(fastTreeBinary)
    checkEquals(names(coefFastTreeBinary), c("Petal.Width", "Petal.Length", "Sepal.Length", "Sepal.Width"))
    checkEquals(as.integer(100 * unlist(coefFastTreeBinary) + 1e-7), c(100, 88, 20, 19))
    checkEquals((1e05 * signif(as.numeric(unlist(sumFastTreeBinary$summary)), digits=sumFastTreeBinary$digits)) %% 1, c(0, 0, 0, 0))
    out2 <- capture.output(print(sumFastTreeBinary))
    CheckStringsFound(out2, c("Call:", "Data: trainIris", "Sepal.Width"))

    sumFastForestBinary <- summary(rxFastForestBinary, digits = 6)
    coefFastForestBinary <- coef(rxFastForestBinary)
    checkEquals(names(coefFastForestBinary), c("Petal.Width", "Petal.Length", "Sepal.Length", "Sepal.Width"))
    checkEquals(as.integer(100 * unlist(coefFastForestBinary) + 1e-7), c(100, 99, 36, 30))
    checkEquals((1e06 * signif(as.numeric(unlist(sumFastForestBinary$summary)), digits=sumFastForestBinary$digits)) %% 1, c(0, 0, 0, 0))
    out3 <- capture.output(print(sumFastForestBinary))
    CheckStringsFound(out3, c("Call:", "Data: trainIris", "Sepal.Width"))
		
    sumNeuralNetBinary <- summary(rxNeuralNetBinary)
    checkEquals(as.integer(100*sumNeuralNetBinary$summary$Weights_0), 
        c(-1, 0, -2, 0, 2, 5, 3, 1, 0, -2, -5, 3))
	out4 <- capture.output(print(sumNeuralNetBinary))
    CheckStringsFound(out4, c("Call:", "Weights_0:", "Biases_0:"))
	
    sumOneClassSvm <- summary(rxOneClassSvm)
    coefOneClassSvm <- coef(rxOneClassSvm)
    checkEquals(as.integer(100*coefOneClassSvm), 
        c(61, 100, 100,  95, 100, 100, 100, 100, 100,  43))
	out5 <- capture.output(print(sumOneClassSvm))
    CheckStringsFound(out5, c("Call:", "Coefficients:", "Support vectors:"))
	
    sumLogitMulti <- summary(logitMulti)
    coefLogitMulti <- coef(logitMulti)
    checkEquals(as.integer(100 * coefLogitMulti),
            c(189, 26, -215, -252, -225, 23, -21, 218, 136), tolerance = 0.01)
	out6 <- capture.output(print(sumLogitMulti))
    CheckStringsFound(out6, c("Call:", "Data: trainIris", "Sepal.Width"))
		
    sumNeuralNetMulti <- summary(rxNeuralNetMulti)
    checkEquals(as.integer(100*sumNeuralNetMulti$summary$Weights_0), 
        c(-1, 0, -3, 0, 2, 4, 4, 2, 0, -3, -3, 5))
	out7 <- capture.output(print(sumNeuralNetMulti))
    CheckStringsFound(out7, c("Call:", "Weights_0:", "Biases_0:"))
		
    sumFastTreeReg <- summary(fastTreeReg)
    coefFastTreeReg <- coef(fastTreeReg)
    # FIXME: Don't get consistent results
	#checkEquals(names(coefFastTreeReg), c(  "Temp", "Wind", "Solar.R"))
    #checkEquals(as.integer(100*coefFastTreeReg), c(100, 65, 52))    
	out8 <- capture.output(print(sumFastTreeReg))
    CheckStringsFound(out8, "Call:")
	#checkTrue(grepl("Data: trainAir", out8[6]))
    #checkTrue(grepl("Wind", out8[9]))  	    
	
    sumFastForestReg <- summary(rxFastForestReg)
    coefFastForestReg <- coef(rxFastForestReg)
	#checkEquals(names(coefFastForestReg), c("Temp", "Wind", "Solar.R"))
    #checkEquals(as.integer(100*coefFastForestReg), c(100, 87, 33))     
	out9 <- capture.output(print(sumFastForestReg))
    CheckStringsFound(out9, c("Call:", "Data: trainAir"))
    #checkTrue(grepl("Wind", out9[10]))  	    
		
    sumNeuralNetReg <- summary(rxNeuralNetReg)
	out10 <- capture.output(print(sumNeuralNetReg))
    CheckStringsFound(out10, "Call:")
	#checkEquals(out10[64], "$Biases_1")	    
}

"utils.run.ExpressEdition" <- function(testFunc) {
    # Whether the test runner was already in Express Edition
    wasExpressEdition = rxIsExpressEdition()
    # Set to run this test under Express Edition
    if (!wasExpressEdition)
        rxOptions(isExpressEdition = TRUE)
    # Verifies that we are really running under Express Edition.
    checkTrue(rxIsExpressEdition())
    tryCatch(do.call(testFunc, list()), finally = 
             {
                 # Restore original test runner setting regardless of whether
                 # test has passed or failed.
                 # Would be better to get rid of this if RUnit support
                 # test initializers and finalizers.
                 rxOptions(isExpressEdition = wasExpressEdition)
                 # Verify that the restoration of Express Edition setting 
                 # is successful. 
                 checkEquals(rxIsExpressEdition(), wasExpressEdition)
             })
}

