代码之家  ›  专栏  ›  技术社区  ›  Luis Ramon Ramirez Rodriguez

求一个复合和的最优解

  •  1
  • Luis Ramon Ramirez Rodriguez  · 技术社区  · 5 年前

    我正在研究一个优化问题,类似于 The Stigler diet 在这个例子中,我没有列出大量的属性,我只讨论了属性:碳水化合物和蛋白质。

    这种食物有N个罐头,每一个都有不同的性质和价格。其目的是获得更便宜的组合,以获得蛋白质值为a且碳水化合物值为b的C kg食品。为此,允许取其含量的任何部分或整个罐头。

    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]
    

    按照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 回复  |  直到 5 年前