> Languages and APIs > ILOG Concert Technology for Java Users > Optimizing the Diet Problem in Java > Creating the Optimizer |
Creating the Optimizer |
INDEX PREVIOUS NEXT |
Once the data has been read, the IloCplex
modeler/optimizer is created.
IloCplex cplex = new IloCplex(); IloNumVar[] Buy = new IloNumVar[nFoods]; if ( byColumn ) buildModelByColumn(cplex, data, Buy, varType); else buildModelByRow (cplex, data, Buy, varType); |
Array IloNumVar[] Buy
is also created where the modeling variables will be stored by buildModelByRow
or buildModelByColumn
.
You have already seen a method very similar to buildModelByRow
. This function is called when byColumn
is false, which is the case when the example is executed without the -c
command line option; otherwise, buildModelByColumn
is called. Note that unlike buildModelByRow
, this method requires IloMPModeler
rather than IloModeler
as parameter since modeling by column is not available with IloModeler
.
First, the function creates an empty minimization objective and empty ranged constraints, and adds them to the active model.
IloObjective cost = model.addMinimize(); IloRange[] constraint = new IloRange[nNutrs]; for (int i = 0; i < nNutrs; i++) { constraint[i] = model.addRange(data.nutrMin[i], data.nutrMax[i]); } |
Empty means that they use a 0
expression. After that the variables are created one by one, and installed in the objective and constraints modeling by column. For each variable, a column object must be created. Start by creating a column object for the objective by calling:
IloColumn col = model.column(cost, data.foodCost[j]); |
The column is then expanded to include the coefficients for all the constraints using col.and
with the column objects that are created for each constraint, as in the following loop:
for (int i = 0; i < nNutrs; i++) { col = col.and(model.column(constraint[i], data.nutrPerFood[i][j])); } |
When the full column object has been constructed it is finally used to create and install the new variable using:
Buy[j] = model.numVar(col, data.foodMin[j], data.foodMax[j], type); |
Once the model is created, solving it and querying the solution is straightforward. What remains to be pointed out is the exception handling. In case of an error, ILOG CPLEX will throw an exception of type IloException
or one of its subclasses. Thus the entire ILOG CPLEX program is enclosed in try/catch
statements. The InputDataReader
can throw exceptions of type java.io.IOException
or InputDataReader.InputDataReaderException
.
Since none of these three possible exceptions is handled elsewhere, the main
function ends by catching them and issuing appropriate error messages.
The call to the method cplex.end
frees the license that ILOG CPLEX uses.
Copyright © 1987-2003 ILOG, S.A. All rights reserved. Legal terms. | PREVIOUS NEXT |