I have used the algebraic modelling language AMPL but I’m now making the switch to python and Pyomo.
I’m struggling a bit with its syntax though. In AMPL I would have something like this:
JavaScript
x
4
1
param M;
2
param n{i in 0..M};
3
var b{k in 0..M-1, j in 1..n[k+1]};
4
How can I implement the last line in Pyomo?
Any help is much appreciated, thank you!
Best regards, Johannes
Advertisement
Answer
Welcome to the site.
Below is an example that I think does what you want. There are many ways to build a sparse set in pyomo
. You can do it “on the side” in pure python (like example below) using set comprehensions or whatever or you can create a rule that returns same. There is a decent example in the documentation.
JavaScript
1
16
16
1
# sparse set example
2
3
import pyomo.environ as pyo
4
5
M = 4
6
7
mdl = pyo.ConcreteModel('sparse set example')
8
9
mdl.A = pyo.Set(initialize=range(M))
10
sparse_index = {(k, j) for k in mdl.A for j in range(1, k+1)} # just a little helper set-comprehension
11
mdl.LT = pyo.Set(within=mdl.A * mdl.A, initialize=sparse_index) # "within" is optional...good for error checking
12
13
mdl.x = pyo.Var(mdl.LT, domain=pyo.NonNegativeReals)
14
15
mdl.pprint()
16
Yields:
JavaScript
1
23
23
1
3 Set Declarations
2
A : Size=1, Index=None, Ordered=Insertion
3
Key : Dimen : Domain : Size : Members
4
None : 1 : Any : 4 : {0, 1, 2, 3}
5
LT : Size=1, Index=None, Ordered=Insertion
6
Key : Dimen : Domain : Size : Members
7
None : 2 : LT_domain : 6 : {(2, 1), (3, 1), (1, 1), (3, 3), (2, 2), (3, 2)}
8
LT_domain : Size=1, Index=None, Ordered=True
9
Key : Dimen : Domain : Size : Members
10
None : 2 : A*A : 16 : {(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3)}
11
12
1 Var Declarations
13
x : Size=6, Index=LT
14
Key : Lower : Value : Upper : Fixed : Stale : Domain
15
(1, 1) : 0 : None : None : False : True : NonNegativeReals
16
(2, 1) : 0 : None : None : False : True : NonNegativeReals
17
(2, 2) : 0 : None : None : False : True : NonNegativeReals
18
(3, 1) : 0 : None : None : False : True : NonNegativeReals
19
(3, 2) : 0 : None : None : False : True : NonNegativeReals
20
(3, 3) : 0 : None : None : False : True : NonNegativeReals
21
22
4 Declarations: A LT_domain LT x
23