Skip to main content

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

Answered

Comments

1 comment

  • 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

Please sign in to leave a comment.