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:
param M; param n{i in 0..M}; var b{k in 0..M-1, j in 1..n[k+1]};
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.
# sparse set example import pyomo.environ as pyo M = 4 mdl = pyo.ConcreteModel('sparse set example') mdl.A = pyo.Set(initialize=range(M)) sparse_index = {(k, j) for k in mdl.A for j in range(1, k+1)} # just a little helper set-comprehension mdl.LT = pyo.Set(within=mdl.A * mdl.A, initialize=sparse_index) # "within" is optional...good for error checking mdl.x = pyo.Var(mdl.LT, domain=pyo.NonNegativeReals) mdl.pprint()
Yields:
3 Set Declarations A : Size=1, Index=None, Ordered=Insertion Key : Dimen : Domain : Size : Members None : 1 : Any : 4 : {0, 1, 2, 3} LT : Size=1, Index=None, Ordered=Insertion Key : Dimen : Domain : Size : Members None : 2 : LT_domain : 6 : {(2, 1), (3, 1), (1, 1), (3, 3), (2, 2), (3, 2)} LT_domain : Size=1, Index=None, Ordered=True Key : Dimen : Domain : Size : Members 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)} 1 Var Declarations x : Size=6, Index=LT Key : Lower : Value : Upper : Fixed : Stale : Domain (1, 1) : 0 : None : None : False : True : NonNegativeReals (2, 1) : 0 : None : None : False : True : NonNegativeReals (2, 2) : 0 : None : None : False : True : NonNegativeReals (3, 1) : 0 : None : None : False : True : NonNegativeReals (3, 2) : 0 : None : None : False : True : NonNegativeReals (3, 3) : 0 : None : None : False : True : NonNegativeReals 4 Declarations: A LT_domain LT x