TransWikia.com

Cplex C++ Interface: How to add many constraints quickly?

Computational Science Asked by Bjoern on March 15, 2021

I noticed that adding constraints to an IloModel one by one can be prohibitively slow. (I am referring to the construction of the model, not the optimization.)

Suppose I have many constraints with the same number of variables, can I add the constraint matrix in one function call?

Are there other ways to speed up the construction of the model?

2 Answers

I came across this issue recently, and discovered that if you first add the constraints to an IloRangeArray, and then add that object to the model, you'll see a significant speed-up. Removing constraints is also faster if they are contained in a container object like an IloRangeArray.

Correct answer by Autumn on March 15, 2021

I was struggling with similar issue recently and noticed that for some reason working with IloRange is much slower than using IloNumExpr. Previously I was adding constraints as follows:

IloEnv env;
IloNumVarArray vars(env, stl_vars.size(), 0, IloInfinity);
IloRangeArray constrs(env, stl_constrs.size(), 0, 1);
for (size_t i = 0; i < stl_constrs.size(); ++i) {
    constrs[i].setUB(stl_constrs[i].ub);
    for (size_t j = 0; j < stl_constrs[i].vars.size(); ++j)
        constrs[i].setLinearCoef(vars[stl_constrs[i].vars[j].ind], stl_constrs[i].vars[j].coefficient);
}
model.add(constrs);

Replacing this code with the following:

IloEnv env;
IloNumVarArray vars(env, stl_vars.size(), 0, IloInfinity);
for (size_t i = 0; i < stl_constrs.size(); ++i) {
    IloNumExpr row(env);
    for (size_t j = 0; j < stl_constrs[i].vars.size(); ++j)
        row += stl_constrs[i].vars[j].coefficient * vars[stl_constrs[i].vars[j].ind];
    model.add(row <= stl_constrs[i].ub);
    row.end();
}

improved speed significantly.

Hope, this will help someone.

Answered by Alexander Belyi on March 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP