retrieving variables as array or dataframe

35 views
Skip to first unread message

Danny Kaufman

unread,
Jan 11, 2019, 2:16:41 PM1/11/19
to pyomo...@googlegroups.com
Does anyone know if there is a native-Pyomo way to retrieve all the Pyomo model variables as a numpy array or pandas dataframe?

For instance, to get:

[lowerbound_x1, body_x1, upperbound_x1...
 lowerbound_x2, body_x2, upperbound_x2...
 ...
 lowerbound_xn, body_xn, upperbound_xn]

Or is the best way to loop through each indexed Var component and construct a dictionary one element at a time?**

Thanks in advance!
Danny

** Currently, this is how I'm creating a dataframe:

"""""""""""""""""""""""""""""""""""""""""""""
import numpy as np
import pandas as pd
import pyomo.environ as pe

d = []
for _index, _paramData in instance.x.items():
    d.append({'lb': _paramData.bounds[0],
              'ub': _paramData.bounds[1],
              'value': pe.value(_paramData)})

df = pd.DataFrame(d)
"""""""""""""""""""""""""""""""""""""""""""""

Santiago rodriguez

unread,
Jan 15, 2019, 1:19:57 PM1/15/19
to Pyomo Forum
There is some functionality to do this with pyomo very easily. However, you will need to install an additional library that is needed. If you are working with conda you could do as follows:

conda install pyomo
conda install scipy numpy
conda install -c conda-forge pynumero_libraries

with that in place

import pyomo.environ as aml
from pyomo.contrib.pynumero.interfaces import PyomoNLP

model  =  aml.ConcreteModel()
model.x - ...

solver = aml.SolverFactory('ipopt')
solver.solve(model, tee=True)

nlp = PyomoNLP(model)
body = nlp.x_init()         # returns numpy array with values of all variables
xl = nlp.xl()                    # returns numpy array with lower bounds
xu = nlp.xu()                 # return numpy array with upper bounds

var_order = nlp.variable_order() # list names of variables in the order they were parsed to the numpy arrays

Alternatively if you don't want to install pynumero you could loop through all your variables using component maps

model_vars = model.component_map(aml.Var)
for var in model_vars.values():
    for k, v in var.items():
        print(k, aml.value(v))
Reply all
Reply to author
Forward
0 new messages