Skip to main content

How to query constraints in callback function?



1 comment

  • Jaromił Najman
    Gurobi Staff Gurobi Staff

    Hi Wissal,

    This is not possible.

    However, with a bit of hacking and the use of callbacks it can be achieved.You can create a copy of your model for which you fix the lower and upper bounds to the feasible point value obtained via cbGetSolution and found in the MIPSOL callback. You then optimize this copy (this is a trivial solve, since all variables are fixed) and finally retrieve the information you need. Please note that you cannot access user cuts/lazy constraints.

    An example code would be

    import gurobipy as gp
    from gurobipy import GRB

    def mycallback(model,where):
    if where == GRB.Callback.MIPSOL:
    # get feasible point values
    vals = model.cbGetSolution(model._vars)
    # get copy model's variable and fix them
    vars = model._copy.getVars()
    for i in range(len(vars)):
    vars[i].lb = vals[i]
    vars[i].ub = vals[i]
    # run a trivial optimize and access constraint values of copy model
    for c in model._copy.getConstrs():
    print("constraint %s: %f %s= %f"%(c.ConstrName,model._copy.getRow(c).getValue(),c.Sense,c.RHS))
    # reset all copy model bounds (not neccessary)

    # read example model
    model ="/Library/gurobi912/mac64/examples/data/glass4.mps")
    # save original vars to access them in callback
    model._vars = model.getVars()
    # create copy of the original model and suppress output
    model._copy = model.copy()

    Best regards,


Please sign in to leave a comment.