flexops.core¶
A discrete, bounded time horizon at a configurable resolution. |
|
Metadata for a slice of a |
OpsBlock¶
The base class of every flex-pse unit model (see
Relaxation policies for the relaxation config slot).
flex-pse never deletes model components. A built model gets updated in place via
OpsBlockData.update_parameters().
Base class of every flex-pse unit model (see module docstring). |
|
How a unit's discrete structure is relaxed. |
A unit’s own relationships are swapped in place from a
Surrogate via OpsBlockData.swap_relation().
Its energy draw is just one example. Any relationship the unit declared
swappable with OpsBlockData.register_relation() qualifies (an RO skid’s
recovery, a tank’s geometry mapping level to volume). Conservation constraints are
never registered, so
they can never be swapped. The predefined surrogate classes themselves,
which one a SurrogateSpec names and how each
validates and builds its own data, are documented on
flexops.surrogates.
Composition: PlantBlock and NetworkBlock¶
There are two levels of composition. A PlantBlock is a
collection of unit blocks (one facility, holding the arcs between its
units), and a NetworkBlock is a composition of plant blocks. Both are
thin dynamic=False flowsheets whose time domain is the TimeBlock’s
ordered integer set (see Time and dynamics). Their
aggregation Expressions (total_electrical_power,
total_thermal_power, total_product, total_fuel_usage,
total_feed) are deferred, since units are normally added after the plant
exists. FlexCosting.cost_process() builds them for every plant and network
on the model.
A facility: a collection of unit blocks (module docstring). |
A network: a composition of plant blocks (module docstring). |
Config-driven build¶
build_model is the single config driven entry point. One validated
FlowsheetSpec yields the whole Pyomo model. See
Build a plant for the imperative and config driven paths
side by side.
- flexops.core.build.build_model(config, *, expand_arcs: bool = True) ConcreteModel¶
Build the whole Pyomo model described by a flat spec.
- Parameters:
config – Anything
load_spec()accepts: aFlowsheetSpec, or a.jsonpath or mapping validated into one.expand_arcs – Whether to apply
network.expand_arcsafter the topology is built, so logic and extensions can use the expanded equalities.
- Returns:
The constructed
ConcreteModel, carryingtime_block, the named property packages and costing blocks, the network, plant and unit tree, its logic and extensions, and the objective if the spec has one.- Raises:
FlexConfigError – If the config fails validation (the message names the offending field path) or does not fit the model it builds.
- flexops.core.build.parse_quantity(value, *, strict: bool = True)¶
Turn a persisted units-carrying value into a Pyomo expression.
- Parameters:
value – Either a
{"value": ..., "units": ...}mapping (a listvaluegives a list of quantities), a list of such mappings, a"<number> <units>"string (the formTimeConfig.time_stepuses), or any other value, which is returned unchanged.strict – Whether a string with no numeric magnitude is an error. Pass
Falsewhere a plain string is itself a legal value — a construction option naming an enum member ("polarization") is not a botched quantity — and it is returned unchanged instead.
- Returns:
A units-carrying Pyomo expression, or
valueitself.- Raises:
FlexConfigError – If
strictand a quantity string has no numeric magnitude.
- flexops.core.build.parse_units(text: str)¶
Parse a units string into a Pyomo units expression.
Handles the compact forms persisted configs use:
"min","m^3/hr","kWh/m^3","USD/kWh", and the"kg/m^2/s"and"1/s"forms Pyomo prints —*-separated factors,^/**exponents, each factor after a/divides, and a bare1is dimensionless. A token Pyomo does not know is registered as a currency (so"USD"works without the costing block existing yet).- Parameters:
text – The units string.
- Returns:
The corresponding Pyomo units expression.
- Raises:
FlexConfigError – If a token is not a parsable unit name and exponent.
Emitting a spec¶
emit_model is build_model in reverse: it reads the flat spec a live
model was, or could have been, built from (see
The config schema).
- flexops.core.emit.emit_model(model, *, data_dir: Path | None = None, inline_limit: int = 2000, check: bool = True, relative_to: Path | None = None) FlowsheetSpec¶
Read the flat spec a live model was (or could have been) built from.
- Parameters:
model – The built Pyomo model.
data_dir – Directory to write lists longer than
inline_limitto, as.json.gzfiles the spec references with$source.inline_limit – Longest list kept inside the spec.
check – Rebuild the spec and warn about every difference from
model.relative_to – Directory the spec will be saved in; file paths under it are written relative to it.
- Returns:
The validated
FlowsheetSpec.- Raises:
FlexConfigError – If the model holds something the spec can’t express and that would change the model if left out (an option with no spec form, indexed members that differ, an arc no template fits).
- Warns:
FlexEmitWarning – For anything left out of the spec: a custom surrogate, an objective no costing block or extension made, a long list with no
data_dir, a costing block that has not runcost_process(), fixes that can’t be found because the model doesn’t rebuild, and every difference the check finds.
- flexops.core.emit.unit_model_class_name(unit_or_class) str¶
Return the flexops.unit_models name of a unit or unit-model class.
- Parameters:
unit_or_class – A built unit or a unit-model class.
- Returns:
The first name in the type’s MRO, minus a
Datasuffix, thatflexops.unit_models.__all__lists.- Raises:
FlexConfigError – If nothing in the MRO is a flexops unit model.
- flexops.core.serialize.to_jsonable(value, *, where: str, packages: Mapping | None = None)¶
Convert a construction-option value to plain JSON data.
- Parameters:
value – The live value.
where – The option’s name, used in errors.
packages – Package element names mapped to their blocks; a value that is one of these blocks becomes
{"$package": name}.
- Returns:
JSON data a spec can hold.
- Raises:
FlexConfigError – If the value, or anything inside it, has no spec form.
- flexops.core.serialize.units_to_str(units, *, where: str = 'a value') str¶
Write Pyomo units as a string that parse_units reads back exactly.
- Parameters:
units – A Pyomo units expression.
where – What the units belong to, named in the error.
- Returns:
The units with
^exponents, e.g.'kWh/m^3'.- Raises:
FlexConfigError – If the string does not parse back to the same units.
- flexops.core.compare.model_differences(a, b, *, rel_tol: float = 1e-09, check_values: bool = False) list[str]¶
Return every difference between two Pyomo models, sorted.
Two models are equivalent when, keyed by component path relative to the model: they have the same Var, Param, active Constraint, active Objective and Arc names; each Var has the same domain, bounds and fixed flag (and value when fixed); each mutable Param has the same value; each active Constraint has the same bounds and body; the objective has the same sense and expression; and both TimeBlocks have the same time_index and dt.
- Parameters:
a – The first model.
b – The second model.
rel_tol – Relative tolerance for numeric comparisons.
check_values – Also compare values of unfixed Vars (useful after a solve).
- Returns:
One line per difference; empty when the models are equivalent.
- flexops.core.compare.assert_models_equivalent(a, b, *, rel_tol: float = 1e-09, check_values: bool = False) None¶
Raise AssertionError listing every difference between two Pyomo models.
- Parameters:
a – The first model.
b – The second model.
rel_tol – Relative tolerance for numeric comparisons.
check_values – Also compare values of unfixed Vars (useful after a solve).
- Raises:
AssertionError – If the models differ; the message lists the first 50 differences and counts the rest.
Extensions¶
An extension is a user function that adds constraints or an objective. Decorate
it with extension() (exported as flexops.extension) and calling it
records an extension element, so emit_model writes it back. The spec only
names the function, so it builds only where the defining package is installed.
- flexops.core.extensions.extension(fn)¶
Mark
fn(model, **options)as a spec extension.Calling the decorated function records
{"entry_point", "options", "name"}onmodel._flex_extensions(soemit_modelwrites it back), then runs it. Logic helpers it calls record nothing, since rebuilding re-runs it. The name isfn.__name__, numbered_2,_3… on repeated calls; pass_name=to pin it.- Parameters:
fn – A function taking the model and keyword options.
- Returns:
The recording wrapper.
- Raises:
FlexConfigError – When called, if the options aren’t plain JSON data.
- flexops.core.extensions.resolve_extension(entry_point: str)¶
Import the function an extension element names.
- Parameters:
entry_point –
'package.module:function'(a dotted qualname is allowed), or the name of an entry point in theflexpse.extensionsgroup.- Returns:
The function.
- Raises:
FlexConfigError – If it can’t be found.
Build stages¶
build_model runs the stages in STAGES in order. Costing is last
because cost_process() aggregates only the terms registered when it runs.
The logic stage builds its kinds in LOGIC_ORDER, status first and
cross-unit logic last. apply_spec() applies the mutable spec elements
(surrogates, dispatches, fixes and unfixes) to a model that already exists.
- flexops.core.stages.STAGES¶
Build order. Changing it is a schema-contract change (see CONTRIBUTING.md).
- flexops.core.stages.LOGIC_ORDER: tuple[str, ...]¶
Order the logic stage builds kinds in, status first and cross-unit logic last.
- class flexops.core.stages.BuildContext(base_dir: Path | None, expand_arcs: bool = False, members: dict[str, list[~flexops.core.ops_block.OpsBlockData]]=<factory>)¶
What the build stages share.
- base_dir¶
The spec file’s directory, for relative source paths.
- Type:
pathlib.Path | None
- members¶
Each unit element’s name mapped to its block data: one for a scalar unit, one per index for an indexed unit.
- Type:
- flexops.core.stages.apply_spec(model, elements, *, on_violation: str | None = None, tolerance: float | None = None) FixReport¶
Apply mutable spec elements to a built model, without rebuilding it.
Fix, unfix and dispatch elements are checked and applied as one batch. Their conflicts with earlier state are not errors: a later apply is an update.
- Parameters:
model – The built model, updated in place.
elements – Element models or dicts, validated as spec elements.
on_violation – Fix policy; omitted means the built spec’s fix_on_violation, or
"error".tolerance – Fix bounds tolerance; omitted means the built spec’s fix_tolerance, or
1e-9.
- Returns:
The
FixReportof the fix, unfix and dispatch elements.- Raises:
FlexConfigError – If any element’s kind is immutable (checked before anything is applied), a unit or variable is not on the model, or an element fails to apply.
- flexops.core.stages.elements_of(spec: FlowsheetSpec, *kinds: str) list¶
Return the spec’s elements of the given kinds in build order.
- Parameters:
spec – The flat spec.
kinds – Element kinds to return.
- Returns:
The elements sorted by name depth, then name, then what they target; the order of the file is never used.
- flexops.core.stages.apply_relation_spec(unit, spec: SurrogateSpec, relation_name: str = 'power_electrical_relation') tuple[bool, dict[str, Any]]¶
Write a surrogate spec into a live unit as
relation_name.A
constant_intensityspec sets the unit’s intensity parameter. Any other spec updates the relation’s active surrogate in place when that surrogate allows it (same type and config, so only parameter values and fixed flags change), and otherwise swaps a new surrogate block in. Each parameter’s value and fixed flag come from the spec.- Parameters:
unit – The built unit to mutate.
spec – The surrogate to attach.
relation_name – The relation the surrogate replaces.
- Returns:
whether the relation is now a swapped surrogate (
Falseforconstant_intensity), and every parameter’s value by name.- Return type:
(swapped, values)- Raises:
FlexConfigError – If the spec does not match its surrogate’s contract, or a
constant_intensityspec targets a unit without a regressable intensity.
Fixing variables¶
The state stage applies fix, unfix and dispatch elements as one
batch: it plans every point, checks conflicts, bounds and domain, and only then
changes the model (see The config schema).
- flexops.core.fixing.apply_state(model, elements: list, *, base_dir: Path | None = None, on_violation: Literal['error', 'warn', 'skip'] = 'error', tolerance: float = 1e-09) FixReport¶
Apply fix, unfix and dispatch elements together, all or nothing.
- Parameters:
model – The built model, changed in place.
elements – Validated fix, unfix and dispatch elements, in any order.
base_dir – Directory
$sourcepaths resolve against.on_violation – Policy for fix elements that don’t set their own, and for dispatches.
tolerance – Bounds tolerance for elements that don’t set their own.
- Returns:
The
FixReport.- Raises:
FlexConfigError – If an element doesn’t fit the model, two elements set a point differently, or a value violates bounds or domain under
"error"(or domain under"warn"); nothing is changed then.- Warns:
FlexFixWarning – Once per element whose violating points were fixed anyway or skipped.
- class flexops.core.fixing.FixReport(fixed: list[str] = <factory>, unfixed: list[str] = <factory>, skipped: list[str] = <factory>, violations: list[FixViolation] = <factory>)¶
What the state stage changed, kept on a built model as
_flex_fix_report.- violations¶
Every violation that was fixed anyway or skipped.
- class flexops.core.fixing.FixViolation(variable: str, value: float, lb: float | None, ub: float | None, kind: Literal['below_lb', 'above_ub', 'domain'], action: Literal['fixed', 'skipped'], element: str)¶
A fix value outside its variable’s bounds or domain that was fixed or skipped.
- kind¶
"below_lb","above_ub"or"domain".- Type:
Literal[‘below_lb’, ‘above_ub’, ‘domain’]
- action¶
"fixed"(fixed anyway) or"skipped"(left free).- Type:
Literal[‘fixed’, ‘skipped’]
- flexops.core.fixing.element_points(model, element, base_dir: Path | None = None) list[tuple]¶
Return
(point, value)for every point a state element touches.- Parameters:
model – The model.
element – A fix, unfix or dispatch element.
base_dir – Directory
$sourcepaths resolve against.
- Returns:
Each
VarDatawith the value it is set to (None for unfix).- Raises:
FlexConfigError – If the path or values don’t fit the model.
- flexops.core.fixing.variable_points(model, path: str) list¶
Return every variable point a ComponentUID path matches on
model.- Parameters:
model – The model the path is relative to.
path – A ComponentUID string such as
'plant.ro[*].status'.
- Returns:
The matched
VarData, an indexed variable contributing all its points.- Raises:
FlexConfigError – If the path is malformed, matches nothing (naming the closest variables), or matches something that is not a variable.
- flexops.core.fixing.time_of(point, time_index)¶
Return a point’s time index, or None if its variable isn’t indexed by time first.
- Parameters:
point – A
VarData.time_index – The model’s TimeBlock
time_index, or None.
- Returns:
The time index of the point, or None.
Registration¶
This registry holds the records that FlexParameterize and the docs generator consume.
Container for everything a unit block registers. |
|
A registered process input/output variable. |
|
A registered design/regression parameter. |
|
A registered power-draw variable. |
|
A registered fuel-usage variable — a volumetric flow, not a power. |
|
A non-conservation relationship a unit has declared swappable. |
|
A registered boundary flow — a resource entering or leaving a facility. |
|
Which side of a facility boundary a registered flow crosses. |
|
A dict-like |
- flexops.core.registration.iter_io_registry(model) Iterator[tuple[Any, IORegistry]]¶
Yield every block on
modelthat exposes a non-empty registry.Walks
modeland all its sub-blocks and yields(block, registry)for each block carrying a non-empty_io_registryattribute, giving FlexParameterize and the docs generator model-wide discoverability.- Parameters:
model – The Pyomo model (or block) to walk.
- Yields:
(block, registry)pairs, each block yielded at most once.
- flexops.core.registration.iter_swapped_relations(model) Iterator[tuple[Any, RelationRecord]]¶
Yield every relation on
modelthat has actually been swapped.A debugging and reporting aid, not a required step on any build or apply path: it answers “what in this model differs from its defaults?” for a model built any way — from config, by hand, or by
flexparameterize.apply_to_model— not only for the call that changed it. Cheap by construction: it reads thefittedfieldswap_relation()already set on eachRelationRecord, rather than re-deriving anything from constraint bodies.Deliberately out of scope: detecting a relationship altered some other way (hand-editing a constraint’s rule, rebuilding a component outside
swap_relation) would mean constructing a shadow default unit and diffing constraint bodies — a “deep audit” left to a future milestone.- Parameters:
model – The Pyomo model (or block) to walk.
- Yields:
(block, RelationRecord)pairs for every swapped relation.
A boundary flow is registered with
register_boundary_flow(), and the
enclosing plant discovers it from this registry rather than by importing the
Feed/
Product classes. flexops.unit_models
imports flexops.core, so the reverse would be circular.