我希望有人能帮助我。我正在练习优化建模,并且正在使用 pyomo glpk 解决以下 LP 问题:
最大 z = 4x1 + 3x2
服从:
我的代码如下:
# Defining the model
model = pyo.ConcreteModel()
# Decision variables
model.x1 = pyo.Var(within = pyo.NonNegativeReals)
x1 = model.x1
model.x2 = pyo.Var(within = pyo.NonPositiveReals)
x2 = model.x2
# Objective function
model.Obj = pyo.Objective(expr = 4*x1+3*x2, sense = pyo.maximize)
# Constraints
model.Const1 = pyo.Constraint(expr = x1+x2<=40)
model.Const2 = pyo.Constraint(expr = 2*x1+x2<=60)
# Run the solver
optm = SolverFactory('glpk')
results = optm.solve(model)
# Show the results
print(results)
print('Objective function = ', model.Obj())
print('x1 = ', x1())
print('x2 = ', x2())
我得到的结果是:
Problem:
- Name: unknown
Lower bound: 120.0
Upper bound: 120.0
Number of objectives: 1
Number of constraints: 3
Number of variables: 3
Number of nonzeros: 5
Sense: maximize
Solver:
- Status: ok
Termination condition: optimal
Statistics:
Branch and bound:
Number of bounded subproblems: 0
Number of created subproblems: 0
Error rc: 0
Time: 0.012318611145019531
Solution:
- number of solutions: 0
number of solutions displayed: 0
Objective function = 120.0
x1 = 30.0
x2 = 0.0
但是,结果应该是:
Object function = 140.0
x1 = 20.0
x2 = 20.0
由于我只使用线性方程,我相信它既是凸的又是凹的,不确定这种情况下是否存在局部最优?
否则,谁能告诉我我做错了什么?
提前非常感谢您的帮助!
您走在正确的道路上。你有一个不幸的打字错误正在困扰着你。您将
x2
的域声明为非 正,您明确希望 pyo.NonNegativeReals
如果您有奇怪的行为,请始终
pprint
和/或display
您的模型。错误往往很快就会显现出来。 pprint
显示了构造,display
类似,但显示了带有值的表达式的求值。
2 个其他小问题...我不会重命名你的变量,只需将它们键入即可。另外,我相信 value(var) 是访问值的首选方式。这是经过一些编辑的工作版本。
import pyomo.environ as pyo
# Defining the model
model = pyo.ConcreteModel()
# Decision variables
model.x1 = pyo.Var(within = pyo.NonNegativeReals)
# x1 = model.x1
model.x2 = pyo.Var(within = pyo.NonNegativeReals)
# x2 = model.x2
# Objective function
model.Obj = pyo.Objective(expr = 4*model.x1+3*model.x2, sense = pyo.maximize)
# Constraints
model.Const1 = pyo.Constraint(expr = model.x1+model.x2<=40)
model.Const2 = pyo.Constraint(expr = 2*model.x1+model.x2<=60)
# Run the solver
optm = pyo.SolverFactory('glpk')
results = optm.solve(model)
model.display()
# Show the results
print(results)
print('Objective function = ', pyo.value(model.Obj))
print('x1 = ', pyo.value(model.x1))
print('x2 = ', pyo.value(model.x2))