c++ - 线性规划 : Modulo constraint

标签 c++ linear-programming coin-or-cbc

我正在使用 Coin-Or 的 rehearse实现线性规划。

我需要模数约束。示例:x 应为 3 的倍数。

OsiCbcSolverInterface solver;
CelModel model(solver);
CelNumVar x;
CelIntVar z;

unsigned int mod = 3;

// Maximize

solver.setObjSense(-1.0);

model.setObjective(x);

model.addConstraint(x <= 7.5);

// The modulo constraint:

model.addConstraint(x == z * mod);

x 的结果应该是 6。但是,z 设置为 2.5,这应该是不可能的,因为我将其声明为一个 CellIntVar

如何强制 z 为整数?

最佳答案

我从未使用过该库,但我认为您应该遵循 tests .

核心信息来自readme:

If you want some of your variables to be integers, use CelIntVar instead of CelNumVar. You must bind the solver to an Integer Linear Programming solver as well, for example Coin-cbc.

查看Rehearse/tests/testRehearse.cpp -> exemple4() (此处提供:不完整的代码;没有复制粘贴):

OsiClpSolverInterface *solver = new OsiClpSolverInterface();

CelModel model(*solver);

...
CelIntVar x1("x1");
...
solver->initialSolve();       // this is the relaxation (and maybe presolving)!
...
CbcModel cbcModel(*solver);   // MIP-solver
cbcModel.branchAndBound();    // Use MIP-solver

printf("Solution for x1 : %g\n", model.getSolutionValue(x1, *cbcModel.solver()));
printf("Solution objvalue = : %g\n", cbcModel.solver()->getObjValue());

这种用法(使用 Osi 获取 LP-solver;在 Osi 提供的 LP-solver 之上构建 MIP-solver 并调用 brandAndBound)基本上遵循 Cbc 的内部接口(interface)(与 python 的 cylp 这看起来相似) .

作为引用:这是来自 here 的官方 CoinOR Cbc(免排练)示例:

// Copyright (C) 2005, International Business Machines
// Corporation and others.  All Rights Reserved.

#include "CbcModel.hpp"

// Using CLP as the solver
#include "OsiClpSolverInterface.hpp"

int main (int argc, const char *argv[])
{
  OsiClpSolverInterface solver1;

  // Read in example model in MPS file format
  // and assert that it is a clean model
  int numMpsReadErrors = solver1.readMps("../../Mps/Sample/p0033.mps","");
  assert(numMpsReadErrors==0);

  // Pass the solver with the problem to be solved to CbcModel 
  CbcModel model(solver1);

  // Do complete search
  model.branchAndBound();

  /* Print the solution.  CbcModel clones the solver so we
     need to get current copy from the CbcModel */
  int numberColumns = model.solver()->getNumCols();

  const double * solution = model.bestSolution();

  for (int iColumn=0;iColumn<numberColumns;iColumn++) {
    double value=solution[iColumn];
    if (fabs(value)>1.0e-7&&model.solver()->isInteger(iColumn)) 
      printf("%d has value %g\n",iColumn,value);
   }
  return 0;
}

关于c++ - 线性规划 : Modulo constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50969975/

相关文章:

c++ - 同步push_back和std::thread

algorithm - 哪个算法分配类次(离散优化问题)

c++ - 使用 C++ 将 vector 数组转换为 .MPS 文件

julia - 如何使用 JuMP 寻求 MIP 的第二最佳解决方案

c++ - 如何在代码中使用 IloExprArray?

c++ - 使用可变参数模板函数计算多个值的平均值

c++ - gcc 的 protobuf 编译问题

c++ - 用高斯混合模型估计颜色分布

python - pandas, melt, unmelt 保存索引