I am trying to extract the results of a pyomo instance, with several indexed expressions and params. The index size is around 675 and there are 13 indexed expressions. The expressions involve either sums or products. I'm using the following code to extract the numerical results but extracting the results is taking longer than solving the model.
from pyomo.core import ConcreteModel, Expression, Param, value, Var
import pandas as pd
def extract_values_from_instance(instance: ConcreteModel)
model_attributes = {
"model_vars": instance.component_map(ctype=Var),
"model_param": instance.component_map(ctype=Param),
"model_expr": instance.component_map(ctype=Expression),
}
LOGGER.info('Extracting model values')
list_of_series = []
scalars_dict = {}
for values in model_attributes.values():
for key, var in values.items():
if var.is_indexed():
list_of_series.append(
pd.Series(
{k: value(v) for k, v in var.extract_values().items()},
index=var.extract_values().keys(),
name=key,
dtype="float64",
)
)
else:
scalars_dict[key] = var()
return pd.concat(list_of_series, axis=1), scalars_dict
Is there a way to extract the numerical results or at least calculate the numerical value from the numexpr that it does not involve calling value()
for each item?
UPDATE:
The culprit seemed to be an expression of the following format
def distance_traveled_rule(model, current_time) -> float:
if current_time == model.time_start.value:
return model.initial_distance # Param
distance_traveled = (
model.initial_distance # Param
+ sum(
model.velocity[time_stamp] * interval
for time_stamp in model.velocity
if time_stamp < current_time
)
)
return distance_traveled
model.distance_traveled = Expression(
model.velocity.index_set(),
rule=distance_traveled_rule,
doc="Distance traveled at each time stamp",
)