0

I am trying to do the following in gurobipy:

  • create a model
  • add variables
  • define a quadratic expression containing those variables
  • creating a new model that is a copy of the first one
  • defining a constraint for the new model using the quadratic expression

When performing this operations with a linear (using addLConstr()) expression everything works flawlessly but I am having some troubles with a quadratic one (tried both addQConstr() and addConstr()). I've already had a look here but I can't fugire out how to make this thing work since I am getting the quadratic expression I want to use passed as an argument to a function. Find code and error below. Code:

from gurobipy import Model
from gurobipy import GRB

m = Model()

x1 = m.addVar(vtype = GRB.CONTINUOUS, name = 'x1', ub = 5, lb = 0)
x2 = m.addVar(vtype = GRB.CONTINUOUS, name = 'x2', ub = 5, lb = 0)

# a linear expression
lin_expr = x1 + x2

# a quadratic expression
quad_expr = x1 * x2

m.addLConstr(lin_expr <= 3)
m.addQConstr(quad_expr <= 6)
m.update()

m_copy = m.copy()

# works
m_copy.addLConstr(lin_expr <= 2)
# doesn't work
m_copy.addQConstr(quad_expr <= 5)

Error:

Traceback (most recent call last):
  File "quadtest.py", line 24, in <module>
    m_copy.addQConstr(quad_expr <= 5)
  File "src/gurobipy/model.pxi", line 3398, in gurobipy.Model.addQConstr
  File "src/gurobipy/model.pxi", line 3234, in gurobipy.Model.__addConstr
gurobipy.GurobiError: Variable not in model

P.S.: when using addConstr() with the linear expression, the same error is thrown...

Edit: added a P.S.

Ronin
  • 27
  • 4
  • Both expressions `lin_expr` and `quad_expr` are formulated with variables `x1` and`x2` of Model `m`. After copying the Model, the expressions still only hold for variables of the Model `m`. Thus, you need to formulate the expressions again in terms of variables of the Model `m_copy`. – joni Apr 09 '21 at 14:02
  • @joni thanks for your response. I did what you suggested yesterday but something was wrong with the code since I tried again today and it actually worked. The weird thing is that when using `addLExpr()` there is no need to "rebuild" the expression used for defining the new constraint, but it is always required for `addConstr()` and `addQConstr()`... Maybe this happens because of `addLConstr()` being a "special" constraint constructor. Thanks for your help! – Ronin Apr 10 '21 at 16:47
  • It would be really interesting to know why it works für `addLExpr()`. Maybe the Gurobi guys will enlighten us? :) – joni Apr 10 '21 at 17:03

0 Answers0