Created
November 5, 2013 15:08
-
-
Save nmische/7320435 to your computer and use it in GitHub Desktop.
Gurobi solution for the first transportation problem in An Illustrated Guide to Linear Programming.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from gurobipy import * | |
try: | |
factories = ['FactoryOne','FactoryTwo'] | |
stores = ['StoreOne','StoreTwo','StoreThree'] | |
cost = { | |
('FactoryOne','StoreOne'): 8, | |
('FactoryOne','StoreTwo'): 6, | |
('FactoryOne','StoreThree'): 10, | |
('FactoryTwo','StoreOne'): 9, | |
('FactoryTwo','StoreTwo'): 5, | |
('FactoryTwo','StoreThree'): 7 | |
} | |
supply = { | |
('FactoryOne'): 11, | |
('FactoryTwo'): 14 | |
} | |
demand = { | |
('StoreOne'): 10, | |
('StoreTwo'): 8, | |
('StoreThree'): 7 | |
} | |
# Create a new model | |
m = Model("transport_problem_1") | |
# Create variables | |
flow = {} | |
for f in factories: | |
for s in stores: | |
flow[f,s] = m.addVar(obj=cost[f,s], name='flow_%s_%s' % (f, s)) | |
# Integrate new variables | |
m.update() | |
# Add supply constraints | |
for f in factories: | |
m.addConstr(quicksum(flow[f,s] for s in stores) == supply[f], 'supply_%s' % (f)) | |
# Add demand constraints | |
for s in stores: | |
m.addConstr(quicksum(flow[f,s] for f in factories) == demand[s], 'demand_%s' % (s)) | |
# 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 f in factories: | |
for s in stores: | |
print f, '->', s, ':', flow[f,s].x | |
except GurobiError: | |
print 'Error reported' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment