我正在使用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
为整数?
答案 0 :(得分:2)
我从没有使用过那个lib,但是我认为您应该遵循tests。
核心信息来自自述文件:
如果希望某些变量为整数,请使用CelIntVar而不是CelNumVar。 您还必须将求解器绑定到Integer Linear Programming求解器,例如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的内部接口(使用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;
}