# file: svm_two_class_metrics_dense_batch.py
#===============================================================================
# Copyright 2014-2017 Intel Corporation All Rights Reserved.
#
# The source code,  information  and material  ("Material") contained  herein is
# owned by Intel Corporation or its  suppliers or licensors,  and  title to such
# Material remains with Intel  Corporation or its  suppliers or  licensors.  The
# Material  contains  proprietary  information  of  Intel or  its suppliers  and
# licensors.  The Material is protected by  worldwide copyright  laws and treaty
# provisions.  No part  of  the  Material   may  be  used,  copied,  reproduced,
# modified, published,  uploaded, posted, transmitted,  distributed or disclosed
# in any way without Intel's prior express written permission.  No license under
# any patent,  copyright or other  intellectual property rights  in the Material
# is granted to  or  conferred  upon  you,  either   expressly,  by implication,
# inducement,  estoppel  or  otherwise.  Any  license   under such  intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing,  you may not remove or alter this
# notice or  any  other  notice   embedded  in  Materials  by  Intel  or Intel's
# suppliers or licensors in any way.
#===============================================================================

#
# !  Content:
# !    Python example of two-class support vector machine (SVM) quality metrics
# !
# !*****************************************************************************

#
## <a name="DAAL-EXAMPLE-PY-SVM_TWO_CLASS_QUALITY_METRIC_SET_BATCH"></a>
## \example svm_two_class_metrics_dense_batch.py
#

from os.path import join as jp, abspath, realpath, split
from os import environ

from daal.algorithms.classifier.quality_metric import binary_confusion_matrix
from daal.algorithms import svm
import daal.algorithms.svm.training
import daal.algorithms.svm.prediction
import daal.algorithms.svm.quality_metric_set
from daal.algorithms.kernel_function.linear import Batch as kf_l_Batch
from daal.algorithms import classifier
import daal.algorithms.classifier.prediction
import daal.algorithms.classifier.training
from daal.data_management import (
    DataSourceIface, FileDataSource, readOnly, BlockDescriptor_Float64,
    HomogenNumericTable, NumericTableIface, MergedNumericTable
)

import inspect
import sys
utils_folder = realpath(abspath(jp(split(inspect.getfile(inspect.currentframe()))[0], "..")))
if utils_folder not in sys.path:
    sys.path.insert(0, utils_folder)
from utils import printNumericTables, printNumericTable

# Input data set parameters
DATA_PREFIX = jp('..', 'data', 'batch')
trainDatasetFileName = jp(DATA_PREFIX, 'svm_two_class_train_dense.csv')
testDatasetFileName = jp(DATA_PREFIX, 'svm_two_class_test_dense.csv')

nFeatures = 20

# Parameters for the SVM kernel function
kernel = kf_l_Batch()

# Model object for the SVM algorithm
trainingResult = None
predictionResult = None
qualityMetricSetResult = None

predictedLabels = None
groundTruthLabels = None


def trainModel():
    global trainingResult

    # Initialize FileDataSource<CSVFeatureManager> to retrieve the input data from a .csv file
    trainDataSource = FileDataSource(
        trainDatasetFileName, DataSourceIface.notAllocateNumericTable,
        DataSourceIface.doDictionaryFromContext
    )

    # Create Numeric Tables for training data and labels
    trainData = HomogenNumericTable(nFeatures, 0, NumericTableIface.notAllocate)
    trainGroundTruth = HomogenNumericTable(1, 0, NumericTableIface.notAllocate)
    mergedData = MergedNumericTable(trainData, trainGroundTruth)

    # Retrieve the data from the input file
    trainDataSource.loadDataBlock(mergedData)

    # Create an algorithm object to train the SVM model
    algorithm = svm.training.Batch()

    algorithm.parameter.kernel = kernel
    algorithm.parameter.cacheSize = 600000000

    # Pass a training data set and dependent values to the algorithm
    algorithm.input.set(classifier.training.data, trainData)
    algorithm.input.set(classifier.training.labels, trainGroundTruth)

    # Build the SVM model and get the algorithm results
    trainingResult = algorithm.compute()

def testModel():
    global predictionResult, groundTruthLabels

    # Initialize FileDataSource<CSVFeatureManager> to retrieve the input data from a .csv file
    testDataSource = FileDataSource(
        testDatasetFileName, DataSourceIface.doAllocateNumericTable,
        DataSourceIface.doDictionaryFromContext
    )

    # Create Numeric Tables for testing data and labels
    testData = HomogenNumericTable(nFeatures, 0, NumericTableIface.notAllocate)
    groundTruthLabels = HomogenNumericTable(1, 0, NumericTableIface.notAllocate)
    mergedData = MergedNumericTable(testData, groundTruthLabels)

    # Retrieve the data from input file
    testDataSource.loadDataBlock(mergedData)

    # Create an algorithm object to predict SVM values
    algorithm = svm.prediction.Batch()

    algorithm.parameter.kernel = kernel

    # Pass a testing data set and the trained model to the algorithm
    algorithm.input.setTable(classifier.prediction.data, testData)
    algorithm.input.setModel(classifier.prediction.model, trainingResult.get(classifier.training.model))

    # Predict SVM values
    # returns Result class from daal.algorithms.classifier.prediction
    predictionResult = algorithm.compute()


def testModelQuality():
    global predictedLabels, qualityMetricSetResult, groundTruthLabels

    # Retrieve predicted labels
    predictedLabels = predictionResult.get(classifier.prediction.prediction)

    # Create a quality metric set object to compute quality metrics of the SVM algorithm
    qualityMetricSet = svm.quality_metric_set.Batch()

    input = qualityMetricSet.getInputDataCollection().getInput(svm.quality_metric_set.confusionMatrix)

    input.set(binary_confusion_matrix.predictedLabels,   predictedLabels)
    input.set(binary_confusion_matrix.groundTruthLabels, groundTruthLabels)

    # Compute quality metrics and get the quality metrics
    # returns ResultCollection class from svm.quality_metric_set
    qualityMetricSetResult = qualityMetricSet.compute()


def printResults():

    # Print the classification results
    printNumericTables(
        groundTruthLabels, predictedLabels,
        "Ground truth", "Classification results",
        "SVN classification results (first 20 observations):", 20, interval=15, flt64=False
    )

    # Print the quality metrics
    qualityMetricResult = qualityMetricSetResult.getResult(svm.quality_metric_set.confusionMatrix)
    printNumericTable(qualityMetricResult.get(binary_confusion_matrix.confusionMatrix), "Confusion matrix:")

    block = BlockDescriptor_Float64()
    qualityMetricsTable = qualityMetricResult.get(binary_confusion_matrix.binaryMetrics)
    qualityMetricsTable.getBlockOfRows(0, 1, readOnly, block)
    qualityMetricsData = block.getArray().flatten()
    print("Accuracy:      {0:.3f}".format(qualityMetricsData[binary_confusion_matrix.accuracy]))
    print("Precision:     {0:.3f}".format(qualityMetricsData[binary_confusion_matrix.precision]))
    print("Recall:        {0:.3f}".format(qualityMetricsData[binary_confusion_matrix.recall]))
    print("F-score:       {0:.3f}".format(qualityMetricsData[binary_confusion_matrix.fscore]))
    print("Specificity:   {0:.3f}".format(qualityMetricsData[binary_confusion_matrix.specificity]))
    print("AUC:           {0:.3f}".format(qualityMetricsData[binary_confusion_matrix.AUC]))
    qualityMetricsTable.releaseBlockOfRows(block)

if __name__ == "__main__":
    trainModel()
    testModel()
    testModelQuality()
    printResults()
