Home > OS >  how can I sort parameters in pyomo?
how can I sort parameters in pyomo?

Time:07-02

I am working with the Pyomo package(for mathematical modeling in python).I have a parameter defined as: model.D=Param(model.t,model.i) .this is a multi-dimensional parameter. t is for the range of time periods, i is for the range of instances and D is the value of the demand. how can I sort this parameter by its value and get the corresponding t and i ?

CodePudding user response:

Do all that data cleaning/sorting stuff with basic python before you build the model. Part of this answer depends on the original format of the data and the format you'd like your answer in, but I think the overall gist is clear....

Code

import pyomo.environ as pyo

d = {   0: [1.2, 3.1, 0.5],
        1: [9.5, 2.0, 3.1] }

# a good format to pass in to a parameter, tuple-indexed dictionary
d_data = {(t, i): d[t][i] for t in d for i in range(len(d[t]))}


# now let's sort the values in d for the missing info on order
d_tuples = {t: sorted([(val, idx) for idx, val in enumerate(d[t])]) for t in d}

d_sorted = {t: [temp[1] for temp in d_tuples[t]] for t in d}


print(d_data)
print(d_tuples)
print(d_sorted)

# now set up the model...
m = pyo.ConcreteModel()

m.T = pyo.Set(initialize=d.keys())
m.I = pyo.Set(initialize=list(range(len(d[0]))))  # assumes all d[t] are equal length

m.D = pyo.Param(m.T, m.I, initialize=d_data)

m.pprint()

Yields:

{(0, 0): 1.2, (0, 1): 3.1, (0, 2): 0.5, (1, 0): 9.5, (1, 1): 2.0, (1, 2): 3.1}
{0: [(0.5, 2), (1.2, 0), (3.1, 1)], 1: [(2.0, 1), (3.1, 2), (9.5, 0)]}
{0: [2, 0, 1], 1: [1, 2, 0]}
3 Set Declarations
    D_index : Size=1, Index=None, Ordered=True
        Key  : Dimen : Domain : Size : Members
        None :     2 :    T*I :    6 : {(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)}
    I : Size=1, Index=None, Ordered=Insertion
        Key  : Dimen : Domain : Size : Members
        None :     1 :    Any :    3 : {0, 1, 2}
    T : Size=1, Index=None, Ordered=Insertion
        Key  : Dimen : Domain : Size : Members
        None :     1 :    Any :    2 : {0, 1}

1 Param Declarations
    D : Size=6, Index=D_index, Domain=Any, Default=None, Mutable=False
        Key    : Value
        (0, 0) :   1.2
        (0, 1) :   3.1
        (0, 2) :   0.5
        (1, 0) :   9.5
        (1, 1) :   2.0
        (1, 2) :   3.1

4 Declarations: T I D_index D
  • Related