【CPLEX教程03】java调用cplex求解一个TSP问题模型

00 前言

前面我们已经搭建好cplex的java环境了,相信大家已经跃跃欲试,想动手写几个模型了。今天就来拿一个TSP的问题模型来给大家演示一下吧~

CPLEX系列教程可以关注我们的公众号哦!获取更多精彩消息!

1240

01 TSP建模

关于TSP建模,就不多解释了。以及什么是TSP问题,也不要问我了。直接贴一个现成的模型出来吧。

1240

02 程序框架

整个程序框架如图,app下是调用cplex的主要package。

1240
其中:

  • App.java:程序入口,cplex调用建模求解过程。
  • ConstraintFactory.java:控制子环约束的。
  • FileManager.java:读取instance数据的。

package graph定义了一些变量,在求解过程中需要用到。input是算例,包含100-9000个城市。

03 求解过程

求解过程可以分为以下几步进行:

  1. 定义一个模型
IloCplex model = new IloCplex();
  1. 定义决策变量,boolVar可以返回一个01的bool类型决策变量。
// define variables
IloIntVar[][] x = new IloIntVar[data.size()][data.size()];
for (int i = 0; i < x.length; i++) {
    for (int j = 0; j < x.length; j++) {
        x[i][j] = model.boolVar("X[" + i + ", " + j + "]");
    }
}
  1. 添加约束7-1,addTerm将1*x[i][j]添加进表达式r里面,最终r的取值是里面所有的元素之和,也就是\(1*x[i][1]+1*x[i][2]+...+1*x[i][n]\)
// one has only a city to go, and should
for (int i = 0; i < x.length; i++) {
    IloLinearIntExpr r = model.linearIntExpr();
    for (int j = 0; j < x.length; j++) {
//                      if (i == j)
//                          continue;
        r.addTerm(1, x[i][j]);
    }
    model.addEq(r, 1);
}
  1. 添加约束7-2,原理同上一条。
// one can only arrive to one city at a time, and should
for (int j = 0; j < x.length; j++) {
    IloLinearIntExpr r = model.linearIntExpr();
    for (int i = 0; i < x.length; i++) {
//                      if (i == j)
//                          continue;
        r.addTerm(1, x[i][j]);
    }
    model.addEq(r, 1);
}
  1. 添加约束7-3,子环约束处理有点复杂,但这个不是本文重点,读者自行理解。
// add cycle restrictions
for (Stack<Edge> stack : stacks) {
//                  stack.forEach((edge) -> System.out.println(edge.getFrom() + "->" + edge.getTo()));
    constraintFactory.cycleRestrictions(model, x, stack);
}
  1. 添加目标函数,z的表达式同上。
// one should complete the tour within the smallest distance possible
IloLinearNumExpr z = model.linearNumExpr();
for (int i = 0; i < x.length; i++) {
    for (int j = 0; j < x.length; j++) {
        if (i == j)
            continue;
        z.addTerm(distance[i][j], x[i][j]);
    }
}
  1. 确定目标是最小化目标
model.addMinimize(z);
  1. 开始求解
if (model.solve()) {

    // get tour
    for (int i = 0; i < x.length; i++) {
        for (int j = 0; j < x.length; j++) {
            if (model.getValue(x[i][j]) >= 0.5) {
                tour.add(new Edge(i, j));
            }
        }
    }

    // repaint tour
} else {
    System.err.println("Boi, u sick!");
    System.exit(1);
}

注意,一次求解不一定能求得最优解,小编跑了一个早上都跑不出来,还是100个节点的。model.getValue(x[i][j]) >= 0.5这个判断只是把求解过程中一些较好的边给添加进去而已。最优解是要满足所有约束的。

04 运行说明

代码下载请关注我们的公众号哦!后台回复【CPTSP】不包括【】即可下载。

1240

代码来源GitHub,小编去掉了部分代码。期待后期进一步精简和修改,大家下载下来后用eclipse导入,设置好cplex环境以后。在App.java里面,右键Run As->Run configurations...:
1240

找到App,在Arguments窗口,找到Program arguments:
1240

输入参数说明:
--instancePath+空格+算例文件的路径,注意用英文双引号括起来。
--maximumRead+空格+数字,表示算例大小,也就是多少个城市,文件名可以直接看出。

然后就可以愉快的run了。

附上运行结果:

1240

大家可以在while(count<1)这个条件里面更改迭代次数,以便能获取更好的解。

转载于:https://www.cnblogs.com/dengfaheng/p/11162150.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java调用Cplex求解TSP问题,您需要使用Cplex Java API。下面是一个简单的例子,演示如何使用Cplex Java API解决TSP问题: ```java import ilog.concert.*; import ilog.cplex.*; public class TSP { public static void main(String[] args) { int n = 4; // number of cities double[][] c = new double[n][n]; // cost matrix // fill in the cost matrix c[0][1] = 2; c[0][2] = 9; c[0][3] = 10; c[1][2] = 6; c[1][3] = 4; c[2][3] = 3; try { IloCplex cplex = new IloCplex(); // create variables IloNumVar[][] x = new IloNumVar[n][]; for (int i = 0; i < n; i++) { x[i] = cplex.boolVarArray(n); x[i][i].setLB(0); } // create objective function IloLinearNumExpr obj = cplex.linearNumExpr(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { obj.addTerm(c[i][j], x[i][j]); } } } cplex.addMinimize(obj); // add constraints for (int i = 0; i < n; i++) { IloLinearNumExpr expr = cplex.linearNumExpr(); for (int j = 0; j < n; j++) { if (i != j) { expr.addTerm(1, x[i][j]); } } cplex.addEq(expr, 1); } for (int j = 0; j < n; j++) { IloLinearNumExpr expr = cplex.linearNumExpr(); for (int i = 0; i < n; i++) { if (i != j) { expr.addTerm(1, x[i][j]); } } cplex.addEq(expr, 1); } // solve the problem if (cplex.solve()) { System.out.println("Solution status: " + cplex.getStatus()); System.out.println("Objective value: " + cplex.getObjValue()); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j && cplex.getValue(x[i][j]) > 0.5) { System.out.println("Edge from " + i + " to " + j); } } } } else { System.out.println("No solution found"); } cplex.end(); } catch (IloException e) { System.err.println("Concert exception " + e); } } } ``` 在这个例子中,我们首先定义了一个包含4个城市的TSP问题,然后使用Cplex Java API建立模型,并求解该问题。该模型包括一个目标函数和两个约束条件。目标函数是所有边的代价的总和,约束条件确保每个城市恰好访问一次,并且每个城市离开恰好一次。最后,我们输出找到的最优解。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值