gtopt::SDDPMethod class

Iterative SDDP solver for multi-phase power system planning.

Wraps a PlanningLP and adds Benders decomposition on top of the per-phase LP subproblems. Handles reservoir volumes, capacity expansion variables, and future state-variable types generically.

Supports multiple scenes (solved in parallel), optimality cut sharing between scenes, iterative feasibility backpropagation, and cut persistence for hot-start.

API for external monitoring / GUI integration

The solver exposes a rich API that enables GUI or monitoring tools to observe the iterative process and control execution:

  • Callback: register an SDDPIterationCallback via set_iteration_callback(). It is invoked after every iteration with the full SDDPIterationResult. Return true from the callback to request a stop.
  • Programmatic stop: call request_stop() from any thread; the solver checks this flag at the start of each iteration and exits gracefully, saving all accumulated cuts.
  • Live query: call current_iteration(), current_gap(), current_lower_bound(), current_upper_bound() at any time (they are atomic and thread-safe) to poll the solver's convergence state.
  • Sentinel file: same as PLP's userstop — check for a sentinel file on disk.
SDDPMethod sddp(planning_lp, SDDPOptions{.max_iterations = 100});

// Register a callback that prints progress and stops at gap < 1e-6
sddp.set_iteration_callback([](const SDDPIterationResult& r) {
    fmt::print("iter {} gap={:.6f}\n", r.iteration, r.gap);
    return r.gap < 1e-6;  // true → stop
});

// Start solving (blocks until done / stopped)
auto results = sddp.solve();

// Or stop programmatically from another thread:
sddp.request_stop();

Public types

struct LiveMetrics
struct PriorIterBounds
struct SceneRetryState
using ForwardPhaseObserver = std::function<void(SceneIndex, PhaseIndex)>

Public static variables

static std::size_t STATIONARY_SEED_DEPTH

Constructors, destructors, conversion operators

SDDPMethod(PlanningLP& planning_lp, SDDPOptions opts = {}) explicit noexcept

Public functions

