gtopt::line_losses namespace

Classes

struct AdaptiveSegmentsOpts
struct BlockResult
LP indices produced by add_block() for one block.
struct DynamicAssignment
struct DynamicLayoutOpts
struct LossConfig
Resolved loss parameters for LP construction.
struct SegGeom
struct TangentGeom

Functions

auto add_block(const LossConfig& config, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, LinearProblem& lp, SparseRow& brow_a, SparseRow& brow_b, double block_tmax_ab, double block_tmax_ba, double block_tcost, std::optional<ColIndex> capacity_col, Uid uid, bool enforce_capacity = true) -> BlockResult
Add loss model variables and constraints for one block.
auto compute_adaptive_loss_segments(std::span<const double> resistances, std::span<const double> peak_flows, const AdaptiveSegmentsOpts& opts = {}) -> std::vector<int>
auto compute_dynamic_loss_layout(std::span<const double> resistances, std::span<const double> peak_flows, const DynamicLayoutOpts& opts = {}) -> std::vector<DynamicAssignment>
auto limit_terms(const LossConfig& config, const BlockResult& result, bool forward) -> std::vector<std::pair<ColIndex, double>>
auto loss_segment_geometry(double envelope, int nseg, int k, LinePwlLayout layout = LinePwlLayout::uniform) -> SegGeom noexcept
auto loss_tangent_geometry(double envelope, int nseg, int k, LinePwlLayout layout = LinePwlLayout::tangent) -> TangentGeom noexcept
auto make_config(LineLossesMode mode, const Line& line, LossAllocationMode allocation, double lossfactor, double resistance, double voltage, int loss_segments, double fmax, double loss_row_scale = 1.0, double loss_envelope = 0.0, double loss_cost_eps = 0.0, int nseg_secant = 1, bool use_sos2 = false, double loss_overflow_cost = 0.0, double loss_flow_abs_cost = 0.0) -> LossConfig
Build a LossConfig for the given line and stage parameters.
auto resolve_mode(const Line& line, const PlanningOptionsLP& options, bool has_expansion) -> LineLossesMode
Resolve the effective LineLossesMode for a line.
auto thermal_loss_share(const LossConfig& config) -> double noexcept

Function documentation

BlockResult gtopt::line_losses::add_block(const LossConfig& config, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, LinearProblem& lp, SparseRow& brow_a, SparseRow& brow_b, double block_tmax_ab, double block_tmax_ba, double block_tcost, std::optional<ColIndex> capacity_col, Uid uid, bool enforce_capacity = true)

Add loss model variables and constraints for one block.

Returns LP indices for the created variables and constraints.

Dispatches to the appropriate mode implementation:

  • none: single bidirectional flow, no loss
  • linear: directional flows with loss coefficients
  • piecewise: shared segments for |f| = fp + fn [1]
  • bidirectional: independent segments per direction [3]
  • piecewise_direct: PLP-faithful, per-segment bus stamps, no loss var/row (requires no capacity column)

std::vector<int> gtopt::line_losses::compute_adaptive_loss_segments(std::span<const double> resistances, std::span<const double> peak_flows, const AdaptiveSegmentsOpts& opts = {})

Parameters
resistances R_i for each line (any unit, must match peak_flows)
peak_flows f_max,i for each line (any unit, must match)
opts budget + floor + ceiling
Returns K_i for each line (length == resistances.size())

Allocate per-line PWL segment counts using the KKT cube-root rule.

Given parallel resistances and peak_flows for N lines and a worst-case error budget err_pct, returns a length-N vector of segment counts K_i minimising the total LP cost Σ K_i subject to

Σ_i L_max,i / (4 K_i²)  ≤  err_pct · Σ_i L_max,i,
    L_max,i  =  R_i · f_max,i²,        floor ≤ K_i ≤ ceiling.

The KKT-optimal allocation is K_i ∝ L_max,i^(1/3); concretely

S  = Σ_i L_max,i^(1/3)
B  = err_pct · Σ_i L_max,i
c  = √(S / (4·B))
K_i = clamp(⌈c · L_max,i^(1/3)⌉, floor, ceiling)

Lossless lines (R_i ≤ 0 OR f_max,i ≤ 0) get K_i = 0 so the caller's PWL builder can omit them entirely.

Empirically on a national-grid-sized system (281 lossy lines, L spans 5 orders of magnitude), this Pareto-dominates uniform-K=4 on every axis at err_pct ≥ 0.02: 39 % fewer LP variables, $1.73 M lower LP cost (tighter PWL upper bound), and comparable CPLEX time — because uniform K wastes segments on small lines whose true loss is already negligible.

When opts.err_pct ≤ 0 returns opts.ceiling for every lossy line (uniform-K fallback).

std::vector<DynamicAssignment> gtopt::line_losses::compute_dynamic_loss_layout(std::span<const double> resistances, std::span<const double> peak_flows, const DynamicLayoutOpts& opts = {})

Parameters
resistances R_i for each line (any unit, must match peak_flows)
peak_flows f_max,i for each line (any unit, must match)
opts budget + floor + ceiling
Returns per-line (K_i, layout_i) (length == size())

Allocate per-line (K, layout) jointly under the same err_pct budget that drives the adaptive K rule.

Phase 1 — K allocation (identical to compute_adaptive_loss_segments): cube-root rule K_i ∝ L_max,i^(1/3) clamped to [floor, ceiling], bounding the worst-case PWL secant error Σ L_max,i / (4 K_i²) ≤ err_pct · Σ L_max,i.

Phase 2 — layout selection: start every line at uniform (presolve eliminates the loss column → fastest LP). Compute the system-wide signed mean error

