Skip to content
Advertisement

How to obtain all IloNumVar from IloModeler or IloCplex

we have a client who gives us a IloModeler and we use that to solve the optimization problem doing this:

IloCplex cplex = new IloCplex();
cplex.setModel(IloModeler); 

and, at the end we would like to return to the client a map with all IloNumVar and their value: Map<IloNumVar, Double>.

But the issue is: How can we obtain from the original IloModeler the list of all IloNumVar in order to see their value using the function cplex.getValue(IloNumVar)?

Advertisement

Answer

java.util.Iterator iterator() This method returns an iterator that traverses the objects in the model.

For example with the zoo example

 IloCplex cplexBus = new IloCplex();// decision variables
 IloNumVar nbbus40 = cplexBus.numVar(0, 10000,IloNumVarType.Int,"var nbBus40"); 
 IloNumVar nbbus30 = cplexBus.numVar(0, 10000,IloNumVarType.Int,"var nbBus30");// move at least 300 kids to the zoo
 cplexBus.add(nbbus40);
 cplexBus.add(nbbus30);

 cplexBus.addGe(cplexBus.sum(cplexBus.prod(40,nbbus40), cplexBus.prod(30,nbbus30)),300);// objective : minimize cost = 500*nbbus40+400*nbBus30
 cplexBus.addMinimize(cplexBus.sum(cplexBus.prod(500,nbbus40), cplexBus.prod(400,nbbus30)));cplexBus.solve();System.out.println("nbbus40 : "  +cplexBus.getValue(nbbus40) );
  System.out.println("nbbus30 : "  +cplexBus.getValue(nbbus30) );

  java.util.Iterator it = cplexBus.iterator();
  while (it.hasNext()) {
    Object o = it.next();
    if (o instanceof IloNumVar) {
      System.out.print("Variable :"+((IloNumVar)o).getName()+"n");
    }
  }

gives

 [java] nbbus40 : 6.0
 [java] nbbus30 : 2.0
 [java] Variable :var nbBus40
 [java] Variable :var nbBus30
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement