从抽象 pyomo 模型实例化具体模型

instantiate a concrete model from an abstract pyomo model

我试图在 Pyomo 5.1.1 中创建一个抽象模型,然后用 python 中的值填充它(即不使用 AMPL 文件)。我基本上遵循 Pyomo documentation example,但我得到 "Constant objective detected"。

import pyomo.environ as oe
model = oe.AbstractModel()
model.I = oe.Set()
model.J = oe.Set()
model.a = oe.Param(model.I,model.J)
model.b = oe.Param(model.I)
model.c = oe.Param(model.J)
model.x = oe.Var(model.J,domain=oe.NonNegativeReals)
def obj_expression(model):
    return oe.summation(model.c,model.x)

model.OBJ = oe.Objective(rule=obj_expression)
def ax_constraint_rule(model,i):
    return sum(model.a[i,j]*model.x[j] for j in model.J) >= model.b[i]

model.AxbConstraint = oe.Constraint(model.I,rule=ax_constraint_rule)

然后,我尝试用实际值初始化这个模型

aa = np.array([[1,2,1,4],[5,2,2,4]])
bb = np.array([2,4])
cc = np.array([1,2,4,2])

cmodel = model.create_instance()
cmodel.a.values = aa
cmodel.b.values = bb
cmodel.c.values = cc

opt = oe.SolverFactory("glpk")
results = opt.solve(cmodel)

我收到以下错误:

WARNING:pyomo.core:Constant objective detected, replacing with a placeholder to prevent solver failure. WARNING:pyomo.core:Empty constraint block written in LP format - solver may error WARNING: Constant objective detected, replacing with a placeholder to prevent solver failure. WARNING: Empty constraint block written in LP format - solver may error

显然我初始化的方式有问题 cmodel 但我在 python.

中找不到任何描述初始化的文档

如果您不需要从 AMPL .dat 文件加载数据,我建议从 ConcreteModel 开始。在这种情况下,没有必要将数据存储到 Param 对象中,除非您需要它们是可变的。仍然建议为索引组件创建 Set 对象;否则,将使用可能与您添加到模型中的组件冲突的名称隐式创建 Set 对象。

通过将您的 ConcreteModel 定义放在一个将数据作为输入的函数中,您实际上是在复制 AbstractModel 及其 create_instance 方法提供的功能。例如,

import pyomo.environ as oe

def build_model(a, b, c):
    m = len(b)
    n = len(c)
    model = oe.ConcreteModel()
    model.I = oe.Set(initialize=range(m))
    model.J = oe.Set(initialize=range(n))
    model.x = oe.Var(model.J,domain=oe.NonNegativeReals)

    model.OBJ = oe.Objective(expr= oe.summation(c,model.x))
    def ax_constraint_rule(model,i):
        arow = a[i]
        return sum(arow[j]*model.x[j] for j in model.J) >= b[i]
    model.AxbConstraint = oe.Constraint(model.I,rule=ax_constraint_rule)
    return model

# Note that there is no need to call create_instance on a ConcreteModel
m = build_model(...)
opt = oe.SolverFactory("glpk")
results = opt.solve(m)

此外,建议先使用 array.tolist() 方法将所有 Numpy 数组转换为 Python 列表,然后再使用它们构建 Pyomo 表达式。 Pyomo 还没有在其表达式系统中内置数组操作的概念,并且以您使用它们的方式使用 Numpy 数组可能比仅使用 Python 慢 很多 列出。