Search code examples
gurobipyomo

How to display optimal variable values of a class-type Pyomo model?


I am a new Pyomo/Python user, and I am just wondering how to display the optimal variable values in a class-type Pyomo model.

I have just tried the standard example from Pyomo example library, the "min-cost-flow model". The code is available in https://github.com/Pyomo/PyomoGallery/wiki/Min-cost-flow

At the bottom of the code, it says:

sp = MinCostFlow('nodes.csv', 'arcs.csv') 
sp.solve()
print('\n\n---------------------------')
print('Cost: ', sp.m.OBJ())

and the output is

Academic license - for non-commercial use only
Read LP format model from file.    
Reading time = 0.00 seconds
x8: 7 rows, 8 columns, 16 nonzeros
No parameters matching 'mip_tolerances_integrality' found
No parameters matching 'mip_tolerances_mipgap' found
Optimize a model with 7 rows, 8 columns and 16 nonzeros
Coefficient statistics:
  Matrix range     [1e+00, 1e+00]
  Objective range  [1e+00, 5e+00]
  Bounds range     [0e+00, 0e+00]
  RHS range        [1e+00, 1e+00]
Presolve removed 7 rows and 8 columns
Presolve time: 0.00s
Presolve: All rows and columns removed
Iteration    Objective       Primal Inf.    Dual Inf.      Time
       0    5.0000000e+00   0.000000e+00   0.000000e+00      0s

Solved in 0 iterations and 0.01 seconds
Optimal objective  5.000000000e+00

I can only get the optimal objective, but how about the optimal variable values? I have also searched the documentation, which told me to use something like:

print("x[2]=",pyo.value(model.x[2])).  

But it did not work for class-type models like the min-cost-flow model.

I also tried to modify the function definition in the class:

def solve(self):
        """Solve the model."""
        solver = pyomo.opt.SolverFactory('gurobi')
        results = solver.solve(self.m, tee=True, keepfiles=False, options_string="mip_tolerances_integrality=1e-9, mip_tolerances_mipgap=0")
        print('\n\n---------------------------')
        print('First Variable: ', self.m.Y[0])

But it did not work as well. The output is:

KeyError: "Index '0' is not valid for indexed component 'Y'"

Can you help me with this? Thanks!

Gabriel


Solution

  • The most straightforward way to display the model results after solution is to use the model.display() function. In your case, self.m.display().

    The display() function works on Var objects as well, so if you have a variable self.m.x, you could do self.m.x.display().