How could SOS constraints be used with MVar?
AnsweredDear community,
I learned SOS constraint from the example document. Since I used MVar in my previous code, I changed Var variables in the example document to an MVar, and put it into SOS constraint. This results in the 'Encountered an attribute error'.
model = gp . Model ("sos")
nx=3
lb=zeros(nx)
ub=ones(nx)
vtype=['b']*nx
c=array([2,1,1])
x=model.addMVar(shape=nx,lb=lb,ub=ub,vtype=vtype)
obj=c@x
model . setObjective (obj, GRB . MAXIMIZE )
# Add first SOS: x0 = 0 or x1 = 0
model . addSOS ( GRB . SOS_TYPE1 , [ x[0] , x[1] ] , [1 , 2])
# Add second SOS: x0 = 0 or x2 = 0
model . addSOS ( GRB . SOS_TYPE1 , [ x[0] , x[2] ] , [1 , 2])
model . optimize ()
Thanks,
Haoyuan
-
Hi Haoyuan,
Accessing an MVar via \(\texttt{x[0]}\) currently does not return a Var object. This will be improved in an upcoming release. A workaround for now would be to cast the MVars object to a list and use this instead
x=model.addMVar(shape=nx,lb=lb,ub=ub,vtype=vtype)
xlist = x.tolist()
# Add first SOS: x0 = 0 or x1 = 0
model.addSOS( GRB.SOS_TYPE1, [ xlist[0], xlist[1] ], [1, 2])
# Add second SOS: x0 = 0 or x2 = 0
model.addSOS( GRB.SOS_TYPE1, [ xlist[0], xlist[2] ], [1, 2])Best regards,
Jaromił1 -
Hi Jaromił,
Thanks very much for your quick response. Since there are a lot of linear constraints in the model, adding constraints item by item takes a lot of time, so I use MVar and the following functions.
# Inequality contraints for example
A=array(
[1,2,3],
[1,0,1],
)
b=ones(nx)
model.addMConstr(A=A,x=x,sense=GRB.GREATER_EQUAL,b=b)One of the reasons I use MVar is that a large number of constraints take a lot of time to add item by item.
Can the SOS constraints be added by addMConstr in fast?Thanks,
Haoyuan0 -
Hi Haoyuan,
Instead of using the addSOS function, you could model the SOS1 constraints yourself, i.e., add them as usual constraints of the form
\[\sum_i w_i x_i \leq 1\]
and let Gurobi recognize the constraint as an SOS1 constraint.
For your case, this means that you would have to add additional rows to your constraint matrix and ones to the rhs vector.
Best regards,
Jaromił1
Please sign in to leave a comment.
Comments
3 comments