Using IBM ILOG Script classes to make clean and reusable code

Explains how to use IBM ILOG Script classes to wrap the calls to external functions.

As shown in this knapsack example, you can wrap the calls to external functions into user-defined IBM ILOG Script classes and methods. Then, it is easy to reuse this algorithm in different OPL models. Although this is standard JavaScript code, the example includes a few useful comments. The IBM ILOG Script wrapping functions are all located in a reusable javaknapsack.mod file.

To wrap the calls to external functions:

  1. Use a function to declare the new algorithm class.
    function Knapsack() {
      IloOplImportJava("../../java/javaknapsack/classes");
     
      this.object = IloOplCallJava("javaknapsack.Knapsack","<init>","");
    
      this.updateInputs = __Knapsack_updateInputs;
      this.solve = __Knapsack_solve;
    };
    

    The content of the function is what the constructor will execute. Part of it is to register methods. Here is an example of implementing a method:

    function __Knapsack_updateInputs(weights,values) {
       this.object.updateInputs(weights,values);
      // The call above is a shortcut as there is no risk of ambiguity.
      // In the general case, if several methods have the same name, you can use:
      //IloOplCallJava(this.object,"updateInputs",
    "(Lilog.opl.IloOplElement;Lilog.opl.IloOplElement;)V", weights, values);
    };
    

    Then, these new IBM ILOG Script class and methods are used in the modified cutstock algorithm, the model of which is the cutstock_ext_main.mod file.

  2. Include the javaknapsack.mod file so that the IBM ILOG Script definition can be used.
    include "javaknapsack.mod";
    
  3. Create the knapsack algorithm.
       // Create a subproblem instance:
       var knapsack = new Knapsack();
    
  4. Write instructions so that at each iteration, the data is updated, the algorithm called, and the solution retrieved.
          knapsack.updateInputs(masterOpl.Size, masterOpl.Duals);
          var solutionValue = knapsack.solve(masterOpl.NewPattern, masterOpl.RollWidth);
    
  5. Run the example.

The rest of the model is the same as the cutstock model that uses a CPLEX algorithm to solve the submodel. See The cutting stock problem.