The Java Interface to CPLEX
The use of CPLEX in Java is based around the class IloCplex (documented here
). The basic idea is that you create an IloCplex object for your optimization problem, then add variables, the objective, and constraints using methods in the class IloCplex. The IloCplex object can produce IloNumVar
objects and their subclass IloIntVar
objects, when are then used as arguments to further methods from IloCplex to make the objective and constraints. We now summarize the methods of IloCplex which will be of use to us:
Using CPLEX in TspIpSolver
First, we need to set up the objective and the degree constraints. First, add the following fields to the class
private IloCplex cplex; private TspInstance<V,E> tspInstance; private final ImmutableBiMap<E,IloIntVar> edgeVariables;
and initialize them, as below.
public TspIpSolver(TspInstance<V,E> tspInstance, EnumSet<Option> options) throws IloException{
this.options = options;
this.tspInstance = tspInstance;
this.cplex = new IloCplex();
UndirectedGraph<V,E> graph = tspInstance.getGraph(); //for convenience, we will be using this a lot
this.edgeVariables = Util.makeBinaryVariables(cplex, graph.getEdges());
//the degree constraints
//the objective
}
The constraints and objective still need to be added to the cplex object. Try adding them yourself! The following methods should be useful for making the constraints:
- From
Util,public static <T> IloLinearIntExpr integerSum(IloCplex cplex, BiMap<T,IloIntVar> variables, Iterable<T> set)- For each element
Unknown macro: {mathinline}of
e
set, finds the corresponding variableUnknown macro: {mathinline}and returnsx_e
Unknown macro: {mathinline}\sum_{e \in \text{set}} x_e
- For each element
- From
IloCplex,public IloRange addEq(IloNumExpr e, double v)- Adds the equality constraint e = v
- From
UndirectedGraph<V,E>,public Collection<E> getIncidentEdges(V vertex)- returns the edges of the graph that are incident to vertex
If you are unfamiliar with Java, consider viewing the solution for the constraint, then trying the objective yourself.
Solution
For the objective, we need the functions:
- From
Util,public static <T> IloLinearNumExpr sum(IloCplex cplex, BiMap<T,IloIntVar> variables, Iterable<T> set, Function<? super T,? extends Number> coefficients)- For every element
Unknown macro: {mathinline}of
e
set, gets the corresponding variableUnknown macro: {mathinline}fromx_e
variablesand the numberUnknown macro: {mathinline}fromd_e
coefficientsand returns an expression forUnknown macro: {mathinline}.\sum_{e \in \text{set}} d_e x_e
- For every element
Solution