gtopt::SystemLP class

Central coordinator for power system LP formulation.

Manages conversion of System components to LP representations and coordinates:

  • Creation of variables and constraints
  • Time structure management (blocks, stages, scenarios)
  • Grid component interactions
  • Result output

Public types

using collections_t = std::tuple<Collection<BusLP>, Collection<DemandLP>, Collection<GeneratorLP>, Collection<LineLP>, Collection<GeneratorProfileLP>, Collection<DemandProfileLP>, Collection<CapacityProfileLP>, Collection<BatteryLP>, Collection<ThermalNodeLP>, Collection<ThermalStorageLP>, Collection<HydrogenNodeLP>, Collection<HydrogenStorageLP>, Collection<HydrogenDemandLP>, Collection<AmmoniaNodeLP>, Collection<AmmoniaStorageLP>, Collection<CarrierConverterLP>, Collection<AllowancePoolLP>, Collection<ReserveZoneLP>, Collection<ReserveProvisionLP>, Collection<CommitmentLP>, Collection<FuelLP>, Collection<EmissionLP>, Collection<EmissionZoneLP>, Collection<EmissionSourceLP>, Collection<LineCommitmentLP>, Collection<ConverterLP>, Collection<InertiaZoneLP>, Collection<InertiaProvisionLP>, Collection<JunctionLP>, Collection<WaterwayLP>, Collection<FlowLP>, Collection<ReservoirLP>, Collection<ReservoirSeepageLP>, Collection<ReservoirDischargeLimitLP>, Collection<TurbineLP>, Collection<PumpLP>, Collection<ReservoirProductionFactorLP>, Collection<FlowRightLP>, Collection<VolumeRightLP>, Collection<LngTerminalLP>, Collection<GasNodeLP>, Collection<GasSupplyLP>, Collection<GasDemandLP>, Collection<GasPipeLP>, Collection<GasCompressorLP>, Collection<GasTurbineLP>, Collection<DecisionVariableLP>, Collection<PlantLP>, Collection<UserConstraintLP>, Collection<UserModelLP>, Collection<FutureCostLP>>

Public static functions

static auto total_write_cells() -> std::size_t noexcept
static auto total_write_ms() -> double noexcept

Constructors, destructors, conversion operators

SystemLP() deleted
SystemLP(const System& system, SimulationLP& simulation, const LpMatrixOptions& flat_opts = {}) explicit
SystemLP(const System& system, SimulationLP& simulation, PhaseLP phase, SceneLP scene, LpMatrixOptions flat_opts = {}, SystemKind kind = SystemKind::forward) explicit
Construct from System with simulation and options.
SystemLP(const SystemLP&) deleted
SystemLP(SystemLP&& other) noexcept
~SystemLP() defaulted noexcept

Public functions

