首页 > 解决方案 > 使用 python scipy 最小化的线性规划问题

问题描述

我正在尝试使用 python 优化scipy.optimize.minimize一个人使用可用食品并坚持预算的卡路里摄入量。

问题陈述是:有 n 种食物,每种都有不同的数量。他们的价格每天都在变化。每种都有不同的营养价值,每天都会减少。我需要在一个月内购买食物,以使总营养最接近我的目标,并且我使用我确切的每月预算来购买它们。

#df_available has 1 row each for each item's available quantity at the beginning of the month
#df_bought has initial guesses for purchase of each item for each day of the month. This is based on prorated allotment of my total budget to each item on each day.
#df_price has price of each item on each day of the month.
#df_nutrition['nutrition'] has initial nutrition value per unit. it decreases by 1 unit each year, so 1/365 each day.
#strt is start date of the month.
#tot_nutrition is monthly total nutrition target for the month
#tot_budget is my monthly budget

def obj_func():
    return (df_bought.sum()*(df_nutrition['nutrition'] - strt/365).sum())

#constraint 1 makes sure that I buy exactly at my budget
def constraint1():
    return ((df_bought * df_price).sum().sum()- tot_budget)
cons1 = {'type':'eq', 'fun':constraint1}

#constraint 2 makes sure that I dont buy more than available quantity of any item
def constraint2():
    return df_available - df_bought
cons2 = {'type':'ineq', 'fun':constraint2}

cons = ([cons1, cons2])

#bounds ensure that I dont buy negative quantity of any item
bnds = (0, None)

res = minimize(obj_func, df_bought_nominal_m, bounds= bnds, constraints=cons)
print(res)

对于输出,我希望调整 df_bought 值以最小化 obj_function。

该代码给出以下错误:

TypeError: constraint1() takes no arguments (1 given) 

如果我犯了任何新手错误,我深表歉意。我是 python 新手,在网上找不到针对此问题的适当帮助。

标签: pythonscipyminimize

解决方案


推荐阅读