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

How to query constraints in callback function?

回答済み

コメント

2件のコメント

  • 正式なコメント
    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?.
  • 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
    model._copy.optimize()
    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)
    model._copy.reset()

    # read example model
    model = gp.read("/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()
    model._copy.setParam("OutputFlag",0)
    model.optimize(mycallback)

    Best regards,
    Jaromił

    0

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