gpt4 book ai didi

python - 将步长添加到线性优化中

转载 作者:行者123 更新时间:2023-11-30 21:59:41 24 4
gpt4 key购买 nike

我正在研究类似于 pulp example 的混合问题

我有这个限制来确保生产的数量是所需的数量

prob += lpSum([KG[i] * deposit_vars[i] for i in deposit]) == 64, "KGRequirement"

但是我还需要为不同于零的最小值添加另一个约束,这是因为我不方便,例如,0.002KG的一种成分,我必须采取0或至少2公斤,因此有效案例例如0、2、2.3、6、3.23。

我尝试这样做:

for i in deposit:
prob += (KG[i] * deposit_vars[i] == 0) or (TM[i] * deposit_vars[i] >= 30)

但这不起作用,只会使问题变得不可行

编辑

这是我当前的代码:

import pulp
from pulp import *
import pandas as pd

food = ["f1","f2","f3","f4"]
KG = [10,20,50,80]
Protein = [18,12,16,18]
Grass = [13,14,13,16]
price_per_kg = [15,11,10,22]

## protein,carbohydrates,kg

df = pd.DataFrame({"tkid":food,"KG":KG,"Protein":Protein,"Grass":Grass,"value":price_per_kg})


deposit = df["tkid"].values.tolist()

factor_volumen = 1



costs = dict((k,v) for k,v in zip(df["tkid"],df["value"]))
Protein = dict((k,v) for k,v in zip(df["tkid"],df["Protein"]))
Grass = dict((k,v) for k,v in zip(df["tkid"],df["Grass"]))
KG = dict((k,v) for k,v in zip(df["tkid"],df["KG"]))

prob = LpProblem("The Whiskas Problem", LpMinimize)
deposit_vars = LpVariable.dicts("Ingr",deposit,0)
prob += lpSum([costs[i]*deposit_vars[i] for i in deposit]), "Total Cost of Ingredients per can"

#prob += lpSum([deposit_vars[i] for i in deposit]) == 1.0, "PercentagesSum"
prob += lpSum([Protein[i] *KG[i] * deposit_vars[i] for i in deposit]) >= 17.2*14, "ProteinRequirement"
prob += lpSum([Grass[i] *KG[i] * deposit_vars[i] for i in deposit]) >= 12.8*14, "FatRequirement"
prob += lpSum([KG[i] * deposit_vars[i] for i in deposit]) == 14, "KGRequirement"
prob += lpSum([KG[i] * deposit_vars[i] for i in deposit]) <= 80, "KGRequirement1"

prob.writeLP("WhiskasModel.lp")
prob.solve()
# The status of the solution is printed to the screen
print ("Status:", LpStatus[prob.status])

# Each of the variables is printed with it's resolved optimum value
for v in prob.variables():
print (v.name, "=", v.varValue)

# The optimised objective function value is printed to the screen
print ("Total Cost of Ingredients per can = ", value(prob.objective))

我要添加的新约束在这部分:

prob += lpSum([KG[i] * deposit_vars[i] for i in deposit]) <= 80, "KGRequirement1"

我希望产品 KG[i] * Deposit_vars[i] 为 0 或介于 ab 之间

最佳答案

在传统的线性规划公式中,所有变量、目标函数和约束都需要是连续的。您要问的是如何使该变量成为离散变量,即它只能接受值 a,b,... 而不能接受两者之间的任何值。当连续变量和离散变量组合时,称为混合整数问题 (MIP)。 See PuLP documentation that reflects this explanation.我建议你仔细阅读“整数”中提到的混合问题;它们分散在页面各处。根据PuLP的文档,它可以通过调用外部MIP求解器来解决MIP问题,其中一些求解器已经包含在内。

如果没有最小的工作示例,解释如何实现它会有点棘手。一种方法是将变量指定为整数,并将其值作为字典。保留默认解算器,COIN-OR's CBC solver求解器,然后将求解 MIP。同时,这里有一些资源可供您继续前进:

关于python - 将步长添加到线性优化中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54520146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com