flexops.logic

This is the composable unit commitment layer, a set of optional constraint pieces applied per unit. add_status() is the base (present whenever a unit can be shut off), and everything else is opt-in. Every name below is re-exported from flexops.logic itself.

Status

flexops.logic.status.add_status(unit: Any, output_var: Var, min_output: Any, max_output: Any) → Var

Attach the on/off status binary and its semicontinuous links to a unit.

Adds status[t] (Binary, indexed by the unit’s time points) plus two Constraints linking output_var to it:

  • status_min_link[t]: min_output * status[t] <= output_var[t]

  • status_max_link[t]: output_var[t] <= max_output * status[t]

Together they force output_var[t] == 0 when the unit is off (status[t] == 0) and min_output <= output_var[t] <= max_output when it is on. The status binary is tracked so relax/unrelax cover it. Call at most once per unit (v0 uses the fixed component names status / status_min_link / status_max_link).

Parameters:
  • unit – The unit block to attach the status structure to.

  • output_var – The time-indexed output Var (e.g. a power draw) gated by the status binary.

  • min_output – Minimum output when on, a units-carrying quantity matching output_var (e.g. 0 * pyunits.kW).

  • max_output – Maximum output when on, a units-carrying quantity matching output_var.

Returns:

The attached Binary status Var.

flexops.logic.status.relax(unit: Any) → None

Switch every logic-attached Binary on unit to pyo.UnitInterval.

A first-class, live-model domain switch (LP relaxation of the unit’s discrete structure): it changes only variable domains – never constraints, bounds, or fixed values – so warm starts and references held elsewhere (costing, aggregation) survive. A no-op if the unit has no tracked binaries.

Parameters:

unit – The unit whose tracked binaries to relax.

flexops.logic.status.unrelax(unit: Any) → None

Switch every logic-attached Binary on unit back to pyo.Binary.

The exact inverse of relax() (domain-only). A no-op if the unit has no tracked binaries.

Parameters:

unit – The unit whose tracked binaries to restore to integrality.

Commitment and timing

flexops.logic.unit_commitment.add_startup_shutdown(unit: Any, status_var: Var, min_uptime: int = 1, min_downtime: int = 1) → tuple[Var, Var]

Attach startup[t]/shutdown[t] binaries and transition logic.

For each t >= 1, adds:

  • transition[t]: status_var[t] - status_var[t-1] == startup[t] - shutdown[t].

  • min_uptime[t]: sum(startup[i] for i in window) <= status_var[t], window = range(max(1, t - min_uptime + 1), t + 1). A startup within the trailing min_uptime steps forces the unit on at t.

  • min_downtime[t]: the mirror, sum(shutdown[i] for i in window) <= 1 - status_var[t], window sized by min_downtime.

At the defaults (min_uptime=1, min_downtime=1) each window is the single point {t}, so these reduce exactly to the tightening bounds startup[t] <= status_var[t] and shutdown[t] <= 1 - status_var[t]. Summing those two implies startup[t] + shutdown[t] <= 1 directly (even under a continuous relaxation of startup/shutdown), so no separate exclusivity constraint is needed.

No horizon-end truncation is needed – each window’s upper bound is always t, which is always in range; only the lower bound is clamped to 1.

t = 0 is left unconstrained in v0: there is no initial-status Param to reference a transition into the horizon’s first point.

startup/shutdown are continuous on [0, 1], not Binary: once status_var is integral, transition[t] together with the min_uptime[t]/min_downtime[t] rows (whose windows always contain t) admit exactly one solution, startup[t] = max(0, delta) and shutdown[t] = max(0, -delta) for delta = status_var[t] - status_var[t-1]. Declaring them Binary would only add branching candidates. They are therefore not tracked for relax/unrelax.

Parameters:
  • unit – The unit block to attach the transition structure to.

  • status_var – The unit’s time-indexed on/off status Binary (from add_status()).

  • min_uptime – Minimum number of steps the unit must stay on after a startup. Must be >= 1; 1 means no additional requirement beyond the instant the unit turns on.

  • min_downtime – Minimum number of steps the unit must stay off after a shutdown. Must be >= 1, with the same “no-op at 1” meaning.

