【问题标题】:how to revise a existing cplex model in C++如何在 C++ 中修改现有的 cplex 模型
【发布时间】:2015-11-04 04:00:59
【问题描述】:

我有一个非常大的 LP 问题要解决,而且必须解决很多次。

每次,我只需要改变一些系数并再次运行。

所以我的策略是为基本问题制定模型,然后保存。

每次,我都会得到一份基本模型,并尝试更改系数。

问题是如何更改新副本的系数。

我知道在创建模型时如何更改系数。但我不想重复创建过程,因为它需要很多时间。

有没有直接的方法可以改变系数而无需重新创建模型?

【问题讨论】:

    标签: c++ cplex


    【解决方案1】:

    我修改了下面随 CPLEX 提供的 ilolpex1.cpp 示例:

    #include <ilcplex/ilocplex.h>
    ILOSTLBEGIN
    
    static void
       populatebyrow     (IloModel model, IloNumVarArray var, IloRangeArray con);
    
    int
    main (int argc, char **argv)
    {
       IloEnv   env;
       try {
          IloModel model(env);
          IloNumVarArray var(env);
          IloRangeArray con(env);
    
          populatebyrow (model, var, con);
    
          IloCplex cplex(model);
          cplex.exportModel("lpex1.1.lp");
    
          // Optimize the problem and obtain solution.
          if ( !cplex.solve() ) {
             env.error() << "Failed to optimize LP" << endl;
             throw(-1);
          }
    
          env.out() << "Solution status = " << cplex.getStatus() << endl;
          env.out() << "Solution value  = " << cplex.getObjValue() << endl;
    
          // Modify one of the coefficients and solve again.
          con[0].setLinearCoef(var[2], 2);
          cplex.exportModel("lpex1.2.lp");
    
          // Optimize the problem and obtain solution.
          if ( !cplex.solve() ) {
             env.error() << "Failed to optimize LP" << endl;
             throw(-1);
          }
    
          env.out() << "Solution status = " << cplex.getStatus() << endl;
          env.out() << "Solution value  = " << cplex.getObjValue() << endl;
       }
       catch (IloException& e) {
          cerr << "Concert exception caught: " << e << endl;
       }
       catch (...) {
          cerr << "Unknown exception caught" << endl;
       }
    
       env.end();
    
       return 0;
    }  // END main
    
    
    // To populate by row, we first create the variables, and then use them to
    // create the range constraints and objective.
    
    static void
    populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c)
    {
       IloEnv env = model.getEnv();
    
       x.add(IloNumVar(env, 0.0, 40.0));
       x.add(IloNumVar(env));
       x.add(IloNumVar(env));
    
       model.add(IloMaximize(env, x[0] + 2 * x[1] + 3 * x[2]));
    
       c.add( - x[0] +     x[1] + x[2] <= 20);
       c.add(   x[0] - 3 * x[1] + x[2] <= 30);
    
       x[0].setName("x1");
       x[1].setName("x2");
       x[2].setName("x3");
    
       c[0].setName("c1");
       c[1].setName("c2");
       model.add(c);
    
    }  // END populatebyrow
    

    我已使用setLinearCoef 方法更改其中一个系数。您可以比较两个 LP 文件(“lpex1.1.lp”和“lpex1.2.lp”)来查看/验证更改。

    【讨论】:

    • 非常感谢。明白了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 2012-01-08
    相关资源
    最近更新 更多