向CPLEX添加约束不工作的C++API



在用CPLEX解决我的模型后,我想向模型添加更多的约束。我有一个请求向量R,每个i in R有一个相应的变量p_i,还有一个约束p_i = 1(这里我省略了更多的变量和约束(。在第一次求解之后,出现了一个新的请求,我想为其创建一个新变量p_{new_request}和相应的约束p_{new_request} = 1。我尝试了两种不同的方法,一种方法使用

model.add(p[rmap[new_request]] == 1); 

另一个没有,即约束没有添加到模型中。

accept.add(IloRange());
accept[rmap[new_request]] = IloRange(env,1,p[rmap[new_request]],1,name.str().c_str());

我需要第二种方法,因为一旦请求得到服务,我还需要从模型中删除某些约束,即

accept[rmap[i]].end();

我怎样才能正确地做到这一点?非常感谢您的帮助!!!

以下是完整的代码:(由于R = {1,2,3,4,5,6,7,8,9,10,25,26}和我不能访问p[25],因为p是大小为12的矢量,所以我创建了一个映射rmap。(

#include <vector>
#include <unordered_map>
#include <ilcplex/ilocplex.h>
ILOSTLBEGIN
int main(){

bool solved;
// vector R contains all requests
std::vector <int> R = {1,2,3,4,5,6,7,8,9,10,25,26};
// use this unordered map to index variables p with requests
std::unordered_map<int,int> rmap;
int count = 0;
for (const auto& i: R)
{
rmap[i] = count;
count++;
}
int new_request;

// use this stringstream to create variable and constraint names
std::stringstream name;
IloEnv             env;
IloModel     model(env);
IloNumVarArray p(env,R.size());
IloRangeArray accept(env,R.size());

for (const auto& i: R)
{
name << "p_" << i;
p[rmap[i]] = IloNumVar(env, 0, 1, ILOBOOL, name.str().c_str()); 
name.str("");
}
for (const auto& i : R)
{
name << "accept_" << i;
accept[rmap[i]] = IloRange(env,1,p[rmap[i]],1,name.str().c_str()); 
name.str(""); // Clean name
}   
model.add(accept);

IloExpr expr(env);
// Create objective function
for (const auto& i : R)
{
expr += p[rmap[i]]; 
}
IloObjective obj(env, expr, IloObjective::Minimize);
model.add(obj);
expr.clear();


// Create the solver object
IloCplex cplex(model);
env.out() << "Before" << endl;
env.out() << model << endl;
cplex.exportModel("Before.1.lp");

solved = cplex.solve();
if (solved)
{
// If CPLEX successfully solved the model, print the results
std::cout << "nnCplex success!n";
std::cout << "tStatus: " << cplex.getStatus() << "n";
std::cout << "tObjective value: " << cplex.getObjValue() << "n";
// add new request to R, create variable p and corresponding constraint
new_request = 23;
R.push_back(new_request);
rmap[new_request] = R.size() - 1;
name << "p_" << new_request;
p.add(IloNumVar(env,0,1,ILOBOOL,name.str().c_str()));
name.str("");
name << "accept_" << new_request;

// These to lines don't work
accept.add(IloRange());
accept[rmap[new_request]] = IloRange(env,1,p[rmap[new_request]],1,name.str().c_str()); 

// this line works
//model.add(p[rmap[new_request]] == 1);

name.str(""); // Clean name
env.out() << "After" << endl;
env.out() << model << endl;
cplex.exportModel("After.1.lp");
solved = cplex.solve();
}

expr.end();
env.end();
}

我自己也发现了这个错误。必须将约束添加到模型中,而不仅仅是添加到先前添加到模型的IloRangeArrray中。线路

accept.add(IloRange());
accept[rmap[new_request]] = IloRange(env,1,p[rmap[new_request]],1,name.str().c_str());

必须更改为:

IloRange rng(env,1,p[rmap[new_request]],1,name.str().c_str());
accept.add(rng);
model.add(rng);

最新更新