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 linkingoutput_varto 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] == 0when the unit is off (status[t] == 0) andmin_output <= output_var[t] <= max_outputwhen it is on. The status binary is tracked sorelax/unrelaxcover it. Call at most once per unit (v0 uses the fixed component namesstatus/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
statusVar.
- flexops.logic.status.relax(unit: Any) None¶
Switch every logic-attached Binary on
unittopyo.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.
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 trailingmin_uptimesteps forces the unit on att.min_downtime[t]: the mirror,sum(shutdown[i] for i in window) <= 1 - status_var[t], window sized bymin_downtime.
At the defaults (
min_uptime=1, min_downtime=1) each window is the single point{t}, so these reduce exactly to the tightening boundsstartup[t] <= status_var[t]andshutdown[t] <= 1 - status_var[t]. Summing those two impliesstartup[t] + shutdown[t] <= 1directly (even under a continuous relaxation ofstartup/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 = 0is left unconstrained in v0: there is no initial-status Param to reference a transition into the horizon’s first point.startup/shutdownare continuous on[0, 1], not Binary: oncestatus_varis integral,transition[t]together with themin_uptime[t]/min_downtime[t]rows (whose windows always containt) admit exactly one solution,startup[t] = max(0, delta)andshutdown[t] = max(0, -delta)fordelta = status_var[t] - status_var[t-1]. Declaring them Binary would only add branching candidates. They are therefore not tracked forrelax/unrelax.- Parameters:
unit – The unit block to attach the transition structure to.
status_var – The unit’s time-indexed on/off
statusBinary (fromadd_status()).min_uptime – Minimum number of steps the unit must stay on after a startup. Must be
>= 1;1means 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 wheneverstatus_varis), each indexed overt >= 1.- Raises:
FlexConfigError – If
min_uptimeormin_downtimeis< 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 byk.unitmay be on attonly ifupstreamwas on continuously across the trailing window[t - k, t]– one condition that covers both thek-step delay and “upstream off implies downstream off”. Disaggregated over each lag in that window (unit.status[t] <= upstream.status[t - lag]for everylagin0..k) rather than an aggregate sum, because it is tighter under the LP relaxation used byrelax().- Parameters:
unit – The downstream unit block; must already carry a
statusVar (viaadd_status()).upstream – The upstream unit block whose
statusVar gatesunit.k – Number of steps the downstream start is delayed behind the upstream.
initially_on – How to handle a window that reaches before
t = 0. IfTrue(default), the window clamps to[max(t - k, 0), t]– a unit already running att = 0counts as warmed up, the right convention for a standalone horizon. IfFalse, the window is only checked fort >= kandunit.status[t] == 0is forced fort < kinstead – the right convention for a rolling-horizon window with no assumed prior state.
Registers
unit’sstatusVar as rolling-horizon state (trailingksteps) viaflexops.logic.status._register_rolling_state– consuming that registry is the rolling-horizon scheduler’s job, not built here.- Returns:
The attached
startup_delayConstraint.- Raises:
FlexConfigError – If
upstreamhas nostatusVar.
- 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 fromvar.parent_block()(the blockvaris already attached to).- Parameters:
var – A continuous, time-indexed
Varto 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}_dwellConstraint, indexed over everytthat is not a block boundary.Noneifk == 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 tovar[t]via a defining constraint<name>_def) and, for each direction requested, a Constraint bounding how much<name>may change betweentandt - 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 < windowis skipped: the horizon carries no pre-horizon history to ramp against (mirroringadd_startup_shutdown’s untiedt = 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, overwindowsteps.Noneto leave increases unconstrained.ramp_down – Maximum allowed decrease, in
ramp_rate_units, overwindowsteps.Noneto leave decreases unconstrained.ramp_rate_units – Pyomo unit expression (e.g.
pyunits.kW / pyunits.hr) thatramp_up/ramp_downare 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 isNone.- Raises:
FlexConfigError – If
window < 1; if bothramp_upandramp_downareNone; if either is negative; or if either is given withoutramp_rate_units.
Degradation penalty¶
- flexops.logic.degradation.add_degradation(unit, spec: DegradationSpec, *, costing=None) tuple[Var, Var]¶
Attach the degradation penalty
spectounit, billed throughcosting.- 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}", orNone.
- Returns:
the
<name>_rate[t]wear-cost rate Var (1/hr, in the model currency) and the<name>_totalhorizon wear-cost Var.- Return type:
(rate, total)- Raises:
FlexConfigError – If
unitalready has a penalty namedspec.name, a term names a variable that is not onunitor not indexed by time alone, orcostinghas already runcost_process().
Warning
The hinge Vars equal the wear only when a price or budget pushes them down; without
costingorhorizon_budget, or while wear is belowcovered_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 thetreated_flow[t]it defines.Adds:
bypass_flow[t]– Var, same units asflow_var, bounded[0, bypass_max].treated_flow[t]– Var, same units asflow_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
Varbeing (partially) bypassed.bypass_max – Upper bound on
bypass_flow[t], a units-carrying quantity matchingflow_var.
- Returns:
The attached
treated_flowVar.
- 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
statusVar. The constraint is attached to this unit asconditional.y_unit – The “then” unit; must carry a
statusVar.then –
"on"or"off", the implied state ofy_unitwhenx_unitis on.
- Returns:
The attached
conditionalConstraint (onx_unit).- Raises:
FlexConfigError – If
thenis not"on"/"off", or either unit lacks astatusVar.
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.
unitsis 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. Passorder_status=Falseto skip this and order only the namedvariables– the way to register a group whose units carry nostatusVar. Implemented by chainingadd_conditional()over every consecutive pair back to front (add_conditional(units[i + 1], units[i])reads as “units[i + 1]on impliesunits[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 noconditional,units[-1]does.Continuous variables. Each name in
variablesis resolved on every unit and ordered the same way,units[i].<name> >= units[i + 1].<name>, as a Constraint named{name}_orderingattached beside that pair’sconditional. 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
statusVars (default True). Pass False for a group whose units carry nostatusVar, or to leave the on/off order free and canonicalize onlyvariables.
- Returns:
The
len(units) - 1attachedconditionalConstraints, one per consecutive pair, in order – empty whenorder_statusis False. AnyvariablesConstraints 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_statusis False with novariables(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 byadd_conditional– if a unit lacks astatusVar.
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.
- owner¶
The unit (unit-level kinds) or the model (cross-unit kinds).
- Type:
Any
- flexops.logic._records.record(owner, kind: str, **fields) None¶
Append a
LogicRecordtoowner._flex_logicunless 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).