void accumulate_convergence_indicators(SceneIndex scene_index, PhaseIndex phase_index)
auto agreement_rewards_objective() const -> double
void clear_collections_for_eviction() noexcept
void clear_disposable_collections()
void clear_output_written() noexcept
template<typename Self>
auto collections(this Self&& self) -> auto&& noexcept
auto collections_droppable() const -> bool noexcept
auto collections_resident() const -> bool noexcept
template<typename Element, template<typename> class Id>
auto contains(const Id<Element>& id) const -> bool noexcept
void create_lp(const LpMatrixOptions& flat_opts_in = {})
auto cvar_layout() const -> const std::optional<CvarLayout>& noexcept
auto cvar_solution() const -> const std::optional<CvarSolution>& noexcept
void defer_state_link(StateVariable::Key prev_key, LPKey here_key, ColIndex here_col)
auto disposable_collections_resident() const -> bool noexcept
void drop_for_write_out_done() noexcept
template<typename Element, typename Self, template<typename> class Id>
auto element(this Self&& self, const Id<Element>& id) -> auto&&
Get element by ID.
template<typename Element, template<typename> class Id>
auto element_index(const Id<Element>& id) const -> auto
Get index of element by ID.
template<typename Element, typename Self>
auto elements(this Self&& self) -> auto&&
Get all elements of specific type.
void ensure_lp_built()
auto fingerprint() const -> const LpFingerprint& noexcept
Access the LP fingerprint computed during create_lp().
auto is_backend_released() const -> bool noexcept
template<typename Id Id>
auto is_single_bus(const Id& id) const -> bool
auto kind() const -> SystemKind noexcept
template<typename Self>
auto linear_interface(this Self&& self) -> auto&& noexcept
Access linear interfaces.
auto low_memory_mode() const -> LowMemoryMode noexcept
void merge_solver_stats(const SolverStats& other) noexcept
auto name() const -> NameView noexcept
Get system name.
auto operator=(const SystemLP&) -> SystemLP& deleted noexcept
auto operator=(SystemLP&& other) -> SystemLP& noexcept
auto options() const -> const auto& noexcept
Get system options.
auto output_skipped() const -> bool noexcept
auto output_written() const -> bool noexcept
template<typename Self>
auto pending_state_links(this Self&& self) -> auto&& noexcept
auto phase() const -> const auto& noexcept
auto prev_phase_sys() const -> const SystemLP* noexcept
Get the previous phase's SystemLP (nullptr when not set).
template<typename Element>
auto push_back(Element&& e) -> auto
Add element to appropriate collection.
void rebuild_collections_if_needed()
void reconstruct_backend()
void record_cut_deletion(std::span<const int> deleted_indices)
void record_cut_row(SparseRow row)
void record_dynamic_col(SparseCol col)
void release_backend()
auto resolve(const SolverOptions& solver_options = {}) -> std::expected<int, Error>
Resolves the linear programming problem.
auto scene() const -> const auto& noexcept
void set_drop_collections_on_release(bool enable) noexcept
void set_low_memory(LowMemoryMode mode, CompressionCodec codec = CompressionCodec::zstd)
void set_output_skipped(bool v) noexcept
void set_prev_phase_sys(const SystemLP* prev_sys) noexcept
Set the previous phase's SystemLP (nullptr for phase 0).
auto single_bus_id() const -> const auto& noexcept
auto solver_stats() const -> const SolverStats& noexcept
Forward accessor to the LP's cumulative solver counters.
template<typename Self>
auto system(this Self&& self) -> auto&& noexcept
Access the underlying system.
template<typename Self>
auto system_context(this Self&& self) -> auto&& noexcept
Get system context.
auto update_dynamic_col_bounds(std::string_view class_name, std::string_view variable_name, double new_lowb, double new_uppb) -> bool noexcept
auto update_dynamic_col_bounds(std::string_view class_name, std::string_view variable_name, Uid variable_uid, double new_lowb, double new_uppb) -> bool noexcept
auto update_dynamic_col_lowb(std::string_view class_name, std::string_view variable_name, double new_lowb) -> bool noexcept
auto update_lp() -> int
Update LP elements for all (scenario, stage) pairs in this system.
auto write_lp(const std::string& filename, LpFileFormat format = LpFileFormat::lp, LpFormatFallback fallback = LpFormatFallback::other_format) const -> std::expected<std::string, Error>
Writes the LP problem to a file.
void write_out()
Write output for all linear interfaces.

Typedef documentation

