本文介绍了Pyomo:带有 if 语句的约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试解决这个问题.我需要使这家公司的利润最大化.

I am currently trying to solve this problem. I need to maximize the profit of this company.

这是我目前拥有的代码:

That s the code I currently have:

from pyomo.environ import *
from pyomo.opt import *
opt = solvers.SolverFactory("ipopt")
model = ConcreteModel()

model.x1 = Var(within=NonNegativeIntegers)
model.x2 = Var(within=NonNegativeIntegers)
model.y1 = Var(within=NonNegativeIntegers)
model.y2 = Var(within=NonNegativeIntegers)
model.b1 = Var(within=Boolean)
model.b2 = Var(within=Boolean)

model.c1 = Constraint(expr = model.x1 + model.x2 + model.y1 + model.y2 <=   7000)
model.c2 = Constraint(expr = 2*model.x1 + 2*model.x2 + model.y1 + model.y2 <= 10000)
model.c3 = Constraint(expr = model.x1  <= 2000)
model.c4 = Constraint(expr = model.x2 <= 1000)
model.c5 = Constraint(expr = model.y1 <= 2000)
model.c6 = Constraint(expr = model.y2 <= 3000)


model.z = Objective(expr= (150*model.x1 + 180*model.x2*model.b1 + 100*model.y1 + 110*model.y2*model.b2), sense=maximize)
results = opt.solve(model)

这是我尝试为我的约束编写的代码,然后只使用第一个斜率,只要它不超过 2000 个产品:

This is the code I tried to write for my constraint which is then only using the first slope as long as it does not exceed 2000 products:

def ObjRule(model):
 if model.x1 >= 2000:
     return model.b1==1
 if model.x2 >= 2000:
     return model.b2 == 1`

如果有人有提示,我该怎么做就太好了.

If someone would have a hint, how I could proceed that would be great.

先谢谢你,帕特里克

推荐答案

在 Pyomo 中,规则不是发送到求解器的回调.它们为每个索引调用一次以获得一组静态表达式.这组表达式是发送到求解器的内容.您在规则内部使用的任何 if 逻辑不应涉及变量的值(除非它基于变量的初始值,在这种情况下,无论您在主表达式之外使用它的任何地方,您都将变量包装在 value() 中返回).

In Pyomo, rules are not callbacks sent to a solver. They are called once for each index to obtain a static set of expressions. This set of expressions is what is sent to a solver. Any if-logic you use inside of rules should not involve the values of variables (unless it is based on the initial value of a variable, in which case you would wrap the variable in value() wherever you use it outside of the main expression that is returned).

如果要对分段函数进行建模,则需要应用某种建模技巧.在某些情况下,这涉及引入离散变量(参见 examples分段分量),在其他情况下则不然(例如,当最大化可以表示为有限数量仿射函数的最小值的分段函数时).

If you want to model a piecewise function, you need to apply some kind of modeling trick to do so. In some cases this involves introducing discrete variables (see examples for the Piecewise component), in other cases it does not (for instance when maximizing a piecewise function that can be expressed as the min of a finite number of affine functions).

这篇关于Pyomo:带有 if 语句的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:30