Recently successfully ported pretty big, but old, Pyomo model to Pyomo 5.x compliant. It's awesome to see all the new developments. In doing so, realized I wasn't sure about suggested best way to access variable values and obj function value in a Python script. Found a few different approaches scattered across the Pyomo 4.x official docs and various GitHub repos of example Pyomo models and scripts. For example, in the sample production model there's an indexed variable X with index of ('bands', 'coils'). Which of the following is the suggested approach to accessing the variables value after solving? My created model instance is called, of course, instance.
instance.X['coils'].value
value(instance.X['coils'])
instance.X['coils']()
All three work and I found uses of all three approaches in various Pyomo example galleries and docs floating around. Is one of them the "right" way?
Similarly, for getting all variable values, current docs suggest approach like this:
for v in instance.component_objects(Var, active=True):
varobject = getattr(instance, str(v))
for index in varobject:
print (" ", index, varobject[index].value)
However, the following also works and made me wonder about the need for the indirect way of getting the value of a variable using getattr. Both v and varobject have
type class 'pyomo.core.base.var.IndexedVar'. Am I missing something?
for v in instance.component_objects(Var, active=True):
print ("Variable component object",v)
for index in v:
print (" ", index, v[index].value)
I found similar variants with accessing objective function value and couldn't find suggested approach in current docs. Rather than detail all the variants here, I'll just ask if there's a suggested approach. I actually wrote this exploration up in a little Jupyter notebook and blogged it at
http://hselab.org/pyomo-get-variable-values.html. Once I know the suggested Pyomothonic way of accessing variable and obj func values, I can update the blog post in hopes of it being helpful to me and others.