using gtopt::SystemLP::collections_t = std::tuple<Collection<BusLP>, Collection<DemandLP>, Collection<GeneratorLP>, Collection<LineLP>, Collection<GeneratorProfileLP>, Collection<DemandProfileLP>, Collection<CapacityProfileLP>, Collection<BatteryLP>, Collection<ThermalNodeLP>, Collection<ThermalStorageLP>, Collection<HydrogenNodeLP>, Collection<HydrogenStorageLP>, Collection<HydrogenDemandLP>, Collection<AmmoniaNodeLP>, Collection<AmmoniaStorageLP>, Collection<CarrierConverterLP>, Collection<AllowancePoolLP>, Collection<ReserveZoneLP>, Collection<ReserveProvisionLP>, Collection<CommitmentLP>, Collection<FuelLP>, Collection<EmissionLP>, Collection<EmissionZoneLP>, Collection<EmissionSourceLP>, Collection<LineCommitmentLP>, Collection<ConverterLP>, Collection<InertiaZoneLP>, Collection<InertiaProvisionLP>, Collection<JunctionLP>, Collection<WaterwayLP>, Collection<FlowLP>, Collection<ReservoirLP>, Collection<ReservoirSeepageLP>, Collection<ReservoirDischargeLimitLP>, Collection<TurbineLP>, Collection<PumpLP>, Collection<ReservoirProductionFactorLP>, Collection<FlowRightLP>, Collection<VolumeRightLP>, Collection<LngTerminalLP>, Collection<GasNodeLP>, Collection<GasSupplyLP>, Collection<GasDemandLP>, Collection<GasPipeLP>, Collection<GasCompressorLP>, Collection<GasTurbineLP>, Collection<DecisionVariableLP>, Collection<PlantLP>, Collection<UserConstraintLP>, Collection<UserModelLP>, Collection<FutureCostLP>>

Tuple of collections for all LP component types. UserConstraintLP is the last OPERATIONAL collection so user-constraint rows are added after every element whose columns they reference. FutureCostLP follows it — planning-only (no per-(scenario, stage) add_to_lp), built by the separate add_to_planning_lp pass after the stage loop, so it never participates in the operational build order.

Function documentation

static double gtopt::SystemLP::total_write_ms() noexcept

Process-wide write_out instrumentation. These accumulate the per-cell wall time and cell count across every SystemLP::write_out call in the process — used by the runner to print an honest "total per-cell write_out wall" line at the end of the run.

