I am working with python dictionaries to define some variables and parameters for a mathematical mode.
The data frame looks like this:
Service Bill Weight Zone Resi UPS FedEx USPS DHL
1DEA 1 2 N 33.02 9999 9999 9999
2DAM 2 2 N 33.02 9999 9999 9999
I have defined some input and variable from this as follow:
cost = {}
for carrier in carriers:
for row in df.to_dict('records'):
key = (row['Service'], row['Bill Weight'],
row['Zone'],row['Resi'], carrier)
cost[key] = row[carrier]
services = df['Service'].unique().tolist()
weights = df['Bill Weight'].unique().tolist()
zones = df['Zone'].unique().tolist()
addresses = df['Resi'].unique().tolist()
My only valid combinations for assign and cost should be:
['1DEA',1,2,'N','UPS']
['1DEA',1,2,'N','FedEx']
['1DEA',1,2,'N','USPS']
['1DEA',1,2,'N','DHL']
['2DAM',2,2,'N','UPS']
['2DAM',2,2,'N','FedEx']
['2DAM',2,2,'N','USPS']
['2DAM',2,2,'N','DHL']
And the following with gurobi python but I am really only concerned about the construction of my loops through python than the gurobi syntax:
Approach A:
assign = {}
for carrier in carriers:
for row in df.to_dict('records'):
key = (row['Service'], row['Bill Weight'],
row['Zone'],row['Resi'], carrier)
cost[key] = row[carrier]
obj = quicksum(cost[key]*assign[key] \
for key in assign)
Now this works fine for making sure the variables and parameters are generated only from dictionary keys and not all possible combinations of services, weights, zones, and addresses. But it won't work when I have specific constraints like below:
m.addConstrs((assign['1DEA', w, z, r, 'UPS']+assign['1DEA', w, z, r, 'USPS']+assign['1DEA', w, z, r, 'USPS 1C']==1\
for i in clients for s in services for w in weights for z in zones for r in addresses),"C02")
Approach 2:
assign = m.addVars(services, weights, zones, addresses, carriers, name = "Assign", vtype=GRB.BINARY)
obj = quicksum(cost[s, w, z, r, l]*assign[ s, w, z, r, l] \
for s in services for w in weights for z in zones for r in addresses for l in carriers)
This way I can easily write all my constraints but it will create all combinations of services, weights, zones, addresses, carriers which makes my model wrong. for example ['2DAM',1,2,'N','UPS'] is not a valid combination.
Is there a way to limit this looping on services, weights, zones, addresses, carriers to only combinations that are defined in cost dictionary keys?