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 flow by 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_intensity for an electrical draw, thermal_intensity for a heat duty) fixed at intensity and 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 (see register_relation()) so FlexParameterize can deactivate exactly it and attach a fitted replacement (see swap_relation()). When this unit was built from a config whose SurrogateSpec asks for a richer functional form, the swap is applied here, at construction.

flow is 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 PowerKind of 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 inlet and not in exclude_vars, adds an equality Constraint outlet_var[idx] == inlet_var[idx] over every index the variable carries – unless every entry of that variable is already fixed (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: SISOBlock calls it with no exclusions (the flow pass-through is itself a pass-through equality); Tank excludes 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 (see flexops.logic.bypass.add_bypass).

Gated by self.config.allow_pass_through: when it is False this method builds no constraints (a developer wires the missing relationship by hand, and the model’s degrees of freedom reflect the unlinked state variables); when True it 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_vars is not a state variable exposed by inlet, or inlet/outlet were not built by add_stream_ports() (no sibling "{port_name}_state" block).

Note

Ports built via add_inlet_port/add_outlet_port expose their members as auto-generated Reference objects (port.vars[name]), which carry an extra leading UnindexedComponent_set dimension and are awkward to index directly. This method instead resolves each port’s sibling "{port_name}_state" block (the convention add_stream_ports() establishes) and builds constraints directly against its state variables, so indices stay exactly inlet_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 named io_vars on 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 inherited add_inlet_port/add_outlet_port helpers. Each state block is named "{port}_state" (e.g. inlet_state), and each registered IO variable is the live state-block Var itself (e.g. inlet_state.flow_vol_phase), never a Reference or 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_package configured.

allows_status_element: ClassVar[bool] = True

Whether a spec status element may target this unit; False for units that manage their own status.

build() → None

Set up dynamics defaults and the empty IO registry (no constraints).

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 raises pydantic.ValidationError naming 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 against flexops.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 receiving ConfigValue’s own domain then validates. Runtime-only options that cannot be serialized (property_package, costing_package) are supplied by the caller through kwargs, 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 cfg fails schema validation.

  • FlexConfigError – If cfg.unit_model_class is 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 the naming_dict a 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, None if no surrogate is active for the requested relation, or a dict mapping relation names to active block names when relation_name is None and at least one surrogate is active. Returns None when no surrogates are active anywhere on the unit.

Raises:

FlexConfigError – If relation_name is 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 PowerKind of the draw.

  • temperature – The heat-duty temperature, a unit-carrying value (required only for PowerKind.THERMAL).

Returns:

The created, time-indexed Var in kW.

Raises:

FlexConfigError – If kind is not a PowerKind member, or the temperature metadata does not match kind.

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 a Param, 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 through update_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 in units already.

  • units – The Var’s Pyomo units.

  • doc – The Var’s doc= string; required, since the generated docs render it.

  • bounds – Optional (lower, upper) bounds, in units. Give them whenever unfixing the parameter would otherwise admit a physically meaningless value (an efficiency above one, say); None leaves 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_name is 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_scale or time_index).

Returns:

A Pyomo expression representing the objective contribution from the active surrogate block.

Raises:

FlexConfigError – If there is no active surrogate block, relation_name is None while 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. config is the surrogate’s own (including any state recorded by update_surrogate_state()), and each parameter’s value and fixed flag come from the live block. For the receding-horizon handoff, call update_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 SurrogateSpec that rebuilds the surrogate as it stands.

Raises:

FlexConfigError – If the relation is not registered, has no active surrogate block, relation_name is None while several surrogates are active, or the surrogate does not implement read_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_name is None).

Raises:

FlexConfigError – If relation_name is 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 PlantBlockData discovers those flows through this registry rather than by importing the unit-model classes, summing them into total_feed[resource, t] / total_product[resource, t]. Any unit may call it, not only Feed and Product.

resource is the aggregation key and is independent of the Pyomo block name: two blocks sharing one resource sum 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/Reference carrying 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 resource is 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(). var is typically an existing process variable: for a stream built from SimpleGasFlow (whose flow_vol_phase is already m³/hr), that is pyo.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 with pyunits.convert — so a var that 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/Reference carrying 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_name is 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 Var to register.

  • role – "input" or "output".

  • tag_hint – Optional historian-tag hint for FlexParameterize.

Raises:

FlexConfigError – If role is 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 PowerKind of the draw.

  • temperature – The heat-duty temperature, a unit-carrying value (required only for PowerKind.THERMAL).

Raises:

FlexConfigError – If kind is not a PowerKind member, or the temperature metadata does not match kind.

register_process_parameter(param_or_var, regressable: bool = True) → None

Register a design/regression parameter (found during regression).

Parameters:
  • param_or_var – The Pyomo Param or Var to register.

  • regressable – Whether FlexParameterize may fit this parameter.

register_relation(constraint, target) → None

Declare constraint swappable: a relationship determining target.

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’s split_definition, a tank’s level_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 to relation_name, call this to (a) register each coefficient Var in the unit’s IORegistry as 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 coefficients attribute is a CoefficientRegistry whose items() yields (name, Var) pairs. Any object with an items() method returning (str, pyo.Var) pairs is accepted.

Parameters:
  • relation_name – The relation whose surrogate coefficients to register.

  • remove_target – If True, remove record.target from 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 name refers to on this unit.

Part of the documented contract a Surrogate uses 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, sets var[t] to series[t] and, when fix is True, fixes it — removing the dispatch degree of freedom while leaving sizing free (the DERMS/aggregator case). Available on all units; first-classed on BatteryModel.

Parameters:
  • var – A time-indexed Var on 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 var is not indexed, or series does 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}_fitted built from surrogate, 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’s SurrogateSpec), runtime (flexparameterize.apply_to_model), and any unit that hand-builds and registers its own relationship.

surrogate (a Surrogate, e.g. MultilinearSurrogate) is already validated; build() does the rest — it returns (block, body(t)), where block is a Pyomo Block carrying the surrogate’s coefficient Vars (or None if the surrogate needs no auxiliary Vars), and body is a units-carrying Pyomo expression in the surrogate’s own declared output units for that time point, or pyomo.environ.Constraint.Skip to omit it (a lagged/state-space form uses this to skip horizon points where its lag does not exist). body is 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 to unit (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 besides body. Registering another relationship shape is a new class in flexops.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 in record.surrogate_block and record.surrogate_blocks.

When auto_register_coefficients is True (the default), register_surrogate_coefficients() is called automatically after the swap, so the new coefficients are immediately visible in the unit’s IORegistry. Pass False when 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 Surrogate to attach (see surrogate_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 None if the surrogate needs no auxiliary Vars).

Raises:

FlexConfigError – If relation_name was 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 RelationRecord it belongs to, deactivates whatever is currently active for that relation, activates the named block, points record.surrogate_block and record.surrogate_instance at 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_name is 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_name is 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/Var so 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 config from the solution – ARIMA replaces its history, so its spec initializes the next horizon from the solve. Surrogates without such state are unchanged. Never runs implicitly; get_surrogate_spec() and emit_model then 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.