我正在尝试在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 errorWARNING: 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列表要慢得多。

关于python - 从抽象pyomo模型实例化具体模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43803364/

10-11 06:42