Nested loop for sum of variables
AnsweredHi team,
I am new to Gurobi.
I have problem with sum of variables for constraints.
Let we have 3 hours H=[1,2,3]. For each hour we have one variable [V1,V2,V3] and maximum of sum for current and previous hours [K1,K2,K3].
It is necessary to create such a system of restrictions:
V1 <=K1
V1+V2 <=K2
V1+V2+V3<=K3
How do I declare a nested loop to create such a restriction system?
0
-
Hi Eugene,
You could do something like this:
import gurobipy as gp
from gurobipy import GRB
H = range(3)
K = [7, 13, 16]
with gp.Env() as env, gp.Model(env=env) as model:
V = model.addVars(H, name='V')
for h in H:
model.addConstr(gp.quicksum(V[i] for i in range(h+1)) <= K[h])
model.write('temp.lp') # To inspect the resulting modelThere are ways to speed this (model-building) up in case you're looking at thousands of hours, e.g.
- Build the left-hand-side expression iteratively. After adding the constraint for K1, add V2 to the expression. After adding the constraint for K2, add V3 etcetera.
- Alternatively, you could introduce variables containing the cumulative values for the left-hand-side, e.g. C1=V1, C2=C1+V2, C3=C2+V3. You should test what performs best when solving the model.
Kind regards,
Ronald0 -
many thanks
0
Please sign in to leave a comment.
Comments
2 comments