Skip to main content

Request that Model.cbGetSolution() can also take expressions as arguments

Answered

Comments

3 comments

  • Xavier Nodet
    Gurobi Staff Gurobi Staff

    Dear Micheal,

    I'm afraid I don't really see what value would be added with such a feature...  

    If you have the expression already in your program (as an instance of GRBExpr, GRBLinExpr, etc), you could instead turn that expression into a variable, add that variable to your model, and use it to get the value you're looking for. If you don't have the expression already built, then you have to construct it just before calling cbGetSolution, and I don't really see how this is easier for you than computing the value.

    Could you please elaborate on the benefits you expect?

    0
  • Michael Chan
    Gurobi-versary
    First Comment
    First Question

    Hi Xavier,

    I'm very used to writing constraints in this way

    model.add_constraint(gp.quicksum(variables[a, b, c] for a in list_a for b in list_b for c in list_c) <= 1) # where variables is a dict of gurobi variables

    that I always get thrown off when I get an error trying to do the same thing with model.cbGetSolution(), e.g.,

    result = model.cbGetSolution(gp.quicksum(variables[a, b, c] for a in list_a for b in list_b for c in list_c))

    Turning expressions into variables beforehand works in some cases, but not all due to requiring an exponential number of variables.

    0
  • Riley Clement
    Gurobi Staff Gurobi Staff

    Hi Michael,

    Here's a couple of code patterns that might be close to your preferred style.  The first attaches the solution value to each variable using an attribute.  The second creates a tupledict mapping keys to values, and assumes your variables are stored as a dict or tupledict.

    def callback(m, where):
        if where == gp.GRB.Callback.MIPSOL:
            vars = [v1, v2, v3]
          for v, _x in zip(vars, m.cbGetSolution(vars)):
                v._x = _x
            result = gp.quicksum(v._x for v in vars)
            result2 = 2*v1._x - v2._x


    # x is a tupledict of variables
    def callback(m, where):
        if where == gp.GRB.Callback.MIPSOL:
            x_ = gp.tupledict(zip(x.keys(), m.cbGetSolution(x.values())))
            result1 = gp.quicksum(x_.select("*", 3))
            result2 = x_[2,4] + 5*x_[0,1]

    - Riley

    0

Please sign in to leave a comment.