Skip to content

Instantly share code, notes, and snippets.

@nmische
Created November 5, 2013 15:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmische/7320488 to your computer and use it in GitHub Desktop.
Save nmische/7320488 to your computer and use it in GitHub Desktop.
Gurobi solution for the second transportation problem in An Illustrated Guide to Linear Programming.
from gurobipy import *
try:
cities = ['OklahomaCity','Macon','Columbus']
bases = ['MacDill','March','DavisMonthan','McConnell','Pinecastle']
distance = {
('OklahomaCity','MacDill'): 938,
('OklahomaCity','March'): 1030,
('OklahomaCity','DavisMonthan'): 824,
('OklahomaCity','McConnell'): 136,
('OklahomaCity','Pinecastle'): 995,
('Macon','MacDill'): 346,
('Macon','March'): 1818,
('Macon','DavisMonthan'): 1416,
('Macon','McConnell'): 806,
('Macon','Pinecastle'): 296,
('Columbus','MacDill'): 905,
('Columbus','March'): 1795,
('Columbus','DavisMonthan'): 1590,
('Columbus','McConnell'): 716,
('Columbus','Pinecastle'): 854
}
supply = {
('OklahomaCity'): 8,
('Macon'): 5,
('Columbus'): 8
}
demand = {
('MacDill'): 3,
('March'): 5,
('DavisMonthan'): 5,
('McConnell'): 5,
('Pinecastle'): 3
}
# Create a new model
m = Model("transport_problem_2")
# Create variables
flow = {}
for c in cities:
for b in bases:
flow[c,b] = m.addVar(obj=distance[c,b], name='flow_%s_%s' % (c, b))
# Integrate new variables
m.update()
# Add supply constraints
for c in cities:
m.addConstr(quicksum(flow[c,b] for b in bases) == supply[c], 'supply_%s' % (c))
# Add demand constraints
for b in bases:
m.addConstr(quicksum(flow[c,b] for c in cities) == demand[b], 'demand_%s' % (b))
# Optimize the model. The default ModelSense is to is to minimize the objective, which is what we want.
m.optimize()
# Print solution
if m.status == GRB.status.OPTIMAL:
print '\nOptimal flows :'
for c in cities:
for b in bases:
print c, '->', b, ':', flow[c,b].x
except GurobiError:
print 'Error reported'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment