简体   繁体   English

Pyomo:创建摘要 model 和 AMPL 数据

[英]Pyomo: Create Abstract model and AMPL data

I am just starting with Pyomo and I have a big problem.我刚开始使用 Pyomo,我遇到了一个大问题。 I want to create an Abstract Model and use AMPL data format to feed it.我想创建一个摘要 Model 并使用 AMPL 数据格式来提供它。 The question is a classic transportation problem.这个问题是一个经典的交通问题。 I need to find the optimal solution for cost.我需要找到成本最优的解决方案。 M means if the shipment is impossible between a given source and destination, a large cost of M is entered. M 表示如果在给定的来源和目的地之间不可能装运,则输入 M 的大成本。 I need to convert it into AMPL data.我需要将其转换为 AMPL 数据。 Apart from this, I do not know how to create this abstract model. The code for this table and model are shown below.除此之外,我不知道如何创建这个摘要model。这个表和model的代码如下所示。 Also after reading this problem, I created the mathematical model as follows.同样在阅读这个问题之后,我创建了数学 model 如下。

[the mathematical model that I created][1] [我创建的数学 model][1]

[the classic transportation problem tabel][2] [经典运输问题表][2]

from __future__ import division
from pyomo.environ import *

model = AbstractModel()

model.I = Set()
model.J = Set()

model.a = Param(model.I)
model.b = Param(model.J)
model.cost = Param(model.I,model.J)
model.supply = Var(model.I,model.J)

def obj_expression(model):
    return sum(model.supply[i,j] *  model.cost[i,j] for i in model.I for j in model.J)

model.OBJ = Objective(rule=obj_expression)

def ax_constraint_rule_1(model, i):
    return sum(model.supply[i,j] for j in model.J )<= model.a[i]

def ax_constraint_rule_2(model, j):
    return sum(model.supply[i,j] for i in model.I )>= model.b[j]

model.AxbConstraint = Constraint(model.I, rule=ax_constraint_rule_1)
model.AxbConstraint_2 = Constraint(model.J, rule=ax_constraint_rule_2)

pyomo solve --solver=glpk test.py transportation_data.dat
model.pprint()


set I := D1 D2 D3 ;
set J := S1 S2 S3  ;

param cost :=
S1 D1 3
S1 D2 1
S2 D1 4
S2 D2 2
S2 D3 4
S3 D2 3
S3 D3 3
;

param b :=

D1 7
D2 3
D3 5 ;


param a:=
S1 5
S2 7
S3 3

;



Any help with this code?这段代码有什么帮助吗? Really need help with the model creation and AMPL data construction.确实需要帮助创建 model 和 AMPL 数据构建。

Thanks anyway不管怎么说,还是要谢谢你

=============================================== The result =============================================== 结果

  File "E:/pycharm_project/test.py", line 28
    pyomo solve --solver=glpk test.py transportation_data.dat
              ^