auto all_scene_phase_states() const -> auto& noexcept
Full scene-phase states (valid after ensure_initialized()).
auto aperture_chunk_mode() const -> auto noexcept
auto aperture_chunk_size() const -> auto noexcept
auto aperture_drop_tracker() const -> const ApertureDropTracker& noexcept
void bound_alpha(SceneIndex scene_index, PhaseIndex phase_index)
auto boundary_cuts_loaded() const -> bool noexcept
void bump_iteration_offset(IterationIndex value) noexcept
void capture_state_variable_values(SceneIndex scene_index, PhaseIndex phase_index, const ScaledView& col_sol_phys, std::span<const double> reduced_costs) const noexcept
auto check_api_stop_request() const -> bool
Check whether the monitoring API stop-request file exists.
auto check_sentinel_stop() const -> bool
Check whether the sentinel file exists (user-requested stop).
void clear_stop() noexcept
Clear a previous stop request (e.g., before re-running solve()).
void clear_stored_cuts() noexcept
void collect_state_variable_links(SceneIndex scene_index)
void compute_boundary_gap(SDDPIterationResult& ir, std::span<const uint8_t> scene_feasible) const
void compute_iteration_bounds(SDDPIterationResult& ir, std::span<const uint8_t> scene_feasible, std::span<const double> weights) const
Compute and fill ir.upper_bound, ir.lower_bound, ir.scene_lower_bounds.
auto current_gap() const -> double noexcept
Current relative convergence gap.
auto current_iter_max_kappa(IterationIndex iter) const -> double noexcept
auto current_iteration() const -> IterationIndex noexcept
Current iteration number (0 before first iteration completes).
auto current_lower_bound() const -> double noexcept
Current lower bound (phase-0 objective including α).
auto current_pass() const -> int noexcept
Current pass: 0=idle, 1=forward, 2=backward.
auto current_upper_bound() const -> double noexcept
Current upper bound (sum of actual phase costs).
auto cut_manager() -> SDDPCutManager& noexcept
Access the cut manager (for cascade orchestration, tests, etc.).
void diagnose_kappa(SceneIndex scene_index, PhaseIndex phase_index, const LinearInterface& li, IterationIndex iteration_index)
auto ensure_initialized() -> std::expected<void, Error>
void finalize_iteration_result(SDDPIterationResult& ir, IterationIndex iteration_index, const std::vector<SDDPIterationResult>& results)
void forget_first_cuts(std::ptrdiff_t count)
auto global_max_kappa() const -> double noexcept
auto has_converged() const -> bool noexcept
Whether the solver has converged.
void initialize_alpha_variables(SceneIndex scene_index)
auto is_stop_requested() const -> bool noexcept
Check whether a stop has been requested.
auto iteration_offset() const -> IterationIndex noexcept
auto load_boundary_cuts(const std::string& filepath) -> std::expected<CutLoadResult, Error>
auto load_cuts(const std::string& filepath) -> std::expected<CutLoadResult, Error>
auto load_scene_cuts_from_directory(const std::string& directory) -> std::expected<CutLoadResult, Error>
auto max_kappa(SceneIndex scene_index, PhaseIndex phase_index) const -> double noexcept
void maybe_write_api_status(const std::string& status_file, const std::vector<SDDPIterationResult>& results, std::chrono::steady_clock::time_point solve_start, SolverMonitor& monitor, std::string_view final_status = {}) const
auto mutable_options() -> auto& noexcept
Mutable options access (for cascade orchestration between solve() calls).
auto num_stored_cuts() const -> std::ptrdiff_t noexcept
Total number of stored cuts across all scenes.
auto options() const -> auto& noexcept
SDDP options (const).
auto phase_states() const -> auto& noexcept
Legacy accessor for scene 0 (backward compatibility).
auto phase_states(SceneIndex scene_index) const -> auto& noexcept
Per-phase state for a given scene.
void request_stop() noexcept
auto save_all_scene_cuts(const std::string& directory) const -> std::expected<void, Error>
auto save_cuts(const std::string& filepath) const -> std::expected<void, Error>
Save accumulated cuts to a CSV file for hot-start.
void save_cuts_for_iteration(IterationIndex iteration_index, std::span<const uint8_t> scene_feasible)
auto save_scene_cuts(SceneIndex scene_index, const std::string& directory) const -> std::expected<void, Error>
auto scene_alpha_offset(SceneIndex scene_index) const -> double noexcept
auto scene_retry_state(SceneIndex scene_index) -> SceneRetryState&
auto scene_retry_state(SceneIndex scene_index) const -> const SceneRetryState&
auto scenes_done() const -> int noexcept
Number of scenes completed in the current pass.
void seed_max_kappa(double kappa) noexcept
auto seed_prior_bounds() const -> const std::vector<PriorIterBounds>& noexcept
void seed_prior_bounds(std::vector<PriorIterBounds> history) noexcept
void set_forward_phase_observer(ForwardPhaseObserver cb) noexcept
void set_iteration_callback(SDDPIterationCallback cb) noexcept
auto should_dispatch_update_lp(IterationIndex iteration_index) const -> bool
auto should_stop() const -> bool
auto solve(const SolverOptions& lp_opts = {}) -> std::expected<std::vector<SDDPIterationResult>, Error>
Run the SDDP iterative solve.
auto stored_cuts() const -> auto
auto terminal_api_status() const -> std::string_view
void update_max_kappa(SceneIndex scene_index, PhaseIndex phase_index, const LinearInterface& li, IterationIndex iteration_index = {})
void update_max_kappa(SceneIndex scene_index, PhaseIndex phase_index, double kappa) noexcept
Update max kappa from an already-known value (no LP save possible).

Typedef documentation

using gtopt::SDDPMethod::ForwardPhaseObserver = std::function<void(SceneIndex, PhaseIndex)>

Observer invoked at the head of every forward-pass phase, right before the cooperative stop check (scene, phase). Set it before solve(); it runs on pool worker threads, so it must be thread-safe. Used to inject a stop at a deterministic point mid-pass (tests) and for lightweight progress probes.

Function documentation

auto gtopt::SDDPMethod::aperture_chunk_mode() const noexcept

Backward-pass aperture grouping resolved at the last solve() setup (per_scene until then). The input fields options().aperture_chunk_mode / aperture_chunk_size are never overwritten, so a cascade re-solve re-resolves from the user values.

auto gtopt::SDDPMethod::aperture_chunk_size() const noexcept

Concrete apertures per backward-pass task resolved at the last solve() setup (A_max under per_scene, 1 under per_aperture).

const ApertureDropTracker& gtopt::SDDPMethod::aperture_drop_tracker() const noexcept

