How to define a hybrid variable or define two separate set?
AnsweredI would like to convert the mathematical formulation below to Python code.

Below is what I have for my code. I think the main issue is caused by the wrong use of delta_ij and delta_oj; however, I don't know how to create a hybrid decision variable instead or define the decision variable based on conditions.
m = gp.Model()
delta_0j = m.addVars(cartesian_0j, obj=cost,lb = 0, ub=2, vtype=GRB.INTEGER, name='delta_0j')
delta_ij = m.addVars(cartesian_ij, obj=cost, vtype=GRB.BINARY, name='delta_ij')
delta_ji = m.addVars(cartesian_ji, obj=cost, vtype=GRB.BINARY, name='delta_ji')
#1.2
for i in Vcomp_index:
m.addConstr((gp.quicksum(delta_ij[(i, j)] for j in V_index if i<j)
+ (gp.quicksum(delta_ij[(j, i)] for j in V_index if i>j))==2),
name = 'degree constraint')
#1.3
for S in Gamma:
m.addConstr((gp.quicksum(delta_ij[(i, j)] for i in S for j in S_comp(S, V_index) if i<j)
+ (gp.quicksum(delta_ij[(i, j)] for i in S_comp(S, V_index) for j in S if i<j)) >= 2*r[S]), name='capacity constraint')
#1.4
for S in Gamma:
m.addConstr((gp.quicksum(delta_ij[i, j] for i in S for j in S if i<j)<=len(S) - r[S]), name='combined constraint')
#1.5
m.addConstr(((gp.quicksum(delta_0j[(0, j)]) for j in Vcomp_index) == 2*M), name='depot flow')
# objective function
m.setObjective(delta_ij.prod(cost, GRB.MINIMIZE))
m.update()
m.optimize()
0
-
It would be easier to define the variables with a single call to Model.addVars(), then modify the upper bounds afterwards. You can modify the upper bounds by individually setting the UB attribute of each Var object, or by using Model.setAttr() to modify multiple variable bounds at once. E.g., with this code:
import gurobipy as gp
from gurobipy import GRB
# Dummy data
V = list(range(4))
E = [(i, j) for i in V for j in V if i != j]
m = gp.Model()
# Create all variables as integer with domain [0, 1]
delta = m.addVars(E, vtype=GRB.INTEGER, ub=1, name='delta')
# Modify upper bounds of variables for edges emanating from node 0
m.setAttr('UB', delta.select(0, '*'), 2)
# Display bounds
m.update()
for v in delta.values():
print(f'{v.VarName}.UB = {v.UB}')we only increase the upper bounds of variables corresponding to edges emanating from node 0:
delta[0,1].UB = 2.0
delta[0,2].UB = 2.0
delta[0,3].UB = 2.0
delta[1,0].UB = 1.0
delta[1,2].UB = 1.0
delta[1,3].UB = 1.0
delta[2,0].UB = 1.0
delta[2,1].UB = 1.0
delta[2,3].UB = 1.0
delta[3,0].UB = 1.0
delta[3,1].UB = 1.0
delta[3,2].UB = 1.00
Please sign in to leave a comment.
Comments
1 comment