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.