PlanningLP class
#include <gtopt/planning_lp.hpp>
Linear programming model for power system planning.
Encapsulates a linear programming formulation of a power system planning problem, including system configurations, simulation scenarios, and solver options.
Public types
- struct SddpSummary
- Summary of the last SDDP solve (populated by the SDDP solver).
- using phase_ap_systems_t = StrongIndexVector<PhaseIndex, std::optional<SystemLP>>
- using phase_systems_t = StrongIndexVector<PhaseIndex, SystemLP>
-
using scene_phase_ap_t = StrongIndexVector<SceneIndex, phase_
ap_ systems_ t> -
using scene_phase_systems_t = StrongIndexVector<SceneIndex, phase_
systems_ t>
Public static functions
- static void auto_scale_lng_terminals(Planning& planning, double solver_infinity)
- static void auto_scale_loss_link(Planning& planning)
- static auto effective_tiny_reactance_threshold(const Planning& planning) -> double
- static auto inheritable_flat_options(LpMatrixOptions opts) -> LpMatrixOptions
- static auto log_battery_annual_standing_loss_default(const Planning& planning) -> std::size_t
- static auto median_line_reactance_pu(const Planning& planning) -> std::optional<double>
- static void renormalize_scenario_probabilities(Planning& planning)
- static void validate_line_reactance(Planning& planning)
- static void validate_line_resistance(Planning& planning)
- static void validate_line_transmission(Planning& planning)
- static void validate_power_bounds(Planning& planning)
- static void write_out_cell(SystemLP& system)
- Emit output for a single (scene, phase) cell.
Constructors, destructors, conversion operators
- PlanningLP(const PlanningLP&) deleted
- PlanningLP(PlanningLP&&) deleted
-
template<typename PlanningT>PlanningLP(PlanningT&& planning, const LpMatrixOptions& flat_opts = {}, std::shared_ptr<ArrowIndexCache> shared_index_cache = {}) explicit
- Constructs a PlanningLP instance from planning data.
- ~PlanningLP() noexcept
Public functions
- auto aperture_system(SceneIndex scene_index, PhaseIndex phase_index) -> SystemLP* noexcept
- void build_all_lps_eagerly()
- Eagerly build every (scene, phase) LP matrix in parallel.
- void drop_sim_snapshots() noexcept
- Discard every cell's compressed flat-LP snapshot, keeping only the Phase-2a cache (col_sol / col_cost / row_dual + cached scalars) on each
LinearInterface. - auto flat_options() const -> const LpMatrixOptions& noexcept
- The explicit
LpMatrixOptionsthis PlanningLP was built with. - void log_lp_memory_breakdown(std::string_view label) const
- Diagnostic: log the resident-memory breakdown across all cells.
- auto operator=(const PlanningLP&) -> PlanningLP& deleted
- auto operator=(PlanningLP&&) -> PlanningLP& deleted
- auto options() const -> const PlanningOptionsLP& noexcept
- Gets the LP options configuration.
- auto output_delegate() const -> const PlanningLP* noexcept
- Accessor for an installed output delegate.
- auto planning() const -> const Planning& noexcept
- Gets the underlying planning data.
- void release_cells()
- Release the per-(scene, phase) LP cells and their solver backends, freeing the bulk of this object's memory.
- auto resolve(const SolverOptions& lp_opts = {}) -> std::expected<int, Error>
- Solves the linear programming problem.
- auto sddp_summary() const -> const SddpSummary& noexcept
- Read the SDDP summary (populated after a successful SDDP solve).
- void set_output_delegate(std::unique_ptr<PlanningLP> delegate) noexcept
- Install a surrogate PlanningLP whose systems provide the solution data for
write_out(). - void set_output_directory(std::string dir)
- Redirect all subsequent output (per-cell sim-pass emission,
write_out()) todir. - void set_sddp_summary(SddpSummary summary) noexcept
- Populate the SDDP summary (called by the SDDP solver).
-
template<typename Self>auto simulation(this Self&& self) -> auto&& noexcept
- Gets the simulation LP model (const or non-const via deducing this).
-
template<typename Self>auto system(this Self&& self, SceneIndex scene_index, PhaseIndex phase_index) -> auto&& noexcept
-
template<typename Self>auto systems(this Self&& self) -> auto&& noexcept
- Gets the system LP representations.
-
auto write_lp(const std::string& filename,
LpFileFormat format = LpFileFormat::
lp, LpFormatFallback fallback = LpFormatFallback:: strict) const -> bool - Writes the LP formulation to file.
- void write_out()
- Writes solution output (implementation-defined destination).
Typedef documentation
using gtopt:: PlanningLP:: phase_ap_systems_t = StrongIndexVector<PhaseIndex, std::optional<SystemLP>>
Sparse store for the SDDP backward-pass aperture systems: a cell is empty unless an aperture_system_file resolves for that phase. Each present cell is a SystemLP built with SystemKind::aperture from the (path-cached) reduced system, sharing the same SimulationLP.
Function documentation
static void gtopt:: PlanningLP:: auto_scale_lng_terminals(Planning& planning,
double solver_infinity)
Compute adaptive energy scales for LNG terminals from emax. Same solver_infinity semantics as auto_scale_reservoirs. Static so unit tests can exercise it without standing up a full PlanningLP.
static void gtopt:: PlanningLP:: auto_scale_loss_link(Planning& planning)
Compute adaptive scale_loss_link from median(R/V²) when not explicitly set. Picks a power-of-10 multiplier s = 10^round( −log10(median(R/V²))) so the smallest segment coefficient loss_1 = seg_width · R / V² is lifted into the O(seg_width · 1) range in the loss-link row. Mutates planning.options.model_options.scale_loss_link in-place.
Static so unit tests can exercise it without standing up a full PlanningLP, mirroring validate_line_reactance.
static double gtopt:: PlanningLP:: effective_tiny_reactance_threshold(const Planning& planning)
Effective zero-impedance floor on |X/V²|: max(dc_line_reactance_threshold, tiny_reactance_rel_threshold × median_line_reactance_pu). validate_line_reactance writes it back into model_options.dc_line_reactance_threshold so every later consumer (KVL assemblers, island detection, auto_scale_theta) classifies lines against the same floor.
static LpMatrixOptions gtopt:: PlanningLP:: inheritable_flat_options(LpMatrixOptions opts)
Strip the per-instance build carriers from opts (see flat_options()).
static std::size_t gtopt:: PlanningLP:: log_battery_annual_standing_loss_default(const Planning& planning)
Count the batteries whose annual_standing_loss is unset (and therefore get the planning-wide self-discharge default PlanningOptionsLP::battery_annual_standing_loss(), 0.48 p.u./year = 4 %/month unless model_options.battery_annual_standing_loss overrides it) and log the count once at INFO. Read-only: the default itself is applied inside BatteryLP via StorageOptions::default_annual_standing_loss so every construction path (PlanningLP, bare SystemLP) agrees. Returns the count. Static so unit tests can exercise it.
static std::optional<double> gtopt:: PlanningLP:: median_line_reactance_pu(const Planning& planning)
Median of the per-unit reactance |X/V²| over every line with a nonzero reactance (scalar or first nonzero vector entry; file-backed schedules are skipped). std::nullopt when no line qualifies.
static void gtopt:: PlanningLP:: renormalize_scenario_probabilities(Planning& planning)
Renormalise Scenario::probability_factor so that the sum over scenarios contained in active scenes (and themselves active) equals 1.0. Implements the long-standing contract documented on Scenario itself ("when probability_factor
values across all scenarios do not sum to 1, the solver
normalises them internally").
Called from the PlanningLP constructor's auto_scale_* block, before any LP cost coefficient is computed via CostHelper::block_ecost. Mutates planning.simulation.scenario_array in-place: only the scenarios that are part of the active subproblem (active flag AND parent scene active) are rescaled. Scenarios in inactive scenes keep their original (unused) probability_factor.
Idempotent: a second call after the first leaves total probability at 1.0 and is a no-op. Skipped silently when the total mass is already within 1e-12 of 1.0. Logs INFO when a non-trivial rescale happens; WARN when every active scenario has zero / missing probability_factor (degenerate input).
Static so unit tests can exercise it without standing up a full PlanningLP — mirrors auto_scale_*.
static void gtopt:: PlanningLP:: validate_line_reactance(Planning& planning)
Validate zero / tiny line reactances (tiny_reactance_mode).
Flags every line whose reactance is 0 or whose per-unit susceptance term |x_pu| = |X/V²| falls below the effective floor effective_tiny_reactance_threshold = max( model_options.dc_line_reactance_threshold (default 1e-6), tiny_reactance_rel_threshold (default 0.01) × median |X/V²|), written back into dc_line_reactance_threshold. Tie lines lose their resistance / lossfactor unless tie_line_losses = true. The check is dimensionally correct (susceptance, not raw X) so it handles per-unit and physical-unit (kV / Ω) inputs and catches V-vs-kV unit-typo lines that a raw-|X| cutoff misses.
tiny_reactance_mode = tie(default): the value is kept and the KVL assemblers emit a zero-impedance tie (−θ_a + θ_b = −φ, no flow term), warning once per line (aggregated past 20) that the two bus angles are forced equal. A tie between buses whosereference_thetapins it cannot satisfy falls back to a DC link (reactance reset) with a warning.tiny_reactance_mode = dc(legacy): sub-threshold reactances are rewritten to0.0;X = 0lines are DC links (no KVL row).
Lines without reactance (HVDC, PLP DC lines) are DC links in both modes and are not touched. Static so it can be exercised by unit tests without standing up a full PlanningLP.
static void gtopt:: PlanningLP:: validate_line_resistance(Planning& planning)
Validate line resistance values and clamp tiny ones to zero.
Promotes any line whose per-unit loss term |r_pu| = |R/V²| falls below model_options.dc_line_resistance_threshold (default 1e-6) to a lossless line by rewriting its resistance schedule to scalar 0.0. The loss assembler in line_losses then takes its R ≤ 0 → lossless path and omits the loss-PWL (both the loss-pricing AND the line_loss*_link rows).
The line loss-link coefficient is ∝ 1/(R/V²), so a very-low-R line injects the matrix's largest coefficient (e.g. 64102 for R/V² = 5e-8) for a negligible physical loss. The dimensionally-correct check is |R/V²| (X is irrelevant — the R·X product would miss low-R/normal-X lines), mirroring validate_line_reactance on |X/V²|. Catches data V-vs-kV typos, lossless connectors (R = 0), and transformer/busbar segments whose copper loss is below solver tolerance.
Set model_options.dc_line_resistance_threshold = 0 to disable. Static so it can be exercised by unit tests without a full PlanningLP.
static void gtopt:: PlanningLP:: validate_line_transmission(Planning& planning)
Validate line transmission bounds and clamp tiny ones to zero.
Rewrites any Line::tmax_ab / Line::tmax_ba whose raw MW value is nonzero but below 1e-4 MW to scalar 0.0 (same scalar / 2-D-vector / FileSched handling as validate_power_bounds). Making the degenerate transfer limit exactly zero lets the LP-assembly zero-row/column skip eliminate the dead flow column / capacity row cleanly.
Static so it can be exercised by unit tests without standing up a full PlanningLP.
static void gtopt:: PlanningLP:: validate_power_bounds(Planning& planning)
Validate generator power bounds and clamp tiny ones to zero.
Rewrites any Generator::pmax / Generator::pmin whose raw MW value is nonzero but below 1e-4 MW to scalar 0.0 (clamping offending entries inside 2-D vector schedules in place; FileSched schedules are skipped — they can't be validated statically). Making such a degenerate bound exactly zero lets the LP-assembly zero-column skip eliminate the dead generation column cleanly.
Unlike validate_line_reactance / validate_line_resistance the MW threshold is a fixed compile-time constant (no voltage to divide by, no model_options knob). Static so it can be exercised by unit tests without standing up a full PlanningLP.
static void gtopt:: PlanningLP:: write_out_cell(SystemLP& system)
Emit output for a single (scene, phase) cell.
Contains the fast-path dispatch logic that was previously the emit_cell lambda inside write_out():
- output_skipped → no-op A. output_written → drop snapshot, no re-write B. low_memory != off + backend released + optimal → write from cached solution vectors without re-solve generic → ensure_lp_built, write_out, release_backend
Exposed as a public static method so unit tests can verify each fast path in isolation without constructing a full PlanningLP grid.
gtopt:: PlanningLP:: PlanningLP(const PlanningLP&) deleted
Out-of-line to allow std::unique_ptr<PlanningLP> as a member of PlanningLP itself — requires the type to be complete at the definition point of every special member, which is the .cpp.
template<typename PlanningT>
gtopt:: PlanningLP:: PlanningLP(PlanningT&& planning,
const LpMatrixOptions& flat_opts = {},
std::shared_ptr<ArrowIndexCache> shared_index_cache = {}) explicit
Constructs a PlanningLP instance from planning data.
| Parameters | |
|---|---|
| planning | The power system planning data |
| flat_opts | Configuration options (default empty) |
| shared_index_cache | Optional Arrow input-index cache shared with other builds of the same inputs; a fresh one is created by SimulationLP when empty |
SystemLP* gtopt:: PlanningLP:: aperture_system(SceneIndex scene_index,
PhaseIndex phase_index) noexcept
The aperture (backward-pass) system for a cell, or nullptr when this cell has no aperture system — in which case the backward pass falls back to the regular forward system(scene, phase).
void gtopt:: PlanningLP:: build_all_lps_eagerly()
Eagerly build every (scene, phase) LP matrix in parallel.
Under LowMemoryMode::compress this reconstructs each cell from its snapshot. Under off it is a no-op (every backend is already live from construction).
Intended use: the --lp-only CLI path validates that the whole planning horizon can be built, and optionally dumps every cell via --lp-file, without ever running the SDDP iterations. Completely independent of any SDDPMethod instance.
void gtopt:: PlanningLP:: drop_sim_snapshots() noexcept
Discard every cell's compressed flat-LP snapshot, keeping only the Phase-2a cache (col_sol / col_cost / row_dual + cached scalars) on each LinearInterface.
Called at the end of SDDPMethod::simulation_pass, after Pass 1's retry loop has converged and no further backend reconstruct is possible. PlanningLP::write_out reads solution values from the cache and rebuilds XLP col indices via a flatten of the live System element arrays — it does NOT need the snapshot. Dropping the snapshot here frees tens of MB of compressed LP matrix per cell (hundreds of MB per scene × N scenes), which on CEN-scale runs is a meaningful chunk of RAM headroom for the parallel write_out pool.
No-op under low_memory = off (no snapshot is installed in that mode). Safe to call multiple times (idempotent).
const LpMatrixOptions& gtopt:: PlanningLP:: flat_options() const noexcept
The explicit LpMatrixOptions this PlanningLP was built with.
The caller's options (solver, eps, LP names for lp_file / lp_debug / lp_error, compute_stats, equilibration, …) minus the per-instance build carriers (name_store, dedup_registry, the flatten_*_uid cell tags), which each PlanningLP sets up itself. Cascade levels that rebuild their LP inherit these, so a level does not silently fall back to LpMatrixOptions{}.
void gtopt:: PlanningLP:: log_lp_memory_breakdown(std::string_view label) const
Diagnostic: log the resident-memory breakdown across all cells.
| Parameters | |
|---|---|
| label | short context tag (e.g. "post-build", "post-forward"). |
Read-only. Sums the per-cell LP retainers — compressed flat-LP snapshots, cached solution vectors, accumulated cuts — and counts how many cells currently hold their XLP collection wrappers (SystemLP::collections_resident()), printed alongside the live process RSS. Lets us attribute the resident floor (compressed LP vs cache vs collection wrappers) without guessing. Only invoked when the env var GTOPT_LOG_LP_MEMORY is set, so normal runs are unaffected.
const PlanningOptionsLP& gtopt:: PlanningLP:: options() const noexcept
Gets the LP options configuration.
| Returns | Const reference to PlanningOptionsLP |
|---|
const PlanningLP* gtopt:: PlanningLP:: output_delegate() const noexcept
Accessor for an installed output delegate.
Returns the raw pointer (non-owning) to the LP whose systems are forwarded to by write_out() and by the post-solve aggregation helpers in gtopt_lp_runner.cpp (the solver-stats summary needs to walk the delegate's grid when this instance was cleared by the cascade level transition). Returns nullptr when no delegate has been installed (the common monolithic / non-cascade case).
void gtopt:: PlanningLP:: release_cells()
Release the per-(scene, phase) LP cells and their solver backends, freeing the bulk of this object's memory.
After this call systems() returns an empty container: write_out(), resolve(), and aggregate_solver_stats() become no-ops on this instance. The Planning, PlanningOptionsLP, and SimulationLP members remain intact so the shell can still be queried for configuration or used as input to a fresh PlanningLP built from planning().
Intended for multi-level cascade solvers that reused the caller's LP at an early level and want to drop its memory before the next level allocates its own grid of LP matrices.
std::expected<int, Error> gtopt:: PlanningLP:: resolve(const SolverOptions& lp_opts = {})
Solves the linear programming problem.
| Parameters | |
|---|---|
| lp_opts | Solver options (default empty) |
| Returns | Expected with solution status or error message |
void gtopt:: PlanningLP:: set_output_delegate(std::unique_ptr<PlanningLP> delegate) noexcept
Install a surrogate PlanningLP whose systems provide the solution data for write_out().
Intended for the cascade solver: the final-level LP lives in the CascadePlanningMethod owned-LPs vector, which is destroyed when PlanningLP::resolve() returns. Before returning, the cascade transfers ownership of the final level's LP here so that its populated systems remain reachable for output writing.
The delegate is destroyed when this PlanningLP is destroyed (the destructor is defined out-of-line so the incomplete-type unique_ptr<PlanningLP> member compiles cleanly).
void gtopt:: PlanningLP:: set_output_directory(std::string dir)
Redirect all subsequent output (per-cell sim-pass emission, write_out()) to dir.
The systems read output_directory() through a reference to this object at write time, so the change takes effect immediately. Used by the cascade method (cascade_options.write_level_outputs) to give each intermediate level its own output subdirectory. Must not be called while a solve or write-out is in flight.
template<typename Self>
auto&& gtopt:: PlanningLP:: simulation(this Self&& self) noexcept
Gets the simulation LP model (const or non-const via deducing this).
| Returns | Reference to SimulationLP |
|---|
template<typename Self>
auto&& gtopt:: PlanningLP:: systems(this Self&& self) noexcept
Gets the system LP representations.
| Returns | Const reference to vector of SystemLP |
|---|
bool gtopt:: PlanningLP:: write_lp(const std::string& filename,
LpFileFormat format = LpFileFormat:: lp,
LpFormatFallback fallback = LpFormatFallback:: strict) const
Writes the LP formulation to file.
| Parameters | |
|---|---|
| filename | Output file path; a trailing .lp / .mps is stripped (a .mps extension selects MPS regardless of format) |
| format | Requested format (default LP) |
| fallback | strict (default): fail when the backend cannot write format; other_format: write the other format. |
| Returns | false (after logging an error) when the file could not be written |
void gtopt:: PlanningLP:: write_out()
Writes solution output (implementation-defined destination).
When a write-out delegate has been installed via set_output_delegate() (used by the cascade solver to hand back the final level's LP), this call is forwarded to the delegate and writes the delegate's systems, not this instance's. Without the delegate, the cascade's mid-loop release_cells() would leave the caller PlanningLP with an empty system grid and the final level's LP would die unused.