// Copyright (c) 2001, 2003, Oracle Corporation.  All rights reserved.  
// File: ABNDemo.java

/**
 * This sample program describes how to use the ODM Java API to build, test 
 * and apply a classification model using the AdaptiveBayesNetwork(ABN) 
 * algorithm. This program uses the "MINING_DATA_BUILD_V" dataset for building a
 * model to predict which customer should receive an "AFFINITY_CARD".
 * It then tests the model  by computing model accuracy, confusion matrix 
 * and lift results using "MINING_DATA_TEST_V" dataset. After testing the model
 * it applies the built model on "MINING_DATA_APPLY_V" dataset to predict 
 * which customers must receive "AFFINITY_CARD".
 * 
 * NOTE:
 *   Before executing this program you need to provide DB URL, username 
 *   and password in login method and a valid data schema name
 *   by changing the DATA_SCHEMA_NAME constant value in the program.
 */

// Generic Java Imports
import java.io.*;
import java.util.*;
import java.sql.SQLException;

// ODM Imports
import oracle.dmt.odm.*;
import oracle.dmt.odm.data.*;
import oracle.dmt.odm.settings.function.*;
import oracle.dmt.odm.settings.algorithm.*;
import oracle.dmt.odm.task.*;
import oracle.dmt.odm.model.*;
import oracle.dmt.odm.result.*;

public class ABNDemo extends Object {

  private static DataMiningServer m_dms = null;
  private static oracle.dmt.odm.Connection m_dmsConn = null;
  //provide schema name that has the data tables/views
  private static final String DATA_SCHEMA_NAME = "schema name";
  
  public static void main( String args[] ) { 
    try {      
      //1. Login to the Data Mining Server
          //Create a DMS object
          m_dms = new DataMiningServer(
            "put DB URL here", //JDBC URL jdbc:oracle:thin:@<Host name>:<Port>:<SID>
            "user name", //User Name
            "password" //Password 
          );
          //Login to the DMS and create a DMS Connection
          m_dmsConn = m_dms.login();
          //Remove the objects to avoid name conflicts
          cleanup();
      //2. Build a model
      buildModel();
      //3. Test to compute accuracy and confusion matrix for the model
      testModel();
      //4. Compute lift for the model
      computeLift();
      //5. Apply the model
      applyModel();
    } catch(Exception anyExp) {
      anyExp.printStackTrace(System.out);
    } finally {
      try {
      //6. Logout from the Data Mining Server
      m_dms.logout(m_dmsConn);
      } catch(Exception anyExp1) { }//Ignore
    }
  }

  /**
   * This method builds the mining model, build operation requires the training 
   * dataset location details and the mining function settings. 
   * In this example, we will build a classification model using the 
   * build dataset "MINING_DATA_BUILD_V" in the user schema, with the  
   * AdaptiveBayesNetwork algorithm. This model can be used to predict which  
   * customer should receive an "AFFINITY_CARD". After completing the build  
   * task, the model named "ABNDemo_Model" will be created in the DMS.
   */
  public static void buildModel() throws ODMException, SQLException, IOException 
  {
    //1. Create PhysicalDataSpecification
        LocationAccessData lad = new LocationAccessData( 
                                       "MINING_DATA_BUILD_V", //Build Table Name
                                       DATA_SCHEMA_NAME //Schema Name
                                     );
        PhysicalDataSpecification pds = 
          new NonTransactionalDataSpecification( lad );
    //2. Create & Store Mining Function Settings
        AdaptiveBayesNetworkSettings abnAlgo = //Use default settings
          new AdaptiveBayesNetworkSettings();//Refer javadoc for custom settings
        ClassificationFunctionSettings mfs =
          ClassificationFunctionSettings.create(
                   m_dmsConn,       //DMS Connection
                   abnAlgo,         //ABN algorithm settings
                   pds,             //Build data specification
                   "AFFINITY_CARD", //Target column
                   AttributeType.categorical, //Default attribute type
                   DataPreparationStatus.unprepared //Default preparation status
                   );
        //Set inactive attributes by changing the default attribute usage
        mfs.adjustAttributeUsage(new String[]{"CUST_ID"},AttributeUsage.inactive);
        mfs.store( m_dmsConn, "ABNDemo_MFS");
    //3. Create, store & execute Build Task
        MiningBuildTask buildTask = new MiningBuildTask(
                     pds, //Build data specification
                     "ABNDemo_MFS", //Mining function settings name
                     "ABNDemo_Model" //Mining model name
                     );
        executeTask(buildTask, "ABNDemo_BuildTask" );
  }

