gpt4 book ai didi

c++ - 线性规划 : Modulo constraint

转载 作者:行者123 更新时间:2023-11-30 03:22:40 28 4
gpt4 key购买 nike

我正在使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com