2017-05-05 131 views
0

我試圖創建Pyomo 5.1.1抽象模型實例化一個具體的模型,然後使用Python內的值來填充它(即不使用AMPL文件)。我基本上遵循Pyomo documentation example,但我得到「恆定客觀檢測」。從抽象pyomo模型

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但我找不到描述蟒蛇內初始化的任何文件。

回答

1

如果你不需要從AMPL加載數據.dat文件,我建議從ConcreteModel開始。在這種情況下,除非需要它們是可變的,否則不需要將數據存儲到Param對象中。仍然建議爲索引組件創建Set對象;否則,Set對象將被隱式創建,其名稱可能與您添加到模型中的組件衝突。

通過將您ConcreteModel定義,數據作爲輸入,你基本上是通過複製和AbstractModelcreate_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) 

而且,最好是用它們來構建Pyomo表達式之前先轉換所有numpy的陣列使用array.tolist()方法Python列表。 Pyomo還沒有內置到其表達系統陣列操作的概念,以及使用numpy的陣列使用的是它們可以比僅僅使用Python列表慢的方式。