问题描述
大家好,
我正在尝试为表单的一个非常简单的 QP 设置一个抽象模型
I am trying to set up an abstract model for a very simple QP of the form
最小 (x-x0)^2
min (x-x0)^2
s.t.
A x = b
C x
我想使用抽象模型,因为我需要解决不断变化的参数(主要是 x0,但也可能是 A、b、C、d).我现在正在努力在模型实例中简单地设置参数.我不想使用外部数据文件,而是使用内部 python 变量.我在网上找到的所有示例都使用 AMPL 格式的数据文件.
I would like to use an abstract model, as I need to resolve with changing parameters (mainly x0, but potentially also A, b, C, d). I am right now struggeling with simply setting the parameters in the model instance. I do not want to use an external data file, but rather internal python variables. All examples I find online use AMPL formatted data files.
这是我现在拥有的代码
import pyomo.environ as pe
model = pe.AbstractModel()
# the sets
model.n = pe.Param(within=pe.NonNegativeIntegers)
model.m = pe.Param(initialize = 1)
model.ss = pe.RangeSet(1, model.n)
model.os = pe.RangeSet(1, model.m)
# the starting point and the constraint parameters
model.x_hat = pe.Param(model.ss)
model.A = pe.Param(model.os, model.ss)
model.b = pe.Param(model.os)
model.C = pe.Param(model.os, model.os)
model.d = pe.Param(model.ss, model.os)
# the decision variables
model.x_projected = pe.Var(model.ss)
# the cosntraints
# A x = b
def sum_of_elements_rule(model):
value = model.A * model.x_projected
return value == model.d
model.sumelem = pe.Constraint(model.os, rule=sum_of_elements_rule)
# C x <= d
def positivity_constraint(model):
return model.C*model.x_projected <= model.d
model.bounds = pe.Constraint(model.ss, rule=positivity_constraint)
# the cost
def cost_rule(model):
return sum((model.x_projected[i] - model.x[i])**2 for i in model.ss)
model.cost = pe.Objective(rule=cost_rule)
instance = model.create_instance()
不知何故,我被卡住了.我现在如何设置参数?
And somehow here I am stuck. How do I set the parameters now?
谢谢,最好,西奥
推荐答案
我知道这是一篇旧帖子,但解决此问题的方法可能对我有所帮助,因此这里是此问题的解决方案:
I know this is an old post but a solution to this could have helped me so here is the solution to this problem:
## TEST
data_init= {None: dict(
n = {None : 3},
d = {0:0, 1:1, 2:2},
x_hat = {0:10, 1:-1, 2:-100},
b = {None: 10}
)}
# create instance
instance = model.create_instance(data_init)
这以与您所做的相同的方式创建实例,但以更正式的方式创建.
This creates the instance in an equivalent way than what you did but in a more formal way.
这篇关于PYOMO:如何使用带有内部数据的抽象模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!