问题
I am using Gurobi 6.0 with Python 2.7. I am curious to know if Gurobi allows the objective function to have values coming from a dictionary with indices of the decision variables. Attaching the code:
from gurobipy import *
d = {
(0, 0): 0,
(0, 1): -5,
(1, 0): 4,
(1, 1): 2,
(2, 0): 0,
(0, 2): 10
}
m = Model()
x = m.addVar(vtype=GRB.INTEGER)
y = m.addVar(vtype=GRB.INTEGER)
m.update()
m.addConstr(x + y <= 2)
m.setObjective(d[(x, y)], GRB.MAXIMIZE)
m.optimize()
print m.objVal
print x.x
print y.x
The answer to the model was
-5.0
-0.0
-0.0
which clearly makes no sense because max(d[(x,y)]) = 10 happens at x=0 and y=2 as per the given data. What is the issue here? Does Gurobi even allow such dictionary references ? Is it even allowed?
回答1:
For a somewhat complex causal chain d[(x,y)]
in your code is equivalent to d[(0,1)]
, so the constant -5 winds up being your objective function. The reasons are
- gurobi.Var has __hash__ defined
- gurobi.Var has __cmp__ defined. It always returns a truthy object
- In your case, x and y have hash values of 0 and 1
- The python dictionary lookup algorithm resolves d[(x,y)] to d[(0,1)]
What you are trying to do doesn't fit into the integer programming framework. The best way to put this into gurobi is to add indicator variables that x and y take on specific values.
来源:https://stackoverflow.com/questions/28261089/gurobi-objective-with-python-dictionary-values