Skip to main content

Nested loop for sum of variables

Answered

Comments

2 comments

  • Ronald van der Velden
    • Gurobi Staff Gurobi Staff

    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 model

    There 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,
    Ronald

    0
  • Eugene Parus
    • First Comment
    • First Question

    many thanks

    0

Please sign in to leave a comment.