Cross-iteration record of backward-pass apertures dropped as infeasible (issue #551): per-iteration drop counts (copied into SDDPIterationResult::apertures_dropped) and the persistent-drop escalations. Reset at the start of every solve().

void gtopt::SDDPMethod::bound_alpha(SceneIndex scene_index, PhaseIndex phase_index)

Release α's bootstrap pin at (scene, phase) so a subsequently- installed Benders (or boundary) cut can represent arbitrary future-cost values without being artificially clipped by the initial lowb = uppb = 0 equality. Idempotent. Called automatically before every add_row(alpha_cut) on the source phase (backward pass, feasibility pass, aperture pass) and on the last phase when the first boundary cut is installed. Exposed publicly for characterisation tests and for external callers that install cuts on α directly.

Both bounds are released: lowb ← -DblMax, uppb ← +DblMax. Under low_memory = compress the update is mirrored into the m_dynamic_cols_ entry via update_dynamic_col_bounds so apply_post_load_replay preserves the freed bounds across a release+reload cycle. Under LowMemoryMode::off only the live backend is modified — there is no snapshot to re-sync.

bool gtopt::SDDPMethod::boundary_cuts_loaded() const noexcept

True when boundary (terminal FutureCost) cuts were loaded by the last initialize_solver — the boundary-cut gap diagnostics are then active.

void gtopt::SDDPMethod::bump_iteration_offset(IterationIndex value) noexcept

Ratchet m_iteration_offset_ forward to value. Used by :class:CascadePlanningMethod between the forget-pass and the re-solve so phase-2 doesn't restart its iter counter at the phase-1 offset (which otherwise produces duplicate iter numbers in the per-iter log — observed as "iter 20" appearing twice at the first iter of every cascade level that ran a forget pass). std::max semantics: never moves the offset backwards.

void gtopt::SDDPMethod::capture_state_variable_values(SceneIndex scene_index, PhaseIndex phase_index, const ScaledView& col_sol_phys, std::span<const double> reduced_costs) const noexcept

Mirror per-state-variable runtime values onto the persistent StateVariable objects after a forward (or elastic-clone) solve.

Always writes col_sol for every state variable of the solved phase, and reduced_cost on each source state variable reached via an incoming link from the previous phase. Cut construction reads both fields directly from the persistent StateVariable objects, avoiding per-phase full-vector caches.

col_sol_phys is a physical-space view (from LinearInterface::get_col_sol()) so solver-tolerance noise has already been clamped to each column's physical bound box. The captured raw value is recovered by dividing by the state variable's var_scale(), yielding a clean raw LP value for StateVariable::col_sol() consumers (cut builders, next-phase propagate_trial_values).

void gtopt::SDDPMethod::clear_stored_cuts() noexcept

Clear all stored cut metadata (combined + per-scene). Used by CascadePlanningMethod between cascade phases.

void gtopt::SDDPMethod::compute_boundary_gap(SDDPIterationResult& ir, std::span<const uint8_t> scene_feasible) const

Fill ir.boundary (boundary-cut gap diagnostics) from the aggregated bounds and the forward pass's last-phase future-cost values. No-op (inactive diagnostics) when no boundary cuts were loaded.

double gtopt::SDDPMethod::current_iter_max_kappa(IterationIndex iter) const noexcept

Per-iter kappa for the per-iter log clause. Returns the max kappa observed during this iteration only — i.e. a freshly computed condition number that reflects the LP at this iter, not the historical maximum. Once a CPLEX barrier solve returns nullopt (no basis available, the common case under backward_resolve_target-driven re-solves), no cell on the current iter gets updated, so this returns -1.0 and the per-iter log clause is suppressed — much more honest than re-displaying the LP-construction probe value every iter. Different from :meth:global_max_kappa which returns the historical max for solve-time warnings.

void gtopt::SDDPMethod::diagnose_kappa(SceneIndex scene_index, PhaseIndex phase_index, const LinearInterface& li, IterationIndex iteration_index)

Analyze cut rows to identify which Benders cuts have the worst coefficient ratios. Called by update_max_kappa when kappa_warning == diagnose and kappa exceeds the threshold.

std::expected<void, Error> gtopt::SDDPMethod::ensure_initialized()

Ensure the solver is initialized (alpha variables, state links, etc.). Safe to call multiple times (guarded by m_initialized_ flag). Call before loading external cuts that reference alpha columns.

void gtopt::SDDPMethod::finalize_iteration_result(SDDPIterationResult& ir, IterationIndex iteration_index, const std::vector<SDDPIterationResult>& results)

Compute gap + gap_change, update convergence flag, update live-query atomics, log. results carries the previous iterations so that gap_change can be evaluated against the look-back window before the log line is emitted — otherwise the mid-iteration log would show a stale 1.0 sentinel while the later "done" log shows the real value.

void gtopt::SDDPMethod::forget_first_cuts(std::ptrdiff_t count)

Parameters
count Number of leading cuts to remove (clamped to size).

Remove the first count cuts from stored cuts and from the LP. This deletes the LP rows associated with those cuts (via delete_rows) and erases them from m_stored_cuts_. Used by the cascade solver's "forget inherited cuts" feature: the first N cuts loaded via hot-start are dropped so the solver continues with only self-generated cuts.

double gtopt::SDDPMethod::global_max_kappa() const noexcept

Get the global max kappa across all (scene, phase) LP solves. Returns the cached max regardless of when it was observed — used by the SDDP warning machinery that just needs "worst kappa seen during this solve".

IterationIndex gtopt::SDDPMethod::iteration_offset() const noexcept

Current iteration-index offset. Starts at 0 and advances past the last iteration executed at the end of each solve() call so re-entering solve() on the same instance keeps each cut's IterationContext disjoint from those already installed. Also bumped by hot-start cut loaders to start past the max iteration found in the loaded file (see initialize_solver).

std::expected<CutLoadResult, Error> gtopt::SDDPMethod::load_boundary_cuts(const std::string& filepath)

Returns CutLoadResult with count and max iteration, or an error.

Load boundary (future-cost) cuts from a named-variable CSV file.

The CSV header names the state variables (e.g. reservoir or battery names); subsequent rows provide {name, scenario, rhs, coefficients}. Cuts are added only to the last phase, with an alpha column created if needed. This is analogous to PLP's "planos de embalse".

std::expected<CutLoadResult, Error> gtopt::SDDPMethod::load_cuts(const std::string& filepath)

Load cuts from a CSV file and add to all scenes' phase LPs. Cuts are broadcast to all scenes regardless of originating scene, since loaded cuts serve as warm-start approximations for the entire problem (analogous to PLP's cut sharing across scenarios).

