Model data export

The model data exporter.

export_model_data() walks a Pyomo model and returns a ModelData of timeseries and scalars with Pyomo and QUDT units. It has no Acquirium dependency: writing the result to a study is a separate step.

class flexorchestrator.export.ExportedSeries(key, kind, component, index, values, timestamps, unit_pyomo, unit_qudt, unit_verified=False, raw_index=())[source]

Bases: object

One exported value: a timeseries or a scalar.

Parameters:
key

The stored label: the component path, plus the custom index for an element of an indexed component ("costing.capital_cost[pump1]").

Type:

str

kind

"timeseries" or "scalar".

Type:

Literal[‘timeseries’, ‘scalar’]

component

The Pyomo component path the value came from.

Type:

str

index

The custom (non-time) index, as JSON-friendly values; [] for a component with no custom index.

Type:

list[Any]

values

The values; one per time point for a timeseries, one for a scalar. None where the model has no value.

Type:

list[float | None]

timestamps

The time point of each value (timeseries only): the model’s datetimes, or the raw time-set values if it has none.

Type:

list[Any] | None

unit_pyomo

The Pyomo unit string, or None.

Type:

str | None

unit_qudt

The QUDT key, or None if nothing mapped the unit.

Type:

str | None

unit_verified

Whether unit_qudt is confirmed in QUDT (or was given by the user), rather than only generated from the unit’s parts.

Type:

bool

raw_index

The custom index as Pyomo has it (any hashable values).

Type:

tuple[Any, …]

property stale: bool

Whether any value is missing (the model had no value for it).

property value: float | None

The value of a scalar.

Raises:

TypeError – If this is a timeseries.

class flexorchestrator.export.ModelData(series=<factory>)[source]

Bases: object

Everything export_model_data() exported.

Parameters:

series (list[ExportedSeries])

series

The exported values, in walk order.

Type:

list[flexorchestrator.export.model_data.ExportedSeries]

keys()[source]

Return every exported key, in walk order.

Return type:

list[str]

timeseries()[source]

Return the timeseries.

Return type:

list[ExportedSeries]

scalars()[source]

Return the scalars.

Return type:

list[ExportedSeries]

stale()[source]

Return the keys with at least one missing value.

Return type:

list[str]

class flexorchestrator.export.UnitMapper(overrides=None, resolver=None, strict=False, base_units=None)[source]

Bases: object

Maps Pyomo unit strings to QUDT keys, caching each answer.

Parameters:
  • overrides (Mapping[str, str] | None) – {pyomo unit: QUDT key}, checked first, by exact string.

  • resolver (Callable[[str], Mapping[str, Any] | None] | None) – Optional QUDT lookup (see Resolver). With it, keys are verified and unlisted base units are found.

  • strict (bool) – Raise UnitError for a unit no key is found for, instead of warning and returning qudt=None.

  • base_units (Mapping[str, str] | None) – Base-unit symbols; defaults to BASE_UNITS.

Example

>>> UnitMapper().map("L/day").qudt
'L-PER-DAY'
map(unit)[source]

Map one Pyomo unit string.

Parameters:

unit (str | None) – A Pyomo unit string such as "m**3/h" (a value without units is "dimensionless"). None means the units are unknown and maps to nothing, without a warning.

Returns:

The mapping.

Raises:

UnitError – In strict mode, if no key is found.

Return type:

UnitMapping

resolve(identifier)[source]

Return the resolver’s answer for a unit identifier, or None.

None too when there is no resolver or it raises.

Parameters:

identifier (str)

Return type:

Mapping[str, Any] | None

class flexorchestrator.export.UnitMapping(pyomo, qudt, source)[source]

Bases: object

How one Pyomo unit maps to QUDT.

Parameters:
  • pyomo (str | None)

  • qudt (str | None)

  • source (Literal['override', 'verified', 'generated', 'resolver', 'none'])

pyomo

The Pyomo unit string, or None if the units are unknown.

Type:

str | None

qudt

The QUDT key, or None if none was found.

Type:

str | None

source