Returns:

The attached (startup, shutdown) Vars (continuous on [0, 1], integral whenever status_var is), each indexed over t >= 1.

Raises:

FlexConfigError – If min_uptime or min_downtime is < 1.

flexops.logic.delays.add_startup_delay(unit: Any, upstream: Any, k: int, initially_on: bool = True) → Constraint

Tie unit’s on/off status to an upstream unit’s status, delayed by k.

unit may be on at t only if upstream was on continuously across the trailing window [t - k, t] – one condition that covers both the k-step delay and “upstream off implies downstream off”. Disaggregated over each lag in that window (unit.status[t] <= upstream.status[t - lag] for every lag in 0..k) rather than an aggregate sum, because it is tighter under the LP relaxation used by relax().

Parameters:
  • unit – The downstream unit block; must already carry a status Var (via add_status()).

  • upstream – The upstream unit block whose status Var gates unit.

  • k – Number of steps the downstream start is delayed behind the upstream.

  • initially_on – How to handle a window that reaches before t = 0. If True (default), the window clamps to [max(t - k, 0), t] – a unit already running at t = 0 counts as warmed up, the right convention for a standalone horizon. If False, the window is only checked for t >= k and unit.status[t] == 0 is forced for t < k instead – the right convention for a rolling-horizon window with no assumed prior state.

Registers unit’s status Var as rolling-horizon state (trailing k steps) via flexops.logic.status._register_rolling_state – consuming that registry is the rolling-horizon scheduler’s job, not built here.

Returns:

The attached startup_delay Constraint.

Raises:

FlexConfigError – If upstream has no status Var.

flexops.logic.dwell.add_dwell(var: Var, k: int) → Any

Hold a continuous, time-indexed Var constant within fixed k-step blocks.

The horizon is partitioned into blocks starting at t = 0, k, 2k, ...; within each block every point is constrained equal to its predecessor, so the variable can only change value at a block boundary. The unit is taken from var.parent_block() (the block var is already attached to).

Parameters:
  • var – A continuous, time-indexed Var to hold steady within each block (e.g. an inlet flow or temperature set point).

  • k – Block length in steps. Must be >= 1.

Returns:

The attached {var.local_name}_dwell Constraint, indexed over every t that is not a block boundary. None if k == 1 (every point is its own block, so no constraint is built).

Raises:

FlexConfigError – If k < 1.

add_dwell is a distinct, unrelated concept from add_startup_shutdown’s minimum uptime/downtime. It holds a continuous process variable steady, not a unit’s on/off status.

Ramp rate

flexops.logic.ramp.add_ramp_rate(var: Var, *, name: str | None = None, ramp_up: float | None = None, ramp_down: float | None = None, ramp_rate_units: Any = None, window: int = 1) → tuple[Var, Constraint | None, Constraint | None]

Attach a ramp-rate limit to a time-indexed Var.

Builds a tracked Var (name, identical to var[t] via a defining constraint <name>_def) and, for each direction requested, a Constraint bounding how much <name> may change between t and t - window:

  • <name>_ramp_up[t]: tracked[t] - tracked[t - window] <= ramp_up * ramp_rate_units * window * dt.

  • <name>_ramp_down[t]: tracked[t - window] - tracked[t] <= ramp_down * ramp_rate_units * window * dt.

Every t < window is skipped: the horizon carries no pre-horizon history to ramp against (mirroring add_startup_shutdown’s untied t = 0).

Attaching more than one ramp to the same var (e.g. a fast step-to-step check plus a slower windowed one) is allowed, but is more often an accidental duplicate call, so it is logged as a warning.

