Request that Model.cbGetSolution() can also take expressions as arguments
AnsweredAs an example, if v1 and v2 are binary variables, it would be nice to be able to call
result = model.cbGetSolution(v1 + v2)
instead of
result = model.cbGetSolution(v1) + model.cbGetSolution(v2)
or
result = sum(model.cbGetSolution([v1, v2])

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 
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 
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.
Comments
3 comments