std::expected<CutLoadResult, Error> gtopt::SDDPMethod::load_scene_cuts_from_directory(const std::string& directory)

Load all per-scene cut files from a directory. Files matching scene_<N>.csv are loaded; files with the error_ prefix (from infeasible scenes in a previous run) are skipped to prevent loading invalid cuts during hot-start.

double gtopt::SDDPMethod::max_kappa(SceneIndex scene_index, PhaseIndex phase_index) const noexcept

Read-only view of the per-(scene, phase) max-kappa accumulator. Returns the largest kappa observed across all update_max_kappa calls for this cell, or a negative sentinel if no LP has been solved on it yet. (Added 2026-04-28 for testability — exposes the accumulator driven by the update_max_kappa overloads.)

void gtopt::SDDPMethod::maybe_write_api_status(const std::string& status_file, const std::vector<SDDPIterationResult>& results, std::chrono::steady_clock::time_point solve_start, SolverMonitor& monitor, std::string_view final_status = {}) const

Parameters
status_file
results
solve_start
monitor
final_status Empty while the solve is live. At the end of the solve pass the terminal label (see terminal_api_status() or "error"); the write is then the last one for this solve.

Write the monitoring API status file if API is enabled.

void gtopt::SDDPMethod::request_stop() noexcept

Request the solver to stop gracefully after the current iteration. Thread-safe — may be called from any thread.

std::expected<void, Error> gtopt::SDDPMethod::save_all_scene_cuts(const std::string& directory) const

Save all scenes' cuts to per-scene files in the given directory. Each scene gets its own file: <directory>/scene_<N>.csv.

void gtopt::SDDPMethod::save_cuts_for_iteration(IterationIndex iteration_index, std::span<const uint8_t> scene_feasible)

Save cuts (combined + per-scene) after an iteration, handling infeasible scene renaming.

std::expected<void, Error> gtopt::SDDPMethod::save_scene_cuts(SceneIndex scene_index, const std::string& directory) const

Save cuts for a single scene to a per-scene file. Uses scene-specific storage, avoiding lock contention when called in parallel for different scenes.

double gtopt::SDDPMethod::scene_alpha_offset(SceneIndex scene_index) const noexcept

Per-scene α-rebase offset c̄ (zero when not opted in via SDDPOptions::boundary_cuts_mean_shift). The offset is now folded into the first-phase master LP's NATIVE objective offset at boundary-cut load (initialize_solver), so get_obj_value() — and by extension UB / LB — already carries it; the display sites no longer add it (that would double-count). This accessor exposes the raw c̄ unchanged for tests and for populate_future_cost_output.

SceneRetryState& gtopt::SDDPMethod::scene_retry_state(SceneIndex scene_index)

