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

/**
 * This sample program describes how to use the ODM Java API to build, test and 
 * apply a regression model using the SupportVectorMachine(SVM) algorithm.
 * This program uses the "MINING_DATA_BUILD_V" dataset for building a
 * model to predict customer "AGE".
 * It then tests the model by computing model root mean square error using 
 * "MINING_DATA_TEST_V" dataset. After testing the model
 * it applies the built model on "MINING_DATA_APPLY_V" dataset to predict 
 * customer "AGE".
 * 
 * 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 SVMRDemo 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. Compute root mean square error for the model
      testModel();
      //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
    }
  }

  /**
   * To build a mining model, the build dataset location details and 
   * the mining function settings are required. 
   * In this example, we will build a regression model using the build 
   * dataset "MINING_DATA_BUILD_V" in the user schema, with the 
   * SupportVectorMachine algorithm. This model can be used to predict 
   * customer "AGE". After completing the build 
   * task, the model named "SVMRDemo_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
        SVMRegressionSettings svmAlgo = new SVMRegressionSettings(
          Normalization.minMax,
          KernelFunction.linear,
          0.001f,
          null,  // Standard deviation is not required if kernel function is "gaussian"
          null,  // If complexity factor is null, default value will be computed
          50000000,
          null   // If epsilon is null, default value will be computed
          );
      
        RegressionFunctionSettings mfs =
          RegressionFunctionSettings.create(
                   m_dmsConn,       //DMS Connection
                   svmAlgo,          //SVM algorithm settings
                   pds,             //Build data specification
                   "AGE", //Target column
                   DataPreparationStatus.unprepared //Default preparation status
                   );
      
        //Set inactive attributes by changing the default attribute usage
        mfs.adjustAttributeUsage(new String[]{"CUST_ID"},AttributeUsage.inactive);
        
        //Set error metric value for the regression function settings
        mfs.setErrorMetric(ErrorMetric.rootMeanSquareError);
        
        mfs.store( m_dmsConn, "SVMRDemo_MFS");
    //3. Create, store & execute Build Task
        MiningBuildTask buildTask = new MiningBuildTask(
                     pds, //Build data specification
                     "SVMRDemo_MFS", //Mining function settings name
                     "SVMRDemo_Model" //Mining model name
                     );
        executeTask(buildTask, "SVMRDemo_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 is successful.");
    } else {//Task failed
      throw new ODMException("It is failed.\nFailure Description: " + 
        taskStatus.getStateDescription() );
    }
    return isTaskSuccess;
  }

  /**
   * To assess root mean square error for the SVM mining model, 
   * the test dataset location details and input model are required. 
   * In this example, we will test SVMRDemo_Model using "MINING_DATA_TEST_V". 
   * After completing the test task, SVMRDemo_TestResults object will be  
   * created in the DMS. regression test results have root mean square error. 
   */
  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
      RegressionTestTask testTask = new RegressionTestTask(
                   pds, //test data specification
                   "SVMRDemo_Model", //Name of the model to be tested
                   "SVMRDemo_TestResults" ); //Test results name
      //Store & execute the task
      boolean isTaskSuccess = executeTask(testTask, "SVMRDemo_TestTask"); 
      if( isTaskSuccess ) {
        //Restore & display test results
        RegressionTestResult testResult = 
          RegressionTestResult.restore(m_dmsConn, "SVMRDemo_TestResults");
        System.out.println(testResult.toString());
      }
  }

 
  /**
   * To apply a mining model to a data, apply dataset location details, 
   * input model and the output table location details are required. 
   * In this example, we apply the SVMRDemo_Model to the "MINING_DATA_APPLY_V"  
   * dataset to predict customer "AGE".
   * After completing the apply task, SVMRDemo_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 the ApplySourceAttributeItem object to the MiningApplyOutput
        mao.addItem(m_ApplySourceAttributeItem);
        //Output table location details
        LocationAccessData outputTable =
                 new LocationAccessData("SVMRDemo_Apply_Output_Table", DATA_SCHEMA_NAME);      
    //3. Create, store & execute apply Task
        MiningApplyTask applyTask = new MiningApplyTask(
                     pds, //test data specification
                     "SVMRDemo_Model", //Input model name
                     mao, //MiningApplyOutput object
                     outputTable, //Apply output table location details
                     "SVMRDemo_ApplyResults" //Apply results name
                     );
        //Store & execute the task
        boolean isTaskSuccess = executeTask(applyTask, "SVMRDemo_ApplyTask"); 
        if( isTaskSuccess ) {
          //Restore & display apply results
          MiningApplyResult applyResult = 
            MiningApplyResult.restore(m_dmsConn, "SVMRDemo_ApplyResults");
          System.out.println(applyResult.toString());
        }
  }

  /**
   * Cleanup the previously created objects if any. 
   */
  public static void cleanup() throws ODMException, SQLException
  {
    //Remove the MiningFunctionSettings
    try {
      RegressionFunctionSettings.remove(m_dmsConn, "SVMRDemo_MFS");
    }catch(Exception anyExp1) { }//Ignore
    //Remove the MiningBuildTask
    try {
      MiningBuildTask.remove(m_dmsConn, "SVMRDemo_BuildTask");
    }catch(Exception anyExp2) { }//Ignore
    //Remove the MiningModel
    try {
      MiningModel.remove(m_dmsConn, "SVMRDemo_Model");
    }catch(Exception anyExp3) { }//Ignore
    //Remove the RegressionTestTask
    try {
      RegressionTestTask.remove(m_dmsConn, "SVMRDemo_TestTask");
    }catch(Exception anyExp4) { }//Ignore
    //Remove the RegressionTestResults
    try {
      RegressionTestResult.remove(m_dmsConn, "SVMRDemo_TestResults");
    }catch(Exception anyExp5) { }//Ignore
    //Remove the MiningApplyTask
    try {
      MiningApplyTask.remove(m_dmsConn, "SVMRDemo_ApplyTask");
    }catch(Exception anyExp6) { }//Ignore
    //Remove the MiningApplyResult and apply output table
    try {
      MiningApplyResult.remove(m_dmsConn, "SVMRDemo_ApplyResults", true);
    }catch(Exception anyExp7) { }//Ignore    
  }
}
