4 Copyright (c) by Joao Pedro PEDROSO and Mikio KUBO, 2012
7 from pyscipopt
import Model, quicksum, multidict
10 def diet(F, N, a, b, c, d):
11 """diet -- model for the modern diet problem
15 - a[i]: minimum intake of nutrient i
16 - b[i]: maximum intake of nutrient i
17 - c[j]: cost of food j
18 - d[j][i]: amount of nutrient i in food j
19 Returns a model, ready to be solved.
22 model = Model(
"modern diet")
27 x[j] = model.addVar(vtype=
"I", name=
"x(%s)" % j)
28 y[j] = model.addVar(vtype=
"B", name=
"y(%s)" % j)
30 z[i] = model.addVar(lb=a[i], ub=b[i], name=
"z(%s)" % j)
31 v = model.addVar(vtype=
"C", name=
"v")
35 model.addCons(
quicksum(d[j][i] * x[j]
for j
in F) == z[i], name=
"Nutr(%s)" % i)
37 model.addCons(
quicksum(c[j] * x[j]
for j
in F) == v, name=
"Cost")
40 model.addCons(y[j] <= x[j], name=
"Eat(%s)" % j)
43 model.setObjective(
quicksum(y[j]
for j
in F),
"maximize")
44 model.data = x, y, z, v
50 """make_inst: prepare data for the diet model"""
52 "QPounder": [1.84, {
"Cal": 510,
"Carbo": 34,
"Protein": 28,
53 "VitA": 15,
"VitC": 6,
"Calc": 30,
"Iron": 20}],
54 "McLean": [2.19, {
"Cal": 370,
"Carbo": 35,
"Protein": 24,
"VitA": 15,
55 "VitC": 10,
"Calc": 20,
"Iron": 20}],
56 "Big Mac": [1.84, {
"Cal": 500,
"Carbo": 42,
"Protein": 25,
57 "VitA": 6,
"VitC": 2,
"Calc": 25,
"Iron": 20}],
58 "FFilet": [1.44, {
"Cal": 370,
"Carbo": 38,
"Protein": 14,
59 "VitA": 2,
"VitC": 0,
"Calc": 15,
"Iron": 10}],
60 "Chicken": [2.29, {
"Cal": 400,
"Carbo": 42,
"Protein": 31,
61 "VitA": 8,
"VitC": 15,
"Calc": 15,
"Iron": 8}],
62 "Fries": [.77, {
"Cal": 220,
"Carbo": 26,
"Protein": 3,
63 "VitA": 0,
"VitC": 15,
"Calc": 0,
"Iron": 2}],
64 "McMuffin": [1.29, {
"Cal": 345,
"Carbo": 27,
"Protein": 15,
65 "VitA": 4,
"VitC": 0,
"Calc": 20,
"Iron": 15}],
66 "1% LFMilk": [.60, {
"Cal": 110,
"Carbo": 12,
"Protein": 9,
67 "VitA": 10,
"VitC": 4,
"Calc": 30,
"Iron": 0}],
68 "OrgJuice": [.72, {
"Cal": 80,
"Carbo": 20,
"Protein": 1,
69 "VitA": 2,
"VitC": 120,
"Calc": 2,
"Iron": 2}],
75 "Protein": [55,
None],
82 return F, N, a, b, c, d
85 if __name__ ==
"__main__":
89 for b[
"Cal"]
in [
None, 3500, 3000, 2500]:
91 print(
"\nDiet for a maximum of {0} calories".format(b[
"Cal"]
if b[
"Cal"] !=
None else "unlimited"))
92 model =
diet(F, N, a, b, c, d)
96 print(
"Optimal value:", model.getObjVal())
97 x, y, z, v = model.data
99 if model.getVal(x[j]) > 0:
100 print(
"{0:30s}: {1:3.1f} dishes --> {2:4.2f} added to objective".format(j, model.getVal(x[j]),
102 print(
"amount spent:", model.getObjVal())
104 print(
"amount of nutrients:")
106 print(
"{0:30s}: {1:4.2f}".format(i, model.getVal(z[i])))