A demonstration of the ease with which a novice could build experience by building a simple yet functional notebook that combines Python, MIP and ticdat
.
This notebook reads a diet problem data set from the local file "diet_sample_data.xlsx". It optimizes the model, and if the solution is feasible, it displays the solution information.
Once a notebook like this is working, it should be an easy task to recycle the code into a robust, stand-alone solver such as this.
In [1]:
from ticdat import TicDatFactory
input_schema = TicDatFactory (
categories = [["Name"],["Min Nutrition", "Max Nutrition"]],
foods = [["Name"],["Cost"]],
nutrition_quantities = [["Food", "Category"], ["Quantity"]])
In [2]:
dat = input_schema.xls.create_tic_dat("diet_sample_data.xlsx")
In [3]:
import gurobipy as gu
mdl = gu.Model("diet")
In [4]:
nutrition = {c:mdl.addVar(lb=n["Min Nutrition"], ub=n["Max Nutrition"], name=c)
for c,n in dat.categories.items()}
buy = {f:mdl.addVar(name=f) for f in dat.foods}
In [5]:
for c in dat.categories:
mdl.addConstr(gu.quicksum(dat.nutrition_quantities[f,c]["Quantity"] * buy[f]
for f in dat.foods) == nutrition[c],
name = c)
In [6]:
mdl.setObjective(gu.quicksum(buy[f] * c["Cost"] for f,c in dat.foods.items()),
sense=gu.GRB.MINIMIZE)
mdl.optimize()
In [7]:
mdl.status == gu.GRB.OPTIMAL
Out[7]:
In [8]:
for f,x in buy.items():
if x.x > 0:
print "%-20s %s"%(f, x.x)
In [9]:
for c,x in nutrition.items():
print "%-20s %s"%(c, x.x)
In [10]:
print "Total Cost: %s"%sum(dat.foods[f]["Cost"] * x.x for f,x in buy.items())
In [ ]: