'How to extract variables that equal a certain value in pyomo?

I am building a linear optimization model and trying to extract key information from my decision variable values. instance.x.display() displays the following sample

x : Size=121, Index=x_index
    Key      : Lower : Value : Upper : Fixed : Stale : Domain
      (1, 1) :     0 :  None :     1 : False :  True : Binary
      (1, 2) :     0 :   0.0 :     1 : False : False : Binary
      (1, 3) :     0 :   0.0 :     1 : False : False : Binary
      (1, 4) :     0 :   1.0 :     1 : False : False : Binary
      (1, 5) :     0 :   0.0 :     1 : False : False : Binary
      (1, 6) :     0 :   0.0 :     1 : False : False : Binary
      (1, 7) :     0 :   0.0 :     1 : False : False : Binary
      (1, 8) :     0 :   0.0 :     1 : False : False : Binary
      (1, 9) :     0 :   0.0 :     1 : False : False : Binary
     (1, 10) :     0 :   0.0 :     1 : False : False : Binary
     (1, 11) :     0 :   0.0 :     1 : False : False : Binary
      (2, 1) :     0 :   0.0 :     1 : False : False : Binary
      (2, 2) :     0 :  None :     1 : False :  True : Binary
      (2, 3) :     0 :   0.0 :     1 : False : False : Binary
      (2, 4) :     0 :   0.0 :     1 : False : False : Binary
      (2, 5) :     0 :   0.0 :     1 : False : False : Binary

I want to extract the values that are equal to 1, such as x(1,4) which is equal to 1.

I have tried the following code: instance.x.display(value(model.x[i,j] == 1)) which gives me the error message ValueError: Error retrieving component x[11,11]: The component has not been constructed. I am thinking that this is because the value for this is 'None' just like x(1,1) and x(2,2) above.

Any ideas on how to code this to display something like this:

(1,4) -- 1
(2,3) -- 1
(3,5) -- 1
(4,2) -- 1
(5,4) -- 1
(6,7) -- 1


Solution 1:[1]

You can extract all values to a more user-friendly format by:

x_dic = x.get_values()
for i in x_dic.keys():
    if r[i]==1:
        print(i)

I am sure there is a nicer way but this should do the trick :)

Cheers

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1