Skip to main content

Stopping the program if best objective has not changed after a while

Answered

Comments

5 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff Gurobi Staff
    This post is more than three 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 why not try our AI Gurobot?.
  • Eli Towle
    • Gurobi Staff Gurobi Staff

    Yes, you can do this with a custom callback. Here is an example of a callback in Python that terminates the solve if the best solution has not improved for 20 seconds:

    import gurobipy as gp
    from gurobipy import GRB
    import time


    def cb(model, where):
    if where == GRB.Callback.MIPNODE:
    # Get model objective
    obj = model.cbGet(GRB.Callback.MIPNODE_OBJBST)

    # Has objective changed?
    if abs(obj - model._cur_obj) > 1e-8:
    # If so, update incumbent and time
    model._cur_obj = obj
    model._time = time.time()

    # Terminate if objective has not improved in 20s
    if time.time() - model._time > 20:
    model.terminate()


    m = gp.Model()

    # Build model here

    # Last updated objective and time
    m._cur_obj = float('inf')
    m._time = time.time()

    m.optimize(callback=cb)

    To solve the model faster, you could try setting the MIPFocus parameter (to 2 or 3, based on your description).

    1
  • Parisa Keshavarz
    • Gurobi-versary
    • First Comment
    • First Question

    Dear Eli,

    Thank you so much for the quick response. I'm actually using MATLAB, is this also possible in MATLAB or any other method? I read that callback is not supported in MATLAB and I'm having difficulty for the speed. Or maybe is there a way to export the code to python without having to rewrite it?

    Thank you

    0
  • Eli Towle
    • Gurobi Staff Gurobi Staff

    Ah, I looked at your previous posts and saw that you had used Python in the past. No, there is unfortunately no way to implement this in MATLAB, nor is there any automatic code generation tool to export your MATLAB/Gurobi code to another language.

    However, moving the model from the MATLAB API to the Python API isn't too hard. You can use the gurobi_write() MATLAB function to export your model to disk as an MPS file. Then, in Python, you can read that model file with the read() function. I.e., instead of constructing a new model with

    m = gp.Model()

    you read in the exported model file with

    m = gp.read('model.mps')

    Leave the rest of the code as-is and run the Python file.

    1
  • Parisa Keshavarz
    • Gurobi-versary
    • First Comment
    • First Question

    Thank you so much Eli.

    0

Post is closed for comments.