Why this exists: the Write output time X.Xs line in the runner only measures the final PlanningLP::write_out() flush. Under SDDP every cell is written during the forward pass (each iteration's oc.write is dispatched to a thread pool), so by the time the final flush runs there is nothing left to write — the "Write output time" line shows 0.x s for runs that actually wrote gigabytes of parquet, confusingly. This counter restores the real number.

Wall time semantics: this is cumulative per-cell wall, not process wall. Per-cell writes run in parallel under the cell pool, so the wall clock spent in writes is total_write_ms / concurrency. The cumulative number is the useful one to compare against other costs (e.g. cumulative solve time).

gtopt::SystemLP::SystemLP(const System& system, SimulationLP& simulation, PhaseLP phase, SceneLP scene, LpMatrixOptions flat_opts = {}, SystemKind kind = SystemKind::forward) explicit

Construct from System with simulation and options.

Parameters
system The power system to model
simulation Reference to the SimulationLP (scenarios, phases, etc.)
phase Phase LP to associate with this system
scene Scene LP to associate with this system
flat_opts Additional LP build options (default empty)
kind Which system this is: forward (default) or the backward-pass aperture system

gtopt::SystemLP::SystemLP(SystemLP&& other) noexcept

Move constructor: member-wise moves, then re-points the embedded m_system_context_ back-reference to *this (and rebuilds its m_collection_ptrs_ table from this->m_collections_). A defaulted move would leave SystemContext referring to the moved-from SystemLP, which only worked previously because PlanningLP::create_systems happened to never move SystemLP after construction. Required for the parallel phase build path that emplaces SystemLPs into a vector<optional<SystemLP>> and then moves them into the final vector<SystemLP>.

void gtopt::SystemLP::accumulate_convergence_indicators(SceneIndex scene_index, PhaseIndex phase_index)

Parameters
scene_index Scene index this SystemLP belongs to. Currently used only for trace tagging — the SystemLP already owns its scene() / phase() references.
phase_index Phase index this SystemLP belongs to (same).

Walk the live (scenario, stage, block) cells of this (scene, phase) LP and accumulate the four convergence-indicator sums into linear_interface().solver_stats(). Reads slack column values directly from the just-solved backend; must be called after linear_interface().resolve() returned successfully and before release_backend().

Single-writer on the owning thread — the same regime as the SDDP forward-pass solve itself, so no locking is required.

May throw std::runtime_error if elements<X>() is called before rebuild_collections_if_needed() under low_memory != off. The SDDP forward-pass call site guarantees the collections are live (we are inside a li.resolve() success path that just touched them), so the throw is a contract violation rather than an expected failure mode.

double gtopt::SystemLP::agreement_rewards_objective() const

Objective contribution [physical $, the space of linear_interface().get_obj_value()] of the water-rights REWARD terms in the last solution: the sum of FlowRightLP::reward_objective and VolumeRightLP::reward_objective over every (scenario, stage) of this (scene, phase). Always <= 0; 0 when no right carries a positive uvalue. Agreement rewards (e.g. PLP's ValorRiego on delivered irrigation) are valuations, not costs: SDDP reports UB_net = UB − rewards next to the raw UB. Same preconditions as accumulate_convergence_indicators.

void gtopt::SystemLP::clear_collections_for_eviction() noexcept

Memory-limited eviction: drop the ENTIRE collection tuple (disposable AND HasUpdateLP types) while keeping the LinearInterface snapshot + replay intact, so the cell can reconstruct on next touch. Unlike clear_disposable_collections() (keeps HasUpdateLP for update_lp), this reclaims the dominant compress-mode floor — but requires every collection reader, including update_lp(), to call rebuild_collections_if_needed() first (they do). No-op under off or when already empty. See release_backend()'s memory-limited path.

void gtopt::SystemLP::clear_disposable_collections()

Move-assign empty every Collection<X> whose element type does NOT satisfy HasUpdateLP<X>. After add_to_lp/flatten/tighten_scene_phase_links complete, those collections are pure dead weight: their data has already been flattened into the LP snapshot, the only remaining readers (write_out) rehydrate via rebuild_collections_if_needed(), and update_lp does not touch them.

No-op outside LowMemoryMode::compress — under off the collections must stay live for release_backend to be a no-op on the existing live LP.

Collection objects' addresses inside m_collections_ stay valid (the tuple slot doesn't move); only their internal element vectors are emptied. SystemContext::m_collection_ptrs_ therefore keeps pointing at valid (now-empty) Collection objects. Any subsequent elements<X>() call returns an empty range; element<X>(uid) would throw out-of-range — production paths that reach this code after the drop must first call rebuild_collections_if_needed().

void gtopt::SystemLP::clear_output_written() noexcept

Reset the output_written() flag so the next write_out() call re-emits this cell. Intended for the SDDP simulation-pass feasibility-recovery loop: when a later phase fails its solve and installs a feasibility cut on this phase's LP, this phase must be re-solved (yielding new state-variable values) and its output re-written to reflect the new trajectory. File writes overwrite in place (parquet: hive partition + "part"; csv: per-(scene,phase) shard), so clearing the flag is all that is needed.

template<typename Self>
auto&& gtopt::SystemLP::collections(this Self&& self) noexcept

Returns The full collections tuple.

bool gtopt::SystemLP::collections_droppable() const noexcept

True when the disposable collections may be dropped after the build and rebuilt on demand: any low-memory mode, or off when the build opted in via LpMatrixOptions::drop_disposable_collections.

bool gtopt::SystemLP::collections_resident() const noexcept

Diagnostic: are the per-cell XLP collection wrappers currently resident? Under compress they are dropped after construction and rebuilt-and-retained on first update_lp_for_phase — used by the memory-accounting pass to count how many cells hold their ~per-cell collection footprint simultaneously.

const std::optional<CvarLayout>& gtopt::SystemLP::cvar_layout() const noexcept

The mean-CVaR construct of this cell (model_options.risk_measure = cvar), or empty for the expected-cost objective.

const std::optional<CvarSolution>& gtopt::SystemLP::cvar_solution() const noexcept

CVaR values of the solved cell (set by write_out; empty for the expected-cost objective or an unsolved cell).

bool gtopt::SystemLP::disposable_collections_resident() const noexcept

Diagnostic: are the DISPOSABLE (non-HasUpdateLP) collection wrappers resident too? False under compress after construction (clear_disposable_collections()), true after an explicit rebuild_collections_if_needed(). Callers that rehydrate the disposables only for a transient read (the backward aperture step) use it to restore the dropped state afterwards.

void gtopt::SystemLP::drop_for_write_out_done() noexcept

End-of-life drop for a cell whose parquet output is already on disk and which will never see another LP touch (read, mutate, or solve) in the process lifetime. Strictly more aggressive than clear_disposable_collections() + release_backend() + clear_snapshot() because it also drops:

  • The HasUpdateLP collections that clear_disposable_collections() deliberately preserves for subsequent update_lp_for_phase calls (~30 MB / cell on CEN-scale). Those calls will never happen on the write_out path.
  • The cut replay journal in LinearInterface::m_replay_. On recovery hot-starts that loaded tens of thousands of cuts into the journal this is the dominant per-cell residue — several GiB on the 2-year case.
  • The cached primal/dual/reduced-cost vectors in m_cache_. No downstream consumer reads them after write_out.

Must be called after write_out() completes for this cell. The caller (typically PlanningLP::write_out's emit_cell closure) must have already invoked release_backend() and clear_snapshot() — this method only adds drops; it does not duplicate those calls. Idempotent: safe to invoke multiple times. After this returns, the cell still has its scalar metadata (UIDs, options, fingerprint) but any elements<X>() / get_col_sol() access would now read from an empty cache — production paths must avoid touching such cells.

template<typename Element, typename Self, template<typename> class Id>
auto&& gtopt::SystemLP::element(this Self&& self, const Id<Element>& id)

Get element by ID.

Parameters
self The object instance (deduced via explicit object parameter)
id Element ID
Returns Reference to the element
Exceptions
std::runtime_error — same low_memory caveat as elements(). Collections must be live (m_collections_built_ == true) at the point of access.

template<typename Element, template<typename> class Id>
auto gtopt::SystemLP::element_index(const Id<Element>& id) const

Get index of element by ID.

Parameters
id Element ID
Returns Index of the element

template<typename Element, typename Self>
auto&& gtopt::SystemLP::elements(this Self&& self)

Get all elements of specific type.

Returns Reference to elements container
Exceptions
std::runtime_error if m_collections_built_ == false — the caller forgot to invoke rebuild_collections_if_needed() after a release_backend() under non-off low_memory. Throwing (rather than asserting) lets test fixtures and outer frames catch the contract violation and shut down cleanly with a useful message; without the check the access silently returns an empty range and the next subscript triggers a vector OOB abort.

void gtopt::SystemLP::ensure_lp_built()

Ensure the LP backend is live and ready to solve. Pure backend reconstruct — does NOT rebuild m_collections_. Callers that need the XLP element wrappers populated (e.g. to read elements<X>() / collections() after a prior release_backend() under non-off low-memory) must follow up with rebuild_collections_if_needed().

History: a previous version of this function ran a shadow flatten to also populate m_collections_, but that allocated hundreds of MB per cell — under compress it ballooned RSS by ~40% on the large hydrothermal case (tens of thousands of flattens per run via the per-phase solve hot path). Collections are now rehydrated only at the explicit call sites that need them (rebuild_collections_if_needed()).

Per-mode behavior:

  • off: no-op (backend always live).
  • snapshot / compress: reconstruct backend from snapshot if released.
  • rebuild: invoke the SystemLP-owned rebuild callback (which

Callers that subsequently mutate the LP (add_col, add_row, set_*) can skip the explicit call — those mutations invoke ensure_backend themselves.

SystemKind gtopt::SystemLP::kind() const noexcept

Forward (regular) vs aperture (simplified backward-pass) system. State variables/links registered by this LP route to the matching registry in SimulationLP (see SystemKind).

template<typename Self>
auto&& gtopt::SystemLP::linear_interface(this Self&& self) noexcept

Access linear interfaces.

Returns Linear interfaces container

void gtopt::SystemLP::merge_solver_stats(const SolverStats& other) noexcept

Forward the clone-merge helper so callers that spin up a cloned LP for elastic filtering can fold its counters back in before it is destroyed.

NameView gtopt::SystemLP::name() const noexcept

Get system name.

Returns System name as string view

const auto& gtopt::SystemLP::options() const noexcept

Get system options.

Returns Const reference to options

bool gtopt::SystemLP::output_skipped() const noexcept

Skip this cell in PlanningLP::write_out. Set when the owning SDDP method has permanently excluded the scene (elastic filter produced no feasibility cut, so no valid solution exists for this cell). Avoids the wasted rebuild + re-solve that the write path would otherwise do to "rehydrate" the cell.

bool gtopt::SystemLP::output_written() const noexcept

True when write_out() has already emitted this cell's element tables (set by the SDDP simulation pass right after its final per-cell solve). Callers that iterate every cell to write output should skip cells that return true to avoid overwriting the sim-pass output with values read from a rehydrated (possibly un-solved) backend under compress.

template<typename Element>
auto gtopt::SystemLP::push_back(Element&& e)

Add element to appropriate collection.

Parameters
e Element to add
Returns Result of collection push_back

void gtopt::SystemLP::rebuild_collections_if_needed()

Under LowMemoryMode::compress, rebuild the per-element XLP state (generation_cols, capacity_rows, …) if it was dropped by a prior release_backend(). Runs create_collections() followed by a throw-away flatten whose sole purpose is the add_to_lp() side effects on the XLP wrappers — the produced FlatLinearProblem is discarded, the solver backend is untouched. No-op under off (collections never drop). Invoked from ensure_lp_built() so any caller that does ensure_lp_built → read collections works transparently.

void gtopt::SystemLP::release_backend()

Release the solver backend and (under any non-off low-memory mode) drop the per-cell collection wrappers. The memory ceiling under compress becomes active_workers × per-cell instead of num_cells × per-cell resident forever.

Post-release rehydration paths:

  • For LP solve / mutate (add_col, add_row, set_*): call ensure_lp_built() (or just call the mutator — it auto-fires ensure_backend()). Backend only; collections stay empty.
  • For element/collection READS (elements<X>(), collections(), write_out, backward-pass aperture bound updates): call rebuild_collections_if_needed() first. That repopulates m_collections_ via a throw-away flatten and leaves the solver backend alone (so cached primal/dual from the last solve are still served by LinearInterface getters under compress).

Debug builds assert in elements<X>() / element() / collections() if the read is performed without a prior rebuild — release builds silently see empty containers and likely OOB on subsequent indexing.

std::expected<int, Error> gtopt::SystemLP::resolve(const SolverOptions& solver_options = {})

Resolves the linear programming problem.

Parameters
solver_options Configuration options for the LP solver
Returns Expected with solver status code (0 = optimal) or error

void gtopt::SystemLP::set_drop_collections_on_release(bool enable) noexcept

Opt into dropping the disposable XLP collection wrappers on every release_backend() (see m_drop_collections_on_release_). Enabled by the solve method when a process memory limit is configured, so the resident-collections floor is bounded to the active working set at the cost of a rebuild on the next touch. No-op under LowMemoryMode::off (collections must stay live there).

template<typename Self>
auto&& gtopt::SystemLP::system(this Self&& self) noexcept

Access the underlying system.

Returns Reference to the system

template<typename Self>
auto&& gtopt::SystemLP::system_context(this Self&& self) noexcept

Get system context.

Returns Const reference to system context

int gtopt::SystemLP::update_lp()

Update LP elements for all (scenario, stage) pairs in this system.

Returns Total number of LP modifications across all elements

Iterates over all scenarios and stages in this SystemLP and dispatches element.update_lp() to every collection element that satisfies the HasUpdateLP concept. May update coefficients, bounds, or RHS values.

std::expected<std::string, Error> gtopt::SystemLP::write_lp(const std::string& filename, LpFileFormat format = LpFileFormat::lp, LpFormatFallback fallback = LpFormatFallback::other_format) const

Writes the LP problem to a file.

Parameters
filename Base file name (phase/scene labels and .lp extension are appended automatically).
format File format (extension .lp or .mps).
fallback See LinearInterface::write_lp.
Returns The full path of the written file (with extension).