Accessing Solution Information

If a solution was found with the solve() method, it can be accessed and then queried using a variety of methods. The objective function can be accessed by calling

    double objval = cplex.getObjValue();

The values of individual modeling variables for the solution are accessed by calling methods IloCplex.getValue(), for example:

    double x1 = cplex.getValue(var1);

Frequently, solution values for an array of variables are needed. Rather than having to implement a loop to query the solution values variable by variable, the method IloCplex.getValues() is provided to do so with only one function call:

    double[] x = cplex.getValues(vars);

Similarly, slack values can be queried for the constraints in the active model using methods IloCplex.getSlack() or IloCplex.getSlacks().

Printing the Solution to the Diet Model

This can now be applied to solving the diet problem we discussed earlier, and printing its solution.

IloCplex cplex = new IloCplex();

IloNumVar[] Buy = new IloNumVar[nFoods];

if ( byColumn ) buildModelByColumn(cplex, data, Buy, varType);

else buildModelByRow (cplex, data, Buy, varType);

// Solve model

if ( cplex.solve() ) {

System.out.println();

System.out.println("Solution status = " + cplex.getStatus());

System.out.println();

System.out.println(" cost = " + cplex.getObjValue());

for (int i = 0; i < nFoods; i++) {

System.out.println(" Buy" + i + " = " +

cplex.getValue(Buy[i]));

}

System.out.println();

}

The program extract starts by creating a new IloCplex object and passing it, along with the raw data in another object, either to the method buildModelByColumn() or buildModelByRow(). The array of variables returned by it is saved as array Buy. Then the method solve() is called to optimize the active model and, upon success, solution information is printed.


Previous Page: Solving the Model  Return to Top Next Page: Choosing an Optimizer