解决绑定到总和的优化

时间:2019-01-30 19:16:25

标签: python optimization linear-programming nonlinear-optimization

我正在研究一个优化问题,类似于The Stigler diet 而不是示例中的大量属性,我仅具有属性:碳水化合物和蛋白质。

该食品有N罐装,每种罐头具有不同的特性和价格。目的是获得更便宜的组合,以获得C公斤蛋白质值> = a和碳水化合物> = b的食物。为此,我被允许拿走一部分内容或整个罐头。

food = ["f1","f2","f3","f4"]
kg_available = [10,2,5,8]
protein =       [17,12,16,8]
carbohydrates = [10,14,13,16]
price_per_kg =  [15,11,17,12]



df = pd.DataFrame({"food":food,"kg_available":kg_available,"protein":protein,"carbohydrates":carbohydrates,"price_per_kg":price_per_kg})

enter image description here

这是要求的样本:

##            protein,carbohydrates,kg
requirement = [15.5,12.3,11]

E.G。我想要2公斤含15.5蛋白质和12.3碳水化合物的食物。

按照Google网站上的示例,我有以下代码:

data = [
['f1', 10, 15, 17, 10],
['f2', 2, 11, 12, 14],
['f3', 5, 17, 16, 13],
['f4', 8, 12, 8, 16]
]

nutrients = [
    ["protein",15.5],
    ["carbohydrates",12.3]]


food = [[]] * len(data)

# Objective: minimize the sum of (price-normalized) foods.
objective = solver.Objective()
for i in range(0, len(data)):
    food[i] = solver.NumVar(0.0, solver.infinity(), data[i][0])
    objective.SetCoefficient(food[i], 4)
objective.SetMinimization()

# Create the constraints, one per nutrient.

constraints = [0] * len(nutrients)
for i in range(0, len(nutrients)):
    constraints[i] = solver.Constraint(nutrients[i][1], solver.infinity())
    for j in range(0, len(data)):
        constraints[i].SetCoefficient(food[j], data[j][i+3])


status = solver.Solve()

if status == solver.OPTIMAL:
    # Display the amounts (in dollars) to purchase of each food.
    price = 0
    num_nutrients = len(data[i]) - 3
    nutrients = [0] * (len(data[i]) - 3)
    for i in range(0, len(data)):
        price += food[i].solution_value()

        for nutrient in range(0, num_nutrients):
            nutrients[nutrient] += data[i][nutrient+3] * food[i].solution_value()

        if food[i].solution_value() > 0:
            print ("%s = %f" % (data[i][0], food[i].solution_value()))

    print ('Optimal  price: $%.2f' % (price))
else:  # No optimal solution was found.
    if status == solver.FEASIBLE:
        print ('A potentially suboptimal solution was found.')
    else:
        print ('The solver could not solve the problem.')

几乎可以正常工作,它返回以下结果:

f1 = 0.077049
f3 = 0.886885
Optimal  price: $0.96

那将是正确的,除了不考虑我也需要2千克并且每罐的库存有限的那部分。

如何将这种约束添加到问题中?

0 个答案:

没有答案