Parameters:
  • var – The time-indexed Var to ramp-limit. The unit block is inferred from var.parent_block().

  • name – Component-name stem. Defaults to f"{var.local_name}_ramp".

  • ramp_up – Maximum allowed increase, in ramp_rate_units, over window steps. None to leave increases unconstrained.

  • ramp_down – Maximum allowed decrease, in ramp_rate_units, over window steps. None to leave decreases unconstrained.

  • ramp_rate_units – Pyomo unit expression (e.g. pyunits.kW / pyunits.hr) that ramp_up/ramp_down are given in. Required whenever either is given.

  • window – Number of steps the ramp is measured across. Must be >= 1.

Returns:

(tracked_var, ramp_up_constraint, ramp_down_constraint). The unused direction’s constraint is None.

Raises:

FlexConfigError – If window < 1; if both ramp_up and ramp_down are None; if either is negative; or if either is given without ramp_rate_units.

Degradation penalty

flexops.logic.degradation.add_degradation(unit, spec: DegradationSpec, *, costing=None) → tuple[Var, Var]

Attach the degradation penalty spec to unit, billed through costing.

Parameters:
  • unit – The unit block whose variables the terms name.

  • spec – The validated penalty (terms, covered cost and budget).

  • costing – A FlexCosting block to bill the charged wear cost to as the scalar cost f"{unit.local_name}_{spec.name}", or None.

Returns:

the <name>_rate[t] wear-cost rate Var (1/hr, in the model currency) and the <name>_total horizon wear-cost Var.

Return type:

(rate, total)

Raises:

FlexConfigError – If unit already has a penalty named spec.name, a term names a variable that is not on unit or not indexed by time alone, or costing has already run cost_process().

Warning

The hinge Vars equal the wear only when a price or budget pushes them down; without costing or horizon_budget, or while wear is below covered_cost, their values are loose.

add_degradation is the soft counterpart of add_ramp_rate: it prices wear drivers instead of forbidding them. See Degradation penalties for the formulation.

Bypass and implications

flexops.logic.bypass.add_bypass(unit: Any, flow_var: Var, bypass_max: Any) → Var

Attach bypass_flow[t] and the treated_flow[t] it defines.

Adds:

  • bypass_flow[t] – Var, same units as flow_var, bounded [0, bypass_max].

  • treated_flow[t] – Var, same units as flow_var; the quantity a unit’s energy relation should consume instead of the raw flow.

  • treated_flow_eq[t]: treated_flow[t] == flow_var[t] - bypass_flow[t].

Parameters:
  • unit – The unit block to attach the bypass structure to.

  • flow_var – The time-indexed flow Var being (partially) bypassed.

  • bypass_max – Upper bound on bypass_flow[t], a units-carrying quantity matching flow_var.

Returns:

The attached treated_flow Var.

flexops.logic.conditional.add_conditional(x_unit: Any, y_unit: Any, *, then: str = 'on') → Constraint

Attach a conditional status implication between two units, on x_unit.

  • then="on": y_unit.status[t] >= x_unit.status[t] (x on implies y on).

  • then="off": y_unit.status[t] <= 1 - x_unit.status[t] (x on implies y off).

Parameters:
  • x_unit – The “if” unit; must carry a status Var. The constraint is attached to this unit as conditional.

  • y_unit – The “then” unit; must carry a status Var.

  • then – "on" or "off", the implied state of y_unit when x_unit is on.

Returns:

The attached conditional Constraint (on x_unit).

Raises:

FlexConfigError – If then is not "on"/"off", or either unit lacks a status Var.

Parallel trains and degeneracy

Symmetry among identical parallel trains creates degeneracy in solver time. Many solutions with equal objective values differ only in which interchangeable unit is on, or in how a shared duty is split between them. A unit cannot see its siblings, so this is handled outside the unit level. The caller declares the group, not a unit’s own build().

The group is listed in priority order and ordered descending along that list:

group[0].status[t] >= group[1].status[t] >= ... >= group[-1].status[t]