E_sys  =  Σ_uniform L_max,i / (6 K_i²)
          − Σ_midpoint L_max,i / (12 K_i²)

(uniform overstates by +L/(6K²); midpoint understates by −L/(12K²)). If E_sys ≤ err_pct · Σ L_max,i ⇒ keep all uniform; done. Otherwise greedily flip the line with the largest mean-error contribution (L_i / K_i², highest first) to midpoint. Each flip reduces E_sys by L_i / (4 K_i²) (= the worst-case error of that line). Stop when either:

  1. |E_sys| ≤ err_pct · Σ L_max,i (budget met), OR
  2. the next flip would move E_sys further from zero than its current value (greedy local optimum reached — typically when a single heavy line's contribution exceeds the budget on its own).

The latter stop condition prevents overshoot into the negative budget zone: without it, the greedy would happily keep flipping past E_sys = 0 and land at -|E_sys| of the same magnitude.

When opts.err_pct ≤ 0 returns {K = ceiling, layout = uniform} for every lossy line (uniform-K fallback; no layout decision needed).

std::vector<std::pair<ColIndex, double>> gtopt::line_losses::limit_terms(const LossConfig& config, const BlockResult& result, bool forward)

Linear terms Σ coef·col of the loaded quantity f_dir + a·ℓ_dir of one direction (forward = A→B) for the columns add_block produced, with a = thermal_loss_share(config):

  • directional flow + loss columns: {(f, 1), (ℓ, a)} (ℓ the shared loss column for the tangent layout);
  • tangent_signed_flow: {(f, ±1), (ℓ, a)};
  • piecewise_direct: {(seg_k, 1 + a·lf_k)};
  • linear: {(f, 1 + a·λ)}. Loss terms are omitted when a = 0, so the flow mode yields the bare flow. Empty when the direction has no flow column (e.g. tmax_dir = 0). Used by the soft-cap (overload) band rows.

SegGeom gtopt::line_losses::loss_segment_geometry(double envelope, int nseg, int k, LinePwlLayout layout = LinePwlLayout::uniform) noexcept

Compute the per-segment (width, slope) for the static PWL approximation of the line-loss curve. layout = uniform (the default and currently the only mode with a meaningful per-segment distribution — equal_error aliases to it for convex quadratic; tangent uses a structurally different LP, not this function) gives equal-width chords:

width_k = envelope / K slope_k = (envelope / K) × (2k − 1) ← chord (a + b)

so the loss-row coefficient on seg_k is loss_k = slope_k × R / V². Caller (add_segments) must pass the FULL envelope (effective_fmax = tmax when enforce_level ≥ 1, 2·tmax when enforce_level = 0); passing seg_width = envelope/K by mistake makes every slope shrink by 1/K and the LP underestimate loss accordingly. Exposed via this public header so unit tests can pin the formula.

TangentGeom gtopt::line_losses::loss_tangent_geometry(double envelope, int nseg, int k, LinePwlLayout layout = LinePwlLayout::tangent) noexcept

Compute the k-th tangent's geometry for the outer-approximation PWL loss model. Tangent touch points are uniform partition midpoints on [0, envelope]:

t_k = envelope · (2k − 1) / (2K)

giving a max chord-error of (envelope/(2K))² at partition boundaries — same magnitude as the secant overestimate (uniform mode) but BELOW the curve (LP underestimates loss). k is 1-based; layout accepted only as tangent (other layouts return {0, 0, 0} since this geometry is meaningless for them).

LossConfig gtopt::line_losses::make_config(LineLossesMode mode, const Line& line, LossAllocationMode allocation, double lossfactor, double resistance, double voltage, int loss_segments, double fmax, double loss_row_scale = 1.0, double loss_envelope = 0.0, double loss_cost_eps = 0.0, int nseg_secant = 1, bool use_sos2 = false, double loss_overflow_cost = 0.0, double loss_flow_abs_cost = 0.0)

Build a LossConfig for the given line and stage parameters.

Combines mode resolution with physical parameter extraction. For linear mode, auto-computes lossfactor from R/V if needed: λ = R · f_max / V² (linearization at rated flow [2]).

For PWL modes, validates that R > 0 and V > 0 and nseg > 1; falls back to linear or none if insufficient.

LineLossesMode gtopt::line_losses::resolve_mode(const Line& line, const PlanningOptionsLP& options, bool has_expansion)

Resolve the effective LineLossesMode for a line.

Parameters
line The line data (per-element overrides)
options Global planning options
has_expansion Whether the line has capacity expansion (expcap)

Fallback chain:

  1. Per-line line_losses_mode (string → enum)
  2. Per-line use_line_losses (deprecated bool: false → none)
  3. Global line_losses_mode() from PlanningOptionsLP

If the resolved mode is adaptive, it is mapped to:

  • bidirectional if the line has expansion modules (has_expansion)
  • piecewise otherwise (smallest-LP shared-segment model)

If the resolved mode is dynamic, it falls back to piecewise (with a log warning on first call).

If the resolved mode is piecewise_direct and the line has expansion (has_expansion), it falls back to piecewise with a one-shot warning — the direct model bakes the per-segment bound tmax/K into variable bounds and cannot be linked to a capacity column.

double gtopt::line_losses::thermal_loss_share(const LossConfig& config) noexcept

Share a of a direction's loss counted against its thermal limit (f_dir + a·ℓ_dir): full → 1; sending → the loss share booked at the sending bus (receiver 0, split ½, sender 1; tangent_signed_flow always ½); flow and none mode → 0.