Mutable per-scene retry state (test-friendly accessor). Promoted to public so characterisation tests can synthesise the "scene S failed last iteration" state without first forcing a real LP infeasibility — set scene_retry_state(s).global_cuts_at_last_failure = current_count then drive solve() to exercise the stall-stop guard at the next forward dispatch. Production callers should not mutate this vector directly; the rollback hook + stall guard in run_forward_pass_all_scenes own the lifecycle.

void gtopt::SDDPMethod::seed_max_kappa(double kappa) noexcept

Seed the kappa baseline for this solver from an earlier solver's max kappa. Used by CascadePlanningMethod to carry the warmup-derived condition number forward across cascade levels so that observability (the kappa=… clause in the iter log) is preserved when CPLEX barrier without crossover leaves the new level's LPs without a freshly-queryable kappa. Negative values (including the -1 sentinel meaning "no observation yet") are ignored, so calling with other.global_max_kappa() is safe even when the other solver also never produced a kappa.

const std::vector<PriorIterBounds>& gtopt::SDDPMethod::seed_prior_bounds() const noexcept

Read the carried prior history (empty when no seed is installed — typical for L0 or for plain-SDDP runs).

void gtopt::SDDPMethod::seed_prior_bounds(std::vector<PriorIterBounds> history) noexcept

Seed the stationary Δgap lookback with the prior cascade level's recent iter history.

At construction the per-level results history is empty, so finalize_iteration_result falls back to the 1.0 sentinel for ir.gap_change on iter 1 (no lookback available). When this solver is the second-or-later level of a :class:CascadePlanning Method, the previous level's last few iter bounds are a meaningful reference — the cuts and policy state have been inherited, so iter 1's Δgap should measure the cross-level UB delta against the prior level's tail (windowed) rather than a sentinel.

Array, not a single point: stationary_window=N means the gap_change lookback compares results[size-1] against results[size-N]. At iter 1 of a new level the in-level results has size 0 / 1 / 2 — short of any window > 1. Pass the LAST N (or more — STATIONARY_SEED_DEPTH below caps the max we'll consume) entries of the previous level so the new level's first N-1 iters can still pull a windowed reference from the seed, ordered OLDEST-FIRST (the last element is the previous level's most-recent iter).

finalize_iteration_result (sync) and the async equivalent at sddp_iteration.cpp:1846 walk a combined index over [seed... | results...] to resolve the lookback target.

Convergence safety: the seed only feeds the reported Δgap. A stationary STOP needs stationary_window iterations of the level's own with cuts (and the gap below stationary_gap_ceiling), so a seed-vs-iter-1 Δgap can never stop a level by itself — previously a cold level seeded with the prior level's bounds declared "stationary" at iter 1 with a 40 % gap.

void gtopt::SDDPMethod::set_iteration_callback(SDDPIterationCallback cb) noexcept

Register a callback invoked after each iteration. If the callback returns true, the solver stops after that iteration.

bool gtopt::SDDPMethod::should_dispatch_update_lp(IterationIndex iteration_index) const

Check whether update_lp should be dispatched for this iteration. Returns false when the iteration is explicitly disabled or skipped by the global skip count.

bool gtopt::SDDPMethod::should_stop() const

Check all stop conditions: sentinel file, API stop request, programmatic stop, callback

auto gtopt::SDDPMethod::stored_cuts() const

Union view over every stored cut across scenes, rebuilt on call. Equivalent to the former flat-vector accessor — kept for places (cascade transitions, save helpers) that need a combined list.

std::string_view gtopt::SDDPMethod::terminal_api_status() const

Terminal label for solver_status.json once the solve pass ends: "converged", "stopped" (stop request / sentinel / callback), or "max_iterations" (iteration budget exhausted without convergence). Not written for simulation-only runs (max_iterations == 0).

void gtopt::SDDPMethod::update_max_kappa(SceneIndex scene_index, PhaseIndex phase_index, const LinearInterface& li, IterationIndex iteration_index = {})

Update the per-(scene, phase) max kappa value after an LP solve. Also checks kappa against the threshold and emits a warning or saves the LP file depending on the kappa_warning mode.

Variable documentation

static std::size_t gtopt::SDDPMethod::STATIONARY_SEED_DEPTH

Max number of prior-level iter results the cascade orchestrator should pass into :func:seed_prior_bounds. Chosen to cover any realistic stationary_window (current max in use is 4 for L0 warmup; cascade L1+ use window ≤ 3). Bigger is harmless — the gap_change calc only consumes min(window, seed.size() + results.size()) entries — but keeps the per-cascade-transition memory footprint trivially small.