Objective: Add variables and constraints in a loop to a Gurobi model from a list of variables and a list of constraints each of varying lengths where each variable and constraint is stored as a string
Problem: Gurobi only accepts variables and constraints in the Gurobi linear expression type. I need to do this in an automated way because the list of constraints might be very long. So somehow I need to convert those strings to a Gurobi LinExpr type.
Data: I have a list of variables as in this example:
variables=["y1","y2","y3","y4","y5","y6","y7"]
and I have a list of constraints like that:
['y6+y7-d*y1>=0', '1*y2+1*y3-1*u1*d-y6-y7+d*y1>=0', '1*y4+1*y5-u2*1*d-y6-y7+d*y1>=0', '1*x1+1*x2-1*d-1*y2-1*y3+1*u1*d-1*y4-1*y5+u2*1*d+y6+y7-d*y1>=0']
Desired Solution:
I want to add those variables to my Gurobi model as in this example:
y1 = model.addVar(vtype=GRB.CONTINUOUS, name = "y1", lb=0)
y2 = model.addVar(vtype=GRB.CONTINUOUS, name = "y2", lb=0)
y3 = model.addVar(vtype=GRB.CONTINUOUS, name = "y3", lb=0)
y4 = model.addVar(vtype=GRB.CONTINUOUS, name = "y4", lb=0)
y5 = model.addVar(vtype=GRB.CONTINUOUS, name = "y5", lb=0)
y6 = model.addVar(vtype=GRB.CONTINUOUS, name = "y6", lb=0)
y7 = model.addVar(vtype=GRB.CONTINUOUS, name = "y7", lb=0)
and the constraints like that:
c1 = model.addConstr(y1+y2-d*y1>=0,"c1")
c2 = model.addConstr(1*y2+1*y3-1*y5*d-y6-y7+d*y1>=0,"c2")
c3 = model.addConstr(1*y4+1*y5-u2*1*d-y6-y7+d*y1>=0,"c3")
c4 = model.addConstr(1*y1+1*y2-1*d-1*y2-1*y3+1*u1*d-1*y4-1*y5+u2*1*d+y6+y7-d*y1>=0,"c4")
My Try:
I tried to store the data in a dictionary and use the update function to store the variables and constraints like this:
y_dict={}
for y_variable in range(y_count-1):
y_dict['y{}'.format(y_variable+1)]=model.addVar(vtype=GRB.CONTINUOUS, name = "y{}".format(y_variable+1), lb=0)
locals().update(c_dict)
c_dict={}
for idx, constraint in enumerate(list_of_constraints):
c_dict['c{}'.format(idx+1)]=model.addConstr(eval(constraint),"c{}".format(idx+1))
locals().update(c_dict)
But, the error I get when I set the objective is
GurobiError: Variable not in model
Is there any way to convert strings to the Gurobi Linear Expression type?