在列生成算法学习过程中,使用按列对添加模型有利于后期逐步添加列。但是之前只了解按行添加的模式,因而记录java-cplex按列添加模型的方式。
按行添加:根据数学模型的约束数量,逐一将每一个约束添加进入模型,如【cplex求解整数规划示例-按行添加】。
按列添加:根据数学模型的变量数量,逐一将每一个约束的变量添加进入模型。
问题介绍
数据定义
class DataColumn{
// 目标系数
double[] objectiveCoefficient={7, 8, 2, 9, 6};
// 约束系数
double[][] constraintCoefficient={{5, 7, 9, 2, 1}, {18, 4, -9, 10, 12}, {4, 7, 3, 8, 5}, {5, 13, 16, 3, -7}};
// 约束值
double[] constraintValue={250, 285, 211, 315};
// 变量数量
int variableNumber=5;
// 约束数量
int constrainNumber=4;
}
问题建模
public class IntegerProgrammingColumnDemo {
//定义数据
DataColumn data;
public IntegerProgrammingColumnDemo(DataColumn data){
this.data=data;
}
// 定义cplex内部对象
IloCplex model;
// 定义变量
public IloNumVar[] x;
// 求解函数
public void solve() throws IloException{
model.setOut(null);
if(model.solve()==false){
// 模型不可解
System.out.println("模型不可解");
return;
}
else{
System.out.println("目标值:"+model.getObjValue());
for(int i=0;i<data.variableNumber;i++){
System.out.println("变量值x["+(i+1)+"]:"+model.getValue(x[i]));
}
}
}
// 根据数学模型建立求解模型
public void BuildModel() throws IloException{
//初始化模型
model = new IloCplex();
//定义模型目标
IloObjective cost = model.addMaximize();
//定义变量
x = new IloNumVar[data.variableNumber];
//添加约束
IloRange[] cons = new IloRange[data.constrainNumber];
//添加约束范围
for (int i = 0; i < cons.length; i++) {
cons[i] = model.addRange(Double.MIN_VALUE,data.constraintValue[i]);
}
//按列添加模型
for (int j = 0; j < data.variableNumber; j++) {
IloColumn column = model.column(cost, data.objectiveCoefficient[j]);
for(int i=0;i< data.constrainNumber;i++) {
column = column.and(model.column(cons[i], data.constraintCoefficient[i][j]));
}
x[j]=model.numVar(column, 0, Double.MAX_VALUE,IloNumVarType.Int,"x["+j+"]");
}
System.out.print(model);
}
}
问题求解
public static void main(String[] args)throws IloException{
DataColumn data =new DataColumn();
IntegerProgrammingColumnDemo lp=new IntegerProgrammingColumnDemo(data);
lp.BuildModel();
lp.solve();
}
求解结果
========================================
今天到此为止,后续记录其他cplex技术的学习过程。
以上学习笔记,如有侵犯,请立即联系并删除!