メインコンテンツへスキップ

Print intermediate solutions (Objective value and variables) while running MIP using gurobi in python.

回答済み

コメント

2件のコメント

  • 正式なコメント
    Simranjit Kaur
    • Gurobi Staff
    This post is more than two years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support.
  • Chung-Kyun Han
    • Gurobi Staff

    Hi Bhargav Gorantla Sridhar,

     

    Thank you for reaching us.

    I would like to introduce two approaches that handle intermediate solutions.
    The simple one is to write .sol file by SolFiles parameter and I found a post asking the similar question to yours.
    Another approach is to use a callback function(by requesting the MIPSOL_SOL in a MIPSOL callback).
    Please check the linked Python example if you want to know how to implement a callback function.

    Here is an example python code dealing with a callback function and SOLFiles parameter.

    #Print intermediate solutions - two ways 1) callback 2) parameter SolFiles

    import gurobipy as gp
    from gurobipy import GRB

    def mycallback(model, where):

        if where == GRB.Callback.MIPSOL:

            # Access solution values using the custom attribute model._vars
            sol = model.cbGetSolution(model._vars)
            obj = model.cbGet(GRB.Callback.MIPSOL_OBJ)

            # Print the solution with variable names
            print('**** New solution of obj %g '%obj)
            for i in range(len(model._vars)):
               print(f"{model._vars[i].VarName}: {sol[i]}")

    model = gp.Model()

    '''
      Build your own model
    '''

    # Create custom attribute model._vars
    model._vars = model.getVars()

    #Alternative - you can also use the SolFiles parameter to write new solutions to disk.
    model.params.SolFiles = "solution"

    model.optimize(mycallback)

    If you have further questions, feel free to contact us again.

     

    Best regards,
    Chung-Kyun Han

    0

投稿コメントは受け付けていません。