"override" (the user’s), "verified" (generated and confirmed in QUDT), "generated" (generated, no resolver to confirm it), "resolver" (found by looking the whole unit up), or "none".

Type:

Literal[‘override’, ‘verified’, ‘generated’, ‘resolver’, ‘none’]

property verified: bool

Whether the key is known to be right (confirmed in QUDT, or the user’s).

flexorchestrator.export.conversion_factor(from_unit, to_unit)[source]

Return the factor that converts a value in from_unit to to_unit.

Used to keep a stored label in the unit it was first declared with, when a later run exports it in another unit of the same dimensions.

Parameters:
  • from_unit (str) – A Pyomo unit string.

  • to_unit (str) – A Pyomo unit string.

Returns:

value_in_to_unit = factor * value_in_from_unit.

Raises:

UnitError – If either unit doesn’t parse, the dimensions differ, or an offset unit (degC) would need converting to a different unit.

Return type:

float

Example

>>> conversion_factor("kW", "W")
1000.0
flexorchestrator.export.export_model_data(model, keys=None, include=None, exclude=None, time_sets=None, datetime_index=None, unit_mapper=None, max_scalars_per_component=10000)[source]

Export a model’s values, classified by index and with their units.

What is exported:

  • keys only, if given without include;

  • otherwise every active Var, Expression and mutable Param, filtered by include / exclude glob patterns on the component path, plus any keys. Components with a private (_-prefixed) name are skipped unless named in keys.

Parameters:
  • model (Block) – The model (or block) to walk. Paths are relative to it.

  • keys (Iterable[str] | None) – Exact component paths, or element paths such as "x[pump1]". A key always exports, whatever its size; a key that names nothing raises.

  • include (Iterable[str] | None) – Glob patterns a component path must match, e.g. "costing.*".

  • exclude (Iterable[str] | None) – Glob patterns that drop a component.

  • time_sets (Sequence[Set] | None) – The time Sets, main one first. Further entries are subsets of the main one, e.g. every point but the first; a subset counts as time only if listed here. A later Set that is its own block’s time_index starts a new axis, for a model with several time blocks, and each block’s values get that block’s timestamps. When omitted, the main time Set of the model’s TimeBlock is used, without subsets; for a flex-pse model, pass flexorchestrator.flexpse.time_sets(model) (the default time_sets hook) to include the subsets flex-pse builds.

  • datetime_index (Sequence[Any] | None) – One timestamp per element of the main time Set, in order. When omitted, taken from the block that holds the main time Set (flex-pse’s TimeBlock); without either, the raw time values are used as timestamps.

  • unit_mapper (UnitMapper | None) – Maps Pyomo units to QUDT; a lenient UnitMapper by default.

  • max_scalars_per_component (int) – A component indexed by custom sets only and with more elements than this is skipped with a warning, unless it is named in keys.

Returns:

The exported values.

Raises:
  • ExportError – If a key names nothing (or not a Var, Expression or Param), the time sets are ambiguous or inconsistent, two values get the same key, or a named component has a non-numeric value.

  • UnitError – If unit_mapper is strict and a unit doesn’t map.

Return type:

ModelData

Example

>>> data = export_model_data(model, include=["costing.*"])
>>> data["costing.aggregate_electrical_power"].unit_qudt
'KiloW'

Walk a Pyomo model and export its values with units.

Each component is classified by the Set it is indexed by:

  • not indexed -> one scalar, keyed by its path;

  • indexed by time only -> one timeseries, keyed by its path;

  • indexed by time x custom sets, e.g. (unit, t) -> one timeseries per custom index value, keyed path[index];

  • indexed by custom sets only -> one scalar per element, keyed by the element’s Pyomo name (costing.capital_cost[pump1]).

“Time” means a registered time Set, compared by identity: flex-pse’s time set is just the integers 0..N-1, so any other integer Set of that length would match by value. This module depends only on pyomo; flex-pse’s TimeBlock is found by its time_index / datetime_index attributes.

Pyomo units -> QUDT unit keys, and conversion between Pyomo units.

