Merging a binary decision variable with a continuous variable (semi-binary/continuous)
AnsweredI have two decision variables defined as
x = m.addVars(((i, j) for i, j in arcs if f[i][j] == 0),
vtype=GRB.BINARY, name='x')
y = m.addVars(((i, j) for i, j in arcs if f[i][j] == 1),
vtype=GRB.CONTINUOUS, name='y')
As you see, what makes x be binary but y continuous depends on the if condition. Is there a way to merge them into a single variable? For instance, something like:
x = m.addVars(((i, j) for i, j in arcs),
vtype=GRB.CONTINUOUS if f[i][j] else vtype=GRB.BINARY, name='x')
0
-
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 can do this by setting the \( \texttt{vtype} \) keyword argument to a \( \texttt{dict} \) that maps each arc to either \( \texttt{GRB.CONTINUOUS} \) or \( \texttt{GRB.BINARY} \). For example:
import random
vtypes = {(i, j): GRB.CONTINUOUS if random.random() < 0.5 else GRB.BINARY for (i, j) in arcs}
x = m.addVars(arcs, vtype=vtypes, name='x')If you want the continuous variables to be bounded above by \( 1 \), you should include the argument \( \texttt{ub=1} \) in your call to Model.addVars().
Alternatively, you could:
- Set the \( \texttt{vtype} \) argument equal to a list that's the same length as \( \texttt{arcs} \), or
- After calling Model.addVars(), iterate over the variables and individually set their VType attributes.
1 -
Thanks very much for your quick and detailed response.
0
Post is closed for comments.
Comments
3 comments