so a train may not run unless its predecessor runs, and the unit listed first is the first one on. The same ordering applies to any continuous Vars named in variables. What an ordering buys is a smaller search, since it cuts the permuted copies of a split duty, rather than a unique split. A split with an equal cost that is not merely a relabelling of another still satisfies it.

Status ordering is the default and requires a status Var on every unit in the group. Since status is attached by the caller (add_status()) rather than by a unit’s build(), a group that never had unit commitment applied (or one made up of units that have no on/off state at all, such as a tank) is registered with order_status=False, which orders the named variables alone.

flexops.logic.degeneracy.register_parallel_group(units: list[Any], *, variables: Sequence[str] = (), order_status: bool = True) → list[Constraint]

Declare units as a parallel/degenerate hierarchy group and order them.

For units the caller knows to be interchangeable or otherwise hierarchically related — parallel skids, staged trains, a lead/lag pair.

Canonical direction. units is given in priority order, lowest first, and the group is ordered descending along that list:

units[0].status[t] >= units[1].status[t] >= ... >= units[-1].status[t]

so a train may not run unless its predecessor runs and units[0] is the first one on. Pass order_status=False to skip this and order only the named variables – the way to register a group whose units carry no status Var. Implemented by chaining add_conditional() over every consecutive pair back to front (add_conditional(units[i + 1], units[i]) reads as “units[i + 1] on implies units[i] on”), reusing its tested two-unit implication semantics rather than re-implementing them. Each pair’s Constraint therefore lands on the later unit: units[0] carries no conditional, units[-1] does.

Continuous variables. Each name in variables is resolved on every unit and ordered the same way, units[i].<name> >= units[i + 1].<name>, as a Constraint named {name}_ordering attached beside that pair’s conditional. Time-indexed Vars are ordered at every index; scalar Vars (a unit’s regressable process parameters, e.g. ReverseOsmosis.energy_intensity) get a single Constraint. Such parameters are fixed at construction, so an ordering over them only binds once a caller or FlexParameterize unfixes them — until then it is a trivially satisfied constant.

Parameters:
  • units – >= 2 units, in the intended canonical order (highest priority first).

  • variables – Local component names of continuous Vars to order across the group, as each unit exposes them – a renaming unit exposes the renamed name. One name is resolved on every unit and chained over the whole group, units[0].<name> >= units[1].<name> >= .... Empty by default.

  • order_status – Whether to order the group’s status Vars (default True). Pass False for a group whose units carry no status Var, or to leave the on/off order free and canonicalize only variables.

Returns:

The len(units) - 1 attached conditional Constraints, one per consecutive pair, in order – empty when order_status is False. Any variables Constraints are reachable on the units as {name}_ordering.

Raises:

FlexConfigError – If fewer than two units are given, if a unit repeats in the list, if order_status is False with no variables (the call would order nothing), if a variable name does not resolve to a Var on every unit or resolves to differently-indexed Vars across the group, or – on the default path only, raised by add_conditional – if a unit lacks a status Var.

Spec records

Every helper above except relax and unrelax records the spec element that rebuilds it: unit-level helpers on the unit, cross-unit helpers on the model. emit_model writes those records back. A helper called inside another (register_parallel_group’s conditionals, BatteryModel’s own status) runs under suppress_logic_records(), so only the outer call is written.

class flexops.logic._records.LogicRecord(kind: str, owner: Any, fields: dict)

One logic-helper call, as the fields of the spec element that rebuilds it.

kind

The spec element kind.

Type:

str

owner

The unit (unit-level kinds) or the model (cross-unit kinds).

Type:

Any

fields

The element’s fields as JSON data: variable paths relative to the unit, units as full component names.

Type:

dict

flexops.logic._records.record(owner, kind: str, **fields) → None

Append a LogicRecord to owner._flex_logic unless suppressed.

Parameters:
  • owner – The unit or model the record belongs on.

  • kind – The spec element kind.

  • **fields – The element’s fields, already JSON data.

flexops.logic._records.suppress_logic_records()

Stop logic helpers recording while the block runs (for internal calls).