Updating the number of variables and Constraints through For Loop
AnsweredGood afternoon!
I'm using Gurobi in Python and I was hoping to update the number of variables using a for loop. For example, this is how I initially defined yDHT:
yDHT = m.addVars(D, H, S, vtype=GRB.CONTINUOUS, name='yDHT')
where S is a list containing 3 scenarios
Now, I want to increase the number of scenarios to 10 by using a for loop. I also want to solve the optimization model each time a scenario is added. This way, I'll have the initial run of the model containing 3 scenarios + 7 more runs of the models with the updated list of scenarios. For example
Initial optimization run: [S1, S2, S8]
Run optimization with the first scenario added: [S1, S2, S8, S3], while solutions from the previous run being the warm-start
Run optimization with the second scenario added: [S1, S2, S8, S3, S5], while solutions from the previous run being the warm-start
Run optimization with the third scenario added: [S1, S2, S8, S3, S5, S7], while solutions from the previous run being the warm-start
This is how I have done so far:
for scenario_update in range(len(scenarios1.Index)):
entering_scenario = scenarios1.take([scenario_update])
scenarios = scenarios.append(entering_scenario)
scenario = scenarios.Index.tolist()
Which returns the right sequence of scenarios:
[S1, S2, S8] -> [S1, S2, S8, S3] -> [S1, S2, S8, S3, S5] -> [S1, S2, S8, S3, S5, S7]
But I wasn't sure how I should go about updating the constarints for each of the scenarios added, and updating the number of variables.
Should I do something like this?
#Updating the number of variables
YDHT.update({depot, entering_scenario, m.addVar(vtype = GRB.BINARY, name= 'yDHT')})
#Updating Constraints
for s in entering_scenario.Index.tolist():
for d in depot:
m.addConstr(gp.quicksum(yDBT[d, b, s] for b in DC) +
gp.quicksum(yDHT[d, h, s] + yDHV[d, h, s] + yDHU[d, h, s] for h in shelter)
<= PD[d] * xD[d], name='Constraint 4')
#Warm-starting
yDHT[depot[d], shelter[h], scenario[s]].start = yDHT[depot[d], shelter[h], scenario[s]].x
#Re-run the model
m.optimize(callback = data_cb)
Or is there a better approach?
Thank you so much. Any help will be truly appreciated.
Sincerely,
Min Lee
-
Hi Min Lee,
I think that it is easier to have a list or a dictionary holding multiple yDHT entries instead of directly modifying the tupledict returned by the addVars method.
You could have a dictionary similar to
S = {S1: "yHDT defined over scenario S1", S2: "yHDT defined over scenario S2", ...}Then, when adding constraints, you can run over all entries in this dictionary and construct the corresponding constraints.
Best regards,
Jaromił0
Please sign in to leave a comment.
Comments
1 comment