QUDT keys are generated, not looked up in a table of combinations. pint splits any Pyomo unit into parts, (prefix, base unit, exponent), and QUDT names compound units from the same parts by rule: the prefix and the base unit’s symbol, the exponent as a digit, numerator parts joined by -, then -PER- and the denominator parts:

L/day     -> liter, day^-1             -> L-PER-DAY
kg/m**3   -> kilo+gram, meter^-3       -> KiloGM-PER-M3
kWh       -> kilo+watt_hour            -> KiloW-HR
J/(kg*K)  -> joule, kilo+gram^-1, K^-1 -> J-PER-KiloGM-K

Only base units need a QUDT symbol: BASE_UNITS holds the common ones, a currency XYZ becomes CCY_XYZ, and any other base is looked up through the resolver. With a resolver (Acquirium’s resolve_unit), every generated key is verified: it must exist in QUDT with the same SI multiplier as the Pyomo unit, which also guards against text matches like Pyomo’s "a" (a year) resolving to QUDT’s ARE (an area). Without one, keys are generated but unverified.

User overrides always win. A unit no key can be found for is kept with qudt=None and a warning, or raises UnitError in strict mode.

flexorchestrator.export.units.BASE_UNITS: dict[str, str]

pint base-unit name -> QUDT symbol. Prefixes and combinations are generated, so this lists only base units, and only so keys can be generated without a resolver; with one, bases missing here are looked up. The component tests check every entry against Acquirium’s QUDT vocabulary.

Type:

dict

flexorchestrator.export.units.Resolver

Looks a unit up in QUDT by key, symbol or name. Returns {"uri", "multiplier", "offset"} (Acquirium’s resolve_unit shape) or None, or raises if not found.

alias of Callable[[str], Mapping[str, Any] | None]

Tables

polars and pandas tables in and out.

The orchestrator works on plain columns: a list of UTC timestamps and one list of values per column. This module turns a DataFrame of either kind into that, and back.

flexorchestrator.frames.TIME = 'time'

The name of the time column (polars) or index (pandas) on the way out.

Type:

str

flexorchestrator.frames.frame_kind(df)[source]

Return "polars" or "pandas" for a DataFrame.

Raises:

TypeError – If df is neither.

Parameters:

df (Any)

Return type:

Literal[‘polars’, ‘pandas’]

flexorchestrator.frames.check_frame(frame)[source]

Return frame if it names a frame kind.

Raises:

ValueError – If frame isn’t "polars" or "pandas".

Parameters:

frame (Any)

Return type:

Literal[‘polars’, ‘pandas’]

flexorchestrator.frames.to_columns(df, time_column=None)[source]

Split a DataFrame into UTC timestamps and numeric columns.

Parameters:
  • df (Any) – A polars or pandas DataFrame.

  • time_column (str | None) – The column holding the datetimes. For pandas the default is the index; for polars it is the only datetime column.

Returns:

(timestamps, {column: values}), with NaN as None.

Raises:

StorageError – If there is no datetime time column, the timestamps repeat, or a column isn’t numeric.

Return type:

tuple[list[datetime], dict[str, list[float | None]]]

flexorchestrator.frames.from_columns(timestamps, columns, frame)[source]

Build a DataFrame from UTC timestamps and columns.

polars gets a time column of UTC datetimes first; pandas gets a UTC DatetimeIndex named time. Missing values are null (polars) or NaN (pandas).

Parameters:
  • timestamps (Sequence[datetime]) – The UTC timestamps, one per row.

  • columns (Mapping[str, Sequence[float | None]]) – {column: values}, a value per timestamp (None if missing).

  • frame (Literal['polars', 'pandas']) – "polars" or "pandas".

Raises:

ValueError – If frame isn’t "polars" or "pandas".

Return type:

Any

flexorchestrator.frames.model_frame(data, frame)[source]

Return a ModelData’s timeseries as one table.

Every timeseries key is a column, aligned on the union of their timestamps (a subset of time such as startup is missing at the points it doesn’t cover). Scalars aren’t included.

Parameters:
  • data (Any) – The values, with datetime timestamps.

  • frame (Literal['polars', 'pandas']) – "polars" or "pandas".

Return type:

Any