SyntaxError: invalid syntax```




  [1]: https://i.stack.imgur.com/DoWXA.png
  [2]: https://i.stack.imgur.com/Fwmjb.png

Well, you are close, I think.好吧,我想你很接近了。 You have a few things to clean up.你有几件事要清理。

You do NOT need model.m and model.n I'm not sure what you are trying to do there.您不需要model.mmodel.n我不确定您要在那里做什么。

For the sets, I and J, just list them as Set(), because you are providing values for them in your AMPL data.对于集合 I 和 J,只需将它们列为 Set(),因为您在 AMPL 数据中为它们提供了值。 Like:像:

model.I = Set()     
model.J = Set()     

In your formulation you are double indexing c[i,j] but in your formulation and data, c is only indexed by model.I在您的公式中,您是双重索引 c[i,j] 但在您的公式和数据中,c 仅由model.I索引

Similarly, in your model you are only single-indexing a[i], but you have a double index on it in your data and formulation.同样,在您的 model 中,您只是单索引 a[i],但在您的数据和公式中有一个双索引。

In your constraints, the definitions should only hold a variable for the "for each" part, not the variable you are summing over.在您的约束中,定义应该只包含“for each”部分的变量,而不是您要求和的变量。

Clean that stuff up, give it a whirl, comment me back if it is still broke.清理那些东西,试一试,如果它仍然坏了就给我评论。

Edit: A couple more items.....编辑:还有几个项目......

I'd recommend naming your parameters and sets intuitively, such as:我建议直观地命名您的参数和设置,例如:

model.supply , model.cost , etc. Makes it MUCH easier to read & troubleshoot. model.supplymodel.cost等。使其更易于阅读和故障排除。 :) :)

============ ============

Edit #2: Your code cleanup is vastly improved.编辑 #2:您的代码清理得到了极大改进。 A couple cleanup items remain:一些清理项目仍然存在:

In your constraints, you only need to pass variable for the "for each" side of the equation if you are summing over the other variable.在你的约束中,如果你对另一个变量求和,你只需要为等式的“for each”边传递变量。 You are making model.I constraints here, so this is appropriate:你在这里制作model.I约束,所以这是合适的:

def ax_constraint_rule_1(model, i):  # note removal of j
    return sum(model.supply[i,j] for j in model.J ) <= model.a[i]

Note that the summation here is over j for each i so I changed your for loop also.请注意,这里的总和超过了每个ij所以我也更改了你的 for 循环。

flip that around for the other constraint.将其翻转为另一个约束。

your a, b, cost, supply don't line up with your data names.a, b, cost, supply与您的数据名称不一致。 Check them all.检查所有这些。 In your data, a appears to be cost[i, j]在您的数据中, a似乎是cost[i, j]

your cost data is also missing some values!您的成本数据也缺少一些值!

In AMPL syntax, set is not capitalized.在 AMPL 语法中, set不是大写的。 If you get it running, it will barf and call out that error.如果你让它运行,它会呕吐并报出那个错误。

Here's my cut:这是我的剪辑:

from pyomo.environ import *

model = AbstractModel()

# model.m = Param(within=NonNegativeIntegers)
# model.n = Param(within=NonNegativeIntegers)

model.S = Set()     # Sources
model.D = Set()     # Destinations

model.cost = Param(model.S, model.D)    # cost from S->D
model.supply = Param(model.S)           # supply at source S
model.demand = Param(model.D)           # demad at destination D
model.x = Var(model.S, model.D, domain=NonNegativeReals)

### OBJECTIVE FUNCTION ###

# calculate total cost of decisions
def obj_expression(model):
    return sum(model.x[s, d] * model.cost[s, d] for s in model.S for d in model.D)

model.OBJ = Objective(rule=obj_expression)

### CONSTRAINTS ###

# ensure that supply constraint is met for each source in model.S
def supply_constraint(model, s):
    return sum(model.x[s, d] for d in model.D ) <= model.supply[s] 

# ensure that demand constraint is met for each destination in model.D
def demand_constraint(model, d):
    return sum(model.x[s, d] for s in model.S ) >= model.demand[d] 

model.sup_constraint = Constraint(model.S, rule=supply_constraint)
model.dem_constraint = Constraint(model.D, rule=demand_constraint)


model.pprint()

Data file数据文件

set D := D1 D2 D3 ;
set S := S1 S2 S3 ;

param cost :=
S1 D1 3
S1 D2 1
S1 D3 10
S2 D1 4
S2 D2 2
S2 D3 4
S3 D1 10
S3 D2 3
S3 D3 3
;

param demand := 

D1 7
D2 3
D3 5 ;


param supply :=
S1 5
S2 7
S3 3
;

Output: Output:

% pyomo solve --solver=glpk transpo_model.py transpo.dat --summary
[    0.00] Setting up Pyomo environment
[    0.00] Applying Pyomo preprocessing actions
4 Set Declarations
    D : Dim=0, Dimen=1, Size=0, Domain=None, Ordered=False, Bounds=None
        Not constructed
    S : Dim=0, Dimen=1, Size=0, Domain=None, Ordered=False, Bounds=None
        Not constructed
    cost_index : Dim=0, Dimen=2, Size=0, Domain=None, Ordered=False, Bounds=None
        Virtual
    x_index : Dim=0, Dimen=2, Size=0, Domain=None, Ordered=False, Bounds=None
        Virtual

3 Param Declarations
    cost : Size=0, Index=cost_index, Domain=Any, Default=None, Mutable=False
        Not constructed
    demand : Size=0, Index=D, Domain=Any, Default=None, Mutable=False
        Not constructed
    supply : Size=0, Index=S, Domain=Any, Default=None, Mutable=False
        Not constructed

1 Var Declarations
    x : Size=0, Index=x_index
        Not constructed

1 Objective Declarations
    OBJ : Size=0, Index=None, Active=True
        Not constructed

2 Constraint Declarations
    dem_constraint : Size=0, Index=D, Active=True
        Not constructed
    sup_constraint : Size=0, Index=S, Active=True
        Not constructed

11 Declarations: S D cost_index cost supply demand x_index x OBJ sup_constraint dem_constraint
[    0.29] Creating model
[    0.32] Applying solver
[    0.33] Processing results
    Number of solutions: 1
    Solution Information
      Gap: 0.0
      Status: feasible
      Function Value: 46.0
    Solver results file: results.json

==========================================================
Solution Summary
==========================================================

Model unknown

  Variables:
    x : Size=9, Index=x_index
        Key          : Lower : Value : Upper : Fixed : Stale : Domain
        ('S1', 'D1') :     0 :   5.0 :  None : False : False : NonNegativeReals
        ('S1', 'D2') :     0 :   0.0 :  None : False : False : NonNegativeReals
        ('S1', 'D3') :     0 :   0.0 :  None : False : False : NonNegativeReals
        ('S2', 'D1') :     0 :   2.0 :  None : False : False : NonNegativeReals
        ('S2', 'D2') :     0 :   3.0 :  None : False : False : NonNegativeReals
        ('S2', 'D3') :     0 :   2.0 :  None : False : False : NonNegativeReals
        ('S3', 'D1') :     0 :   0.0 :  None : False : False : NonNegativeReals
        ('S3', 'D2') :     0 :   0.0 :  None : False : False : NonNegativeReals
        ('S3', 'D3') :     0 :   3.0 :  None : False : False : NonNegativeReals

  Objectives:
    OBJ : Size=1, Index=None, Active=True
        Key  : Active : Value
        None :   True :  46.0

  Constraints:
    sup_constraint : Size=3
        Key : Lower : Body : Upper
         S1 :  None :  5.0 :   5.0
         S2 :  None :  7.0 :   7.0
         S3 :  None :  3.0 :   3.0
    dem_constraint : Size=3
        Key : Lower : Body : Upper
         D1 :   7.0 :  7.0 :  None
         D2 :   3.0 :  3.0 :  None
         D3 :   5.0 :  5.0 :  None

[    0.33] Applying Pyomo postprocessing actions
[    0.33] Pyomo Finished

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM