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:
objectOne 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:
- kind¶
"timeseries"or"scalar".- Type:
Literal[‘timeseries’, ‘scalar’]
- 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.
Nonewhere the model has no value.
- 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_verified¶
Whether
unit_qudtis confirmed in QUDT (or was given by the user), rather than only generated from the unit’s parts.- Type:
- class flexorchestrator.export.ModelData(series=<factory>)[source]¶
Bases:
objectEverything
export_model_data()exported.- Parameters:
series (list[ExportedSeries])
- series¶
The exported values, in walk order.
- class flexorchestrator.export.UnitMapper(overrides=None, resolver=None, strict=False, base_units=None)[source]¶
Bases:
objectMaps 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
UnitErrorfor a unit no key is found for, instead of warning and returningqudt=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.
- class flexorchestrator.export.UnitMapping(pyomo, qudt, source)[source]¶
Bases:
objectHow one Pyomo unit maps to QUDT.
- Parameters:
- 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’]
- flexorchestrator.export.conversion_factor(from_unit, to_unit)[source]¶
Return the factor that converts a value in
from_unittoto_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:
- 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:
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:
keysonly, if given withoutinclude;otherwise every active Var, Expression and mutable Param, filtered by
include/excludeglob patterns on the component path, plus anykeys. Components with a private (_-prefixed) name are skipped unless named inkeys.
- 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_indexstarts 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, passflexorchestrator.flexpse.time_sets(model)(the defaulttime_setshook) 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
UnitMapperby 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_mapperis strict and a unit doesn’t map.
- Return type:
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, keyedpath[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:
- flexorchestrator.export.units.Resolver¶
Looks a unit up in QUDT by key, symbol or name. Returns
{"uri", "multiplier", "offset"}(Acquirium’sresolve_unitshape) orNone, or raises if not found.
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:
- flexorchestrator.frames.check_frame(frame)[source]¶
Return
frameif it names a frame kind.- Raises:
ValueError – If
frameisn’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:
- Returns:
(timestamps, {column: values}), with NaN asNone.- Raises:
StorageError – If there is no datetime time column, the timestamps repeat, or a column isn’t numeric.
- Return type:
- flexorchestrator.frames.from_columns(timestamps, columns, frame)[source]¶
Build a DataFrame from UTC timestamps and columns.
polars gets a
timecolumn of UTC datetimes first; pandas gets a UTCDatetimeIndexnamedtime. Missing values are null (polars) or NaN (pandas).- Parameters:
- Raises:
ValueError – If
frameisn’t"polars"or"pandas".- Return type: