I am solving an LP by using GUROBI - C++ combo.

Assume I have a variable $p \in \mathbb{R}^n$. I am adding this as a vector:

GRBEnv* env;
GRBModel* model;
vector<GRBVar> p;

Now I have $a\in\mathbb{R}^n$ parameters, and I want to add a constraint $a^\top p\ \leq 0$, so I say:

GRBLinExpr sum_expo = 0;
for (int i = 0; i < p.size(); i++) {// add all the coeffs given
                        sum_expo += a[i] * p[i];
model->addConstr(sum_expo <= 0);

Obviously, this is too inefficient. Is there a way that I can:

  1. Define the whole $p$ vector as a multivariate GRBVar, rather than having a vector with all GRBVar values
  2. Add a constraint $a^\top p \leq 0$ in a single line.
  • $\begingroup$ Thanks for the answer. I somehow taught using addVars in one command and then somehow giving inner-product defined constraint would be more efficient. So is what I am doing above standard? $\endgroup$ – independentvariable Feb 13 at 23:51

You can use addTerms() to construct a linear expression in one call. According to the documentation this is the most efficient way:

  • You should avoid using expr = expr + x in a loop. It will lead to runtimes that are quadratic in the number of terms in the expression.
  • Using expr += x (or expr -= x) is much more efficient than expr = expr + x. Building a large expression by looping over += statements is reasonably efficient, but it isn't the most efficient approach.
  • The most efficient way to build a large expression is to make a single call to addTerms.

Concerning adding multiple constraints in one call (documentation about addConstrs):

We recommend that you build your model one constraint at a time (using addConstr), since it introduces no significant overhead and we find that it produces simpler code. Feel free to use these methods if you disagree, though.

| improve this answer | |
  • $\begingroup$ thanks for this answer. How can I call that? Something like:sum_expo::addTerms(a, p, p.size()); $\endgroup$ – independentvariable Feb 14 at 14:10
  • 1
    $\begingroup$ ok fied by sum_expo.addTerms(&a[0], &p[0], X.size()); $\endgroup$ – independentvariable Feb 14 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.