Adding a constraint with multiple MVar
AnsweredHello all,
I am trying to create a constraint for my model with multiple MVar vector variables (1-D). Here is a minimal code example for which I hope you can reproduce the error I get:
vec_1 = model.addMVar(3)
vec_2 = model.addMVar(3)
const_vec = np.array([4,5,3])
model.addConstr(vec_1 <= np.multiply(const_vec, vec_2))
In essence, I want Gurobi to compare each entry of vec_1 with the entry of const_vec times the entry of vec_2. I realize that Gurobi doesn't like arithmetic inside of the constraint initialization, so I tried this:
a = np.multiply(const_vec, vec_2)
model.addConstr(vec_1 <= a)
Now a is of the type MLinExpr but I can not find a correct way to deal with this kind of object in the documentation. addConstr seems to be the wrong method. Maybe addLConstr?
Thanks in advance for the help!
Andreas
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
You could convert the constant vector to a (sparse) diagonal matrix, then build the constraint using Gurobi's support for matrix multiplication:
import gurobipy as gp
import numpy as np
import scipy.sparse as sp
m = gp.Model()
x = m.addMVar(3, name='x')
y = m.addMVar(3, name='y')
a = np.array([4, 5, 3])
m.addConstr(x <= sp.diags(a) @ y)0 -
Thanks for the great answer! Works perfectly.
0
Post is closed for comments.
Comments
3 comments