Reading matrix variables in in callback / Python matrix API
AnsweredI'm attempting to solve a MIP with a 1-dimensional matrix variable "visitors" (integer), using the new Python matrix API.
In a user callback, I want to read out the optimal fractional solution in the current node.
This is the callback code:
def mycallback(m, where):
C = GRB.Callback
if where != C.MIPNODE:
return
status = m.cbGet(C.MIPNODE_STATUS)
if status != GRB.OPTIMAL:
return
n = m._cbcount
m._cbcount += 1
print(f"Callback #{n} at optimal relaxation solution in node")
# get relaxed solution
v = m.cbGetNodeRel([m._visitors])
vv = v.getAttr('x')
I expect vv to be a numpy array containing the optimal fractional values.
My setup code is as follows:
visitors = m.addMVar(DAYS, vtype=GRB.INTEGER, lb=MIN_PER_DAY, ub=MAX_PER_DAY, name="visitors")
m._visitors = visitors
Unfortunately, reading out an MVar in a callback does not seem to work.
I get this exception. Any advice?
(Using a list or a single MVar in cbGetNodeRel does not make a difference.)
Callback #8567 at optimal relaxation solution in node
Traceback (most recent call last):
File "callback.pxi", line 180, in gurobipy.CallbackClass.callback
File "optimize.py", line 39, in mycallback
v = m.cbGetNodeRel([m._visitors])
File "model.pxi", line 5878, in gurobipy.Model.cbGetNodeRel
File "mvar.pxi", line 67, in gurobipy.MVar.__getattr__
File "mvar.pxi", line 174, in gurobipy.MVar.getAttr
File "attrutil.pxi", line 23, in gurobipy.__getattrinfo
AttributeError: 'gurobipy.MVar' object has no attribute '__cindex__'
-
Official comment
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?. -
Hi Sven,
Thank you for pointing this out! This is indeed a missing feature and we will most likely add it for the next version.
Cheers,
Matthias0 -
I wonder about one detail in your message though: In your callback you do
v = m.cbGetNodeRel([m._visitors])
vv = v.getAttr('x')where m._visitors is an MVar object, so my expectation would be that v (and not vv) is an ndarray containing the relaxation values for m._visitors. What would you expect v to be instead?
0 -
Dear Robert,
probably you're right. I thought that v would be something like an Mvar populated with the values in attribute x, but I suppose cbGet NodeRel gives you directly the ndarray? In any case, the error suggests that this is indeed not implemented yet.
Thanks for the observation.
Best,
Sven
0 -
Hello Sven,
in the next bugfix release 9.0.1 (due in the next few weeks or so), you'll be able to query relaxation and solution values on MVar objects in the callback. The result of such a query is an ndarray of the same shape as the MVar itself.
Robert
0 -
Hello Robert,
that is excellent news; thank you.
Sven
0
Post is closed for comments.
Comments
6 comments