I use cplex
to solve the travelling salesman problem (TSP).
Given that if x[i][j]=1
, then the path goes from the city i to the city j, otherwise, ther is no path between these cities.
The corresponding matrix:
IloNumVar[][] x = new IloNumVar[n][];
for(int i = 0; i < n; i++){
x[i] = cplex.boolVarArray(n);
}
When cplex
finishes solving, I want to get the values of x
like this:
if(cplex.solve()){
double[][] var = new double[n][n];
for(int i = 0; i<x.length; i++){
for(int j = 0 ; j < x[i].length; j ++){
var[i][j] = cplex.getValue(x[i][j]);
if(var[i][j] ==1){
System.out.print(i + " "+ j);
}
}
}
}
but it gives an error. I will appreciate anyone who can give some advice. the error is in :
var[i][j] = cplex.getValue(x[i][j]);
the explain is :
Exception in thread "main" ilog.cplex.IloCplex$UnknownObjectException: CPLEX Error: object is unknown to IloCplex
at ilog.cplex.IloCplex.getValue(IloCplex.java:6495)
the entire code is following:
import java.io.IOException;
import ilog.concert.*;
import ilog.cplex.IloCplex;
public class TSP {
public static void solveMe(int n) throws IloException, IOException{
//random data
double[] xPos = new double[n];
double[] yPos = new double[n];
for (int i = 0; i < n; i ++){
xPos[i] = Math.random()*100;
yPos[i] = Math.random()*100;
}
double[][] c = new double[n][n];
for (int i = 0 ; i < n; i++){
for (int j = 0 ; j < n; j++)
c[i][j] = Math.sqrt(Math.pow(xPos[i]-xPos[j], 2)+ Math.pow(yPos[i]-yPos[j],2));
}
//model
IloCplex cplex = new IloCplex();
//variables
IloNumVar[][] x = new IloNumVar[n][];
for(int i = 0; i < n; i++){
x[i] = cplex.boolVarArray(n);
}
IloNumVar[] u = cplex.numVarArray(n, 0, Double.MAX_VALUE);
//Objective
IloLinearNumExpr obj = cplex.linearNumExpr();
for(int i =0 ; i <n ; i++){
for (int j = 0; j< n ;j++){
if(j != i){
obj.addTerm(c[i][j], x[i][j]);
}
}
}
cplex.addMinimize(obj);
//constraints
for(int j = 0; j < n; j++){
IloLinearNumExpr expr = cplex.linearNumExpr();
for(int i = 0; i< n ; i++){
if(i!=j){
expr.addTerm(1.0, x[i][j]);
}
}
cplex.addEq(expr, 1.0);
}
for(int i = 0; i < n; i++){
IloLinearNumExpr expr = cplex.linearNumExpr();
for(int j = 0; j< n ; j++){
if(j!=i){
expr.addTerm(1.0, x[i][j]);
}
}
cplex.addEq(expr, 1.0);
}
for(int i = 1; i < n; i++){
for(int j = 1; j < n; j++){
if(i != j){
IloLinearNumExpr expr = cplex.linearNumExpr();
expr.addTerm(1.0, u[i]);
expr.addTerm(-1.0, u[j]);
expr.addTerm(n-1, x[i][j]);
cplex.addLe(expr, n-2);
}
}
}
//solve mode
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<x.length; i++){
for(int j = 0 ; j < x[i].length; j ++){
System.out.print(cplex.getValue(x[i][j]));
}
}
}
//end
cplex.end();
}
}