OpsBlockData¶
- class flexops.core.ops_block.OpsBlockData(component)¶
Base class of every flex-pse unit model (see module docstring).
- add_constant_intensity_relation(flow, *, kind: PowerKind = PowerKind.ELECTRICAL, intensity, temperature=None) None¶
Declare a power draw and tie it to
flowby a constant intensity.Every flex-pse unit’s flow-to-energy relationship is built here (there is no separate regression unit class): it declares
power_<kind>[t], an intensity Var (energy_intensityfor an electrical draw,thermal_intensityfor a heat duty) fixed atintensityand registered as a regressable process parameter, and the equality\[P_{kind}[t] = \text{intensity} \cdot \dot{V}[t]\]as a Constraint named
power_<kind>_relation. That name is the swap contract: it is registered (seeregister_relation()) so FlexParameterize can deactivate exactly it and attach a fitted replacement (seeswap_relation()). When this unit was built from a config whoseSurrogateSpecasks for a richer functional form, the swap is applied here, at construction.flowis the unit’s product stream — what it delivers, not what it takes in — so the intensity reads as energy per unit of output (a reverse-osmosis skid’s kWh per m³ of permeate, the industry’s specific energy consumption). For a unit that passes its flow straight through the two coincide; for one with a recovery or a loss they do not, and the product is the meaningful denominator. The basis is recorded on the unit’s registry so FlexParameterize regresses against the same stream.- Parameters:
flow – The unit’s time-indexed product flow Var/Reference (
flow[t]) the draw scales with.kind – The
PowerKindof the draw.intensity – Energy per unit volume (e.g.
0.5 * pyunits.kWh / pyunits.m**3), converted to kWh/m³.temperature – The heat-duty temperature (required for
PowerKind.THERMAL).
- add_pass_through_constraints(inlet: Port, outlet: Port, *, exclude_vars: Sequence[str] = (), name_prefix: str = 'pass_through') None¶
Pass non-excluded, non-fixed inlet state variables straight to the outlet.
For each state-variable name exposed by
inletand not inexclude_vars, adds an equality Constraintoutlet_var[idx] == inlet_var[idx]over every index the variable carries – unless every entry of that variable is alreadyfixed(e.g. an inlet held at a known pressure), in which case building a redundant constraint is skipped. This is the generic “everything not otherwise governed flows straight through” wiring:SISOBlockcalls it with no exclusions (the flow pass-through is itself a pass-through equality);Tankexcludes the flow-basis variable because its holdup equation governs flow instead. Note this is intra-unit property copying, distinct from a physical bypass stream that diverts flow around a unit (seeflexops.logic.bypass.add_bypass).Gated by
self.config.allow_pass_through: when it isFalsethis method builds no constraints (a developer wires the missing relationship by hand, and the model’s degrees of freedom reflect the unlinked state variables); whenTrueit builds them.- Parameters:
inlet – The unit’s inlet Port carrying the source state variables.
outlet – The unit’s outlet Port receiving the passed-through values.
exclude_vars – State-variable names to leave unlinked (e.g. a topology’s flow-basis variable when the unit governs flow itself).
name_prefix – Prefix of the Constraint names this builds (
"{name_prefix}_{state_var}_eq"). A multi-outlet topology calls this once per outlet and must vary the prefix, since two calls would otherwise collide on one component name.
- Raises:
FlexConfigError – If a name in
exclude_varsis not a state variable exposed byinlet, orinlet/outletwere not built byadd_stream_ports()(no sibling"{port_name}_state"block).
Note
Ports built via
add_inlet_port/add_outlet_portexpose their members as auto-generatedReferenceobjects (port.vars[name]), which carry an extra leadingUnindexedComponent_setdimension and are awkward to index directly. This method instead resolves each port’s sibling"{port_name}_state"block (the conventionadd_stream_ports()establishes) and builds constraints directly against its state variables, so indices stay exactlyinlet_var.index_set()(e.g.(t, phase)), with no leaked reference dimension.
- add_stream_ports(inlet_ports: Sequence[str] = ('inlet',), outlet_ports: Sequence[str] = ('outlet',), io_vars: Sequence[str] = ('flow_vol_phase',)) None¶
Build the configured stream state blocks and expose them as ports.
For each requested port, constructs a scalar state block from this unit’s configured
property_package(its state variables indexed over the time set), registers the namedio_varson that block as process IO variables — inlet ports as"input", outlet ports as"output"— and builds the IDAES port from the state block via the inheritedadd_inlet_port/add_outlet_porthelpers. Each state block is named"{port}_state"(e.g.inlet_state), and each registered IO variable is the live state-blockVaritself (e.g.inlet_state.flow_vol_phase), never aReferenceor slice. The extensive/intensive split of the states a port carries is applied when the topology layer wires the ports onto arcs.- Parameters:
inlet_ports – Names of the inlet ports to build (default one
"inlet").outlet_ports – Names of the outlet ports to build (default one
"outlet").io_vars – State-block variable names to register as process IO on every port (default the volumetric
"flow_vol_phase"). Which variables are the meaningful IO is property-package dependent, so the caller chooses them.
- Raises:
FlexConfigError – If the unit has no
property_packageconfigured.
- allows_status_element: ClassVar[bool] = True¶
Whether a spec
statuselement may target this unit;Falsefor units that manage their own status.
- classmethod build_from_config(cfg: UnitConfig, *, index_set=None, **kwargs)¶
Construct a unit from a validated
UnitConfig.The per-unit primitive behind
build_model(). A path or mapping is round-tripped through the pydantic schema first, so a raw dict is never passed onward and an invalid one raisespydantic.ValidationErrornaming the offending field path (the error is deliberately not wrapped — the field path is the contract).The unit-model class always comes from
cfg.unit_model_class, resolved againstflexops.unit_models. Persisted construction options carry their units as data: a value written{"value": 0.5, "units": "kWh/m^3"}becomes a units-carrying Pyomo expression, as does each such value inside a mapping option (heating_values); anything else passes through unchanged – including a plain string naming an enum member ("detail": "polarization"), which the receivingConfigValue’s own domain then validates. Runtime-only options that cannot be serialized (property_package,costing_package) are supplied by the caller throughkwargs, which wins over the config on a key collision.- Parameters:
cfg – A
UnitConfig, or a mapping/path to validate into one.index_set – A Pyomo Set to build one unit per member over; omitted builds a single unit.
**kwargs – Extra runtime construction options.
- Returns:
The constructible unit block, to be assigned onto a model (
m.u = OpsBlockData.build_from_config(cfg, ...)).- Raises:
pydantic.ValidationError – If
cfgfails schema validation.FlexConfigError – If
cfg.unit_model_classis not a flexops unit-model class.
- create_stream_naming_convention(naming_dict: dict[str, str]) None¶
Register this unit’s role -> Pyomo component name mapping.
Called once from an IO-topology base’s
build(), before any named component is built, with either that topology’s default vocabulary or thenaming_dicta physical subclass passed up. Only the components are renamed; ports never are.- Parameters:
naming_dict – The complete role -> component name mapping this unit builds and looks names up through.
- current_surrogate_block(relation_name: str | None = None) str | None | dict[str, str]¶
Return the local name of the currently active surrogate block(s).
- Parameters:
relation_name – If provided, return the active block for this relation only. If
None, return a mapping of every relation that currently has an active surrogate to its block’s local name.- Returns:
The active block’s local name,
Noneif no surrogate is active for the requested relation, or adictmapping relation names to active block names whenrelation_nameisNoneand at least one surrogate is active. ReturnsNonewhen no surrogates are active anywhere on the unit.- Raises:
FlexConfigError – If
relation_nameis provided but is not a registered relation.
- declare_power(kind: PowerKind = PowerKind.ELECTRICAL, *, temperature=None)¶
Create, register, and return this unit’s power-draw Var (kW).
Creates
power_electrical[t](resp.power_thermal[t]) indexed over the time set, attaches it under its nomenclature name, registers it (with its temperature metadata), and returns it.- Parameters:
kind – The
PowerKindof the draw.temperature – The heat-duty temperature, a unit-carrying value (required only for
PowerKind.THERMAL).
- Returns:
The created, time-indexed
Varin kW.- Raises:
FlexConfigError – If
kindis not aPowerKindmember, or thetemperaturemetadata does not matchkind.
- declare_process_parameter(name: str, value, units, doc: str, *, bounds: tuple[float | None, float | None] | None = None, regressable: bool = True)¶
Create, fix, register, and return a scalar process-parameter Var.
The parameter twin of
declare_power(), and the one way flex-pse declares a design or fitted coefficient: a scalar Var fixed at its configured value rather than aParam, so a design mode or a regression can unfix it in place without any component being replaced. Because it is registered, the value is reachable afterwards throughupdate_parameters().- Parameters:
name – The component name to attach the Var under.
value – The initial value, either a units-carrying Pyomo expression (converted into
units) or a bare number, taken to be inunitsalready.units – The Var’s Pyomo units.
doc – The Var’s
doc=string; required, since the generated docs render it.bounds – Optional
(lower, upper)bounds, inunits. Give them whenever unfixing the parameter would otherwise admit a physically meaningless value (an efficiency above one, say);Noneleaves it unbounded.regressable – Whether FlexParameterize may fit this parameter.
- Returns:
The created, fixed scalar
Var.
- fix_surrogate_coefficients(relation_name: str | None = None) None¶
Fix all coefficient Vars in the active surrogate block(s) at their current values.
This is the counterpart to
unfix_surrogate_coefficients(). After solving, call this to lock the coefficients at their solved values.- Parameters:
relation_name – The relation whose coefficients to fix. If
None, every relation on this unit that currently has an active surrogate block is operated on.- Raises:
FlexConfigError – If
relation_nameis provided but is not registered or has no active surrogate block.
- get_surrogate_objective(relation_name: str | None = None, **kwargs)¶
Return the active surrogate’s objective expression, if it exposes one.
This mirrors
get_surrogate_spec(): the method picks the active surrogate on the selected relation and delegates to the surrogate block’s objective helper when available, without creating a persistent Objective.- Parameters:
relation_name – The relation whose active surrogate objective to fetch. If
None, use the unit’s only active surrogate.**kwargs – Extra arguments forwarded to the surrogate block’s objective helper (for example,
innovation_scaleortime_index).
- Returns:
A Pyomo expression representing the objective contribution from the active surrogate block.
- Raises:
FlexConfigError – If there is no active surrogate block,
relation_nameisNonewhile several surrogates are active, or the active surrogate block does not expose a regression/objective helper.
- get_surrogate_spec(relation_name: str | None = None) SurrogateSpec¶
Return the active surrogate’s current spec, read from its block.
A pure read: it changes nothing.
configis the surrogate’s own (including any state recorded byupdate_surrogate_state()), and each parameter’s value and fixed flag come from the live block. For the receding-horizon handoff, callupdate_surrogate_state()after the solve, then this.- Parameters:
relation_name – The relation whose active surrogate spec to retrieve. If
None, use the unit’s only active surrogate.- Returns:
A
SurrogateSpecthat rebuilds the surrogate as it stands.- Raises:
FlexConfigError – If the relation is not registered, has no active surrogate block,
relation_nameisNonewhile several surrogates are active, or the surrogate does not implementread_spec.
- list_surrogate_blocks(relation_name: str | None = None) list[str]¶
Return the local names of every surrogate block ever built.
- Parameters:
relation_name – If provided, limit the result to surrogate blocks built for this relation. If
None, return every surrogate block ever built on this unit, across all relations.- Returns:
Local names of the surrogate blocks, oldest first. Empty if no surrogate has been swapped for the requested relation (or for any relation when
relation_nameisNone).- Raises:
FlexConfigError – If
relation_nameis provided but is not a registered relation.
- register_boundary_flow(var, *, resource: str, kind: BoundaryKind) None¶
Register a total flow crossing the facility boundary, for aggregation.
A boundary block (a source or a sink) meters the whole resource it withdraws or delivers, and the enclosing
PlantBlockDatadiscovers those flows through this registry rather than by importing the unit-model classes, summing them intototal_feed[resource, t]/total_product[resource, t]. Any unit may call it, not onlyFeedandProduct.resourceis the aggregation key and is independent of the Pyomo block name: two blocks sharing oneresourcesum into a single row (the same resource entering at two points), and two blocks with different ones give two rows.- Parameters:
var – The time-indexed Pyomo
Var/Referencecarrying the total flow across the boundary.resource – The resource’s name (e.g.
"raw_water"), the key its flow aggregates under.kind – Whether the flow enters or leaves the facility.
- Raises:
FlexConfigError – If
resourceis empty.
- register_fuel_usage(var, fuel_name: str) None¶
Register a fuel-usage variable — a volumetric flow — for costing.
Fuel is metered and billed on volume, not as a kW power draw, so a unit that burns fuel registers its usage flow here rather than through
register_power().varis typically an existing process variable: for a stream built fromSimpleGasFlow(whoseflow_vol_phaseis already m³/hr), that ispyo.Reference(self.inlet_state.flow_vol_phase[:, "Vap"]).FlexCosting pulls every registered flow from the model and sums it into
aggregate_fuel_usage[t, fuel_name]in EECO’s m³/hr, converting withpyunits.convert— so avarthat is not a volumetric rate fails loudly there, the same contract a power draw has. flex-pse applies no heating value; energy-basis tariff conversion is EECO’s job.- Parameters:
var – The time-indexed Pyomo
Var/Referencecarrying the fuel’s volumetric flow (convertible to m³/hr).fuel_name – The fuel’s name (e.g.
"natural_gas"), the key its flow aggregates and bills under.
- Raises:
FlexConfigError – If
fuel_nameis empty.
- register_io_variable(var, role: str = 'input', tag_hint: str | None = None) None¶
Register a process input/output variable (fixed during regression).
- Parameters:
var – The Pyomo
Varto register.role –
"input"or"output".tag_hint – Optional historian-tag hint for FlexParameterize.
- Raises:
FlexConfigError – If
roleis not"input"or"output".
- register_power(var, kind: PowerKind = PowerKind.ELECTRICAL, *, temperature=None) None¶
Register a power-draw variable for plant/costing aggregation.
- Parameters:
var – The Pyomo
Var(kW) to register.kind – The
PowerKindof the draw.temperature – The heat-duty temperature, a unit-carrying value (required only for
PowerKind.THERMAL).
- Raises:
FlexConfigError – If
kindis not aPowerKindmember, or thetemperaturemetadata does not matchkind.
- register_process_parameter(param_or_var, regressable: bool = True) None¶
Register a design/regression parameter (found during regression).
- Parameters:
param_or_var – The Pyomo
ParamorVarto register.regressable – Whether FlexParameterize may fit this parameter.
- register_relation(constraint, target) None¶
Declare
constraintswappable: a relationship determiningtarget.Only a registered relationship may ever be swapped by
swap_relation()— a mass balance or other conservation law that is never registered can never be swapped, by construction (there is no naming convention to accidentally satisfy).add_constant_intensity_relation()registers the relation it builds; a unit with its own performance relationship (an RO skid’ssplit_definition, a tank’slevel_definition) registers it the same way.- Parameters:
constraint – The live, time-indexed Constraint to declare swappable.
target – The live Var/Reference it determines. Must be indexed over exactly one dimension (time); a target indexed over more (a per-component flux, say) is out of scope for this milestone.
- Raises:
FlexConfigError – If
target’s index set is not one-dimensional.
- register_surrogate_coefficients(relation_name: str, *, remove_target: bool = True) list[str]¶
Register a swapped surrogate’s coefficient Vars as regressable parameters.
After
swap_relation()attaches a surrogate torelation_name, call this to (a) register each coefficient Var in the unit’sIORegistryas a regressable process parameter, and (b) remove the relation’s performance target from the parameter list so it is not regressed against alongside the coefficients.The surrogate block’s
coefficientsattribute is aCoefficientRegistrywhoseitems()yields(name, Var)pairs. Any object with anitems()method returning(str, pyo.Var)pairs is accepted.- Parameters:
relation_name – The relation whose surrogate coefficients to register.
remove_target – If True, remove
record.targetfrom the parameters list (it is a performance output, not a regressable input).
- Returns:
The local names of the registered coefficient parameters.
- resolve_variable(name: str, *, field: str, model_wide: bool = False)¶
Return the variable
namerefers to on this unit.Part of the documented contract a
Surrogateuses to resolve its declared variables at build time (dotted names into a sub-block, e.g."outlet_state.pressure", resolve too). A mistyped name, or one naming a block or constraint, is refused here so it never reaches a build.- Parameters:
name – A component name, possibly dotted into a sub-block.
field – The surrogate field the name came from, for the error.
model_wide – Also accept a name qualified from the model root (a
model_alias(), such as"plant.unit.flow_out") when it is not a name on this unit.
- Returns:
The resolved Var, Expression or Param.
- Raises:
FlexConfigError – If the name is not a component on this unit (or the model, with
model_wide), or names something other than a Var, Expression or Param.
- set_external_dispatch(var, series, *, fix: bool = True) None¶
Drive a controllable var from an external time-indexed command series.
For each time point
t, setsvar[t]toseries[t]and, whenfixis True, fixes it — removing the dispatch degree of freedom while leaving sizing free (the DERMS/aggregator case). Available on all units; first-classed onBatteryModel.- Parameters:
var – A time-indexed
Varon this unit.series – A mapping or pandas Series aligned to the time set, keyed by integer index or timestamp.
fix – Whether to fix each
var[t]after setting it.
- Raises:
FlexConfigError – If
varis not indexed, orseriesdoes not cover exactly the time set.
- swap_relation(relation_name: str, surrogate: Surrogate, *, auto_register_coefficients: bool = True) Block | None¶
Replace a registered relationship in place, from a surrogate.
Deactivates the named relation (never deletes it), deactivates whatever an earlier swap’s builder attached, and adds
{relation_name}_fittedbuilt fromsurrogate, reusing the unit’s existing registered variables so ports and arcs are untouched. One implementation, every caller: construction-time (add_constant_intensity_relation(), via a config’sSurrogateSpec), runtime (flexparameterize.apply_to_model), and any unit that hand-builds and registers its own relationship.surrogate(aSurrogate, e.g.MultilinearSurrogate) is already validated;build()does the rest — it returns(block, body(t)), whereblockis a Pyomo Block carrying the surrogate’s coefficient Vars (orNoneif the surrogate needs no auxiliary Vars), andbodyis a units-carrying Pyomo expression in the surrogate’s own declared output units for that time point, orpyomo.environ.Constraint.Skipto omit it (a lagged/state-space form uses this to skip horizon points where its lag does not exist).bodyis converted into the registered target’s own units here, so a surrogate fitted in one unit basis attaches cleanly to a target carrying another. A builder may attach its own components tounit(an auxiliary Var/Constraint a big-M or state-space form needs); this method finds and tracks them itself, so nothing needs to be returned besidesbody. Registering another relationship shape is a new class inflexops.surrogates, never a config-schema change.The fitted constraint is placed on the surrogate block itself when one is returned, so deactivating the block turns off the entire surrogate layer in one step. The block is named
surrogate_{relation_base}(uniquified on collision) and tracked inrecord.surrogate_blockandrecord.surrogate_blocks.When
auto_register_coefficientsisTrue(the default),register_surrogate_coefficients()is called automatically after the swap, so the new coefficients are immediately visible in the unit’sIORegistry. PassFalsewhen the caller will handle registration itself (e.g. because it must set coefficient values before they become regressable parameters).- Parameters:
relation_name – Local name of a relation this unit registered via
register_relation()(e.g."power_electrical_relation","split_definition").surrogate – The
Surrogateto attach (seesurrogate_from_spec()).auto_register_coefficients – If
True, register the new surrogate block’s coefficients in the IO registry before returning.
- Returns:
The surrogate sub-block (or
Noneif the surrogate needs no auxiliary Vars).- Raises:
FlexConfigError – If
relation_namewas never registered, or a declared input variable is not found on the unit.
- switch_surrogate_block(block_name: str) None¶
Switch to a previously built surrogate block by its local name.
Looks up the block on this unit by name, finds the
RelationRecordit belongs to, deactivates whatever is currently active for that relation, activates the named block, pointsrecord.surrogate_blockandrecord.surrogate_instanceat it and the surrogate that built it, and re-registers its coefficients as regressable parameters.- Parameters:
block_name – The local name of the surrogate block to activate (e.g.
"surrogate_power"or"surrogate_power_1").- Raises:
FlexConfigError – If
block_nameis not found on this unit, or is not a surrogate block.
- unfix_surrogate_coefficients(relation_name: str | None = None) None¶
Unfix all coefficient Vars in the active surrogate block(s).
After calling, the coefficients are free variables again and a solve can adjust them. Call
fix_surrogate_coefficients()to re-fix them at their current values after the solve.- Parameters:
relation_name – The relation whose coefficients to unfix. If
None, every relation on this unit that currently has an active surrogate block is operated on.- Raises:
FlexConfigError – If
relation_nameis provided but is not registered or has no active surrogate block.
- update_parameters(values: dict) None¶
Update registered process parameters in place, by name.
This is flex-pse’s only sanctioned way to change a built model’s parameters: mutate the existing (mutable)
Param/Varso every constraint and expression that references it sees the new value. Never delete and rebuild components — anything else on the model holding a reference to the old component would silently keep the stale one.- Parameters:
values – Mapping of registered parameter name (as returned by
register_process_parameter) to its new value. Values may carry Pyomo units; bare numbers are taken in the component’s declared units.- Raises:
FlexConfigError – If a name is not a registered process parameter.
- update_surrogate_parameters(values: dict, relation_name: str | None = None) None¶
Set the active surrogate’s parameter values in place, by name.
Fixed flags are unchanged. An array parameter takes nested lists of its shape.
- Parameters:
values –
{parameter name: value}, by the names the surrogate registers (e.g."ar.L1","exog.feed").relation_name – The relation whose surrogate to update. If
None, use the unit’s only active surrogate.
- Raises:
FlexConfigError – If there is no single active surrogate, a name is not one of its parameters, or a value has the wrong shape.
- update_surrogate_state(relation_name: str | None = None) None¶
Record the active surrogate’s solved state into its config.
Call after a successful solve. A surrogate with time-dependent state rewrites its own
configfrom the solution – ARIMA replaces itshistory, so its spec initializes the next horizon from the solve. Surrogates without such state are unchanged. Never runs implicitly;get_surrogate_spec()andemit_modelthen see the new state.- Parameters:
relation_name – The relation whose surrogate to update. If
None, use the unit’s only active surrogate.- Raises:
FlexConfigError – If there is no single active surrogate to update, it does not implement
update_state, or it reports that the block has not been solved.