Skip to main content

My code takes much more time for the modeling part than for the solution, how can I improve it?

Answered

Comments

5 comments

  • Simranjit Kaur
    • Gurobi Staff Gurobi Staff

    Hi Jie Zhu,

    Could you please share a minimum reproducible example? Please see Tutorial: Preparing a Minimal Reproducible Example.

    Best regards,
    Simran

     

    0
  • Jie Zhu
    • Gurobi-versary
    • Conversationalist
    • First Question

    Thank you very much for your reply, the code below is the minimum repeatability example corresponding to my model, in this example, the code in bold runs for more than 40 seconds. In my actual model, I need to keep iterating over the parameters in this minimum repeatability example, which means that the bolded code needs to be run many times, is there any way to speed up the running of the bolded code?

    import numpy as np
    from gurobipy import Model,GRB,quicksum,MVar
    TEST_HOUR = 96
    M_F = np.random.uniform(0.92, 0.98, size=(6*TEST_HOUR,2*TEST_HOUR))
    F = np.random.uniform(0.92, 0.98, size=(6*TEST_HOUR,2*TEST_HOUR))
    H = np.random.uniform(0.92, 0.98, size=(6*TEST_HOUR,1))
    m = Model('Inner_approximation')
    #addMVar
    s = m.addMVar((1,1),lb = 0,vtype = GRB.CONTINUOUS, name = 's')
    g = m.addMVar((6*TEST_HOUR,6*TEST_HOUR), lb = 0, vtype = GRB.CONTINUOUS, name = 'G')
    r = m.addMVar((2*TEST_HOUR,1),lb = -100,ub = 100,vtype = GRB.CONTINUOUS, name = 'r')
    #setObjective
    m.setObjective(s, GRB.MINIMIZE)
    #addConstr
    m.addConstr(g @ M_F == F, name = "convert euqation")
    m.addConstr(g @ H <= H @ s + F @ r, name = "ineuqation")
    m.optimize()
    0
  • Eli Towle
    • Gurobi Staff Gurobi Staff

    Building the expression \( \texttt{g @ M_F}\) consumes the most time. Based on your initial post, it looks like this expression is present in each model you solve. In that case, you could add the corresponding constraints to the model once, then modify the constraint right-hand sides (the RHS attribute) in each iteration. For example:

    c1 = m.addConstr(g @ M_F == 0, name="convert_euqation")
    c2 = None

    for i in range(n):
    # Modify right-hand sides of first set of constraints
    c1.RHS = F[i]

    # Update second set of constraints
    if c2 is not None:
    m.remove(c2)
    c2 = m.addConstr(g @ H[i] <= H[i] @ s + F[i] @ r, name="ineuqation")

    m.optimize()
    0
  • Jie Zhu
    • Gurobi-versary
    • Conversationalist
    • First Question

    Thank you very much, the problem has been solved by following your improvements!

    0
  • Gwyneth Butera
    • Gurobi Staff Gurobi Staff

    Please also see How do I improve the time to build my model?

    0

Please sign in to leave a comment.