【问题标题】:instantiate a concrete model from an abstract pyomo model从抽象 pyomo 模型实例化具体模型
【发布时间】:2017-05-05 11:04:54
【问题描述】:

我正在尝试在 Pyomo 5.1.1 中创建一个抽象模型,然后用 python 中的值填充它(即不使用 AMPL 文件)。我基本上是在关注Pyomo documentation example,但得到“检测到恒定目标”。

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 中初始化的文档。

【问题讨论】:

    标签: python mathematical-optimization glpk pyomo


    【解决方案1】:

    如果您不需要从 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 列表慢很多

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 2020-09-29
      • 2020-08-26
      • 2021-06-23
      • 2020-10-03
      • 2018-06-12
      • 2020-06-02
      相关资源
      最近更新 更多