I am trying to figure out how I can write this objective function into python using Gurobi. I have to minimize the sum of the product of three dictionary's values. The reason I am confused is that while the first two dictionaries I am multiplying are the same length (somewhere in the thousands), the third has only 12 items. Also the first two dictionaries have tuple keys and the third does not.
The first dictionary ASSG
is a decision variable that has the format:
ASSG = {('Abilene, TX', 'Boston, MA'): <gurobi.Var ASSG[Abilene, TX,Boston, MA]>,
('Abilene, TX', 'Chicago, IL'): <gurobi.Var ASSG[Abilene, TX,Chicago, IL]>,
('Abilene, TX', 'Dallas, TX'): <gurobi.Var ASSG[Abilene, TX,Dallas, TX]>,
('Abilene, TX', 'Denver, CO'): <gurobi.Var ASSG[Abilene, TX,Denver, CO]>,
...}
The second dictionary is miles
and it has the following format:
miles = {('Abilene, TX', 'Boston, MA'): 2091.92,
('Abilene, TX', 'Chicago, IL'): 1148.37,
('Abilene, TX', 'Dallas, TX'): 189.87,
('Abilene, TX', 'Denver, CO'): 775.6,
...}
The third dictionary is called Demand
and it looks like:
Demand = {'Boston, MA': 1051,
'Chicago, IL': 940,
'Dallas, TX': 1131,
'Denver, CO': 466,
'Los Angeles, CA': 1301,
'Richmond, VA': 1171,
'Miami, FL': 1463,
'New York, NY': 1120,
'Phoenix, AZ': 665,
'Pittsburgh, PA': 1280,
'San Fransisco, CA': 615,
'Seattle, WA': 528}
I think what I need to do is multiply all of the values where the keys in Demand
match the second element in the tuple of ASSG
and miles
's keys. i.e. All the items with 'Boston, MA'
get multiplied, all the Chicagos, all the Dallases...
I have tried multiplying them separately and then using quicksum but I receive an error:
a = {k: ASSG[k]*miles[k] for k in ASSG}
b = {k:Demand.get(k[1], 1)* v for k,v in x.items()}
m.setObjective(quicksum(b.values()))
m.ModelSense = GRB.MINIMIZE
m.update()
GurobiError: Variable not in model
x
that you used in defininingb
? Is itASSG
variable? 2) If what you want is something like $\sum\limits_{ij}\text{demand}_i\times \text{miles}_{ij}\times \text{ASSG}_{ij}$ then just loop overi
andj
. something like:quicksum(Demand[i]*miles[i,j]*val for (i,j), val in ASSG.items())
$\endgroup$ – EhsanK♦ Oct 17 '19 at 5:17ValueError: too many values to unpack (expected 2)
$\endgroup$ – Jacob Myer Oct 18 '19 at 0:51items()
afterASSG
. Without that, you're just looping over the keys and that's why it told you expected only 2. $\endgroup$ – EhsanK♦ Oct 18 '19 at 1:31KeyError: 'Abilene, TX'
, I fixed this by changingDemand[i]
toDemand[j]
. This allowed the model to run but there is another issue: no solution was found. I am assuming this has to do with the constraints we discussed here (or.stackexchange.com/questions/2837/…) as this is the same model @EhsanK $\endgroup$ – Jacob Myer Oct 18 '19 at 2:31