从导入的复杂模型中动态设置项因子

Set term factors dynamically from an imported cplex-Model

假设我有一个 OptimizationModel abc.lp,我想用 CPlex java-API 导入它。我使用:importModel 函数 (click) 导入它。现在我想在约束或 objective 中更改一些决策变量的因素。例如,导入的模型 abc.lp 如下所示:

Objective: Minimize <factor1>x1 + <factor2>x2

Constraint: <factor1>x1 + <factor2>x2 <= 40

对我来说,factor1factor2 是函数的输入参数。所以我得到:

public void(double factor1, double factor2){
...
cplexModel.import("path/to/abc.lp")
// Change parameters, how to do it?

有没有一种简便的方法可以使用 Cplex-API 从导入的模型中动态设置因子?

非常感谢!

是的,这是可能的。这不是很直观,至少对我而言。

这是一个假定 LP(线性 objective 和约束)的示例片段:

 // Read model from file with name args[0] into cplex optimizer object
 cplex.importModel(args[0]);

 // Get the objective and modify it.
 IloObjective obj = cplex.getObjective();
 IloLinearNumExpr objExpr = (IloLinearNumExpr) obj.getExpr();
 IloLinearNumExprIterator iter = objExpr.linearIterator();
 // Loop through the linear objective and modify, as necessary.
 while (iter.hasNext()) {
   IloNumVar var = iter.nextNumVar();
   System.out.println("Old coefficient for " + var + ": " + iter.getValue());
   // Modify as needed.
   if ( var.getName().equals("x1") ) {
      iter.setValue(42);
      System.out.println("New coefficient for " + var + ": " + iter.getValue());
   }
 }
 // Save the changes.
 obj.setExpr(objExpr);

 // Assumes that there is an LP Matrix.  The fact that we used
 // importModel() above guarantees that there will be at least
 // one.
 IloLPMatrix lp = (IloLPMatrix) cplex.LPMatrixIterator().next();
 for (int i = 0; i < lp.getNrows(); i++) {
    IloRange range = lp.getRange(i);
    System.out.println("Constraint " + range.getName());
    IloLinearNumExpr conExpr = (IloLinearNumExpr) range.getExpr();
    IloLinearNumExprIterator conIter = conExpr.linearIterator();
    // Loop through the linear constraints and modify, as necessary.
    while (conIter.hasNext()) {
       IloNumVar var = conIter.nextNumVar();
       System.out.println("Coefficient for " + var + ": " + conIter.getValue());
       // Modify as needed (as above).
       if ( var.getName().equals("x1") ) {
          conIter.setValue(42);
          System.out.println("New coefficient for " + var + ": " + conIter.getValue());
       }
  }
  // Save changes (as above).
  range.setExpr(conExpr);
}
cplex.exportModel("modified.lp");

// Solve the model and display the solution if one was found
if ( cplex.solve() ) {
   // do something here.
} 

在这里,我们正在寻找一个名为 "x1" 的变量。我们在 objective 和所有线性约束中将其系数设置为 42。 println 用于调试。我很快就这样做了,所以一定要测试一下。否则,您应该能够修改它以满足您的需要。希望对您有所帮助。