  /**
   * This method stores the given task with the specified name in the DMS 
   * and submits the task for asynchronous execution in the DMS. After 
   * completing the task successfully it returns true. If there is a task 
   * failure, then it prints error description and returns false.
   * 
   * @param taskObj task object
   * @param taskName name of the task
   * 
   * @return boolean returns true when the task is successful
   */
  public static boolean executeTask(MiningTask taskObj, String taskName)
    throws ODMException, SQLException {
    boolean isTaskSuccess = false;
    taskObj.store(m_dmsConn, taskName); //Store the task
    taskObj.execute(m_dmsConn); //Submit the task for asynchronous execution
    System.out.print(taskName + " is started, please wait. ");
    //Wait for completion of the task
    MiningTaskStatus taskStatus = taskObj.waitForCompletion(m_dmsConn);
    //Check the status of the task after completion
    isTaskSuccess = taskStatus.getTaskState().equals(MiningTaskState.success);
    if( isTaskSuccess ) {
      //Task completed successfully
      System.out.println("It completed successfully.");
    } else {//Task failed
      throw new ODMException("It is failed.\nFailure Description: " + 
        taskStatus.getStateDescription() );
    }
    return isTaskSuccess;
  }

  /**
   * This method tests the mining model, it assess accuracy & compute  
   * a confusion matrix for the ABN mining model. The test dataset location 
   * details and input model are required for this operation.
   * In this example, we will test "ABNDemo_Model" using "MINING_DATA_TEST_V". 
   * After completing the test task, "ABNDemo_TestResults" object will be  
   * created in the DMS. Classification test results have both the accuracy and 
   * confusion matrix.
   */
  public static void testModel() throws ODMException, SQLException, IOException 
  {
    //1. Create PhysicalDataSpecification
      LocationAccessData lad = new LocationAccessData( 
                                 "MINING_DATA_TEST_V", //Test table/view Name
                                 DATA_SCHEMA_NAME ); //Schema Name
      PhysicalDataSpecification pds = 
        new NonTransactionalDataSpecification( lad );
    //2. Create, store & execute Test Task
      ClassificationTestTask testTask = new ClassificationTestTask(
                   pds, //test data specification
                   "ABNDemo_Model", //Name of the model to be tested
                   "ABNDemo_TestResults" ); //Test results name
      //Store & execute the task
      boolean isTaskSuccess = executeTask(testTask, "ABNDemo_TestTask"); 
      if( isTaskSuccess ) {
        //Restore & display test results
        ClassificationTestResult testResult = 
          ClassificationTestResult.restore(m_dmsConn, "ABNDemo_TestResults");
        System.out.println(testResult.toString());
      }
  }

  /**
   * This method compute lift of the mining model on a test dataset. The test  
   * dataset location details and input model are required for this operation. 
   * In this example, we compute lift using "ABNDemo_Model" and the same dataset
   * used for testing the model i.e.,"MINING_DATA_TEST_V". 
   * After completing the lift task, "ABNDemo_LiftResults" object will be created 
   * in the DMS. A Lift results object provides at each quantile: quantile lift,
   * cumulative lift, target density, cumulative target density.
   */
  public static void computeLift() throws ODMException, SQLException, IOException
  {
    //1. Create PhysicalDataSpecification
      LocationAccessData lad = new LocationAccessData( 
                                     "MINING_DATA_TEST_V", //Test table/view Name
                                     DATA_SCHEMA_NAME //Schema Name
                                   );
      PhysicalDataSpecification pds = 
        new NonTransactionalDataSpecification( lad );
    //2. Create, store & execute lift Task
      Category positiveCategory = new Category(
        "Receive Affinity Card", //display name for positive target value
        "1", //positive target value
        DataType.intType);//data type of the positive target value        
      MiningLiftTask liftTask = new MiningLiftTask(
          pds, // Physical Data Spec for input data
          10, // Number of quantiles to be used
          positiveCategory, // Positive target value
          "ABNDemo_Model", //Name of the model to be tested
          "ABNDemo_LiftResults" //Lift results name
      );
      //Store & execute the task
      boolean isTaskSuccess = executeTask(liftTask, "ABNDemo_LiftTask"); 
      if( isTaskSuccess ) {
        //Restore & display lift results
        MiningLiftResult liftResult = 
          MiningLiftResult.restore(m_dmsConn, "ABNDemo_LiftResults");
        System.out.println(liftResult.toString());
      }
  }

