我试图在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中初始化的文档。
答案 0 :(得分: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列表相比可能太多。