1.1下载gurobi求解器,https://www.gurobi.com/downloads/
下载完成后,一路next安装好,放着。然后点击academic license申请个证书,如果没账号就注册一个,用qq邮箱比用公司的邮箱会快。公司邮箱会慢点,但是也会收得到,收到验证邮件后点击进去设置密码即可。
1.2 获取学术许可成功
1.3打开gurobi的命令行窗口会提示输入许可
把刚刚那个grbgetkey复制粘贴到这个窗口就完事了
1.4 安装完成
经过以上两步已经完成了gurobi的安装,但是许多同学在安装的最后一步并不会去重启,即使它提示你需要重启。这就会导致环境变量不生效,后面会有意想不到的事情发生。
2.1 Gurobi导入idea中
打开idea,点projecstructure,module。做如下操作
2.2找到gurobi的安装路径的lib目录
添加jar包 添加完成apply,返回开始贴上官方代码。
2.3 运行MIP问题的例子
例子在这,https://www.gurobi.com/documentation/9.1/examples/mip1_java.html,代码如下:
import gurobi.*;
public class Mip1 {
public static void main(String[] args) {
try {
GRBEnv env = new GRBEnv(true);
env.set("logFile", "mip1.log");
env.start();
GRBModel model = new GRBModel(env);
GRBVar x = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "x");
GRBVar y = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "y");
GRBVar z = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "z");
GRBLinExpr expr = new GRBLinExpr();
expr.addTerm(1.0, x); expr.addTerm(1.0, y); expr.addTerm(2.0, z);
model.setObjective(expr, GRB.MAXIMIZE);
expr = new GRBLinExpr();
expr.addTerm(1.0, x); expr.addTerm(2.0, y); expr.addTerm(3.0, z);
model.addConstr(expr, GRB.LESS_EQUAL, 4.0, "c0");
expr = new GRBLinExpr();
expr.addTerm(1.0, x); expr.addTerm(1.0, y);
model.addConstr(expr, GRB.GREATER_EQUAL, 1.0, "c1");
model.optimize();
System.out.println(x.get(GRB.StringAttr.VarName)
+ " " +x.get(GRB.DoubleAttr.X));
System.out.println(y.get(GRB.StringAttr.VarName)
+ " " +y.get(GRB.DoubleAttr.X));
System.out.println(z.get(GRB.StringAttr.VarName)
+ " " +z.get(GRB.DoubleAttr.X));
System.out.println("Obj: " + model.get(GRB.DoubleAttr.ObjVal));
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
2.4 运行
报错:java.lang.UnsatisfiedLinkError:no gurobi950 in java.library.path 原因是环境变量未生效,重启解决
2.5 运行结果
Set parameter Username
Set parameter LogFile to value "mip1.log"
Academic license - for non-commercial use only - expires 2022-01-09
Gurobi Optimizer version 9.5.0 build v9.5.0rc5 (win64)
Thread count: 4 physical cores, 4 logical processors, using up to 4 threads
Optimize a model with 2 rows, 3 columns and 5 nonzeros
Model fingerprint: 0x98886187
Variable types: 0 continuous, 3 integer (3 binary)
Coefficient statistics:
Matrix range [1e+00, 3e+00]
Objective range [1e+00, 2e+00]
Bounds range [1e+00, 1e+00]
RHS range [1e+00, 4e+00]
Found heuristic solution: objective 2.0000000
Presolve removed 2 rows and 3 columns
Presolve time: 0.14s
Presolve: All rows and columns removed
Explored 0 nodes (0 simplex iterations) in 0.22 seconds (0.00 work units)
Thread count was 1 (of 4 available processors)
Solution count 2: 3 2
Optimal solution found (tolerance 1.00e-04)
Best objective 3.000000000000e+00, best bound 3.000000000000e+00, gap 0.0000%
x 1.0
y 0.0
z 1.0
Obj: 3.0
Process finished with exit code 0
|