  /**
   * This method apply a mining model to a data. The apply dataset location 
   * details, input model and the output table location details are required
   * for this operation. 
   * In this example, we apply the "ABNDemo_Model" to the "MINING_DATA_APPLY_V"  
   * dataset to predict which customers receive an "AFFINITY_CARD".
   * After completing the apply task, "ABNDemo_ApplyResults" object will be  
   * created in the DMS and an apply output table will be created at the  
   * specfied location.
   */
  public static void applyModel() throws ODMException, SQLException, IOException 
  {
    //1. Create PhysicalDataSpecification
        LocationAccessData lad = new LocationAccessData( 
                                 "MINING_DATA_APPLY_V", //Apply table/view Name
                                 DATA_SCHEMA_NAME //Schema Name
                               );
        PhysicalDataSpecification pds = 
          new NonTransactionalDataSpecification( lad );
    //2. Create MiningApplyOutput & apply output table/view details
        // Create MiningApplyOutput object
        MiningApplyOutput mao = MiningApplyOutput.createDefault();
        // Add all the source attributes to be returned with the scored result.
        // In this example, attribute "CUST_ID" from the source table will be 
        // returned with the result aliased as "CUST_ID"
        MiningAttribute sourceAttribute =
                  new MiningAttribute("CUST_ID", DataType.intType,
                                      AttributeType.notApplicable);
        Attribute destinationAttribute = new Attribute("CUST_ID", DataType.intType);

        ApplySourceAttributeItem m_ApplySourceAttributeItem =
           new ApplySourceAttributeItem(sourceAttribute,destinationAttribute);
        // Add a source destination mapping
        mao.addItem(m_ApplySourceAttributeItem);
        //Output table location details
        LocationAccessData outputTable =
                 new LocationAccessData("ABNDemo_Apply_Output_Table", 
                  DATA_SCHEMA_NAME );      
    //3. Create, store & execute apply Task
        MiningApplyTask applyTask = new MiningApplyTask(
                     pds, //test data specification
                     "ABNDemo_Model", //Input model name
                     mao, //MiningApplyOutput object
                     outputTable, //Apply output table location details
                     "ABNDemo_ApplyResults" //Apply results name
                     );
        //Store & execute the task
        boolean isTaskSuccess = executeTask(applyTask, "ABNDemo_ApplyTask"); 
        if( isTaskSuccess ) {
          //Restore & display apply results
          MiningApplyResult applyResult = 
            MiningApplyResult.restore(m_dmsConn, "ABNDemo_ApplyResults");
          System.out.println(applyResult.toString());
        }
  }

  /**
   * Cleanup the previously created objects if any. 
   */
  public static void cleanup() throws ODMException, SQLException
  {
    //Remove the MiningFunctionSettings
    try {
      ClassificationFunctionSettings.remove(m_dmsConn, "ABNDemo_MFS");
    }catch(Exception anyExp1) { }//Ignore
    //Remove the MiningBuildTask
    try {
      MiningBuildTask.remove(m_dmsConn, "ABNDemo_BuildTask");
    }catch(Exception anyExp2) { }//Ignore
    //Remove the MiningModel
    try {
      MiningModel.remove(m_dmsConn, "ABNDemo_Model");
    }catch(Exception anyExp3) { }//Ignore
    //Remove the ClasificationTestTask
    try {
      ClassificationTestTask.remove(m_dmsConn, "ABNDemo_TestTask");
    }catch(Exception anyExp4) { }//Ignore
    //Remove the ClassificationTestResults
    try {
      ClassificationTestResult.remove(m_dmsConn, "ABNDemo_TestResults");
    }catch(Exception anyExp5) { }//Ignore
    //Remove the MiningLiftTask
    try {
      MiningLiftTask.remove(m_dmsConn, "ABNDemo_LiftTask");
    }catch(Exception anyExp6) { }//Ignore
    //Remove the MiningLiftResult
    try {
      MiningLiftResult.remove(m_dmsConn, "ABNDemo_LiftResults");
    }catch(Exception anyExp7) { }//Ignore
    //Remove the MiningApplyTask
    try {
      MiningApplyTask.remove(m_dmsConn, "ABNDemo_ApplyTask");
    }catch(Exception anyExp8) { }//Ignore
    //Remove the MiningApplyResult and apply output table
    try {
      MiningApplyResult.remove(m_dmsConn, "ABNDemo_ApplyResults", true);
    }catch(Exception anyExp9) { }//Ignore    
  }
}