gtopt namespace

This file defines the Collection class, which is a central data structure for managing indexed collections of elements. It makes extensive use of move semantics for efficient memory management, particularly for container operations.

Resolve and stamp a single (class, uid, attribute) reference into row with coefficient coef. Handles both single-col registrations (the common case) and multi-col sum registrations used by virtual aggregators like line.flowp under piecewise_direct line-loss mode (no aggregator LP col — flowp resolves to Σ flowp_seg_k, so we stamp coef on every segment col). See AmplVariable::block_cols_sum for the sum-of-cols data layout.

Returns {emitted, offset_shift}. offset_shift is coef × offset when the resolved column carries a non-zero AMPL offset (e.g. demand's Option C neg_fail = load − lmax); the caller folds the shift onto the row's RHS via the existing param_shift accumulator.

Namespaces

namespace cli
namespace detail
namespace gas
namespace ieee738
namespace kirchhoff
namespace line_direction
namespace line_losses
namespace line_thermal
namespace log
namespace names_registry_detail
namespace sddp_file
File naming patterns for per-scene cut files.
namespace storage_state_defaults
namespace unit_registry_detail

Classes

struct AbsExpr
abs(linear_expression) term (F5).
struct ActiveTask
class AdaptiveWorkPool
Default work pool using int64_t priority key with std::less semantics (smaller key → higher priority).
struct AllowancePool
Tradable emission-allowance pool (cap-and-trade).
class AllowancePoolLP
struct AmmoniaNode
Carrier-tagged balance node for ammonia (MWh_LHV) flows.
class AmmoniaNodeLP
struct AmmoniaStorage
Ammonia (NH₃) energy storage — long-term H₂ carrier.
class AmmoniaStorageLP
LP representation of an ammonia storage element.
struct AmplCompoundKey
struct AmplCompoundLeg
struct AmplMetadataKey
Lookup key for the per-element metadata registry.
struct AmplParamKey
struct AmplScalarKey
struct AmplVariable
struct AmplVariableKey
struct AmplVariableKeyHash
struct Aperture
One backward-pass opening referencing a source scenario.
struct ApertureChunkResolution
struct ApertureCutResult
Result of a single aperture's clone + update + solve + cut.
class ApertureDataCache
In-memory cache for aperture-specific schedule data.
struct ApertureDrop
One dropped aperture of a (scene, phase) cell.
struct ApertureDropCount
(uid, drop count) entry of the summary's top lists.
struct ApertureDropRecord
What ApertureDropTracker::record learned from one cell's drops.
class ApertureDropTracker
struct ApertureEntry
struct ApertureIterationCounts
Aperture solve / drop counts of one iteration.
struct ApertureSummary
End-of-solve aperture statistics (ApertureDropTracker::summary()).
struct ArrayIndexBase
template<typename Type, typename Map, typename FSched, typename... Uid>
struct ArrayIndexTraits
struct ArrowIndexCache
template<typename Uid Uid>
struct ArrowTraits
template<>
struct ArrowTraits<double>
template<>
struct ArrowTraits<int>
template<>
struct ArrowTraits<int16_t>
template<>
struct ArrowTraits<int8_t>
template<typename... Uids>
struct ArrowUidTraits
struct BackwardPassOutcome
Outcome of running the backward pass across all scenes.
template<typename Key = int64_t>
struct BasicTaskRequirements
Task requirements with a generic priority key.
template<typename Key = int64_t, typename KeyCompare = std::less<Key>>
class BasicWorkPool
Adaptive thread pool with generic priority key.
struct Basis
A captured simplex basis: one BasisStatus per column and row.
struct Battery
Represents a battery energy storage system (BESS).
class BatteryLP
Linear programming representation of a battery energy storage system.
class BendersCut
Class-based interface for Benders cut construction with work-pool support and infeasibility monitoring.
struct Block
Smallest time unit in the optimization horizon.
class BlockLP
struct BoundaryCutCoeffStats
struct BoundaryGapDiagnostics
struct BoundEnvelopeReport
struct BoxEdgeStats
struct BuildInfo
struct Bus
Electrical busbar (node) in the power network.
class BusLP
struct Capacity
Complete capacity entity with identification and attributes.
struct CapacityCut
A stored optimality cut projected onto capacity coordinates.
struct CapacityCutCoefficient
struct CapacityObjectBase
Base class providing capacity constraint logic for LP objects.
template<typename Object Object>
struct CapacityObjectLP
A linear programming representation of an object with capacity constraints.
struct CapacityProfile
Generic profile element (kind-tagged owner FK).
class CapacityProfileLP
template<typename OwnerLP>
struct CapacityProfileTraits
template<>
struct CapacityProfileTraits<DemandLP>
template<>
struct CapacityProfileTraits<GeneratorLP>
struct CarrierConverter
One-stage flow converter between two carrier-typed nodes.
class CarrierConverterLP
template<typename Node Node>
class CarrierNodeLP
template<typename Storage, typename NodeLP, auto NodeRef, const StorageStateDefaults& Defaults>
class CarrierStorageLP
struct CascadeLevel
One cascade level configuration.
struct CascadeLevelMethod
Solver options for one cascade level.
struct CascadeLevelStats
Statistics collected for each cascade level after solving.
struct CascadeOptions
Cascade solver configuration: variable number of levels.
class CascadePlanningMethod
Multi-level solver with configurable LP formulations per level.
struct CascadeProgress
Top-level checkpoint payload.
struct CascadeProgressLevel
One entry of CascadeProgress::levels.
struct CascadeTransition
Transition configuration: how a cascade level receives information from the previous level.
template<CopyMove Type, typename VectorType = std::vector<Type>, typename IndexType = ElementIndex<Type>>
class Collection
A container for managing typed elements with efficient lookup by name, UID, or index.
struct Commitment
Unit commitment parameters for a generator.
class CommitmentLogicRule
class CommitmentLP
struct CommitmentRunInfo
struct CompressedBuffer
Compressed buffer with metadata for round-trip compression.
struct CompressionStatsSample
struct ConstraintDirective
struct ConstraintDomain
Domain over which a constraint is instantiated.
struct ConstraintExpr
Complete parsed constraint expression.
class ConstraintParseError
Parser-time diagnostic error.
class ConstraintParser
Parser for AMPL-inspired user constraint expressions.
struct ConstraintTerm
A single term in a constraint expression.
struct Converter
Couples a battery to a generator (discharge) and a demand (charge).
class ConverterLP
class CoordinatorPool
Fixed-width scene/pass orchestration pool (Tier 1).
class CostHelper
Handles cost calculations with time discounting for optimization problems.
class CPUMonitor
struct CriticalSpan
One critical span of a DLR line.
struct CutKey
struct CutLoadResult
Result of a cut load operation.
struct CutTag
struct CvarLayout
Layout of the CVaR construct of one (scene, phase) LP.
struct CvarScenarioInput
struct CvarScenarioResult
Post-solve values of one scenario.
struct CvarScenarioTerm
One scenario of a built CVaR construct.
struct CvarSolution
Post-solve values of a cell's construct.
struct DecisionVariable
A free continuous LP column with optional bounds and cost.
class DecisionVariableLP
class DecompressionGuard
struct Demand
Represents an electrical demand (load) at a bus.
struct DemandAttrs
Technical and economic attributes shared by demand objects.
class DemandLP
struct DemandProfile
Time-varying load-shape profile for a demand element.
class DemandProfileLP
class DisjointSetUnion
Disjoint Set Union (Union-Find) with path compression and union by rank.
struct DiveInput
Input of propagation_dive. All dense spans are in RAW LP space.
struct DiveOutput
Outcome of propagation_dive.
struct DiveSummary
Summary of a dive run, for the pipeline report and logs.
struct DlrConductor
class DomainRule
struct DomainRuleContext
class DomainRulePipeline
An ordered set of DomainRules applied as a pipeline.
struct DualInfeasibility
struct ElasticCostPolicy
struct ElasticSolveResult
template<typename SystemLP_Type>
class ElementContext
Provides a context for interacting with elements within a SystemLP.
template<typename Element>
struct ElementIndex
struct ElementRef
Reference to a gtopt element and one of its LP attributes.
struct ElementRefResolution
template<typename SystemContext SystemContext, typename Element>
struct ElementTraits
Defines default traits for element access and manipulation.
template<typename SystemContext SystemContext>
struct ElementTraits<SystemContext, BusLP>
Specialization of ElementTraits for BusLP elements.
struct ElfIdentity
Identity fields read from an ELF file (64-bit little-endian only).
struct Emission
Pollutant type tag. Just uid + name.
struct EmissionCapture
Per-(generator, pollutant) CCS / abatement parameters.
class EmissionLP
struct EmissionSource
class EmissionSourceLP
struct EmissionZone
A pollutant cap / price constraint scope, possibly covering multiple pollutants (GHG basket).
struct EmissionZoneFactor
One row of an EmissionZone.emissions[] table: the pollutant kind plus its CO₂-equivalent weight (GWP).
class EmissionZoneLP
template<typename E>
struct EnumEntry
Name-value pair for an enumerator.
template<typename IndexType = std::size_t>
struct enumerate_adapter
struct Error
struct ExpansionCandidate
struct FailSegment
One segment of a stepwise demand-failure (VoLL) curve.
struct FailSegmentWidths
class FcutLogWriter
Mutex-serialised writer for the gtopt_fcut.log debug file.
struct FcutSlackInfo
struct FeasibilityCutResult
Result structure for feasibility cut building.
struct FileSchedRef
struct FingerprintEntry
struct FingerprintStats
Per-class column/row count statistics (informational, not compared).
struct FixedLpResult
Result of a fixed-integer LP solve.
class FlatHelper
Converts multi-dimensional optimization data into flat vectors for LP formulation.
struct FlatLinearProblem
Represents a linear problem in column-major flat representation.
class FlatLpDedupRegistry
struct FlatLpMeta
Scene-invariant label metadata, bundled behind a shared_ptr.
struct Flow
Exogenous water flow at a hydraulic junction.
class FlowLP
struct FlowRight
Flow-based water right (derechos de caudal).
class FlowRightLP
struct FormatSI
struct ForwardPassOutcome
Outcome of running the forward pass across all scenes.
struct Fuel
Time-schedulable fuel price, heat content, and emission factors.
struct FuelEmissionFactor
Per-pollutant emission factors of a Fuel (tons / fuel-unit).
class FuelLP
struct FutureCost
The future cost function (cost-to-go) as a first-class element.
class FutureCostLP
struct GasCompressor
Compressor station between two gas nodes.
class GasCompressorLP
struct GasDemand
Gas load (sink) with optional priced shedding.
class GasDemandLP
struct GasNode
Gas-network node with a squared-pressure column and a balance row.
class GasNodeLP
struct GasOptions
Network-level gas properties (options.gas_options).
struct GasPipe
Gas pipeline (radial tangents or linearised) with line pack.
class GasPipeLP
struct GasSlpStats
Outcome of one gas_slp_refine call.
struct GasSupply
Gas source injecting into a GasNode.
class GasSupplyLP
struct GasTurbine
Generator fuel-gas link with heat rate and pressure gate.
class GasTurbineLP
struct Generator
Represents a generation unit (thermal, renewable, hydro) at a bus.
struct GeneratorAttrs
Core technical and economic attributes shared by generator objects.
class GeneratorLP
struct GeneratorProfile
Time-varying capacity-factor profile for a generator.
class GeneratorProfileLP
Linear programming representation of a generator profile.
struct GpuDeviceState
class GpuMonitor
class GpuMonitorBase
struct HourBlockEntry
Hour → (stage, block) mapping persisted alongside the planning JSON so Python post-processing tools (ts2gtopt, reconstruct_output_hours) can expand block-level solver output back to an hourly series.
struct HydrogenDemand
Hydrogen offtake at a HydrogenNode with an optional per-stage energy requirement.
class HydrogenDemandLP
struct HydrogenNode
Carrier-tagged balance node for hydrogen (MWh_LHV) flows.
class HydrogenNodeLP
struct HydrogenStorage
Hydrogen energy storage (gaseous / liquid / cavern).
class HydrogenStorageLP
LP representation of a hydrogen storage element.
struct IfCondAtom
struct IfExpr
Data-only conditional expression (F8).
struct IndexRange
Specifies a set of index values for a time dimension.
struct InertiaProvision
Generator contribution to inertia zone(s).
class InertiaProvisionLP
struct InertiaRequirementCredit
Commitment-dependent relief of an inertia requirement.
struct InertiaZone
System inertia requirement zone.
class InertiaZoneLP
struct InflowModel
Opt-in autoregressive inflow model attached to a Flow element.
class InputContext
struct InputTraits
Input data access traits.
class IntegerVariable
struct IntegrationTerm
One nonzero (node index, weight) of a banded integration row.
struct IntegrityDecision
struct InvestmentMasterIteration
Per-iteration record of the outer loop.
struct InvestmentMasterOptions
Options controlling the outer investment-master loop.
struct InvestmentMasterResult
template<typename T>
class IotaRange
struct Iteration
Per-iteration control flags for the SDDP solver.
class IterationLP
LP-side wrapper for an Iteration control entry.
struct Junction
Hydraulic node in a hydro cascade network.
class JunctionLP
Linear programming formulation for power system junctions.
struct LabelHash
class LabelMaker
struct Line
Represents a transmission line (branch) connecting two buses.
class LinearInterface
class LinearParser
class LinearProblem
Main class for building and manipulating linear planning problems.
struct LineCommitment
Marks a Line as an OTS switching candidate (issue #509).
class LineCommitmentLP
struct LineDlr
Dynamic line rating of a Line through its critical spans.
class LineDlrLP
class LineLP
struct LinkedLibraryRecord
struct LngGeneratorLink
Link between an LNG terminal and a thermal generator.
struct LngTerminal
LNG storage terminal in a power system.
class LngTerminalLP
Linear programming representation of an LNG storage terminal.
struct LoadedLibraryIdentity
The solver library actually mapped in this process.
struct LoadedObject
An object mapped into this process.
struct LoadedSystem
class LowercaseView
Lazy, zero-copy view that lowercases each character on access.
struct LowMemorySnapshot
class LpBuildError
The single exception type of the LP-assembly failure channel.
struct LpBuildErrorInfo
Structured context of one LP-assembly failure.
class LpCache
Post-solve cache for LinearInterface.
struct LPClassName
class LpDebugWriter
struct LpFailure
struct LpFileTarget
A user-supplied --lp-file value split into output stem and format.
struct LpFingerprint
Complete LP fingerprint for one LP phase.
struct LPKey
struct LpLabelMeta
struct LpLabelStore
struct LpMatrixOptions
Configuration options for converting to flat LP representation.
class LpNameSpillStore
class LpReplayBuffer
Replay state for LinearInterface low-memory reconstruct.
struct LpScaledColumn
A column whose scale factor is not 1: x_physical = scale * x_LP.
struct LpScaledRow
struct LpScales
Everything needed to read an exported LP back in physical units.
struct LpScalesBlock
Weights of one (scenario, stage, block) of the cell.
struct LpScalesBuild
Which gtopt wrote the sidecar (audit trail).
struct LpScalesContext
struct LpScalesDetail
struct LpScalesNumerics
struct LpScalesObjective
Objective scaling: obj_physical = obj_LP * scale_objective.
struct LpScalesRange
struct LpScalesRowType
Matrix coefficient range of one constraint family.
struct LpScalesStage
struct LpScalesTables
class LpSnapshotHolder
Snapshot + codec holder for LinearInterface low-memory paths.
struct LpValidationOptions
Thresholds + on/off flag for incremental LP validation.
struct LpValidationStats
Per-kind counters + bounded list of offenders + max/min trackers.
struct LPVariable
struct MainOptions
Forward declaration; full type in gtopt/planning.hpp.
struct MarkovChainConfig
struct MatrixStats
struct MemoryClamp
class MemoryMonitor
struct MemorySnapshot
Snapshot of memory state at a point in time.
struct MinMaxExpr
max(arg1, arg2, ...) / min(arg1, arg2, ...) term (F7).
class MinUpDownRule
struct MipStartContext
struct MipStartDive
struct MipStartDomainRules
class MipStartGenerator
struct MipStartInject
STAGE 5: inject the candidate as a backend MIP start.
struct MipStartOptions
Initial-MIP-solution (warm-start) configuration: a staged pipeline.
struct MipStartPeakInjection
struct MipStartRelax
struct MipStartReport
Outcome of the MIP-start pipeline (for logging / tests).
struct MipStartRound
STAGE 1: round the relaxation's integer columns.
struct MipStartScipRepair
struct MipStartWindow
struct ModelOptions
Power system model configuration for LP construction.
struct MonitorPoint
class MonolithicMethod
Solves each (scene, phase) LP independently using a work pool.
struct MonolithicOptions
Monolithic solver configuration parameters.
template<typename T>
class MultiArray2D
Minimal 2D array wrapper around std::vector.
template<typename Type, typename Tuple, std::size_t Depth>
struct mvector_traits
template<typename Type, typename Tuple>
struct mvector_traits<Type, Tuple, 1U>
class NamesRegistry
template<Carrier C>
struct Node
Generic carrier-tagged balance node.
struct Object
Base object type providing common identification functionality.
struct ObjectAttrs
Basic attributes common to all objects in the system.
template<typename Object Object>
struct ObjectId
template<typename ObjectType>
class ObjectLP
Wrapper class that adds LP capabilities to objects.
template<typename Object Object>
struct ObjectSingleId
class ObjectUtils
Provides common utility methods for objects in the optimization framework.
template<typename Type, typename... Uid>
class OptSchedule
class OutputContext
struct OutputSelection
template<typename... Ts>
struct Overload
class PamplParser
Parser for pseudo-AMPL constraint files (.pampl).
struct PamplParseResult
Result of parsing a PAMPL file or string.
struct ParseResult
struct PeakInjectionInfo
class PeakInjectionRule
struct PendingStateLink
struct PersistentApertureDrop
struct Phase
Groups consecutive planning stages into a higher-level period.
class PhaseGridRecorder
class PhaseLP
Linear programming phase containing multiple stages.
class PhaseRangeSet
struct PhaseStateInfo
struct Planning
Represents a complete power planning model.
struct PlanningDirectoryPeek
Directory options read from the options block of planning files.
class PlanningLP
Linear programming model for power system planning.
class PlanningMethod
Abstract interface for planning problem solvers.
struct PlanningOptions
Global configuration parameters for the optimization model.
class PlanningOptionsLP
Wrapper for PlanningOptions with default value handling.
struct Plant
Declarative plant primitive: groups generator configuration variants and emits Σ-capacity / Σ-commit caps natively.
class PlantLP
struct PlpFeasibilityCuts
Result bundle of build_plp_feasibility_cuts.
struct PluginIntegrityPolicy
struct PluginReport
template<typename IndexT, typename T>
class PositionVector
struct PowerBasedResult
Columns / rows created by add_power_based_rows.
struct PowerBasedUnit
struct PricingOutcome
struct ProductionFactorSegment
One segment of the piecewise-linear production factor curve.
struct ProfileLPMode
Owner-kind switches of ProfileObjectLP::add_profile_to_lp.
template<typename ProfileType, typename ElementLPType>
class ProfileObjectLP
Base class for profile-based LP objects.
struct Pump
Hydraulic pump converting electrical power into upstream water flow.
class PumpLP
Linear programming representation of a hydraulic pump.
struct RelaxedVarInfo
struct ReserveContingency
One contingency candidate of a dynamic requirement.
struct ReserveProvision
Generator contribution to spinning-reserve zone(s).
class ReserveProvisionLP
struct ReserveRequirementPlane
One affine plane of a dynamic reserve requirement.
struct ReserveZone
Regional spinning-reserve requirement zone.
class ReserveZoneLP
struct Reservoir
Water reservoir in a hydro cascade system.
struct ReservoirDischargeLimit
Volume-dependent discharge limit for a reservoir.
struct ReservoirDischargeLimitCoeffs
LP constraint coefficients for the drawdown limit.
class ReservoirDischargeLimitLP
LP wrapper for ReservoirDischargeLimit constraints.
struct ReservoirDischargeLimitSegment
One segment of the piecewise-linear drawdown limit curve.
class ReservoirLP
Linear programming representation of a water reservoir.
struct ReservoirProductionFactor
Reservoir-dependent turbine production factor (PLP "rendimiento").
class ReservoirProductionFactorLP
LP representation of a ReservoirProductionFactor element.
struct ReservoirRefCache
struct ReservoirSeepage
Piecewise-linear seepage model between a waterway and a reservoir.
struct ReservoirSeepageCoeffs
LP constraint coefficients for volume-dependent seepage.
class ReservoirSeepageLP
LP wrapper for ReservoirSeepage systems.
struct ReservoirSeepageSegment
One segment of the piecewise-linear seepage curve.
struct ResolveColResult
struct ResolvedCol
struct ResolvedParamFile
A resolved solver parameter file and where it was found.
class ResourceGovernor
struct RightBoundRule
Volume-dependent bound rule for water rights.
struct RightBoundSegment
One segment of a piecewise-linear bound function.
class RobustSolveGuard
struct RowDiagnostics
struct RowTypeStats
Per-row-type coefficient statistics.
struct RuleBoundState
struct SanityOptions
struct ScalarFailSegment
class ScaledView
struct ScalingState
struct Scenario
One possible future realization in stochastic planning.
class ScenarioLP
struct Scene
struct SceneBounds
Per-scene bounds snapshot for one completed iteration.
class SceneCutStore
class SceneIterationTracker
class SceneLP
Represents a logical scene with linear programming scenario elements.
struct SceneMerge
The scenes folded into one LP scene for nonanticipative variables.
struct ScenePhaseLPStats
Label + stats for a single scene/phase LP.
template<typename Type, typename... Uid>
class Schedule
class ScopedStdoutSilencer
class SDDPCutManager
struct SDDPIterationResult
Result of a single SDDP iteration (forward + backward pass).
struct SDDPLogTag
class SDDPMethod
Iterative SDDP solver for multi-phase power system planning.
struct SDDPOptions
Configuration options for the SDDP iterative solver.
struct SddpOptions
SDDP-specific solver configuration parameters.
class SDDPPlanningMethod
Adapter that wraps SDDPMethod behind the PlanningMethod interface.
class SDDPWorkPool
Work pool specialised for the SDDP solver with tuple priority key.
class SeedCommitmentRule
struct SimpleCommitment
Deprecated alias of a Commitment (input only, see file docs).
struct Simulation
Complete time-structure of a planning simulation.
class SimulationLP
Linear programming representation of a power system simulation.
class SnakeCaseView
Lazy, zero-copy view that yields the snake_case form of a string.
struct SolutionRow
struct SolveEffort
class SolveEffortTotals
class SolverBackend
Abstract interface for LP/MIP solver backends.
struct SolverBuildInfo
struct SolverCfgEnumKey
struct SolverLibraryReport
Solver-library identity of one solver provided by a plugin.
struct SolverLinkedLibrary
class SolverMonitor
Background thread that samples workpool statistics and writes JSON.
struct SolverOptions
Configuration options for linear programming solvers.
class SolverRegistry
Singleton registry for dynamically loaded solver plugins.
struct SolverResourceDescriptor
struct SolverStats
Per-LP counters tracking backend activity over the lifetime of the LP.
struct SolverStatusSnapshot
struct SolverTestReport
Aggregated results for all tests run against one solver.
struct SolverTestResult
Result of running one named test against one solver.
class SolverTier
Tier-2 LP-solve executor.
struct SolverVersion
A solver version triple; components are -1 when unknown.
struct SolverVersionPin
class SparseCol
Represents a variable column in a linear program.
struct SparseColLabel
struct SparseColLabelHash
class SparseRow
Represents a constraint row in a linear program with sparse coefficients.
struct SparseRowLabel
struct SparseRowLabelHash
template<typename T>
class StableVector
struct Stage
Investment period grouping consecutive time blocks.
class StageLP
A class representing a stage in a linear programming planning problem.
struct StallGateLimits
Configured dispatch-gate thresholds of the pool.
struct StallGateSnapshot
Live readings the stall diagnosis looks at.
struct StallTracker
class StateVariable
struct StateVarLink
Describes one state-variable linkage between consecutive phases.
struct STBUids
struct StorageIntegration
Parsed model_options.storage_integration value.
template<typename Object Object>
class StorageLP
struct StorageOptions
Options controlling storage LP behaviour for a single add_to_lp call.
struct StorageStateDefaults
struct StoredCut
A serialisable representation of a Benders cut.
struct StrengthenedCutResult
Result of build_strengthened_benders_cut.
template<typename Index Index, typename T>
class StrongIndexVector
struct STUids
struct SumElementRef
Aggregation over multiple elements of the same type.
struct SumPredicate
A predicate that filters a sum(...) aggregation (F4).
class SwapGrowthGate
struct System
Complete physical power system model.
class SystemContext
class SystemLP
Central coordinator for power system LP formulation.
template<typename T = void, typename Key = int64_t, typename KeyCompare = std::less<Key>>
class Task
Queued unit of work: a type-erased callable plus its scheduling requirements.
struct TaskResourceStats
Per-task resource usage sampled before/after execution.
struct ThermalNode
Carrier-tagged balance node for MW_th flows.
class ThermalNodeLP
struct ThermalStorage
Thermal Energy Storage (sensible / latent / molten-salt).
class ThermalStorageLP
LP representation of a thermal storage element.
struct ThrottleCounts
Per-gate throttle counters (ticks on which each gate blocked).
struct TimeAggRef
sum{idx in window} [dur[idx] *] inner_expr — TIME aggregation.
struct TUids
struct TupleHash
Generic hash for any std::tuple of hashable elements.
struct Turbine
Hydroelectric turbine converting water flow into electrical power.
class TurbineLP
Linear programming representation of a hydroelectric turbine.
class uid_passkey
struct UidColumn
template<typename Value, typename... Uids>
struct UidMapTraits
template<class Tag>
class UidOf
template<typename... Uids>
struct UidToArrowIdx
template<>
struct UidToArrowIdx<ScenarioUid, StageUid>
template<>
struct UidToArrowIdx<ScenarioUid, StageUid, BlockUid>
template<>
struct UidToArrowIdx<StageUid>
template<>
struct UidToArrowIdx<StageUid, BlockUid>
template<typename... Uids>
struct UidToVectorIdx
template<>
struct UidToVectorIdx<ScenarioUid, StageUid>
template<>
struct UidToVectorIdx<ScenarioUid, StageUid, BlockUid>
template<>
struct UidToVectorIdx<StageUid>
template<>
struct UidToVectorIdx<StageUid, BlockUid>
struct UidTraits
Traits for UID-based data access patterns.
class UnitRegistry
struct UnreachableSumElement
struct UserConstraint
Stores a user-defined linear constraint expression.
class UserConstraintLP
LP element wrapping a single user-defined constraint.
struct UserModel
A self-contained AMPL model fragment: user vars + user constraints.
class UserModelLP
struct UserParam
struct ValidationResult
Result of semantic validation.
struct VariableScale
Scale definition for an LP variable.
class VariableScaleMap
Lookup table for variable scales built from an array of VariableScale.
struct VersionPinOverrides
struct VolumeRight
Volume-based water right (derechos de volumen).
class VolumeRightLP
LP representation of a volume-based water right.
class WarnOnceFlag
struct Waterway
Water channel connecting two hydraulic junctions.
class WaterwayLP
struct WorkPoolConfig

Enums

enum class AmplVariableKind: std::uint8_t { Regular, StateBacked }
enum class ApertureChunkMode: uint8_t { per_scene = 0, per_aperture = 1, chunked = 2 }
How the backward-pass apertures of one (scene, phase) cell are grouped into work-pool tasks.
enum class ApertureFailureKind: std::uint8_t { infeasible, timed_out, abandoned, non_optimal }
enum class ApertureSelectionMode: uint8_t { head = 0, stride = 1, tail = 2 }
How SddpOptions::num_apertures selects a subset from each phase's Phase::apertures list.
enum class ApertureSolveMode: uint8_t { cold = 0, warm = 1, reduced_cost = 2, dual_shared = 3, screened = 4 }
How each backward-pass aperture subproblem is solved and how its optimality cut's coefficients are recovered.
enum class BarrierSolver: uint8_t { automatic = 0, ipx = 1, hipo = 2 }
Which interior-point implementation runs algorithm = barrier.
enum class BasisCrossMode: uint8_t { off = 0, warm = 1, forward_to_backward = 2, backward_to_forward = 3, full_cross = 4 }
Cross-pass simplex-basis warm-start reuse between the SDDP forward and backward passes.
enum class BasisStatus: uint8_t { at_lower = 0, basic = 1, at_upper = 2, free = 3 }
Basis status of one column or row (slack) in a simplex basis.
enum class BoundaryCutSharingMode: uint8_t { per_scene = 0, shared = 1, multicut = 2 }
How terminal/boundary (future-cost) cuts are shared across scenes.
enum class BoundaryCutsMode: uint8_t { noload = 0, separated = 1, combined = 2, phi_expectation = 3 }
How boundary (future-cost) cuts are loaded for the last phase.
enum class BoundaryCutsValuation: uint8_t { end_of_horizon = 0, present_value = 1 }
Valuation basis for boundary (future-cost) cut coefficients and RHS.
enum class BoundRuleAxis: uint8_t { reservoir_volume = 0, stage_month = 1 }
The driving axis for a RightBoundRule piecewise function.
enum class BuildMode: uint8_t { serial = 0, scene_parallel = 1, full_parallel = 2, direct_parallel = 3 }
How PlanningLP::create_systems assembles per-cell SystemLPs.
enum class Carrier: std::uint8_t { Electric = 0, Water = 1, Hydrogen = 2, Thermal = 3, Ammonia = 4 }
enum class CascadeLevelStatus: std::uint8_t { pending = 0, in_progress = 1, done = 2 }
Lifecycle of a single cascade level across runs.
enum class CogenMode: uint8_t { dispatched = 0, must_run = 1 }
Cogeneration-unit modelling mode.
enum class CompressionCodec: uint8_t { uncompressed = 0, gzip = 1, zstd = 2, lz4 = 3, bzip2 = 4, xz = 5, snappy = 6, brotli = 7, lzo = 8, auto_select = 9 }
Compression codec for file I/O and in-memory compression.
enum class ConstraintMode: uint8_t { normal = 0, strict = 1, debug = 2 }
Controls error handling and verbosity for user constraint resolution.
enum class ConstraintScaleType: uint8_t { Power = 0, Energy, Raw }
How the LP dual of a user constraint row is scaled for output.
enum class ConstraintScope: uint8_t { Block = 0, Stage, Phase, Global }
Time-granularity at which a UserConstraint row (or a DecisionVariable column) is instantiated.
enum class ConstraintType: std::uint8_t { LESS_EQUAL, EQUAL, GREATER_EQUAL, RANGE }
enum class ConvergenceMode: uint8_t { gap_only = 0, gap_stationary = 1, statistical = 2 }
SDDP convergence criterion selection.
enum class ConvexKind: std::uint8_t { UpperEnvelope, LowerEnvelope }
enum class CrossoverMode: uint8_t { automatic = 0, primal = 1, dual = 2, none = 3 }
Barrier crossover strategy after an interior-point (barrier) solve.
enum class CutDrainMode: uint8_t { count = 0, iteration = 1, all = 2 }
How the SDDP async path drains in-flight cuts after the aggregate-convergence signal fires.
enum class CutSharingMode: uint8_t { none = 0, multicut = 1, markov = 2 }
SDDP cut sharing mode across scenes in the backward pass.
enum class CutType: uint8_t { Optimality = 0, Feasibility }
Type of Benders cut: optimality (standard) or feasibility (elastic filter).
enum class DataFormat: uint8_t { parquet = 0, csv = 1 }
File format for input/output data files.
enum class DirectiveKind: std::uint8_t { RegRange = 0, ReserveProvSum = 1, DailyBudget = 2, HydroFloor = 3, MaxStartsWindow = 4 }
enum class DroppedTermKind: std::uint8_t { suppressed, inactive, prev_first_block, block_omitted, zero_capacity, not_materialised, scope_mismatch }
enum class ElasticFilterMode: uint8_t { single_cut = 0, multi_cut = 1, chinneck = 3, state_repair = 4, farkas_recursive = 5 }
How the elastic filter handles feasibility issues in the backward pass.
enum class ErrorCode: uint8_t { Success = 0, SolverError, InternalError, InvalidInput, FileIOError, Cancelled }
enum class FastSqrtMethod: uint8_t { ieee_halve = 0, newton1 = 1, std_sqrt = 2 }
Fast approximate sqrt method for Ruiz equilibration.
enum class FlowRightMode: std::uint8_t { per_block = 0, stage_average = 1, stage_uniform = 2 }
Time resolution of a FlowRight (flow_mode).
enum class ForwardSamplingMode: uint8_t { persistent = 0, resampled = 1 }
How the SDDP forward pass samples the stochastic scene data.
enum class GasCompressorDrive: uint8_t { gas = 0, electric = 1 }
Driver of a GasCompressor (drive).
enum class GasCompressorFuelModel: uint8_t { none = 0, fixed_fraction = 1, saldarriaga = 2 }
Fuel model of a GasCompressor (fuel_model).
enum class GasLinearization: uint8_t { secant = 0, tangent = 1 }
Linearisation of a weymouth_mode: linearized pipe (linearization).
enum class GasWeymouthMode: uint8_t { radial = 0, linearized = 1, none = 2 }
Pressure-flow model of a GasPipe (weymouth_mode).
enum class GridCell: char { Idle = '.', Forward = 'F', Backward = 'B', Elastic = 'E', Aperture = 'A', Infeasible = 'X' }
Phase grid cell states (ordered by display priority).
enum class HotStartMode: uint8_t { none = 0, keep = 1, append = 2, replace = 3 }
How the SDDP solver handles hot-start and the output cut file.
enum class IntegerCutsMode: uint8_t { none = 0, strengthened = 1 }
How the SDDP backward pass builds optimality cuts on cells whose LP carries integer columns (integer expansion modules, unit-commitment binaries, …).
enum class IntegerDomain: std::uint8_t { Binary = 0, Integer = 1, Relaxed = 2 }
enum class IntegerScope: std::uint8_t { Block = 0, Group = 1, Stage = 2, Phase = 3 }
enum class IntegrityVerdict: int { ok = 0, warn, refuse }
enum class KappaMode: uint8_t { estimate = 0, exact = 1, off = 2 }
How the basis condition number (kappa) is obtained after a solve.
enum class KappaModeSource: int { compiled_default = 0, environment }
Where the default kappa mode came from.
enum class KappaWarningMode: uint8_t { none = 0, warn = 1, save_lp = 2, diagnose = 3 }
Controls warnings when the LP condition number (kappa) exceeds a threshold.
enum class KirchhoffMode: uint8_t { node_angle = 0, cycle_basis = 1 }
Selects the Kirchhoff Voltage Law (KVL) formulation.
enum class LineDirectionMode: uint8_t { off = 0, report = 1, structural = 2 }
Global radial-line detection (model_options.line_direction_mode).
enum class LineDlrLimitMode: uint8_t { replace = 0, min = 1 }
How a dynamic line rating (Line.dlr) combines with the static conductor rating of the line.
enum class LineDlrSolarMode: uint8_t { ghi = 0, none = 1 }
How the DLR heat balance treats the solar_irradiance input.
enum class LineDlrSpanMode: uint8_t { min = 0, rows = 1 }
How the critical spans of a dynamic line rating (Line.dlr) limit the line flow.
enum class LineFlowDirection: uint8_t { both = 0, ab = 1, ba = 2, automatic = 3 }
Allowed flow direction of a line (Line.flow_direction).
enum class LineKvlKind: uint8_t { dc, tie, ac }
How the Kirchhoff assemblers treat one line at one stage.
enum class LineLossesMode: uint8_t { none = 0, linear = 1, piecewise = 2, bidirectional = 3, adaptive = 4, dynamic = 5, piecewise_direct = 6, tangent_signed_flow = 7 }
Selects the mathematical model for transmission line losses.
enum class LineOverloadSlackBound: uint8_t { thermal = 0, ratio = 1, unbounded = 2 }
Upper bound of the overload slack (the overload_penalty band between the normal threshold and the hard cap).
enum class LinePwlLayout: uint8_t { uniform = 0, equal_error = 1, tangent = 2, midpoint = 3 }
Segment-layout strategy for the piecewise-linear loss model.
enum class LineThermalLimitMode: uint8_t { flow = 0, sending = 1, full = 2 }
How a line's thermal limit interacts with its loss variable.
enum class LossAllocationMode: uint8_t { receiver = 0, sender = 1, split = 2 }
How transmission losses are allocated between sender and receiver buses in the nodal power balance equation.
enum class LowMemoryMode: uint8_t { off = 0, compress = 2 }
Low-memory mode for SDDP solver.
enum class LPAlgo: uint8_t { default_algo = 0, primal = 1, dual = 2, barrier = 3, last_algo = 4 }
Enumeration of linear programming solution algorithms.
enum class LpDebugPass: std::uint8_t { forward, backward, aperture }
enum class LpEquilibrationMethod: uint8_t { none = 0, row_max = 1, ruiz = 2 }
LP matrix equilibration method for numerical conditioning.
enum class LpFileFormat: std::uint8_t { lp = 0, mps = 1 }
File format used when an assembled LP model is written to disk.
enum class LpFormatFallback: std::uint8_t { strict = 0, other_format = 1 }
enum class LpNamesLevel: int8_t { none = 0, all = 1 }
LP variable/constraint naming level for matrix assembly.
enum class LpScalesLevel: std::uint8_t { none = 0, summary = 1, full = 2 }
Content of the --lp-scales sidecar written next to --lp-file.
enum class MethodType: uint8_t { monolithic = 0, sddp = 1, cascade = 2 }
Top-level solver selection: monolithic LP, SDDP, or cascade.
enum class MinMaxKind: std::uint8_t { Max, Min }
Kind of min/max expression (F7).
enum class MipStartEffort: uint8_t { check_feasibility = 0, solve_fixed = 1, solve_mip = 2, repair = 3, no_check = 4 }
Effort level applied to an injected MIP-start (warm incumbent).
enum class MissingCutVarMode: uint8_t { skip_coeff = 0, skip_cut = 1 }
How to handle boundary/named cut rows that reference state variables not present in the current model.
enum class MonthType: uint8_t { january = 1, february = 2, march = 3, april = 4, may = 5, june = 6, july = 7, august = 8, september = 9, october = 10, november = 11, december = 12 }
Calendar month (1-based: january=1, december=12).
enum class NetworkModel: uint8_t { dc = 0, lindistflow = 1 }
Power-flow model of the network (model_options.network_model).
enum class OutageReserveMode: uint8_t { none = 0, proportional = 1, exclude = 2 }
How reserve offers react to a Generator.outage_fraction maintenance schedule (model_options.outage_reserve_mode).
enum class OutputFlags: uint8_t { none = 0U, solution = 1U, dual = 2U, reduced_cost = 4U, extras = 8U, all = 15U }
Bitmask controlling which fields the output writer emits.
enum class ParamFileSource: std::uint8_t { absolute, input_directory, working_directory }
Where a resolved solver parameter file was found.
enum class PenaltyClass: uint8_t { Raw = 0, HydroFlow }
How the penalty value on a soft UserConstraint is interpreted before being assigned to the slack column's LP objective coefficient.
enum class PlpCutStatus: uint8_t { cuts_added = 0, holguras = 1, fail = 2 }
enum class PluginCheckMode: int { warning = 0, error }
enum class PluginCheckSource: int { compiled_default = 0, environment, command_line }
Where the effective plugin check mode came from.
enum class PrevStageLink: uint8_t { none = 0, stage = 1, period = 2 }
What a user-constraint <attr>_prev term reads at the FIRST block of a stage whose predecessor stage is in the SAME phase.
enum class PricingMode: std::uint8_t { fixed = 0, relaxed = 1, fast_start = 2 }
Post-MIP pricing method — see the file header.
enum class ProbabilityRescaleMode: uint8_t { none = 0, build = 1, runtime = 2 }
Controls when scenario/scene probabilities are rescaled to sum 1.0.
enum class ProfileOwnerKind: std::uint8_t { Generator = 0, Demand = 1 }
enum class RecoveryMode: uint8_t { none = 0, cuts = 1, full = 2 }
Controls what is recovered from a previous SDDP run.
enum class RelaxInfeasibleAction: uint8_t { stop = 0, warn = 1, feasopt = 2 }
What to do when the initial LP relaxation is infeasible.
enum class ResourceClass: std::uint8_t { cpu = 0, gpu = 1 }
Broad execution class of a task's dominant resource.
enum class RiskMeasure: std::uint8_t { expected = 0, cvar = 1, trim = 2 }
Risk measure applied to the scenario costs of a (scene, phase) LP.
enum class RiskRankBy: std::uint8_t { cost = 0, index = 1 }
How the tail of risk_measure is selected.
enum class RiskTail: std::uint8_t { upper = 0, lower = 1 }
Side of the ranking the tail is taken from.
enum class SDDPPassDirection: int { forward = 0, backward = 1 }
Pass direction for the SDDP scheduler.
enum class SDDPTaskKind: int { lp = 0, non_lp = 1 }
Task kind for the kind field of SDDPTaskKey. LP solves (0) have higher priority than non-LP tasks (1).
enum class SolveMode: uint8_t { monolithic = 0, sequential = 1 }
Monolithic solver execution mode.
enum class SolveOutcome: std::uint8_t { Optimal = 0, Partial = 1, Failed = 2 }
enum class SolverLogMode: uint8_t { nolog = 0, detailed = 1 }
Controls whether and how solver log files are written.
enum class SolverScaling: uint8_t { none = 0, automatic = 1, aggressive = 2 }
Solver-internal scaling strategy.
enum class StartsScope: std::uint8_t { Hour = 0, Day = 1, Week = 2, Horizon = 3 }
enum class StartupTierIntegrality: std::uint8_t { continuous = 0, integer = 1 }
Integrality of the hot / warm / cold startup-tier selectors.
enum class StateVariableLookupMode: uint8_t { warm_start = 0, cross_phase = 1 }
How update_lp elements obtain reservoir/battery volume between phases.
enum class SystemKind: std::uint8_t { forward = 0, aperture = 1 }
enum class TaskPriority: uint8_t { Low = 0, Medium = 1, High = 2, Critical = 3 }
enum class TaskStatus: uint8_t { Success, Failed, Cancelled }
enum class TimeAggWeight: std::uint8_t { Count, Duration }
enum class TimeWindow: std::uint8_t { Stage, Day }
Time window iterated by a sum{...} time-aggregator (piece-4 step 2).
enum class TinyReactanceMode: uint8_t { tie = 0, dc = 1 }
What to do with a line whose reactance is set but is 0 or has a per-unit |X/V²| below model_options.dc_line_reactance_threshold (default 1e-6).
enum class TransitionIntegrality: std::uint8_t { automatic = 0, continuous = 1, binary = 2 }
Integrality of the commitment startup / shutdown columns.

Typedefs

using Active = IntBoolFieldSched
using ActiveSched = Schedule<IntBool, StageUid>
using AllowancePoolLPId = ObjectId<class AllowancePoolLP>
using AllowancePoolLPSId = ObjectSingleId<class AllowancePoolLP>
using AmmoniaNodeLPId = ObjectId<class AmmoniaNodeLP>
using AmmoniaNodeLPSId = ObjectSingleId<class AmmoniaNodeLP>
using AmmoniaStorageLPId = ObjectId<class AmmoniaStorageLP>
using AmmoniaStorageLPSId = ObjectSingleId<class AmmoniaStorageLP>
using AmplActiveFn = std::optional<bool>(*)(const SystemContext&sc, Uid element_uid, const StageLP&stage)
using AmplCompoundMap = flat_map<AmplCompoundKey, std::vector<AmplCompoundLeg>>
Compound-attribute registry: (class, compound_name) -> legs.
using AmplElementMetadata = std::vector<std::pair<std::string_view, AmplMetadataValue>>
using AmplElementMetadataMap = flat_map<AmplMetadataKey, AmplElementMetadata>
using AmplElementNameKey = std::pair<std::string_view, std::string_view>
using AmplElementNameMap = flat_map<AmplElementNameKey, Uid>
Name registry: (class_name, name) -> element uid.
using AmplIterCallback = void(*)(void*state, Uid uid)
using AmplIterFn = void(*)(const SystemContext&sc, void*state, AmplIterCallback cb)
using AmplIterMap = flat_map<std::string_view, AmplIterFn>
Iterator dispatch table: class_name -> iterator.
using AmplMetadataValue = std::variant<std::string, double>
using AmplParamFn = std::optional<double>(*)(const SystemContext&sc, Uid element_uid, StageUid stage_uid, BlockUid block_uid)
using AmplParamMap = flat_map<AmplParamKey, AmplParamFn>
Parameter dispatch table: (class, attribute) -> resolver.
using AmplResolveCache = std::unordered_map<const ElementRef*, ElementRefResolution>
using AmplScalarMap = flat_map<AmplScalarKey, double>
using AmplVariableMap = std::unordered_map<AmplVariableKey, AmplVariable, AmplVariableKeyHash>
Variable registry: (class_name, uid, attribute, scenario, stage) -> cols.
using ApertureChunkResult = std::vector<ApertureCutResult>
using ApertureChunkSubmitFunc = std::function<std::future<ApertureChunkResult>( const std::function<ApertureChunkResult()>&task)>
using ApertureContext = std::tuple<SceneUid, PhaseUid, ApertureUid, int>
using ApertureIndex = StrongIndexType<Aperture>
using ApertureUid = ScenarioUid
using ApertureValueFn = std::function<std::optional<double>(StageUid, BlockUid)>
template<typename Type>
using Array = std::vector<Type>
Array type template for consistent vector usage.
using ArrowArray = std::shared_ptr<arrow::Array>
using ArrowChunkedArray = std::shared_ptr<arrow::ChunkedArray>
using ArrowColumnResult = arrow::Result<ArrowChunkedArray>
using ArrowField = std::shared_ptr<arrow::Field>
using ArrowIndex = int64_t
using ArrowPresentMask = std::uint32_t
using ArrowTable = std::shared_ptr<arrow::Table>
using BatteryLPId = ObjectId<class BatteryLP>
using BatteryLPSId = ObjectSingleId<class BatteryLP>
template<typename Value = Index>
using BIndexHolder = IndexHolder0<BlockUid, Value>
using block_factor_matrix_t = gtopt::MultiArray2D<std::vector<double>>
using BlockContext = std::tuple<ScenarioUid, StageUid, BlockUid>
using BlockExContext = std::tuple<ScenarioUid, StageUid, BlockUid, int>
using BlockIndex = StrongPositionIndexType<Block>
using BlockUid = UidOf<Block>
using Bool = bool
Boolean type for logical conditions.
using BoolFieldSched = FieldSched<Bool>
using BoolOrName = std::variant<bool, Name>
using BusLPId = ObjectId<class BusLP>
using BusLPSId = ObjectSingleId<class BusLP>
using CarrierConverterLPId = ObjectId<class CarrierConverterLP>
using CarrierConverterLPSId = ObjectSingleId<class CarrierConverterLP>
using col_name_map_t = std::unordered_map<std::string, ColIndex, LabelHash, std::equal_to<>>
Column (variable) name → strong column index map.
using ColIndex = StrongIndexType<SparseCol>
Type alias for column index.
using CommitmentPeriodValue = std::variant<Real, Name>
using DecisionVariableLPSId = ObjectSingleId<class DecisionVariableLP>
using DemandLPId = ObjectId<DemandLP>
using DemandLPSId = ObjectSingleId<DemandLP>
using EmissionLPSId = ObjectSingleId<EmissionLP>
using EmissionSourceLPSId = ObjectSingleId<EmissionSourceLP>
using EmissionZoneLPSId = ObjectSingleId<EmissionZoneLP>
template<typename Type, typename Vector = std::vector<Type>>
using FieldSched = std::variant<Type, Vector, FileSched>
template<typename Type, typename Vector2 = std::vector<std::vector<Type>>>
using FieldSched2 = FieldSched<Type, Vector2>
template<typename Type, typename Vector3 = std::vector<std::vector<std::vector<Type>>>>
using FieldSched3 = FieldSched<Type, Vector3>
using FileSched = String
template<typename key_type, typename value_type>
using flat_map = boost::container::flat_map<key_type, value_type>
using FlowLPSId = ObjectSingleId<class FlowLP>
Single-ID alias for referencing a FlowLP in other LP elements.
using FlowRightLPSId = ObjectSingleId<class FlowRightLP>
using FuelLPSId = ObjectSingleId<FuelLP>
using FutureCostLPSId = ObjectSingleId<class FutureCostLP>
using GasCompressorLPId = ObjectId<class GasCompressorLP>
using GasCompressorLPSId = ObjectSingleId<class GasCompressorLP>
using GasDemandLPId = ObjectId<class GasDemandLP>
using GasDemandLPSId = ObjectSingleId<class GasDemandLP>
using GasNodeLPId = ObjectId<class GasNodeLP>
using GasNodeLPSId = ObjectSingleId<class GasNodeLP>
using GasPipeLPId = ObjectId<class GasPipeLP>
using GasPipeLPSId = ObjectSingleId<class GasPipeLP>
using GasSupplyLPId = ObjectId<class GasSupplyLP>
using GasSupplyLPSId = ObjectSingleId<class GasSupplyLP>
using GasTurbineLPId = ObjectId<class GasTurbineLP>
using GasTurbineLPSId = ObjectSingleId<class GasTurbineLP>
using GeneratorLPId = ObjectId<GeneratorLP>
using GeneratorLPSId = ObjectSingleId<GeneratorLP>
using GroupUid = Uid
template<typename Value = Index>
using GSTBIndexHolder = tuple_map_t<std::tuple<ScenarioUid, StageUid, BlockUid>, Value>
template<typename Value = Index>
using GSTIndexHolder = tuple_map_t<std::tuple<ScenarioUid, StageUid>, Value>
using HydrogenDemandLPId = ObjectId<class HydrogenDemandLP>
using HydrogenDemandLPSId = ObjectSingleId<class HydrogenDemandLP>
using HydrogenNodeLPId = ObjectId<class HydrogenNodeLP>
using HydrogenNodeLPSId = ObjectSingleId<class HydrogenNodeLP>
using HydrogenStorageLPId = ObjectId<class HydrogenStorageLP>
using HydrogenStorageLPSId = ObjectSingleId<class HydrogenStorageLP>
using Id = std::pair<Uid, Name>
Combined identifier with both numeric ID and name.
using Index = std::int32_t
Index type for large-scale sparse matrices and arrays.
template<typename key_type, typename value_type>
using index_map_t = gtopt::flat_map<key_type, value_type>
template<typename FirstIndex, typename Value = Index>
using IndexHolder0 = gtopt::flat_map<FirstIndex, Value>
template<typename FirstIndex, typename Value = Index>
using IndexHolder1 = index_map_t<FirstIndex, Value>
template<typename FirstIndex, typename SecondIndex, typename Value = Index>
using IndexHolder2 = tuple_map_t<std::tuple<FirstIndex, SecondIndex>, Value>
template<typename FirstIndex, typename SecondIndex, typename ThirdIndex, typename Value = Index>
using IndexHolder3 = tuple_map_t<std::tuple<FirstIndex, SecondIndex>, IndexHolder0<ThirdIndex, Value>>
using IniData = std::map<std::string, std::map<std::string, std::string>>
Parsed INI sections: section name → {key → value}.
using Int = int
Integer type for counting and discrete quantities.
using IntBool = std::int32_t
Integer boolean for space-efficient storage.
using IntBoolFieldSched = FieldSched<IntBool>
using IntBoolFieldSched2 = FieldSched2<IntBool>
using IntegrationRows = std::vector<std::vector<IntegrationTerm>>
using IntFieldSched = FieldSched<Int>
using IterationContext = std::tuple<SceneUid, PhaseUid, IterationUid, int>
using IterationIndex = StrongIndexType<IterationTag>
using IterationUid = UidOf<Iteration>
using JunctionLPId = ObjectId<class JunctionLP>
using JunctionLPSId = ObjectSingleId<class JunctionLP>
using LineLPSId = ObjectSingleId<LineLP>
using LngTerminalLPId = ObjectId<class LngTerminalLP>
using LngTerminalLPSId = ObjectSingleId<class LngTerminalLP>
using lp_collection_ptrs_t = std::array<const void*, lp_type_count_v>
Array of const void* pointers, one slot per LP element type.
using lp_element_types_t = std::tuple<BusLP, DemandLP, GeneratorLP, LineLP, GeneratorProfileLP, DemandProfileLP, CapacityProfileLP, BatteryLP, ThermalNodeLP, ThermalStorageLP, HydrogenNodeLP, HydrogenStorageLP, HydrogenDemandLP, AmmoniaNodeLP, AmmoniaStorageLP, CarrierConverterLP, AllowancePoolLP, ReserveZoneLP, ReserveProvisionLP, CommitmentLP, FuelLP, EmissionLP, EmissionZoneLP, EmissionSourceLP, LineCommitmentLP, ConverterLP, InertiaZoneLP, InertiaProvisionLP, JunctionLP, WaterwayLP, FlowLP, ReservoirLP, ReservoirSeepageLP, ReservoirDischargeLimitLP, TurbineLP, PumpLP, ReservoirProductionFactorLP, FlowRightLP, VolumeRightLP, LngTerminalLP, GasNodeLP, GasSupplyLP, GasDemandLP, GasPipeLP, GasCompressorLP, GasTurbineLP, DecisionVariableLP, PlantLP, UserConstraintLP, UserModelLP, FutureCostLP>
Ordered tuple of all LP element types.
using LpContext = std::variant<std::monostate, StageContext, BlockContext, BlockExContext, ScenePhaseContext, IterationContext, ApertureContext, PhaseContext>
template<typename Type, typename Tuple>
using mvector_traits_auto = mvector_traits<Type, Tuple, std::tuple_size_v<Tuple>>
using Name = std::string
Name type for entity identification.
using NameView = std::string_view
String view type for non-owning name references.
using OptActive = OptIntBoolFieldSched
using OptActiveSched = OptSchedule<IntBool, StageUid>
using OptBool = std::optional<Bool>
Optional boolean type.
using OptBoolFieldSched = std::optional<BoolFieldSched>
using OptBoolOrName = std::optional<BoolOrName>
using OptCommitmentPeriod = std::optional<CommitmentPeriodValue>
using OptConstraintDirective = std::optional<ConstraintDirective>
Optional directive carried on every UserConstraint.
using OptInflowModel = std::optional<InflowModel>
using OptInt = std::optional<Int>
Optional integer type.
using OptIntBool = std::optional<IntBool>
Optional integer boolean type.
using OptIntBoolFieldSched = std::optional<IntBoolFieldSched>
using OptIntBoolFieldSched2 = std::optional<IntBoolFieldSched2>
using OptIntFieldSched = std::optional<IntFieldSched>
using Options = PlanningOptions
Backward-compatibility alias (deprecated — use PlanningOptions).
using OptionsLP = PlanningOptionsLP
Backward-compatibility alias (deprecated — use PlanningOptionsLP).
using OptLineDlr = std::optional<LineDlr>
using OptName = std::optional<Name>
Optional name type.
using OptReal = std::optional<Real>
Optional real number type.
using OptRealFieldSched = std::optional<RealFieldSched>
using OptRealFieldSched2 = std::optional<RealFieldSched2>
using OptRealFieldSched3 = std::optional<RealFieldSched3>
using OptSceneIndex = std::optional<SceneIndex>
using OptSingleId = std::optional<SingleId>
using OptStageIndex = std::optional<StageIndex>
using OptStartsScope = std::optional<StartsScopeValue>
using OptSTBRealFieldSched = OptRealFieldSched3
using OptSTBRealSched = OptSchedule<Real, ScenarioUid, StageUid, BlockUid>
using OptSTRealFieldSched = OptRealFieldSched2
using OptSTRealSched = OptSchedule<Real, ScenarioUid, StageUid>
using OptTBIntBoolFieldSched = OptIntBoolFieldSched2
using OptTBIntBoolSched = OptSchedule<IntBool, StageUid, BlockUid>
using OptTBRealFieldSched = OptRealFieldSched2
using OptTBRealSched = OptSchedule<Real, StageUid, BlockUid>
using OptTBUidFieldSched = OptUidFieldSched2
using OptTBUidSched = OptUidFieldSched2
using OptTBUidSchedRT = OptSchedule<Uid, StageUid, BlockUid>
using OptTRealFieldSched = OptRealFieldSched
using OptTRealSched = OptSchedule<Real, StageUid>
using OptUid = std::optional<Uid>
Optional unique identifier type.
using OptUidFieldSched = std::optional<UidFieldSched>
using OptUidFieldSched2 = std::optional<UidFieldSched2>
using PhaseContext = std::tuple<SceneUid, PhaseUid, Uid>
using PhaseIndex = StrongPositionIndexType<Phase>
Strongly-typed index for Phase objects in collections.
using PhaseStageIndex = StrongPositionIndexType<PhaseStageTag>
using PhaseUid = UidOf<Phase>
Strongly-typed unique identifier for Phase objects.
using PlantLPSId = ObjectSingleId<class PlantLP>
using PumpLPSId = ObjectSingleId<class PumpLP>
Single-ID alias for referencing a PumpLP in other LP elements.
using Real = double
Real number type for physical quantities and costs.
using RealFieldSched = FieldSched<Real>
using RealFieldSched2 = FieldSched2<double>
using RealFieldSched3 = FieldSched3<double>
using ReservoirLPId = ObjectId<class ReservoirLP>
using ReservoirLPSId = ObjectSingleId<class ReservoirLP>
using row_name_map_t = std::unordered_map<std::string, RowIndex, LabelHash, std::equal_to<>>
Row (constraint) name → strong row index map.
using RowIndex = StrongIndexType<SparseRow>
Type alias for row index.
using scenario_stage_factor_matrix_t = gtopt::MultiArray2D<double>
using ScenarioIndex = StrongPositionIndexType<struct Scenario>
using ScenarioUid = UidOf<Scenario>
using SceneIndex = StrongPositionIndexType<Scene>
using ScenePhaseContext = std::tuple<SceneUid, PhaseUid>
using SceneScenarioIndex = StrongPositionIndexType<SceneScenarioTag>
using SceneUid = UidOf<Scene>
using SDDPIterationCallback = std::function<bool(const SDDPIterationResult&result)>
using SDDPTaskKey = std::tuple<IterationIndex, int, int, SDDPTaskKind>
SDDP solver task priority key.
using SeedCommitmentMap = std::unordered_map<std::uint64_t, double>
using SingleId = std::variant<Uid, Name>
using Size = std::size_t
Size type for container dimensions and indices.
using solver_backend_factory_fn = SolverBackend*(*)(const char*solver_name)
Plugin entry-point function type: creates a SolverBackend by solver name.
using solver_plugin_abi_version_fn = int(*)()
using solver_plugin_build_info_fn = int(*)(const char*solver_name, SolverBuildInfo*out)
using solver_plugin_build_tag_fn = const char*(*)()
gtopt_plugin_build_tag: NUL-terminated build tag of the plugin.
using solver_plugin_infinity_fn = double(*)(const char*solver_name)
using solver_plugin_linked_libraries_fn = int(*)(int*struct_version, const SolverLinkedLibrary**out)
using solver_plugin_name_fn = const char*(*)()
Plugin name function type: returns the plugin name.
using solver_plugin_names_fn = const char*const *(*)()
Plugin solver-list function type: returns null-terminated array of names.
using solver_plugin_resource_desc_fn = int(*)(const char*solver_name, SolverResourceDescriptor*out)
using solver_plugin_version_pin_fn = int(*)(const char*solver_name, SolverVersionPin*out)
using SolverCfgPairs = std::vector<std::pair<std::string, std::string>>
using SparseEntries = std::vector<SparseEntry>
using SparseEntry = std::pair<uint32_t, double>
using stage_factor_matrix_t = std::vector<double>
using StageContext = std::tuple<ScenarioUid, StageUid>
using StageIndex = StrongPositionIndexType<Stage>
using StageUid = UidOf<Stage>
using StartsScopeValue = std::variant<Int, Name>
template<typename Value = Index>
using STBIndexHolder = IndexHolder3<ScenarioUid, StageUid, BlockUid, Value>
using STBRealFieldSched = RealFieldSched3
using STBRealSched = Schedule<Real, ScenarioUid, StageUid, BlockUid>
template<typename Value = Index>
using STIndexHolder = IndexHolder2<ScenarioUid, StageUid, Value>
using STRealFieldSched = RealFieldSched2
using STRealSched = Schedule<Real, ScenarioUid, StageUid>
using String = std::string
String type for general textual data.
template<typename Type>
using StrongIndexType = strong::type<Index, Type, strong::formattable, strong::regular, strong::hashable, strong::arithmetic, strong::bicrementable, strong::implicitly_convertible_to<Index>>
Strong type for count-like indices (LP rows, LP columns).
template<typename Type>
using StrongPositionIndexType = strong::type<Index, Type, strong::formattable, strong::regular, strong::ordered, strong::hashable, strong::bicrementable, strong::boolean, strong::implicitly_convertible_to<Index>>
Strong type for positional indices into a logical sequence (scene, phase, stage, scenario, block).
using TaskRequirements = BasicTaskRequirements<>
using TBIntBoolFieldSched = IntBoolFieldSched2
using TBIntBoolSched = Schedule<IntBool, StageUid, BlockUid>
using TBRealFieldSched = RealFieldSched2
using TBRealSched = Schedule<Real, StageUid, BlockUid>
using TBUidFieldSched = UidFieldSched2
using TBUidSched = UidFieldSched2
using TBUidSchedRT = Schedule<Uid, StageUid, BlockUid>
using ThermalNodeLPId = ObjectId<class ThermalNodeLP>
using ThermalNodeLPSId = ObjectSingleId<class ThermalNodeLP>
using ThermalStorageLPId = ObjectId<class ThermalStorageLP>
using ThermalStorageLPSId = ObjectSingleId<class ThermalStorageLP>
template<typename Value = Index>
using TIndexHolder = IndexHolder1<StageUid, Value>
using TRealFieldSched = RealFieldSched
using TRealSched = Schedule<Real, StageUid>
template<typename key_type, typename value_type>
using tuple_map_t = gtopt::flat_map<key_type, value_type>
using TurbineLPSId = ObjectSingleId<class TurbineLP>
Single-ID alias for referencing a TurbineLP in other LP elements.
using Uid = uid_t
Unique identifier type.
using uid_t = std::int32_t
Base type for unique identifiers.
using UidFieldSched = FieldSched<Uid>
using UidFieldSched2 = FieldSched2<Uid>
using UserModelLPSId = ObjectSingleId<class UserModelLP>
using UserParamMap = std::unordered_map<Name, UserParam>
A collection of named parameters, keyed by name for fast lookup.
using VolumeRightLPId = ObjectId<class VolumeRightLP>
using VolumeRightLPSId = ObjectSingleId<class VolumeRightLP>
using WaterwayLPId = ObjectId<class WaterwayLP>
using WaterwayLPSId = ObjectSingleId<class WaterwayLP>

Functions

auto accumulated_groups(std::span<const double> cells, double period) -> std::vector<std::size_t>
template<std::ranges::range Range>
auto active(Range&& range) -> auto noexcept
auto active_future_cost(const PlanningLP& planning_lp) -> const FutureCost*
template<typename SystemContextT, typename IdT, typename StageT>
auto active_ref(const SystemContextT& sc, const IdT& id, const StageT& stage) -> const std::remove_cvref_t<decltype(sc.element(id))>*
auto active_user_alpha_uid(const PlanningLP& planning_lp) -> std::optional<Uid> noexcept
auto add_cut_row(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, CutType cut_type, const SparseRow& cut, double eps = 0.0) -> RowIndex
auto add_cvar_to_lp(LinearProblem& lp, std::span<const CvarScenarioInput> scenarios, double alpha, double weight, double var_scale, SceneUid scene_uid, PhaseUid phase_uid) -> CvarLayout
auto add_power_based_rows(const PowerBasedUnit& unit, LinearProblem& lp) -> PowerBasedResult
template<std::ranges::range Range, typename Pred>
auto all_of(Range&& range, Pred&& pred) -> bool
Checks if all elements in range satisfy predicate.
auto alpha_col_weights(const SimulationLP& sim, CutSharingMode cut_sharing, const MarkovChainConfig* markov, SceneIndex scene_index, std::size_t n_alpha, bool terminal_phase, std::size_t terminal_phi_count = 0) -> std::vector<double>
auto alpha_cols_on_cell(const SimulationLP& sim, SceneIndex scene_index, PhaseIndex phase_index, SystemKind kind = SystemKind::forward) -> std::vector<std::pair<ColIndex, Uid>>
auto ampl_metadata_uid(Uid uid) -> AmplMetadataValue noexcept
auto annual_discount_factor(double annual_discount_rate, double time_hours) -> double noexcept
auto annuity_from_overnight(double overnight_cost, double rate, std::optional<double> life) -> double noexcept
Annuity [$/unit-year] of an overnight cost [$/unit].
void apply_alpha_floor(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, SystemKind kind = SystemKind::forward, bool bound_above = false)
void apply_aperture_chunk_override(SDDPOptions& opts, std::optional<ApertureChunkMode> mode, std::optional<int> size) noexcept
void apply_cli_options(Planning& planning, const MainOptions& opts)
Apply command-line options from a MainOptions struct to a Planning object.
void apply_cli_options(Planning& planning, const std::optional<bool>& use_single_bus, const std::optional<bool>& use_kirchhoff, const std::optional<std::string>& input_directory, const std::optional<std::string>& input_format, const std::optional<std::string>& output_directory, const std::optional<std::string>& output_format, const std::optional<std::string>& output_compression, const std::optional<std::string>& cut_directory = {}, const std::optional<std::string>& log_directory = {}, const std::optional<int>& sddp_max_iterations = {}, const std::optional<double>& sddp_convergence_tol = {}, const std::optional<double>& sddp_elastic_penalty = {}, const std::optional<std::string>& sddp_elastic_mode = {}, const std::optional<int>& sddp_num_apertures = {}, const std::optional<bool>& lp_debug = {}, const std::optional<bool>& lp_error = {}, const std::optional<std::string>& lp_compression = {}, const std::optional<double>& lp_coeff_ratio_threshold = {})
Apply command-line options to a Planning object.
void apply_config_file_defaults(Planning& planning, const MainOptions& conf)
Apply the .gtopt.conf planning-level defaults to planning.
void apply_future_cost_config(const FutureCost& fc, SDDPOptions& opts)
auto apply_mip_start(LinearInterface& li, const SolverOptions& base_opts, const MipStartOptions& opts, std::span<const CommitmentRunInfo> commitments = {}, std::span<const PeakInjectionInfo> injections = {}, const FlatLinearProblem* flat_lp = nullptr) -> std::expected<MipStartReport, Error>
auto apply_row_max_equilibration(std::span<const std::int32_t> matind, std::span<double> matval, std::span<double> rowlb, std::span<double> rowub, double infinity, std::span<const std::int32_t> rowpin = {}) -> std::vector<double>
auto apply_ruiz_scaling(std::span<const std::int32_t> matbeg, std::span<const std::int32_t> matind, std::span<double> matval, std::span<double> rowlb, std::span<double> rowub, std::span<double> collb, std::span<double> colub, std::span<double> objval, std::span<double> col_scales, std::span<const std::int32_t> colpin, double infinity, FastSqrtMethod sqrt_method, int max_iterations, double tolerance, std::span<const std::int32_t> rowpin = {}) -> std::vector<double>
auto apply_set_options(Planning& planning, const std::vector<std::string>& set_options) -> bool
auto apply_tail_weights_to_lp(LinearProblem& lp, std::span<const CvarScenarioInput> scenarios, std::span<const double> risk_probability, RiskMeasure measure, RiskTail tail, double alpha, double weight, SceneUid scene_uid, PhaseUid phase_uid) -> CvarLayout
void apply_terminal_alpha_floor(PlanningLP& planning_lp, SceneIndex scene_index)
template<char sep = '_'>
auto as_label() -> auto noexcept
Creates an empty label string.
template<typename Sep, typename... Args>
auto as_label(Args && ... args) -> std::string
No-separator variant of as_label().
template<char sep = '_', typename... Args>
auto as_label(Args && ... args) -> std::string
Creates a concatenated label from multiple arguments.
template<char sep = '_'>
void as_label_into(std::string& result) noexcept
Clears and writes a label into an existing string buffer.
template<typename Sep, typename... Args>
void as_label_into(std::string& result, Args && ... args)
No-separator variant of as_label_into().
template<char sep = '_', typename... Args>
void as_label_into(std::string& result, Args && ... args)
Writes a concatenated label into an existing string buffer.
template<typename... Args>
auto as_string(const std::tuple<Args...>& t) -> std::string
template<typename SystemLPT>
auto average_volume_from_cache(const SystemLPT& sys, const ScenarioLP& scenario, const StageLP& stage, const ReservoirRefCache& rc) -> Real
auto axis_uses_reservoir(BoundRuleAxis axis) -> bool noexcept
Whether this axis depends on a reservoir reference.
void bound_alpha(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, SystemKind kind = SystemKind::forward)
void bound_alpha_for_cut(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, const SparseRow& cut, SystemKind kind = SystemKind::forward)
void bound_user_alpha(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, Uid user_alpha_uid, SystemKind kind = SystemKind::forward)
auto boundary_cut_coeff_stats(const std::string& filepath) -> flat_map<std::string, BoundaryCutCoeffStats>
auto boundary_cut_max_avg_coeff(const std::string& filepath) -> double
auto boundary_cut_scale_alpha(const PlanningLP& planning_lp, const std::string& boundary_cuts_file, double option_scale_alpha) -> double
auto boundary_cut_scene_count(const std::string& filepath) -> std::size_t
auto build_benders_cut_physical(ColIndex alpha_col, std::span<const StateVarLink> links, const LinearInterface& rc_source, double objective_value_physical, double cut_coeff_eps = 0.0) -> SparseRow
auto build_benders_cut_physical(ColIndex alpha_col, std::span<const StateVarLink> links, double objective_value_physical, double scale_objective, double cut_coeff_eps = 0.0) -> SparseRow
auto build_benders_cut_physical(ColIndex alpha_col, std::span<const StateVarLink> links, std::span<const double> reduced_costs_physical, std::span<const double> trial_values_physical, double objective_value_physical, double cut_coeff_eps = 0.0) -> SparseRow
auto build_effective_apertures(std::span<const Aperture> aperture_defs, std::span<const Uid> phase_apertures) -> std::vector<ApertureEntry>
auto build_farkas_recursive_cut(ElasticSolveResult& elastic, std::span<const StateVarLink> links, const LpContext& context, double fact_eps) -> PlpFeasibilityCuts
auto build_feasibility_cut(const LinearInterface& li, ColIndex alpha_col, std::span<const StateVarLink> links, double penalty, const SolverOptions& opts, double scale_alpha = 1.0, double scale_objective = 1.0) -> std::optional<FeasibilityCutResult>
auto build_feasibility_cut_physical(std::span<const StateVarLink> links, std::span<const RelaxedVarInfo> link_infos, LinearInterface& rc_source, double cut_coeff_eps, int niter) -> SparseRow
auto build_info() -> BuildInfo noexcept
auto build_iteration_status_json(const std::vector<SDDPIterationResult>& results, double elapsed_seconds, const SolverStatusSnapshot& snapshot) -> std::string
auto build_multi_cuts(ElasticSolveResult& elastic, std::span<const StateVarLink> links, const LpContext& context, double cut_coeff_eps, int niter) -> std::vector<SparseRow>
auto build_phase_uid_map(const PlanningLP& planning_lp) -> flat_map<PhaseUid, PhaseIndex>
auto build_plp_feasibility_cuts(ElasticSolveResult& elastic, std::span<const StateVarLink> links, const LpContext& context, double fact_eps) -> PlpFeasibilityCuts
auto build_scene_uid_map(const PlanningLP& planning_lp) -> flat_map<SceneUid, SceneIndex>
auto build_solve_and_output(Planning&& planning, const MainOptions& opts) -> std::expected<int, std::string>
auto build_strengthened_benders_cut(ColIndex alpha_col, std::span<const StateVarLink> links, const LinearInterface& target_li, double cut_coeff_eps, const SolverOptions& lp_opts, const SolverOptions& mip_opts) -> std::optional<StrengthenedCutResult>
auto build_synthetic_apertures(std::span<const ScenarioLP> all_scenarios, std::ptrdiff_t n_apertures) -> Array<Aperture>
auto build_table_path(std::string_view input_dir, std::string_view cname, std::string_view fname) -> std::filesystem::path
Build the filesystem path for an input table.
template<typename SystemContextT>
auto build_time_reservoir_volume(const SystemContextT& sc, const ScenarioLP& scenario, const StageLP& stage, const ReservoirLP& rsv) -> Real
auto cached_sibling_param_file(const std::optional<std::string>& param_file, std::string_view sibling_name) -> const SolverCfgPairs*
Cached pairs of a sibling file next to param_file.
auto cached_solver_param_file(const std::filesystem::path& path) -> const SolverCfgPairs*
Once-per-process cached parse_solver_param_file.
auto canonicalize_json_keys(std::string_view json_text) -> std::string
Convenience overload using the process-wide singleton.
auto canonicalize_json_keys(std::string_view json_text, const NamesRegistry& registry) -> std::string
auto canonicalize_json_keys(std::string_view json_text, const NamesRegistry& registry, std::string_view enforce_dialect) -> std::string
auto canonicalize_json_keys(std::string_view json_text, std::string_view enforce_dialect) -> std::string
Convenience overload using the process-wide singleton + dialect enforcement.
auto capital_recovery_factor(double rate, std::optional<double> life) -> double noexcept
auto cast_to_double_array(const std::shared_ptr<arrow::Array>& chunk) -> std::shared_ptr<arrow::DoubleArray>
Cast an Arrow array chunk to DoubleArray, handling float32 widening.
auto cast_to_int32_array(const std::shared_ptr<arrow::Array>& chunk) -> std::shared_ptr<arrow::Int32Array>
auto cell_groups(std::span<const double> cells, double period) -> std::vector<std::size_t>
auto check_all_solvers(bool verbose = false) -> int
Run the test suite against every USABLE solver.
void check_model_sanity(ValidationResult& result, const Planning& planning)
Data-quality (sanity) warnings — never errors.
auto check_plugin_build_id(std::string_view plugin, std::optional<std::string_view> manifest_id, std::optional<std::string_view> file_id, const PluginIntegrityPolicy& policy) -> IntegrityDecision
auto check_plugin_build_tag(std::string_view plugin, std::string_view host_tag, std::optional<std::string_view> plugin_tag, const PluginIntegrityPolicy& policy) -> IntegrityDecision
auto check_runpath_shadowing(std::string_view solver, const std::filesystem::path& loaded_library, const std::filesystem::path& runpath_library, std::string_view ld_library_path, const PluginIntegrityPolicy& policy) -> IntegrityDecision
auto check_solver_library_identity(std::string_view solver, const std::vector<LinkedLibraryRecord>* records, const LoadedLibraryIdentity& loaded, bool statically_linked, const VersionPinOverrides& pin_overrides, const PluginIntegrityPolicy& policy) -> IntegrityDecision
auto check_solver_version(std::string_view solver, const SolverVersion& compiled, const SolverVersion& runtime, bool statically_linked, std::string_view library_path, const PluginIntegrityPolicy& policy) -> IntegrityDecision
auto check_solver_version_pin(std::string_view solver, const SolverVersion& pinned, const SolverVersion& runtime, std::string_view library_path, const VersionPinOverrides& overrides, const PluginIntegrityPolicy& policy) -> IntegrityDecision
auto chinneck_filter_solve(const LinearInterface& li, std::span<const StateVarLink> links, double penalty, const SolverOptions& opts, double slack_tol = 1e-6) -> std::optional<ElasticSolveResult>
auto classify_aperture_failure(int status, double solve_s, double timeout_s) -> ApertureFailureKind noexcept
auto classify_dropped_term(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const ElementRef& ref, bool suppressed) -> DroppedTermKind
Classify a known element reference that produced no column.
auto classify_error_exit_code(std::string_view error) -> int noexcept
Classify an error string into an exit code.
auto classify_line_reactance(std::optional<double> reactance, double voltage, double threshold, TinyReactanceMode mode) -> LineKvlKind noexcept
Classify a line's stage reactance for KVL assembly.
auto classify_solve_outcome(const std::expected<int, Error>& result) -> SolveOutcome noexcept
void clear_flat_lp_vectors(FlatLinearProblem& flp)
void close_producing_col(LinearProblem& lp, ColIndex col)
Close the producing (positive) direction of column col.
void close_producing_cols(LinearProblem& lp, const BIndexHolder<ColIndex>& cols)
Close the producing direction of every column in cols.
auto codec_name(CompressionCodec codec) -> std::string_view noexcept
Return the name of the codec as a string.
template<std::ranges::sized_range R>
auto col_index_size(const R& r) -> ColIndex noexcept
Build a ColIndex from the size of any sized range.
auto col_scale_cost(double scale) -> auto noexcept
auto col_scale_sol(double scale) -> auto noexcept
auto collect_sum_cols(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const SumElementRef& sum_ref, double base_coeff, SparseRow& row, const LinearProblem& lp, std::vector<UnreachableSumElement>* unreachable = nullptr) -> double
Collect (coefficient, ColIndex) pairs for a SumElementRef.
auto committed_pmin(const CommitmentLP* cmt, const GeneratorLP& gen, StageUid stage_uid, BlockUid block_uid) -> double
auto committed_pmin(const CommitmentLP* cmt, const GeneratorLP& gen, StageUid stage_uid, BlockUid block_uid) -> double
auto compiled_default_kappa_mode() -> KappaMode noexcept
auto compress(std::span<const char> data, CompressionCodec codec) -> std::vector<char>
auto compress_buffer(std::span<const char> data, CompressionCodec codec) -> CompressedBuffer
auto compress_flat_lp(FlatLinearProblem& flp, CompressionCodec codec, FlatLpDedupRegistry* registry = nullptr, const std::string& dedup_key = {}) -> CompressedBuffer
auto compute_auto_aperture_chunk_size(int max_apertures_per_phase, int n_active_scenes, int n_physical_cores, double parallel_factor = 2.0) -> int noexcept
auto compute_boundary_gap_diagnostics(double upper_bound, double lower_bound, double terminal_future_cost, double alpha_offset, double expected_abs_opex, bool terminal_in_ub) -> BoundaryGapDiagnostics noexcept
auto compute_convergence_gap(double upper_bound, double lower_bound) -> double noexcept
auto compute_lp_fingerprint(const StableVector<SparseCol>& cols, const StableVector<SparseRow>& rows) -> LpFingerprint
Same, from LinearProblem's stable row / column storage.
auto compute_lp_fingerprint(const std::vector<SparseCol>& cols, const std::vector<SparseRow>& rows) -> LpFingerprint
auto compute_row_type_stats(std::span<const double> matval, std::span<const FlatLinearProblem::index_t> matind, std::span<const std::string> rownm, std::size_t nrows) -> std::vector<FlatLinearProblem::RowTypeStatsEntry>
auto compute_scene_weights(std::span<const SceneLP> scenes, std::span<const uint8_t> scene_feasible, ProbabilityRescaleMode rescale_mode = ProbabilityRescaleMode::runtime) -> std::vector<double>
auto context_type_name(const LpContext& context) -> std::string_view
template<typename Collections>
auto count_all_elements(Collections&& collections) -> auto
Counts the total number of active elements across all collections.
auto cpu_resource_descriptor() -> SolverResourceDescriptor
Convenience: a default (CPU) descriptor for backends that export nothing.
auto create_exclusive_file(const std::filesystem::path& path) -> bool noexcept
auto csv_read_table(const std::filesystem::path& fpath) -> std::expected<ArrowTable, std::string>
Read an Arrow table from a CSV file.
auto decanonicalize_json_keys(std::string_view json_text, const NamesRegistry& registry, std::string_view dialect) -> std::string
auto decanonicalize_json_keys(std::string_view json_text, std::string_view dialect) -> std::string
Convenience overload using the process-wide singleton.
auto decision_variable_scope_restriction(const DecisionVariable& dv) -> std::optional<std::string>
auto decompress(std::span<const char> compressed, size_t original_size, CompressionCodec codec) -> std::vector<char>
void decompress_flat_lp(FlatLinearProblem& flp, const CompressedBuffer& buf)
auto default_kappa_mode() -> KappaMode
auto default_max_process_swap_mb() -> double noexcept
auto default_swap_growth_mb() -> double noexcept
auto describe_kappa_mode() -> std::string
auto describe_plugin_check(PluginCheckMode mode, PluginCheckSource source) -> std::string
auto describe_solver_library(const SolverLibraryReport& lib) -> std::string
auto describe_stall_reason(const StallGateSnapshot& s, const StallGateLimits& lim) -> std::string
auto deserialize_col_labels_meta(std::span<const char> data, std::size_t num_entries, std::vector<std::string>& string_pool) -> std::vector<SparseColLabel>
auto deserialize_row_labels_meta(std::span<const char> data, std::size_t num_entries, std::vector<std::string>& string_pool) -> std::vector<SparseRowLabel>
Inverse of serialize_labels_meta for row labels.
auto detect_islands_and_fix_references(Array<Bus>& buses, const Array<Line>& lines, const PlanningOptionsLP& options) -> std::size_t
Detect bus islands and assign a reference bus per island.
auto detected_physical_concurrency() -> unsigned noexcept
template<typename F>
auto dispatch_profile_owner(ProfileOwnerKind kind, F&& f) -> auto
auto dive_mip_start(MipStartContext& ctx, DiveSummary& summary) -> std::optional<std::vector<double>>
auto dlr_default_span_uid(Uid line_uid, int position) -> Uid noexcept
Default uid of the position-th (1-based) span of line line_uid.
auto dlr_span_rating_mw(const ieee738::ConductorParams& conductor, double conductor_temperature, const ieee738::SpanWeather& weather, double voltage_kv, double v_pu, double power_factor, int subconductors, double safety_factor) -> double noexcept
auto dropped_term_kind_name(DroppedTermKind kind) -> std::string_view noexcept
Short label of a DroppedTermKind (log summaries).
auto dual_infeasibility(std::span<const double> col_low, std::span<const double> col_upp, std::span<const double> reduced_cost, std::span<const double> col_sol, std::span<const double> row_low, std::span<const double> row_upp, std::span<const double> row_dual, double inf) -> DualInfeasibility noexcept
auto dual_shared_bound_correction(std::span<const double> rep_reduced_costs, std::span<const double> rep_low, std::span<const double> rep_upp, std::span<const double> ap_low, std::span<const double> ap_upp) -> std::optional<double> noexcept
auto dump_integer_solution(const LinearInterface& li, const std::string& path) -> std::expected<void, Error>
auto dump_json_schema(std::string_view type_name = {}) -> std::string
Render the JSON Schema of a known top-level gtopt input type.
auto duration_groups(std::span<const double> cells, double period, bool point) -> std::vector<std::size_t>
auto effective_default_kappa_mode() -> std::pair<KappaMode, KappaModeSource>
auto effective_scale_alpha(const PlanningLP& planning_lp, double option_scale_alpha, double cut_max_coeff) -> double
auto elastic_filter_solve(const LinearInterface& li, std::span<const StateVarLink> links, double penalty, const SolverOptions& opts, const ElasticCostPolicy& cost_policy = {}, std::span<const RowIndex> elastic_fcut_rows = {}) -> std::optional<ElasticSolveResult>
auto element_ref_active(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const ElementRef& ref) -> std::optional<bool>
template<typename Map, typename BHolder>
auto emplace_bholder(const ScenarioLP& scenario, const StageLP& stage, Map& map, BHolder&& holder, bool empty_insert = false) -> auto
template<typename Map, typename Value = Map::value_type>
auto emplace_value(const ScenarioLP& scenario, const StageLP& stage, Map& map, Value&& value) -> auto
auto enum_entries(ApertureChunkMode) -> auto noexcept
auto enum_entries(ApertureSelectionMode) -> auto noexcept
auto enum_entries(ApertureSolveMode) -> auto noexcept
auto enum_entries(BarrierSolver) -> auto noexcept
ADL customization point for NamedEnum concept.
auto enum_entries(BasisCrossMode) -> auto noexcept
auto enum_entries(BoundaryCutSharingMode) -> auto noexcept
auto enum_entries(BoundaryCutsMode) -> auto noexcept
auto enum_entries(BoundaryCutsValuation) -> auto noexcept
auto enum_entries(BoundRuleAxis) -> auto noexcept
auto enum_entries(BuildMode) -> auto noexcept
auto enum_entries(Carrier) -> auto noexcept
auto enum_entries(CogenMode) -> auto noexcept
auto enum_entries(CompressionCodec) -> auto noexcept
auto enum_entries(ConstraintMode) -> auto noexcept
auto enum_entries(ConstraintScaleType) -> auto noexcept
auto enum_entries(ConstraintScope) -> auto noexcept
auto enum_entries(ConvergenceMode) -> auto noexcept
auto enum_entries(CrossoverMode) -> auto noexcept
ADL customization point for NamedEnum concept.
auto enum_entries(CutDrainMode) -> auto noexcept
auto enum_entries(CutSharingMode) -> auto noexcept
auto enum_entries(CutType) -> auto noexcept
auto enum_entries(DataFormat) -> auto noexcept
auto enum_entries(DirectiveKind) -> auto noexcept
auto enum_entries(ElasticFilterMode) -> auto noexcept
auto enum_entries(FastSqrtMethod) -> auto noexcept
auto enum_entries(FlowRightMode) -> auto noexcept
auto enum_entries(ForwardSamplingMode) -> auto noexcept
auto enum_entries(GasCompressorDrive) -> auto noexcept
auto enum_entries(GasCompressorFuelModel) -> auto noexcept
auto enum_entries(GasLinearization) -> auto noexcept
auto enum_entries(GasWeymouthMode) -> auto noexcept
auto enum_entries(HotStartMode) -> auto noexcept
auto enum_entries(IntegerCutsMode) -> auto noexcept
auto enum_entries(KappaMode) -> auto noexcept
ADL customization point for NamedEnum concept.
auto enum_entries(KappaWarningMode) -> auto noexcept
auto enum_entries(KirchhoffMode) -> auto noexcept
auto enum_entries(LineDirectionMode) -> auto noexcept
auto enum_entries(LineDlrLimitMode) -> auto noexcept
auto enum_entries(LineDlrSolarMode) -> auto noexcept
auto enum_entries(LineDlrSpanMode) -> auto noexcept
auto enum_entries(LineFlowDirection) -> auto noexcept
auto enum_entries(LineLossesMode) -> auto noexcept
auto enum_entries(LineOverloadSlackBound) -> auto noexcept
auto enum_entries(LinePwlLayout) -> auto noexcept
auto enum_entries(LineThermalLimitMode) -> auto noexcept
auto enum_entries(LossAllocationMode) -> auto noexcept
auto enum_entries(LowMemoryMode) -> auto noexcept
auto enum_entries(LPAlgo) -> auto noexcept
ADL customization point for NamedEnum concept.
auto enum_entries(LpEquilibrationMethod) -> auto noexcept
auto enum_entries(LpScalesLevel) -> auto noexcept
auto enum_entries(MethodType) -> auto noexcept
auto enum_entries(MipStartEffort) -> auto noexcept
ADL customization point for NamedEnum concept.
auto enum_entries(MissingCutVarMode) -> auto noexcept
auto enum_entries(MonthType) -> auto noexcept
auto enum_entries(NetworkModel) -> auto noexcept
auto enum_entries(OutageReserveMode) -> auto noexcept
auto enum_entries(OutputFlags) -> auto noexcept
auto enum_entries(PenaltyClass) -> auto noexcept
auto enum_entries(PrevStageLink) -> auto noexcept
auto enum_entries(PricingMode) -> auto noexcept
auto enum_entries(ProbabilityRescaleMode) -> auto noexcept
auto enum_entries(ProfileOwnerKind kind) -> auto noexcept
auto enum_entries(RecoveryMode) -> auto noexcept
auto enum_entries(RelaxInfeasibleAction) -> auto noexcept
auto enum_entries(RiskMeasure) -> auto noexcept
auto enum_entries(RiskRankBy) -> auto noexcept
auto enum_entries(RiskTail) -> auto noexcept
auto enum_entries(SolveMode) -> auto noexcept
auto enum_entries(SolverLogMode) -> auto noexcept
ADL customization point for NamedEnum concept.
auto enum_entries(SolverScaling) -> auto noexcept
ADL customization point for NamedEnum concept.
auto enum_entries(StartsScope) -> auto noexcept
auto enum_entries(StartupTierIntegrality) -> auto noexcept
auto enum_entries(StateVariableLookupMode) -> auto noexcept
auto enum_entries(TinyReactanceMode) -> auto noexcept
auto enum_entries(TransitionIntegrality) -> auto noexcept
template<typename E, std::size_t N>
auto enum_from_name(std::span<const EnumEntry<E>, N> entries, std::string_view name) -> std::optional<E> noexcept
Look up an enumerator by name (span overload).
template<NamedEnum E>
auto enum_from_name(std::string_view name) -> std::optional<E> noexcept
Look up a NamedEnum value by name (ADL-based).
template<NamedEnum E>
auto enum_name(E value) -> std::string_view noexcept
Return the canonical name of a NamedEnum value (ADL-based).
template<typename E, std::size_t N>
auto enum_name(std::span<const EnumEntry<E>, N> entries, E value) -> std::string_view noexcept
Return the canonical name of an enumerator (span overload).
template<typename IndexType = std::size_t, std::ranges::range R, std::ranges::range... Rs>
auto enumerate(R&& range, Rs && ... ranges) -> auto
template<typename IndexType = size_t, typename Range>
auto enumerate_active(const Range& range) -> auto noexcept
template<typename IndexType = size_t, std::ranges::range Range, typename Op>
auto enumerate_if(Range&& range, Op&& op) -> auto
auto env_solver_must_fail(std::string_view solver_name, const std::vector<std::string>& load_errors, bool fallback_on_refused) -> bool
auto equilibrate_row_in_place(std::span<double> elements, double& rowlb, double& rowub, double infinity) -> double noexcept
auto equilibrate_row_ruiz_in_place(std::span<const int> columns, std::span<double> elements, std::span<const double> col_scales, double& rowlb, double& rowub, double infinity) -> double noexcept
auto evaluate_bound_rule(const RightBoundRule& rule, Real volume) -> Real noexcept
Evaluate the piecewise-linear bound function.
template<typename ColSol, typename RowDual>
auto evaluate_cvar(const CvarLayout& layout, const ColSol& col_sol, const RowDual& row_dual) -> CvarSolution
auto evaluate_production_factor(const std::vector<ProductionFactorSegment>& segments, Real volume) -> Real noexcept
Evaluate the piecewise-linear concave production factor function.
auto evaluate_seepage(const std::vector<ReservoirSeepageSegment>& segments, Real volume) -> Real noexcept
Evaluate the piecewise-linear seepage function.
auto executable_directory() -> std::filesystem::path
auto expr_finest_time_window(const ConstraintExpr& expr) -> std::optional<TimeWindow> noexcept
auto extract_capacity_cuts(const SimulationLP& sim, std::span<const StoredCut> cuts, PhaseIndex phase_index = PhaseIndex { 0}) -> std::vector<CapacityCut>
template<typename ElementLP, typename ScenarioT, typename StageT>
void fail_lp(const ElementLP& element, const ScenarioT& scenario, const StageT& stage, LpFailure failure)
template<typename T, typename Vector>
auto field_sched_dynamic_bytes(const FieldSched<T, Vector>& fs) -> std::size_t noexcept
template<typename T, typename Vector>
auto field_sched_dynamic_bytes(const std::optional<FieldSched<T, Vector>>& opt_fs) -> std::size_t noexcept
auto find_active_bound_segment(const std::vector<RightBoundSegment>& segments, Real volume) -> const RightBoundSegment* noexcept
Find the active segment for a given reservoir volume.
auto find_active_rdl_segment(const std::vector<ReservoirDischargeLimitSegment>& segments, Real volume) -> const ReservoirDischargeLimitSegment* noexcept
Find the active segment for a given reservoir volume.
auto find_active_segment(const std::vector<ReservoirSeepageSegment>& segments, Real volume) -> const ReservoirSeepageSegment* noexcept
Find the active segment for a given reservoir volume.
auto find_alpha_state_var(const SimulationLP& sim, SceneIndex scene_index, PhaseIndex phase_index, SceneIndex source_scene, SystemKind kind = SystemKind::forward) -> const StateVariable* noexcept
auto find_alpha_state_var(const SimulationLP& sim, SceneIndex scene_index, PhaseIndex phase_index, SystemKind kind = SystemKind::forward) -> const StateVariable* noexcept
auto find_config_file() -> std::filesystem::path
Find the .gtopt.conf file following the standard search order.
auto find_expansion_candidates(const Planning& planning) -> std::vector<ExpansionCandidate>
auto find_loaded_object(const void* address) -> std::optional<LoadedObject>
auto find_names_file() -> std::optional<std::filesystem::path>
auto find_noload_fuel_commitment(const SystemContext& sc, const GeneratorLP& gen) -> const CommitmentLP*
auto find_noload_fuel_commitment(const SystemContext& sc, const GeneratorLP& gen) -> const CommitmentLP*
template<typename Holder>
auto find_or_empty_inner(const Holder& holder, const ScenarioLP& scenario, const StageLP& stage) -> const auto& noexcept
template<typename ColNameMatch>
auto find_phase_state_col(const SimulationLP& sim, SceneIndex scene_index, PhaseIndex phase_index, std::string_view class_name, Uid uid, ColNameMatch&& col_match) -> std::optional<ColIndex>
auto find_reservoir_ref_cache(const ReservoirLP& rsv, const ScenarioLP& scenario, const StageLP& stage) -> std::optional<ReservoirRefCache>
auto find_set_option(const std::vector<std::string>& set_options, std::string_view key) -> std::optional<std::string>
Value of the last --set <key>=<value> entry for key.
auto find_source_alpha_state_var(const SimulationLP& sim, const SDDPOptions& options, SceneIndex scene_index, PhaseIndex src_phase_index) -> const StateVariable* noexcept
auto find_trusted_executable(std::string_view name) -> std::string
auto find_unit_commitment(const SystemContext& sc, ElementIndex<GeneratorLP> gen_index, const StageLP& stage) -> const CommitmentLP*
auto find_unit_commitment(const SystemContext& sc, ElementIndex<GeneratorLP> gen_index, const StageLP& stage) -> const CommitmentLP*
auto find_units_file() -> std::optional<std::filesystem::path>
auto find_user_alpha_state_var(const SimulationLP& sim, SceneIndex scene_index, PhaseIndex phase_index, Uid user_alpha_uid, SystemKind kind = SystemKind::forward) -> const StateVariable* noexcept
auto finite_kappa(double kappa) -> std::optional<double> noexcept
auto first_block_index() -> BlockIndex noexcept
First block index.
auto first_phase_index() -> PhaseIndex noexcept
First phase index — the root of the planning horizon.
auto first_phase_stage_index() -> PhaseStageIndex noexcept
First stage of a phase.
auto first_scenario_index() -> ScenarioIndex noexcept
First scenario index.
auto first_scene_index() -> SceneIndex noexcept
First scene index — the canonical root scene used when boundary cuts and column-name maps are built scene-independently.
auto first_scene_scenario_index() -> SceneScenarioIndex noexcept
First scenario of a scene.
auto first_stage_index() -> StageIndex noexcept
First stage index — the root of the planning horizon.
auto first_time_key(std::string key) -> bool
void flush_default_logger_best_effort() noexcept
Best-effort flush of spdlog's default logger.
auto format_fcut_cut_lines(std::span<const StateVarLink> links, std::span<const SparseRow> cuts) -> std::string
auto format_lp_build_error(const LpBuildErrorInfo& info) -> std::string
auto format_si(double v) -> FormatSI noexcept
auto format_throttle_summary(const ThrottleCounts& c) -> std::string
auto format_version_string(std::string_view version, std::string_view git_revision) -> std::string
auto forward_basis_needed(BasisCrossMode mode) -> bool noexcept
True when mode captures the forward solve's basis for later reuse.
template<NamedEnum E>
auto gas_enum_or(const OptName& name, E fallback) -> std::optional<E> noexcept
auto gas_slp_refine(SystemLP& system, const SolverOptions& solver_options = {}) -> std::expected<GasSlpStats, Error>
void gate_reserve_provisions_by_status(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, LinearProblem& lp, ElementIndex<GeneratorLP> gen_index, const BIndexHolder<ColIndex>& status_cols, const BIndexHolder<ColIndex>& generation_cols, std::optional<ColIndex> gen_capacity_col, const std::function<double(BlockUid, double)>& committed_floor)
auto generator_fuel_burn_legs(const GeneratorLP& gen, const CommitmentLP* cmt, const ScenarioLP& scenario, const StageLP& stage, BlockUid buid) -> std::vector<std::pair<ColIndex, double>>
auto generator_fuel_burn_legs(const GeneratorLP& gen, const CommitmentLP* cmt, const ScenarioLP& scenario, const StageLP& stage, BlockUid buid) -> std::vector<std::pair<ColIndex, double>>
void get_all_futures(std::span<std::future<void>> futures)
auto get_compression_stats() -> std::vector<CompressionStatsSample> noexcept
auto get_cpu_quota_pct() -> double noexcept
template<typename Element, typename SystemContext SystemContext, template<typename> class Id>
auto get_element(SystemContext& sc, const Id<Element>& id) -> auto&&
Free function to get a reference to an element by its ID.
template<typename Element, typename SystemContext SystemContext, template<typename> class Id>
auto get_element_index(SystemContext& sc, const Id<Element>& id) -> auto
Free function to get the index of an element by its ID.
template<typename Element, typename SystemContext SystemContext>
auto get_elements(SystemContext& sc) -> auto&&
Free function to get a container of all elements of a specific type.
template<typename Obj>
auto get_name(const Obj& obj) -> auto
template<>
auto get_name<Id>(const Id& obj) -> auto
template<typename T>
auto get_opt(const po::variables_map& vm, const std::string& name) -> std::optional<T>
Extract an optional value from a variables_map.
template<typename T, typename K = T::key_type>
auto get_optiter(const T& map, K&& key) -> auto noexcept
Finds key in map and returns optional iterator.
template<typename T, typename K>
auto get_optvalue(const T& map, K&& key) -> auto
template<typename T, typename K>
auto get_optvalue_optkey(const T& map, const std::optional<K>& key) -> auto
template<typename Obj>
auto get_uid(const Obj& obj) -> Uid
template<>
auto get_uid<Id>(const Id& obj) -> Uid
auto GetColumn(const ArrowTable& table, std::string_view name) -> ArrowColumnResult
Get column by name with explicit error checking.
auto gtopt_cli_main(const std::vector<std::string>& args, std::ostream& out, std::ostream& err, bool stdout_is_tty) -> int
Full command-line entry point of the gtopt binary.
auto gtopt_environment(char*const* envp) -> std::vector<std::pair<std::string, std::string>>
auto gtopt_main(const MainOptions& raw_opts) -> std::expected<int, std::string>
Run the gtopt power-system optimizer.
auto guarded_cut_intercept(double z, bool interior) -> double noexcept
auto has_active_use_user_alpha(const PlanningLP& planning_lp) -> bool
auto has_flag(OutputFlags set, OutputFlags bit) -> bool noexcept
auto has_ignored_cwd_config(const std::filesystem::path& loaded) -> bool
True when the current directory holds a .gtopt.conf that is not loaded — i.e. a file that older releases would have read and that is now ignored. Used only to tell the user about it.
auto has_no_shedding_penalty(const Planning& planning) -> bool noexcept
Return true when the planning has no demand-shedding penalty.
template<typename Obj>
auto id(const Obj& obj) -> Id noexcept
Creates an Id from an object's attributes.
auto identify_all_available_solvers() -> std::vector<std::string>
Return the solvers that are actually usable on this machine.
auto in_lp_debug_range(int scene_uid, int phase_uid, OptInt scene_min, OptInt scene_max, OptInt phase_min, OptInt phase_max) -> bool noexcept
auto index_of(IterationUid uid) -> IterationIndex noexcept
Convert a 1-based IterationUid back to the matching 0-based IterationIndex.
template<typename T, typename Vector>
auto inherit_field_sched(const std::optional<FieldSched<T, Vector>>& sched, std::string_view owner_class, Uid uid) -> std::optional<FieldSched<T, Vector>>
template<typename SystemLPT>
auto initial_state_fallback(const SystemLPT& sys, const ScenarioLP& scenario, const StageLP& stage, LPClassName class_name, Uid uid, std::string_view col_name, Real initial) -> Real
auto insecure_plugin_location(const std::filesystem::path& path) -> std::string
void install_async_default_logger()
Install the async wrapper as spdlog's default logger.
auto integrity_finding(std::string status, std::string message, const PluginIntegrityPolicy& policy) -> IntegrityDecision
template<typename IndexType, typename A, typename B>
auto iota_range(A first, B last) -> IotaRange<IndexType>
template<typename T>
auto iota_range(T first, T last) -> IotaRange<T>
Create an IotaRange [first, last) with deduced type.
auto is_codec_available(CompressionCodec codec) -> bool noexcept
Check whether a given codec is available at runtime.
auto is_compatible_double_type(arrow::Type::type type_id) -> bool
Check if an Arrow type is a compatible floating-point type that can be cast to double.
auto is_compatible_int32_type(arrow::Type::type type_id) -> bool
Check if an Arrow type is a compatible integer type that can be cast to int32.
auto is_empty_col_label(const SparseColLabel& l) -> bool noexcept
auto is_empty_row_label(const SparseRowLabel& l) -> bool noexcept
auto is_fast_start(OptBool explicit_flag, OptReal min_up_time, OptReal min_down_time, double max_hours) -> bool noexcept
auto is_final_state_col(std::string_view col_name) -> bool noexcept
auto is_first_stage_col_name(std::string_view variable_name) -> bool
auto is_infinite_kappa(double kappa) -> bool noexcept
auto is_infinity(double v, double solver_infinity) -> bool noexcept
auto is_interior_solve(const SolverOptions& opts) -> bool noexcept
auto is_long_layout(const ArrowTable& table) -> bool
True when table uses the long layout: it carries both a bare uid column and a value column.
auto is_native_bess_reserve_generator(const SystemContext& sc, const GeneratorLP& gen) -> bool
auto is_removed_cut_sharing_mode_name(std::string_view name) -> bool noexcept
auto is_world_writable_directory(const std::filesystem::path& dir) -> bool noexcept
True when dir exists and is writable by "others" (mode o+w).
auto iteration_relative(IterationIndex cur, IterationIndex offset) -> Index noexcept
Signed distance of cur from a base offset, as a plain Index offset (not wrapped in IterationIndex — because the difference of two positional indices is not itself a positional index, it's a count).
auto kappa_mode_from_env() -> std::optional<KappaMode>
auto known_schema_names() -> const std::vector<std::string_view>&
The selector names accepted by dump_json_schema: planning (the default) and options first, then every contract type in snake_case, sorted. Exposed for diagnostics and tests.
auto load_basis(const std::filesystem::path& path) -> std::expected<Basis, Error>
auto load_boundary_cuts_csv(PlanningLP& planning_lp, const std::string& filepath, const SDDPOptions& options, const LabelMaker& label_maker, const StrongIndexVector<SceneIndex, StrongIndexVector<PhaseIndex, PhaseStateInfo>>& scene_phase_states) -> std::expected<CutLoadResult, Error>
auto load_cascade_progress(const std::filesystem::path& path) -> std::expected<CascadeProgress, Error>
auto load_cuts_parquet(PlanningLP& planning_lp, const std::string& filepath, double scale_alpha, const LabelMaker& label_maker, const StrongIndexVector<SceneIndex, StrongIndexVector<PhaseIndex, PhaseStateInfo>>* scene_phase_states = nullptr, SDDPCutManager* cut_store = nullptr) -> std::expected<CutLoadResult, Error>
auto load_gtopt_config() -> MainOptions
Load a MainOptions from the [gtopt] section of .gtopt.conf.
auto load_gtopt_config_from(const std::filesystem::path& config_path) -> MainOptions
Load a MainOptions from the [gtopt] section of a config file.
auto load_names_registry() -> NamesRegistry
auto load_scene_cuts_from_directory_parquet(PlanningLP& planning_lp, const std::string& directory, double scale_alpha, const LabelMaker& label_maker, const StrongIndexVector<SceneIndex, StrongIndexVector<PhaseIndex, PhaseStateInfo>>* scene_phase_states = nullptr) -> std::expected<CutLoadResult, Error>
auto load_seed_commitment(const std::string& path) -> std::expected<SeedCommitmentMap, Error>
auto load_solver_cfg(const std::optional<std::string>& param_file, std::string_view solver_name, std::span<const SolverCfgEnumKey> enum_keys) -> SolverCfgPairs
Load and translate a solver tuning file.
auto load_solver_cfg_cached(const std::optional<std::string>& param_file, std::string_view solver_name, std::span<const SolverCfgEnumKey> enum_keys) -> SolverCfgPairs
Once-per-process cached load_solver_cfg.
auto load_system_from_file(std::string_view file, const std::string& input_directory) -> System
auto load_system_with_model_options(std::string_view file, const std::string& input_directory) -> LoadedSystem
auto load_unit_registry() -> UnitRegistry
auto load_user_constraints(Planning& planning) -> std::expected<void, std::string>
Load user constraints from external file(s) referenced in planning.
auto local_integration_rows(std::span<const double> times, std::span<const double> weights, double start, double end, StorageIntegration mode, bool match_weights = true) -> IntegrationRows
void log_and_throw(std::string msg)
void log_aperture_summary(const ApertureSummary& summary, std::string_view prefix)
void log_compression_stats() noexcept
void log_diagnostic_lines(std::string_view level, std::string_view header, std::string_view diag)
Log a multi-line diagnostic string line-by-line via spdlog.
void log_gtopt_environment()
void log_lp_stats_summary(const std::vector<ScenePhaseLPStats>& entries, double ratio_threshold = 1e7)
Log a summary of LP coefficient statistics.
template<typename Holder>
auto lookup_inner(const Holder& holder, const ScenarioLP& scenario, const StageLP& stage, BlockUid buid) -> std::optional<typename Holder::mapped_type::mapped_type> noexcept
auto lowercase(std::string s) -> std::string
Returns a lowercase copy of the given string (rvalue overload).
template<detail::string_like T>
auto lowercase(T&& sv) -> LowercaseView noexcept
Returns a lazy, zero-copy lowercase view over a string-like value.
auto lp_debug_passes_includes(std::string_view passes, LpDebugPass which) -> bool noexcept
auto lp_file_extension(LpFileFormat format) -> std::string_view noexcept
File extension (with leading dot) written for format.
auto lp_file_format_name(LpFileFormat format) -> std::string_view noexcept
Name of the format as accepted by --lp-format ("lp" / "mps").
auto lp_file_path(std::string_view stem, LpFileFormat format) -> std::string
Path of the file written for stem in format (stem + extension).
auto lp_scales_path(std::string_view lp_path, std::string_view suffix = lp_scales_json_suffix) -> std::string
auto lp_scales_to_json(const LpScales& scales) -> std::string
Serialises scales to JSON text (daw::json).
auto make_aperture_context(SceneUid scene_uid, PhaseUid phase_uid, ApertureUid aperture, int extra) -> ApertureContext
Build an SDDP aperture cut context.
template<typename Type, typename FieldSched, typename... Uid>
auto make_array_index(const auto& system_context, std::string_view class_name, const FieldSched& sched, const Id& id) -> auto
auto make_backward_lp_task_req(IterationIndex iteration_index) -> BasicTaskRequirements<SDDPTaskKey> noexcept
auto make_block_context(ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid) -> BlockContext
Build a block-level context from strongly-typed UIDs.
auto make_block_context(ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid, int extra) -> BlockExContext
Build a block-level context with an extra index (e.g. segment number).
auto make_default_domain_rules(const MipStartDomainRules& opts, SeedCommitmentMap seed = {}) -> DomainRulePipeline
auto make_file_sched_ref(std::string_view owner_class, std::string_view fsched, Uid uid) -> FileSched
auto make_forward_lp_task_req(IterationIndex iteration_index) -> BasicTaskRequirements<SDDPTaskKey> noexcept
auto make_iteration_context(SceneUid scene_uid, PhaseUid phase_uid, IterationUid iteration_uid, int extra) -> IterationContext
auto make_lp_matrix_options(bool enable_names, const std::optional<double>& matrix_eps, bool compute_stats = false, const std::optional<std::string>& lp_solver = {}, std::optional<LpEquilibrationMethod> equilibration_method = {}) -> LpMatrixOptions
Build LpMatrixOptions from internal parameters.
auto make_lp_scales(const SystemLP& system, std::string_view lp_path, LpScalesLevel level = LpScalesLevel::full) -> LpScales
auto make_lp_scales_detail(const SystemLP& system) -> LpScalesDetail
auto make_markov_config(std::vector<int> state_of_scene, std::vector<double> transition) -> MarkovChainConfig
auto make_mip_start_generator(const MipStartOptions& opts) -> std::unique_ptr<MipStartGenerator>
auto make_options_description() -> po::options_description
Create the command-line options description for the gtopt application.
auto make_phase_context(SceneUid scene_uid, PhaseUid phase_uid, Uid element_uid) -> PhaseContext
auto make_planning_method(const PlanningOptionsLP& options, size_t num_phases = 0) -> std::unique_ptr<PlanningMethod>
Create a solver instance based on options.
auto make_reservoir_ref_cache(const ReservoirLP& rsv, const ScenarioLP& scenario, const StageLP& stage) -> ReservoirRefCache
Populate a ReservoirRefCache from a ReservoirLP reference.
auto make_scene_phase_context(SceneUid scene_uid, PhaseUid phase_uid) -> ScenePhaseContext
Build an SDDP scene/phase context.
auto make_sddp_task_key(IterationIndex iteration_index, SDDPPassDirection direction, SDDPTaskKind kind, int phase_rank = 0) -> SDDPTaskKey noexcept
Build an SDDPTaskKey from strongly-typed SDDP parameters.
auto make_sddp_work_pool(double cpu_factor = 2.0, double memory_limit_mb = 0.0, int cell_task_headroom = 0) -> std::unique_ptr<SDDPWorkPool>
Create and start an SDDPWorkPool configured for the SDDP solver.
auto make_solver_work_pool(double cpu_factor = 2.0, double cpu_threshold_override = 0.0, std::chrono::milliseconds scheduler_interval = std::chrono::milliseconds(50), double memory_limit_mb = 0.0, std::string_view pool_label = "SolverWorkPool") -> std::unique_ptr<AdaptiveWorkPool>
Create and start an AdaptiveWorkPool configured for solver use.
auto make_stage_context(ScenarioUid scenario_uid, StageUid stage_uid) -> StageContext
Build a stage-level context from strongly-typed UIDs.
template<class Tag>
auto make_uid(uid_t value) -> auto
template<typename Map, typename Iterator>
void map_insert_sorted_unique(Map& map, Iterator first, Iterator last)
Insert from a pre-sorted, deduplicated range [first, last) using the most efficient API for each backend.
template<typename Map, typename Size>
void map_reserve(Map& map, Size n)
Reserve capacity for n elements in any associative container.
auto markov_active(CutSharingMode cut_sharing, const MarkovChainConfig* markov) -> bool noexcept
auto markov_alpha_weights(const SimulationLP& sim, const MarkovChainConfig& markov, SceneIndex scene_index) -> std::vector<double>
auto match_linked_library(const std::vector<LinkedLibraryRecord>& records, const LoadedLibraryIdentity& loaded) -> const LinkedLibraryRecord*
auto memory_clamp_threads(double cpu_factor, double memory_limit_mb, std::string_view pool_label) -> MemoryClamp
template<typename T>
auto merge(std::vector<T>& dest, std::vector<T>&& src) -> bool
Efficiently merges two vectors using move semantics.
template<typename T>
auto merge(std::vector<T>& dest, std::vector<T>& src) -> bool
void merge_config_defaults(MainOptions& opts, const MainOptions& defaults)
Merge config-file defaults into a MainOptions struct.
template<typename OptA, typename OptB>
auto merge_opt(OptA& a, OptB&& b) -> auto&
Merges two optionals, keeping value if source has value.
auto mip_polish_reserve(std::optional<double> time_limit) -> double noexcept
auto next(IterationIndex iteration_index) -> IterationIndex noexcept
Next iteration index (iteration_index + 1), preserving strong type.
auto next(IterationIndex iteration_index, Index n) -> IterationIndex noexcept
Advance an iteration index by n steps, returning a new IterationIndex. Replaces the IterationIndex{static_cast<Index>(offset) + n} pattern used to compute an iteration budget horizon.
auto next(PhaseIndex phase_index) -> PhaseIndex noexcept
Next phase index (phase_index + 1), preserving strong type.
auto next(PhaseStageIndex index) -> PhaseStageIndex noexcept
Next phase-local stage position.
auto next(SceneIndex scene_index) -> SceneIndex noexcept
Next scene index (scene_index + 1), preserving strong type.
auto next(StageIndex stage_index) -> StageIndex noexcept
Next stage index (stage_index + 1), preserving strong type.
auto next_fallback_algo(LPAlgo current) -> LPAlgo noexcept
auto no_solver_message(const std::vector<std::string>& load_errors) -> std::string
auto nonanticipative_cut_load_error(const SimulationLP& sim, std::string_view what) -> std::optional<Error>
auto operator&(OutputFlags a, OutputFlags b) -> OutputFlags noexcept
auto operator|(OutputFlags a, OutputFlags b) -> OutputFlags noexcept
auto operator|=(OutputFlags& a, OutputFlags b) -> OutputFlags& noexcept
auto other_lp_file_format(LpFileFormat format) -> LpFileFormat noexcept
The other format (used for the fallback of diagnostic dumps).
auto output_flags_to_string(OutputFlags flags) -> std::string
auto output_selection_to_string(const OutputSelection& sel) -> std::string
auto parquet_read_table(const std::filesystem::path& fpath) -> std::expected<ArrowTable, std::string>
Read an Arrow table from a Parquet file.
auto parse_aperture_chunk_size(std::string_view s) -> std::optional<int> noexcept
Parse an aperture-chunk-size value from a string.
auto parse_build_id_manifest(std::string_view text) -> std::optional<std::string>
template<typename T>
auto parse_conf_number(std::string_view text) -> std::optional<T>
auto parse_cut_sharing_mode(std::string_view name) -> CutSharingMode
auto parse_elastic_filter_mode(std::string_view name) -> ElasticFilterMode
auto parse_env_flag(std::string_view text) -> std::optional<bool>
auto parse_file_sched_ref(std::string_view owner_class, std::string_view fsched) -> FileSchedRef
auto parse_ini_file(const std::filesystem::path& path) -> IniData
Parse a simple INI file.
auto parse_lp_algorithm(std::string_view s) -> LPAlgo
Parse an LP algorithm value from a string (name or integer).
auto parse_lp_file_format(std::string_view name) -> std::optional<LpFileFormat> noexcept
Parse "lp" / "mps" (case-sensitive); nullopt on anything else.
auto parse_main_options(const po::variables_map& vm, std::vector<std::string> system_files) -> MainOptions
Build a MainOptions struct from a parsed CLI variables_map.
auto parse_memory_size(const std::string& s) -> double
Parse a memory size string into megabytes.
auto parse_output_flags(std::string_view spec) -> OutputFlags
auto parse_output_selection(std::string_view spec) -> OutputSelection
auto parse_planning_files(const std::vector<std::string>& planning_files, const std::optional<std::string>& input_directory = {}, std::string_view enforce_dialect = {}) -> std::expected<Planning, std::string>
auto parse_planning_json(std::string_view json_content) -> Planning
auto parse_plugin_check_mode(std::string_view text) -> std::optional<PluginCheckMode>
Parse "warning" / "error" (case-insensitive; "warn" accepted).
auto parse_solver_param_file(const std::filesystem::path& path) -> std::optional<SolverCfgPairs>
Parse a solver-NATIVE parameter file into (name, value) pairs.
auto partition_apertures(std::span<const ApertureEntry> apertures, int chunk_size) -> std::vector<std::span<const ApertureEntry>>
auto peek_planning_directories(const std::vector<std::string>& planning_files, const std::optional<std::string>& input_directory = {}) -> PlanningDirectoryPeek
auto physical_concurrency() -> unsigned noexcept
template<typename SystemLPT>
auto physical_efin_from_cache(const SystemLPT& sys, const ScenarioLP& scenario, const StageLP& stage, const ReservoirRefCache& rc) -> Real
template<typename SystemLPT>
auto physical_eini_from_cache(const SystemLPT& sys, const ScenarioLP& scenario, const StageLP& stage, const ReservoirRefCache& rc) -> Real
auto pivot_long_to_wide(const ArrowTable& table_in) -> ArrowTable
Pivot a long-layout table [<index cols…>, uid, value] into the wide layout [<index cols…>, uid:N…] that the input loaders expect.
auto plan_nonanticipative_scene_merge(const Planning& planning) -> std::optional<SceneMerge>
Decide whether (and how) the active scenes must be merged.
auto plugin_check_mode_from_env() -> std::optional<PluginCheckMode>
auto previous(IterationIndex iteration_index) -> IterationIndex noexcept
Previous iteration index (iteration_index - 1), preserving strong type.
auto previous(PhaseIndex phase_index) -> PhaseIndex noexcept
Previous phase index (phase_index - 1), preserving strong type.
auto previous(PhaseStageIndex index) -> PhaseStageIndex noexcept
Previous phase-local stage position.
auto previous(SceneIndex scene_index) -> SceneIndex noexcept
Previous scene index (scene_index - 1), preserving strong type.
auto previous(StageIndex stage_index) -> StageIndex noexcept
Previous stage index (stage_index - 1), preserving strong type.
auto pricing_csv_header() -> std::string_view noexcept
auto pricing_csv_line(int scene_uid, int phase_uid, const PricingOutcome& o) -> std::string
auto pricing_outcome_reportable(const PricingOutcome& o) -> bool noexcept
auto print_available_solvers(std::ostream& out) -> int
void print_cli_help(std::ostream& out, const cli::options_description& desc)
auto print_json_schema(std::string_view name, std::ostream& out) -> int
auto print_naming_dialects(std::string_view filter, std::ostream& out, std::ostream& err) -> int
auto probe_parquet_codec(std::string_view requested) -> std::string
void propagate_trial_values(std::span<StateVarLink> links, LinearInterface& target_li) noexcept
void propagate_trial_values(std::span<StateVarLink> links, std::span<const double> source_solution, LinearInterface& target_li) noexcept
auto propagation_dive(const DiveInput& in) -> DiveOutput
Relaxation-guided fix-and-propagate dive (stage 1). See the file header.
template<typename Element, typename SystemContext SystemContext, typename E>
auto push_back(SystemContext& sc, E&& element) -> auto
Free function to add a new element to the system.
auto reactive_ratio(double power_factor) -> double noexcept
auto read_build_id_manifest(const std::filesystem::path& plugin_path) -> std::optional<std::string>
auto read_elf_identity(const std::filesystem::path& path) -> std::expected<ElfIdentity, std::string>
void reconcile_basis(Basis& basis, std::size_t ncols, std::size_t nrows) noexcept
Reconcile a basis captured from a related LP to current dimensions.
void record_col_bounds_dynamic(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, ColIndex col, double lowb, double uppb, SystemKind kind = SystemKind::forward) noexcept
void register_alpha_variables(PlanningLP& planning_lp, SceneIndex scene_index, double scale_alpha, CutSharingMode cut_sharing = CutSharingMode::none, BoundaryCutSharingMode boundary_cut_sharing = BoundaryCutSharingMode::per_scene, bool register_as_state_variable = true, const MarkovChainConfig* markov = nullptr, std::size_t terminal_phi_count = 0, bool release_after = true)
void register_ampl_iterator_dispatchers(SimulationLP& sim)
void register_ampl_param_dispatchers(SimulationLP& sim)
void register_solver_run(const std::string& filepath)
void reject_nan_in_float_columns(const arrow::Table& table, std::string_view path)
void reject_non_numeric_columns(const arrow::Table& table, std::string_view path)
auto relax_fixed_state_variable(LinearInterface& li, const StateVarLink& link, PhaseIndex phase_index, double penalty) -> RelaxedVarInfo
auto remaining_time_limit(std::optional<double> time_limit, double elapsed_s) -> std::optional<double> noexcept
auto removed_cut_sharing_mode_message(std::string_view name) -> std::string
auto require_bool(std::string_view option_name, std::string_view value) -> bool
Parse a boolean option value by name; throw on invalid input.
template<NamedEnum E>
auto require_enum(std::string_view option_name, std::string_view value) -> E
Look up a NamedEnum value by name; throw on invalid input.
template<typename U>
auto require_sid(const std::optional<U>& opt, std::string_view caller, std::string_view field) -> U
auto require_stage_month(const StageLP& stage, std::string_view consumer_kind, std::string_view consumer_id, std::string_view feature) -> MonthType
Assert that a stage carries a calendar month, or throw.
void reset_compression_stats() noexcept
void reset_default_swap_gate() noexcept
Restore the built-in swap-gate defaults (2048 MB / 64 MB).
auto resolve_aperture_chunk(std::optional<ApertureChunkMode> mode, int size, int max_apertures_per_phase, int n_active_scenes, int n_physical_cores, double parallel_factor = 2.0) -> ApertureChunkResolution noexcept
auto resolve_aperture_system_file(const OptName& phase_file, const OptName& global_file) -> OptName noexcept
template<typename VolumeGetter>
auto resolve_bound_rule_axis_value(const RightBoundRule& rule, const std::optional<MonthType>& stage_month, VolumeGetter&& volume_getter) -> Real
Resolve the rule's input value by axis dispatch.
auto resolve_col_to_row(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const ElementRef& ref, double base_coeff, SparseRow& row, const LinearProblem& lp, AmplResolveCache* resolve_cache = nullptr) -> ResolveColResult
Resolve an ElementRef into one or more SparseRow entries.
auto resolve_effective_apertures(std::span<const Aperture> aperture_defs, std::span<const ScenarioLP> all_scenarios, const std::optional<Array<Uid>>& requested_uids, Array<Aperture>& owned, std::string_view log_tag) -> std::optional<std::span<const Aperture>>
template<std::ranges::input_range Range, typename Proj = std::identity>
auto resolve_emission_uid(const SingleId& ref, const Range& emissions, Proj proj = {}) -> std::optional<Uid>
template<typename Segment>
auto resolve_fail_segment_widths(std::span<const Segment> segments) -> FailSegmentWidths
auto resolve_forward_solver_options(SolverOptions fwd, bool explicit_options, bool duals_feed_cuts, BasisCrossMode basis_mode) -> SolverOptions noexcept
auto resolve_future_cost_aliases(Planning& planning) -> std::expected<void, Error>
auto resolve_future_cost_path(const PlanningLP& planning_lp, const std::string& path) -> std::string
auto resolve_in_runpath(std::string_view soname, const std::vector<std::string>& runpath, const std::filesystem::path& origin) -> std::filesystem::path
auto resolve_kappa_mode(std::optional<KappaMode> opts_mode) -> KappaMode
opts_mode if set, else default_kappa_mode().
auto resolve_log_directory(const MainOptions& opts) -> std::filesystem::path
Resolve the directory that receives gtopt_N.log / trace_N.log, before the planning JSON is fully parsed.
auto resolve_planning_args(MainOptions opts) -> std::expected<MainOptions, std::string>
Resolve planning file arguments and directory context.
auto resolve_single_col(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const ElementRef& ref, const LinearProblem& lp) -> std::optional<ResolvedCol>
Try to look up the LP ColIndex for one element reference.
auto resolve_single_param(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const ElementRef& ref) -> std::optional<double>
Try to look up a data parameter value for one element reference.
auto resolve_solver_param_file(SolverOptions& opts, std::string_view input_directory, std::string_view where) -> bool
auto resolve_solver_param_file(std::string_view file, std::string_view input_directory) -> std::optional<std::filesystem::path>
Path-only form of resolve_solver_param_file_source().
auto resolve_solver_param_file_source(std::string_view file, std::string_view input_directory) -> std::optional<ResolvedParamFile>
auto resolve_solver_param_files(PlanningOptions& options) -> int
void resolve_solver_setup(Planning& planning, const MainOptions& opts)
auto resolve_system_file(std::string_view file, const std::string& input_directory) -> std::filesystem::path
auto risk_measure_csv_header() -> std::string_view noexcept
Header of risk_measure.csv (trailing newline included).
auto risk_measure_csv_line(int scene_uid, int phase_uid, double eta, const CvarLayout& layout, const CvarScenarioResult& r) -> std::string
One risk_measure.csv line.
auto row_families(const LinearInterface& li, std::span<const int> rows) -> std::map<std::string, int>
template<std::ranges::sized_range R>
auto row_index_size(const R& r) -> RowIndex noexcept
Build a RowIndex from the size of any sized range. Mirror of col_index_size() — see that helper for rationale.
auto run_check_json_info(const std::vector<std::string>& json_files, int timeout_seconds = 30) -> std::string
Run gtopt_check_json --info on one or more JSON files and return the captured output.
auto run_check_lp_diagnostic(const std::string& lp_file, int timeout_seconds = 10, const SolverOptions& solver_opts = {}) -> std::string
Run gtopt_check_lp on an LP file and return the diagnostic output.
auto run_check_solvers_command(std::string_view solver, bool verbose, std::ostream& out, std::ostream& err) -> int
auto run_one_solver_test(std::string_view solver_name, std::string_view test_name) -> SolverTestResult
Run ONE named test against ONE solver.
auto run_solver_tests(std::string_view solver_name, bool verbose = false) -> SolverTestReport
Run the full LinearInterface test suite against solver_name.
template<std::ranges::input_range Range, typename Proj = std::identity>
auto same_emission(const SingleId& lhs, const SingleId& rhs, const Range& emissions, Proj proj = {}) -> bool
auto sample_forward_realization(const SimulationLP& sim, IterationIndex iteration_index, SceneIndex scene_index, PhaseIndex phase_index) -> SceneIndex noexcept
auto sample_weighted_index(std::span<const double> weights, std::uint64_t iteration, std::uint64_t scene, std::uint64_t phase) -> std::size_t noexcept
auto save_basis(const std::filesystem::path& path, const Basis& basis) -> std::expected<void, Error>
auto save_cascade_progress(const CascadeProgress& progress, const std::filesystem::path& path) -> std::expected<void, Error>
auto save_cuts_parquet(std::span<const StoredCut> cuts, const PlanningLP& planning_lp, const std::string& filepath, bool append_mode = false) -> std::expected<void, Error>
Save accumulated cuts to a Parquet file with typed schema.
auto save_scene_cuts_parquet(std::span<const StoredCut> cuts, SceneIndex scene_index, SceneUid scene_uid, const PlanningLP& planning_lp, const std::string& directory) -> std::expected<void, Error>
Save cuts for a single scene to a per-scene Parquet file.
auto scan_bound_envelope(std::span<const double> collb, std::span<const double> colub, std::span<const double> rowlb, std::span<const double> rowub, double infinity, double large_bound) -> BoundEnvelopeReport noexcept
auto scene_probability_masses(const SimulationLP& sim) -> std::vector<double>
auto scip_repair_candidate(MipStartContext& ctx, std::vector<double> candidate) -> std::optional<std::vector<double>>
auto scope_granularity(ConstraintScope scope) -> int noexcept
auto scope_is_planning(ConstraintScope scope) -> bool noexcept
auto scope_name(ConstraintScope scope) -> std::string_view noexcept
Human-readable spelling of a ConstraintScope for diagnostics.
auto sddp_gap_converged(double gap, double convergence_tol) -> bool noexcept
auto sddp_log(std::string_view tag, IterationUid iteration_uid) -> SDDPLogTag noexcept
"SDDP Init [i1]" — iteration-level only.
auto sddp_log(std::string_view tag, IterationUid iteration_uid, SceneUid scene_uid) -> SDDPLogTag noexcept
"SDDP Forward [i1 s1]" — scene-level (no phase).
auto sddp_log(std::string_view tag, IterationUid iteration_uid, SceneUid scene_uid, PhaseUid phase_uid) -> SDDPLogTag noexcept
auto sddp_log(std::string_view tag, IterationUid iteration_uid, SceneUid scene_uid, PhaseUid phase_uid, Uid aperture_uid) -> SDDPLogTag noexcept
"SDDP Aperture [i1 s1 p2 a5]" — with aperture uid appended.
auto seed_commitment_key(Uid gen_uid, Uid block_uid) -> std::uint64_t noexcept
auto select_apertures(std::span<const Uid> phase_apertures, const std::optional<int>& num_apertures, ApertureSelectionMode mode = ApertureSelectionMode::head) -> std::vector<Uid>
auto select_codec(CompressionCodec preferred) -> CompressionCodec noexcept
auto select_rdl_coeffs(const std::vector<ReservoirDischargeLimitSegment>& segments, Real volume) -> ReservoirDischargeLimitCoeffs noexcept
Select the active segment and return LP coefficients.
auto select_seepage_coeffs(const std::vector<ReservoirSeepageSegment>& segments, Real volume) -> ReservoirSeepageCoeffs noexcept
Select the active seepage segment and return LP coefficients.
auto serialize_labels_meta(const std::vector<SparseColLabel>& labels) -> std::vector<char>
Serialize a vector of column labels into a self-contained byte buffer.
auto serialize_labels_meta(const std::vector<SparseRowLabel>& labels) -> std::vector<char>
Serialize a vector of row labels into a self-contained byte buffer.
void set_cpu_quota_pct(double pct) noexcept
void set_default_swap_gate(double max_process_swap_mb, double swap_growth_mb) noexcept
void setup_file_logging(const MainOptions& opts, bool suppress_stdout)
Add a <log_dir>/gtopt_N.log file sink to spdlog's default logger.
auto sha256_file(const std::filesystem::path& path) -> std::string
auto sha256_hex(std::span<const std::byte> data) -> std::string
SHA-256 of data as 64 lowercase hex characters.
auto sha256_hex(std::string_view data) -> std::string
SHA-256 of the bytes of data as 64 lowercase hex characters.
void share_cuts_for_phase(PhaseIndex phase_index, const StrongIndexVector<SceneIndex, std::vector<SparseRow>>& scene_cuts, CutSharingMode mode, PlanningLP& planning, IterationIndex iteration_index = IterationIndex {0})
auto short_build_id(std::string_view build_id) -> std::string
First 12 hex digits of a build-id (for compact listings).
auto shutdown_trajectory_power(const std::vector<double>& traj, double step, double pmin, double delta) -> double
auto smt_ratio() -> unsigned noexcept
auto snake_case(std::string s) -> std::string
Returns a snake_case copy of the given string (std::string overload).
template<detail::string_like T>
auto snake_case(T&& sv) -> SnakeCaseView noexcept
Returns a lazy, zero-copy snake_case view over a string-like value.
auto snap_period_boundaries(std::span<const double> cells, double period, bool point = true) -> std::vector<std::size_t>
Cell indices j after which a new group starts (the group ends at τ_j).
auto solution_csv_header(bool with_kappa = true) -> std::string_view noexcept
auto solution_csv_line(const SolutionRow& row, bool with_kappa = true) -> std::string
auto solution_status_name(int status) -> std::string_view noexcept
auto solve_apertures_for_phase(SceneIndex scene_index, PhaseIndex phase_index, const PhaseStateInfo& src_state, ColIndex src_alpha_col, const ScenarioLP& base_scenario, std::span<const ScenarioLP> all_scenarios, std::span<const Aperture> aperture_defs, std::span<const Uid> phase_apertures, int total_cuts, SystemLP& sys, const PhaseLP& phase_lp, const SolverOptions& opts, const LabelMaker& label_maker, const std::string& log_directory, SceneUid scene_uid_val, PhaseUid phase_uid_val, const ApertureChunkSubmitFunc& submit_fn, double aperture_timeout = 0.0, bool save_aperture_lp = false, const ApertureDataCache& aperture_cache = {}, IterationIndex iteration_index = {}, double cut_coeff_eps = 0.0, LpDebugWriter* lp_debug_writer = nullptr, bool use_manual_clone = false, int chunk_size = 1, class SDDPWorkPool* pool_for_slot_release = nullptr, std::span<const StateVarLink> cut_links = {}, ApertureSolveMode aperture_solve_mode = ApertureSolveMode::reduced_cost, const Basis* seed_basis = nullptr, Basis* captured_basis_out = nullptr, int aperture_screen_count = default_sddp_aperture_screen_count, Basis* last_basis_out = nullptr, ApertureDropTracker* drop_tracker = nullptr) -> std::optional<SparseRow>
auto solve_elastic_lp(LinearInterface& li, std::span<const int> int_cols, std::span<const double> candidate, double penalty, const SolverOptions& opts) -> std::vector<double>
auto solve_fixed_integer_lp(LinearInterface& li, std::span<const int> int_cols, std::span<const double> candidate, const SolverOptions& opts) -> FixedLpResult
auto solve_investment_master(const Planning& planning, const InvestmentMasterOptions& opts) -> std::expected<InvestmentMasterResult, Error>
template<typename SystemLPT>
auto solved_stage_state(const SystemLPT& sys, const ScenarioLP& scenario, const StageLP& stage, LPClassName class_name, Uid uid, std::string_view col_name, std::optional<ColIndex> local_col = std::nullopt) -> std::optional<Real>
auto solver_allow_unpinned_env(std::string_view solver) -> std::string
auto solver_allow_unpinned_from_env(std::string_view solver) -> bool
auto solver_fallback_on_refused_from_env() -> bool
auto solver_load_errors(std::string_view solver_name, const std::vector<std::string>& load_errors) -> std::vector<std::string>
auto solver_unavailable_message(std::string_view solver_name, const std::vector<std::string>& available, const std::vector<std::string>& load_errors) -> std::string
auto spawn_environment() -> char*const* noexcept
Environment block for posix_spawn (the current process environment).
void split_config_defaults(MainOptions& opts, const MainOptions& conf)
Split config-file values into runtime-only fields and the planning-level defaults layer.
auto split_lp_file_target(std::string filename, LpFileFormat requested = LpFileFormat::lp) -> LpFileTarget
auto stage_block_span(std::span<const Block> block_array, const Stage& stage) -> std::span<const Block>
auto startup_trajectory_power(const std::vector<double>& traj, double step, double pmin, double delta) -> double
template<typename StorageElement>
auto storage_carries_state(const StorageElement& element, StorageStateDefaults defaults) -> bool noexcept
void strip_cr(std::string& s) noexcept
Strip trailing carriage-return left by std::getline on DOS text files.
template<typename Pool, typename Func>
auto submit_or_run_inline(Pool& pool, Func&& func, const typename Pool::Requirements& req = {}, std::string_view refusal_warning = {}) -> std::future<std::invoke_result_t<Func&>>
void switch_to_sync_default_logger()
Swap the default logger back to a synchronous one.
auto table_has_column(const ArrowTable& table, std::string_view name) -> bool noexcept
auto tail_risk_weights(std::span<const double> probability, std::span<const double> index, double alpha, double weight, RiskMeasure measure, RiskTail tail) -> std::vector<double>
auto test_force_fix_duals_bail() -> bool noexcept
auto time_window_finer_than_scope(TimeWindow window, ConstraintScope scope) -> bool noexcept
auto time_window_granularity(TimeWindow window) -> int noexcept
auto time_window_name(TimeWindow window) -> std::string_view noexcept
auto to_scales_context(const LpContext& context) -> std::optional<LpScalesContext>
template<typename Tag>
auto to_size(StrongIndexType<Tag> idx) -> std::size_t noexcept
template<typename Tag>
auto to_size(StrongPositionIndexType<Tag> idx) -> std::size_t noexcept
Container offset of a strong index: its underlying value as std::size_t.
auto to_string(Carrier c) -> std::string_view noexcept
auto to_string(IntegrityVerdict v) -> std::string_view noexcept
auto to_string(PluginCheckMode m) -> std::string_view noexcept
auto to_string(PluginCheckSource s) -> std::string_view noexcept
template<std::ranges::range Range, typename Transform = decltype([](const auto& x) { return x; }), typename RRef = decltype(*std::ranges::begin(std::declval<Range>()))>
auto to_vector(Range&& range, Transform&& transform = {}) -> auto
Converts range to vector, optionally transforming elements.
auto transition_cols_binary(TransitionIntegrality mode) -> bool noexcept
auto translate_solver_cfg_value(std::span<const SolverCfgEnumKey> enum_keys, std::string_view key, std::string_view value) -> std::optional<std::string>
Translate one tuning value into the solver's numeric code.
auto try_read_table(const std::filesystem::path& fpath, std::string_view format) -> std::expected<ArrowTable, std::string>
Try to read a table, preferring format and falling back to the other format on failure.
auto uid_of(IterationIndex idx) -> IterationUid noexcept
Convert a 0-based IterationIndex to the matching 1-based IterationUid. The only sanctioned way to produce an IterationUid from runtime iteration state, so the +1 convention stays in one place.
template<class Tag>
auto unknown_uid_of() -> UidOf<Tag> noexcept
auto validate_markov_config(const MarkovChainConfig& markov, std::size_t num_scenes) -> std::optional<std::string>
auto validate_nonanticipative_sddp(const SimulationLP& sim, const SDDPOptions& opts) -> std::optional<Error>
Refuse SDDP options that cannot honour a nonanticipative merge.
auto validate_planning(Planning& planning) -> ValidationResult
Validate a Planning object for semantic correctness.
template<class Tag>
auto value_of(const UidOf<Tag>& u) -> uid_t noexcept
auto violated_integer_rows(const FlatLinearProblem& flat, std::span<const double> row_low, std::span<const double> row_upp, std::span<const int> int_cols, std::span<const double> values, double infinity = 1e20, double tol = 1e-6) -> std::vector<int>
template<typename Collections, typename Op>
auto visit_elements(Collections&& collections, Op op) -> auto
void warn_deprecated_cli(const std::optional<bool>& opt, std::string_view cli_flag, std::string_view set_path)
Specialisation for bool (prints true/false instead of 1/0).
void warn_deprecated_cli(const std::optional<std::string>& opt, std::string_view cli_flag, std::string_view set_path)
Overload for string options — no conversion needed.
template<typename T>
void warn_deprecated_cli(const std::optional<T>& opt, std::string_view cli_flag, std::string_view set_path)
Emit a deprecation warning for a CLI option replaceable by –set.
void warn_deprecated_cli_flags(const MainOptions& opts)
Emit the "--flag is deprecated, use --set" warnings for every deprecated CLI flag set in opts.
template<typename... Args>
void warn_once(WarnOnceFlag& flag, spdlog::format_string_t<Args...> fmt, Args && ... args)
template<typename... Args>
void warn_once_per_key(std::string key, spdlog::format_string_t<Args...> fmt, Args && ... args)
void warn_profile_above_one(std::string_view class_name, Uid uid, std::string_view name, double max_value, bool clamped)
void warn_ref_once(std::string_view cname, Uid uid, std::string_view ref_what, Uid ref_uid)
auto weighted_average_benders_cut(const std::vector<SparseRow>& cuts, const std::vector<double>& weights) -> SparseRow
auto write_json_output(const Planning& planning, const std::string& json_file) -> std::expected<void, std::string>
Write the merged Planning to a JSON file.
void write_lp_fingerprint(const LpFingerprint& fingerprint, const std::string& filepath, int scene_uid = 0, int phase_uid = 0)
auto write_lp_scales(const SystemLP& system, std::string_view lp_path, LpScalesLevel level = LpScalesLevel::full, std::string_view compression = {}) -> std::expected<std::string, Error>
auto write_lp_scales_tables(const LpScalesDetail& detail, Uid scene_uid, Uid phase_uid, std::string_view columns_path, std::string_view rows_path) -> std::expected<void, Error>
void write_solver_status(const std::string& filepath, const std::vector<SDDPIterationResult>& results, double elapsed_seconds, const SolverStatusSnapshot& snapshot, SolverMonitor& monitor)

Variables

auto active_fnc
Predicate that checks if element has is_active() member returning true.
auto aperture_chunk_mode_entries
auto aperture_selection_mode_entries
auto aperture_solve_mode_entries
Includes "warm_start" / "barrier" as back-compatible aliases.
std::size_t aperture_summary_top_n
Number of phases / apertures listed in the end-of-run summary.
auto barrier_solver_entries
auto basis_cross_mode_entries
Includes "fwd2bwd" / "bwd2fwd" / "cross" as convenience aliases.
auto bound_rule_axis_entries
auto boundary_cut_sharing_mode_entries
auto boundary_cuts_mode_entries
auto boundary_cuts_valuation_entries
auto build_mode_entries
auto carrier_entries
auto cogen_mode_entries
auto compression_codec_entries
auto constraint_mode_entries
auto constraint_scale_type_entries
auto constraint_scope_entries
auto convergence_mode_entries
auto crossover_mode_entries
auto cut_drain_mode_entries
auto cut_sharing_mode_entries
auto cut_type_entries
std::string_view cvar_class_name
Column / row name tags of the CVaR construct.
std::string_view cvar_eta_name
std::string_view cvar_excess_name
auto data_format_entries
double days_per_year
Days in a standard year (non-leap).
double DblMax
Maximum representable double value used for unbounded variable bounds.
auto default_aperture_chunk_mode
THE single default for the backward-pass aperture grouping.
double default_cvar_alpha
double default_cvar_weight
double default_fast_start_max_hours
int default_sddp_aperture_drop_warn_after
int default_sddp_aperture_screen_count
auto directive_kind_entries
std::string_view EfinColName
auto elastic_filter_mode_entries
std::string_view elastic_fix_constraint_name
IntBool False
False value for integer boolean.
auto fast_sqrt_method_entries
std::string_view flow_abs_constraint_name
std::string_view flow_link_constraint_name
Flow conservation constraint on a node / waterway / line.
auto flow_right_mode_entries
auto forward_sampling_mode_entries
auto gas_compressor_drive_entries
auto gas_compressor_fuel_model_entries
auto gas_linearization_entries
auto gas_weymouth_mode_entries
ProfileLPMode generator_profile_lp_mode
auto has_value_fnc
Predicate that checks if element exists (not nullopt).
auto hot_start_mode_entries
double hours_per_day
Hours in a standard day.
double hours_per_year
Hours in a standard year.
auto integer_cuts_mode_entries
double interior_cut_rel_gap
auto is_true_fnc
std::string_view k_build_id_manifest_suffix
Suffix of the per-plugin manifest file: libgtopt_solver_x.so.build-id.
PluginCheckMode k_default_plugin_check_mode
double k_kappa_infinite
std::string_view k_kappa_mode_env
Environment variable selecting the default kappa mode.
std::string_view k_plugin_check_env
Environment variable selecting the mode when no CLI override is set.
std::string_view k_plugin_refused_marker
Text every refusal message contains (--solvers lists those errors).
int k_solver_abi_version
ABI version for the SolverBackend plugin interface.
int k_solver_build_info_version
Current layout version of SolverBuildInfo.
std::string_view k_solver_fallback_on_refused_env
int k_solver_linked_library_version
Current layout version of SolverLinkedLibrary.
int k_solver_resource_desc_version
Bumped whenever SolverResourceDescriptor gains/reorders a field.
int k_solver_version_pin_version
Current layout version of SolverVersionPin.
auto kappa_mode_entries
auto kappa_warning_mode_entries
ArrowPresentMask kArrowSparseZeroFillBit
double kDefaultGasCompressibility
Default gas compressibility factor Z.
double kDefaultGasSpecificGravity
Default gas specific gravity (air = 1).
double kDefaultGasTemperature
Default flowing gas temperature [K].
double kDefaultSlpDamping
Default SLP damping ω.
double kDefaultSlpInitialFlow
Default first-pass |f₀| as a fraction of fmax.
double kDefaultSlpMinFlow
Default minimum |f₀| as a fraction of fmax.
double kDefaultSlpProximalCost
Default SLP proximal cost ρ [$ / flow unit / h] on |f̄ − f₀|.
double kDefaultSlpTolerance
Default SLP stopping tolerance on the relative flow change.
int kDiagMaxLines
int kDiagTailLines
Number of trailing lines to keep when truncating diagnostic output.
std::string_view kirchhoff_class_name
Kirchhoff Voltage Law cycle rows on a meshed network.
std::string_view kirchhoff_cycle_constraint_name
Kirchhoff Voltage Law cycle constraint (Σ X·P = 0 around a loop).
auto kirchhoff_mode_entries
double kSddpGapFpEpsilon
double kStatePinDetectEps
int kZstdCompressionLevel
auto line_direction_mode_entries
auto line_dlr_limit_mode_entries
auto line_dlr_solar_mode_entries
auto line_dlr_span_mode_entries
auto line_flow_direction_entries
auto line_losses_mode_entries
auto line_overload_slack_bound_entries
auto line_pwl_layout_entries
auto line_thermal_limit_mode_entries
auto log_mode_entries
auto loss_allocation_mode_entries
std::string_view loss_lambda_convex_constraint_name
std::string_view loss_lambda_flow_constraint_name
std::string_view loss_link_constraint_name
Linearised line-loss constraint (segments approximating |P|² · R).
auto low_memory_mode_entries
auto lp_algo_entries
Compile-time table mapping each LPAlgo enumerator to its name.
auto lp_equilibration_method_entries
std::string_view lp_scales_cols_suffix
std::string_view lp_scales_json_suffix
Suffixes of the sidecar files written next to a model file.
auto lp_scales_level_entries
std::string_view lp_scales_rows_suffix
std::string_view lp_scales_schema
Schema identifier written in the "schema" field of every sidecar.
std::size_t lp_type_count_v
Total number of LP element types.
template<typename T>
std::size_t lp_type_index_v
Compile-time index of LP element type T in lp_element_types_t.
std::size_t max_fail_segments
double max_mip_polish_reserve_s
Upper bound, in seconds, of the polish reserve taken from the MIP.
auto method_type_entries
double min_mip_polish_time_slice_s
double min_retry_time_slice_s
double mip_polish_reserve_fraction
auto mip_start_effort_entries
auto missing_cut_var_mode_entries
auto month_type_entries
Name-value table for MonthType.
auto network_model_entries
auto NumberOptsWithInf
auto outage_reserve_mode_entries
auto output_flags_entries
auto penalty_class_entries
auto prev_stage_link_entries
auto pricing_mode_entries
auto probability_rescale_mode_entries
auto profile_owner_kind_entries
auto recovery_mode_entries
auto relax_infeasible_action_entries
auto risk_measure_entries
auto risk_rank_by_entries
auto risk_tail_entries
double sddp_alpha_bootstrap_min
std::string_view sddp_alpha_class_name
std::string_view sddp_alpha_col_name
LPClassName sddp_alpha_lp_class
Uid sddp_alpha_uid
std::string_view sddp_aperture_cut_constraint_name
CutTag sddp_aperture_cut_tag
std::string_view sddp_bcut_constraint_name
std::string_view sddp_bcut_row_prefix
CutTag sddp_bcut_tag
std::string_view sddp_boundary_cut_class_name
CutTag sddp_boundary_cut_tag
std::string_view sddp_class_name
std::string_view sddp_ecut_constraint_name
std::string_view sddp_ecut_row_prefix
CutTag sddp_ecut_tag
std::string_view sddp_elastic_sdn_col_name
std::string_view sddp_elastic_sup_col_name
std::string_view sddp_elastic_zfc_col_name
std::string_view sddp_fcut_constraint_name
std::string_view sddp_fcut_row_prefix
CutTag sddp_fcut_tag
std::string_view sddp_frcut_constraint_name
CutTag sddp_frcut_tag
std::string_view sddp_loaded_cut_class_name
std::string_view sddp_loaded_cut_constraint_name
CutTag sddp_loaded_cut_tag
std::string_view sddp_mcut_constraint_name
std::string_view sddp_plpcut_constraint_name
std::string_view sddp_scut_constraint_name
std::string_view sddp_scut_row_prefix
CutTag sddp_scut_tag
std::string_view sddp_share_cut_constraint_name
CutTag sddp_share_cut_tag
int solution_status_limit_polished
auto solve_mode_entries
auto solver_scaling_entries
auto starts_scope_entries
auto startup_tier_integrality_entries
auto state_variable_lookup_mode_entries
std::string_view storage_close_constraint_name
auto StrictParsePolicy
std::string_view system_class_name
Top-level system-wide constraint rows (e.g. emission cap).
const void* this_thread_worker_pool
auto tiny_reactance_mode_entries
auto transition_integrality_entries
IntBool True
True value for integer boolean.
auto true_fnc
Predicate that always returns true.
GroupUid unknown_group
Sentinel meaning "no group" — used for Stage and Phase scopes.
Index unknown_index
Uid unknown_uid

Daily commitment grid (Commitment.commitment_breaks)

auto clock_of_day(double hours) -> double noexcept
Clock hour of a time of day hours, reduced to [0, 24).
auto daily_cell_bounds(std::span<const double> breaks, double start_hour, double period) -> std::vector<double>
auto cell_of_time(std::span<const double> bounds, double t, double tol = 1e-9) -> std::size_t noexcept
auto daily_cells_wrap(std::span<const double> breaks, double start_hour, double period) -> bool noexcept

Compression utility functions (detail — exposed for testing)

auto gzip_lp_file_inline(const std::string& src_path) -> std::string
Inline gzip compression via zlib. Returns .gz path or empty on failure.
auto zstd_lp_file_inline(const std::string& src_path) -> std::string
Inline zstd compression via libzstd. Returns .zst path or empty on failure.
auto compress_lp_file(const std::string& src_path, const std::string& lp_compression = {}) -> std::string

Enum documentation

enum class gtopt::AmplVariableKind: std::uint8_t

Tag on each registered AMPL variable distinguishing ordinary LP columns from state-backed columns that bridge phases via the state-variable subsystem.

Current status: every entry is Regular. No registration path sets StateBacked yet, and the parser's state(<ref>) wrapper (ElementRef::state_wrapped) is accepted but not checked against this tag — wrapped and unwrapped references resolve identically. Cross-phase state for user models is provided by DecisionVariable state: true (registered through SystemContext::add_state_col), which does not use this tag. The tag is kept so a future resolver check can require state(...) exactly when the referenced entry is StateBacked.

Enumerators
Regular

Ordinary LP column scoped to this (scene, phase).

StateBacked

Also a StateVariable — cross-phase bridge.

enum class gtopt::ApertureChunkMode: uint8_t

How the backward-pass apertures of one (scene, phase) cell are grouped into work-pool tasks.

Each task clones the phase LP once and solves its apertures in series on that clone; under aperture_solve_mode = warm (the effective default) every aperture after the first in a task re-optimizes the resident basis with a few dual-simplex pivots instead of a cold solve.

  • per_scene (default): one task per (scene, phase) holding all of its apertures. Maximum warm-start reuse and one clone per cell; backward parallelism is capped at the number of scenes. Measured on a 16-scene × 16-aperture hydrothermal case: several times faster backward than per_aperture, identical bounds and peak memory. Legacy integer spelling: aperture_chunk_size = -1 (0 / unset — the former "auto" — also resolves here now).
  • per_aperture: one task per aperture, each on a fresh clone with a cold solve. Maximum fan-out, no warm-start reuse. Legacy integer spelling: aperture_chunk_size = 1 (the pre-2026-11 effective default).
  • chunked: aperture_chunk_size = K apertures per task (K ≥ 1). When K is unset the work-pool-saturation formula compute_auto_aperture_chunk_size picks it. Legacy integer spelling: aperture_chunk_size = K > 1 without a mode.

The cuts are mathematically identical across modes (the grouping only changes scheduling and the simplex path), so bounds agree up to solver tolerances. Resolution of mode + size (incl. the legacy integer encoding) lives in resolve_aperture_chunk() (sddp_aperture.hpp).

Enumerators
per_scene

All apertures of a (scene, phase) in one serial task. DEFAULT.

per_aperture

One task (fresh clone, cold solve) per aperture.

chunked

K = aperture_chunk_size apertures per task.

enum class gtopt::ApertureFailureKind: std::uint8_t

Why a non-feasible aperture solve failed, derived from the LinearInterface::get_status() code (0 optimal, 1 abandoned, 2 proven infeasible/unbounded, 3 any other non-optimal outcome) and the measured solve time.

Enumerators
infeasible

status 2: proven primal/dual infeasible

timed_out

status 1 with the solve reaching the aperture timeout

abandoned

status 1 well below the timeout (iteration/objective limit, numerical abort, solver exception)

non_optimal

status 3 (or unknown) well below the timeout: neither optimal nor proven infeasible, e.g. CPLEX infeasible-or-unbounded or unscaled infeasibilities

enum class gtopt::ApertureSelectionMode: uint8_t

How SddpOptions::num_apertures selects a subset from each phase's Phase::apertures list.

Phase::apertures is emitted by plp2gtopt sorted wettest → driest, so the choice of selection rule controls which N entries survive truncation:

  • head (default): pick the first N entries — i.e. the N wettest apertures per phase. Concentrates effort on the high-water tail of the distribution. Best for cascade L0 where the uninodal relaxation needs only the worst-case wet tail.
  • stride: pick N entries evenly spaced across the full ordered list (indices i × total / N for i = 0..N-1). Samples the whole wetness spectrum — first index is still the wettest, last index is near the driest. Best when the level wants a representative cross-section rather than the tail.

When num_apertures is nullopt, the full per-phase list is used regardless of mode. When num_apertures >= len(Phase::apertures), the full list survives in either mode.

Enumerators
head

Pick first N (wettest-N when list is wettest-first).

stride

Pick N entries evenly spaced across the full list.

tail

Pick last N (driest-N when list is wettest-first).

enum class gtopt::ApertureSolveMode: uint8_t

How each backward-pass aperture subproblem is solved and how its optimality cut's coefficients are recovered.

Apertures differ only in column (flow) bounds — or, under Flow.inflow_model / profile elements, in equality-row RHS — so the modes trade off per-solve cost against the quality / determinism of the reduced costs that become the cut coefficients:

  • cold: each aperture is an independent cold barrier solve with crossover. Crossover lands a vertex basis, so the reduced costs feeding the cut are the exact vertex duals. Byte-for-byte the legacy behaviour.
  • warm (effective default — an unset option resolves to warm in PlanningOptionsLP::sddp_aperture_solve_mode(), and plp2gtopt emits it explicitly): engages whenever a task holds more than one aperture (aperture_chunk_mode = per_scene, the default, or chunked with K > 1). The first aperture in a chunk seeds a basis (cold barrier + crossover, or a dual seed from the forward basis under basis_cross_mode = full_cross); every subsequent aperture re-optimizes that resident basis with a warm dual simplex solve (a few pivots off the previous optimum, presolve off) instead of a fresh barrier. See docs/analysis/sddp-aperture-warmstart-fullnetwork.md.
  • reduced_cost: each aperture is a cold barrier solve WITHOUT crossover. No vertex basis is formed; the cut coefficients are taken directly from the interior-point (analytic-center) reduced costs, whose tolerance-level noise is filtered by cut_coeff_eps. ~35% faster per aperture than cold on big cut-laden LPs by skipping the crossover, at the price of approximate (to barrier tolerance) duals — see the cut-validity caveat in docs/analysis/sddp-aperture-warmstart-fullnetwork.md.
  • dual_shared (opt-in, Infanger–Morton dual sharing): only the phase's highest-weight ("representative") aperture is solved; every other aperture's cut is synthesized from the representative's vertex duals. Apertures differ only in flow column bounds, so all aperture LPs share one dual feasible set; weak duality gives the valid per-aperture bound Q_a(x) ≥ L_a + Σ_i rc_i (x_i − v̂_i) with L_a = z* + Σ_j max(d_j,0)·Δl_j + Σ_j min(d_j,0)·Δu_j over the changed flow columns — shared slope, per-aperture intercept correction (Lemma AP2, docs/formulation/sddp-cut-validity.md §6). Falls back to an exact solve on non-finite / sentinel bound deltas, on row-touching aperture updates (profile elements), and until a first feasible representative exists. Target backend: re-solve-free duals for PDLP/cuOpt-style backends with no warm-start path (cut-validity ledger F10).
  • screened (opt-in): dual_shared plus an exactness screen — the aperture_screen_count synthesized cuts with the largest |intercept correction| are re-solved exactly on the resident basis (their corrections flag where the shared support is loosest).
Enumerators
cold

Cold barrier + crossover; cut from vertex reduced costs.

warm

Warm dual simplex off the resident chunk basis (per_scene / chunked K>1). EFFECTIVE DEFAULT (unset resolves to warm; see PlanningOptionsLP::sddp_aperture_solve_mode).

reduced_cost

Cold barrier, NO crossover; cut from interior-point reduced costs (filtered by cut_coeff_eps).

dual_shared

Solve the representative aperture only; synthesize the rest via Infanger–Morton dual sharing (valid per-aperture intercept correction, Lemma AP2).

screened

dual_shared + exact re-solve of the top aperture_screen_count cuts by |correction|.

enum class gtopt::BarrierSolver: uint8_t

Which interior-point implementation runs algorithm = barrier.

Only backends that ship more than one IPM read it; the others ignore it.

  • auto (default): the backend's own choice. HiGHS: HiPO, the parallel factorisation-based IPM, when the HiGHS build has it (-DHIPO=ON), otherwise IPX.
  • ipx: HiGHS IPX (serial, basis-preconditioned CG). The barrier of a HiGHS build without HiPO, and of gtopt before HiPO builds.
  • hipo: HiGHS HiPO (multithreaded). Falls back to IPX, as auto does, when the HiGHS build has no HiPO.
Enumerators
automatic

Backend default (HiGHS: HiPO if available, else IPX).

ipx

HiGHS IPX.

hipo

HiGHS HiPO.

enum class gtopt::BasisCrossMode: uint8_t

Cross-pass simplex-basis warm-start reuse between the SDDP forward and backward passes.

SDDP solves the same per-(scene, phase) LP family in both the forward pass (trial-state simulation) and the backward pass (dual/aperture cut build). A simplex basis from one pass is a valid warm start for the other: bounds and appended cut rows change, but reconcile_basis extends the basis and the dual/primal simplex repairs any residual infeasibility. A warm basis only saves pivots — it can never change the optimum or corrupt a cut (cut coefficients come from the converged solve), so every mode is correctness- neutral. Reuse silently degrades to a cold solve on backends without basis save/restore (only CPLEX and HiGHS support it) and is gated off where the forward/backward row structure is not tail-append compatible (e.g. aperture_system_file).

  • off: no basis reuse.
  • warm: same-direction reuse — each forward solve warm-starts from this cell's OWN forward basis captured the previous iteration (forward→forward) and saves its basis for the next one. No forward<->backward crossing.
  • forward_to_backward: the forward solve's basis seeds the backward dual/aperture solve of the same (scene, phase).
  • backward_to_forward: the backward basis seeds the next forward solve. On the aperture path that is the cell's aperture chain's last optimal basis (it already prices the cuts just added on α); on the non-aperture path, the post-cut target re-solve basis.
  • full_cross (effective default — an unset option resolves to full_cross in PlanningOptionsLP::sddp_basis_cross_mode(), and plp2gtopt emits it explicitly): both cross directions + forward→forward (the forward seed prefers the backward basis, falling back to its own previous forward basis when no backward basis was captured).
Enumerators
off

No cross-pass basis reuse.

warm

Reuse only within the same pass (resident basis chain).

forward_to_backward

Forward basis seeds the backward solve.

backward_to_forward

Backward basis seeds the next forward solve.

full_cross

Bidirectional + per-aperture basis caching. EFFECTIVE DEFAULT (unset resolves to full_cross; see PlanningOptionsLP::sddp_basis_cross_mode).

enum class gtopt::BasisStatus: uint8_t

Basis status of one column or row (slack) in a simplex basis.

Solver-agnostic; each backend maps to/from its native encoding (CPLEX cstat/rstat, HiGHS HighsBasisStatus, OSI CoinWarmStartBasis::Status). The numeric values intentionally match the CPLEX CPX_AT_LOWER/CPX_BASIC/CPX_AT_UPPER/CPX_FREE_SUPER constants, but backends map explicitly rather than rely on that.

Enumerators
at_lower

nonbasic, at lower bound

basic

in the basis

at_upper

nonbasic, at upper bound

free

nonbasic free / superbasic / at zero

enum class gtopt::BoundaryCutSharingMode: uint8_t

How terminal/boundary (future-cost) cuts are shared across scenes.

The terminal-phase analogue of CutSharingMode (which governs the intermediate phases). boundary_cuts_mode controls whether / from where boundary cuts are loaded; this controls how the loaded cuts are scoped to scenes on the terminal α.

  • per_scene (default): each scene's terminal α is bounded ONLY by its own scenario's boundary cuts (scene-UID matched). Valid; the terminal-phase analogue of cut_sharing_mode = none. Pairs with none / multicut.
  • shared: broadcast every boundary cut onto every scene's single terminal α. Valid only when the post-horizon value function is scenario-identical; otherwise over-tightens the terminal α (same LB > UB failure mode as the intermediate broadcast modes).
  • multicut: N terminal α columns (one per source scene), scenario-s cut → terminal varphi_s, priced at the M4 weight w_r = p_s (= 1/N under uniform probabilities). Full PLP fidelity; pairs with cut_sharing_mode = multicut.

Back-compat: the legacy boundary_cuts_mode scope values map here — separated → per_scene, combined → shared.

Enumerators
per_scene

Each scene's terminal α bounded only by its own cuts.

shared

Broadcast each boundary cut onto every scene's terminal α

multicut

N terminal α columns, cut s → varphi_s, priced at the M4 weight w_r = p_s (= 1/N under uniform probabilities)

enum class gtopt::BoundaryCutsMode: uint8_t

How boundary (future-cost) cuts are loaded for the last phase.

  • noload: Do not load boundary cuts even if a file is given.
  • separated: Load cuts per scene (scene UID matching; default).
  • combined: Broadcast all cuts into all scenes.
  • phi_expectation: PLP-literal terminal FCF. The CSV's scene column is read as a PLANE-HYDROLOGY index j (PLP ISimul, NOT a gtopt scene UID). Every scene's terminal LP carries NVarPhi = |distinct j| φ_j columns, each priced p_s / NVarPhi (the folded form of PLP's 1/NVarPhi — defprbpd.f:812-818), each bounded below by hydrology-j's cuts at FULL magnitude (the CSV must be RAW — no 1/NVarPhi pre-division). Terminal FCF = (1/NVarPhi) Σ_j max_cuts_j(V_end) = E_j[FCF_j(V_end)], an expectation over the plane hydrologies, independent of the run's scene count. The forward UB carries this term at the realized terminal volumes (PLP ZSPFAdd semantics) — see docs/formulation/sddp-cut-validity.md §9.
Enumerators
noload

Skip loading boundary cuts.

separated

Per-scene cut assignment (default).

combined

Broadcast all cuts to all scenes.

phi_expectation

PLP-literal: NVarPhi φ_j columns per LP, priced p_s/NVarPhi, raw per-hydrology cuts

enum class gtopt::BoundaryCutsValuation: uint8_t

Valuation basis for boundary (future-cost) cut coefficients and RHS.

Determines whether the effective discount factor of the last stage (combining the annual discount rate and the stage discount_factor) is applied when loading boundary cuts into the LP.

  • end_of_horizon: Cuts are valued at the end of the last stage. No discount factor is applied (default).
  • present_value: Cuts are expressed in present-value terms. The effective discount factor of the last stage is applied to the RHS and coefficients so that the future cost is discounted back to the planning horizon's reference time.
Enumerators
end_of_horizon

No discounting; cuts valued at last stage (default).

present_value

Apply last-stage effective discount factor.

enum class gtopt::BoundRuleAxis: uint8_t

The driving axis for a RightBoundRule piecewise function.

  • reservoir_volume (default): the rule input is a referenced reservoir's current volume in hm³. This preserves the Maule/Laja cushion-zone behaviour and is the only axis required by existing test fixtures.
  • stage_month: the rule input is the calendar month of the active stage (1=Jan..12=Dec). Allows a single FlowRight/VolumeRight to carry a 12-segment monthly modulation table directly, without precomputing per-stage schedules. Future: per-block axes such as demand_minus_inflow for La Invernada conditional rules.

enum class gtopt::BuildMode: uint8_t

How PlanningLP::create_systems assembles per-cell SystemLPs.

Three granularities of LP build, trading pool overhead against concurrency:

  • serial: build every cell in the calling thread with no pool, no build buffer, no futures. Honest serial baseline; also useful when you want deterministic ordering for debugging. --cpu-factor is ignored. CLI string: "serial".
  • scene_parallel (default): submit one task per scene; each task builds all of that scene's phases sequentially into its own phase_systems_t, resolves cross-phase links, and writes the result into its slot of all_systems on completion. Pre-00c605d7 default and current default — coarser granularity, lower pool-submit and malloc-arena contention, better per-worker cache locality. CLI string: "scene-parallel".
  • full_parallel: dispatch every (scene × phase) cell through an AdaptiveWorkPool so every cell builds concurrently (post-00c605d7 mode). Maximum concurrency but pays a per-cell build-buffer + move-merge overhead; opt in with --build-mode full-parallel when the case is fine-grained enough to amortise that cost. CLI string: "full-parallel".

--cpu-factor sizes the work pool for both parallel modes and is ignored under serial. Alternate names using underscores ("full_parallel", "scene_parallel") are accepted as aliases.

Enumerators
serial

No pool; build all cells in the calling thread.

scene_parallel

Parallel by scene; phases sequential (default).

full_parallel

Parallel by (scene × phase) cell via WorkPool.

direct_parallel

Parallel by (scene × phase) cell via jthreads.

enum class gtopt::Carrier: std::uint8_t

Energy carrier tag. Each value identifies a distinct balance network: an electric grid (MW_e), a water cascade (m³/s), a thermal stream (MW_th), or a hydrogen network (kg_H₂ ≡ MWh_LHV). Carriers do not mix — a Generator on a Carrier::Thermal node cannot supply a Demand on a Carrier::Electric node except through an explicit Converter.

Enumerators
Electric

Electricity (MW_e). Reserved for future Bus refactor.

Water

Water flow (m³/s). Reserved for future Junction refactor.

Hydrogen

Hydrogen energy (MWh_LHV); 1 kg-H₂ ≈ 33.3 kWh-LHV.

Thermal

Thermal energy (MW_th). CSP / district heat.

Ammonia

Ammonia energy (MWh_LHV); 1 kg-NH₃ ≈ 5.17 kWh-LHV. Long-term H₂ carrier (Haber-Bosch synthesis, NH₃ cracking back to H₂ for end-use). Easier to liquefy (-33 °C @ 1 atm) and ship than H₂.

enum class gtopt::CascadeLevelStatus: std::uint8_t

Lifecycle of a single cascade level across runs.

Enumerators
pending

Not yet entered (initial state).

in_progress

Entered but not finished — partial work on disk.

done

Solve finished (converged OR budget exhausted).

enum class gtopt::CogenMode: uint8_t

Cogeneration-unit modelling mode.

Stored on Generator.cogen_mode as an OptName (case-insensitive JSON string). The mere presence of a value tags the unit as a cogen regardless of any name-pattern heuristic; the value selects the LP bound-shape contract:

  • dispatched — the LP dispatches the unit freely on cost, identically to a normal thermal (pmin/pmax left at their rated values). Downstream tools (gtopt_marginal_units' merit-walk-up, audit dashboards) still skip the unit as "not a real market competitor" because its physical role is industrial heat supply.
  • must_run — the unit is pinned via pmin == pmax (the converter sets both bounds to the cogen's heat-bound dispatch trajectory, scalar or scheduled). Pin hardness is controlled by the existing pmin_fcost field — unset = hard pin (LP infeasibility on conflict); set = soft pin (slack at the penalty cost via the standard unserved-slack column).

Future cogen-LP work (heat-electricity coupling, multi-mode operation) will land as additional enumerators here, never as new OptName values silently parsed. Side-channel metadata that doesn't drive LP behavior belongs in the description meta block, not as new cogen_mode values.

Enumerators
dispatched

LP-free dispatch (pmin/pmax untouched).

must_run

pmin == pmax pin (hardness via pmin_fcost)

enum class gtopt::CompressionCodec: uint8_t

Compression codec for file I/O and in-memory compression.

Used for both output files (Parquet/CSV) and in-memory LP snapshots (low_memory compress mode). For in-memory use, auto_select resolves to zstd (level 1), the best ratio at negligible decompress cost.

Enumerators
uncompressed

No compression.

gzip

gzip compression

zstd

Zstandard compression (default for lp_compression).

lz4

LZ4 compression (fastest in-memory option).

bzip2

bzip2 compression (file I/O only)

xz

xz/LZMA compression (file I/O only)

snappy

Snappy compression (fast Parquet output_compression).

brotli

Brotli compression (Arrow/Parquet only).

lzo

LZO compression (Arrow/Parquet only).

auto_select

In-memory default: resolves to zstd level 1.

enum class gtopt::ConstraintMode: uint8_t

Controls error handling and verbosity for user constraint resolution.

During LP construction, user constraint expressions reference LP columns (variables), data parameters, and named user parameters. When a reference cannot be resolved (unknown element, attribute, or parameter name), this option controls whether the solver logs a warning and skips the term or raises a fatal error.

  • normal: Log warnings for unresolved references and skip the affected terms. Suitable for development and exploratory modeling.
  • strict: Treat any unresolved reference as a fatal error (default). Ensures no constraint terms are silently dropped.
  • debug: Like strict, but additionally logs detailed info about every resolved variable, parameter, and constraint row added to the LP. Useful for verifying constraint assembly.
Enumerators
normal

Warn and skip unresolved references.

strict

Fail on any unresolved reference (default).

debug

Strict + verbose logging of every resolved term.

enum class gtopt::ConstraintScaleType: uint8_t

How the LP dual of a user constraint row is scaled for output.

The LP objective accumulates cost as prob × discount × duration / scale_obj per unit. The LP dual of a row therefore carries a factor that must be inverted to recover the physical shadow price. The ConstraintScaleType determines which factors are removed:

EnumAccepted stringsInverse scale
Power"power" (default)see below
Energy"energy"see below
Raw"raw", "unitless"see below

Inverse scale formulas:

  • Power/Energy: scale_obj / (prob × discount × Δt)
  • Raw: scale_obj / discount
  • Power — constraint on an instantaneous-power (MW) variable such as generator output, load, or line flow. Dual unit: $/MW.
  • Energy — constraint on an energy (MWh) variable such as battery SoC. Dual unit: $/MWh. Uses the same block_cost_factors scaling as Power.
  • Raw / Unitless — constraint has no physical unit (e.g. a dimensionless coefficient matrix). The dual is scaled back only by the stage discount factor; probability and block duration are NOT removed. Dual unit: scale_obj / discount.
Enumerators
Power

Default — power (MW) constraint.

Energy

Energy (MWh) constraint.

Raw

Raw / unitless — only discount scaling.

enum class gtopt::ConstraintScope: uint8_t

Time-granularity at which a UserConstraint row (or a DecisionVariable column) is instantiated.

AMPL's native semantics: the index set on a declaration is the scope. scope is the granularity reduction; it is ORTHOGONAL to the for(...) clause (which restricts instances, not granularity).

EnumAccepted stringsRows / cols created
Block"block" (def.)one per (scenario, stage, block) — today
Stage"stage"one per (scenario, stage)
Phase"phase"one per (scene, phase) cell
Global"global"one per (scene, phase) cell, un-indexed
  • Block — the default and the historical behaviour: one LP row per block. A constraint over per-block variables (generator.generation).
  • Stage — a single row per stage; per-block references inside the expression must be wrapped in a sum{b in stage} time-aggregator (piece-4 step 2) so the coarse row reaches the fine variables. Built in the per-(scenario, stage) operational pass.
  • Phase — a single row per (scene, phase) cell (all scenarios / stages of the cell collapsed); built in the planning pass (add_to_phase_lp).
  • Global — a single un-indexed row per cell — the FCF α terminal cut / annual-cap shape; built in the planning pass (add_to_global_lp).

Phase and Global differ only by ORDERING / intent inside the planning pass (the phase sweep runs first so global rows can reference state columns the phase sweep registered), not by row count.

Enumerators
Block

Default — one row/col per (scenario, stage, block).

Stage

One row/col per (scenario, stage).

Phase

One row/col per (scene, phase) cell.

Global

One un-indexed row/col per (scene, phase) cell.

enum class gtopt::ConstraintType: std::uint8_t

enum class gtopt::ConvergenceMode: uint8_t

SDDP convergence criterion selection.

All modes respect min_iterations and max_iterations.

  • gap_only: Converge only when the deterministic gap closes.
  • gap_stationary: Also declare convergence when the gap stops improving.
  • statistical: Full PLP-style criterion (default). Adds a confidence-interval test for multi-scene problems.
Enumerators
gap_only

Deterministic gap test only.

gap_stationary

Gap + stationary gap detection.

statistical

Gap + stationary + CI (default, PLP-style).

enum class gtopt::ConvexKind: std::uint8_t

Shape of a nonlinear wrapper term for convexity checking.

  • UpperEnvelope applies to abs(x) and max(x_i) — both are convex functions. A term c · f(x) inside a constraint is lowerable iff c > 0 with <= (or c < 0 with >=, the algebraically equivalent form).
  • LowerEnvelope applies to min(x_i) — concave. A term c · f(x) is lowerable iff c > 0 with >= (or c < 0 with <=).
Enumerators
UpperEnvelope

abs(x), max(x_i)

LowerEnvelope

min(x_i)

enum class gtopt::CrossoverMode: uint8_t

Barrier crossover strategy after an interior-point (barrier) solve.

Decides whether the solver crosses over from the barrier interior point to a basic (vertex) solution, and — when it does — which crossover runs. Each backend maps these to its native parameters:

CrossoverModeCPLEX SolutionType + BarCrossAlgHiGHS run_crossover
automaticAUTO(0) + automatic(0)on
primalAUTO(0) + primal(1)on
dualAUTO(0) + dual(2)on
noneNONBASIC(2) — keep interior ptoff

automatic (default) lets the solver pick the cheaper of primal/dual. primal is currently the best crossover for the GTEP barrier solves when a basis IS needed, so the internal vertex-dual paths request it explicitly. none keeps the interior point (no crossover) for speed — its duals are the analytic-center multipliers. Note: CPLEX's deprecated BarCrossAlg = -1 ("no crossover") is NOT how none is expressed — CPXsetintparam rejects that value; none maps to SolutionType = NONBASIC instead.

Enumerators
automatic

Cross over; let the solver choose primal/dual (default).

primal

Cross over via primal crossover.

dual

Cross over via dual crossover.

none

No crossover — keep the barrier interior (non-basic) point.

enum class gtopt::CutDrainMode: uint8_t

How the SDDP async path drains in-flight cuts after the aggregate-convergence signal fires.

When m_stop_requested_ flips in SDDPMethod::solve_async (because the aggregate tracker certified an iter as converged), some scenes can still have an in-flight forward+backward pass for the NEXT iter — under max_async_spread > 0, a fast scene may be up to max_async_spread iters ahead of the slowest one. Cuts added by those still-running tasks AFTER the stop signal are non-deterministic (their inclusion depends on pool drain timing); we must drop them so the cut count handed off to the next cascade level is reproducible.

Three drain strategies are available:

  • count — snapshot each scene's cut count at the boundary (per-scene, recorded the moment m_stop_requested_ flips). Any cuts pushed past that snapshot get truncated. Cuts already in the store at the boundary (including a fast scene's iter-(N+1) head-start cuts) are kept. Asymmetric across scenes: faster scenes carry more cuts into the next level.
  • iteration — drop every cut whose iteration_index is greater than the last aggregate-certified iter (i.e. results.back().iteration_index). Symmetric: every scene retains cuts up to the SAME iter; faster scenes lose their head-start cuts. Bit-for-bit reproducible irrespective of pool timing. Recommended default.
  • all — no truncation at all; every cut currently in the store (including any race cuts that landed after the stop signal) is kept. Maximises learned-cut retention at the cost of run-to-run determinism — the inherited cut count for the next cascade level will vary depending on how many in-flight tasks happened to finish before the orchestration loop exited.

Default iteration (introduced 2026-05). Switch to count to preserve the legacy asymmetric behaviour, or to all if convergence at the next cascade level is more important than reproducibility.

Enumerators
count

Snapshot per-scene cut count at the stop boundary. Legacy behaviour; asymmetric across scenes.

iteration

Filter by cut.iteration_index <= last_certified_iter. Default; symmetric and run-to-run deterministic.

all

Keep every cut currently in the store — no truncation. Trades determinism for maximum cut retention.

enum class gtopt::CutSharingMode: uint8_t

SDDP cut sharing mode across scenes in the backward pass.

When multicut is selected, the backward pass is synchronized per-phase: all scenes complete a phase before cuts are broadcast and the next phase is processed.

  • none (default): each scene's single α is bounded only by that scene's own cuts. Every scene optimises against its OWN persistent-sample-path cost-to-go, so the LB is the wait-and-see bound Σ_s p_s·C_s^opt — unconditionally valid (theorem N1 in docs/formulation/sddp-cut-validity.md §7).
  • multicut (PLP-faithful): each scene-LP carries N α columns (varphi_0..N-1, one per source scene), each bounded ONLY by its own scenario's cuts and priced at the M4 weight w_r = p_s (the owning scene's normalized probability, uniform across the N columns — alpha_unit_cost; = 1/N under uniform probabilities); a scene-S cut targets varphi_S in every destination LP. The resulting recursion is the Bellman recursion of the stagewise-resampled process with measure q_r = p_r (scene data redrawn at every phase boundary), so the LB is a valid lower bound for that process for any probability vector (theorems M1/M4; the pre-M4 uniform 1/N pricing was unsound for non-uniform probabilities — theorem M3, fixed 2026-07-08). Note the objective's future term is the expected cost-to-go of the resampled process — NOT a general E[Q] identity for the persistent process. Mirrors PLP plp-agrespd.fAgrResPD (IColx = NCol-NSimul+ISimul). Full statements and proofs: docs/formulation/sddp-cut-validity.md §8.
  • markov (opt-in, experimental): Markov-chain SDDP — each scene-LP carries M future-cost columns varphi_0..M-1 (one per Markov state), scene-S's backward cut lands on varphi_{m(S)} in every scene-LP, and varphi_{m'} is priced w_{s,m'} = p_s·P[m(s)][m'] / pi_{m'} (theorem MK1). Requires markov_states (scene→state assignment) and markov_transition (row-stochastic M×M matrix) in sddp_options. Generalizes multicut: M = N singleton states with transition rows equal to the normalized scene probabilities reproduce the multicut layout. Full derivation and validity conditions: docs/formulation/sddp-markov.md.
Enumerators
none

No sharing; each scene's single α is bounded only by its own cuts (per-scene persistent-path bound; unconditionally valid LB — theorem N1)

multicut

PLP-faithful: N α columns per scene-LP (one per source scene), each bounded ONLY by its own scenario's cuts, priced w_r = p_s (M4; = 1/N under uniform probabilities) → valid LB for the stagewise-RESAMPLED process with measure q_r = p_r for any probability vector (theorems M1/M4)

markov

Markov-chain SDDP (opt-in, experimental): M α columns per scene-LP (one per Markov state), cut s → varphi_{m(s)}, priced p_s·P[m(s)][m']/pi_{m'} → valid LB for the Markov-modulated resampled process (theorem MK1 in docs/formulation/sddp-markov.md; singleton states exact, multi-scene states valid-but-loose under A2)

enum class gtopt::CutType: uint8_t

Type of Benders cut: optimality (standard) or feasibility (elastic filter).

Enumerators
Optimality

Standard Benders optimality cut.

Feasibility

Feasibility cut from elastic filter.

enum class gtopt::DataFormat: uint8_t

File format for input/output data files.

Enumerators
parquet

Apache Parquet columnar format (default).

csv

Comma-separated values.

enum class gtopt::DirectiveKind: std::uint8_t

Constraint-family discriminator. Each value selects a typed payload shape (validated by ConstraintDirective::valid_for_kind()) and a policy (penalty tier, daily aggregation, gating) that UserConstraintLP applies at LP-build time.

Kept uint8_t so the enclosing ConstraintDirective stays cheap to pass by value.

Enumerators
RegRange

PLEXOS regulation-range UC (*_RegRange_e[12]). Couples commitment(g).status with reserve_provision(g, .).{up|dn}; LP-relax needs the directive's soft-penalty override to absorb the implied-bounds chain into a finite-cost slack (task #51).

ReserveProvSum

Σ_g reserve_provision(g, R).{up|dn} ≥ requirement aggregator. Covers the CSF / CPF / CTF *MinProvision and *UpMinProvision shapes. Same soft-penalty tier as RegRange.

DailyBudget

Per-day cumulative budget (typical scope tags: fuel:GAS, owner:CSF, region:Z1). Implies daily_sum = true at LP-build time. Subsumes the _consolidate_gas_maxopday_groups post-processor that today rewrites Gas_MaxOpDay rows in plexos2gtopt/parsers.py.

HydroFloor

Reservoir floor gated on a commitment-status variable (efin ≥ X only when the unit is on). Reserved for the P2 follow-up — wired here so the JSON schema is stable, but UserConstraintLP does not yet honour the gate (treated as a pass-through directive in Step 1).

MaxStartsWindow

Σ_{τ ∈ window(N h)} startup(g, τ) ≤ MaxStarts(g). Reserved for the P2 ordered-time primitives (window(N h, expr)). Step 1 honours window_hours = 24 as a DailyBudget alias; other windows are wired but no-op until P2.

enum class gtopt::DroppedTermKind: std::uint8_t

Why a KNOWN element reference resolved to no LP column at one (scenario, stage, block). Every kind but scope_mismatch is an intentional absence: the term is an implicit 0.

Enumerators
suppressed

class/attribute disabled by the planning mode

inactive

element inactive at this stage

prev_first_block

prev(...) / _prev at the stage's first block

block_omitted

column registered at this stage, not this block

zero_capacity

pmax / lmax / tmax = 0 at this block

not_materialised

attribute never built for this element so far

scope_mismatch

The element is ACTIVE here and its column for this attribute was registered at an earlier stage of this LP, but not at this one: a registration / scope mismatch, never an implicit 0.

enum class gtopt::ElasticFilterMode: uint8_t

How the elastic filter handles feasibility issues in the backward pass.

  • single_cut: Build a single Benders feasibility cut.
  • multi_cut: Build a Benders cut + per-slack bound cuts.
  • chinneck (default): Run a Chinneck-style elastic IIS filter — identify the irreducible infeasible subset of fixed state-variable bounds, then emit per-IIS-bound multi-cuts plus a tightened Benders cut whose reduced costs come from the IIS-restricted clone. More LP solves per fcut event than multi_cut, but the cuts forbid only the true infeasibility-causing region (Chinneck, Feasibility and Infeasibility in Optimization, 2008, §3.5; PLP osi_lp_get_feasible_cut). Falls back to the full elastic result when the IIS re-fix step cannot confirm a smaller subset, so behaviour is no worse than multi_cut in the worst case.
  • state_repair (alias plp): exact reproduction of PLP's feasibility-cut formulation (plp-agrespd.fAgrElastici + osicallsc.cpp::osi_lp_get_feasible_cut, default FOneFeasRay=FALSE). Elastic Phase-1 clone with unit slack costs tilted by 0.01× the previous-basis reduced cost of each state column; one single-variable cut ray_i · x_i ≥ ray_i · nx_i · (1 + fact_eps) per link with |ray_i| above the PLP emission tolerance. NO box clamp, NO saturation / degenerate-family drops, NO aggregated fallback — the RHS is bound-consistent by construction because the elastic slack caps equal the previous phase's state box. Cuts persist across iterations (exempt from forward_infeas_rollback). Tolerances: sddp_options.fact_eps (PLP FactEPS); cycle cap: sddp_options.fact_max_cycles (PLP FactMXC). See build_plp_feasibility_cuts.
  • farkas_recursive: the published SDDP-correct RECURSIVE feasibility cut (Füllner & Rebennack, SIAM Review 2023, §17.2–17.3). Elastic Phase-1 clone with flat unit slack costs (the review's eᵀy⁺ + eᵀy⁻, no rc tilt) that ADDITIONALLY relaxes every feasibility-cut row already installed in the stage LP with a + z_r slack (the §17.2 + I z term) — so the clone always solves even when a previously-installed cut is itself unsatisfiable at the trial (the "relaxed clone infeasible" kill chain). Emits ONE aggregated cut per event on the previous phase, Σ σ_i·x_i ≥ Σ σ_i·v̂_i + V, whose intercept folds the downstream cut intercepts ω_rᵀb_r through the clone optimum V (strong duality — eq. (17.3)). Built from ordinary optimal duals only, never a solver Farkas/ray API (solver-independence directive). Shares fact_eps / fact_max_cycles and the rollback exemption with state_repair. See build_farkas_recursive_cut.
Enumerators
single_cut

Build a single Benders feasibility cut.

multi_cut

Build a Benders cut + per-slack bound cuts.

chinneck

Build cuts only on the Chinneck IIS (default).

state_repair

PLP-exact single-variable cuts (AgrElastici parity; canonical name for the legacy "plp")

farkas_recursive

Füllner–Rebennack §17.2–17.3 recursive aggregated cut (installed fcut rows elasticized with +z; ω·b folded via V)

enum class gtopt::ErrorCode: uint8_t

Enumerators
Success

SolverError

InternalError

InvalidInput

FileIOError

Cancelled

Cooperative stop (request_stop / sentinel / API stop file) hit mid-pass. Not a solver failure: SDDP must not treat it as an infeasible scene (no retry-state change, no cut rollback).

enum class gtopt::FastSqrtMethod: uint8_t

Fast approximate sqrt method for Ruiz equilibration.

Controls which sqrt implementation is used inside the Ruiz scaling loop. Since Ruiz is iterative and self-correcting, an approximate sqrt only affects convergence speed, not final accuracy.

  • ieee_halve: IEEE 754 exponent halving (~2-3% accuracy, ~1 cycle).
  • newton1: ieee_halve + one Newton-Raphson step (~0.1% accuracy).
  • std_sqrt: Standard library std::sqrt (exact, ~10-20 cycles).
Enumerators
ieee_halve

IEEE 754 exponent halving (default).

newton1

ieee_halve + one Newton-Raphson refinement

std_sqrt

Standard library std::sqrt.

enum class gtopt::FlowRightMode: std::uint8_t

Time resolution of a FlowRight (flow_mode).

  • per_block (default): per-block flow column, per-block kink.
  • stage_average: per-block flow column + stage qeh column; the kink and costs apply to qeh.
  • stage_uniform: one stage qeh column used in every block balance.

enum class gtopt::ForwardSamplingMode: uint8_t

How the SDDP forward pass samples the stochastic scene data.

  • persistent (default): every scene-driver simulates its OWN scenario data at every phase — the historical behaviour. The forward UB is then the Monte-Carlo estimate of the PERSISTENT per-scene process (each scene rides one frozen sample path end to end). Fully gated: this mode never enters the resampling code and is byte-identical to pre-option builds.
  • resampled: at every phase boundary (phase > 0) the driver re-draws a scene realization with probability p_r (normalized scene probability_factors) and overwrites the phase LP's stochastic bounds with the drawn scene's data via the bound-only update_aperture machinery (flow discharges + profile bounds — the same per-element path the aperture backward pass uses; writes are replay-recorded so low-memory reconstructs preserve them). The forward UB then estimates the stagewise-resampled process with measure q_r = p_r — the SAME process the cut_sharing = multicut lower bound certifies (theorems M1/M4, docs/formulation/sddp-cut-validity.md §8), removing the Corollary-M2 UB/LB process mismatch by construction.

v1 semantics (resampled): ONE sampled path per scene-driver per iteration; the draw is a pure deterministic function of (iteration, scene, phase) (sample_forward_realization — stable under forward-pass backtracking and thread scheduling); the drawn id is cached on PhaseStateInfo::sampled_scene so the backward pass re-solves the SAME realization; the simulation pass restores each scene's own persistent data so final outputs keep per-scene semantics. On heterogeneous dynamics the pure-Benders backward's cuts are built at the sampled realization (WARN-tier vs the persistent tails — theorem doc §8 remark); the certified heterogeneous route remains the aperture backward pass.

Enumerators
persistent

Each scene-driver on its own path (default; legacy).

resampled

Probability-weighted re-draw at every phase boundary (deterministic seed; matches the multicut LB process).

enum class gtopt::GasCompressorDrive: uint8_t

Driver of a GasCompressor (drive).

  • gas (default): the fuel is drawn from the suction node.
  • electric: the fuel equivalent is drawn as power from bus.

enum class gtopt::GasCompressorFuelModel: uint8_t

Fuel model of a GasCompressor (fuel_model).

  • fixed_fraction (default): LC = γ_ff Ψ.
  • saldarriaga: Taylor planes of LC = γ (β^α − 1) Ψ.
  • none: no fuel.

enum class gtopt::GasLinearization: uint8_t

Linearisation of a weymouth_mode: linearized pipe (linearization).

  • secant (default): π_a − e^s π_b = K_e |f₀| f.
  • tangent: π_a − e^s π_b = 2 K_e |f₀| f − K_e f₀ |f₀|.

enum class gtopt::GasWeymouthMode: uint8_t

Pressure-flow model of a GasPipe (weymouth_mode).

  • radial (default): fixed direction a → b, Weymouth tangent outer approximation (exact on radial networks).
  • linearized: signed flow, one equality per block linearised at a reference flow f₀ (meshed networks; refined by the gas SLP).
  • none: capacity-only arc a → b, no pressure coupling.

enum class gtopt::GridCell: char

Phase grid cell states (ordered by display priority).

enum class gtopt::HotStartMode: uint8_t

How the SDDP solver handles hot-start and the output cut file.

Controls both whether to load cuts from a previous run and how to handle the combined output file (sddp_cuts.csv) at the end of the solve.

Enumerators
none

Cold start — no cuts loaded (default).

keep

Hot-start; keep original output file unchanged.

append

Hot-start; append new cuts to original file.

replace

Hot-start; replace original file with all cuts.

enum class gtopt::IntegerCutsMode: uint8_t

How the SDDP backward pass builds optimality cuts on cells whose LP carries integer columns (integer expansion modules, unit-commitment binaries, …).

  • none (default): legacy behaviour, byte-identical — the backward pass reads whatever the target solve produced. On pure-LP cells this is the certified Theorem-O1 cut; on integer-bearing cells it is UNSOUND (a MIP re-solve has no reduced costs; the emitted cut degenerates to a flat α ≥ z_MIP(v̂) that can overshoot — see docs/analysis/investigations/sddp/sddip_integer_expansion_2026-07.md §1). Kept as the default so pure-LP runs pay nothing and existing behaviour is unchanged.
  • strengthened: strengthened Benders cuts (Zou, Ahmed & Sun 2019 §5). On integer-bearing cells the backward step clones the target LP, relaxes integrality, solves the LP relaxation at the pinned trial state (duals λ = pinned reduced costs — the sound LP-relaxation cut), then re-instates integrality, relaxes the state pins to their physical box, charges −λ on the state columns, and solves ONE MIP: its optimum is the Lagrangian value L(λ) − ⟨λ, v̂⟩, which replaces the cut intercept. Valid by weak Lagrangian duality (Theorem SB1 in the investigation doc) and never looser than the LP cut (Corollary SB2). Falls back silently to the LP-relaxation cut when the MIP solve fails or times out. Pure-LP cells never enter this path.
Enumerators
none

Legacy behaviour (LP cells certified; MIP cells unsound).

strengthened

LP-relaxation cut + Lagrangian (MIP) intercept.

enum class gtopt::IntegerDomain: std::uint8_t

Solver-level domain of an integer-registered LP column.

Binary and Integer are reified at LP build time as is_integer = true on the underlying SparseCol. Relaxed means the user (or global option) asked for the LP relaxation: the column stays continuous in its declared bounds.

The Relaxed form is what the SDDP backward pass already uses; making the relaxation site explicit lets cut audits and integer-feasibility checks distinguish "intentionally relaxed" from "should have been integer but escaped the choke-point".

Enumerators
Binary

{0, 1}

Integer

[lowb, uppb] integer

Relaxed

continuous over the declared bounds

enum class gtopt::IntegerScope: std::uint8_t

Time-grid scope of an integer-registered LP column.

Set at the call site by the producer — the layout resolver may refine WITHIN a scope (e.g. picking which named layout a Group uses) but never crosses scopes. A binding that targets a Phase-scoped column with a chronological layout is rejected at load time.

Block — one column per (stage, block); the identity layout. Group — one column per (stage, group); group = contiguous run of blocks. Stage — one column per stage, layout-immune. Phase — one column per phase, layout-immune, scenario-invariant.

enum class gtopt::IntegrityVerdict: int

enum class gtopt::KappaMode: uint8_t

How the basis condition number (kappa) is obtained after a solve.

gtopt reads kappa after every solve (logs, SDDP numerics monitoring).

  • estimate (default): the solver's cheap estimate. HiGHS: Hager estimate (getKappa(exact=false)); CPLEX: CPX_KAPPA.
  • exact: the exact value, for diagnostics. HiGHS: getKappa(exact=true), one FTRAN per basis row (the plugin's behaviour before 2026-11; ~75 % of HiGHS CPU on CEN SDDP cells); CPLEX: CPX_EXACT_KAPPA.
  • off: never computed (kappa reported as unavailable).
  • Gurobi: Kappa / KappaExact. OSI/CLP: estimate and exact both return its dual-error proxy. MindOpt, SCIP, cuOpt: no kappa query (always unavailable).

off is honoured above the backend too: LinearInterface does not call the backend at all. With any mode, kappa is read once per solve.

Enumerators
estimate

Cheap estimate (default).

exact

Exact condition number (expensive).

off

Not computed.

enum class gtopt::KappaModeSource: int

Where the default kappa mode came from.

Enumerators
compiled_default

GTOPT_KAPPA_MODE_DEFAULT (CMake)

environment

$GTOPT_KAPPA_MODE

enum class gtopt::KappaWarningMode: uint8_t

Controls warnings when the LP condition number (kappa) exceeds a threshold.

After each LP solve (forward, backward, aperture, and monolithic), the solver checks the basis condition number. When kappa exceeds kappa_threshold (default 1e9), this option controls the response.

  • none: No kappa checking or warnings.
  • warn: Log a warning with scene, phase, and iteration (default).
  • save_lp: Log a warning AND save the culprit LP file for debugging.
  • diagnose: Like save_lp, but also analyze cut rows to identify which Benders cuts have the worst coefficient ratios.
Enumerators
none

No kappa checking.

warn

Log a warning when kappa exceeds threshold (default).

save_lp

Warn and save the LP file.

diagnose

Warn, save LP, and analyze cut coefficient ranges.

enum class gtopt::KirchhoffMode: uint8_t

Selects the Kirchhoff Voltage Law (KVL) formulation.

  • node_angle (0): the classical B–θ form. One bus angle (theta) variable per active bus, plus one KVL equality per active line per block: −θ_a + θ_b + x_τ · f_p − x_τ · f_n = −φ where x_τ = τ · X / V². A reference bus per island has its theta pinned at 0 to fix the gauge. Required for line expansion that changes topology per stage and for phase-shift transformers.
  • cycle_basis (1, default): the loop-flow form — eliminates theta entirely and replaces per-line KVL with one equality per fundamental cycle: Σ_{l∈C} ε_l · x_l · (f_p − f_n) = Σ_{l∈C} ε_l · φ_l with ε_l ∈ {+1,−1} the cycle direction sign. No reference-bus pin, no theta column scale to tune, typically (|L| − |B| + #islands) rows per block instead of |L| — strictly smaller LP for meshed grids. PyPSA-style; reference: Hörsch et al., "PyPSA: Python for Power System Analysis", 2018.

Default: cycle_basis. Selected via model_options.kirchhoff_mode (string) or the --kirchhoff-mode CLI flag. See kirchhoff_node_angle.hpp for the row-assembly helper.

Enumerators
node_angle

B–θ formulation (per-line KVL row, gauge-pinned).

cycle_basis

Loop-flow formulation (per-cycle KVL row, no theta).

enum class gtopt::LineDirectionMode: uint8_t

Global radial-line detection (model_options.line_direction_mode).

  • off (default): no detection; the LP is unchanged.
  • report: detect radial (bridge) lines and their structural flow direction and log the classification; the LP is unchanged.
  • structural: as report, and apply the certified one-way and dead-end lines (lines without an explicit flow_direction). KVL rows of radial lines are kept (with angle bounds they still cap the flow under node_angle). Lines referenced by user constraints and switchable (line-commitment) lines are excluded.
Enumerators
off

no detection (default)

report

detect and log only

structural

detect and apply the certified directions

enum class gtopt::LineDlrLimitMode: uint8_t

How a dynamic line rating (Line.dlr) combines with the static conductor rating of the line.

  • replace (0): the DLR rating IS the conductor's thermal capacity and replaces conductor_rating_*; on a line without a conductor rating it replaces max_rating / min_rating instead. Flow, outage, equipment and security limits always apply.
  • min (1): min(static limits, DLR) in every block.

Unset (per line and in model_options): replace on lines with a conductor_rating_*, min otherwise (the historical min(tmax, DLR)).

Enumerators
replace

DLR replaces the static thermal rating.

min

min(static tmax, DLR rating)

enum class gtopt::LineDlrSolarMode: uint8_t

How the DLR heat balance treats the solar_irradiance input.

  • ghi (0, default): the input is the global horizontal irradiance and is used directly as the absorbed flux, q_s = α·S·D — the conservative "full sun on the conductor" convention, shared with the Python critical-span tooling (no sun-geometry model).
  • none (1): the solar gain is ignored, q_s = 0 (night-time / sensitivity runs); solar_irradiance becomes optional.
Enumerators
ghi

q_s = α·S·D with S = GHI (default)

none

q_s = 0

enum class gtopt::LineDlrSpanMode: uint8_t

How the critical spans of a dynamic line rating (Line.dlr) limit the line flow.

  • min (0, default): per block, the effective rating is the minimum over the spans (and the static tmax), applied where tmax is applied today (flow-column bound or thermal-limit row). Smallest LP; the argmin span is recorded.
  • rows (1): one thermal-limit row pair per critical span and block, f_dir + a·ℓ_dir ≤ T_k,b. Rows of spans dominated in a block are dropped at build time. Same optimum as min; the per-span duals come straight from the solver.
Enumerators
min

effective rating = min over spans (default)

rows

one row pair per non-dominated span

enum class gtopt::LineFlowDirection: uint8_t

Allowed flow direction of a line (Line.flow_direction).

  • both (default when unset and the global mode is off): the line carries flow in both directions — today's LP.
  • ab / ba: user-asserted one-way line. The opposite direction is given a zero limit (exactly as tmax_ba = 0 / tmax_ab = 0), so the reverse flow column(s), loss segments and rows are not emitted and tangent_signed_flow builds its one-sided form.
  • auto: use the structural certificate of line_direction.hpp (radial line whose cut-off side can only withdraw or only inject), even when model_options.line_direction_mode is off.

Unset → follows model_options.line_direction_mode (structural behaves as auto, off / report as both).

Enumerators
both

flow in both directions (default)

ab

one-way bus_a → bus_b

ba

one-way bus_b → bus_a

automatic

structural detection (JSON name "auto")

enum class gtopt::LineKvlKind: uint8_t

How the Kirchhoff assemblers treat one line at one stage.

Enumerators
dc

no KVL coupling (reactance unset, or zero / tiny in dc mode)

tie

zero-impedance tie: KVL row without the flow term

ac

regular AC line: full KVL row with x_τ = τ·X/V²

enum class gtopt::LineLossesMode: uint8_t

Selects the mathematical model for transmission line losses.

Each mode trades off accuracy, LP size, and solver compatibility:

  • none (0): No losses. Flow balance: P_send = P_recv. Simplest model; suitable when losses are negligible or handled externally.
  • linear (1): Lumped linear loss factor λ. P_loss = λ · |f|. If the line has resistance > 0 and voltage > 0 but no explicit lossfactor, one is auto-computed as λ = R · f_max / V² (linearization at rated flow of the quadratic curve P_loss = R · f² / V²). Zero extra LP rows; loss enters as bus-balance coefficients. Ref: Wood & Wollenberg, "Power Generation, Operation and Control", Ch. 13, incremental transmission losses.
  • piecewise (2): Piecewise-linear approximation of P_loss = R · f² / V². The historical single-direction implementation used one shared K-segment set covering [0, f_max] with link row fp + fn − Σ seg_k = 0 and a single shared loss column charged once to one bus. As of 2026-05-31 piecewise is implemented as a thin wrapper around bidirectional for every non-tangent PWL layout: the single-direction shared-loss formulation is structurally vulnerable to a phantom-flow arbitrage (fp · fn > 0 while only one bus pays loss) that inflates total system loss in meshed networks with negative-LMP receiving buses. Selecting piecewise therefore now produces the same LP shape as bidirectional (2 × K segment columns, per-direction link + loss-tracking rows, per-direction loss column). The legacy single-direction code path is kept only for LinePwlLayout::tangent, which has no per-direction counterpart. Segment k (1-based) has loss coefficient (f_max/K) · R · (2k−1) / V² (uniform layout). Ref: Macedo, Vallejos, Fernández, "A Dynamic Piecewise Linear Model for DC Transmission Losses in Optimal Scheduling Problems", IEEE Trans. Power Syst., vol. 26, no. 1, 2011; FERC Staff Paper, "Optimal Power Flow Paper 2: Linearization", December 2012 (bidirectional shape).
  • bidirectional (3): Two independent piecewise-linear models, one per flow direction (A→B and B→A). Each direction gets its own K segment variables + linking + loss-tracking rows. Produces 2× the rows and columns of piecewise but explicitly prevents simultaneous bidirectional flow through non-negative variable bounds. Ref: FERC Staff Paper, "Optimal Power Flow Paper 2: Linearization", December 2012.
  • adaptive (4): Automatically selects an arbitrage-free PWL mode based on whether the line carries capacity expansion:
    • has expansion → bidirectional (capacity rows need the per-direction decomposition)
    • no expansion + any KVL → piecewise (which itself wraps bidirectional for non-tangent layouts; both produce identical LP). The previous shortcut that routed cycle_basis + no-expansion to piecewise_direct has been retired because piecewise_direct is not phantom-flow safe on meshed networks with negative-LMP receivers (see piecewise_direct docstring below). Recommended default for any GTEP case that may produce negative receiver LMPs (curtailment-priced demand, must-dispatch surplus, congestion).
  • dynamic (5): Iteratively adjusted piecewise-linear segments that track the current operating point. Achieves higher accuracy with fewer segments than static PWL. Currently a placeholder that falls back to piecewise with a log warning. Ref: Macedo et al. (2011), §III — dynamic cut adjustment.
  • piecewise_direct (6): PLP-faithful two-direction piecewise-linear model for lines without capacity expansion. Per direction, K segment variables (bound [0, tmax_dir/K]) inject directly into the bus-balance rows with the per-segment loss factor λ_k = (tmax_dir/K) · (2k−1) · R / V² baked into the coefficients (PLP genpdlin.f). There is no loss variable, no loss-tracking row, no aggregator column, and no flow-link row: each segment also stamps directly into the Kirchhoff (KVL) row with ±x_τ. This produces the most compact LP (2K cols, 0 extra rows per block per line) and matches the row count of PLP exactly.

    ⚠ Phantom-flow caveat: because there is NO link row and NO fp/fn aggregator, the LP has no structural barrier preventing simultaneous non-zero positive- AND negative-direction segments. Empirically on a large national test case, piecewise_direct is the WORST mode for phantom bidirectional flow. In meshed networks with blocks where the receiving bus has negative LMP, the LP can inflate both directions to dump quadratic loss "for free" at the negative-LMP bus. Use bidirectional (or piecewise, which now wraps bidirectional) instead when phantom-flow purity matters more than LP row count. piecewise_direct is only safe in networks that never see negative LMPs at receiving buses (PLP's historical operating regime).

    Trade-off: the line.flowp / line.flown solution columns are not emitted for piecewise_direct lines — the AMPL compound line.flow is unavailable for these lines (use piecewise if you need it). Activation: opt-in only — adaptive prefers piecewise (smaller LP per block, but more rows). Select explicitly for PLP-diff parity or to halve the LP size on transmission-heavy cases. On expandable lines this mode falls back to piecewise with a warning. Ref: PLP Fortran genpdlin.f (GenPDLinA).

  • tangent_signed_flow (7): Coffrin-style outer approximation on a SINGLE signed flow variable. Per (line, block) the LP carries:
    • one signed flow column f ∈ [−tmax_ba, +tmax_ab] (no flowp/flown decomposition; KVL uses f directly);
    • one loss column ℓ ∈ [0, (R/V²)·fmax²] (the quadratic upper envelope on [−fmax, +fmax], exact at the rated flow);
    • K tangent inequalities of the form ℓ ≥ (2·R/V²)·f_k·f − (R/V²)·f_k², k = 1..K where f_k are uniformly spread (midpoint placement) across [−fmax, +fmax]: f_k = fmax · (2k − K − 1) / K.

    Each tangent is the gradient of the quadratic loss curve at f = f_k; the K-fold maximum is a piecewise-affine LOWER approximation of ℓ(f) = (R/V²)·f², exact at every tangent point and within (fmax/K)²·R/V² of the curve at the partition boundaries. Combined with the upper bound on ℓ, the LP's feasible loss region tightly brackets the true quadratic.

    ✔ Phantom-flow IMPOSSIBLE by construction: there is no fp/fn decomposition, so the LP has no way to express simultaneous bidirectional flow on a line. KVL stamps the single signed f column with its natural ±x_τ coefficient. ⚠ Loss-side arbitrage is still OPEN under a negative bus-dual pair-sum: the abs-flow proxy v is only lower-bounded by ±f, so the LP can inflate v past |f| and ride the loss up the chord row (idle line → sink of c·env² MW). loss_cost_eps (on the loss column, ≥ ½·|worst pair-sum|) closes it at loss-scaled cost (see line.hpp); the exact fix is the SOS2 λ-form. Demonstrated in test_line_losses_negative_lmp_kvl.cpp.

    LP size (per line per block): (2+L) cols + (K+3) rows (signed flow, loss column, L abs-flow v cols; K tangent rows — the zero-slope middle tangent is DROPPED when K is odd, so prefer EVEN K — plus 2 abs rows and 1 chord row). At K=5, L=1 that's 3 + 7 = 10 elements vs bidirectional at K=5 (14 + 4 = 18) — roughly 44 % fewer while preserving the convex-quadratic shape.

    Works with BOTH node_angle and cycle_basis Kirchhoff modes (the signed f column drops directly into the KVL row with +x_τ instead of the +x_τ·fp − x_τ·fn pair).

    Activation: opt-in only via explicit line_losses_mode = "tangent_signed_flow". The adaptive resolver does NOT route here (its decision tree is unchanged); a future PR can lift the constraint after wider-system validation on negative-LMP and expansion-line workloads.

    Refs:

    • Coffrin & Van Hentenryck, A Linear-Programming Approximation of AC Power Flows, INFORMS J. Computing, 2014 (arXiv:1206.3614).
    • Aigner & Van Hentenryck, Line Loss Outer Approximation, arXiv:2112.10975 (2022).
Enumerators
none

No losses modeled.

linear

Lumped linear loss factor.

piecewise

Per-direction PWL (wraps bidirectional; PLP-named).

bidirectional

Two-direction piecewise-linear.

adaptive

Piecewise if fixed capacity, bidirectional if expandable.

dynamic

Dynamic piecewise-linear (future; falls back to piecewise).

piecewise_direct

PLP-style compact PWL (NOT arbitrage-proof, see docstring).

tangent_signed_flow

Coffrin outer-approximation; single signed flow column (NO fp/fn) + K tangent rows; phantom-flow impossible.

enum class gtopt::LineOverloadSlackBound: uint8_t

Upper bound of the overload slack (the overload_penalty band between the normal threshold and the hard cap).

  • thermal (0, default): the conductor's thermal headroom capped by the ratio, min(hard − normal, max_overload_ratio × normal) — on DLR lines hard is the IEEE 738 emergency rating (at tmax_conductor_emergency) and normal the rating at tmax_conductor; on static lines tmax and tmax_normal. Without a finite hard cap (no emergency data) it is ratio.
  • ratio (1): max_overload_ratio × normal (default ratio 1.5, i.e. slack ≤ +150 %, flow ≤ 2.5 × normal).
  • unbounded (2): no bound on the slack; the hard cap is enforced only by the flow bound / thermal rows (previous DLR behaviour).
Enumerators
thermal

min(hard − normal, ratio × normal); default

ratio

max_overload_ratio × normal

unbounded

no slack bound

enum class gtopt::LinePwlLayout: uint8_t

Segment-layout strategy for the piecewise-linear loss model.

Applies only when line_losses_mode is piecewise, bidirectional, adaptive, dynamic, or piecewise_direct. Controls where the breakpoints are placed along [0, envelope] and what kind of lines (secant chords vs. tangent supports) approximate the quadratic loss curve ℓ(f) = (R/V²)·f².

  • uniform (0, default): equal-width secant chords. Breakpoints at b_k = (k/K)·envelope; each segment's chord slope is (R/V²)·width·(2k−1). Backwards-compatible with all bundles that don't carry loss_pwl_layout. Worst-case chord error scales as (envelope/K)²/4, peaking on the OUTER segment.
  • equal_error (1): √-spaced secant chords (minimax). Breakpoints at b_k = √(k/K)·envelope; each segment carries the SAME max chord error. Drop-in replacement for uniform: same K, same LP row count, but max chord error drops by a factor of ~√K. Recommended when you want better accuracy at no LP-size cost.
  • tangent (2): outer-approximation via K tangent lines (future). Loss is bounded below by the maximum of K tangents at points t_k = ((2k−1)/(2K))·envelope. Yields a LOWER bound on losses that's tight at the LP's chosen operating point. Currently reserved; falls back to uniform with a one-time log warning until the alternative LP structure (1 col + K rows per (line, block) instead of K cols + 1 row) is wired up.
  • midpoint (3): de-biased secant chords. Same K segment columns, same chord SLOPES (R/V²)·width·(2k−1), and the same single loss-tracking row as uniform — but the row is an INEQUALITY loss ≥ Σ loss_k·seg_k − (R/V²)·(width/2)² so the whole PWL is shifted DOWN by the constant (R/V²)·width²/4. This turns each secant chord into the tangent of ℓ(f)=(R/V²)·f² at the segment MIDPOINT m_k=(2k−1)·width/2. Because adjacent midpoint tangents intersect EXACTLY at the breakpoints b_k=k·width, the offset is a FLAT constant (R/V²)·width²/4 for every flow f>0 (it does NOT accumulate per segment). Result: an UNBIASED estimator — exact at the segment midpoints, at most (R/V²)·width²/4 UNDER at the breakpoints — versus uniform's strict (all-positive) overstatement of up to (R/V²)·width²/4 at the midpoints. Removes the systematic loss-overstatement of the secant layout while keeping the exact LP structure (K cols + 1 row). uniform is preserved as the default for callers that need a guaranteed upper bound on losses.

    ⚠ Negative-LMP caveat: the inequality loss ≥ … makes loss a free variable above its lower bound, so in blocks where the receiver bus has a NEGATIVE LMP the LP can pick loss arbitrarily high (up to whatever upstream generation can supply) to gain on the dual. Empirically on a large national test case this inflates loss_sol reporting by ~6× system-wide on lines whose receivers see periodic negative-LMP excursions (must-dispatch wind, fixed-load exports), but the LP-objective impact is bounded by the gen merit-order at the sender so the SOLVE stays well-conditioned. Use uniform (strict equality) when the reported loss_sol values matter for downstream accounting and your network has recurring negative-LMP receivers.

Theory references:

  • Imamura et al., On piecewise linear approximation of quadratic functions (2003).
  • Aigner & Van Hentenryck, Line Loss Outer Approximation, arXiv:2112.10975 (2022) — for the tangent mode.
  • Fitiwi et al., Dynamic PWL DC Transmission Losses, IEEE 2010.
Enumerators
uniform

Equal-width secant chords (default; current behavior).

equal_error

√-spaced secant chords (minimax error)

tangent

Outer-approximation tangents (future; falls back to uniform).

midpoint

De-biased secant chords (midpoint-tangent shift).

enum class gtopt::LineThermalLimitMode: uint8_t

How a line's thermal limit interacts with its loss variable.

The thermal limit T_dir of one flow direction is tmax_ab / tmax_ba (and, on expandable lines, the installed capacity). With losses the power entering the line at the sending bus and the power leaving it at the receiving bus differ by the loss ℓ_dir; which of them the limit applies to is what this mode selects:

  • flow (0, default): the limit bounds the flow variable only, f_dir ≤ T_dir (column bound / capacity row). No extra row. Historical behaviour. Under the default receiver loss allocation the flow variable already IS the sending-end power, so this is the physical sending-end limit there.
  • sending (1): the SENDING-END power stays within the limit, f_dir + a_s·ℓ_dir ≤ T_dir, with a_s the share of the loss that loss_allocation_mode books at the sending bus (receiver 0, split ½, sender 1; tangent_signed_flow always books ½). Exactly the physical limit on the larger (sending) end of the line whatever the allocation; a no-op under receiver allocation.
  • full (2): flow plus the WHOLE loss stays within the limit, f_dir + ℓ_dir ≤ T_dir. Allocation-independent and the most conservative variant (equals sending under sender allocation).

The extra rows only apply to modes with a loss term (linear tightens the flow bound / capacity-row coefficient to 1 + a·λ, the PWL modes add one row per direction and block, none is unaffected). Resolution: per-line Line.line_thermal_limit_mode, else model_options.line_thermal_limit_mode, else flow.

Enumerators
flow

limit on the flow variable only (default)

sending

limit on the sending-end power f + a_s·ℓ

full

limit on f + ℓ (whole loss)

enum class gtopt::LossAllocationMode: uint8_t

How transmission losses are allocated between sender and receiver buses in the nodal power balance equation.

The total loss is always λ·f (conserving energy). The allocation determines which bus "absorbs" the loss in the KCL equation via emission (PerdEms) and reception (PerdRec) fractions where PerdEms + PerdRec = 1:

  • receiver (0, default): sender = −f, receiver = +(1 − λ)f. PerdEms=0, PerdRec=1.
  • sender (1): sender = −(1 + λ)f, receiver = +f. PerdEms=1, PerdRec=0. (PLP FPerdLin = 'E')
  • split (2): sender = −(1 + λ/2)f, receiver = +(1 − λ/2)f. PerdEms=0.5, PerdRec=0.5. (PLP FPerdLin = 'M')
Enumerators
receiver

100% losses at receiving bus (default)

sender

100% losses at sending bus (PLP 'E')

split

50/50 between sender and receiver (PLP 'M')

enum class gtopt::LowMemoryMode: uint8_t

Low-memory mode for SDDP solver.

Controls whether and how the solver releases backend memory between solves.

  • off: Disabled — keep solver backend loaded (default).
  • compress: Release solver backend after each solve; keep a (optionally compressed) FlatLinearProblem snapshot + dynamic columns + accumulated cuts. Reconstructed on demand. Set memory_codec = uncompressed to retain the flat LP raw (previously the dedicated snapshot mode).

The previous rebuild mode (re-flatten from collections on every solve, no snapshot) was removed 2026-05-13: it delivered no measurable benefit over compress on production workloads, while doubling the surface area of LP-lifecycle bugs we had to keep alive.

Enumerators
off

Disabled — keep solver backend loaded (default).

compress

Release solver, keep (optionally compressed) flat LP.

enum class gtopt::LPAlgo: uint8_t

Enumeration of linear programming solution algorithms.

Enumerators
default_algo

Use the solver's default algorithm.

primal

Use the primal simplex algorithm.

dual

Use the dual simplex algorithm.

barrier

Use the interior point (barrier) algorithm.

last_algo

Sentinel value for iteration/validation.

enum class gtopt::LpDebugPass: std::uint8_t

SDDP passes enumerated for lp_debug_passes membership tests. Kept as a tiny enum (string-tag pairs lower in the .cpp) rather than a bit-flag so call sites stay readable: lp_debug_passes_includes(s, LpDebugPass::backward).

enum class gtopt::LpEquilibrationMethod: uint8_t

LP matrix equilibration method for numerical conditioning.

Controls how the constraint matrix is scaled before being sent to the LP solver. Better-conditioned matrices produce more accurate solutions and reduce solver iterations.

  • none: No equilibration (default).
  • row_max: Per-row max-abs normalization. Each row is divided by its largest |coefficient| so that every row's infinity-norm becomes 1.0.
  • ruiz: Ruiz geometric-mean iterative scaling. Alternately normalizes rows and columns by sqrt(infinity-norm) until convergence. Produces a better-conditioned matrix than single-pass row_max, especially for problems with heterogeneous variable scales. Ref: Ruiz, D. (2001) "A scaling algorithm to equilibrate both rows and columns norms in matrices".
Enumerators
none

No equilibration (default).

row_max

Per-row max-abs normalization.

ruiz

Ruiz geometric-mean iterative scaling.

enum class gtopt::LpFileFormat: std::uint8_t

File format used when an assembled LP model is written to disk.

Enumerators
lp

CPLEX LP format (default), extension .lp.

mps

MPS format, extension .mps.

enum class gtopt::LpFormatFallback: std::uint8_t

What LinearInterface::write_lp does when the backend cannot write the requested format.

Enumerators
strict

Fail with an error naming the backend. Used when the user asked for the format explicitly (--lp-file, --lp-format).

other_format

Write the other format instead and log a warning. Used by the diagnostic dumps (--lp-debug, error / kappa LPs), where having a file matters more than its format.

enum class gtopt::LpNamesLevel: int8_t

LP variable/constraint naming level for matrix assembly.

Controls whether naming information is generated during LP construction. When enabled (all), column and row names, name-to-index maps, and duplicate-name error checking are all active. State variable I/O uses the StateVariable map (ColIndex-based) directly and does not need column name strings.

  • none: No names generated (default, lowest memory).
  • all: All column + row names + name-to-index maps; duplicates throw.
Enumerators
none

No names generated (lowest memory, default).

all

All column + row names + name maps; duplicates throw.

enum class gtopt::LpScalesLevel: std::uint8_t

Content of the --lp-scales sidecar written next to --lp-file.

Enumerators
none

No sidecar (default).

summary

Header, objective, block/stage weights, numerics.

full

summary + scaled columns and row scales

enum class gtopt::MethodType: uint8_t

Top-level solver selection: monolithic LP, SDDP, or cascade.

Enumerators
monolithic

Single monolithic LP/MIP (default).

sddp

Stochastic Dual Dynamic Programming decomposition.

cascade

Cascade: Benders -> guided SDDP -> free SDDP.

enum class gtopt::MinMaxKind: std::uint8_t

Kind of min/max expression (F7).

Enumerators
Max

max(a, b, c) — convex upper envelope

Min

min(a, b, c) — concave lower envelope

enum class gtopt::MipStartEffort: uint8_t

Effort level applied to an injected MIP-start (warm incumbent).

Controls how hard the backend works to validate / complete / repair a supplied starting integer solution before branch-and-cut. Mirrors the CPLEX CPX_MIPSTART_* effort levels; other backends map it as closely as their native start API allows (or ignore it).

  • check_feasibility (default): the backend tests the start and keeps it only if it is feasible — a discarded start costs nothing, so this is the zero-risk default. CPLEX: CPX_MIPSTART_CHECKFEAS.
  • solve_fixed: fix the supplied integer values and solve the residual LP (the dispatch) to complete the start. CPLEX: CPX_MIPSTART_SOLVEFIXED.
  • solve_mip: solve a bounded sub-MIP around the start. CPLEX: CPX_MIPSTART_SOLVEMIP.
  • repair: run the backend's start-repair heuristic on a slightly infeasible start. CPLEX: CPX_MIPSTART_REPAIR.
  • no_check: trust the start verbatim (fastest, unsafe). CPLEX: CPX_MIPSTART_NOCHECK.
Enumerators
check_feasibility

Test feasibility, keep only if feasible (default).

solve_fixed

Fix integers, solve the residual dispatch LP.

solve_mip

Solve a bounded sub-MIP around the start.

repair

Repair a slightly-infeasible start.

no_check

Trust the start verbatim (fastest, unsafe).

enum class gtopt::MissingCutVarMode: uint8_t

How to handle boundary/named cut rows that reference state variables not present in the current model.

  • skip_coeff: Drop the missing variable's coefficient from the cut but still load the cut (default).
  • skip_cut: Skip the entire cut if any missing variable has a non-zero coefficient.
Enumerators
skip_coeff

Drop the coefficient, load the cut.

skip_cut

Skip the entire cut.

enum class gtopt::MonthType: uint8_t

Calendar month (1-based: january=1, december=12).

Used in Stage to tag each planning period with its calendar month, enabling seasonal parameter lookups (e.g., irrigation schedules).

enum class gtopt::NetworkModel: uint8_t

Power-flow model of the network (model_options.network_model).

  • dc (default): the transmission model – transport, or the DC power flow (B–θ / cycle basis) when use_kirchhoff is on. Today's LP, byte-identical.
  • lindistflow: the linearised DistFlow model of radial distribution feeders (Baran & Wu 1989): squared bus voltage w = |V|², reactive power balance, w_b = w_a/t² − 2(r·P + x·Q)/V² per branch, MVA polygon limits. Replaces the DC angle rows (no θ columns).

enum class gtopt::OutageReserveMode: uint8_t

How reserve offers react to a Generator.outage_fraction maintenance schedule (model_options.outage_reserve_mode).

In every mode the generation bounds scale by the available fraction a = 1 − f, and so do the provision headroom rows built from them. The mode only changes the provision column's own ceiling:

Enumerators
none

urmax / drmax untouched (default)

proportional

urmax / drmax scaled by a (monthly average)

exclude

no reserve offered in a block with f > 0

enum class gtopt::OutputFlags: uint8_t

Bitmask controlling which fields the output writer emits.

Each OutputContext add-field call is gated by one of these bits:

  • solution → primal column values (suffix sol)
  • dual → row dual values / marginals (suffix dual)
  • reduced_cost→ column reduced costs (suffix cost)

The default when the option is unset is all — today's behaviour. none disables output-field emission entirely (still creates the output directory and writes the merged planning JSON).

Combinations are expressed as comma-separated names on the CLI/JSON, e.g. --write-out solution,dual or "write_out": "sol,dual". Parsing is case-insensitive and accepts the abbreviations declared in output_flags_entries (sol, rcost, rc, cost).

Enumerators
none

solution

dual

reduced_cost

extras

Opt-in atom for streams that no current consumer reads but that may be useful for future audits / debugging. Today this gates Generator's capacity_dual, heat_rate_slack_sol/cost, vom_cost_sol, fuel_cost_sol; and Line's piecewise-segment flowp/flown slices, consolidated loss_sol, overloadp/overloadn_sol/cost. Default write_out is solution | dual | reduced_cost (extras excluded); pass --write-out all or --write-out sol,dual,rc,extras to opt in.

all

enum class gtopt::ParamFileSource: std::uint8_t

Where a resolved solver parameter file was found.

Enumerators
absolute

the given path was already absolute

input_directory

<input_directory>/<file> (the case directory)

working_directory

<cwd>/<file> (fallback only)

enum class gtopt::PenaltyClass: uint8_t

How the penalty value on a soft UserConstraint is interpreted before being assigned to the slack column's LP objective coefficient.

The UserConstraint::penalty field stores a single scalar supplied by the modeller, but different physical quantities use different natural units. When the expression is a flow balance in m³/s, for example, the modeller would like to author the penalty in $/m³ (the same unit as the global hydro_fail_cost) and let the LP assembly convert to $/(m³/s) per block using block duration. PenaltyClass selects which conversion the slack column's cost goes through:

EnumAccepted stringsSlack cost (per-block row)
Raw"raw" (default)penalty × w
HydroFlow"hydro_flow"penalty × 3600 × w

with w = probability × discount × duration[h] (CostHelper:: block_ecost), as for every other cost. A row spanning several blocks uses w = probability × discount and, for HydroFlow, × span hours.

  • Raw — no unit conversion. Appropriate for dimensionless or already-converted coefficients, and for energy ($/MWh) constraints where the slack column is itself in MWh. Default when penalty_class is absent (backwards-compatible with pre-2026-04 inputs).
  • HydroFlow — penalty is authored in $/m³ (volume) and converted to $/(m³/s) per block using duration × 3600. This mirrors the FlowRight fail-cost path (source/flow_right_lp.cpp:74) so that a soft-flow UserConstraint using hydro_fail_cost-style pricing composes uniformly with element-level pricing.
Enumerators
Raw

Default — penalty in row units (weighted like any cost).

HydroFlow

$/m³ → $/(m³/s)·h via × 3600 (then weighted)

enum class gtopt::PlpCutStatus: uint8_t

Return status of build_plp_feasibility_cuts — mirrors PLP's AgrElastici outcome codes.

Enumerators
cuts_added

≥ 1 single-variable rows emitted (PLP: cut installed on t−1, caller backtracks and re-solves).

holguras

The elastic clone solved to optimality but EVERY ray/dx was zeroed by the FactEPS tolerances — the elastic repaired feasibility without moving any state (PLP IStat = −1 "holguras"). PLP tolerates this in the dual (backward) phase only; the forward pass declares the scene infeasible.

fail

The elastic clone itself was not proven optimal — the infeasibility is rooted in rows the elastic filter cannot relax. No cut exists; the caller declares infeasibility.

enum class gtopt::PluginCheckMode: int

What a failed plugin integrity check does. ONE mode for every check (build-id vs manifest, build tag, compiled vs runtime solver version, RUNPATH shadowing, missing manifest / build-id / identity symbols).

Enumerators
warning

log a clear warning and keep loading

error

refuse the plugin (or the affected solver) with an error

enum class gtopt::PluginCheckSource: int

Where the effective plugin check mode came from.

Enumerators
compiled_default

GTOPT_PLUGIN_CHECK_DEFAULT (CMake)

environment

$GTOPT_PLUGIN_CHECK

command_line

--plugin-check

enum class gtopt::PrevStageLink: uint8_t

What a user-constraint <attr>_prev term reads at the FIRST block of a stage whose predecessor stage is in the SAME phase.

Inside a chronological stage x_prev is x at the previous block. At the first block of a stage the previous block belongs to the previous stage:

  • stage (default): when that stage is in the same phase (same LP) and chronological, x_prev is x at its LAST block — ramp rows stay continuous across stage boundaries.
  • none: the legacy behaviour — x_prev is the constant 0 at the first block of every stage except the horizon start.
  • period: like stage, except on a PERIODIC stage (Stage.periodic, a typical day / week repeated in a cycle, ≥ 2 blocks) the first block wraps to the LAST block of the same stage (the period repeats).

Independent of this option: the first block of the HORIZON reads the element's initial_<attr> (Generator.initial_generation), and the first block of a LATER phase reads 0 (no cross-phase state). JSON / CLI: model_options.prev_stage_link.

Enumerators
none

0 at every stage start (legacy)

stage

previous stage's last block, same phase (default)

period

periodic stage: own last block; else as stage

enum class gtopt::PricingMode: std::uint8_t

Post-MIP pricing method — see the file header.

Enumerators
fixed

Integers pinned at the incumbent (default).

relaxed

LP relaxation of the full MIP.

fast_start

Fast-start commitment relaxed, the rest pinned.

enum class gtopt::ProbabilityRescaleMode: uint8_t

Controls when scenario/scene probabilities are rescaled to sum 1.0.

Scenario probability_factor values should sum to 1.0 over all scenes. When they do not, a warning is always emitted. This option controls whether (and when) the solver normalizes the values automatically.

  • none: No rescaling. Warn about mismatched probabilities but leave values unchanged. This may produce incorrect expected-cost computations if probabilities do not sum to 1.0.
  • build: Rescale at build time (during validation, before LP construction). Scenario factors are GLOBAL probabilities (a scene's weight is the sum of its scenarios' factors). Rules, always reported as warnings (never errors):
    1. total ~ 1.0: left untouched (scene weights kept);
    2. every scene sums to ~1.0 (two or more scenes; a single-scenario scene qualifies with factor 1.0): the input is read as CONDITIONAL per-scene probabilities and every factor is divided by the number of scenes, so the scenes get equal weight;
    3. any other total: every factor is divided by the global total, preserving the relative scene weights (single-scenario scenes keep their factor as their relative weight). This scales the expected OPEX relative to CAPEX; when the total is outside [0.5, 2] the warning suggests the values are representative-period weights (e.g. day counts), which belong in block/stage durations instead.
  • runtime: Rescale at build time AND at runtime. In addition to build-time normalization, scene weights are re-normalized during SDDP when a scene becomes infeasible, so the remaining feasible scenes' probabilities still sum to 1.0. This is the default.
Enumerators
none

No rescaling, warn only.

build

Rescale at build/validation time.

runtime

Rescale at build time and at runtime (default).

enum class gtopt::ProfileOwnerKind: std::uint8_t

Discriminator identifying the owner element type of a CapacityProfile.

Extending this enum is the canonical way to add a new profile-able element type (e.g. Line, Waterway). Each new entry must be paired with a CapacityProfileTraits<OwnerLP> specialization in gtopt/capacity_profile_traits.hpp and a new row in profile_owner_kind_entries.

enum class gtopt::RecoveryMode: uint8_t

Controls what is recovered from a previous SDDP run.

  • none: No recovery — cold start.
  • cuts: Recover only Benders cuts from previous run.
  • full: Recover Benders cuts AND state variable solutions (default).
Enumerators
none

No recovery — cold start.

cuts

Recover only Benders cuts.

full

Recover cuts + state variable solutions (default).

enum class gtopt::RelaxInfeasibleAction: uint8_t

What to do when the initial LP relaxation is infeasible.

The MIP-start pipeline solves the LP relaxation first (stage A). If that relaxation is itself infeasible, the MIP cannot have a feasible solution either, and this selects the response.

  • stop (default): report the infeasibility and abort the solve.
  • warn: log a warning and proceed to the MIP solve anyway (let the solver's own infeasibility handling / soft slacks take over).
  • feasopt: run the backend's infeasibility diagnostic (CPLEX FeasOpt / conflict refiner) to identify the minimal conflicting constraints, print them, then abort.
Enumerators
stop

Report and abort (default).

warn

Warn and proceed to the MIP solve.

feasopt

Diagnose the conflict, then abort.

enum class gtopt::ResourceClass: std::uint8_t

Broad execution class of a task's dominant resource.

Enumerators
cpu

host-CPU solve; full cpu_factor x cores fan-out

gpu

device solve; gated by the per-device GPU token bucket

enum class gtopt::RiskMeasure: std::uint8_t

Risk measure applied to the scenario costs of a (scene, phase) LP.

Enumerators
expected

Expected cost Σ p_s C_s (default, risk-neutral).

cvar

(1 − λ)·E[C] + λ·CVaR_α[C]: tail weighted up

trim

(1 − λ)·E[C] + λ·E[C | not in tail]: tail excluded

enum class gtopt::RiskRankBy: std::uint8_t

How the tail of risk_measure is selected.

Enumerators
cost

Endogenous: by the scenario's total cost at the optimum (Rockafellar–Uryasev rows). Upper tail and cvar only.

index

Exogenous: by Scenario.risk_index (hydrology index, expected unserved energy, ...). Fixed risk-adjusted weights, no extra rows.

enum class gtopt::RiskTail: std::uint8_t

Side of the ranking the tail is taken from.

Enumerators
upper

Highest cost / highest risk_index.

lower

Lowest risk_index (index ranking only).

enum class gtopt::SDDPPassDirection: int

Pass direction for the SDDP scheduler.

Converted to the is_backward field of SDDPTaskKey by the factory (forward → 0, backward → 1) so the lexicographic key tuple keeps forward strictly ahead of backward at the same iteration.

enum class gtopt::SDDPTaskKind: int

Task kind for the kind field of SDDPTaskKey. LP solves (0) have higher priority than non-LP tasks (1).

enum class gtopt::SolveMode: uint8_t

Monolithic solver execution mode.

Enumerators
monolithic

Solve all phases in a single LP (default).

sequential

Solve phases sequentially.

enum class gtopt::SolveOutcome: std::uint8_t

enum class gtopt::SolverLogMode: uint8_t

Controls whether and how solver log files are written.

  • nolog: No solver log files are written (default).
  • detailed: Separate log files per scene/phase/aperture, using the naming pattern <solver>_sc<N>_ph<N>[_ap<N>].log. Each thread writes to its own file – no locking required.
Enumerators
nolog

No solver log files (default).

detailed

Separate log files per scene/phase/aperture.

enum class gtopt::SolverScaling: uint8_t

Solver-internal scaling strategy.

Controls whether and how the LP solver applies matrix scaling before solving. Each backend maps these values to its native parameter:

SolverScalingCPLEX CPX_PARAM_SCAINDHiGHS scale_strategyCLP
none-10 (off)0
automatic0 (equilibration)4 (default)3
aggressive1 (aggressive)1 (forced)2
Enumerators
none

Disable solver-internal scaling.

automatic

Solver's default/auto strategy (recommended).

aggressive

Aggressive equilibration (for high-kappa LPs).

enum class gtopt::StartsScope: std::uint8_t

Scope of Commitment::max_starts — defines the rolling time window over which the LP cap Σ startup ≤ max_starts is enforced. Mirrors PLEXOS's per-Generator Max Starts {Hour|Day|Week|Month|Year} properties (prop_id 203..207); the longer per-month / per-year scopes collapse to Horizon here because a typical gtopt stage is shorter than a month. See Commitment::max_starts docstring for the full LP-row emission rule.

Enumerators
Hour

One LP row per single-period window.

Day

One LP row per 24h cumulative-duration window.

Week

One LP row per 7×24h window (CEN PCP target).

Horizon

One LP row per stage; default + collapse-target for per-month / per-year PLEXOS scopes

enum class gtopt::StartupTierIntegrality: std::uint8_t

Integrality of the hot / warm / cold startup-tier selectors.

Enumerators
continuous

Continuous in [0, 1] (default; TU tier rows).

integer

Binary.

enum class gtopt::StateVariableLookupMode: uint8_t

How update_lp elements obtain reservoir/battery volume between phases.

  • warm_start (default): volume comes from the previous iteration's warm-start solution, a recovered state file, or the element's vini.
  • cross_phase: volume is taken from the previous phase's efin within the same forward pass.
Enumerators
warm_start

Warm solution / recovery / vini (default, no cross-phase).

cross_phase

Previous phase's efin within the same forward pass.

enum class gtopt::SystemKind: std::uint8_t

Which of a (scene, phase) cell's two LPs a state variable belongs to.

forward is the regular full-detail system used by the SDDP forward pass and the monolithic/cascade solves. aperture is the optional, simplified aperture system solved per aperture in the SDDP backward pass (see aperture_system_file). The two LPs have different column layouts, so their state variables are kept in physically separate registries and never collide — LPKey::kind selects which.

enum class gtopt::TaskPriority: uint8_t

enum class gtopt::TaskStatus: uint8_t

enum class gtopt::TimeAggWeight: std::uint8_t

Per-block weight applied to each term inside a sum{...} time-agg.

dur[b] weighting is LOAD-BEARING for RATE variables (flow [m³/s]): Σ_b Δt_b · flow_b is energy [m³], Σ_b flow_b is meaningless. See feedback_stage_avg_flows. Count (unweighted) is the right choice for per-day event counts (e.g. Σ startups ≤ N), matching unweighted daily_sum.

Enumerators
Count

unweighted: Σ_b col_b (per-day / per-stage count)

Duration

Δt-weighted: Σ_b Δt_b · col_b (energy).

enum class gtopt::TimeWindow: std::uint8_t

Time window iterated by a sum{...} time-aggregator (piece-4 step 2).

Enumerators
Stage

all blocks of the representative stage

Day

blocks within each 24 h day (the daily_sum window)

enum class gtopt::TinyReactanceMode: uint8_t

What to do with a line whose reactance is set but is 0 or has a per-unit |X/V²| below model_options.dc_line_reactance_threshold (default 1e-6).

Such lines are bus-bar segments, couplers, series-compensation auxiliary nodes or near-zero-impedance branches. Physically they force θ_a ≈ θ_b, but their x_τ coefficient is zero or numerically negligible.

  • tie (0, default): zero-impedance tie. The KVL relation is kept without the flow term — node_angle emits −θ_a + θ_b = −φ (the off-nominal tap τ multiplies x and is therefore irrelevant; the phase shift φ is kept) and cycle_basis keeps the line as a cycle edge with x = 0. The flow stays a free variable bounded by tmax and still enters both bus balances. The line connects its buses for island detection and reference-angle pinning, like any AC line.
  • dc (1): legacy behaviour — sub-threshold reactances are clamped to 0 and X = 0 lines are DC links (no KVL row at all), so the LP can use them as free phase shifters.

Only lines with NO reactance (unset; HVDC and PLP DC lines are emitted that way) are DC links in tie mode.

Enumerators
tie

zero-impedance tie: θ_a − θ_b = φ, no flow term (default)

dc

legacy: X = 0 / tiny X is a free-flow DC link

enum class gtopt::TransitionIntegrality: std::uint8_t

Integrality of the commitment startup / shutdown columns.

Enumerators
automatic

Binary (default; exact).

continuous

Always continuous in [0, 1].

binary

Always binary.

Typedef documentation

using gtopt::AmplActiveFn = std::optional<bool>(*)(const SystemContext&sc, Uid element_uid, const StageLP&stage)

Activity probe for one element of a class at a stage: true / false from the element's own is_active(stage), nullopt when the element is not in this cell's collection (e.g. a UserModel-bundled variable). Used by the user-constraint resolver to tell an INTENTIONALLY absent column (inactive element) from a registration / scope mismatch.

using gtopt::AmplCompoundMap = flat_map<AmplCompoundKey, std::vector<AmplCompoundLeg>>

Compound-attribute registry: (class, compound_name) -> legs.

using gtopt::AmplElementMetadata = std::vector<std::pair<std::string_view, AmplMetadataValue>>

Metadata bundle for one element: an ordered (key, value) list. Small enough that linear search beats a map.

using gtopt::AmplElementMetadataMap = flat_map<AmplMetadataKey, AmplElementMetadata>

Metadata registry: (class, uid) -> attribute bundle. Populated by each element's add_to_lp so that collect_sum_cols can evaluate multi-predicate filters without re-reading the element's fields.

using gtopt::AmplElementNameKey = std::pair<std::string_view, std::string_view>

Map from (class_name, element_uid) to its registered element name, used so that PAMPL expressions like generator("G1") can resolve the string "G1" to its Uid. Key is (class_name, name).

Both views are non-owning: class_name points into constexpr LPClassName::snake_case() (program lifetime); element_name points into the element's Id::name (owned by the System, which outlives the registry).

using gtopt::AmplElementNameMap = flat_map<AmplElementNameKey, Uid>

Name registry: (class_name, name) -> element uid.

using gtopt::AmplIterCallback = void(*)(void*state, Uid uid)

Captureless callback: forwarded the state pointer the iterator was invoked with. Used by AmplIterFn so that the iterator's signature stays a plain function pointer (no std::function, no template).

using gtopt::AmplIterFn = void(*)(const SystemContext&sc, void*state, AmplIterCallback cb)

Iterator signature: walk every element of the registered class and call cb(state, uid) per element. Filtering by SumPredicate is the caller's responsibility — the iterator emits unfiltered uids so the registry stays decoupled from constraint_expr.hpp.

using gtopt::AmplIterMap = flat_map<std::string_view, AmplIterFn>

Iterator dispatch table: class_name -> iterator.

using gtopt::AmplMetadataValue = std::variant<std::string, double>

Value stored against a metadata key. Strings for categorical attributes (type, bus, name, class_name, …), doubles for numeric data (uid, cap, …).

using gtopt::AmplParamFn = std::optional<double>(*)(const SystemContext&sc, Uid element_uid, StageUid stage_uid, BlockUid block_uid)

Resolver signature for a class+attribute parameter. Returns the physical (scaled) value of the parameter at this (stage, block), or nullopt when the schedule has no entry. Element type is fixed by the registration; the function knows internally which *LP class to look up via SystemContext::get_element.

using gtopt::AmplParamMap = flat_map<AmplParamKey, AmplParamFn>

Parameter dispatch table: (class, attribute) -> resolver.

using gtopt::AmplResolveCache = std::unordered_map<const ElementRef*, ElementRefResolution>

using gtopt::AmplScalarMap = flat_map<AmplScalarKey, double>

Scalar registry: (class, attribute) -> resolved double value.

Values are cached at registration time (once per SimulationLP under std::call_once) so the resolver path is a pure read. Options are immutable for the lifetime of a SimulationLP, which is what makes the cache-by-value approach safe.

using gtopt::AmplVariableMap = std::unordered_map<AmplVariableKey, AmplVariable, AmplVariableKeyHash>

Variable registry: (class_name, uid, attribute, scenario, stage) -> cols.

using gtopt::ApertureChunkResult = std::vector<ApertureCutResult>

Result of a chunked task (one task can hold N aperture solves under the chunked aperture pass). At chunk_size=1 each chunk is a 1-element vector — equivalent to the legacy 1-task-per-aperture path.

using gtopt::ApertureChunkSubmitFunc = std::function<std::future<ApertureChunkResult>( const std::function<ApertureChunkResult()>&task)>

Callback for submitting a chunk task (1..K aperture solves on a shared LP clone) to the SDDP work pool.

The task body itself is responsible for cloning the phase LP once, iterating its assigned apertures serially with warm-start reuse on the shared clone, and producing one ApertureCutResult per aperture (in input order, including memo-hit duplicates). The caller submits all chunks first, then collects every future, enabling parallel execution across chunks.

using gtopt::ApertureContext = std::tuple<SceneUid, PhaseUid, ApertureUid, int>

SDDP aperture cut context. Tuple: (scene_uid, phase_uid, aperture_uid, extra)

using gtopt::ApertureIndex = StrongIndexType<Aperture>

Positional index into an aperture array (distinct from ApertureUid; this is a counting index for aperture_array[idx] style access, intentionally left as StrongIndexType per existing Index-type conventions).

using gtopt::ApertureUid = ScenarioUid

Aperture UID and Scenario UID are the same concept: an aperture is a stochastic opening that references a source scenario, and the convention (see build_synthetic_apertures) is that aperture.uid == aperture.source_scenario. Aliasing them here makes that semantic equality load-bearing in the type system, avoiding a spurious second strong type.

using gtopt::ApertureValueFn = std::function<std::optional<double>(StageUid, BlockUid)>

Value-provider signature: (StageUid, BlockUid) -> std::optional<double>. Returns the aperture value for the given stage/block, or std::nullopt if the value is unavailable (keeps the forward-pass value unchanged).

template<typename Type>
using gtopt::Array = std::vector<Type>

Array type template for consistent vector usage.

Template parameters
Type The element type to store in the array

using gtopt::ArrowArray = std::shared_ptr<arrow::Array>

using gtopt::ArrowChunkedArray = std::shared_ptr<arrow::ChunkedArray>

using gtopt::ArrowColumnResult = arrow::Result<ArrowChunkedArray>

using gtopt::ArrowField = std::shared_ptr<arrow::Field>

using gtopt::ArrowIndex = int64_t

using gtopt::ArrowPresentMask = std::uint32_t

Bitmask describing which UID dimensions are present in an input table. Bit i corresponds to the i-th UID in the parameter pack. When the bit is 0, the underlying column was absent from the table and the loader has built / will look up the index with a default-constructed UID in that slot — i.e. the value is broadcast across that dimension.

using gtopt::ArrowTable = std::shared_ptr<arrow::Table>

using gtopt::BatteryLPId = ObjectId<class BatteryLP>

template<typename Value = Index>
using gtopt::BIndexHolder = IndexHolder0<BlockUid, Value>

using gtopt::block_factor_matrix_t = gtopt::MultiArray2D<std::vector<double>>

using gtopt::BlockContext = std::tuple<ScenarioUid, StageUid, BlockUid>

Block-level context: dispatch variables (generation, load, flow, theta, extraction) – one column per block. Tuple: (scenario_uid, stage_uid, block_uid)

using gtopt::BlockExContext = std::tuple<ScenarioUid, StageUid, BlockUid, int>

Block-level context with an extra index (e.g. segment number). Tuple: (scenario_uid, stage_uid, block_uid, extra_index)

using gtopt::BlockUid = UidOf<Block>

using gtopt::Bool = bool

Boolean type for logical conditions.

using gtopt::BoolOrName = std::variant<bool, Name>

JSON value of the removed transition_status_rows key (a bool or a name): still parsed so old inputs load, then ignored with a warning.

using gtopt::BusLPId = ObjectId<class BusLP>

using gtopt::BusLPSId = ObjectSingleId<class BusLP>

using gtopt::col_name_map_t = std::unordered_map<std::string, ColIndex, LabelHash, std::equal_to<>>

Column (variable) name → strong column index map.

using gtopt::ColIndex = StrongIndexType<SparseCol>

Type alias for column index.

using gtopt::CommitmentPeriodValue = std::variant<Real, Name>

Commitment.commitment_period: a length in hours (Real, variant alternative 0 — keep aligned with json_variant_type_list<Real, Name> in json_commitment.hpp) or "auto" (Name).

using gtopt::EmissionLPSId = ObjectSingleId<EmissionLP>

SingleId-style reference into Collection<EmissionLP>. Consumed by EmissionZone.emissions[].emission and EmissionSource.emission resolvers.

template<typename Type, typename Vector = std::vector<Type>>
using gtopt::FieldSched = std::variant<Type, Vector, FileSched>

template<typename Type, typename Vector2 = std::vector<std::vector<Type>>>
using gtopt::FieldSched2 = FieldSched<Type, Vector2>

template<typename Type, typename Vector3 = std::vector<std::vector<std::vector<Type>>>>
using gtopt::FieldSched3 = FieldSched<Type, Vector3>

using gtopt::FileSched = String

template<typename key_type, typename value_type>
using gtopt::flat_map = boost::container::flat_map<key_type, value_type>

using gtopt::FlowLPSId = ObjectSingleId<class FlowLP>

Single-ID alias for referencing a FlowLP in other LP elements.

using gtopt::FuelLPSId = ObjectSingleId<FuelLP>

SingleId-style reference into Collection<FuelLP>. Used by downstream consumers (e.g. Generator.fuel, Commitment.fuel) that resolve the Fuel at LP-build time via sc.element<FuelLP>(FuelLPSId{...}).

using gtopt::GasNodeLPId = ObjectId<class GasNodeLP>

using gtopt::GasPipeLPId = ObjectId<class GasPipeLP>

using gtopt::GroupUid = Uid

Opaque identifier for a commitment-layout group within a (stage, layout) pair. Until the binding stack lands (Phase 2) every integer column is Block scope and group_uid() returns the block uid; the type is reserved here so call sites and tests can be authored against the long-term shape.

template<typename Value = Index>
using gtopt::GSTBIndexHolder = tuple_map_t<std::tuple<ScenarioUid, StageUid, BlockUid>, Value>

template<typename Value = Index>
using gtopt::GSTIndexHolder = tuple_map_t<std::tuple<ScenarioUid, StageUid>, Value>

using gtopt::Id = std::pair<Uid, Name>

Combined identifier with both numeric ID and name.

using gtopt::Index = std::int32_t

Index type for large-scale sparse matrices and arrays.

template<typename key_type, typename value_type>
using gtopt::index_map_t = gtopt::flat_map<key_type, value_type>

template<typename FirstIndex, typename Value = Index>
using gtopt::IndexHolder0 = gtopt::flat_map<FirstIndex, Value>

template<typename FirstIndex, typename Value = Index>
using gtopt::IndexHolder1 = index_map_t<FirstIndex, Value>

template<typename FirstIndex, typename SecondIndex, typename Value = Index>
using gtopt::IndexHolder2 = tuple_map_t<std::tuple<FirstIndex, SecondIndex>, Value>

template<typename FirstIndex, typename SecondIndex, typename ThirdIndex, typename Value = Index>
using gtopt::IndexHolder3 = tuple_map_t<std::tuple<FirstIndex, SecondIndex>, IndexHolder0<ThirdIndex, Value>>

using gtopt::IniData = std::map<std::string, std::map<std::string, std::string>>

Parsed INI sections: section name → {key → value}.

using gtopt::Int = int

Integer type for counting and discrete quantities.

using gtopt::IntBool = std::int32_t

Integer boolean for space-efficient storage.

using gtopt::IntegrationRows = std::vector<std::vector<IntegrationTerm>>

Rows of a banded integration operator: row k lists the flow-node weights of the level increment e_k − e_{k−1}.

using gtopt::IterationContext = std::tuple<SceneUid, PhaseUid, IterationUid, int>

SDDP cut context with iteration UID and extra index (cut offset). Tuple: (scene_uid, phase_uid, iteration_uid, extra). All three positional identifiers are UIDs (1-based, matching the PhaseUid / SceneUid convention). Convert to/from the 0-based runtime IterationIndex via uid_of(idx) / index_of(uid).

using gtopt::IterationIndex = StrongIndexType<IterationTag>

Strongly-typed index for SDDP iterations. 0-based, matches the pattern used by SceneIndex / PhaseIndex for array subscripts and loop counters.

using gtopt::IterationUid = UidOf<Iteration>

Strongly-typed UID for SDDP iterations. 1-based, matches the PhaseUid / SceneUid convention used in LP-label context tuples: UIDs appear in ScenePhaseContext / IterationContext, indices appear in runtime control flow. The two are convertible via uid_of(index) / index_of(uid) (uid = index + 1).

using gtopt::JunctionLPId = ObjectId<class JunctionLP>

using gtopt::LineLPSId = ObjectSingleId<LineLP>

SingleId-style FK alias for LineLP. Used by elements that reference a Line through ElementIndex (e.g. LineCommitmentLP per issue #509).

using gtopt::lp_collection_ptrs_t = std::array<const void*, lp_type_count_v>

Array of const void* pointers, one slot per LP element type.

Each slot stores a pointer to the corresponding Collection<T> inside a SystemLP. The slot for type T is at index lp_type_index_v<T>. Populated in SystemContext::SystemContext() via std::apply.

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

Ordered tuple of all LP element types.

The position of each type in this tuple determines its index in the m_collection_ptrs_ array inside SystemContext (see lp_type_index_v). The order matches SystemLP::collections_t for readability, but correctness does not depend on that — the indices are always looked up via lp_type_index_v<T>, never assumed to match positionally.

UserConstraintLP is the last OPERATIONAL type so that user constraints are added to the LP after all other elements (user constraints reference columns created by the earlier elements). UserModelLP (generic AMPL capture) follows it — it reuses the same resolver/registry via internal delegates, so it must run after the columns it may reference exist. FutureCostLP is last, planning-only (no per-(scenario, stage) add_to_lp), so it does not affect the operational build order; it is placed after both ReservoirLP and UserConstraintLP so its α cut can reference their terminal state columns.

using gtopt::LpContext = std::variant<std::monostate, StageContext, BlockContext, BlockExContext, ScenePhaseContext, IterationContext, ApertureContext, PhaseContext>

Type-erased context for internal storage (LinearProblem, FlatLinearProblem). std::monostate = no context (legacy or context-free columns).

template<typename Type, typename Tuple>
using gtopt::mvector_traits_auto = mvector_traits<Type, Tuple, std::tuple_size_v<Tuple>>

using gtopt::Name = std::string

Name type for entity identification.

using gtopt::NameView = std::string_view

String view type for non-owning name references.

using gtopt::OptBool = std::optional<Bool>

Optional boolean type.

using gtopt::OptBoolFieldSched = std::optional<BoolFieldSched>

using gtopt::OptBoolOrName = std::optional<BoolOrName>

using gtopt::OptCommitmentPeriod = std::optional<CommitmentPeriodValue>

using gtopt::OptConstraintDirective = std::optional<ConstraintDirective>

Optional directive carried on every UserConstraint.

using gtopt::OptInflowModel = std::optional<InflowModel>

using gtopt::OptInt = std::optional<Int>

Optional integer type.

using gtopt::OptIntBool = std::optional<IntBool>

Optional integer boolean type.

using gtopt::OptIntBoolFieldSched = std::optional<IntBoolFieldSched>

using gtopt::OptIntBoolFieldSched2 = std::optional<IntBoolFieldSched2>

using gtopt::OptIntFieldSched = std::optional<IntFieldSched>

using gtopt::Options = PlanningOptions

Backward-compatibility alias (deprecated — use PlanningOptions).

using gtopt::OptionsLP = PlanningOptionsLP

Backward-compatibility alias (deprecated — use PlanningOptionsLP).

using gtopt::OptLineDlr = std::optional<LineDlr>

using gtopt::OptName = std::optional<Name>

Optional name type.

using gtopt::OptReal = std::optional<Real>

Optional real number type.

using gtopt::OptRealFieldSched = std::optional<RealFieldSched>

using gtopt::OptRealFieldSched2 = std::optional<RealFieldSched2>

using gtopt::OptRealFieldSched3 = std::optional<RealFieldSched3>

using gtopt::OptSceneIndex = std::optional<SceneIndex>

using gtopt::OptSingleId = std::optional<SingleId>

using gtopt::OptStageIndex = std::optional<StageIndex>

using gtopt::OptStartsScope = std::optional<StartsScopeValue>

using gtopt::OptUid = std::optional<Uid>

Optional unique identifier type.

using gtopt::OptUidFieldSched = std::optional<UidFieldSched>

using gtopt::OptUidFieldSched2 = std::optional<UidFieldSched2>

using gtopt::PhaseContext = std::tuple<SceneUid, PhaseUid, Uid>

Planning-level (coarse-scope) context for phase/global-scoped AMPL constructs (UserConstraint / DecisionVariable / FutureCost) built ONCE per (scene, phase) cell by the planning pass. Distinct from ScenePhaseContext: it carries an extra Uid discriminator (the element's own uid) so several global-scoped rows in the same cell receive distinct, labelable identities and never collide in LinearProblem::add_row's metadata-based duplicate detector — a plain std::monostate would (add_row skips dedup entirely for monostate rows). The variable_uid in the row metadata also carries the element uid, so the discriminator here is belt-and-suspenders: it guarantees a unique LABEL string even when two different element classes happen to share a uid. Tuple: (scene_uid, phase_uid, element_uid)

using gtopt::PhaseIndex = StrongPositionIndexType<Phase>

Strongly-typed index for Phase objects in collections.

using gtopt::PhaseStageIndex = StrongPositionIndexType<PhaseStageTag>

using gtopt::PhaseUid = UidOf<Phase>

Strongly-typed unique identifier for Phase objects.

using gtopt::PlantLPSId = ObjectSingleId<class PlantLP>

using gtopt::PumpLPSId = ObjectSingleId<class PumpLP>

Single-ID alias for referencing a PumpLP in other LP elements.

using gtopt::Real = double

Real number type for physical quantities and costs.

using gtopt::RealFieldSched2 = FieldSched2<double>

using gtopt::RealFieldSched3 = FieldSched3<double>

using gtopt::row_name_map_t = std::unordered_map<std::string, RowIndex, LabelHash, std::equal_to<>>

Row (constraint) name → strong row index map.

using gtopt::RowIndex = StrongIndexType<SparseRow>

Type alias for row index.

using gtopt::ScenarioUid = UidOf<Scenario>

using gtopt::ScenePhaseContext = std::tuple<SceneUid, PhaseUid>

SDDP phase-level context: alpha columns, shared cuts. Tuple: (scene_uid, phase_uid)

using gtopt::SceneScenarioIndex = StrongPositionIndexType<SceneScenarioTag>

using gtopt::SceneUid = UidOf<Scene>

using gtopt::SDDPIterationCallback = std::function<bool(const SDDPIterationResult&result)>

Callback invoked after each SDDP iteration. If the callback returns true, the solver stops after this iteration.

using gtopt::SDDPTaskKey = std::tuple<IterationIndex, int, int, SDDPTaskKind>

SDDP solver task priority key.

A 4-tuple (iteration_index, is_backward, phase_rank, kind):

  • IterationIndex: SDDP iteration number (0, 1, …)
  • int is_backward: 0 for forward, 1 for backward. Lexicographic comparison keeps the forward pass strictly ahead of the backward pass within the same iteration.
  • int phase_rank: NON-NEGATIVE laggard-first tie-break for per-phase backward aperture chunks ((n_phases-1) - phase); 0 for the phase-agnostic scene-driver tasks (forward / backward / sim).
  • SDDPTaskKind: lp (0) or non_lp (1)

Tuple comparison with std::less<SDDPTaskKey> (lexicographic, smaller → higher dequeue priority):

  • lower iteration → higher priority
  • forward (0) → higher priority than backward (1)
  • smaller phase_rank → higher priority (laggard scene's chunks first)
  • lp (0) < non_lp (1)

phase_rank differentiates live tasks only in the async path, where two scenes can be in the same iteration's backward sweep at different phases at once. Scene-driver submissions run all their phases as one task (rank 0); only the backward aperture-chunk tasks set a positive rank. See the header comment block for the full rationale.

using gtopt::SeedCommitmentMap = std::unordered_map<std::uint64_t, double>

A dense external commitment seed: seed_commitment_key(gen_uid, block_uid) → status u (any value; the rule thresholds at 0.5). Populated from an external solution (previous-day PLEXOS / gtopt, nearest-historical, an ML predictor, …) and consumed by SeedCommitmentRule. The producer owns cross-day alignment (it emits keys in THIS case's (generator, block) space); gtopt just matches by identity.

using gtopt::SingleId = std::variant<Uid, Name>

using gtopt::Size = std::size_t

Size type for container dimensions and indices.

using gtopt::solver_backend_factory_fn = SolverBackend*(*)(const char*solver_name)

Plugin entry-point function type: creates a SolverBackend by solver name.

using gtopt::solver_plugin_abi_version_fn = int(*)()

Plugin ABI version function type: returns the ABI version the plugin was built against. SolverRegistry rejects plugins whose version differs from k_solver_abi_version.

using gtopt::solver_plugin_build_info_fn = int(*)(const char*solver_name, SolverBuildInfo*out)

gtopt_solver_build_info: fills out and returns the struct_version it wrote, or 0 when solver_name is unknown.

using gtopt::solver_plugin_build_tag_fn = const char*(*)()

gtopt_plugin_build_tag: NUL-terminated build tag of the plugin.

using gtopt::solver_plugin_infinity_fn = double(*)(const char*solver_name)

Plugin infinity function type: returns the solver's representation of +infinity (CPLEX: CPX_INFBOUND = 1e20, HiGHS / OSI / Gurobi: 1e30, MindOpt: ~1e30). Queryable WITHOUT instantiating a SolverBackend, so callers like PlanningLP::auto_scale_* can compare data values against the solver's infinity threshold to detect "no bound" sentinels (e.g. Reservoir.fmax = 1e30) without paying the cost of creating a throwaway backend instance.

Optional: plugins built before ABI version k_solver_abi_version added this symbol may not export it. SolverRegistry::load_plugin treats absence as a soft error and falls back to instance-level query (creates a backend, calls infinity(), drops it).

using gtopt::solver_plugin_linked_libraries_fn = int(*)(int*struct_version, const SolverLinkedLibrary**out)

gtopt_plugin_linked_libraries: sets *out to the plugin's array of linked libraries and *struct_version to its layout version, and returns the number of entries.

using gtopt::solver_plugin_name_fn = const char*(*)()

Plugin name function type: returns the plugin name.

using gtopt::solver_plugin_names_fn = const char*const *(*)()

Plugin solver-list function type: returns null-terminated array of names.

using gtopt::solver_plugin_resource_desc_fn = int(*)(const char*solver_name, SolverResourceDescriptor*out)

Plugin resource-descriptor function type: fills out with the solver's SolverResourceDescriptor (resource class + estimated per-solve GPU footprint) and returns the descriptor struct_version it wrote, or 0 when the solver name is unknown. Queryable WITHOUT instantiating a backend so the work-pool admission layer can classify tasks before dispatch.

Optional (same convention as gtopt_solver_infinity): plugins that do not export gtopt_solver_resource_descriptor are treated as CPU-class — today's behaviour, zero regression. The POD's own struct_version lets the descriptor grow without bumping k_solver_abi_version.

using gtopt::solver_plugin_version_pin_fn = int(*)(const char*solver_name, SolverVersionPin*out)

gtopt_solver_version_pin: fills out and returns the struct_version it wrote, or 0 when solver_name is unknown.

using gtopt::SolverCfgPairs = std::vector<std::pair<std::string, std::string>>

One (key, value) tuning pair in file order — the order matters because plugins apply the pairs sequentially and last-write wins.

using gtopt::SparseEntries = std::vector<SparseEntry>

using gtopt::SparseEntry = std::pair<uint32_t, double>

One (grid-slot, value) sample produced by FlatHelper::flat_sparse: first is the flat grid-slot index that the dense flat() vector fills for the same holder entry, second the projected + scaled value. Entries are sorted ascending by slot, so consumers emit rows in exactly the dense scan's (scenario, stage, block) order.

using gtopt::stage_factor_matrix_t = std::vector<double>

using gtopt::StageContext = std::tuple<ScenarioUid, StageUid>

Stage-level context: state variables (eini, sini, efin), demand fail columns, capacity variables. Tuple: (scenario_uid, stage_uid)

using gtopt::StageUid = UidOf<Stage>

using gtopt::StartsScopeValue = std::variant<Int, Name>

Two-shape scope value for Commitment::starts_scope:

  • Name — a NamedEnum entry: "hour" | "day" | "week" | "horizon" (also "month" | "year" aliasing to Horizon). Convenient + PLEXOS-faithful.
  • Int — an explicit window length in HOURS (e.g. 48 for a 2-day window, 336 for a fortnight, 720 for a calendar month). Lets users express arbitrary rolling windows the NamedEnum doesn't cover.

Resolved to a window length [hours] at LP-build time by Commitment::starts_window_hours() — a value of 0 (or unset, or any unrecognised name) means "horizon = never flush until stage end".

template<typename Value = Index>
using gtopt::STBIndexHolder = IndexHolder3<ScenarioUid, StageUid, BlockUid, Value>

template<typename Value = Index>
using gtopt::STIndexHolder = IndexHolder2<ScenarioUid, StageUid, Value>

using gtopt::String = std::string

String type for general textual data.

template<typename Type>
using gtopt::StrongIndexType = strong::type<Index, Type, strong::formattable, strong::regular, strong::hashable, strong::arithmetic, strong::bicrementable, strong::implicitly_convertible_to<Index>>

Strong type for count-like indices (LP rows, LP columns).

Template parameters
Type The tag type for compile-time type checking

Retains full arithmetic because row/column positions may need to shift after deletions (row -= RowIndex{k}) and to participate in offset bookkeeping. For positional indices that should never take part in free-form arithmetic (scene, phase, stage, scenario, block) use StrongPositionIndexType instead.

template<typename Type>
using gtopt::StrongPositionIndexType = strong::type<Index, Type, strong::formattable, strong::regular, strong::ordered, strong::hashable, strong::bicrementable, strong::boolean, strong::implicitly_convertible_to<Index>>

Strong type for positional indices into a logical sequence (scene, phase, stage, scenario, block).

Template parameters
Type The tag type for compile-time type checking

Unlike StrongIndexType, these indices do not support free-form arithmetic (idx + idx, idx * k, …) — stepping is done through the next() / previous() helpers and through iota_range. They are contextually convertible to bool so that !idx detects the zeroth element (if (!phase_index) ≡ "first phase").

using gtopt::TaskRequirements = BasicTaskRequirements<>

Backward-compatible alias: TaskRequirements is BasicTaskRequirements<int64_t>.

template<typename Value = Index>
using gtopt::TIndexHolder = IndexHolder1<StageUid, Value>

template<typename key_type, typename value_type>
using gtopt::tuple_map_t = gtopt::flat_map<key_type, value_type>

using gtopt::TurbineLPSId = ObjectSingleId<class TurbineLP>

Single-ID alias for referencing a TurbineLP in other LP elements.

using gtopt::Uid = uid_t

Unique identifier type.

using gtopt::uid_t = std::int32_t

Base type for unique identifiers.

Used for entity identification in the power system model

using gtopt::UserParamMap = std::unordered_map<Name, UserParam>

A collection of named parameters, keyed by name for fast lookup.

using gtopt::WaterwayLPId = ObjectId<class WaterwayLP>

Function documentation

std::vector<std::size_t> gtopt::accumulated_groups(std::span<const double> cells, double period)

Legacy tumbling grouping: a group closes once its accumulated duration reaches P (non-overlapping, chronological).

template<std::ranges::range Range>
auto gtopt::active(Range&& range) noexcept

const FutureCost* gtopt::active_future_cost(const PlanningLP& planning_lp)

Pointer to the first ACTIVE FutureCost element in planning_lp, or nullptr when there is none. Reads the element straight from the System INPUT data (future_cost_array) of the representative (scene 0, phase 0) cell — NOT the LP collection, which the SDDP default low_memory = compress drops for planning-only elements. Used by both methods to source the user-α uid + the boundary-cut configuration.

template<typename SystemContextT, typename IdT, typename StageT>
const std::remove_cvref_t<decltype(sc.element(id))>* gtopt::active_ref(const SystemContextT& sc, const IdT& id, const StageT& stage)

The referenced element when it is active in stage, else nullptr.

sc is a SystemContext (or anything with element(id)); id is any id accepted by SystemContext::element (ObjectSingleId<XLP>, ElementIndex<XLP>).

std::optional<Uid> gtopt::active_user_alpha_uid(const PlanningLP& planning_lp) noexcept

The active user-α column's uid when a FutureCost element has use_user_alpha=true AND a user_alpha_uid set; std::nullopt otherwise. Single source of truth for the "user α is the FCF recourse column" guard used across the SDDP backward/forward/alpha passes.

RowIndex gtopt::add_cut_row(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, CutType cut_type, const SparseRow& cut, double eps = 0.0)

Install an SDDP cut (feasibility or optimality) on the LP backend at (scene, phase). Single unified entry point for every cut install site:

  1. Add the row to the live LP backend and record it in active_cuts() / the low-memory replay via LinearInterface::add_cut_row.
  2. For optimality cuts that reference α, release α's bootstrap pin via bound_alpha_for_cut, whose floor is derived from active_cuts() — so it must run after step 1 (otherwise a cell's first cut floors α at the 0 fallback). Feasibility cuts, and optimality cuts with no α term, leave the pin intact. Callers that also persist the cut into SDDPCutManager should call SDDPMethod::store_cut(...) afterwards using the returned RowIndex — store_cut no longer re-records the cut for replay (that now happens once inside this function).

CvarLayout gtopt::add_cvar_to_lp(LinearProblem& lp, std::span<const CvarScenarioInput> scenarios, double alpha, double weight, double var_scale, SceneUid scene_uid, PhaseUid phase_uid)

Exceptions
std::invalid_argument when α ∉ [0, 1), λ ∉ [0, 1] or no scenario carries positive probability.

Add the mean-CVaR construct to lp (see the file header).

Mutates the objective coefficient of every costed column in the scenario ranges (× (1 − λ)), the objective constant (− λ Σ const_s), and appends η, one u_s per scenario with p_s > 0 and one row per such scenario. var_scale is used as the column and row scale of the construct (pass scale_objective so η, u_s are in the objective's LP units).

PowerBasedResult gtopt::add_power_based_rows(const PowerBasedUnit& unit, LinearProblem& lp)

Add PB1–PB6 for one unit (docs/unit-commitment.md §4.6). The caller drops the energy-block C2 / C4 / C5 rows and rewrites the reserve headroom rows (see rewrite_reserve_rows_power_based).

template<std::ranges::range Range, typename Pred>
bool gtopt::all_of(Range&& range, Pred&& pred)

Checks if all elements in range satisfy predicate.

Template parameters
Range Input range type
Pred Predicate type
Parameters
range Input range
pred Predicate to test
Returns true if all elements satisfy predicate, false otherwise

std::vector<double> gtopt::alpha_col_weights(const SimulationLP& sim, CutSharingMode cut_sharing, const MarkovChainConfig* markov, SceneIndex scene_index, std::size_t n_alpha, bool terminal_phase, std::size_t terminal_phi_count = 0)

THE single mode-aware accessor for the per-column objective weights of the n_alpha α (future-cost) columns on a scene-LP cell — shared by register_alpha_variables (column pricing) and the forward-pass UB strip so the priced future term and the stripped future term are structurally unable to diverge. This is the ONLY public pricing accessor; the uniform M4 weight it replicates for non-Markov layouts (alpha_unit_cost) is an implementation detail internal to sddp_method_alpha.cpp.

  • markov_active(cut_sharing, markov) on a NON-terminal phase with markov->num_states == n_alpha: the MK1 per-state weights w_{s,m'} = p_s·P[m(s)][m']/pi_{m'} (markov_alpha_weights; docs/formulation/sddp-markov.md §2).
  • every other layout — none (n_alpha = 1 → weight 1.0), multicut, and ANY terminal phase (which follows boundary_cut_sharing, never markov): the uniform M4 weight w_r = p_s replicated n_alpha times (Prop. M4, docs/formulation/sddp-cut-validity.md §8; ledger §1.2) — the normalized probability of the scene that OWNS the LP, uniform across the N columns (NOT p_r per column). With varphi_r ≈ V_r = p_r·Ṽ_r, the scene-LP future term becomes Σ_r p_s·p_r·Ṽ_r, i.e. after dividing by p_s the Bellman recursion of the process resampled with measure q_r = p_r — a certified lower bound for that process for ANY probability vector. Under uniform probabilities p_s = 1/N this reproduces the historical 1/N pricing exactly. Masses come from scene_probability_masses; a zero-mass OWNING scene (folded objective 0 anyway) falls back to the uniform 1/n_alpha.
  • TERMINAL phase under BoundaryCutsMode::phi_expectation (terminal_phi_count > 0): the PLP-literal weight w_j = p_s / NVarPhi replicated across the NVarPhi φ_j columns. The boundary cuts on each φ_j are RAW (unfolded — no 1/NVarPhi pre-division, no p_s folding), so the WHOLE probability composition rides on the column price: the folded future term is Σ_j (p_s/NVarPhi)·Φ_j = p_s · E_j[Φ_j] — the scene's probability weighting composes exactly once, mirroring how the M4 pricing composes w_r = p_s with p_r-folded backward cuts (Prop. M4 §8; §9 "phi_expectation" in docs/formulation/sddp-cut-validity.md). This is PLP's stage-52 LP verbatim: NVarPhi φ columns each priced 1/NVarPhi (PlaCFFO, defprbpd.f), lifted into gtopt's p_s-folded per-scene LP.

Always returns exactly n_alpha entries. markov may be null (treated as empty — non-markov pricing). terminal_phi_count is the boundary CSV's NVarPhi (0 = not phi_expectation); it is only consulted when terminal_phase is true, where it must equal n_alpha.

std::vector<std::pair<ColIndex, Uid>> gtopt::alpha_cols_on_cell(const SimulationLP& sim, SceneIndex scene_index, PhaseIndex phase_index, SystemKind kind = SystemKind::forward)

Enumerate every α (future-cost) column registered on (scene_index, phase_index, kind), in source-scene order, as (col, uid) pairs. Single-α modes yield exactly one entry (uid sddp_alpha_uid, offset 0); CutSharingMode::multicut (or terminal BoundaryCutSharingMode::multicut) yields N entries varphi_0..N-1 (uid = sddp_alpha_uid + source_scene). The terminal phase under BoundaryCutsMode::phi_expectation yields NVarPhi entries (uid = sddp_alpha_uid + plane_rank — the plane hydrology's rank in the boundary CSV's sorted distinct scene values; NVarPhi may exceed the scene count). α uids are contiguous from sddp_alpha_uid, so enumeration stops at the first registry gap. Shared by apply_alpha_floor and bound_alpha_for_cut so the per-varphi_s iteration lives in one place.

AmplMetadataValue gtopt::ampl_metadata_uid(Uid uid) noexcept

Metadata value for a reference to another element (a generator's bus, a gas pipe's node_a, …): the referenced element's uid, stored as a number so sum(...) predicates compare it numerically (bus = 3). The one place a Uid becomes a metadata double.

double gtopt::annual_discount_factor(double annual_discount_rate, double time_hours) noexcept

double gtopt::annuity_from_overnight(double overnight_cost, double rate, std::optional<double> life) noexcept

Annuity [$/unit-year] of an overnight cost [$/unit].

void gtopt::apply_alpha_floor(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, SystemKind kind = SystemKind::forward, bool bound_above = false)

Parameters
planning_lp Owning planning LP carrying the per-cell LinearInterface / SystemContext.
scene_index Target scene cell.
phase_index Target phase cell. No-op when α is not registered on (scene_index, phase_index).
kind Which system's α to floor — forward (default) or the backward-pass aperture system.
bound_above When true, ALSO clamp α's column UPPER bound to the cut-derived ceiling ceil = rhs − Σⱼ min(coefⱼ·vⱼ_max, coefⱼ·vⱼ_min) (symmetric to the floor), turning α from a one-sided / free column into a finite box [floor, ceil]. Only safe where the full cut set is already installed (monolithic boundary-cut load) — NOT the SDDP per-cut path, where a later cut can legitimately push α above a ceiling derived from earlier cuts. Both bounds are in the rebased-physical frame (cut.lowb already carries the mean-shift offset c) and are written via set_col_low/upp which divide by the α column's col_scale (= scale_alpha), so the offset and α-scale are both accounted for. Defaults to false (SDDP behaviour unchanged: upper stays +∞).

Generalised cut-derived α floor for an arbitrary phase.

Same projection logic as apply_terminal_alpha_floor but parametrised on the phase index and on the seed (universal weak floor that always holds before any cut is examined). The terminal helper is a one-line wrapper around this with phase_index = sim.last_phase_index() and seed_phys = 0.0.

Exposed so a follow-up can refresh the floor at every interior (scene, phase) cell after a new optimality cut is installed — closing the same CPX_STAT_UNBOUNDED window at intermediate phases whose backward cuts cover only a sub-region of the post-aperture trial-state polytope. See plan §4 in the issue thread for the wiring proposal (SDDPOptions::alpha_floor_mode).

void gtopt::apply_aperture_chunk_override(SDDPOptions& opts, std::optional<ApertureChunkMode> mode, std::optional<int> size) noexcept

Apply a per-level (cascade) aperture-grouping override onto opts.

  • mode set: replaces the inherited mode; when the new mode is not chunked an inherited K is dropped (it would only trigger a spurious "size ignored" warning). size, if also set, wins.
  • only size set (legacy per-level integer): if the inherited mode is chunked and K > 0 only K changes; otherwise the inherited mode is cleared so the integer re-selects it (deprecated encoding, see resolve_aperture_chunk()).

void gtopt::apply_cli_options(Planning& planning, const MainOptions& opts)

Apply command-line options from a MainOptions struct to a Planning object.

Parameters
planning The Planning object to update
opts The MainOptions containing the option overrides

Convenience overload that takes a MainOptions struct directly, delegating to the individual-parameter overload.

void gtopt::apply_cli_options(Planning& planning, const std::optional<bool>& use_single_bus, const std::optional<bool>& use_kirchhoff, const std::optional<std::string>& input_directory, const std::optional<std::string>& input_format, const std::optional<std::string>& output_directory, const std::optional<std::string>& output_format, const std::optional<std::string>& output_compression, const std::optional<std::string>& cut_directory = {}, const std::optional<std::string>& log_directory = {}, const std::optional<int>& sddp_max_iterations = {}, const std::optional<double>& sddp_convergence_tol = {}, const std::optional<double>& sddp_elastic_penalty = {}, const std::optional<std::string>& sddp_elastic_mode = {}, const std::optional<int>& sddp_num_apertures = {}, const std::optional<bool>& lp_debug = {}, const std::optional<bool>& lp_error = {}, const std::optional<std::string>& lp_compression = {}, const std::optional<double>& lp_coeff_ratio_threshold = {})

Apply command-line options to a Planning object.

Parameters
planning The Planning object to update
use_single_bus Optional single-bus mode flag
use_kirchhoff Optional Kirchhoff mode flag
input_directory Optional input directory path
input_format Optional input format string
output_directory Optional output directory path
output_format Optional output format string
output_compression Optional compression codec string
cut_directory Optional directory for SDDP cut files
log_directory Optional directory for log/debug LP files
sddp_max_iterations Optional SDDP max iterations
sddp_convergence_tol Optional SDDP convergence tolerance
sddp_elastic_penalty Optional elastic penalty coefficient
sddp_elastic_mode Optional elastic filter mode string
sddp_num_apertures Optional number of SDDP apertures
lp_debug Optional flag to enable LP debug output
lp_error Optional flag to write an error LP file for infeasible cells (independent of lp_debug)
lp_compression Optional LP output compression codec string
lp_coeff_ratio_threshold Optional threshold for LP coefficient ratio

Updates the planning options based on parsed command-line values.

void gtopt::apply_config_file_defaults(Planning& planning, const MainOptions& conf)

Apply the .gtopt.conf planning-level defaults to planning.

Each config-file value is applied only when the planning JSON left the matching option unset, so the JSON (and afterwards --set and the CLI flags, applied by the caller) always win over the config file. Relative directories from the config file are resolved against the current working directory (as they were when the config file behaved like a CLI default), not against the planning JSON location.

void gtopt::apply_future_cost_config(const FutureCost& fc, SDDPOptions& opts)

Apply the boundary-cut / FCF fields of a FutureCost element onto the internal SDDPOptions carrier that load_boundary_cuts_csv consumes — the ONE read-site mapping used by BOTH MonolithicMethod (onto a fresh, default-constructed SDDPOptions) and SDDPMethod (onto its runtime options). Only fields the element explicitly authors overwrite the target, so a programmatic SDDPOptions (test fixtures) without an element is left unchanged. When the element sets mode but not sharing, the terminal sharing is derived from mode (combined → shared, otherwise per_scene), the legacy scope rule.

Mapping: cuts_file → boundary_cuts_file, mode → boundary_cuts_mode, sharing → boundary_cut_sharing, mean_shift → boundary_cuts_mean_shift, iteration_limit → boundary_max_iterations, missing_cut_var_mode → missing_cut_var_mode, valuation → boundary_cuts_valuation, scale_alpha → scale_alpha. single_cut_equality / use_user_alpha are read off the element itself.

std::expected<MipStartReport, Error> gtopt::apply_mip_start(LinearInterface& li, const SolverOptions& base_opts, const MipStartOptions& opts, std::span<const CommitmentRunInfo> commitments = {}, std::span<const PeakInjectionInfo> injections = {}, const FlatLinearProblem* flat_lp = nullptr)

Returns A report on success (including the relaxation-only / no-op cases), or an Error when the relaxation is infeasible and the policy is stop or feasopt (the caller must NOT proceed to the MIP solve). flat_lp (optional) is the flattened LP that the active backend was loaded from — required only by scip_repair, which builds a second backend from it; nullptr for every other method.

Run the two-stage MIP-start pipeline on li immediately before its MIP solve. base_opts are the effective monolithic solver options (the relaxation solve overlays opts.relax.solver_options on top).

std::vector<double> gtopt::apply_row_max_equilibration(std::span<const std::int32_t> matind, std::span<double> matval, std::span<double> rowlb, std::span<double> rowub, double infinity, std::span<const std::int32_t> rowpin = {})

Bulk row-max equilibration: scale every row of the CSC matrix so its largest |coefficient| becomes 1. Returns the per-row scale factors (max|coeff| per row, or 1.0 for empty rows).

std::vector<double> gtopt::apply_ruiz_scaling(std::span<const std::int32_t> matbeg, std::span<const std::int32_t> matind, std::span<double> matval, std::span<double> rowlb, std::span<double> rowub, std::span<double> collb, std::span<double> colub, std::span<double> objval, std::span<double> col_scales, std::span<const std::int32_t> colpin, double infinity, FastSqrtMethod sqrt_method, int max_iterations, double tolerance, std::span<const std::int32_t> rowpin = {})

Bulk Ruiz geometric-mean iterative equilibration: alternately normalises rows and columns by 1/sqrt(infinity-norm) until the worst deviation from 1 drops below tolerance, or max_iterations rounds are done. Updates matval, the row/col bounds, the objective and col_scales in place; returns the cumulative per-row scale. colpin lists columns exempt from rescaling (integer ∪ pin_scale).

max_iterations / tolerance are plumbed from LpMatrixOptions::ruiz_max_iterations / ruiz_tolerance so the iterative cost can be tuned (notably in SDDP/cascade, where the whole system LP is rebuilt — and re-equilibrated — at every level).

bool gtopt::apply_set_options(Planning& planning, const std::vector<std::string>& set_options)

Apply all --set key=value overrides to a Planning object. Returns true if all options were applied successfully.

CvarLayout gtopt::apply_tail_weights_to_lp(LinearProblem& lp, std::span<const CvarScenarioInput> scenarios, std::span<const double> risk_probability, RiskMeasure measure, RiskTail tail, double alpha, double weight, SceneUid scene_uid, PhaseUid phase_uid)

Re-weight the scenario costs of lp with fixed risk-adjusted probabilities risk_probability (from tail_risk_weights): every costed, non-first-stage column of scenario s and its share of the objective constant are multiplied by q_s / p_s. No row or column is added; the LP stays the size of the expected-cost LP.

void gtopt::apply_terminal_alpha_floor(PlanningLP& planning_lp, SceneIndex scene_index)

Apply a derived lower-bound floor on α_T at the last phase by projecting every installed boundary cut onto the worst-case trial-state box. For each cut

α + Σⱼ coefⱼ · vⱼ ≥ rhs

the universal floor over the feasible state-variable box [vⱼ_min, vⱼ_max] is

floor_cut = rhs − Σⱼ max(coefⱼ · vⱼ_max, coefⱼ · vⱼ_min)

(when coefⱼ > 0 the maximiser is vⱼ_max; when coefⱼ < 0 it is vⱼ_min). Taking the max of floor_cut across every cut and clamping at 0 (cost-to-go is non-negative under non-negative stage costs) gives the tightest universal lower bound on α_T implied by the cuts alone, independent of which trial state the master / aperture clones pick.

The motivation is the plain-variant hydrothermal case pathology: boundary cuts cover only the trial-state regions they were generated at, and aperture-perturbed trial states can fall outside that polyhedral approximation, leaving α_T effectively unbounded below in the aperture clone (CPLEX returns CPX_STAT_UNBOUNDED, logged as "infeasible (status 2)" by the aperture pass). Pinning the column at the cut-derived floor closes that hole without over-tightening (boundary cuts that produce a tighter row-based bound still dominate).

The floor is seeded at 0 before any cut is examined and only ratchets UP from there, so the function is safe to call even when no cuts (or no α-referencing cuts) are installed at the last phase — the result in that case is the weak universal floor α_T ≥ 0, which always holds under non-negative stage costs and prevents α_T from going unbounded below in aperture clones. No-op only when α is not registered at the last phase on scene_index (a pre-register_alpha_variables call site). The mirror update_dynamic_col_bounds is called so the floor survives a release_backend + ensure_backend cycle under LowMemoryMode::compress.

Unit convention. All arithmetic in this helper runs in physical-space units:

  • LinearInterface::active_cuts() returns rows captured by record_cut_row BEFORE compose_physical mutated them — so cut.lowb is rhs_phys and cut.cmap[col] is coef_phys.
  • State-variable column bounds are read via get_col_low() / get_col_upp() (ScaledView returning raw × col_scale), so the multiplication coef_phys · v_phys lands in the same units as rhs_phys.
  • The floor is written via the physical setter set_col_low(α_col, floor_phys) (which divides by α's col_scale = scale_alpha internally to land raw in the backend) and mirrored to update_dynamic_col_bounds with the same physical floor (SparseCol.lowb is physical — see LinearProblem::flatten). Both representations stay coherent across release_backend / ensure_backend cycles.

template<char sep = '_'>
auto gtopt::as_label() noexcept

Creates an empty label string.

Template parameters
sep Separator character (default '_')
Returns constexpr std::string Empty string

template<typename Sep, typename... Args>
std::string gtopt::as_label(Args && ... args)

No-separator variant of as_label().

Template parameters
Sep MUST be void — selects this overload via the std::is_void_v<Sep> constraint. Any other type is rejected, and any char NTTP routes to the regular overload.
Args Argument types (deduced).
Parameters
args Values to concatenate, in order.
Returns std::string The concatenated, separator-free result.

Selected by passing void as the template argument: arguments are concatenated back-to-back with no separator inserted. Useful when you want the inline punctuation to come from the call site itself — e.g. reconstructing a key like "i0 s1 p4" from individual fields:

auto k = as_label<void>('i', iter,
                        ' ', 's', scene_uid,
                        ' ', 'p', phase_uid); // "i0 s1 p4"

Each char argument becomes a single-character string (via the existing string_holder(char) constructor), so spaces, brackets, and other punctuation pass through verbatim. Integral arguments still hit the compile-time 0–1023 cache; floating-point and custom types still flow through string_holder.

Empty arguments are skipped (nothing is added — there is no separator to suppress). Calling with no arguments returns the empty string.

template<char sep = '_', typename... Args>
std::string gtopt::as_label(Args && ... args)

Creates a concatenated label from multiple arguments.

Template parameters
sep Separator character between components (default '_')
Args Argument types (automatically deduced)
Parameters
args Values to concatenate into label
Returns constexpr std::string Concatenated label string
Exceptions
Nothing if all arguments can be converted to string without throwing

Example:

auto label = as_label("config", "value", 42); // "config_value_42"

template<char sep = '_'>
void gtopt::as_label_into(std::string& result) noexcept

Clears and writes a label into an existing string buffer.

Template parameters
sep Separator character (default '_')
Returns constexpr void

template<typename Sep, typename... Args>
void gtopt::as_label_into(std::string& result, Args && ... args)

No-separator variant of as_label_into().

Counterpart of as_label<void>(...) that writes into an existing buffer (cleared, capacity preserved). Selected by passing void as the template argument. See as_label<void> for argument semantics.

template<char sep = '_', typename... Args>
void gtopt::as_label_into(std::string& result, Args && ... args)

Writes a concatenated label into an existing string buffer.

Template parameters
sep Separator character between components (default '_')
Args Argument types (automatically deduced)
Parameters
result String buffer to write into (cleared, not deallocated)
args Values to concatenate into label

Like as_label(), but reuses the buffer's existing capacity to avoid repeated heap allocations across calls. The buffer is cleared (not deallocated) on each call, so its capacity grows monotonically to the high-water mark.

template<typename... Args>
std::string gtopt::as_string(const std::tuple<Args...>& t)

template<typename SystemLPT>
Real gtopt::average_volume_from_cache(const SystemLPT& sys, const ScenarioLP& scenario, const StageLP& stage, const ReservoirRefCache& rc)

Convenience: return the (vini + vfin) / 2 average that all four reservoir-driven update_lp impls (FlowRight, RDL, ProductionFactor, VolumeRight) use as the bound-rule axis input. ReservoirSeepageLP uses physical_eini_from_cache directly (vini-only, by design).

bool gtopt::axis_uses_reservoir(BoundRuleAxis axis) noexcept

Whether this axis depends on a reservoir reference.

Call sites use this to skip the reservoir element lookup entirely when the configured axis does not consume reservoir state, so the reservoir field can be left unset on stage-month rules.

void gtopt::bound_alpha(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, SystemKind kind = SystemKind::forward)

Release α's bootstrap pin (lowb = uppb = 0) at the given (scene, phase) cell. Sets lowb = -DblMax, uppb = +DblMax on the live LP backend and mirrors the change into the m_dynamic_cols_ entry so release+reload replay preserves the freed bounds. Idempotent and safe to call on a cell whose α has not been registered (no-op). Shared by the SDDPMethod backward/feasibility paths and the boundary-cut loader in source/sddp_cut_io.cpp so every cut-install site uses the same free-α semantics.

void gtopt::bound_alpha_for_cut(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, const SparseRow& cut, SystemKind kind = SystemKind::forward)

Release α's bootstrap pin at (scene, phase) ONLY when cut actually references α — i.e., α is registered on the cell AND the cut's sparse coefficient map contains the α column. No-op otherwise. Meant to be called at every optimality-cut install site (backward-pass aperture expected-cut, aperture bcut fallback, and cut-file loaders for CSV/JSON optimality cuts) so a cut that does not constrain α — e.g. α coefficient filtered by cut_coeff_eps at save time, or a pure state-coupling cut — does not prematurely release the bootstrap pin. Feasibility cuts should never call this (they carry no lower-bound information on the future-cost variable); callers must gate on cut type upstream.

void gtopt::bound_user_alpha(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, Uid user_alpha_uid, SystemKind kind = SystemKind::forward)

Release the bootstrap pin (lowb = uppb = 0) on the USER-authored α (dynamic AmplFutureCost, piece 5 step 2c) at (scene, phase). Locates the user α via find_user_alpha_state_var and frees its column to [-∞, +∞] on the live backend, mirroring the change into the compress-replay channel so a release_backend + ensure_backend cycle preserves the freed bounds. No-op when the user α is not registered on the cell. The user α is a single column (NOT N varphi_s), so this is the bound_alpha analogue for the user-overridable FCF — it does NOT compute a cut-derived floor (the user's own UserConstraint cuts already bound it).

flat_map<std::string, BoundaryCutCoeffStats> gtopt::boundary_cut_coeff_stats(const std::string& filepath)

Extract the per-state-variable coefficient statistics from a boundary-cut CSV: {state_var_name → {min, avg, max}} over every cut row, read through the same Arrow CSV path as load_boundary_cuts_csv. The state variable name is the trailing CSV column header (reservoir / battery name). This is the parse the scale-alpha derivation builds on (the reservoir efin soft-cost / water-value is now computed in the Python converters, not here). Empty when the file is missing, malformed, or has no state columns.

double gtopt::boundary_cut_max_avg_coeff(const std::string& filepath)

max_i |avg(coeff_i)| over boundary_cut_coeff_stats — the cut-coeff magnitude used to scale α. Returns 0.0 when the file yields no columns.

double gtopt::boundary_cut_scale_alpha(const PlanningLP& planning_lp, const std::string& boundary_cuts_file, double option_scale_alpha)

Compute scale_alpha for a boundary-cut workflow straight from the cut file: effective_scale_alpha(planning_lp, option_scale_alpha, boundary_cut_max_avg_coeff(boundary_cuts_file)). This is the single entry point both MonolithicMethod and SDDPMethod use when boundary cuts are installed, so α is scaled identically regardless of solver method.

std::size_t gtopt::boundary_cut_scene_count(const std::string& filepath)

Count the DISTINCT values of the boundary-cut CSV's scene column — the NVarPhi of BoundaryCutsMode::phi_expectation (the number of PLP plane hydrologies whose per-hydrology FCFs the file carries; PLP ISimul / leeplaem.f). Read through the same Arrow CSV path as load_boundary_cuts_csv so layout / type handling stays identical. Returns 0 when the file is missing, malformed, or has no scene column — callers treat 0 as "phi layout unavailable". Deterministic on the same file, so the α-registration pre-scan and the loader's plane-rank mapping (sorted distinct scene values) always agree.

SparseRow gtopt::build_benders_cut_physical(ColIndex alpha_col, std::span<const StateVarLink> links, const LinearInterface& rc_source, double objective_value_physical, double cut_coeff_eps = 0.0)

Physical-space Benders cut builder that reads reduced cost from an arbitrary LinearInterface (typically an elastic clone) and trial value from each link's back-pointer StateVariable. Intended for cut paths whose rc comes from a local LP solve rather than the base forward pass — the forward-pass feasibility cut and the aperture per-aperture cut both fit this shape.

rc_phys = rc_source.get_col_cost()[link.dependent_col] (ScaledView: LP × scale_objective / col_scale) v̂_phys = link.state_var->col_sol_physical()

scale_objective is not a parameter: it is embedded in the get_col_cost() view. The clone must have been solved (rc and col solution available) before this call.

SparseRow gtopt::build_benders_cut_physical(ColIndex alpha_col, std::span<const StateVarLink> links, double objective_value_physical, double scale_objective, double cut_coeff_eps = 0.0)

Parameters
alpha_col α column in the source phase's LP.
links State-variable linkage descriptors. Links with a null state_var contribute zero (rc_phys = v̂_phys = 0), matching the test-fixture convention.
objective_value_physical Target subproblem optimum in $, i.e. target_li.get_obj_value().
scale_objective Global objective scale (required so reduced_cost_physical() can descale the LP reduced cost to $/phys_unit).
cut_coeff_eps Drop state-var coefficients below this absolute threshold (default 0 = keep all).

Physical-space Benders cut builder that reads reduced cost and trial value from each link's back-pointer state variable instead of taking flat spans. The SDDP backward pass uses this overload: the forward pass already mirrors the target LP's col_sol / reduced_cost onto every StateVariable via capture_state_variable_values, so the builder can read the live values directly without re-taking the full per-LP snapshots.

rc_phys = state_var->reduced_cost_physical(scale_objective) = rc_LP[dep] · scale_objective / col_scale[dep] (the DEPENDENT column's own scale — never the source column's var_scale, which ruiz makes different) v̂_phys = state_var->col_sol_physical() lowb = objective_value_physical − Σ rc_phys · v̂_phys row[src_col] = −rc_phys, row[alpha_col] = 1.0

The returned row carries no already_lp_space flag: add_row on an equilibrated LP will fold col_scales and run per-row row-max equilibration, so the resulting row is well-conditioned without any post-hoc rescale_benders_cut pass.

SparseRow gtopt::build_benders_cut_physical(ColIndex alpha_col, std::span<const StateVarLink> links, std::span<const double> reduced_costs_physical, std::span<const double> trial_values_physical, double objective_value_physical, double cut_coeff_eps = 0.0)

Parameters
alpha_col α column index in the source phase's LP.
links State-variable linkage descriptors (same struct the LP-space overload consumes). link.dependent_col selects the target entry in reduced_costs_physical; link.source_col selects the matching entry in trial_values_physical.
reduced_costs_physical Physical reduced costs of the target LP's dependent columns — read from target_li.get_col_cost() (which applies LP × scale_objective / col_scale).
trial_values_physical Physical trial values for each link's source column — read from source_li.get_col_sol()[link.source_col] (= LP × col_scale_source). Indexed in parallel with links, so entry i corresponds to links[i].
objective_value_physical Target subproblem optimum in $, i.e. target_li.get_obj_value().
cut_coeff_eps Drop state-var coefficients below this absolute threshold (default 0 = keep all).

Physical-space Benders optimality cut builder.

α_phys ≥ z_t_phys + Σ_i rc_phys_i · (x_{t-1,i}_phys − v̂_i_phys)

Intended for use with LinearInterface::add_equilibrated_row, which folds col_scales and the per-row equilibration internally. All inputs are in physical space:

Returns a SparseRow with:

  • row[alpha_col] = 1.0
  • row[source_col] = -rc_phys
  • row.lowb = obj_phys − Σ rc_phys · v̂_phys
  • row.uppb = DblMax, row.scale = 1.0

The caller is expected to pass this row to LinearInterface::add_equilibrated_row, which applies the LP's column scales and per-row row-max equilibration to produce the final LP-space row.

std::vector<ApertureEntry> gtopt::build_effective_apertures(std::span<const Aperture> aperture_defs, std::span<const Uid> phase_apertures)

Parameters
aperture_defs All aperture definitions from the simulation
phase_apertures Per-phase aperture UID set (may be empty)
Returns Deduplicated aperture entries with repetition counts

Build the effective (deduplicated) aperture list for a single phase.

When phase_apertures is empty, all active apertures from aperture_defs are used (each with count = 1). When phase_apertures is non-empty, UIDs are counted for duplicates and mapped to their definitions; order of first appearance is preserved for deterministic results.

PlpFeasibilityCuts gtopt::build_farkas_recursive_cut(ElasticSolveResult& elastic, std::span<const StateVarLink> links, const LpContext& context, double fact_eps)

Parameters
elastic Solved elastic clone + slack info (non-const: reading duals may trigger ensure_duals()).
links Outgoing state-variable links (same order as elastic.link_infos).
context LP context stamped on the emitted row.
fact_eps Zero-guard + outward-margin tolerance (SDDPOptions::fact_eps, default 1e-8).

Füllner–Rebennack recursive feasibility cut (SIAM Review 2023, §17.2–17.3) — ONE aggregated cut per infeasibility event, built from ORDINARY optimal duals of the elastic Phase-1 clone. Never touches a solver Farkas/ray API (CPXdualfarkas, GRB FarkasDual, …) so the construction is identical across backends (solver-independence directive, 2026-07-11).

The clone must come from elastic_filter_solve with ElasticCostPolicy::Model::unit (the review's eᵀy⁺ + eᵀy⁻ objective) and with every INSTALLED feasibility-cut row passed as elastic_fcut_rows (the §17.2 + I z term: a_rᵀx + z_r ≥ b_r, z_r ≥ 0, cost = row_scale(r), i.e. 1 per physical unit of violation) — that is what makes the clone ALWAYS solvable when a previously-installed cut is itself the unsatisfiable row.

Mapping to the review's eq. (17.3) (σᵀT)x ≥ σᵀh_t + ωᵀα^f:

  • h_t ↔ the trial RHS of the state-fixing rows dep_i + sup_i − sdn_i = trial_i (the only x-dependent RHS entries in gtopt's bound-pin formulation; σ_i = −dual_i is the σᵀT coefficient on the source column, same sign convention as build_feasibility_cut_physical),
  • α^f_r ↔ b_r, the installed cut row's lower bound, with dual ω_r = dual(fcut_row_r) ≥ 0 at the min-slack optimum.

The intercept σᵀh_t + ωᵀα^f (plus gtopt's extra column-box dual folds, absent from the review's y ≥ 0 canonical form) equals — by STRONG DUALITY — the clone optimum V(v̂) rebased at the trial:

Σ_i σ_i·x_i  ≥  Σ_i σ_i·v̂_i + V(v̂),

which is what this builder emits (with the fact_eps relative outward margin rhs += fact_eps·|rhs|, like state_repair). V is read as get_obj_value() − get_obj_constant(): the LP's objective CONSTANT (solver-native offset — demand-fail baseline, boundary c̄) is NOT part of the feasibility gap. The clone from elastic_filter_solve already has the offset zeroed, so the subtraction is normally a no-op; leaking it (pre-2026-07-11) inflated every intercept by ~1.7e8/phase on the 2-yr case and drove an additive p52→p0 RHS runaway through the z-fold. When the unmargined intercept is satisfiable at the box top (Σ σ_i·edge_i, edge = source_upp for σ>0 / source_low for σ<0), the margined RHS is clamped to that box-top LHS so the outward epsilon can never make an exactly-edge cut presolve-infeasible — the aggregated mirror of state_repair's bound_limit. An intercept already above the box top BEFORE the margin is kept verbatim (it is the exact unreachability proof; the master then correctly backtracks another level) and WARN-logged. The downstream cut intercepts ω_r·b_r are FOLDED through V — the poisoned rows' residual violation Σ ω_r·z*_r is exactly the z-part of the unit-cost objective. Note this deliberately does NOT add ω_r·b_r on top of the σ·nx form: with unit costs Σ σ_i·nx_i = σᵀv̂ + V_slack, so the literal sum would double-count by Σ ω_r·(a_rᵀx*) ≥ 0 and cut off feasible master states. Validity: V is convex in the fixing-row RHS and any optimal dual is a subgradient — V(x) ≥ V(v̂) + σ̃ᵀ(x − v̂) with σ̃ = −σ, and feasibility requires V(x) ≤ 0 — so the cut is valid even at degenerate vertices.

σ zero-guard: |σ| < fact_eps + 2⁻³⁶ → 0; non-finite duals are zeroed with a WARN. Coefficients are emitted per-physical-unit (σ_view / col_scale(dep)), exact under ruiz/var_scale scaling.

Status semantics mirror build_plp_feasibility_cuts:

  • cuts_added — one aggregated row in cuts;
  • holguras — clone optimal but every σ zeroed (no state sensitivity; no valid state cut exists);
  • fail — clone not proven optimal (infeasibility rooted in rows the filter cannot relax).

std::optional<FeasibilityCutResult> gtopt::build_feasibility_cut(const LinearInterface& li, ColIndex alpha_col, std::span<const StateVarLink> links, double penalty, const SolverOptions& opts, double scale_alpha = 1.0, double scale_objective = 1.0)

Parameters
li The LP to clone (not modified)
alpha_col α column in the source phase's LP
links Outgoing state-variable links from the source phase
penalty Elastic penalty coefficient
opts Solver options
scale_alpha Unused; retained for source compatibility (the physical builder folds column scales itself).
scale_objective Unused; retained for source compatibility.
Returns A feasibility cut (SparseRow) and the ElasticSolveResult, or nullopt if the elastic solve fails.

Build a Benders feasibility cut from a solved elastic clone.

This wraps the common pattern: clone → relax → solve → extract cut. The function calls elastic_filter_solve() internally.

SparseRow gtopt::build_feasibility_cut_physical(std::span<const StateVarLink> links, std::span<const RelaxedVarInfo> link_infos, LinearInterface& rc_source, double cut_coeff_eps, int niter)

Parameters
links State-variable linkage descriptors. Each link contributes its source_col coefficient derived from its paired link_info.fixing_row.
link_infos RelaxedVarInfo per link (same order and size as links). Provides fixing_row for the row-dual read and sup_col/sdn_col for the slack-activation term in the RHS.
rc_source Solved elastic clone — must have crossover = true so get_row_price() returns a valid vertex dual.
cut_coeff_eps Drop state-var coefficients below this absolute threshold (default 0).
niter Unused; retained for signature stability (the former niter-scaled RHS bump is disabled, PLP parity).

Physical-space feasibility cut builder — PLP / classical-Benders convention (no α term). Produces a pure state-coupling constraint Σ πᵢ · sᵢ ≥ Σ πᵢ · v̂ᵢ + Σ slack_iᵢ where πᵢ is the dual of the fixing equation dep_col + sup − sdn = v̂ at the elastic clone's Phase-1 optimum, and slack_i = x[sup_i] - x[sdn_i] is the net slack activation (the amount the trial had to move to become feasible). Matches plp-agrespd.fAgrElastici line-for-line (lp->getRowPrice()[row] for the coefficient, (b[row] + dx) * ray[i] for the RHS term).

Why no α: a feasibility cut certifies "this trial point leads to downstream infeasibility" — it carries no lower-bound information on the expected future cost. Mixing α into the cut would let the master drive α negative to "satisfy" the cut trivially (the LB-frozen-at-0 pathology).

BuildInfo gtopt::build_info() noexcept

std::string gtopt::build_iteration_status_json(const std::vector<SDDPIterationResult>& results, double elapsed_seconds, const SolverStatusSnapshot& snapshot)

Parameters
results Vector of per-iteration results
elapsed_seconds Total elapsed time since solve() started
snapshot Current solver state snapshot
Returns Partial JSON string (no trailing })

Build the ITERATION portion of the solver-status JSON document.

Serialises every field that depends on live solver state (top-level scalars, async block, lp_task_stats, per-iteration history, and the phase_grid) EXCEPT the real-time pool/realtime block, which the SolverMonitor owns and refreshes on its own sampling cadence.

The returned string is a partial JSON document: it begins with { and ends WITHOUT the closing } — the caller (or the monitor thread) appends the freshly-sampled pool/realtime block and the closing brace via build_realtime_status_json().

This is intended to be called on the SOLVER thread, where results and phase_grid are stable (i.e. the per-iteration synchronisation point), so the monitor thread never touches live solver state.

std::vector<SparseRow> gtopt::build_multi_cuts(ElasticSolveResult& elastic, std::span<const StateVarLink> links, const LpContext& context, double cut_coeff_eps, int niter)

Parameters
elastic Solved elastic clone + per-link slack info (non-const because reading dual prices may trigger ensure_duals() on the backend). Per-direction slack costs (slack_cost_sup/slack_cost_sdn) are read directly from the clone's slack column costs via get_col_cost_raw(), which transparently picks up the asymmetric bias applied at relaxation time and any future per-link variation. No external penalty parameter needs to be plumbed through — the elastic clone is the single source of truth for slack pricing.
links Outgoing state-variable links (same order as elastic.link_infos).
context LP context for the generated cut rows.
cut_coeff_eps Threshold for the |π| < ε drop above (default 1e-8 in production, override for tests).
niter Iteration counter; controls the outward FactEPS perturbation (1e-10 × niter).
Returns Vector of feasibility cuts (one per surviving link), OR an empty vector when the whole-family degeneracy guard fires. Caller (sddp_forward_pass.cpp) treats empty as "no feasibility cut produced" and flags the scene infeasible.

Build per-slack bound-constraint cuts from a solved elastic clone.

For each outgoing link whose slack was activated (non-zero) in the elastic-clone solution, this function generates one feasibility cut on the source column:

π · source_col ≥ π · clamp(v̂ + dx · scale, source_low, source_upp)

π = −row_dual[fixing_row] (signed sensitivity dual at the elastic clone's optimum) dx = sdn_val − sup_val (net slack activation on the fixing row dep + sup − sdn = v̂)

Per-link drops (mirroring PLP osicallsc.cpp::osi_lp_get_feasible_cut):

  1. |π| < cut_coeff_eps — drop tiny duals.
  2. |π · dx| < 1e-9 × (|π · v̂| + 1e-8) — drop sub-tolerance slack activations (the dx-relative low-activation filter).

Whole-family drop (gtopt-specific guard, no PLP equivalent):

  • When EVERY surviving per-link cut clamps at source_upp (top 10 % of [source_low, source_upp]), the family is a "every state floored at emax" degenerate cut. Master retries installing such a family always cascade-fail (the master cannot reach emax on every reservoir simultaneously in one phase). The function CLEARS its return vector in that case so the caller sees "no cut produced" and declares infeasibility directly, skipping the wasted retry chain (the large hydrothermal case: 28 backtracks → 0). A WARN is emitted naming the reservoirs.

flat_map<PhaseUid, PhaseIndex> gtopt::build_phase_uid_map(const PlanningLP& planning_lp)

Build a phase UID -> PhaseIndex lookup from a SimulationLP. Uses flat_map for cache-friendly sorted lookup.

PlpFeasibilityCuts gtopt::build_plp_feasibility_cuts(ElasticSolveResult& elastic, std::span<const StateVarLink> links, const LpContext& context, double fact_eps)

Parameters
elastic Solved elastic clone + per-link slack info (non-const: reading duals may trigger ensure_duals()). elastic.solved == false short-circuits to PlpCutStatus::fail.
links Outgoing state-variable links (same order as elastic.link_infos).
context LP context stamped on each emitted row; when it carries an IterationContext the 4th slot is made per-sibling-unique (same scheme as build_multi_cuts) so the StoredCut CutKey dedup keeps every sibling.
fact_eps PLP FactEPS (SDDPOptions::fact_eps, default 1e-8).

PLP-exact per-link feasibility-cut builder — reproduces plp-agrespd.fAgrElastici + osicallsc.cpp:: osi_lp_get_feasible_cut under the default FOneFeasRay = FALSE (the only branch PLP production runs exercise).

From the solved elastic Phase-1 clone (per-physical-unit slack costs — pair with ElasticCostPolicy::Model::plp_unit_rc_tilt), per link i with eps = fact_eps + 2⁻³⁶:

ray_i = −dual(fixing_row_i); |ray_i| < eps → 0 dx_i = sdn_i − sup_i (LP-raw; = PLP's sp − sn); |dx_i| < fact_eps·(|trial_i| + 1e-8) → dx_i = 0 ∧ ray_i = 0 nx_i = v̂_phys_i + dx_i·dep_scale_i (the minimally repaired initial state — the dep_clone_phys convention) rhsi_i = ray_i · nx_i

Emission: deps = 1e-3·fact_eps·|Σ rhsi| + 2⁻³⁶; every link with |ray_i| > deps yields ONE single-variable row ray_i · x_i ≥ rhsi_i + fact_eps·|rhsi_i|.

Deliberately ABSENT (PLP guarantees bound-consistency BY CONSTRUCTION — the slack caps equal the previous phase's state box, so nx_i ∈ [source_low, source_upp] always):

  • no clamping of the RHS to the state box,
  • no top-10 % saturation drop,
  • no all-upper degenerate-family drop,
  • no fallback aggregated cut.

flat_map<SceneUid, SceneIndex> gtopt::build_scene_uid_map(const PlanningLP& planning_lp)

Build a scene UID -> SceneIndex lookup from a SimulationLP. Uses flat_map for cache-friendly sorted lookup.

std::expected<int, std::string> gtopt::build_solve_and_output(Planning&& planning, const MainOptions& opts)

Build the LP model, solve it, and write output.

Wraps the full LP pipeline: matrix construction, optional LP-file dump, coefficient stats, solver invocation, post-solve stats, and output writing. Returns 0 on success, 1 when the solver finds no optimal solution, or an error string on hard failures.

std::optional<StrengthenedCutResult> gtopt::build_strengthened_benders_cut(ColIndex alpha_col, std::span<const StateVarLink> links, const LinearInterface& target_li, double cut_coeff_eps, const SolverOptions& lp_opts, const SolverOptions& mip_opts)

Returns nullopt when the LP-relaxation solve fails (caller falls back to its legacy cut path). Otherwise the cut, with tightened == false when the MIP solve failed / timed out (the row is then the plain LP-relaxation cut — still valid).

Strengthened Benders optimality cut for an integer-bearing target subproblem (Zou, Ahmed & Sun 2019 §5; Theorem SB1 / Corollary SB2 in docs/analysis/investigations/sddp/sddip_integer_expansion_2026-07.md).

On a CLONE of target_li (never mutated; state pins dep = v̂ must be in place, i.e. post-propagate_trial_values):

  1. relax integrality, solve the LP relaxation at v̂ → z*_LP and pinned reduced costs λ (the sound LP-relaxation duals — a MIP re-solve has none);
  2. build the Theorem-O1 cut α + Σ(−λ_i)x_i ≥ z*_LP − ⟨λ, v̂⟩ (cut_coeff_eps filter as usual; dropped links get λ_i = 0);
  3. restore integrality, relax every pinned dependent column to its physical source box [source_low, source_upp], charge −λ_i on each kept dependent column's objective coefficient, and solve ONE MIP. Its physical optimum is directly the strengthened intercept m* = L(λ) − ⟨λ, v̂⟩;
  4. emit rhs = max(b_LP, m*) — valid for every state in the box by weak Lagrangian duality, and never looser than the LP cut.

The strengthening MIP runs under mip_opts — callers should pin a tight mip_gap (the incumbent value over-tightens by up to gap × |m*|; see the investigation doc §6.3) and a time_limit.

Array<Aperture> gtopt::build_synthetic_apertures(std::span<const ScenarioLP> all_scenarios, std::ptrdiff_t n_apertures)

Parameters
all_scenarios All scenario LP objects
n_apertures Number of apertures to create (capped at all_scenarios.size())
Returns Array of synthetic Aperture objects

Build synthetic aperture definitions from the first N scenarios.

Creates one aperture per scenario with equal probability (1/N). Used when no explicit aperture_array is provided in the simulation and the solver falls back to the legacy num_apertures-based behaviour.

std::filesystem::path gtopt::build_table_path(std::string_view input_dir, std::string_view cname, std::string_view fname)

Build the filesystem path for an input table.

Parameters
input_dir Root input directory.
cname Class name (used as sub-directory when '@' is absent).
fname Field name, possibly containing an '@' separator.
Returns Resolved path (without file extension).

If fname contains '@', the part before '@' is treated as an override class directory; otherwise cname is used.

template<typename SystemContextT>
Real gtopt::build_time_reservoir_volume(const SystemContextT& sc, const ScenarioLP& scenario, const StageLP& stage, const ReservoirLP& rsv)

Build-time estimate of a reservoir's volume at stage for the RightBoundRule evaluated in add_to_lp (before any solve).

At a phase boundary the predecessor phase's efin StateVariable is the correct per-phase state once a forward pass has set it (e.g. when the phase LP is rebuilt under low_memory); an UNSET state variable (no forward solve yet) falls back to the case eini. In-phase stages have no solved state at build time and use the case eini; update_lp refreshes the bound from the solved/propagated state before every solve.

const SolverCfgPairs* gtopt::cached_sibling_param_file(const std::optional<std::string>& param_file, std::string_view sibling_name)

Cached pairs of a sibling file next to param_file.

Resolves <dir of param_file>/<sibling_name> (e.g. cplex_warmstart.prm, highs_warmstart.opts) through cached_solver_param_file. Returns nullptr when param_file is unset/empty or the sibling does not exist.

const SolverCfgPairs* gtopt::cached_solver_param_file(const std::filesystem::path& path)

Once-per-process cached parse_solver_param_file.

Thread-safe. Returns the file's pairs, or nullptr when the file cannot be read; the pointer stays valid for the life of the process (map nodes are never erased). A missing file is cached too, so a hot path never even re-stats it. Plugins use this instead of the solvers' own file readers (CPXreadcopyparam, GRBreadparams, Highs::readOptions, MDOreadparams), which hit the disk on every call — once per new env / clone / warm-start solve.

std::string gtopt::canonicalize_json_keys(std::string_view json_text)

Convenience overload using the process-wide singleton.

std::string gtopt::canonicalize_json_keys(std::string_view json_text, const NamesRegistry& registry)

Rewrite every "alias": object-key occurrence in json_text to its canonical form using registry. Returns a new string; the input is not modified.

Performance: single linear pass over the input, O(N) in text size plus O(K) per key lookup where K is the longest registered alias. On the large hydrothermal case (~12 MB JSON) the empirical overhead is well under 100 ms.

Safety: only quoted strings that appear in object-key position (immediately after { or , inside an object, ending in :) are considered for substitution. Quoted strings in value position are passed through verbatim. JSON string escapes (\", \\, \n, \u00XX, etc.) are recognised so escaped quotes inside strings do not terminate the token scan.

std::string gtopt::canonicalize_json_keys(std::string_view json_text, const NamesRegistry& registry, std::string_view enforce_dialect)

Same as above, plus drive the input warn pass: when enforce_dialect is non-empty and an alias's source dialect tag in the registry differs from it, emit a once-per-alias spdlog::warn. Empty preserves the pre-feature silent behaviour.

std::string gtopt::canonicalize_json_keys(std::string_view json_text, std::string_view enforce_dialect)

Convenience overload using the process-wide singleton + dialect enforcement.

double gtopt::capital_recovery_factor(double rate, std::optional<double> life) noexcept

Capital recovery factor CRF(r, n) [1/year].

  • n unset or n <= 0: perpetuity, CRF = r.
  • r == 0: straight-line, CRF = 1 / n.
  • r <= -1 is not a rate: returns 0 (no annuity).

std::shared_ptr<arrow::DoubleArray> gtopt::cast_to_double_array(const std::shared_ptr<arrow::Array>& chunk)

Cast an Arrow array chunk to DoubleArray, handling float32 widening.

Parameters
chunk The Arrow array chunk to cast
Returns A shared pointer to a DoubleArray, or nullptr if the type is incompatible

std::shared_ptr<arrow::Int32Array> gtopt::cast_to_int32_array(const std::shared_ptr<arrow::Array>& chunk)

std::vector<std::size_t> gtopt::cell_groups(std::span<const double> cells, double period)

Group index (consecutive, from 0) of every cell for a nominal group length period [h]: cell k → ⌊mid_k / P⌋, renumbered without gaps (a long cell spanning several nominal groups leaves no empty group). All zeros when P ≤ 0.

int gtopt::check_all_solvers(bool verbose = false)

Run the test suite against every USABLE solver.

Parameters
verbose Forward to run_solver_tests.
Returns 0 if all tests for all usable solvers pass, 1 otherwise.

Calls identify_all_available_solvers() first, then run_solver_tests() for each survivor, printing a summary to stdout.

void gtopt::check_model_sanity(ValidationResult& result, const Planning& planning)

Data-quality (sanity) warnings — never errors.

Flags data that is legal but almost certainly wrong, one summary warning per category (count + top offenders; details at debug level):

  • water-right rewards (FlowRight.uvalue > 0, fcost < 0, hydro_use_value) above the demand fail cost (phantom reward);
  • generator / demand / capacity profiles outside [0, 1];
  • generators / batteries with pmax = 0 over the whole horizon that still carry commitment binaries or a pmin > 0;
  • line impedance: X/R above a ceiling, reactance above a p.u. ceiling for its kV, |X|/V² far from its kV-class median;
  • reservoirs without emin whose volume drives an agreement bound_rule with a reserve level.

Thresholds come from planning.options.sanity_options. Only inline values are inspected (file-backed schedules are skipped). Called by validate_planning(); exposed for tests.

IntegrityDecision gtopt::check_plugin_build_id(std::string_view plugin, std::optional<std::string_view> manifest_id, std::optional<std::string_view> file_id, const PluginIntegrityPolicy& policy)

Compare the plugin file's build-id with its manifest entry. Match → ok; mismatch, no manifest or no build-id → finding.

IntegrityDecision gtopt::check_plugin_build_tag(std::string_view plugin, std::string_view host_tag, std::optional<std::string_view> plugin_tag, const PluginIntegrityPolicy& policy)

Compare the plugin's build tag with the host's. Equal → ok; differs or missing → finding.

IntegrityDecision gtopt::check_runpath_shadowing(std::string_view solver, const std::filesystem::path& loaded_library, const std::filesystem::path& runpath_library, std::string_view ld_library_path, const PluginIntegrityPolicy& policy)

The solver library actually loaded vs the one the plugin's RUNPATH would pick. Empty runpath_library or equal paths → ok; otherwise finding (typically LD_LIBRARY_PATH or a preloaded library shadowing it).

IntegrityDecision gtopt::check_solver_library_identity(std::string_view solver, const std::vector<LinkedLibraryRecord>* records, const LoadedLibraryIdentity& loaded, bool statically_linked, const VersionPinOverrides& pin_overrides, const PluginIntegrityPolicy& policy)

Parameters
solver
records nullptr when the plugin does not report them.
loaded
statically_linked
pin_overrides
policy

Is the solver library mapped at run time the one the plugin was built against? Unlike the version check it does not trust what the library reports about itself: it compares the GNU build-id (else the SHA-256) recorded at build time with that of the library actually mapped.

  • statically linked → ok "static"; plugin does not report its linked libraries (older gtopt), or the library was not located → ok "unchecked";
  • same build-id (or SHA-256) → ok "verified";
  • the loaded library is not one the plugin was linked against, or its id differs → status "FOREIGN"; the recorded id cannot be compared (loaded library without build-id / unreadable) → "unverified". Both are refused unless $GTOPT_<SOLVER>_ALLOW_UNPINNED is set (pin_overrides.env_allow_unpinned) or the mode is warning; unlike the pin, a plugin built with -DGTOPT_<SOLVER>_ALLOW_UNPINNED=ON (pin_overrides.built_allow_unpinned, ignored here) is NOT exempt.
  • Full-library hash (-DGTOPT_SOLVER_LIB_FULL_HASH=ON): the record carries the SHA-256 of the linked file next to its build-id; the build-id must match AND loaded.sha256 (hash of the mapped file) must equal it → ok "verified, sha256 verified"; another hash → "SHA256 MISMATCH" (same refusal rules), so a fake that copies the build-id note is still caught.

IntegrityDecision gtopt::check_solver_version(std::string_view solver, const SolverVersion& compiled, const SolverVersion& runtime, bool statically_linked, std::string_view library_path, const PluginIntegrityPolicy& policy)

Compare the solver version the plugin was compiled against with the version of the library loaded at runtime.

  • major.minor differ → finding: solver APIs / struct layouts change between minor releases (the HiGHS 1.10 vs 1.16 ABI break);
  • only patch differs → ok, status "patch differs" (patch releases keep the ABI; logged at info level, never refused);
  • versions not reported: ok "static" when the library is linked into the plugin (it cannot differ), ok "unchecked" otherwise (e.g. CBC, which has no runtime version query — the library path is still shown);
  • equal → ok.

IntegrityDecision gtopt::check_solver_version_pin(std::string_view solver, const SolverVersion& pinned, const SolverVersion& runtime, std::string_view library_path, const VersionPinOverrides& overrides, const PluginIntegrityPolicy& policy)

Compare the solver library loaded at runtime with the release gtopt is pinned to (CMake GTOPT_<SOLVER>_PIN_VERSION; another release can end on another optimal vertex of a degenerate LP and change duals/costs).

  • no pin (pinned unknown) → ok, status "" (nothing to check);
  • runtime equal to the pin (major.minor, and patch when the pin has one) → ok "pinned";
  • runtime differs → status "UNPINNED"; runtime version unknown → status "pin unverified". Both are refused when the plugin check mode is error and neither override is set; otherwise a warning that names the reason it was let through.

std::optional<ElasticSolveResult> gtopt::chinneck_filter_solve(const LinearInterface& li, std::span<const StateVarLink> links, double penalty, const SolverOptions& opts, double slack_tol = 1e-6)

Parameters
li The LP to clone (not modified)
links Outgoing state-variable links from the previous phase
penalty Elastic penalty coefficient (smaller than for elastic_filter_solve is fine — IIS uses which slack is non-zero, not by how much it dominates cost)
opts Solver options
slack_tol Tolerance for considering a slack "active" (default 1e-6)
Returns Solved IIS-filtered clone and link-infos, or nullopt on failure.

Chinneck-style elastic IIS filter.

Single-pass deletion-filter approximation of Chinneck's elastic algorithm (2008, Feasibility and Infeasibility in Optimization, §3.5).

Procedure:

  1. Clone the LP and relax every fixed state-variable bound with two penalised slack variables (same as elastic_filter_solve()).
  2. Solve the relaxed clone with penalty. If it is itself infeasible or some other solver error occurs, return nullopt.
  3. Inspect the slack values:
    • links whose sup and sdn are both ≤ slack_tol are NOT contributing to the infeasibility ("non-essential")
    • links with at least one slack > slack_tol form the IIS candidate set
  4. Re-fix the non-essential links to their original trial_value (drop their slack columns out of consideration by zeroing the upper bound on sup/sdn) and re-solve. If the re-solve stays feasible at the same penalty cost, the IIS is confirmed. If it becomes infeasible (one of the supposedly non-essential links was actually essential due to penalty competition), undo the re-fix and fall back to the conservative full-elastic IIS.

The returned ElasticSolveResult carries link_infos whose sup_col / sdn_col are reset to unknown_index for non-essential links, so downstream build_multi_cuts() skips them and emits cuts only on the IIS subset.

ApertureFailureKind gtopt::classify_aperture_failure(int status, double solve_s, double timeout_s) noexcept

Classify an aperture failure. The status code alone cannot tell a time-limit stop apart: CPLEX reports CPX_STAT_ABORT_TIME_LIM through is_abandoned() (status 1) while HiGHS' kTimeLimit and CLP's time-limit stop land in the catch-all status 3, and both codes also cover stops that have nothing to do with time (iteration/objective limits, infeasible-or-unbounded, unscaled infeasibilities). So a status-1/3 stop counts as a timeout only when the measured solve time reached (95 % of) a positive timeout_s.

DroppedTermKind gtopt::classify_dropped_term(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const ElementRef& ref, bool suppressed)

Classify a known element reference that produced no column.

Called only on the silent-zero path (!emitted && element_known, or a planning-mode suppression). Uses the element's own is_active(stage) (via SimulationLP::find_ampl_active), the AMPL registry of this (scenario, stage) and of the earlier stages of the same LP, and the capacity parameters pmax / lmax / tmax_ab+tmax_ba.

int gtopt::classify_error_exit_code(std::string_view error) noexcept

Classify an error string into an exit code.

Returns 2 for input errors (missing file, parse error, invalid JSON), 3 for internal/solver errors.

Examines error for keywords indicating input-related errors vs internal/solver errors.

LineKvlKind gtopt::classify_line_reactance(std::optional<double> reactance, double voltage, double threshold, TinyReactanceMode mode) noexcept

Classify a line's stage reactance for KVL assembly.

Parameters
reactance stage reactance X (nullopt = unset)
voltage stage voltage V (1.0 in per-unit mode)
threshold dc_line_reactance_threshold (≤ 0 disables)
mode tiny_reactance_mode

SolveOutcome gtopt::classify_solve_outcome(const std::expected<int, Error>& result) noexcept

Map a solver resolve() return value to a SolveOutcome.

ErrorCode::SolverError is the documented "soft" error band — every other code is treated as a hard failure. The result type is the same std::expected<int, Error> that PlanningLP::resolve() returns; the int payload is the solve status (unused here).

void gtopt::clear_flat_lp_vectors(FlatLinearProblem& flp)

Clear only the large numeric vectors of a FlatLinearProblem, preserving metadata (ncols, nrows, nnz, names, stats, etc.).

void gtopt::close_producing_col(LinearProblem& lp, ColIndex col)

Close the producing (positive) direction of column col.

void gtopt::close_producing_cols(LinearProblem& lp, const BIndexHolder<ColIndex>& cols)

Close the producing direction of every column in cols.

std::string_view gtopt::codec_name(CompressionCodec codec) noexcept

Return the name of the codec as a string.

template<std::ranges::sized_range R>
ColIndex gtopt::col_index_size(const R& r) noexcept

Build a ColIndex from the size of any sized range.

Template parameters
R Any std::ranges::sized_range.
Parameters
r The range whose size should be interpreted as a column count.
Returns ColIndex{static_cast<Index>(std::ranges::size(r))}.

Centralises the ColIndex{static_cast<Index>(r.size())} pattern so that callers stay in strong-index space. Typical call sites:

if (col < col_index_size(col_sol)) { ... }
for (auto idx : iota_range<ColIndex>(ColIndex{0}, col_index_size(cols)))

auto gtopt::col_scale_cost(double scale) noexcept

Returns a lambda that rescales LP reduced costs to physical units. rc_physical = rc_LP / scale (inverse of primal rescaling).

Usage in add_to_output: out.add_col_cost(cname, "theta", pid, theta_cols, col_scale_cost(scale));

auto gtopt::col_scale_sol(double scale) noexcept

Returns a lambda that rescales LP primal values to physical units. physical_value = LP_value × scale.

Usage in add_to_output: out.add_col_sol(cname, "theta", pid, theta_cols, col_scale_sol(scale));

double gtopt::collect_sum_cols(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const SumElementRef& sum_ref, double base_coeff, SparseRow& row, const LinearProblem& lp, std::vector<UnreachableSumElement>* unreachable = nullptr)

Collect (coefficient, ColIndex) pairs for a SumElementRef.

When sum_ref.all_elements is true, iterates over every element in the collection of the matching type. Otherwise iterates over the explicit ID list. The base_coeff is multiplied into each term's coefficient.

Returns the total offset_shift = Σ_e (coef × offset_e) across all resolved elements that carry a non-zero AMPL offset. The caller folds this onto the row's RHS via the existing param_shift mechanism so shifted-variable encodings (Option C demand) compose correctly under sum(demand(all).load) predicates. When unreachable is non-null, every summed element that contributed no column at this block is appended to it (instead of vanishing silently), so the caller can classify it: error / warn on a scope mismatch or an unknown explicit id, count it as an implicit 0 otherwise.

double gtopt::committed_pmin(const CommitmentLP* cmt, const GeneratorLP& gen, StageUid stage_uid, BlockUid block_uid)

Committed minimum stable output of gen at (stage, block) [MW]: the floor the unit holds while ON, max(Generator.pmin, Commitment.pmin), or Generator.pmin without a commitment (cmt null). Read from the input parameters, never from the generation column's lower bound: with the documented UC pattern Generator.pmin = 0 that bound carries no committed minimum. Unset values read 0. Same value on chronological and block stages.

double gtopt::committed_pmin(const CommitmentLP* cmt, const GeneratorLP& gen, StageUid stage_uid, BlockUid block_uid)

KappaMode gtopt::compiled_default_kappa_mode() noexcept

The compiled default resolved for this build (auto → off under NDEBUG, estimate otherwise).

std::vector<char> gtopt::compress(std::span<const char> data, CompressionCodec codec)

Parameters
data Input data to compress.
codec Compression algorithm (must be available).
Returns Compressed bytes.
Exceptions
std::runtime_error if codec is unavailable or compression fails.

Compress a byte buffer using the specified codec.

CompressedBuffer gtopt::compress_buffer(std::span<const char> data, CompressionCodec codec)

Compress a byte span into a CompressedBuffer./// Compress a byte span into a CompressedBuffer.

CompressedBuffer gtopt::compress_flat_lp(FlatLinearProblem& flp, CompressionCodec codec, FlatLpDedupRegistry* registry = nullptr, const std::string& dedup_key = {})

Serialize the numeric vectors of a FlatLinearProblem into a contiguous buffer, compress it, and clear the source vectors (keeping metadata like ncols/nrows, names, stats, etc.). No-op and returns an empty buffer when codec resolves to none. When registry is non-null the buffer is deduplicated against the registry's base for dedup_key (see FlatLpDedupRegistry).

int gtopt::compute_auto_aperture_chunk_size(int max_apertures_per_phase, int n_active_scenes, int n_physical_cores, double parallel_factor = 2.0) noexcept

Parameters
max_apertures_per_phase Largest A across phases (use the max, not the average — smaller phases will simply under-chunk, which is harmless; larger phases would otherwise over-chunk and grow the queue).
n_active_scenes Number of scenes the SDDP solver will process per iteration (simulation.scene_count() minus inactive scenes).
n_physical_cores Output of gtopt::physical_concurrency() (CPU-quota-aware).
parallel_factor Over-subscription factor matching the work pool's cpu_factor. Default 2.0.
Returns The chunk size to use, in [1, max_apertures_per_phase].

Compute a default aperture_chunk_size from problem dimensions.

Sizes the per-phase aperture chunks so that the resulting task count (N_scenes × ⌈A/K⌉) roughly equals the work pool's target concurrency (parallel_factor × N_cores). The intuition:

  • If N_scenes × A ≤ parallel_factor × N_cores, the pool can run every (scene, aperture) task concurrently — no point in chunking, return 1.
  • If N_scenes × A ≫ parallel_factor × N_cores, the pool is oversubscribed at K=1. Chunking K>1 reduces the queue depth (one task per chunk instead of one per aperture) and gives each chunk warm-start reuse on its inner solves — the update_aperture deltas between successive apertures (column bounds; equality-row RHS under AR inflows / profile elements) keep the dual basis valid, so the second-and-later resolves typically converge in a fraction of a cold barrier.

Closed form:

K_auto = clamp(⌈(N_scenes × A) / (parallel_factor × N_cores)⌉, 1, A)

All inputs are clamped to non-negative; degenerate inputs (any of n_apertures, n_active_scenes, n_physical_cores == 0, or parallel_factor ≤ 0) collapse to 1 — a safe no-chunking default that callers can detect and fall back to the legacy 1-task-per- aperture path.

parallel_factor defaults to 2.0 to match make_sddp_work_pool's default cpu_factor = 2.0 (sddp_pool.hpp): the pool sizes itself at 2 × N_cores workers, so the auto-K target tracks the same over-subscription ratio.

BoundaryGapDiagnostics gtopt::compute_boundary_gap_diagnostics(double upper_bound, double lower_bound, double terminal_future_cost, double alpha_offset, double expected_abs_opex, bool terminal_in_ub) noexcept

Parameters
upper_bound Raw SDDP UB (Σ feasible scenes).
lower_bound Raw SDDP LB.
terminal_future_cost E[Φ'(v_T)] at the forward final states.
alpha_offset Σ_s c̄ restitution folded into the objective.
expected_abs_opex Σ_s |opex_s|.
terminal_in_ub UB already carries E[Φ'] (phi_expectation).

Build the boundary-cut gap diagnostics from the aggregated bounds.

double gtopt::compute_convergence_gap(double upper_bound, double lower_bound) noexcept

Compute relative convergence gap: (UB - LB) / max(1.0, |UB|). Always returns a non-negative value.

LpFingerprint gtopt::compute_lp_fingerprint(const StableVector<SparseCol>& cols, const StableVector<SparseRow>& rows)

Same, from LinearProblem's stable row / column storage.

LpFingerprint gtopt::compute_lp_fingerprint(const std::vector<SparseCol>& cols, const std::vector<SparseRow>& rows)

Parameters
cols Vector of SparseCol (from LinearProblem)
rows Vector of SparseRow (from LinearProblem)

Compute the LP fingerprint from raw LP columns and rows.

std::vector<FlatLinearProblem::RowTypeStatsEntry> gtopt::compute_row_type_stats(std::span<const double> matval, std::span<const FlatLinearProblem::index_t> matind, std::span<const std::string> rownm, std::size_t nrows)

Classify rows by constraint type (the second _-delimited token of the row name, or the whole name when it has no separator) and accumulate per-type count / nnz / min/max |coefficient|, sorted by descending per-type max/min ratio. Pure helper extracted from LinearProblem::flatten() so the classification is unit-testable without building an LP. matind holds the row index of each CSC entry in matval; rownm must have nrows entries.

std::vector<double> gtopt::compute_scene_weights(std::span<const SceneLP> scenes, std::span<const uint8_t> scene_feasible, ProbabilityRescaleMode rescale_mode = ProbabilityRescaleMode::runtime)

Parameters
scenes The scene objects from SimulationLP
scene_feasible Per-scene feasibility flag (0 = infeasible); output size equals scene_feasible.size()
rescale_mode When runtime, normalize weights over feasible scenes to sum 1.0. When build or none, use raw probability weights (no re-normalization).
Returns Weight vector of size scene_feasible.size()

Compute normalised per-scene probability weights.

For each scene: weight = sum of scenario probability_factors if positive, else 1.0. Infeasible scenes (scene_feasible[si]==0) get weight 0. Weights are normalised to sum to 1 across feasible scenes. Falls back to equal weights when no positive probabilities are found.

std::string_view gtopt::context_type_name(const LpContext& context)

Map an LpContext variant to its human-readable type name. Returns "monostate" for context-free entries.

template<typename Collections>
auto gtopt::count_all_elements(Collections&& collections)

Counts the total number of active elements across all collections.

Parameters
collections Tuple of collections to count
Returns Total number of active elements

SolverResourceDescriptor gtopt::cpu_resource_descriptor()

Convenience: a default (CPU) descriptor for backends that export nothing.

bool gtopt::create_exclusive_file(const std::filesystem::path& path) noexcept

Create path as a new, empty regular file with mode 0600. Fails (returns false) when the path already exists — including a dangling symlink — so the following write can never land on a pre-existing file.

std::expected<ArrowTable, std::string> gtopt::csv_read_table(const std::filesystem::path& fpath)

Read an Arrow table from a CSV file.

Configures the CSV reader to use typed columns for Scenario, Stage and Block UIDs. Returns an error string on failure.

std::string gtopt::decanonicalize_json_keys(std::string_view json_text, const NamesRegistry& registry, std::string_view dialect)

Rewrite every canonical object-key in json_text to its alias in dialect using registry. Inverse of canonicalize_json_keys. Keys without a matching (canonical, dialect) entry are left unchanged so a partial dialect coverage degrades gracefully.

dialect empty makes the function a verbatim copy. Mirrors the safety properties of canonicalize_json_keys: only object-key quoted strings are considered.

std::string gtopt::decanonicalize_json_keys(std::string_view json_text, std::string_view dialect)

Convenience overload using the process-wide singleton.

std::optional<std::string> gtopt::decision_variable_scope_restriction(const DecisionVariable& dv)

Describe why dv's LP column is NOT one-per-(scenario, stage, block): "scope '<stage|phase|global>'" for a coarse scope, "single-block selector (block N)" for a block selector; nullopt for a plain per-block variable. Feeds SimulationLP::register_ampl_scoped_element, which lets the user-constraint resolver report an unreachable column instead of silently dropping the term.

std::vector<char> gtopt::decompress(std::span<const char> compressed, size_t original_size, CompressionCodec codec)

Parameters
compressed Compressed data.
original_size Original uncompressed size (must be known).
codec Algorithm used for compression.
Returns Decompressed bytes of exactly original_size.
Exceptions
std::runtime_error if decompression fails or the codec does not produce exactly original_size bytes (corrupt/truncated stream or mismatched metadata — never zero-padded).

Decompress a buffer previously compressed with the same codec.

void gtopt::decompress_flat_lp(FlatLinearProblem& flp, const CompressedBuffer& buf)

Exceptions
std::runtime_error on a corrupt buffer or when buf.original_size disagrees with the flat-LP metadata; flp numeric vectors are left empty in that case.

Decompress a buffer previously created by compress_flat_lp() and restore the numeric vectors of flp. No-op when buf is empty.

double gtopt::default_max_process_swap_mb() noexcept

Process-wide default for WorkPoolConfig::max_process_swap_mb (built-in 2048 MB; 0 = swap gate off).

double gtopt::default_swap_growth_mb() noexcept

Process-wide default for WorkPoolConfig::swap_growth_mb (built-in 64 MB per observation window).

std::string gtopt::describe_kappa_mode()

One line for --version, e.g. kappa mode: off (compiled default, auto) or kappa mode: exact (from $GTOPT_KAPPA_MODE; compiled default: auto=off).

std::string gtopt::describe_plugin_check(PluginCheckMode mode, PluginCheckSource source)

One line describing the effective mode, its source and the compiled default, e.g. plugin check: error (compiled default) or plugin check: warning (from $GTOPT_PLUGIN_CHECK; compiled default: error). Printed by --version and --solvers.

std::string gtopt::describe_solver_library(const SolverLibraryReport& lib)

One-line summary of lib, e.g. runtime 1.16.0, compiled 1.16.0 (match), pin 1.16.0 (pinned), /opt/.../libhighs.so.1.16.0 [build-id 1a2b3c4d5e6f, verified] (the pin part only when the solver is pinned; the identity status when checked).

std::string gtopt::describe_stall_reason(const StallGateSnapshot& s, const StallGateLimits& lim)

Human-readable name of the gate most likely blocking dispatch, in the same priority order as the scheduler's can_dispatch_next(): memory %, free memory, process RSS, VmSwap gate, swap I/O, CPU, then the "tasks not completing" fallbacks.

std::vector<SparseColLabel> gtopt::deserialize_col_labels_meta(std::span<const char> data, std::size_t num_entries, std::vector<std::string>& string_pool)

Inverse of serialize_labels_meta for column labels. Re-materialises strings into string_pool (which MUST be reserved to at least 2 * num_entries before calling, so string_views into pool entries stay valid — push_back must not reallocate).

std::vector<SparseRowLabel> gtopt::deserialize_row_labels_meta(std::span<const char> data, std::size_t num_entries, std::vector<std::string>& string_pool)

Inverse of serialize_labels_meta for row labels.

std::size_t gtopt::detect_islands_and_fix_references(Array<Bus>& buses, const Array<Line>& lines, const PlanningOptionsLP& options)

Detect bus islands and assign a reference bus per island.

Parameters
buses Mutable bus array — reference_theta may be set.
lines Transmission lines (read-only).
options Resolved planning options.
Returns Number of islands detected (0 when Kirchhoff is disabled).

Builds a Union-Find over buses connected by lines that have a non-null reactance (i.e. lines participating in Kirchhoff constraints). For each resulting connected component (island) that lacks a user-specified reference_theta, the first bus in that island is assigned reference_theta = 0.

Self-loop lines (bus_a == bus_b) are silently ignored.

When Kirchhoff is disabled or only one bus exists, this function is a no-op and returns 0.

unsigned gtopt::detected_physical_concurrency() noexcept

True hardware physical-core count (Linux topology probe), never affected by set_cpu_quota_pct(). Use this for diagnostics, log messages, and the SMT-ratio computation. Returns std::thread::hardware_concurrency() on non-Linux or parse failure.

template<typename F>
auto gtopt::dispatch_profile_owner(ProfileOwnerKind kind, F&& f)

Compile-time visitor over the registered owner-kind ⇄ OwnerLP table.

Calls f(std::type_identity<OwnerLP>{}) for the matching kind and returns the result. Used by CapacityProfileLP to fan a single CapacityProfile::owner_kind runtime value out to the typed cols_at / sid / etc. paths above.

Adding a new kind requires:

  1. A new ProfileOwnerKind enumerator
  2. A new CapacityProfileTraits<OwnerLP> specialization
  3. A new case branch here

std::optional<std::vector<double>> gtopt::dive_mip_start(MipStartContext& ctx, DiveSummary& summary)

Returns the dense raw start (verified feasible when summary.verified), or std::nullopt when the relaxation has no primal.

Run the full dive → verify → repair stage on a solved, integrality-relaxed LP relaxation.

Uid gtopt::dlr_default_span_uid(Uid line_uid, int position) noexcept

Default uid of the position-th (1-based) span of line line_uid.

double gtopt::dlr_span_rating_mw(const ieee738::ConductorParams& conductor, double conductor_temperature, const ieee738::SpanWeather& weather, double voltage_kv, double v_pu, double power_factor, int subconductors, double safety_factor) noexcept

MW rating of one span at one conductor temperature (IEEE 738 ampacity converted with ieee738::ampacity_to_mw).

std::string_view gtopt::dropped_term_kind_name(DroppedTermKind kind) noexcept

Short label of a DroppedTermKind (log summaries).

DualInfeasibility gtopt::dual_infeasibility(std::span<const double> col_low, std::span<const double> col_upp, std::span<const double> reduced_cost, std::span<const double> col_sol, std::span<const double> row_low, std::span<const double> row_upp, std::span<const double> row_dual, double inf) noexcept

std::optional<double> gtopt::dual_shared_bound_correction(std::span<const double> rep_reduced_costs, std::span<const double> rep_low, std::span<const double> rep_upp, std::span<const double> ap_low, std::span<const double> ap_upp) noexcept

Parameters
rep_reduced_costs Representative's physical reduced costs (materialized get_col_cost() view, post-solve).
rep_low Representative's physical column lower bounds at its solve (materialized get_col_low()).
rep_upp Representative's physical column upper bounds at its solve (materialized get_col_upp()).
ap_low Aperture a's physical column lower bounds (same view read after update_aperture rewrote the clone).
ap_upp Aperture a's physical column upper bounds (same view read after update_aperture rewrote the clone).
Returns

The correction corr_a, or std::nullopt when it cannot be computed soundly:

  • span sizes disagree,
  • a non-zero reduced cost meets a non-finite or ±sentinel-magnitude (≥ 1e29) bound delta — a bound became (un)bounded between the representative and the aperture. Equal bounds contribute nothing (skipped before any subtraction, so equal infinities are safe); zero reduced costs annihilate their column regardless of the delta.

Per-aperture intercept correction for the dual-shared cut synthesis (Lemma AP2, docs/formulation/sddp-cut-validity.md §6).

Aperture LPs of one (scene, phase) share (A, b, c) and differ only in column bounds, so they share one dual feasible set {y, λ ≥ 0, μ ≥ 0 : Aᵀy + λ − μ = c} — bound-independent. Splitting the representative's vertex reduced costs d = λ − μ (λ = d⁺, μ = d⁻ by complementarity), weak duality on aperture a's LP gives

Q_a(x) ≥ z* + corr_a + Σ_i rc_i (x_i − v̂_i), corr_a = Σ_j max(d_j, 0)·(l_j^a − l_j^rep)

  • Σ_j min(d_j, 0)·(u_j^a − u_j^rep)

over the changed columns — the representative cut's slope is shared verbatim and only the intercept moves by corr_a.

Units: d_j from the representative clone's get_col_cost()[j] (physical view, rc_LP × scale_objective / col_scale) and bound deltas from get_col_low() / get_col_upp() (physical, raw × col_scale) — the col_scale cancels in the product and the scale_objective folding matches z* = get_obj_value().

std::expected<void, Error> gtopt::dump_integer_solution(const LinearInterface& li, const std::string& path)

Returns Empty on success, or a FileIOError if the file cannot be written.

Dump the live MIP solution's COMPLETE RAW column values to path — one <index> <value> line per column, integer AND continuous — preceded by ncols / nint headers (ncols is a structural sanity check on replay; nint is informational). Call AFTER a successful MIP solve (integrality intact, before any dual-recovery relaxation). A later run replays the dump as a MIP start via mip_start.from_file (FileMipStart): both runs build the identical deterministic flat LP, so raw column indices line up 1:1, and the replayed start is the complete, CONSISTENT solution — the exact optimum round-trips through a strict backend feasibility check (CPLEX CHECKFEAS) instead of being rejected for carrying relaxation continuous values under optimal integers.

std::string gtopt::dump_json_schema(std::string_view type_name = {})

Render the JSON Schema of a known top-level gtopt input type.

Parameters
type_name Selects the root type. An empty name yields the full Planning scheme; "options" selects PlanningOptions; any other contract type is selected by snake_case or C++ name (case-insensitive), e.g. "gas_pipe".
Returns The JSON Schema as a string. For an UNKNOWN type_name, an error listing the known names is printed to stderr and an empty string is returned (mirrors the --list-dialects unknown-filter behaviour).

std::vector<std::size_t> gtopt::duration_groups(std::span<const double> cells, double period, bool point)

Grouping used by the duration logic of a stage. Block stages with uniform durations keep the legacy accumulated grouping (identical LPs for existing cases; equal to cell_groups whenever the duration divides P); point stages and variable-duration block stages use the midpoint-snapped cell groups.

std::pair<KappaMode, KappaModeSource> gtopt::effective_default_kappa_mode()

Default for an unset solver_options.kappa_mode, and where it came from: $GTOPT_KAPPA_MODE, else the compiled default. Reads the environment on every call (cheap; lets tests change it).

double gtopt::effective_scale_alpha(const PlanningLP& planning_lp, double option_scale_alpha, double cut_max_coeff)

Compute the effective scale_alpha: if the option is > 0 use it, otherwise auto-compute as max(scale_objective, 10^ceil(log10(cut_max_coeff))) — the log10 round-up SDDP uses for its α estimate. cut_max_coeff is the column-averaged max boundary-cut coefficient (see boundary_cut_max_avg_coeff) and is required: α only exists when boundary cuts are installed, so this is never called without a cut to scale against. A non-positive cut_max_coeff (unreadable / empty CSV) falls back to the floor max(1, scale_objective).

std::optional<ElasticSolveResult> gtopt::elastic_filter_solve(const LinearInterface& li, std::span<const StateVarLink> links, double penalty, const SolverOptions& opts, const ElasticCostPolicy& cost_policy = {}, std::span<const RowIndex> elastic_fcut_rows = {})

Parameters
li The LP to clone (not modified)
links Outgoing state-variable links from the previous phase. Must not contain the α column — collect_state_variable_links skips α by class name.
penalty Elastic penalty coefficient for slack variables
opts Solver options for the clone solve
cost_policy Slack pricing model (default: legacy penalty × dep_scale_phys; the state_repair mode passes plp_unit_rc_tilt, farkas_recursive passes unit).
elastic_fcut_rows Feasibility-cut rows already installed in li to relax with a +z_r slack in the clone (a_rᵀx + z_r ≥ b_r, unit cost — the §17.2 + I z term). Default empty: no cut row is touched (legacy behaviour, byte-identical for every existing mode). The added slacks are reported in ElasticSolveResult::fcut_infos.
Returns Solved elastic clone and per-link slack info, or nullopt if no columns were fixed or the clone solve failed.

Clone the LP, apply elastic relaxation on fixed state-variable columns, and solve the clone. The original LP is never modified.

α is intentionally outside the state-variable pool this filter operates on: callers (via collect_state_variable_links) already exclude α from links, so α never receives slack variables and its bounds are left untouched in the clone. The Chinneck Phase-1 objective zeroing applies to every column including α AND to the LP's objective CONSTANT (the solver-native offset from add_obj_constant — demand-fail Option-A baseline, boundary-cut c̄, …), so clone.get_obj_value() is the pure slack activation. With α kept at whatever bounds the source LP has (pinned at 0 by bootstrap or freed by a prior optimality cut), the clone's solve measures the true feasibility gap on the forward state variables without α absorbing it.

std::optional<bool> gtopt::element_ref_active(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const ElementRef& ref)

is_active(stage) of the element ref names; nullopt when the reference does not resolve or the class has no activity probe.

template<typename Map, typename BHolder>
auto gtopt::emplace_bholder(const ScenarioLP& scenario, const StageLP& stage, Map& map, BHolder&& holder, bool empty_insert = false)

template<typename Map, typename Value = Map::value_type>
auto gtopt::emplace_value(const ScenarioLP& scenario, const StageLP& stage, Map& map, Value&& value)

auto gtopt::enum_entries(ApertureChunkMode) noexcept

auto gtopt::enum_entries(ApertureSolveMode) noexcept

auto gtopt::enum_entries(BarrierSolver) noexcept

ADL customization point for NamedEnum concept.

auto gtopt::enum_entries(BasisCrossMode) noexcept

auto gtopt::enum_entries(BoundaryCutsMode) noexcept

auto gtopt::enum_entries(BuildMode) noexcept

auto gtopt::enum_entries(Carrier) noexcept

auto gtopt::enum_entries(CogenMode) noexcept

auto gtopt::enum_entries(ConstraintMode) noexcept

auto gtopt::enum_entries(ConvergenceMode) noexcept

auto gtopt::enum_entries(CrossoverMode) noexcept

ADL customization point for NamedEnum concept.

auto gtopt::enum_entries(CutDrainMode) noexcept

auto gtopt::enum_entries(CutSharingMode) noexcept

auto gtopt::enum_entries(CutType) noexcept

auto gtopt::enum_entries(DataFormat) noexcept

auto gtopt::enum_entries(ElasticFilterMode) noexcept

auto gtopt::enum_entries(FlowRightMode) noexcept

auto gtopt::enum_entries(GasCompressorDrive) noexcept

auto gtopt::enum_entries(GasLinearization) noexcept

auto gtopt::enum_entries(GasWeymouthMode) noexcept

auto gtopt::enum_entries(HotStartMode) noexcept

auto gtopt::enum_entries(IntegerCutsMode) noexcept

auto gtopt::enum_entries(KappaMode) noexcept

ADL customization point for NamedEnum concept.

auto gtopt::enum_entries(KirchhoffMode) noexcept

auto gtopt::enum_entries(LineDirectionMode) noexcept

auto gtopt::enum_entries(LineDlrLimitMode) noexcept

auto gtopt::enum_entries(LineDlrSolarMode) noexcept

auto gtopt::enum_entries(LineDlrSpanMode) noexcept

auto gtopt::enum_entries(LineFlowDirection) noexcept

auto gtopt::enum_entries(LineLossesMode) noexcept

auto gtopt::enum_entries(LinePwlLayout) noexcept

auto gtopt::enum_entries(LossAllocationMode) noexcept

auto gtopt::enum_entries(LowMemoryMode) noexcept

auto gtopt::enum_entries(LPAlgo) noexcept

ADL customization point for NamedEnum concept.

auto gtopt::enum_entries(LpScalesLevel) noexcept

auto gtopt::enum_entries(MethodType) noexcept

auto gtopt::enum_entries(MipStartEffort) noexcept

ADL customization point for NamedEnum concept.

auto gtopt::enum_entries(MissingCutVarMode) noexcept

auto gtopt::enum_entries(MonthType) noexcept

auto gtopt::enum_entries(NetworkModel) noexcept

auto gtopt::enum_entries(OutputFlags) noexcept

auto gtopt::enum_entries(PrevStageLink) noexcept

auto gtopt::enum_entries(PricingMode) noexcept

auto gtopt::enum_entries(ProfileOwnerKind kind) noexcept

auto gtopt::enum_entries(RecoveryMode) noexcept

auto gtopt::enum_entries(RiskMeasure) noexcept

auto gtopt::enum_entries(RiskRankBy) noexcept

auto gtopt::enum_entries(RiskTail) noexcept

auto gtopt::enum_entries(SolveMode) noexcept

auto gtopt::enum_entries(SolverLogMode) noexcept

ADL customization point for NamedEnum concept.

auto gtopt::enum_entries(SolverScaling) noexcept

ADL customization point for NamedEnum concept.

auto gtopt::enum_entries(StartsScope) noexcept

auto gtopt::enum_entries(TinyReactanceMode) noexcept

template<typename E, std::size_t N>
std::optional<E> gtopt::enum_from_name(std::span<const EnumEntry<E>, N> entries, std::string_view name) noexcept

Look up an enumerator by name (span overload).

Template parameters
E Enum type.
N Table size (deduced from the span extent).
Parameters
entries Compile-time table of name-value pairs.
name Name to search for (ASCII case-insensitive).
Returns The matching enumerator, or std::nullopt if not found.

The comparison is ASCII case-insensitive so CLI / JSON / config callers can accept "january", "January", "JANUARY" interchangeably. Every entry in the project's enum tables is lowercase ASCII, so no locale is involved.

template<NamedEnum E>
std::optional<E> gtopt::enum_from_name(std::string_view name) noexcept

Look up a NamedEnum value by name (ADL-based).

Template parameters
E A type satisfying the NamedEnum concept.
Parameters
name Name to search for (ASCII case-insensitive).
Returns The matching enumerator, or std::nullopt if not found.

Uses the ADL enum_entries(E{}) customization point to obtain the lookup table, then delegates to the span-based overload.

template<NamedEnum E>
std::string_view gtopt::enum_name(E value) noexcept

Return the canonical name of a NamedEnum value (ADL-based).

Parameters
value The enumerator to look up.
Returns The name string, or "unknown" for out-of-range values.

Uses the ADL enum_entries(value) customization point to obtain the lookup table, then delegates to the span-based overload.

template<typename E, std::size_t N>
std::string_view gtopt::enum_name(std::span<const EnumEntry<E>, N> entries, E value) noexcept

Return the canonical name of an enumerator (span overload).

Template parameters
E Enum type.
N Table size (deduced from the span extent).
Parameters
entries Compile-time table of name-value pairs.
value The enumerator to look up.
Returns The name string, or "unknown" for out-of-range values.

template<typename IndexType = std::size_t, std::ranges::range R, std::ranges::range... Rs>
auto gtopt::enumerate(R&& range, Rs && ... ranges)

template<typename IndexType = size_t, typename Range>
auto gtopt::enumerate_active(const Range& range) noexcept

template<typename IndexType = size_t, std::ranges::range Range, typename Op>
auto gtopt::enumerate_if(Range&& range, Op&& op)

bool gtopt::env_solver_must_fail(std::string_view solver_name, const std::vector<std::string>& load_errors, bool fallback_on_refused)

Decide what an unavailable GTOPT_SOLVER=<solver_name> does: true (fail, like an explicit --solver) when its plugin was refused by an integrity check (a load error for it carries k_plugin_refused_marker) and fallback_on_refused is false; false (warn and fall back to the automatic choice) when the solver simply has no plugin, its plugin failed for another reason, or the override is set.

double gtopt::equilibrate_row_in_place(std::span<double> elements, double& rowlb, double& rowub, double infinity) noexcept

Parameters
elements Coefficients of the row (mutated in place).
rowlb Lower bound (mutated in place unless ±infinity).
rowub Upper bound (mutated in place unless ±infinity).
infinity Solver infinity sentinel — bounds matching ±infinity are left untouched.
Returns The divisor applied: max|coeff| before normalisation, or 1.0 for empty/zero rows. Callers compose this with any pre-existing row scale and store it via LinearInterface::set_row_scale so dual recovery (dual_physical = dual_LP × row_scale) stays correct.

Normalise a single row in place so max|coeff| == 1.

Mirrors the per-row loop body of apply_row_max_equilibration in linear_problem.cpp, intended for both bulk and one-row callers. Safe on empty rows and all-zero rows (no-op, returns 1.0).

double gtopt::equilibrate_row_ruiz_in_place(std::span<const int> columns, std::span<double> elements, std::span<const double> col_scales, double& rowlb, double& rowub, double infinity) noexcept

Parameters
columns Column indices for the row's non-zeros.
elements Coefficients; mutated in place.
col_scales Per-column scale vector from the initial build (LinearInterface::get_col_scales()). Indices outside its range are treated as scale 1.0.
rowlb Mutated in place unless ±infinity.
rowub Mutated in place unless ±infinity.
infinity Solver infinity sentinel.
Returns Combined divisor: the row-max after column scaling.

One-shot Ruiz-style scaling for a single row against an already- converged column-scale profile.

Applies elements[k] *= col_scales[columns[k]] first (folding the equilibrated column factors into the new row) and then calls equilibrate_row_in_place for the row-max normalisation. Intended for user-space cuts that arrive in physical units (e.g. boundary cuts loaded from CSV). The accumulated Ruiz col_scales are frozen after the initial build — we do not re-iterate, just bring the new row onto the same footing.

Real gtopt::evaluate_bound_rule(const RightBoundRule& rule, Real volume) noexcept

Evaluate the piecewise-linear bound function.

Parameters
rule The bound rule with segments, cap, and floor
volume Current reservoir volume [hm³]
Returns The computed bound value (clamped)

Computes: result = constant_i + slope_i * volume for the active segment, then clamps to [floor, cap].

template<typename ColSol, typename RowDual>
CvarSolution gtopt::evaluate_cvar(const CvarLayout& layout, const ColSol& col_sol, const RowDual& row_dual)

Evaluate the construct on a solved LP. col_sol and row_dual are indexable by Index (a std::span<const double>, a ScaledView, …): physical primal and physical (cost-factor-folded) duals. An empty row_dual (duals unavailable) leaves μ_s = 0, so π_s = (1 − λ) p_s.

Real gtopt::evaluate_production_factor(const std::vector<ProductionFactorSegment>& segments, Real volume) noexcept

Evaluate the piecewise-linear concave production factor function.

Parameters
segments The piecewise-linear segments
volume Current reservoir volume [hm³]
Returns Efficiency value (non-negative)

Implements the PLP FRendimientos function (plp-frendim.f):

result = min over all segments of
         { constant_i + slope_i × (volume − volume_breakpoint_i) }

Here constant_i is the production factor at breakpoint_i (point-slope form). This is the concave-envelope minimum, matching the Fortran:

f(V) = min_i ( constant_i + slope_i * (V - volume_i) )

Difference from seepage: ReservoirSeepageSegment.constant is the y-intercept (value at V = 0), while ProductionFactorSegment.constant is the value at the breakpoint. ReservoirSeepage uses range-based segment selection; production factor uses concave-envelope minimum.

Returns at least 0.0 (production factor cannot be negative).

Real gtopt::evaluate_seepage(const std::vector<ReservoirSeepageSegment>& segments, Real volume) noexcept

Evaluate the piecewise-linear seepage function.

Parameters
segments The piecewise-linear segments (sorted by volume breakpoint)
volume Current reservoir volume [hm³]
Returns ReservoirSeepage rate (non-negative) [m³/s]

Implements the PLP seepage model (matches Fortran FFiltracionesi):

Find the segment i where volume_i ≤ volume < volume_{i+1},
then compute:  result = constant_i + slope_i × volume

Here constant_i is the y-intercept at V = 0 for segment i's linear equation, matching the PLP file format (plpfilemb.dat Constante field).

Returns at least 0.0 (seepage rate cannot be negative).

std::filesystem::path gtopt::executable_directory()

Directory holding the running executable (/proc/self/exe), or an empty path when it cannot be determined.

std::optional<TimeWindow> gtopt::expr_finest_time_window(const ConstraintExpr& expr) noexcept

std::vector<CapacityCut> gtopt::extract_capacity_cuts(const SimulationLP& sim, std::span<const StoredCut> cuts, PhaseIndex phase_index = PhaseIndex { 0})

Parameters
sim The live simulation whose registries resolve the stored column indices.
cuts Stored cuts, e.g. SDDPMethod::stored_cuts().
phase_index Phase whose α the extracted cuts bound (default: phase 0 — the investment-master FCF).
Returns One CapacityCut per matching stored optimality cut, in input order (cuts whose coefficients contain a column that no registry entry resolves are skipped with a warning — they belong to a different LP universe).

Project the stored optimality cuts installed on phase_index onto capacity state-variable coordinates (capainst / capacost).

Coefficients are resolved by column index against the originating (scene, phase) state-variable registry — the same resolution the oracle harness uses — so the caller must pass the live SimulationLP of the run that produced cuts. α coefficients (class "Sddp", every varphi_s under multicut) are skipped; feasibility cuts are ignored (they carry no cost-to-go bound).

template<typename ElementLP, typename ScenarioT, typename StageT>
void gtopt::fail_lp(const ElementLP& element, const ScenarioT& scenario, const StageT& stage, LpFailure failure)

Throw an LpBuildError for element at (scenario, stage).

The one way an add_to_lp reports a failure (see the file header).

template<typename T, typename Vector>
std::size_t gtopt::field_sched_dynamic_bytes(const FieldSched<T, Vector>& fs) noexcept

template<typename T, typename Vector>
std::size_t gtopt::field_sched_dynamic_bytes(const std::optional<FieldSched<T, Vector>>& opt_fs) noexcept

const RightBoundSegment* gtopt::find_active_bound_segment(const std::vector<RightBoundSegment>& segments, Real volume) noexcept

Find the active segment for a given reservoir volume.

Returns a pointer to the last segment whose volume breakpoint is <= volume (range selection). Returns the first segment when volume is below all breakpoints.

const ReservoirDischargeLimitSegment* gtopt::find_active_rdl_segment(const std::vector<ReservoirDischargeLimitSegment>& segments, Real volume) noexcept

Find the active segment for a given reservoir volume.

Returns a pointer to the last segment whose volume breakpoint is ≤ volume.

Precondition: segments must be non-empty and sorted ascending by volume.

const ReservoirSeepageSegment* gtopt::find_active_segment(const std::vector<ReservoirSeepageSegment>& segments, Real volume) noexcept

Find the active segment for a given reservoir volume.

Parameters
segments The piecewise-linear segments (sorted by volume breakpoint)
volume Current reservoir volume [hm³]
Returns Pointer to the active ReservoirSeepageSegment (never null)

Returns a pointer to the last segment whose volume breakpoint is ≤ volume (range selection, matching PLP Fortran FFiltracionesi). Returns the first segment when volume is below all breakpoints.

Precondition: segments must be non-empty and sorted in ascending order by volume breakpoint. Results are undefined if this is violated.

const StateVariable* gtopt::find_alpha_state_var(const SimulationLP& sim, SceneIndex scene_index, PhaseIndex phase_index, SceneIndex source_scene, SystemKind kind = SystemKind::forward) noexcept

Multicut overload: look up the α column dedicated to source_scene within the (scene_index, phase_index) cell. Under CutSharingMode::multicut each scene-LP carries N α columns (varphi_0..N-1), keyed by uid = sddp_alpha_uid + source_scene; a scenario-s backward cut is installed on varphi_s in EVERY destination scene-LP (never the destination's own α). For the single-α modes the only registered column is source_scene == scene_index (uid offset 0), so passing source_scene = scene_index reproduces the legacy lookup.

const StateVariable* gtopt::find_alpha_state_var(const SimulationLP& sim, SceneIndex scene_index, PhaseIndex phase_index, SystemKind kind = SystemKind::forward) noexcept

Parameters
sim SimulationLP holding the state-variable registry.
scene_index Scene of the (scene, phase) cell.
phase_index Phase of the (scene, phase) cell.
kind Which registry to look in — forward (default) for the regular system's α, aperture for the backward-pass aperture system's α (registered in parallel).

Look up the alpha (future-cost) state variable registered by SDDPMethod::initialize_alpha_variables for the given (scene, phase). Returns nullptr for any phase that has not yet been initialised.

Callers should read the alpha column index freshly via svar->col() and the forward-pass trial value via svar->col_sol(), which is populated by capture_state_variable_values after every successful solve. This replaces the former PhaseStateInfo::alpha_col cache, which could become stale on low_memory reconstruct/clone paths.

std::filesystem::path gtopt::find_config_file()

Find the .gtopt.conf file following the standard search order.

Returns Path to the config file, or empty path if none found.
  1. $GTOPT_CONFIG (if set and file exists)
  2. ~/.gtopt.conf (home directory)

The current working directory is deliberately NOT searched: a .gtopt.conf shipped inside a case bundle (or an uploaded archive) must not silently change how gtopt runs. Use gtopt --config FILE or $GTOPT_CONFIG to opt in to a project-local file.

std::vector<ExpansionCandidate> gtopt::find_expansion_candidates(const Planning& planning)

Discover the expansion candidates in planning — every generator / demand element carrying a positive expcap · expmod (the same gate CapacityObjectBase::add_to_lp uses to publish capainst). The expmod schedule is read at its scalar / first-stage value; the master treats the build as a single here-and-now decision (v1).

std::optional<LoadedObject> gtopt::find_loaded_object(const void* address)

Find the loaded object (executable or shared library) whose PT_LOAD segments contain address. std::nullopt if none does.

std::optional<std::filesystem::path> gtopt::find_names_file()

Resolve the override file the registry singleton would load from: $GTOPT_NAMING_DIALECTS_FILE when set and existing, else nullopt (the compiled-in dictionary is used). No other path is probed.

const CommitmentLP* gtopt::find_noload_fuel_commitment(const SystemContext& sc, const GeneratorLP& gen)

The CommitmentLP of gen that carries a no-load fuel burn (Commitment.noload_fuel > 0), or nullptr. CommitmentLP is built before FuelLP / EmissionSourceLP, so its status columns exist when they collect fuel-burn legs.

template<typename Holder>
const auto& gtopt::find_or_empty_inner(const Holder& holder, const ScenarioLP& scenario, const StageLP& stage) noexcept

STBIndexHolder<X>::at({s,t}) throws on missing key. LP-element classes that follow the conditional-insert pattern (only insert the outer (s, t) key when the inner per-block map is non-empty — see LineLP::add_to_lp, JunctionLP::add_to_lp, WaterwayLP::add_to_lp) need a graceful fallback on the read side: callers must see an empty inner map instead of a thrown exception when the level / stage / scenario in question didn't populate the holder.

Returns a reference to a per-instantiation static empty BIndexHolder<Inner> when the (scenario, stage) outer key is missing. One static instance per Inner type.

Generic over any STB-style holder (flat_map<tuple<ScenarioUid, StageUid>, BIndexHolder<Inner>>); used today by LineLP's flow/loss/capacity accessors and by JunctionLP::drain_cols_at / WaterwayLP::flow_cols_at. Co-located here with the STBIndexHolder aliases so all the LP element classes can share one definition.

template<typename ColNameMatch>
std::optional<ColIndex> gtopt::find_phase_state_col(const SimulationLP& sim, SceneIndex scene_index, PhaseIndex phase_index, std::string_view class_name, Uid uid, ColNameMatch&& col_match)

Returns the column, or nullopt when no state variable matches.

Resolve the PHASE-STATE column of a state variable on a (scene, phase) cell: among the registered state variables with class_name, uid and a column name accepted by col_match, the one of the phase's LAST stage.

A phase spanning several stages registers one efin state variable per stage for the same element (same class / uid / column name); only the last stage's column is the phase state that SDDP links to the next phase, that Benders cuts are written on, and that a terminal FCF prices. Taking the first registry match instead (the map is ordered by stage) silently binds cut coefficients to the FIRST stage's end-volume. For single-stage phases the result is the unique match.

std::optional<ReservoirRefCache> gtopt::find_reservoir_ref_cache(const ReservoirLP& rsv, const ScenarioLP& scenario, const StageLP& stage)

Non-throwing make_reservoir_ref_cache: nullopt when the reservoir has no eini / efin column for (scenario, stage) — i.e. it is inactive in the stage. Consumers then omit the volume-dependent term and their update_lp finds no cached state (no-op). See active_ref.hpp.

std::optional<std::string> gtopt::find_set_option(const std::vector<std::string>& set_options, std::string_view key)

Value of the last --set <key>=<value> entry for key.

Only exact top-level keys match (e.g. "log_directory"). A literal null value is treated as "not set", mirroring apply_set_options, where a JSON null overlay leaves the option untouched.

const StateVariable* gtopt::find_source_alpha_state_var(const SimulationLP& sim, const SDDPOptions& options, SceneIndex scene_index, PhaseIndex src_phase_index) noexcept

Resolve THE α column a scene-S backward/aperture cut must target on (scene_index, src_phase_index) under the configured cut-sharing mode — the single mode-dispatch shared by the pure-Benders backward pass and both aperture backward variants (a fourth cut-sharing mode extends the routing here, in exactly one place):

  • markov: the Markov-STATE column varphi_{m(S)} (uid = sddp_alpha_uid + m(S) — the state index rides the multicut overload's uid-offset scheme; docs/formulation/sddp-markov.md §2/§6).
  • multicut: scene S's OWN column varphi_S (uid = sddp_alpha_uid + S; PLP plp-agrespd.f:94 parity).
  • single-α modes: the legacy offset-0 lookup.

Does NOT handle the user-overridable FCF (use_user_alpha) — the one call site that supports it (backward_pass_single_phase) dispatches to find_user_alpha_state_var BEFORE falling back to this resolution. Returns nullptr when the cell has no registered α (mirrors find_alpha_state_var).

std::string gtopt::find_trusted_executable(std::string_view name)

Locate the executable name (a bare file name, no '/').

Search order: the directory of the running executable, then the absolute, non-world-writable entries of $PATH. Only regular files the user may execute are returned. Returns an empty string when the tool is not found or name contains a path separator.

const CommitmentLP* gtopt::find_unit_commitment(const SystemContext& sc, ElementIndex<GeneratorLP> gen_index, const StageLP& stage)

The Commitment of generator gen_index active at stage, or nullptr.

const CommitmentLP* gtopt::find_unit_commitment(const SystemContext& sc, ElementIndex<GeneratorLP> gen_index, const StageLP& stage)

std::optional<std::filesystem::path> gtopt::find_units_file()

Resolve the override file the registry singleton would load from: $GTOPT_UNIT_DIALECTS_FILE when set and existing, else nullopt (the compiled-in dictionary is used). No other path is probed.

const StateVariable* gtopt::find_user_alpha_state_var(const SimulationLP& sim, SceneIndex scene_index, PhaseIndex phase_index, Uid user_alpha_uid, SystemKind kind = SystemKind::forward) noexcept

Look up the USER-authored α (future-cost) state variable for the dynamic AmplFutureCost recourse (piece 5 step 2c). Unlike find_alpha_state_var (which is keyed on the built-in sddp_alpha_lp_class), this resolves the user's global state/link DecisionVariable registered under DecisionVariableLP::StateClassName ("UserStateVar") with key.uid == user_alpha_uid. Returns nullptr when no such state variable exists on (scene_index, phase_index, kind). A separate function — NOT an overload — because the built-in overloads are class-keyed; keeping the intent explicit avoids ambiguity at the call sites that must dispatch on has_active_use_user_alpha.

std::optional<double> gtopt::finite_kappa(double kappa) noexcept

A backend kappa value as a real condition number: nullopt for a solver infinity sentinel, +/-inf, NaN or a negative value.

BlockIndex gtopt::first_block_index() noexcept

First block index.

PhaseIndex gtopt::first_phase_index() noexcept

First phase index — the root of the planning horizon.

PhaseStageIndex gtopt::first_phase_stage_index() noexcept

First stage of a phase.

ScenarioIndex gtopt::first_scenario_index() noexcept

First scenario index.

SceneIndex gtopt::first_scene_index() noexcept

First scene index — the canonical root scene used when boundary cuts and column-name maps are built scene-independently.

SceneScenarioIndex gtopt::first_scene_scenario_index() noexcept

First scenario of a scene.

StageIndex gtopt::first_stage_index() noexcept

First stage index — the root of the planning horizon.

bool gtopt::first_time_key(std::string key)

Process-wide one-shot latch keyed by string: true only for the first call (from any thread) that presents key. A single registry shared by every caller (non-template inline function → one static instance).

void gtopt::flush_default_logger_best_effort() noexcept

Best-effort flush of spdlog's default logger.

Wraps spdlog::default_logger()->flush() in try/catch + noexcept so it can be called immediately before std::abort(), std::terminate(), or a fatal return without risking an exception inside a noexcept frame or a terminate handler. Silently swallows any failure — at the call sites it's the last thing we do before tearing the process down.

std::string gtopt::format_fcut_cut_lines(std::span<const StateVarLink> links, std::span<const SparseRow> cuts)

Format the cut: / rhs: lines of one cut-emission record.

One cut: line per coefficient of each row in cuts, resolved against links by source_col to recover the element identity (Class:uid[:name] var); coefficients on columns with no matching link fall back to the bare column index. Each row closes with one rhs: <sense> <value> line — >=-rows report lowb, <=-rows (multi_cut can emit both senses) report uppb. Values are printed with {:.17g} so the log round-trips the installed doubles exactly, like PLP's cf:/rhsi: lines in plpfact.log.

std::string gtopt::format_lp_build_error(const LpBuildErrorInfo& info)

One-line, human-readable rendering of an LpBuildErrorInfo:

LP build error in Generator uid=3 'g3' (scenario=1, stage=2, block=4): field 'capacity' = unset, expected capacity or expansion: <detail>

FormatSI gtopt::format_si(double v) noexcept

std::string gtopt::format_throttle_summary(const ThrottleCounts& c)

Compact label=count list of the gates that fired (zero counters omitted), e.g. "cpu=12 swap_io=3"; empty when none fired.

std::string gtopt::format_version_string(std::string_view version, std::string_view git_revision)

Human-readable version of a build: <version> (<git_revision>).

  • git_revision empty or "unknown" (built outside a git checkout, e.g. from a source tarball) -> <version> alone.
  • git_revision == "v" + version (a clean build of exactly the release tag) -> <version> alone.
  • anything else -> both, e.g. 1.1.0 (v1.1.0-20-g5a4fd2ef8), 1.1.0 (v1.1.0-dirty), or 1.2.0-dev (v1.1.0-23-gabc) when the last tag does not match the version (a development build).

bool gtopt::forward_basis_needed(BasisCrossMode mode) noexcept

True when mode captures the forward solve's basis for later reuse.

template<NamedEnum E>
std::optional<E> gtopt::gas_enum_or(const OptName& name, E fallback) noexcept

Parses an optional selector: fallback when unset, the enumerator when the name is known, std::nullopt for an unknown name.

std::expected<GasSlpStats, Error> gtopt::gas_slp_refine(SystemLP& system, const SolverOptions& solver_options = {})

Run the gas SLP on an already-solved system (no-op without linearised pipes or with slp_iterations ≤ 0). Returns the re-solve's error when a re-solve fails.

void gtopt::gate_reserve_provisions_by_status(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, LinearProblem& lp, ElementIndex<GeneratorLP> gen_index, const BIndexHolder<ColIndex>& status_cols, const BIndexHolder<ColIndex>& generation_cols, std::optional<ColIndex> gen_capacity_col, const std::function<double(BlockUid, double)>& committed_floor)

Gate the online reserve headroom of every ReserveProvision of generator gen_index with the unit's commitment status u (per block in status_cols). Called by CommitmentLP (chronological and block formulations alike), which runs after ReserveProvisionLP and so finds the rows built with the generator's plain bounds:

  • up: g + r_up ≤ Pmax → g + r_up − Pmax·u ≤ 0 (an expandable generator keeps its capacity row and gets a u-gated copy commit_up_provision);
  • down: g − r_dn ≥ lowb → g − r_dn − floor·u ≥ 0 with floor = committed_floor(buid, lowb) (the committed minimum);
  • offline (cold) up reserve: r_up ≤ urmax·(1 − u);
  • PLEXOS Min Provision: the urmin / drmin column floors become r − rmin·u ≥ 0.

std::vector<std::pair<ColIndex, double>> gtopt::generator_fuel_burn_legs(const GeneratorLP& gen, const CommitmentLP* cmt, const ScenarioLP& scenario, const StageLP& stage, BlockUid buid)

Every fuel-burn leg of gen in block buid [fuel-unit / h per unit of column]: GeneratorLP::fuel_burn_legs (dispatch column and heat-rate slack columns) plus the no-load burn noload_fuel · u of cmt when non-null. Shared by FuelLP offtake rows and fuel-basis EmissionSourceLP rows so both see the same fuel.

std::vector<std::pair<ColIndex, double>> gtopt::generator_fuel_burn_legs(const GeneratorLP& gen, const CommitmentLP* cmt, const ScenarioLP& scenario, const StageLP& stage, BlockUid buid)

void gtopt::get_all_futures(std::span<std::future<void>> futures)

Join every future in futures: .get() each one, capturing the FIRST exception and rethrowing it only after ALL futures have completed. Invalid (default-constructed / moved-from) entries are skipped.

This is the mandatory barrier idiom for pool fan-outs whose tasks reference stack locals: a bare for (auto& f : futures) f.get(); rethrows mid-loop, and the unwinding then destroys locals (build buffers, mutexes, option structs) that still-running sibling tasks are reading — a use-after-free, because the pool's destructor only joins its workers AFTER later-declared locals are gone. Draining every future first guarantees no task from this fan-out is in flight when the exception propagates.

std::vector<CompressionStatsSample> gtopt::get_compression_stats() noexcept

Read out the per-codec accumulators (snapshot, no clear). Codecs with zero ops in both directions are omitted.

double gtopt::get_cpu_quota_pct() noexcept

Currently configured CPU quota in percent, or 0 when no clamp is active. Useful for logging and tests.

template<typename Element, typename SystemContext SystemContext, template<typename> class Id>
auto&& gtopt::get_element(SystemContext& sc, const Id<Element>& id)

Free function to get a reference to an element by its ID.

Parameters
sc The system context.
id The ID of the element.
Returns A reference to the element.

template<typename Element, typename SystemContext SystemContext, template<typename> class Id>
auto gtopt::get_element_index(SystemContext& sc, const Id<Element>& id)

Free function to get the index of an element by its ID.

Parameters
sc The system context.
id The ID of the element.
Returns The ElementIndex for the given ID.

template<typename Element, typename SystemContext SystemContext>
auto&& gtopt::get_elements(SystemContext& sc)

Free function to get a container of all elements of a specific type.

Parameters
sc The system context.
Returns A reference to the container of elements.
Exceptions
std::runtime_error — propagates from the underlying ElementTraits::get_elements(sc) / SystemLP::elements<X>().

template<typename Obj>
auto gtopt::get_name(const Obj& obj)

template<>
auto gtopt::get_name<Id>(const Id& obj)

template<typename T>
std::optional<T> gtopt::get_opt(const po::variables_map& vm, const std::string& name)

Extract an optional value from a variables_map.

Template parameters
T The type of the value to extract
Parameters
vm The variables map containing parsed options
name The name of the option to look up
Returns std::optional<T> containing the value if present, std::nullopt otherwise

template<typename T, typename K = T::key_type>
auto gtopt::get_optiter(const T& map, K&& key) noexcept

Finds key in map and returns optional iterator.

Template parameters
T Map type
K Key type (defaults to map's key_type)
Parameters
map Map to search
key Key to find
Returns std::optional containing iterator if found, nullopt otherwise
Exceptions
Nothing (noexcept)

template<typename T, typename K>
auto gtopt::get_optvalue(const T& map, K&& key)

template<typename T, typename K>
auto gtopt::get_optvalue_optkey(const T& map, const std::optional<K>& key)

template<typename Obj>
Uid gtopt::get_uid(const Obj& obj)

template<>
Uid gtopt::get_uid<Id>(const Id& obj)

ArrowColumnResult gtopt::GetColumn(const ArrowTable& table, std::string_view name)

Get column by name with explicit error checking.

int gtopt::gtopt_cli_main(const std::vector<std::string>& args, std::ostream& out, std::ostream& err, bool stdout_is_tty)

Full command-line entry point of the gtopt binary.

Parameters
args Command-line arguments WITHOUT the program name (i.e. argv[1..argc)).
out Stream for regular output (help, listings).
err Stream for error diagnostics of the info commands.
stdout_is_tty Whether the process stdout is interactive. When false (and not --quiet), spdlog output is redirected to <log_directory>/gtopt_N.log. main() passes isatty(STDOUT_FILENO) != 0.
Returns Process exit code (see file header).

std::vector<std::pair<std::string, std::string>> gtopt::gtopt_environment(char*const* envp)

GTOPT_* variables of the NULL-terminated environment block envp, sorted by name. Values of secret-like names (containing TOKEN, KEY, SECRET or PASSWORD) are replaced by ***.

std::expected<int, std::string> gtopt::gtopt_main(const MainOptions& raw_opts)

Run the gtopt power-system optimizer.

Parameters
raw_opts All runtime options; only set the fields you need.
Returns 0 on success, 1 on infeasibility, or an error string on failure.

Reads the planning files listed in raw_opts.planning_files, merges them into a single Planning object, applies CLI overrides, builds and solves the LP model, writes the solution output, and saves a copy of the merged planning as planning.json in the output directory.

double gtopt::guarded_cut_intercept(double z, bool interior) noexcept

Cut intercept from forward data: lowered by interior_cut_rel_gap · max(1, |z|) when the data come from an interior solve.

bool gtopt::has_active_use_user_alpha(const PlanningLP& planning_lp)

Whether the active FutureCost element in planning_lp has use_user_alpha = true (piece 5 step 2a) — the user-overridable FCF flag that suppresses the built-in α (register_alpha_variables runs with register_as_state_variable = false). Returns false when there is no active FutureCost element (the legacy boundary-cut / no-FCF paths).

bool gtopt::has_flag(OutputFlags set, OutputFlags bit) noexcept

bool gtopt::has_ignored_cwd_config(const std::filesystem::path& loaded)

True when the current directory holds a .gtopt.conf that is not loaded — i.e. a file that older releases would have read and that is now ignored. Used only to tell the user about it.

bool gtopt::has_no_shedding_penalty(const Planning& planning) noexcept

Return true when the planning has no demand-shedding penalty.

A shedding penalty can come from one of three places:

  • the global model_options.demand_fail_cost option (defaults to 1000 $/MWh when unset, so only an explicit 0 disables it),
  • a per-demand fcost field (curtailment cost, $/MWh), or
  • a per-demand ecost field (energy-shortage cost, $/MWh).

gtopt_main uses this to gate the "no demand-shedding penalty" warning so it does not fire on planning JSONs that set per-demand fcost/ecost but set the global demand_fail_cost to 0.

template<typename Obj>
Id gtopt::id(const Obj& obj) noexcept

Creates an Id from an object's attributes.

Template parameters
Obj The object type (must have uid and name members)
Parameters
obj The object to get identification from
Returns Id containing the object's uid and name

std::vector<std::string> gtopt::identify_all_available_solvers()

Return the solvers that are actually usable on this machine.

Returns Names of usable solvers, in available_solvers() order.

SolverRegistry::available_solvers() lists every plugin that LOADED, but a plugin can load without being runnable on the current hardware (e.g. the cuOpt .so loads with no usable GPU). This probes each loaded solver with a trivial feasible LP and keeps only those that solve it to optimality, so a present-but-unusable backend is excluded rather than reported as a failure. A note is printed to stdout for each skipped solver.

bool gtopt::in_lp_debug_range(int scene_uid, int phase_uid, OptInt scene_min, OptInt scene_max, OptInt phase_min, OptInt phase_max) noexcept

Check whether a (scene_uid, phase_uid) pair falls inside the optional debug filter ranges. Empty optionals mean "no bound on that side".

IterationIndex gtopt::index_of(IterationUid uid) noexcept

Convert a 1-based IterationUid back to the matching 0-based IterationIndex.

template<typename T, typename Vector>
std::optional<FieldSched<T, Vector>> gtopt::inherit_field_sched(const std::optional<FieldSched<T, Vector>>& sched, std::string_view owner_class, Uid uid)

Copy an optional field schedule from a parent element of class owner_class / uid uid onto a synthesized child element. Inline scalars and vectors are copied verbatim; a file reference is rewritten with make_file_sched_ref so the child still reads the parent's table rows instead of its own class directory and uid.

template<typename SystemLPT>
Real gtopt::initial_state_fallback(const SystemLPT& sys, const ScenarioLP& scenario, const StageLP& stage, LPClassName class_name, Uid uid, std::string_view col_name, Real initial)

The initial estimate a state reader uses when solved_stage_state found nothing. initial (the case eini) is the correct value only while the LP has never been solved (SDDP iteration 0 before the first forward solve, build time). Once the LP HAS been solved the solved value existed and was lost, which is a bug in the caller's data flow: warn once with context instead of silently substituting initial.

std::string gtopt::insecure_plugin_location(const std::filesystem::path& path)

Why the plugin at path must not be loaded (the file or its directory is world-writable), or an empty string when its location is acceptable.

void gtopt::install_async_default_logger()

Install the async wrapper as spdlog's default logger.

Public, idempotent wrapper around the internal ensure_default_logger_async() helper. Safe to call from the standalone binary before any other spdlog state is touched so that pre-gtopt_main() log lines (CLI parsing diagnostics, env-level load, etc.) are also dispatched through the background thread pool.

A second call is a no-op (detected by the registered logger name).

IntegrityDecision gtopt::integrity_finding(std::string status, std::string message, const PluginIntegrityPolicy& policy)

Turn a failed check into a decision: warn under warning, refuse under error; the message gets the matching hint appended.

template<typename IndexType, typename A, typename B>
IotaRange<IndexType> gtopt::iota_range(A first, B last)

Create an IotaRange [first, last) with explicit IndexType, similar to enumerate<IndexType>(...). Usage: iota_range<PhaseIndex>(0, num_phases)

template<typename T>
IotaRange<T> gtopt::iota_range(T first, T last)

Create an IotaRange [first, last) with deduced type.

bool gtopt::is_codec_available(CompressionCodec codec) noexcept

Check whether a given codec is available at runtime.

bool gtopt::is_compatible_double_type(arrow::Type::type type_id)

Check if an Arrow type is a compatible floating-point type that can be cast to double.

Parameters
type_id The Arrow type id to check
Returns true if the type is float or double

bool gtopt::is_compatible_int32_type(arrow::Type::type type_id)

Check if an Arrow type is a compatible integer type that can be cast to int32.

Parameters
type_id The Arrow type id to check
Returns true if the type is int8, int16, int32, or int64

bool gtopt::is_empty_col_label(const SparseColLabel& l) noexcept

True for a metadata entry that carries no identifying fields. Entries with no class_name / variable_name / unknown uid / monostate context are skipped by the duplicate-detection maps — several internal paths (structural tests, unnamed bootstrap bookkeeping) legitimately create unlabelled cols/rows and they must not trip the detector.

bool gtopt::is_fast_start(OptBool explicit_flag, OptReal min_up_time, OptReal min_down_time, double max_hours) noexcept

Fast-start classification of one commitment.

An explicit fast_start flag wins. Otherwise the auto rule holds when min_up_time <= max_hours and min_down_time <= max_hours (unset = 0). gtopt has no startup-time / notification-time field, so the rule uses min up/down only.

bool gtopt::is_final_state_col(std::string_view col_name) noexcept

Returns true if col_name is a final-state column name that may appear in boundary / hot-start cut CSV headers.

Used by the cut CSV loader to decide whether a header column is a state variable (and thus a candidate cut coefficient column) or metadata (rhs / scene / phase / iteration).

Exposed for unit testing: the predicate is the source of truth for the cut-file column allow-list, and a regression here silently drops state coefficients on load.

bool gtopt::is_first_stage_col_name(std::string_view variable_name)

True for the capacity (first-stage) columns that CapacityObjectBase creates inside the first scenario's build call: their cost is the same in every scenario, so CVaR leaves them alone.

bool gtopt::is_infinite_kappa(double kappa) noexcept

True when a backend kappa value is the solver's "infinite / cannot estimate" answer rather than a finite condition number.

bool gtopt::is_infinity(double v, double solver_infinity) noexcept

True iff v is an infinity-like sentinel relative to solver_infinity. Use to skip auto-scaling, equilibration division, etc. on values that represent "unbounded" rather than a real physical magnitude. solver_infinity MUST come from SolverBackend::infinity() (CPLEX: 1e20, HiGHS / OSI / Gurobi: 1e30) — never a magic number. This is the free-function counterpart of LinearInterface::is_pos_inf(value), usable in pre-LP code (e.g. PlanningLP::auto_scale_* once a throwaway SolverBackend has been instantiated to query its infinity).

bool gtopt::is_interior_solve(const SolverOptions& opts) noexcept

True when opts solves an LP by barrier (or the solver default, which picks barrier on these LPs) without crossover — the solution and its duals are an interior point, not a vertex.

bool gtopt::is_long_layout(const ArrowTable& table)

True when table uses the long layout: it carries both a bare uid column and a value column.

Mirrors the Python reader sniff in scripts/gtopt_check_output/_reader.pydataset_layout. The wide layout (one uid:N column per element) never has a bare uid+value pair, so the test is unambiguous.

bool gtopt::is_native_bess_reserve_generator(const SystemContext& sc, const GeneratorLP& gen)

True when gen is the discharge generator of a battery whose reserve_sustain_hours is set, i.e. its reserve provisions are modelled by the native BESS rows of the linking ConverterLP (ReserveProvisionLP then skips its generic generator rows).

bool gtopt::is_removed_cut_sharing_mode_name(std::string_view name) noexcept

True when name spells one of the cut-sharing modes REMOVED on 2026-07-08 (accumulate, broadcast_mean / expected, max) — KNOWN INVALID cross-scene broadcasts; see docs/formulation/sddp-cut-validity.md §7. Ingestion paths use this to fail loudly with a removal message instead of the generic unknown-name error (and instead of silently degrading to a default).

bool gtopt::is_world_writable_directory(const std::filesystem::path& dir) noexcept

True when dir exists and is writable by "others" (mode o+w).

Index gtopt::iteration_relative(IterationIndex cur, IterationIndex offset) noexcept

Signed distance of cur from a base offset, as a plain Index offset (not wrapped in IterationIndex — because the difference of two positional indices is not itself a positional index, it's a count).

Replaces the iteration_index - m_iteration_offset_ idiom sprinkled across SDDP iteration management (relative-iteration logging, min_iter clamping, max_async_spread checks). Having a single helper means future tweaks (e.g. bounds-checking on negative differences) land in one place.

std::optional<KappaMode> gtopt::kappa_mode_from_env()

Mode named by $GTOPT_KAPPA_MODE; nullopt when unset, empty or unparsable (the last logs a warning once).

const std::vector<std::string_view>& gtopt::known_schema_names()

The selector names accepted by dump_json_schema: planning (the default) and options first, then every contract type in snake_case, sorted. Exposed for diagnostics and tests.

std::expected<Basis, Error> gtopt::load_basis(const std::filesystem::path& path)

Returns the reconstructed basis, or a FileIOError (file missing / unreadable) / InvalidInput (bad magic, version, or truncated / corrupt body) — never throws.

Deserialize a Basis from path.

std::expected<CutLoadResult, Error> gtopt::load_boundary_cuts_csv(PlanningLP& planning_lp, const std::string& filepath, const SDDPOptions& options, const LabelMaker& label_maker, const StrongIndexVector<SceneIndex, StrongIndexVector<PhaseIndex, PhaseStateInfo>>& scene_phase_states)

Parameters
planning_lp The PlanningLP to add cuts to
filepath Input CSV file path
options SDDP options (boundary mode, max iters)
label_maker Label maker for LP row names
scene_phase_states Per-scene phase state (for alpha columns)
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, [iteration,] scene, rhs, coefficients}. Cuts are added only to the last phase, with an alpha column created if needed. Analogous to PLP's "planos de embalse".

std::expected<CascadeProgress, Error> gtopt::load_cascade_progress(const std::filesystem::path& path)

Load cascade_progress.json from disk.

Returns FileIOError if the file is missing or malformed. Callers should treat "missing file" as cold-start (no recovery available), not as a hard error.

std::expected<CutLoadResult, Error> gtopt::load_cuts_parquet(PlanningLP& planning_lp, const std::string& filepath, double scale_alpha, const LabelMaker& label_maker, const StrongIndexVector<SceneIndex, StrongIndexVector<PhaseIndex, PhaseStateInfo>>* scene_phase_states = nullptr, SDDPCutManager* cut_store = nullptr)

Parameters
planning_lp PlanningLP whose phase LPs receive the cuts
filepath Input Parquet file path (base stem)
scale_alpha α column scale (unused; kept for API parity with the CSV loader)
label_maker Label maker for LP row names (unused; kept for API parity with the CSV loader)
scene_phase_states Per-scene phase state (unused; kept for API parity with the CSV loader)
cut_store When non-null, every loaded cut is also pushed into this SDDPCutManager via store_cut so the manager's per-scene vectors stay authoritative for inherited + generated cuts. Without this, SDDPCutManager::forget_first_cuts(N) would walk a store that doesn't know about the loaded cuts and would delete the wrong rows from the LP — root cause of the cascade forget_first_cuts + low_memory=compress crash observed on the large hydrothermal case when inherit_optimality_cuts > 0.
Returns CutLoadResult with count and max iteration, or an error

Load cuts from a Parquet file (plus any sibling *.append-*.parquet files) and add to all scenes' phase LPs. Coefficient keys must be structured class:var:uid.

MainOptions gtopt::load_gtopt_config()

Load a MainOptions from the [gtopt] section of .gtopt.conf.

Reads the config file found by find_config_file() ($GTOPT_CONFIG, then ~/.gtopt.conf; the current directory is not searched) via load_gtopt_config_from().

MainOptions gtopt::load_gtopt_config_from(const std::filesystem::path& config_path)

Load a MainOptions from the [gtopt] section of a config file.

Parameters
config_path Config file to read; an empty path yields defaults.
Returns MainOptions with fields populated from the config file. Fields not present in the config file remain as nullopt.

Extracts values from the [gtopt] section (and the per-solver [solver.<name>] sections) of config_path. Keys use kebab-case matching the CLI flag names (e.g. output-format, sddp-max-iterations). Explicit-path entry point: no environment / CWD / HOME lookup, so it can be unit tested with a fixture file.

NamesRegistry gtopt::load_names_registry()

Build a fresh registry with the same resolution as instance() (override file, else compiled-in dictionary), without caching. Exposed for tests of the resolution order.

std::expected<CutLoadResult, Error> gtopt::load_scene_cuts_from_directory_parquet(PlanningLP& planning_lp, const std::string& directory, double scale_alpha, const LabelMaker& label_maker, const StrongIndexVector<SceneIndex, StrongIndexVector<PhaseIndex, PhaseStateInfo>>* scene_phase_states = nullptr)

Load all per-scene Parquet cut files from a directory.

Files matching scene_<N>.parquet and the combined sddp_cuts.parquet are loaded. Files with the error_ prefix (from infeasible scenes in a previous run) are skipped.

std::expected<SeedCommitmentMap, Error> gtopt::load_seed_commitment(const std::string& path)

Returns the (generator,block) → u seed map, a FileIOError when the path cannot be opened / parsed, or an InvalidInput error when a required column is missing (a header-only file yields an empty map, which the pipeline treats as "no seed").

Load an external commitment seed from a CSV read through the Arrow CSV reader (the same path as boundary_cuts.csv). Required header + columns: generator_uid (int), block_uid (int), u (0/1 status, thresholded at 0.5 by SeedCommitmentRule); extra columns are ignored. The PRODUCER owns cross-day alignment — it must emit keys in the TARGET case's (generator, block) uid space; gtopt matches purely by identity, so any strategy (previous-day PLEXOS / gtopt, nearest-historical, an ML predictor) is just a producer of this CSV.

SolverCfgPairs gtopt::load_solver_cfg(const std::optional<std::string>& param_file, std::string_view solver_name, std::span<const SolverCfgEnumKey> enum_keys)

Load and translate a solver tuning file.

Parameters
param_file gtopt's solver-agnostic parameter-file path (only its parent directory is used); disengaged → empty result.
solver_name Basename stem: cuopt → cuopt.cfg / cuopt.prm.
enum_keys Per-key named-value tables (may be empty).

Resolves <solver>.cfg (INI, preferred) then <solver>.prm (legacy) as siblings of param_file — see the file header for both dialects. Every value is routed through translate_solver_cfg_value with enum_keys, so .cfg and legacy .prm files both accept named values. Order is preserved: sectionless INI entries first, then the [<solver>] section (so section entries win when a plugin applies the pairs sequentially).

SolverCfgPairs gtopt::load_solver_cfg_cached(const std::optional<std::string>& param_file, std::string_view solver_name, std::span<const SolverCfgEnumKey> enum_keys)

Once-per-process cached load_solver_cfg.

The cuOpt plugin consults its tuning file on every solve; the file is read (and its warnings logged) only the first time a given (directory, solver) pair is requested. Edits to the file during a run are not picked up — tuning files are run inputs, not live controls.

System gtopt::load_system_from_file(std::string_view file, const std::string& input_directory)

Load only the system block from an external Planning JSON file. The loaded file's options and simulation blocks are discarded. Throws std::runtime_error if the file cannot be found or read.

LoadedSystem gtopt::load_system_with_model_options(std::string_view file, const std::string& input_directory)

Load both the system and the options.model_options blocks from an external Planning JSON file. Throws std::runtime_error on read failure.

UnitRegistry gtopt::load_unit_registry()

Build a fresh registry with the same resolution as instance(), without caching. Exposed for tests of the resolution order.

std::expected<void, std::string> gtopt::load_user_constraints(Planning& planning)

Load user constraints from external file(s) referenced in planning.

IntegrationRows gtopt::local_integration_rows(std::span<const double> times, std::span<const double> weights, double start, double end, StorageIntegration mode, bool match_weights = true)

Banded integration rows for nodes times (strictly increasing, inside [start, end]) with block weights weights (target column sums).

Row k (k = 0..n−1) is the increment over [p_{k−1}, p_k], with p_{−1} = start, p_k = t_k for k < n−1 and p_{n−1} = end. So the level after row k is the state at node t_k, and after the last row the state at the period end. Zero-length intervals (Chebyshev–Lobatto first node) give an empty row. The raw Lagrange weights are scaled by Σ w / (end − start) (the weights may be in weighted-duration units) before the column correction (match_weights = false returns the raw Lagrange rule; with points = n that is the exact cumulative integral of the global node interpolant, the dense S = V J V⁻¹).

void gtopt::log_and_throw(std::string msg)

Log msg at error level, then throw it as a std::runtime_error. The message is passed as a {} argument (not the format string) so a stray brace in already-formatted text is never reinterpreted as a placeholder.

void gtopt::log_aperture_summary(const ApertureSummary& summary, std::string_view prefix)

Log summary as a compact INFO block (nothing when no aperture was solved). prefix names the run, e.g. "SDDP" or "Cascade [L1]".

void gtopt::log_compression_stats() noexcept

Emit one INFO log line per codec that has been used since startup or since the last reset_compression_stats(). Idempotent and cheap when no codec was used (no log lines emitted).

void gtopt::log_diagnostic_lines(std::string_view level, std::string_view header, std::string_view diag)

Log a multi-line diagnostic string line-by-line via spdlog.

Parameters
level "error" → spdlog::error; any other value → spdlog::info.
header Description for the first line (e.g. the LP file path).
diag Multi-line diagnostic output to log line-by-line.

Each non-empty line is prefixed with the spdlog timestamp and level so that external-tool output (gtopt_check_lp, COIN-OR messages, etc.) is visually consistent with the rest of the log stream.

When the output exceeds kDiagMaxLines, only the last kDiagTailLines lines are printed to avoid flooding the log.

void gtopt::log_gtopt_environment()

Log every GTOPT_* variable of the process environment (info level); GTOPT_TEST_* test hooks are logged as warnings.

void gtopt::log_lp_stats_summary(const std::vector<ScenePhaseLPStats>& entries, double ratio_threshold = 1e7)

Log a summary of LP coefficient statistics.

Parameters
entries Per-scene/phase statistics.
ratio_threshold Ratio above which the detailed table is shown (default 1e7).

When the global coefficient ratio is below ratio_threshold a single summary line is emitted. Otherwise a per-scene/phase table is printed followed by the global aggregate.

template<typename Holder>
std::optional<typename Holder::mapped_type::mapped_type> gtopt::lookup_inner(const Holder& holder, const ScenarioLP& scenario, const StageLP& stage, BlockUid buid) noexcept

Optional block-level lookup over an STBIndexHolder<X>-style map: flat_map<tuple<ScenarioUid, StageUid>, flat_map<BlockUid, X>>. Returns std::nullopt when either the outer (scenario, stage) key or the inner block key is missing.

Conditional-insert producers (GeneratorLP, WaterwayLP, FlowLP, DemandLP, BusLP::theta_cols) may legitimately elide a per-block column under the P1 zero-bound optimization (generator_lp.cpp:131, waterway_lp.cpp:72, demand_lp.cpp:206). Consumers (TurbineLP, PumpLP, …) use this helper to handle the elided slot — skip the consumer's matching constraint — rather than calling flat_map::at and tripping std::out_of_range.

Used today via the lookup_*_col(scenario, stage, buid) accessors on GeneratorLP, WaterwayLP, FlowLP, and BusLP.

std::string gtopt::lowercase(std::string s)

Returns a lowercase copy of the given string (rvalue overload).

Parameters
s An rvalue std::string; transformed in-place.
Returns std::string The same string with every ASCII letter lowercased.

The rvalue string is transformed in-place (zero extra allocation) and returned. Callers that need a lazy, zero-copy view should pass a std::string_view or any non-owning string type to get a LowercaseView.

Example: auto lbl = lowercase(as_label("Generator", 42)); // "generator_42"

template<detail::string_like T>
LowercaseView gtopt::lowercase(T&& sv) noexcept

Returns a lazy, zero-copy lowercase view over a string-like value.

Parameters
sv Any string-like value (string literal, std::string_view, LPClassName, etc.) that is not a std::string rvalue.
Returns LowercaseView A lazy view; valid as long as the underlying data lives (same lifetime rules as std::string_view).

Unlike the std::string overload, this overload does not allocate: it wraps the input as a LowercaseView that applies to_lower_char on each character access. The view can be passed directly to as_label():

std::string_view cn = "Generator";
auto a = as_label(lowercase(cn), 1, 2); // "generator_1_2"

bool gtopt::lp_debug_passes_includes(std::string_view passes, LpDebugPass which) noexcept

Return true iff passes (a comma-separated list of pass tokens, case-insensitive, whitespace-tolerant) selects which. An empty or unset passes string falls back to the legacy default "forward,aperture". The literal token "all" matches every pass. Unknown tokens are silently skipped (the surrounding configuration layer is responsible for warning the user).

std::string_view gtopt::lp_file_extension(LpFileFormat format) noexcept

File extension (with leading dot) written for format.

std::string_view gtopt::lp_file_format_name(LpFileFormat format) noexcept

Name of the format as accepted by --lp-format ("lp" / "mps").

std::string gtopt::lp_file_path(std::string_view stem, LpFileFormat format)

Path of the file written for stem in format (stem + extension).

std::string gtopt::lp_scales_path(std::string_view lp_path, std::string_view suffix = lp_scales_json_suffix)

Sidecar path for a written model file: compression (.gz, .zst, .lz4, .bz2, .xz) and model (.lp, .mps) extensions are replaced by suffix (otherwise suffix is appended).

std::string gtopt::lp_scales_to_json(const LpScales& scales)

Serialises scales to JSON text (daw::json).

ApertureContext gtopt::make_aperture_context(SceneUid scene_uid, PhaseUid phase_uid, ApertureUid aperture, int extra)

Build an SDDP aperture cut context.

template<typename Type, typename FieldSched, typename... Uid>
auto gtopt::make_array_index(const auto& system_context, std::string_view class_name, const FieldSched& sched, const Id& id)

BasicTaskRequirements<SDDPTaskKey> gtopt::make_backward_lp_task_req(IterationIndex iteration_index) noexcept

Build a BasicTaskRequirements<SDDPTaskKey> for a backward-pass LP solve. See make_forward_lp_task_req for the ordering invariant.

BlockContext gtopt::make_block_context(ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid)

Build a block-level context from strongly-typed UIDs.

BlockExContext gtopt::make_block_context(ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid, int extra)

Build a block-level context with an extra index (e.g. segment number).

DomainRulePipeline gtopt::make_default_domain_rules(const MipStartDomainRules& opts, SeedCommitmentMap seed = {})

Build the default domain-rule repair pipeline from the per-stage toggles. THE place to register future rules that encode more power-system knowledge into the initial integer guess (ramp, must-run, reserve coverage, …). Registers (each gated on its opts toggle, all default ON): MinUpDownRule, PeakInjectionRule, then CommitmentLogicRule (LAST — it derives v/w from the final u). Every rule is also data-gated: it no-ops when its slice of DomainRuleContext is empty, so registering by default is free for runs that don't supply the data.

When seed is non-empty a SeedCommitmentRule is registered FIRST (before every other rule), so an external commitment seed is the base the remaining rules repair. An empty seed (the default) reproduces the legacy pipeline exactly.

FileSched gtopt::make_file_sched_ref(std::string_view owner_class, std::string_view fsched, Uid uid)

Build a FileSched that resolves fsched exactly as element uid of class owner_class would: "<Class>@<field>#<uid>". A reference that already carries a uid override is returned unchanged (idempotent).

BasicTaskRequirements<SDDPTaskKey> gtopt::make_forward_lp_task_req(IterationIndex iteration_index) noexcept

Build a BasicTaskRequirements<SDDPTaskKey> for a forward-pass LP solve.

Centralises the (priority, priority_key) tuple so the SDDP solver never spells out the key inline, and so the lexicographic ordering invariant stays in one place:

iter N LP < iter N+1 LP (same direction) forward LP < backward LP (same iter) any LP < any non-LP (same iter, direction)

Both forward and backward solves share TaskPriority::Medium; the tuple key alone provides full SDDP ordering. Exposed for unit testing — the priority-key invariant is the contract every SDDP scheduler caller relies on, and a regression here silently reorders the solve graph.

IterationContext gtopt::make_iteration_context(SceneUid scene_uid, PhaseUid phase_uid, IterationUid iteration_uid, int extra)

Build an SDDP scene/phase context from an already-converted IterationUid. The primary overload — keeps call sites visually homogeneous (three UIDs + one extra).

All three UIDs must be REAL identifiers (not the unknown_uid sentinel). Passing unknown_uid for any of them produces an unlabelable LP-row context that LinearInterface::generate_labels_from_maps cannot disambiguate from other unknown_uid-tagged rows, ultimately triggering a duplicate-label collision or the "metadata without a class_name (unlabelable)" error. Caught here at construction time by throwing std::invalid_argument so the bad call site surfaces directly instead of in the (much later) label generation pass.

LpMatrixOptions gtopt::make_lp_matrix_options(bool enable_names, const std::optional<double>& matrix_eps, bool compute_stats = false, const std::optional<std::string>& lp_solver = {}, std::optional<LpEquilibrationMethod> equilibration_method = {})

Build LpMatrixOptions from internal parameters.

Parameters
enable_names Whether to enable column/row name generation
matrix_eps Optional epsilon tolerance for matrix coefficients
compute_stats Whether to compute LP statistics (default false)
lp_solver Optional solver name to use
equilibration_method Optional equilibration method
Returns LpMatrixOptions configured according to the parameters

LpScales gtopt::make_lp_scales(const SystemLP& system, std::string_view lp_path, LpScalesLevel level = LpScalesLevel::full)

Parameters
system
lp_path Path of the written model file (only its name is kept).
level full also points to the Parquet tables (tables).

Collects the scale factors of the LP held by one (scene, phase) cell.

LpScalesDetail gtopt::make_lp_scales_detail(const SystemLP& system)

The columns and rows of the cell whose scale is not 1, with the names written in the model file.

MarkovChainConfig gtopt::make_markov_config(std::vector<int> state_of_scene, std::vector<double> transition)

Build a MarkovChainConfig from the JSON-facing arrays (SddpOptions::markov_states / markov_transition). num_states is inferred as the integer square root of the transition length; a non-square length yields the raw length preserved so validate_markov_config can report it. No validation here.

std::unique_ptr<MipStartGenerator> gtopt::make_mip_start_generator(const MipStartOptions& opts)

Factory: build the candidate generator for these options. When opts.from_file is set, the file-replay generator; otherwise the default dive generator (propagation dive + verify + repair, see mip_start_dive.hpp), or the legacy round + domain-rules warmstart generator when opts.dive.enabled is false. Never returns nullptr.

po::options_description gtopt::make_options_description()

Create the command-line options description for the gtopt application.

Returns po::options_description The options description containing all supported options

PhaseContext gtopt::make_phase_context(SceneUid scene_uid, PhaseUid phase_uid, Uid element_uid)

Build a planning-level (phase/global-scope) context from the cell's (scene, phase) UIDs and the owning element's uid (the discriminator).

std::unique_ptr<PlanningMethod> gtopt::make_planning_method(const PlanningOptionsLP& options, size_t num_phases = 0)

Create a solver instance based on options.

Parameters
options The PlanningOptionsLP with all resolved SDDP configuration
num_phases Number of phases in the simulation (used to validate SDDP requirements; falls back to monolithic when < 2)
Returns Unique pointer to the selected solver

ReservoirRefCache gtopt::make_reservoir_ref_cache(const ReservoirLP& rsv, const ScenarioLP& scenario, const StageLP& stage)

Populate a ReservoirRefCache from a ReservoirLP reference.

ScenePhaseContext gtopt::make_scene_phase_context(SceneUid scene_uid, PhaseUid phase_uid)

Build an SDDP scene/phase context.

SDDPTaskKey gtopt::make_sddp_task_key(IterationIndex iteration_index, SDDPPassDirection direction, SDDPTaskKind kind, int phase_rank = 0) noexcept

Build an SDDPTaskKey from strongly-typed SDDP parameters.

Parameters
iteration_index SDDP iteration index
direction Forward or backward pass
kind LP solve or non-LP task
phase_rank Laggard-first tie-break (0 = phase-agnostic driver)

Produces (iteration_index, is_backward, phase_rank, kind) where is_backward = (direction == backward) ? 1 : 0.

phase_rank is a NON-NEGATIVE laggard-first tie-break used only by the per-phase backward aperture-chunk tasks (see make_aperture_submit_fn): in the async path two scenes can be in the same iteration's backward sweep at different phases at once, and the scene with MORE phases still to process (the laggard) should drain first. Scene-driver tasks (forward / backward / sim), which run all their phases internally as a single pool task, leave it at the default 0 (highest within their (iteration, is_backward) class). Kept non-negative so it never inverts the is_backward ordering above it in the tuple.

std::unique_ptr<SDDPWorkPool> gtopt::make_sddp_work_pool(double cpu_factor = 2.0, double memory_limit_mb = 0.0, int cell_task_headroom = 0)

Create and start an SDDPWorkPool configured for the SDDP solver.

Parameters
cpu_factor Over-commit factor applied to physical_concurrency(). Default 2.0. Was 4.0 under the previous per-task std::async design; with persistent lazy-spawned workers the pool self- regulates, so 2× is a better ceiling.
memory_limit_mb Process RSS limit in MB (0 = no limit).
cell_task_headroom Extra slots reserved for the synchronised backward pass's per-scene cell tasks (which block on aperture futures and would otherwise reduce the aperture-parallelism ceiling). Pass the number of feasible scenes for the run. Default 0 preserves prior behaviour for callers that have not migrated.
Returns A started SDDPWorkPool (heap-allocated, non-movable).

Uses SDDPTaskKey (tuple) as the secondary priority key so that the SDDP forward/backward LP solves are ordered by (iteration, is_backward, kind) with the default std::less<SDDPTaskKey> comparator (smaller tuple → higher priority).

The pool sizes itself as cpu_factor × physical_concurrency() + cell_task_headroom. The headroom term compensates for a structural property of the synchronised backward pass: per-scene cell tasks block on their aperture sub-task futures while holding a worker slot. With cell_task_headroom = num_feasible_scenes the pool always has cpu_factor × physical_concurrency slots free for aperture solves regardless of how many cell tasks are mid-wait. Without the headroom, the cell-task block silently caps aperture parallelism at (cpu_factor × physical_concurrency) − num_scenes (typically ~80 % of the nominal cap on a 16-scene problem — observed on the large hydrothermal case as Active 36-48/80, Pending 0, where the gap between 80 and the active count is the cell-task block).

The headroom workers are lazily spawned, so on iterations where the cell-task block is short (e.g. backward pass without apertures) they stay parked in cv_.wait and add no measurable overhead.

std::unique_ptr<AdaptiveWorkPool> gtopt::make_solver_work_pool(double cpu_factor = 2.0, double cpu_threshold_override = 0.0, std::chrono::milliseconds scheduler_interval = std::chrono::milliseconds(50), double memory_limit_mb = 0.0, std::string_view pool_label = "SolverWorkPool")

Create and start an AdaptiveWorkPool configured for solver use.

Parameters
cpu_factor Over-commit factor applied to hardware_concurrency. Default 2.0 — extra threads compensate for mutex contention during LP clone operations.
cpu_threshold_override If provided and > 0, use this value as the pool's CPU-load dispatch gate instead of the default 100 - 50/max_threads formula. Useful for I/O-bound workloads (e.g. parquet encode) where the formula's thread-count-driven cap is too conservative.
scheduler_interval Period of the pool's scheduler loop (dispatch / monitoring tick). Default 50 ms.
memory_limit_mb Process RSS limit in MB enforced by the dispatch gate; 0 (default) disables the limit.
pool_label Pool name used in logs and statistics.
Returns A started AdaptiveWorkPool (heap-allocated, non-movable).

Both MonolithicMethod and SDDPMethod (auxiliary pool) use this factory.

StageContext gtopt::make_stage_context(ScenarioUid scenario_uid, StageUid stage_uid)

Build a stage-level context from strongly-typed UIDs.

template<class Tag>
auto gtopt::make_uid(uid_t value)

Sanctioned factory: construct a UidOf<Tag> from a raw uid_t.

Intended call sites are file / JSON boundaries where a raw integer crosses from external data into the type system. Inside the codebase, prefer copying an existing UID from an element rather than calling this.

template<typename Map, typename Iterator>
void gtopt::map_insert_sorted_unique(Map& map, Iterator first, Iterator last)

Insert from a pre-sorted, deduplicated range [first, last) using the most efficient API for each backend.

The range must be sorted in ascending key order and must contain no duplicate keys. For std::flat_map and boost::container::flat_map, violating this precondition is undefined behaviour.

Backend behaviour:

  • std::flat_map : insert(std::sorted_unique, first, last) — O(n) bulk insert that skips per-element comparisons.
  • boost::flat_map: insert(ordered_unique_range, first, last) — same semantics using the Boost equivalent tag.

template<typename Map, typename Size>
void gtopt::map_reserve(Map& map, Size n)

Reserve capacity for n elements in any associative container.

Dispatch is by if constexpr (requires …) on the actual argument type, so the same call site behaves correctly across std::unordered_map, boost::container::flat_map, std::flat_map, and std::map — no matter which flat_map backend the build is configured to use.

bool gtopt::markov_active(CutSharingMode cut_sharing, const MarkovChainConfig* markov) noexcept

True when Markov-chain SDDP pricing/routing is in effect: the mode is markov AND a non-empty chain configuration is present. THE single predicate shared by alpha_col_weights (pricing) and register_alpha_variables (column layout) so the two cannot drift.

std::vector<double> gtopt::markov_alpha_weights(const SimulationLP& sim, const MarkovChainConfig& markov, SceneIndex scene_index)

Per-column pricing weights of scene-scene_index's LP under CutSharingMode::markov: w_{s,m'} = p_s·P[m(s)][m'] / pi_{m'} for m' = 0..M-1 (theorem MK1 in docs/formulation/sddp-markov.md §2). Scene probabilities come from scene_probability_masses (single shared derivation); the weights are scale-invariant in the total mass, so no normalization is applied. A zero-mass state (every assigned scene degenerate) prices its column 0 — the state is unreachable under the folded measure. Consumed via the mode-aware alpha_col_weights accessor, which register_alpha_variables (objective pricing) and the forward-pass UB strip both call so the two always agree.

const LinkedLibraryRecord* gtopt::match_linked_library(const std::vector<LinkedLibraryRecord>& records, const LoadedLibraryIdentity& loaded)

The record of records the loaded library corresponds to: same soname, else same file name as the recorded path. nullptr when none matches.

MemoryClamp gtopt::memory_clamp_threads(double cpu_factor, double memory_limit_mb, std::string_view pool_label)

Compute the thread count and growth ceiling for a work pool.

cpu_factor × physical_concurrency() is the absolute CPU budget — the ceiling. There are NO a-priori per-task size estimates anywhere.

Worker-thread count is DECOUPLED from memory throttling: the pool always runs at the full ceiling so worker threads stay available even while the dispatch gate throttles memory-heavy work. This is required by the SDDP backward pass's blocking-slot pattern (release_slot_while_blocking): a parent cell-task drops its slot and blocks on child futures, and a free worker must be able to run that child. Clamping the worker count below cell_task_headroom deadlocks the pass — observed as a livelock at RSS ≫ limit with the rss-throttle counter spinning and no progress.

Memory is bounded purely by the live dispatch controller in BasicWorkPool::can_dispatch_task (measured idle-floor + marginal per-task cost + one-admit-per-monitor-interval rate limit + always-admit- when-idle progress guarantee). The rate limit serialises admission to ~one task per monitor interval regardless of worker count, so keeping all workers available can never cause a dispatch burst.

template<typename T>
bool gtopt::merge(std::vector<T>& dest, std::vector<T>&& src)

Efficiently merges two vectors using move semantics.

Template parameters
T Type of elements (must be move-constructible)
Parameters
dest Destination vector (will receive elements)
src Source vector (will be emptied)
Exceptions
Nothing (noexcept)

Appends elements from source vector to destination vector. After the operation, the source vector will be empty but in a valid state. Handles self-merge safely.

template<typename T>
bool gtopt::merge(std::vector<T>& dest, std::vector<T>& src)

Overload for lvalue source vector (converts to rvalue reference)

void gtopt::merge_config_defaults(MainOptions& opts, const MainOptions& defaults)

Merge config-file defaults into a MainOptions struct.

Parameters
opts The primary options (typically from CLI parsing).
defaults The fallback options (typically from config file).

For each field in opts that is not set (nullopt / empty), copies the value from defaults. CLI-set fields are never overwritten.

template<typename OptA, typename OptB>
auto& gtopt::merge_opt(OptA& a, OptB&& b)

Merges two optionals, keeping value if source has value.

Template parameters
OptA Destination optional type
OptB Source optional type
Parameters
a Destination optional (modified in place)
b Source optional (rvalue reference)
Returns Reference to modified destination optional
Exceptions
Nothing (noexcept)

If source optional (b) has value, assigns it to destination (a). Otherwise leaves destination unchanged.

double gtopt::mip_polish_reserve(std::optional<double> time_limit) noexcept

Polish reserve for a MIP solve under time_limit: min(mip_polish_reserve_fraction * limit, max_mip_polish_reserve_s), or 0 when no limit is set.

IterationIndex gtopt::next(IterationIndex iteration_index) noexcept

Next iteration index (iteration_index + 1), preserving strong type.

IterationIndex gtopt::next(IterationIndex iteration_index, Index n) noexcept

Advance an iteration index by n steps, returning a new IterationIndex. Replaces the IterationIndex{static_cast<Index>(offset) + n} pattern used to compute an iteration budget horizon.

Example: next(m_iteration_offset_, m_options_.max_iterations) returns the exclusive upper bound of a training run that starts at m_iteration_offset_ and takes max_iterations iterations.

PhaseIndex gtopt::next(PhaseIndex phase_index) noexcept

Next phase index (phase_index + 1), preserving strong type.

PhaseStageIndex gtopt::next(PhaseStageIndex index) noexcept

Next phase-local stage position.

SceneIndex gtopt::next(SceneIndex scene_index) noexcept

Next scene index (scene_index + 1), preserving strong type.

StageIndex gtopt::next(StageIndex stage_index) noexcept

Next stage index (stage_index + 1), preserving strong type.

LPAlgo gtopt::next_fallback_algo(LPAlgo current) noexcept

Return the next algorithm in the LP fallback cycle: barrier → dual → primal → barrier. default_algo and last_algo both map to dual (the cycle starts as if the input were barrier).

Used by LinearInterface::initial_solve / resolve to walk the algorithm space when the primary algorithm fails to reach optimal. Lives in this header so it is constexpr-testable in isolation without spinning up an LP backend.

std::string gtopt::no_solver_message(const std::vector<std::string>& load_errors)

Error text when no solver is usable and none was requested by name. When some plugin was REFUSED by an integrity check (a load error carries k_plugin_refused_marker), says that plugins were found but every one was refused, lists the load errors (each refusal names its own override) and the generic overrides – not the install hints, which would send the user after a missing solver that is installed. Otherwise (genuinely no plugin) returns the "No solver plugins found." text with the install hints.

std::optional<Error> gtopt::nonanticipative_cut_load_error(const SimulationLP& sim, std::string_view what)

Error returned when cuts are loaded from a file into a merged scene (nullopt when the simulation has no nonanticipative merge).

LpFileFormat gtopt::other_lp_file_format(LpFileFormat format) noexcept

The other format (used for the fallback of diagnostic dumps).

std::string gtopt::output_flags_to_string(OutputFlags flags)

Render an OutputFlags bitmask back into its canonical comma-separated form (for logging / JSON round-trip). all and none are emitted as themselves; any other combination lists the atomic bits in enum order.

std::string gtopt::output_selection_to_string(const OutputSelection& sel)

Render an OutputSelection back into its canonical comma-separated form (round-trip with parse_output_selection).

std::expected<ArrowTable, std::string> gtopt::parquet_read_table(const std::filesystem::path& fpath)

Read an Arrow table from a Parquet file.

Returns an error string on failure.

std::optional<int> gtopt::parse_aperture_chunk_size(std::string_view s) noexcept

Parse an aperture-chunk-size value from a string.

Parameters
s The string to parse.
Returns The resolved integer, or std::nullopt on parse failure (e.g. an empty string or non-numeric non-"auto" input).

Accepts either an integer literal (parsed via std::stoi) or the case-insensitive string "auto" — mapped to 0 ("unset"): under aperture_chunk_mode = chunked that picks K via compute_auto_aperture_chunk_size; with no mode it keeps the default per_scene (see resolve_aperture_chunk).

Used by both the boost::program_options CLI parse (where the flag is declared as a std::string) and the INI-file parser (where the value is read as a string from the section map). Single source of truth for the "auto" alias keeps the two parse paths in sync.

std::optional<std::string> gtopt::parse_build_id_manifest(std::string_view text)

Parse a manifest line <hex build-id> <file name> (sha256sum-like; the file name is optional). Returns the lowercase build-id, or std::nullopt when text has no valid hex token.

template<typename T>
std::optional<T> gtopt::parse_conf_number(std::string_view text)

Parse a whole config-file value as a number of type T (surrounding blanks allowed, trailing garbage rejected — std::stoi("4x") used to return 4). Nullopt when it is not a valid T.

CutSharingMode gtopt::parse_cut_sharing_mode(std::string_view name)

Parse a cut-sharing mode from a string ("none", "multicut", "markov"). Throws std::invalid_argument on any other spelling — including the modes REMOVED 2026-07-08 ("accumulate", "broadcast_mean" / "expected", "max"), which get a dedicated removal message plus an ERROR-level log (see is_removed_cut_sharing_mode_name).

ElasticFilterMode gtopt::parse_elastic_filter_mode(std::string_view name)

Parse an elastic filter mode from a string (backward-compatible wrapper). Accepts "single_cut" / "cut" (= single_cut), "multi_cut", "chinneck" / "iis" (= chinneck). Unknown strings — including the retired "backpropagate" — fall back to the default mode (chinneck).

std::optional<bool> gtopt::parse_env_flag(std::string_view text)

Parse a boolean environment flag: 1/true/yes/on → true, 0/false/no/off/"" → false (case-insensitive), anything else → std::nullopt.

FileSchedRef gtopt::parse_file_sched_ref(std::string_view owner_class, std::string_view fsched)

Split fsched into (class directory, field stem, optional uid). owner_class is used when no @ is present. A # suffix that is not a plain integer is kept as part of the field stem (no override).

IniData gtopt::parse_ini_file(const std::filesystem::path& path)

Parse a simple INI file.

Parameters
path Path to the INI file.
Returns Parsed sections, or empty if the file cannot be opened.

Handles [section] headers, key = value pairs, # and ; comments, and blank lines. Keys are trimmed; values are trimmed. Keys outside any section are placed under the empty-string section.

LPAlgo gtopt::parse_lp_algorithm(std::string_view s)

Parse an LP algorithm value from a string (name or integer).

Parameters
s The string to parse.
Returns The corresponding integer value for the algorithm.
Exceptions
cli::parse_error on unrecognised input.

Accepts either a numeric string ("0"–"3") or a case-sensitive algorithm name ("default", "primal", "dual", "barrier"). The name lookup is driven by lp_algo_entries – the same compile-time table used for logging – so the two are always in sync. With C++26 P2996 static reflection that table would itself be generated automatically from the LPAlgo enum, making this function fully reflection-driven.

std::optional<LpFileFormat> gtopt::parse_lp_file_format(std::string_view name) noexcept

Parse "lp" / "mps" (case-sensitive); nullopt on anything else.

MainOptions gtopt::parse_main_options(const po::variables_map& vm, std::vector<std::string> system_files)

Build a MainOptions struct from a parsed CLI variables_map.

Parameters
vm Parsed CLI variables map (from po::store/ponotify)
system_files Positional system-file arguments
Returns Fully populated MainOptions

Extracts every gtopt_main option from vm into a MainOptions value. system_files is taken from the positional arguments already pulled out by the caller (they are not stored in vm by default).

double gtopt::parse_memory_size(const std::string& s)

Parse a memory size string into megabytes.

Parameters
s The string to parse.
Returns Size in megabytes.
Exceptions
cli::parse_error on unrecognised input.

Accepts a plain number (interpreted as MB) or a number with suffix: "M"/"MB" for megabytes, "G"/"GB" for gigabytes. Examples: "4096", "300M", "5G", "1.5GB".

OutputFlags gtopt::parse_output_flags(std::string_view spec)

Parse a comma/whitespace-separated specification into an OutputFlags bitmask. Empty input yields OutputFlags::none; unknown tokens throw std::invalid_argument with the list of accepted names.

Accepted atoms (case-insensitive): none, solution (sol), dual, reduced_cost (reduced-cost, rcost, rc, cost), all.

Examples:

  • "all" → solution | dual | reduced_cost
  • "sol,dual" → solution | dual
  • "none" → no bits set

OutputSelection gtopt::parse_output_selection(std::string_view spec)

Parse OutputSelection from a comma-separated specification. See OutputSelection's docstring for the full syntax.

Throws std::invalid_argument on:

  • unknown atom keyword (with a list of accepted names),
  • a class-name continuation that has no preceding atom (e.g. Generator,sol would error because Generator precedes any scoped atom).

std::expected<Planning, std::string> gtopt::parse_planning_files(const std::vector<std::string>& planning_files, const std::optional<std::string>& input_directory = {}, std::string_view enforce_dialect = {})

Parse planning JSON files into a Planning object.

Iterates over each path in planning_files, reads the JSON, and merges it into a single Planning. Returns an error string on the first failure.

enforce_dialect optionally drives the input-warn pass on every alias canonicalization (see canonicalize_json_keys): when non-empty and an alias's source dialect differs from this value, a once-per-alias spdlog::warn is emitted. Empty preserves the pre-feature silent behaviour.

Planning gtopt::parse_planning_json(std::string_view json_content)

Parse a single JSON string into a Planning object.

Single instantiation point for from_json<Planning> — call sites avoid pulling in the heavy daw::json template machinery.

std::optional<PluginCheckMode> gtopt::parse_plugin_check_mode(std::string_view text)

Parse "warning" / "error" (case-insensitive; "warn" accepted).

std::optional<SolverCfgPairs> gtopt::parse_solver_param_file(const std::filesystem::path& path)

Parse a solver-NATIVE parameter file into (name, value) pairs.

Returns the pairs in file order, or std::nullopt when the file cannot be opened.

Accepts the line formats of the native parameter files gtopt ships next to a case (solvers/): CPLEX .prm (CPXPARAM_Name value, with the CPLEX Parameter File Version … header line skipped), Gurobi / MindOpt .prm (Name value) and HiGHS .opts (name = value). Blank lines and # / ; / // comment lines are skipped. The value is the rest of the line, trimmed, with one pair of surrounding double quotes removed (CPLEX writes string parameters quoted). Values are NOT translated — the plugin applies them with its typed setters.

std::vector<std::span<const ApertureEntry>> gtopt::partition_apertures(std::span<const ApertureEntry> apertures, int chunk_size)

Parameters
apertures Effective (deduplicated) aperture list for the phase.
chunk_size Apertures per task (<=0 collapses to 1).
Returns Vector of non-overlapping spans whose union covers apertures.

Partition a span of ApertureEntry into contiguous chunks of size chunk_size (the last chunk may be shorter).

Each returned span aliases the input — the caller must keep the backing storage alive for the lifetime of the returned vector.

Used by the chunked aperture backward pass: every chunk becomes a single SDDP work-pool task that clones the phase LP once and solves its inner apertures serially with warm-start reuse on the shared clone. Order is preserved end-to-end so the wetness sort applied in plp2gtopt (wettest → driest within a phase) keeps similar bounds adjacent within each chunk. Pairs with SddpOptions::num_apertures = N which truncates each phase's list to its first N (= wettest N) entries before chunking.

Edge cases:

  • apertures empty → empty vector.
  • chunk_size <= 0 → one chunk per aperture (K=1).
  • chunk_size >= apertures.size() → exactly one chunk.

PlanningDirectoryPeek gtopt::peek_planning_directories(const std::vector<std::string>& planning_files, const std::optional<std::string>& input_directory = {})

Cheaply read options.output_directory / options.log_directory from planning_files without deserialising the whole Planning.

Used to place the log files before the full parse runs (the file sink must exist before the first log line). Files are located the same way as in parse_planning_files; later files override earlier ones (same as Planning::merge). Missing / malformed files are skipped silently — the full parse reports them.

unsigned gtopt::physical_concurrency() noexcept

Effective physical CPU core count. Equal to detected_physical_concurrency() unless set_cpu_quota_pct() has been called with a value in (0, 100), in which case the result is ceil(detected × pct / 100) (always at least 1).

All work-pool factories should call this — never std::thread::hardware_concurrency() directly — so the CPU quota cascades through every cpu_factor multiplication.

template<typename SystemLPT>
Real gtopt::physical_efin_from_cache(const SystemLPT& sys, const ScenarioLP& scenario, const StageLP& stage, const ReservoirRefCache& rc)

Physical efin of stage for the reservoir cached in rc — see solved_stage_state for the resolution order. Falls back to the case eini (rc.default_volume) only when no solve produced it.

template<typename SystemLPT>
Real gtopt::physical_eini_from_cache(const SystemLPT& sys, const ScenarioLP& scenario, const StageLP& stage, const ReservoirRefCache& rc)

Read the physical eini of the current stage — the predecessor phase's solved efin propagated via gtopt's existing StateVariable channel.

Resolution order:

  1. Predecessor's efin StateVariable (cross-phase). When sys.prev_phase_sys() is set (production path — SDDPMethod::update_lp_for_phase wires it at sddp_method_iteration.cpp:281), look up the predecessor's efin StateVariable by key in the simulation registry and return col_sol_physical(). set_col_sol is called on every StateVariable immediately after the predecessor's forward solve, so by the time this phase's update_lp runs the value is already correct — no LI query, no is_optimal() check on the current phase's still-unsolved LP. Daily-cycle reservoirs have no state link and are not reached here (their predecessor lookup returns no match).
  2. Current LI's eini_col solution (in-phase). Daily-cycle reservoirs pin eini == efin via the close constraint, so reading the current eini_col after the LP is solved is the right answer. Also covers test paths that don't set prev_phase_sys.
  3. Default volume. Iter-0 first phase, before any solve.

Why the StateVariable channel (and not the propagated col bound, or prev_li.get_col_sol() directly):

  • The current LI's eini_col solution is unavailable when update_lp runs — that's BEFORE the solve. The pre-existing fallback to rc.default_volume (= JSON eini) selected the wrong piecewise segment for ReservoirSeepage/RDL/ProductionFactor /FlowRight/VolumeRight whenever the predecessor's actual trial differed from the JSON eini. On the large hydrothermal case scen 51 phase 38 ELTORO eini = 1731 hm³ (segment 2 constant = 15.09 m³/s) vs predecessor's drained-to-0 trial → row forced 15.09 m³/s seepage at empty storage → cascade infeasibility through p38→p1.
  • StateVariable::col_sol_physical() is gtopt's canonical cross-phase value channel: it's updated post-solve and consumed by propagate_trial_values and BendersCut exactly the same way. Reading it here makes the segment-selection axis consistent with the rest of the SDDP machinery.
  • Restores the design from commit 7a446444 refactor(update_lp): cache reservoir refs + use StateVariable channel that aeeb1c98 simplify(update_context): read eini_col directly, drop StateVariable detour removed under the (incorrect) assumption that current_eini_col == prev_phase_efin_col algebraically when update_lp runs.

ArrowTable gtopt::pivot_long_to_wide(const ArrowTable& table_in)

Pivot a long-layout table [<index cols…>, uid, value] into the wide layout [<index cols…>, uid:N…] that the input loaders expect.

Index columns are every column other than uid/value (any subset of scenario/stage/block — broadcast semantics are preserved because an absent index column simply stays absent). Duplicate (index…) keys in the long form collapse to one wide row per distinct key. Missing (uid, key) cells are zero-filled (matching gtopt's sparse long output, which drops exact zeros; plp2gtopt emits dense long so this never fires). The value column type is preserved as int32 (integer fields such as Line/active) or double (floating fields); index/uid columns are emitted as int32. This is a pure column-shape transform — it is agnostic to whether uid denotes an element (field files) or a scenario (aperture files), so it serves both readers.

std::optional<SceneMerge> gtopt::plan_nonanticipative_scene_merge(const Planning& planning)

Decide whether (and how) the active scenes must be merged.

Returns nullopt when nothing must be merged (no nonanticipative variable, or at most one active scene); otherwise the merge.

Scans system.decision_variable_array and every user_model_array[*].variable_array for nonanticipative: true.

Throws std::runtime_error (named variable + reason) when:

  • a nonanticipative variable is not scope: "global";
  • it is the user α of a FutureCost (use_user_alpha): α is a per-scene cost-to-go and cannot be shared;
  • the run has FutureCost boundary cuts: the FCF α of a scene LP is tied to the first scenario's state, so a merged scene would drop the future cost of every other scenario;
  • the active scenes do not cover one contiguous scenario range.

std::optional<PluginCheckMode> gtopt::plugin_check_mode_from_env()

Mode named by $GTOPT_PLUGIN_CHECK; std::nullopt when it is unset, empty or unparsable (the last logs a warning).

IterationIndex gtopt::previous(IterationIndex iteration_index) noexcept

Previous iteration index (iteration_index - 1), preserving strong type.

PhaseIndex gtopt::previous(PhaseIndex phase_index) noexcept

Previous phase index (phase_index - 1), preserving strong type.

PhaseStageIndex gtopt::previous(PhaseStageIndex index) noexcept

Previous phase-local stage position.

SceneIndex gtopt::previous(SceneIndex scene_index) noexcept

Previous scene index (scene_index - 1), preserving strong type.

StageIndex gtopt::previous(StageIndex stage_index) noexcept

Previous stage index (stage_index - 1), preserving strong type.

std::string_view gtopt::pricing_csv_header() noexcept

Column layout of pricing.csv (one row per solved MIP cell; written by PlanningLP::write_out next to solution.csv). Trailing newline included.

std::string gtopt::pricing_csv_line(int scene_uid, int phase_uid, const PricingOutcome& o)

One pricing.csv line for cell (scene_uid, phase_uid). The free-text reason is double-quoted (embedded quotes doubled).

bool gtopt::pricing_outcome_reportable(const PricingOutcome& o) noexcept

True when o carries anything worth a pricing.csv row (a MIP cell whose duals were recovered, or a non-default mode request).

int gtopt::print_available_solvers(std::ostream& out)

Returns 0 (the listing itself never fails).

--solvers: list the loadable LP solver plugins (or the search directories, load errors and hints when none is found).

void gtopt::print_cli_help(std::ostream& out, const cli::options_description& desc)

Print the --help text: the option table followed by the examples and output-layout sections.

int gtopt::print_json_schema(std::string_view name, std::ostream& out)

Returns 0 on success, 1 for an unknown schema name.

--json-schema [NAME]: dump the JSON Schema of the input model.

int gtopt::print_naming_dialects(std::string_view filter, std::ostream& out, std::ostream& err)

Returns 0 on success, 1 for an unknown dialect filter.

--list-dialects [NAME]: tab-separated dump of the naming/unit registries, optionally restricted to one dialect.

std::string gtopt::probe_parquet_codec(std::string_view requested)

Probe the Arrow/Parquet runtime to determine the best available codec for the requested name. Uses arrow::util::Codec::IsAvailable() — the correct runtime check — rather than parquet::IsCodecSupported(), which only validates the enum value and does not detect codecs that were absent when the Arrow library was compiled.

Falls back (with a WARN log) to "gzip", then to "" (uncompressed) when the requested codec is unavailable.

Call once at program startup (e.g. in gtopt_main() after loading options) and store the result in planning.options.output_compression so that every downstream write uses the same pre-validated codec without re-probing on each file.

void gtopt::propagate_trial_values(std::span<StateVarLink> links, LinearInterface& target_li) noexcept

Propagate trial values using the source StateVariable's cached col_sol() instead of a full-LP solution span. This is the only overload used by production SDDP code — the older span-based overload above is kept for tests that drive propagation directly.

void gtopt::propagate_trial_values(std::span<StateVarLink> links, std::span<const double> source_solution, LinearInterface& target_li) noexcept

Propagate trial values: fix dependent columns to source-column solution via column bounds (lo == hi). This is the standard SDDP bound-fixing formulation: the reduced cost of the fixed column at optimum is the shadow price of the implicit bound, which becomes the cut coefficient.

DiveOutput gtopt::propagation_dive(const DiveInput& in)

Relaxation-guided fix-and-propagate dive (stage 1). See the file header.

template<typename Element, typename SystemContext SystemContext, typename E>
auto gtopt::push_back(SystemContext& sc, E&& element)

Free function to add a new element to the system.

Parameters
sc The system context.
element The element to add.
Returns The ElementIndex of the newly added element.

double gtopt::reactive_ratio(double power_factor) noexcept

Reactive-to-active ratio Q/P = sign(pf)·tan(acos|pf|) of a signed power factor (negative = leading / absorbing). |pf| ≥ 1 or 0 (undefined) → 0 (unity).

std::optional<std::string> gtopt::read_build_id_manifest(const std::filesystem::path& plugin_path)

Read the manifest next to plugin_path. std::nullopt when there is no manifest file or it does not parse.

std::expected<ElfIdentity, std::string> gtopt::read_elf_identity(const std::filesystem::path& path)

Read build-id, soname and runpath from the ELF file path without loading it. Returns an error string for unreadable / non-ELF64-LE files.

void gtopt::reconcile_basis(Basis& basis, std::size_t ncols, std::size_t nrows) noexcept

Reconcile a basis captured from a related LP to current dimensions.

The common SDDP case: between the iteration that captured the basis and the one re-using it, cuts have appended rows (column count is stable — the cost-to-go alpha column already exists). This:

  • grows row_status to nrows, the appended rows entering the basis (slack basic) — the textbook extension that keeps a dual-feasible basis valid after adding constraints;
  • grows col_status to ncols, appended columns nonbasic at lower;
  • truncates surplus statuses if the LP instead shrank (cuts dropped).

Each appended row contributes exactly one basic slack, so the basis stays square (#basic == nrows) and the backend accepts it verbatim.

void gtopt::record_col_bounds_dynamic(PlanningLP& planning_lp, SceneIndex scene_index, PhaseIndex phase_index, ColIndex col, double lowb, double uppb, SystemKind kind = SystemKind::forward) noexcept

Set the RAW (lowb, uppb) bounds on column col at (scene, phase) AND record the change into the compress-replay channel, so a release_backend + ensure_backend cycle (LowMemoryMode::compress) preserves the bounds. Used by the user-α bootstrap pin / release (piece 5 step 2c) — a dedicated helper rather than bound_alpha (which is keyed on the built-in α class and computes a cut-derived floor). ±DblMax is accepted as the "unbounded" sentinel (mapped to the solver's infinity via normalize_bound). The replay record is established by LinearInterface::set_col_*_raw, which write the pending-col-bounds channel (keyed by column index) whenever the interface is not mid-replay and not a throwaway clone. No-op when col is out of range or the cell's system is absent.

void gtopt::register_alpha_variables(PlanningLP& planning_lp, SceneIndex scene_index, double scale_alpha, CutSharingMode cut_sharing = CutSharingMode::none, BoundaryCutSharingMode boundary_cut_sharing = BoundaryCutSharingMode::per_scene, bool register_as_state_variable = true, const MarkovChainConfig* markov = nullptr, std::size_t terminal_phi_count = 0, bool release_after = true)

Parameters
planning_lp PlanningLP whose cells receive the α columns.
scene_index Scene whose (scene, phase) cells are processed.
scale_alpha Column scale of every α column (physical α in $ = LP value × scale_alpha).
cut_sharing Cut-sharing mode; under multicut (or markov) non-terminal phases carry one α column per source scene (or Markov state) instead of a single α.
boundary_cut_sharing Terminal-phase α layout; multicut gives one terminal α column per scene.
register_as_state_variable When true (default) each α column is registered in the simulation StateVariable map (the byte-for-byte legacy behaviour, drives cut routing + the forward-pass UB estimator). When false (a user-overridable FCF — FutureCost::use_user_alpha), the α columns are still ADDED to each LP but with cost = 0 and are NOT registered as state variables, so the built-in α is inert (pinned lowb = uppb = 0, never priced, never floored, never cut) and the user-authored α + cuts fully replace it.
markov Markov-chain configuration, consulted only when cut_sharing == CutSharingMode::markov: non-terminal phases then carry markov->num_states α columns priced by markov_alpha_weights (theorem MK1, docs/formulation/sddp-markov.md). nullptr / empty keeps the mode-independent legacy layout.
terminal_phi_count NVarPhi for BoundaryCutsMode::phi_expectation (0 = mode inactive, byte-identical legacy layout). When > 0, the TERMINAL phase carries terminal_phi_count φ_j columns (uid = sddp_alpha_uid + j), each priced p_s / NVarPhi via alpha_col_weights, overriding the boundary_cut_sharing terminal layout. Callers derive it from boundary_cut_scene_count(boundary_cuts_file) — the count of distinct plane hydrologies in the boundary CSV.
release_after

Register the α (future-cost) column on every (scene, phase) cell of planning_lp that does not already have it. Each α is added as a SparseCol pinned at lowb = uppb = 0 (bootstrap) with cost = scale_alpha, mirrored into m_dynamic_cols_ for low-memory replay, and registered in the simulation-level StateVariable map so cross-level / cut I/O machinery treats α uniformly. Cut-install sites (backward pass, boundary/named cut loaders) subsequently call bound_alpha(...) to release the pin. Called once per scene during SDDPMethod::initialize_solver; exposed here so isolated callers (tests, direct cut-loader harnesses) can establish the same precondition without standing up a full SDDPMethod.

void gtopt::register_ampl_iterator_dispatchers(SimulationLP& sim)

Populate class_name -> AmplIterFn on sim with one entry per LP class that supports sum(class(all)...) enumeration.

void gtopt::register_ampl_param_dispatchers(SimulationLP& sim)

Populate (class_name, attribute) -> AmplParamFn on sim with one entry per user-facing PAMPL attribute that resolves to a scalar parameter (i.e., a param_X accessor on the matching *LP class).

void gtopt::register_solver_run(const std::string& filepath)

Register this run in the run-discovery registry (idempotent).

Normally invoked indirectly via write_solver_status(); exposed so the monitor thread can ensure the registry entry exists when it becomes the sole periodic writer.

void gtopt::reject_nan_in_float_columns(const arrow::Table& table, std::string_view path)

Parameters
table Arrow table to scan (must not be nullptr).
path Source label (file path, table name, …) — included verbatim in the error message so the user can locate the offending input.
Exceptions
std::runtime_error on the first NaN cell, with the column name and chunked-array row index (relative to column start).

Scan every Float32 / Float64 column of table for NaN cells; throw std::runtime_error on the first NaN encountered. Infinity is allowed — only NaN is rejected.

void gtopt::reject_non_numeric_columns(const arrow::Table& table, std::string_view path)

Parameters
table Arrow table to scan (must not be nullptr).
path Source label (file path, table name, …) — included verbatim in the error message.
Exceptions
std::runtime_error on the first non-numeric column, naming the column and its inferred Arrow type.

Scan every column of table for non-numeric types; throw std::runtime_error if any column has a type that is neither integer nor floating-point. Integer columns (Int8 … Int64, UInt8 … UInt64) are accepted because they implicitly convert to double downstream, satisfying the user-stated rule that "1, 1.0, -5" is a valid mixed numeric column.

Use this on tables returned by Arrow's CSV TableReader::Read, whose type-inference pass silently falls back to String whenever a single non-numeric token appears (e.g. "1, foo, 3") — exactly the failure mode we want surfaced loudly rather than absorbed into the LP build.

RelaxedVarInfo gtopt::relax_fixed_state_variable(LinearInterface& li, const StateVarLink& link, PhaseIndex phase_index, double penalty)

Relax a single fixed state-variable column to its physical source bounds, adding penalised slack variables. Returns a RelaxedVarInfo with the relaxation status and slack column indices. Converts to bool (true iff relaxed) for backward compatibility.

std::optional<double> gtopt::remaining_time_limit(std::optional<double> time_limit, double elapsed_s) noexcept

Remaining wall-clock budget of time_limit after elapsed_s seconds.

std::nullopt when no limit is set (unset or <= 0 ⇒ unlimited); otherwise time_limit - elapsed_s, which may be zero or negative once the budget is exhausted.

std::string gtopt::removed_cut_sharing_mode_message(std::string_view name)

Error text for a removed cut-sharing mode name — shared by the JSON ingestion path (json_sddp_options.hpp) and parse_cut_sharing_mode so every entry point reports the same diagnosis.

bool gtopt::require_bool(std::string_view option_name, std::string_view value)

Parse a boolean option value by name; throw on invalid input.

Parameters
option_name Human-readable option name (for the error message).
value The string supplied by the user.
Returns The parsed boolean.
Exceptions
std::invalid_argument if value is not a recognised boolean.

The bool sibling of require_enum, for the many non-enum boolean options (crossover, presolve, …). Accepts (ASCII case-insensitive) true/false, with 1/0 as numeric aliases. Rejecting anything else is the point: a hand-rolled value == "true" silently maps a typo ("flase", "ture", capitalised "False" under a case-sensitive check) to false, so a mis-spelled CLI / --set / config flag fails open instead of erroring.

template<NamedEnum E>
E gtopt::require_enum(std::string_view option_name, std::string_view value)

Look up a NamedEnum value by name; throw on invalid input.

Template parameters
E A type satisfying the NamedEnum concept.
Parameters
option_name Human-readable option name (for the error message).
value The string supplied by the user.
Returns The matching enumerator.
Exceptions
std::invalid_argument if value does not match any entry.

Builds a user-friendly error message listing all valid names when the lookup fails. Intended for CLI / config-file option parsing where an invalid value should be a hard error.

template<typename U>
U gtopt::require_sid(const std::optional<U>& opt, std::string_view caller, std::string_view field)

Throw std::logic_error if opt has no value, otherwise return *opt.

Used by element-LP wrappers to convert an optional foreign-key field (e.g. Turbine::waterway) into a strong SId without silent UB when the field was unset. The previous form (assert(opt.has_value()); *opt) compiled out in release, leaving *opt on a disengaged optional — silent UB. This helper makes the precondition violation visible.

MonthType gtopt::require_stage_month(const StageLP& stage, std::string_view consumer_kind, std::string_view consumer_id, std::string_view feature)

Assert that a stage carries a calendar month, or throw.

Parameters
stage The active stage.
consumer_kind Short name of the element kind requesting the month (e.g. "VolumeRight", "UserConstraint").
consumer_id Identifier of the consuming element — usually its uid or name — included in the error for pinpointing.
feature Short description of the feature that needs the month (e.g. "reset_month", "monthly parameter lookup").
Returns The resolved MonthType.
Exceptions
std::runtime_error if stage.month() is nullopt.

Used by LP primitives whose behaviour depends on stage.month (reset months, monthly parameter lookups, stage_month bound-rule axes). A missing month is a schema bug in the caller's simulation definition; we refuse to silently degrade.

void gtopt::reset_compression_stats() noexcept

Reset all per-codec accumulators to zero. Useful between runs in a long-lived process (e.g. cascade levels) to attribute stats per level.

void gtopt::reset_default_swap_gate() noexcept

Restore the built-in swap-gate defaults (2048 MB / 64 MB).

ApertureChunkResolution gtopt::resolve_aperture_chunk(std::optional<ApertureChunkMode> mode, int size, int max_apertures_per_phase, int n_active_scenes, int n_physical_cores, double parallel_factor = 2.0) noexcept

Resolve the backward-pass aperture grouping from the user-facing aperture_chunk_mode (optional) and aperture_chunk_size (0 = unset).

Explicit mode:

  • per_scene → K = A_max. A size other than 0 / -1 is ignored (size_ignored).
  • per_aperture → K = 1. A size other than 0 / 1 is ignored.
  • chunked → K = size clamped to [1, A_max]; size 0 (unset) or < -1 → auto formula (auto_size, the latter also invalid_size); size -1 contradicts and is treated as K = A_max (size_ignored).

Mode unset (legacy integer encoding, kept for back-compat):

  • size 0 (unset / "auto") → per_scene (the default), silent.
  • size -1 → per_scene + legacy_size.
  • size 1 → per_aperture + legacy_size.
  • size K > 1 → chunked K + legacy_size.
  • size < -1 → per_scene + invalid_size.

OptName gtopt::resolve_aperture_system_file(const OptName& phase_file, const OptName& global_file) noexcept

Resolve which aperture-system file applies, given the per-phase override and the already-resolved global default (the cascade-level tier is folded into global_file upstream, e.g. by CascadePlanningMethod). An empty string is treated as "unset" so a blank JSON value never shadows the global. Returns an empty OptName when no aperture system applies — the backward pass then falls back to the regular forward system.

Resolution order realised here: phase_file (highest) → global_file.

template<typename VolumeGetter>
Real gtopt::resolve_bound_rule_axis_value(const RightBoundRule& rule, const std::optional<MonthType>& stage_month, VolumeGetter&& volume_getter)

Resolve the rule's input value by axis dispatch.

Parameters
rule The configured rule.
stage_month Active stage's calendar month, when set.
volume_getter Callable returning the reservoir volume in hm³. Invoked only when the axis is reservoir_volume, so the caller can defer any expensive lookup work behind it.
Returns The numeric input to feed into evaluate_bound_rule.
Exceptions
std::runtime_error when rule.axis == stage_month and the active stage has no calendar month assigned. The previous silent 0.0 fallback produced a wrong but feasible LP that was nearly impossible to diagnose from the output; we now fail loudly and tell the caller exactly how to fix the Simulation definition.

Each axis is sourced differently and the call sites in FlowRightLP / VolumeRightLP should not have to know about the dispatch table. The reservoir-volume axis pulls from a caller-supplied callable so this header stays free of SystemContext coupling.

ResolveColResult gtopt::resolve_col_to_row(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const ElementRef& ref, double base_coeff, SparseRow& row, const LinearProblem& lp, AmplResolveCache* resolve_cache = nullptr)

Resolve an ElementRef into one or more SparseRow entries.

Parameters
sc System context holding the AMPL element registry.
scenario Scenario of the (scenario, stage, block) cell.
stage Stage of the cell.
block Block of the cell.
ref Element reference (type, id, attribute) to resolve.
base_coeff The outer coefficient of the constraint term; each emitted entry contributes base_coeff * leg_coeff.
row Row that receives the resolved column entries.
lp Linear problem the resolved columns belong to.
resolve_cache Optional per-build lookup cache (may be null).
Returns {emitted, offset_shift, element_known} — see ResolveColResult.

Unlike resolve_single_col, this helper is compound-aware: when the referenced attribute is a registered PAMPL compound (e.g. line.flow → flowp − flown), each leg is looked up and added to row with the appropriate scaled coefficient. Ordinary single-column attributes resolve to exactly one entry.

std::optional<std::span<const Aperture>> gtopt::resolve_effective_apertures(std::span<const Aperture> aperture_defs, std::span<const ScenarioLP> all_scenarios, const std::optional<Array<Uid>>& requested_uids, Array<Aperture>& owned, std::string_view log_tag)

Parameters
aperture_defs All aperture definitions from the simulation.
all_scenarios All scenario LP objects (used to build a synthetic aperture list when no aperture_array).
requested_uids Per-phase aperture UID set (may be empty std::nullopt to mean "use everything").
owned Output storage for filtered / synthetic apertures. Must be empty on entry. The returned span may reference this buffer.
log_tag Caller tag for the "requested UID not found" warning (e.g. "BackwardPass[i3 s1 p7]").
Returns Span over the effective apertures, or std::nullopt to tell the caller to fall back to the non-aperture path.

Resolve the effective aperture definitions for a single backward-pass step.

Centralises the four-way decision used by both backward_pass_with_apertures (loop) and backward_pass_with_apertures_single_phase (single-phase dispatcher):

  1. requested_uids is empty (std::nullopt):
    • if aperture_defs is also empty → std::nullopt (caller falls back to the non-aperture backward path),
    • otherwise → return a span over aperture_defs unchanged.
  2. requested_uids is present:
    • if the requested list is empty → std::nullopt (fallback),
    • if aperture_defs is non-empty → filter aperture_defs by UID into owned (warning emitted for any requested UID not found),
    • if aperture_defs is empty → build a synthetic aperture list from all_scenarios (one per scenario, sized to min(|requested|, |all_scenarios|)).
  3. If after filtering / synthesis owned is still empty → std::nullopt (fallback).

The returned span aliases either the original aperture_defs span or the caller-provided owned storage; the caller must keep both alive for the lifetime of the returned span.

template<std::ranges::input_range Range, typename Proj = std::identity>
std::optional<Uid> gtopt::resolve_emission_uid(const SingleId& ref, const Range& emissions, Proj proj = {})

Resolve an Emission reference (uid or name) to its uid.

A Uid reference is returned as-is; a Name reference is looked up in emissions (any range whose elements project — via proj — to const Emission&). Returns nullopt for an unknown name.

template<typename Segment>
FailSegmentWidths gtopt::resolve_fail_segment_widths(std::span<const Segment> segments)

Resolve segment widths: explicit fractions are clipped so the cumulative sum never exceeds 1; an open last segment takes the residual; firm = 1 − Σ widths (≥ 0).

SolverOptions gtopt::resolve_forward_solver_options(SolverOptions fwd, bool explicit_options, bool duals_feed_cuts, BasisCrossMode basis_mode) noexcept

Parameters
fwd forward options (explicit or the base LP ones)
explicit_options forward_solver_options was given
duals_feed_cuts the backward pass builds cuts from the forward duals (no aperture set resolves)
basis_mode effective basis_cross_mode

Resolve the forward-pass solver options (see the file comment).

std::expected<void, Error> gtopt::resolve_future_cost_aliases(Planning& planning)

Fold the deprecated boundary-cut keys of planning into its FutureCost element (see the file comment for the full mapping and rules).

std::string gtopt::resolve_future_cost_path(const PlanningLP& planning_lp, const std::string& path)

Resolve a boundary-cut file path the same way for every method: an absolute path is returned unchanged; a relative one is joined onto options.input_directory. Empty stays empty.

std::filesystem::path gtopt::resolve_in_runpath(std::string_view soname, const std::vector<std::string>& runpath, const std::filesystem::path& origin)

Where the dynamic loader would find soname following runpath ($ORIGIN / ${ORIGIN} expanded to origin). First existing candidate, or "" when the runpath does not provide it.

KappaMode gtopt::resolve_kappa_mode(std::optional<KappaMode> opts_mode)

opts_mode if set, else default_kappa_mode().

std::filesystem::path gtopt::resolve_log_directory(const MainOptions& opts)

Resolve the directory that receives gtopt_N.log / trace_N.log, before the planning JSON is fully parsed.

Precedence (same as the solver-side PlanningOptionsLP::log_directory after configure_planning):

  1. CLI --log-directory (opts.log_directory);
  2. --set log_directory=<dir>;
  3. options.log_directory in the planning JSON (later files win);
  4. <output_directory>/logs, where output_directory is CLI --output-directory > --set output_directory > JSON > "output"; a command-line value (flag or --set) is relative to the CWD, a relative JSON / default value is anchored at the first planning file's parent directory.

Explicit log directories (1–3) are used verbatim (CWD-relative). Does not create the directory. Expects opts to have gone through resolve_planning_args (directory arguments expanded).

std::expected<MainOptions, std::string> gtopt::resolve_planning_args(MainOptions opts)

Resolve planning file arguments and directory context.

Parameters
opts A copy of the original MainOptions (modified in place).
Returns The resolved MainOptions, or an error string.

See the file-level documentation for the three features implemented.

std::optional<ResolvedCol> gtopt::resolve_single_col(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const ElementRef& ref, const LinearProblem& lp)

Try to look up the LP ColIndex for one element reference.

Returns std::nullopt when the element is not found, the block is not active in the requested (scenario, stage), or the attribute is unknown.

The returned ResolvedCol::scale converts the LP variable to physical units so that the caller can build correctly-scaled constraint rows.

When a column has a non-unit scale stored in SparseCol::scale (set at variable creation time), the scale is retrieved via lp.get_col_scale(col) – providing a uniform mechanism that works for all current and future scaled variables without hardcoding per-element logic.

std::optional<double> gtopt::resolve_single_param(const SystemContext& sc, const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const ElementRef& ref)

Try to look up a data parameter value for one element reference.

Returns std::nullopt when the element is not found or the attribute is not a known parameter. Parameters are fixed data values (not LP columns) such as pmax, gcost, fmax, emin, etc.

For schedule-valued parameters the value is resolved for the given (scenario, stage, block) context. If the schedule has no value for the given context, std::nullopt is returned.

bool gtopt::resolve_solver_param_file(SolverOptions& opts, std::string_view input_directory, std::string_view where)

Resolve param_file in place on one SolverOptions bundle.

A resolved path replaces the stored string (absolute) and is logged at INFO with where as context, naming whether the input_directory copy or the working-directory fallback was used; a file that cannot be found is kept as given and reported at WARN (the plugin will then fail to open it and the solver runs with its defaults). Returns false only in that not-found case; an unset / empty param_file is a successful no-op.

std::optional<std::filesystem::path> gtopt::resolve_solver_param_file(std::string_view file, std::string_view input_directory)

Path-only form of resolve_solver_param_file_source().

std::optional<ResolvedParamFile> gtopt::resolve_solver_param_file_source(std::string_view file, std::string_view input_directory)

Resolve a (possibly relative) solver parameter file, reporting where it was found.

Absolute paths are returned unchanged. A relative path is tried first as input_directory / file (the full relative path, so solvers/cplex.prm maps to <input_directory>/solvers/cplex.prm): the case directory wins. Only when that file does not exist is the path tried relative to the current working directory. The first candidate that exists is returned in absolute form; std::nullopt when neither exists.

int gtopt::resolve_solver_param_files(PlanningOptions& options)

Resolve param_file on every SolverOptions bundle carried by options: the global solver_options, the monolithic and MIP-start relaxation overrides, and the SDDP forward / backward overrides (both the top-level sddp_options and the cascade's global sddp_options). Returns the number of param files that could not be found.

void gtopt::resolve_solver_setup(Planning& planning, const MainOptions& opts)

Resolve the solver the run will use and apply its configuration to planning: pin the effective solver name (--solver > planning pin > GTOPT_SOLVER / plugin priority) on planning.options.lp_matrix_options.solver_name, overlay the .gtopt.conf [solver.<name>] section under solver_options, and auto-discover <input_directory>/solvers/<name>.prm into solver_options.param_file when unset. Idempotent; gtopt_main runs it before writing the pre-solve snapshot (gtopt_state.json) so the snapshot records the solver and the resolved parameter file.

std::filesystem::path gtopt::resolve_system_file(std::string_view file, const std::string& input_directory)

Resolve a relative file path the way parse_planning_files resolves planning JSONs: try the path as given (relative to CWD) first, then fall back to input_directory / filename. Absolute paths are used as-is. Returns the best candidate; the caller surfaces a clear error if it does not exist.

std::string_view gtopt::risk_measure_csv_header() noexcept

Header of risk_measure.csv (trailing newline included).

std::string gtopt::risk_measure_csv_line(int scene_uid, int phase_uid, double eta, const CvarLayout& layout, const CvarScenarioResult& r)

One risk_measure.csv line.

std::map<std::string, int> gtopt::row_families(const LinearInterface& li, std::span<const int> rows)

Group rows by their label family (class:constraint), for logging. Rows without a label land in "unlabeled".

template<std::ranges::sized_range R>
RowIndex gtopt::row_index_size(const R& r) noexcept

Build a RowIndex from the size of any sized range. Mirror of col_index_size() — see that helper for rationale.

std::string gtopt::run_check_json_info(const std::vector<std::string>& json_files, int timeout_seconds = 30)

Run gtopt_check_json --info on one or more JSON files and return the captured output.

Parameters
json_files List of planning JSON file stems/paths.
timeout_seconds Maximum execution time in seconds (default: 30).
Returns Captured output, or an empty string if the tool is unavailable.

Looks for the gtopt_check_json binary like run_check_lp_diagnostic(). If found, spawns it directly (without invoking a shell) via posix_spawn with:

gtopt_check_json --info --no-color <file1.json> [<file2.json> ...]

stdout and stderr are captured and returned as a string so the caller can forward every line through the spdlog INFO stream (instead of writing directly to the terminal). An optional timeout wrapper prevents indefinite hangs.

std::string gtopt::run_check_lp_diagnostic(const std::string& lp_file, int timeout_seconds = 10, const SolverOptions& solver_opts = {})

Run gtopt_check_lp on an LP file and return the diagnostic output.

Parameters
lp_file Full path to the LP file (may include or omit the .lp extension).
timeout_seconds Maximum execution time in seconds (default: 10).
solver_opts Solver options to forward to gtopt_check_lp so the diagnostic replicates the same algorithm and tolerance settings used by gtopt. Default-constructs to algorithm=barrier with no tolerance overrides.
Returns Captured diagnostic output, or an empty string if unavailable.

Looks for the gtopt_check_lp binary next to the gtopt executable, then on the absolute, non-world-writable PATH entries (find_trusted_executable()). If found, spawns it directly (without invoking a shell) via posix_spawn with:

gtopt_check_lp --quiet --no-color --no-ai --timeout <timeout_seconds>
                [--algo <algo>]
                [--optimal-eps <v>] [--feasible-eps <v>]
                [--barrier-eps <v>]
                <lp_file>

If the binary is not on PATH or the file does not exist, an empty string is returned so callers can skip logging silently.

The --quiet flag ensures the child process never stalls waiting for input and always exits with code 0, even when no solver is available or NEOS is unreachable.

int gtopt::run_check_solvers_command(std::string_view solver, bool verbose, std::ostream& out, std::ostream& err)

Returns 0 when every test passes, 1 otherwise.

--check-solvers [NAME]: run the solver self-test suite. An empty solver runs every available solver; an unknown one is reported on err.

SolverTestResult gtopt::run_one_solver_test(std::string_view solver_name, std::string_view test_name)

Run ONE named test against ONE solver.

Parameters
solver_name Solver identifier (e.g. "clp", "mindopt").
test_name Test entry name (e.g. "add_rows", "add_cols").
Returns Result for the named test, or a failure result with name == test_name and a "test '<name>' not found" detail when the name is not registered.

Looks up test_name in the internal test-function table and invokes the matching SolverTestResult test_<name>(std::string_view) shim. Catches any exception and reports it as a failure. Used by the per-(solver, test) doctest split in test_check_solvers.cpp to avoid the full suite re-run that run_solver_tests does — a single-test call should take ~50 ms vs ~5 s for the full per-solver suite.

SolverTestReport gtopt::run_solver_tests(std::string_view solver_name, bool verbose = false)

Run the full LinearInterface test suite against solver_name.

Parameters
solver_name Solver identifier understood by SolverRegistry (e.g. "clp", "cbc", "highs").
verbose When true, print each test name as it executes to stdout (useful when running from a terminal).
Returns Aggregated pass/fail for all test cases.

The test suite covers:

  • construction (default, by-name, from FlatLinearProblem)
  • problem-name get/set
  • add_col / add_row / delete_rows
  • set/get objective coefficients, column bounds, row bounds
  • get_coeff / set_coeff (skipped when !supports_set_coeff())
  • set_continuous / set_integer / is_continuous / is_integer
  • LP names and name maps (row_name_map, col_name_map)
  • load_flat from FlatLinearProblem
  • initial_solve with all LPAlgo variants (default, primal, dual, barrier)
  • get_obj_value / get_col_sol / get_row_dual / get_col_cost
  • is_optimal / is_prim_infeasible / is_dual_infeasible
  • get_kappa
  • resolve (warm re-solve after bound tightening)
  • clone (deep copy; independent solve)
  • set_warm_start_solution
  • save_base_numrows / reset_from
  • lp_stats_* fields after load_flat
  • write_lp (creates a temp file and verifies creation)

template<std::ranges::input_range Range, typename Proj = std::identity>
bool gtopt::same_emission(const SingleId& lhs, const SingleId& rhs, const Range& emissions, Proj proj = {})

Name-or-uid equality of two Emission references.

EmissionZone.emissions[].emission, EmissionSource.emission, Fuel.emission_factors[].emission and Generator.emission_captures[].emission may each name the pollutant by uid OR by name; a plain SingleId comparison would treat Uid{1} and "co2" as different pollutants even when they denote the same Emission row. Both sides are resolved against emissions; identical references compare equal even when they cannot be resolved.

SceneIndex gtopt::sample_forward_realization(const SimulationLP& sim, IterationIndex iteration_index, SceneIndex scene_index, PhaseIndex phase_index) noexcept

SimulationLP-facing wrapper over sample_weighted_index: draws a SCENE index with probability proportional to each scene's probability_factor (sum of its scenarios'), keyed on (iteration_index, scene_index, phase_index). Consumed by the forward pass under ForwardSamplingMode::resampled; single-scene simulations always return scene 0.

std::size_t gtopt::sample_weighted_index(std::span<const double> weights, std::uint64_t iteration, std::uint64_t scene, std::uint64_t phase) noexcept

Deterministic probability-weighted index draw for the forward-pass resampling (ForwardSamplingMode::resampled).

Pure function of (weights, iteration, scene, phase) — a splitmix64 hash chain mapped through the normalized weight CDF — deliberately NOT a <random> engine/distribution pair, whose output is implementation-defined across standard libraries: the sampled path must be bit-reproducible everywhere, stable under forward-pass BACKTRACKING (re-entering the same (iteration, scene, phase) re-draws the SAME realization) and independent of thread scheduling.

Degenerate inputs: an empty span returns 0; a non-positive total weight falls back to a uniform draw over weights.size(). Negative entries are clamped to 0.

std::expected<void, Error> gtopt::save_basis(const std::filesystem::path& path, const Basis& basis)

Returns empty on success, or a FileIOError if the file cannot be written.

Serialize basis to path in the binary layout documented above.

std::expected<void, Error> gtopt::save_cascade_progress(const CascadeProgress& progress, const std::filesystem::path& path)

Persist cascade_progress.json atomically: writes <path>.tmp then std::filesystem::rename(tmp, path). POSIX rename is atomic — the file is either the previous good state or the new good state, never a partial mix.

std::expected<void, Error> gtopt::save_cuts_parquet(std::span<const StoredCut> cuts, const PlanningLP& planning_lp, const std::string& filepath, bool append_mode = false)

Save accumulated cuts to a Parquet file with typed schema.

std::expected<void, Error> gtopt::save_scene_cuts_parquet(std::span<const StoredCut> cuts, SceneIndex scene_index, SceneUid scene_uid, const PlanningLP& planning_lp, const std::string& directory)

Save cuts for a single scene to a per-scene Parquet file.

BoundEnvelopeReport gtopt::scan_bound_envelope(std::span<const double> collb, std::span<const double> colub, std::span<const double> rowlb, std::span<const double> rowub, double infinity, double large_bound) noexcept

Pure LP_QUALITY scan over the post-flatten bound vectors: counts FREE columns (both bounds at the ±infinity sentinel — no box for a first-order solver to project onto) and large-but-finite (|b| >= large_bound) column/row bounds, keeping the first offender of each kind. Extracted from LinearProblem::flatten() so the classification is unit-testable without building an LP; the caller owns the logging.

std::vector<double> gtopt::scene_probability_masses(const SimulationLP& sim)

Per-scene probability mass p_s — THE single derivation shared by the M4/MK1 pricing (alpha_col_weights → alpha_unit_cost / markov_alpha_weights) and the resampled forward draw (sample_forward_realization).

Rule: mass_s = max(SceneLP::probability_factor(), 0) — negative data is clamped to 0 — and when EVERY scene is degenerate (total ≤ 0) the whole vector falls back to all-ones (uniform). A single zero-mass scene among positive ones stays 0: it must never be sampled and its folded objective contributes 0. (compute_scene_weights keeps its own per-scene feasibility layer on top of raw probabilities — that path masks infeasible scenes, which this pure mass derivation has no business knowing about.)

std::optional<std::vector<double>> gtopt::scip_repair_candidate(MipStartContext& ctx, std::vector<double> candidate)

Optional SCIP repair STAGE (stage 3 of the pipeline) — composable with any base method and any active solver via mip_start.scip_repair=true. Build a SCIP backend from ctx.flat_lp, hand it the candidate commitment through set_mip_start(repair) (→ the SCIP plugin's completesol/repair), and return the candidate with SCIP's repaired integer columns overlaid. Returns std::nullopt (caller keeps the pre-SCIP candidate) when the SCIP plugin or the flat LP is absent, or SCIP finds nothing feasible. Defined in mip_start_scip.cpp — the core links no SCIP headers.

int gtopt::scope_granularity(ConstraintScope scope) noexcept

Granularity rank of a COARSE scope on the shared TimeWindow scale (SMALLER is FINER). Block returns a sentinel -1 (finer than every window) so the per-block path is never flagged as lossy.

bool gtopt::scope_is_planning(ConstraintScope scope) noexcept

True iff scope routes through the planning passes (add_to_phase_lp / add_to_global_lp) rather than the per-block / per-stage operational add_to_lp.

std::string_view gtopt::scope_name(ConstraintScope scope) noexcept

Human-readable spelling of a ConstraintScope for diagnostics.

bool gtopt::sddp_gap_converged(double gap, double convergence_tol) noexcept

Primary gap convergence predicate: gap lies inside the converged band (-kSddpGapFpEpsilon, convergence_tol).

The band is one-sided on purpose: a gap at or below -kSddpGapFpEpsilon means LB > UB beyond rounding noise, i.e. the cuts overshoot the optimum, and must not be read as "converged" (otherwise every large negative gap, e.g. -11.84, would satisfy gap < convergence_tol). A negative convergence_tol empties the band and so disables the gap test.

SDDPLogTag gtopt::sddp_log(std::string_view tag, IterationUid iteration_uid) noexcept

"SDDP Init [i1]" — iteration-level only.

SDDPLogTag gtopt::sddp_log(std::string_view tag, IterationUid iteration_uid, SceneUid scene_uid) noexcept

"SDDP Forward [i1 s1]" — scene-level (no phase).

SDDPLogTag gtopt::sddp_log(std::string_view tag, IterationUid iteration_uid, SceneUid scene_uid, PhaseUid phase_uid) noexcept

"SDDP Forward [i1 s1 p2]" — with phase tag and per-phase key. Strict-typed UID-only signature: callers pass IterationUid / SceneUid / PhaseUid (1-based, matching the printed [iN sM pK] format). Passing the matching *Index (0-based, internal) is a compile error — the caller must convert via gtopt::uid_of(...) at the call site, mirroring the SPDLOG_*("...[i{}]…", gtopt::uid_of(iteration_index), ...) pattern used everywhere else in the SDDP code (see PR #459).

SDDPLogTag gtopt::sddp_log(std::string_view tag, IterationUid iteration_uid, SceneUid scene_uid, PhaseUid phase_uid, Uid aperture_uid) noexcept

"SDDP Aperture [i1 s1 p2 a5]" — with aperture uid appended.

std::uint64_t gtopt::seed_commitment_key(Uid gen_uid, Uid block_uid) noexcept

Pack a (generator uid, block uid) pair into the SeedCommitmentMap key. Both uids are int32; cast through uint32 so a negative sentinel keeps a stable bit pattern rather than sign-extending across the two halves.

std::vector<Uid> gtopt::select_apertures(std::span<const Uid> phase_apertures, const std::optional<int>& num_apertures, ApertureSelectionMode mode = ApertureSelectionMode::head)

Parameters
phase_apertures Per-phase aperture UIDs (assumed wettest-first).
num_apertures SDDPOptions::num_apertures value to apply.
mode Selection rule (head | stride; default head).
Returns Owned vector of selected UIDs (preserves input order in head mode; stride mode walks indices in ascending order so wetness order is preserved within the picks).

Select a subset of a per-phase aperture-UID list according to SDDPOptions::num_apertures and aperture_selection_mode.

Phase::apertures is emitted by plp2gtopt sorted wettest → driest; this helper produces the effective per-phase list the backward pass will actually solve for.

Semantics:

  • num_apertures = nullopt → return a copy of the full input.
  • num_apertures = 0 → return an empty vector.
  • num_apertures = N ≥ size() → return a copy of the full input.
  • num_apertures = N > 0 with:
    • mode = head → phase_apertures.first(N) (N wettest).
    • mode = stride → N entries at indices i*size/N, i = 0..N-1 (evenly spaced across the full ordered list — wettest is still index 0, last pick is near driest).
    • mode = tail → phase_apertures.last(N) (N driest); mirror of head.

CompressionCodec gtopt::select_codec(CompressionCodec preferred) noexcept

Select the best available codec, preferring the requested one. Falls back to zstd (always available), then none.

ReservoirDischargeLimitCoeffs gtopt::select_rdl_coeffs(const std::vector<ReservoirDischargeLimitSegment>& segments, Real volume) noexcept

Select the active segment and return LP coefficients.

ReservoirSeepageCoeffs gtopt::select_seepage_coeffs(const std::vector<ReservoirSeepageSegment>& segments, Real volume) noexcept

Select the active seepage segment and return LP coefficients.

Parameters
segments The piecewise-linear segments (sorted by volume breakpoint)
volume Current reservoir volume [hm³]
Returns ReservoirSeepageCoeffs with slope and intercept (y-intercept) for the active segment

Implements the PLP range-selection logic (matches Fortran FFiltracionesi): finds the segment i where segments[i].volume ≤ volume < segments[i+1].volume and returns its slope and constant (y-intercept) as LP coefficients.

The LP constraint becomes: filt_flow - slope*0.5*eini - slope*0.5*efin = constant where constant is the y-intercept at V = 0 for the active segment's linear equation: seepage = constant + slope × V.

std::vector<char> gtopt::serialize_labels_meta(const std::vector<SparseColLabel>& labels)

Serialize a vector of column labels into a self-contained byte buffer.

std::vector<char> gtopt::serialize_labels_meta(const std::vector<SparseRowLabel>& labels)

Serialize a vector of row labels into a self-contained byte buffer.

void gtopt::set_cpu_quota_pct(double pct) noexcept

Set the process-global CPU quota as a percentage of physical cores. Values in (0, 100) clamp physical_concurrency() to ceil(detected × pct / 100) (minimum 1). Values outside that range — including 0, negative, NaN, and ≥100 — disable the clamp.

Intended to be called once during CLI parsing, before any pool is constructed. Thread-safe: the underlying state is an atomic load.

void gtopt::set_default_swap_gate(double max_process_swap_mb, double swap_growth_mb) noexcept

Override the process-wide swap-gate defaults for pools created from now on. Negative values are clamped to 0 (max_process_swap_mb == 0 disables the gate; swap_growth_mb == 0 treats ANY net growth as active swapping).

void gtopt::setup_file_logging(const MainOptions& opts, bool suppress_stdout)

Add a <log_dir>/gtopt_N.log file sink to spdlog's default logger.

The log directory comes from resolve_log_directory(opts) (so --set log_directory / JSON options.log_directory are honoured). Creates the directory if needed and attaches a basic_file_sink_mt (truncating) at the current default level so all subsequent spdlog::info/warn/error go to the file.

When suppress_stdout is true, the existing console sinks are removed so log output appears only in the file — this is what the standalone binary uses when stdout is not a TTY (i.e. when piped to run_gtopt, redirected, or run from CI), keeping the calling process's stdout clean and avoiding duplicate-output overhead.

std::string gtopt::sha256_file(const std::filesystem::path& path)

Lowercase hex SHA-256 (FIPS 180-4, as CMake's file(SHA256)) of a file's content; "" when it cannot be read.

std::string gtopt::sha256_hex(std::span<const std::byte> data)

SHA-256 of data as 64 lowercase hex characters.

std::string gtopt::sha256_hex(std::string_view data)

SHA-256 of the bytes of data as 64 lowercase hex characters.

void gtopt::share_cuts_for_phase(PhaseIndex phase_index, const StrongIndexVector<SceneIndex, std::vector<SparseRow>>& scene_cuts, CutSharingMode mode, PlanningLP& planning, IterationIndex iteration_index = IterationIndex {0})

Parameters
phase_index Phase index where cuts will be added
scene_cuts Per-scene optimality cuts for this phase
mode Cut sharing mode (none/accumulate/expected/max)
planning PlanningLP reference (for LP access)
iteration_index Current SDDP iteration; combined with the per-scene UID and phase_index to build a unique LP-row label context for every cut landing in each destination scene's LP (avoids the "metadata without a class_name" labeller throw and the duplicate-label collision when the same accumulated cut is replicated to multiple scenes). Defaults to IterationIndex{0} for callers that legitimately treat a single share-call as iteration 0 (e.g. unit tests that exercise a single iteration).

Share optimality cuts across scenes for a single phase.

std::string gtopt::short_build_id(std::string_view build_id)

First 12 hex digits of a build-id (for compact listings).

double gtopt::shutdown_trajectory_power(const std::vector<double>& traj, double step, double pmin, double delta)

Shut-down trajectory power f^SD(δ) [MW] at δ > 0 hours AFTER the shut-down instant (0 beyond the trajectory); pmin is f^SD(0).

unsigned gtopt::smt_ratio() noexcept

Ratio of logical to physical cores (1 without HT, typically 2 with HT). Returns 1 on detection failure. Always uses detected_physical_concurrency() so a CPU quota does not skew the ratio.

std::string gtopt::snake_case(std::string s)

Returns a snake_case copy of the given string (std::string overload).

Parameters
s An rvalue std::string.
Returns std::string The snake_case form of s.

Eager counterpart of snake_case(T&&). Allocates a fresh std::string sized to the exact output length (via detail::snake_case_size) and writes lowercased characters with synthesised underscores at word boundaries.

Unlike lowercase(std::string) this overload cannot transform in-place because the output is generally longer than the input (one extra character per inserted underscore).

Example: auto lbl = snake_case(as_label("HTTPCode")); // "http_code"

template<detail::string_like T>
SnakeCaseView gtopt::snake_case(T&& sv) noexcept

Returns a lazy, zero-copy snake_case view over a string-like value.

Parameters
sv Any string-like value (string literal, std::string_view, LPClassName, etc.) that is not a std::string rvalue.
Returns SnakeCaseView A lazy view; valid as long as the underlying data lives (same lifetime rules as std::string_view).

Wraps the input as a SnakeCaseView that applies to_lower_char and synthesises word-boundary underscores on each character access. No heap allocation occurs until as_label() (or another consumer) copies the characters out.

std::string_view cn = "GeneratorLP";
auto a = as_label(snake_case(cn), 1, 2); // "generator_lp_1_2"

std::vector<std::size_t> gtopt::snap_period_boundaries(std::span<const double> cells, double period, bool point = true)

Cell indices j after which a new group starts (the group ends at τ_j).

std::string_view gtopt::solution_csv_header(bool with_kappa = true) noexcept

The single source of truth for the CSV column order/names (trailing newline included). Its comma count MUST equal the field count emitted by solution_csv_line; test_solution_csv pins that invariant.

with_kappa = false (kappa_mode = off everywhere) drops the kappa and max_kappa columns: kappa is neither queried nor printed.

std::string gtopt::solution_csv_line(const SolutionRow& row, bool with_kappa = true)

Format one row as a CSV line (trailing newline included), matching the column order of solution_csv_header.

std::string_view gtopt::solution_status_name(int status) noexcept

CLP status-code → human name. Values follow the CLP convention (0=optimal, 1=primal infeasible, 2=dual infeasible/unbounded, 3=iteration limit, 4=error), plus gtopt's 5=limit_polished (see solution_status_limit_polished); anything else (incl. the -1 never-solved sentinel) reports "unknown".

std::optional<SparseRow> gtopt::solve_apertures_for_phase(SceneIndex scene_index, PhaseIndex phase_index, const PhaseStateInfo& src_state, ColIndex src_alpha_col, const ScenarioLP& base_scenario, std::span<const ScenarioLP> all_scenarios, std::span<const Aperture> aperture_defs, std::span<const Uid> phase_apertures, int total_cuts, SystemLP& sys, const PhaseLP& phase_lp, const SolverOptions& opts, const LabelMaker& label_maker, const std::string& log_directory, SceneUid scene_uid_val, PhaseUid phase_uid_val, const ApertureChunkSubmitFunc& submit_fn, double aperture_timeout = 0.0, bool save_aperture_lp = false, const ApertureDataCache& aperture_cache = {}, IterationIndex iteration_index = {}, double cut_coeff_eps = 0.0, LpDebugWriter* lp_debug_writer = nullptr, bool use_manual_clone = false, int chunk_size = 1, class SDDPWorkPool* pool_for_slot_release = nullptr, std::span<const StateVarLink> cut_links = {}, ApertureSolveMode aperture_solve_mode = ApertureSolveMode::reduced_cost, const Basis* seed_basis = nullptr, Basis* captured_basis_out = nullptr, int aperture_screen_count = default_sddp_aperture_screen_count, Basis* last_basis_out = nullptr, ApertureDropTracker* drop_tracker = nullptr)

Parameters
scene_index Scene index (for logging/labelling)
phase_index Target phase being solved
src_state Phase state of the source (previous) phase
src_alpha_col α (future-cost) column of the source phase LP that each aperture cut is built on
base_scenario The scene's base scenario (for flow bound update)
all_scenarios All simulation scenarios (for aperture lookup)
aperture_defs Aperture definitions to use
phase_apertures Per-phase aperture UID set (may be empty)
total_cuts Running cut count (for label uniqueness)
sys SystemLP for the (scene, phase) pair
phase_lp PhaseLP for the target phase
opts Solver options
label_maker Label maker for LP row names
log_directory Directory for debug LP files (empty = no save)
scene_uid_val Scene UID (for logging)
phase_uid_val Phase UID (for logging)
submit_fn Callback to submit an aperture task to the work pool
aperture_timeout Timeout in seconds for each aperture LP solve; 0 = no timeout. When exceeded, the aperture is treated as infeasible and skipped.
save_aperture_lp If true, save each aperture LP to the log directory
aperture_cache Cache of pre-built aperture LP data
iteration_index Current SDDP iteration index
cut_coeff_eps Epsilon below which cut coefficients are zeroed
lp_debug_writer Optional writer. When non-null, each aperture clone's LP is dumped to disk (pre-solve) under the writer's configured directory using sddp_file::debug_aperture_lp_fmt. Lets the lp_debug option extend to aperture backward- pass clones — callers are responsible for applying the lp_debug_scene/phase_min/max filter window and passing nullptr when the current (scene, phase) is outside it.
use_manual_clone If true, each aperture clone is built via LinearInterface::clone_from_flat() (replays the source's FlatLinearProblem snapshot through load_flat() on a fresh backend env). This skips the backend's native clone() and the s_global_clone_mutex — the manual route uses only env-local solver calls, so 80 aperture clones can be built in parallel rather than serialised under the lock. Pre-condition: the source phase LP must hold a decompressed FlatLinearProblem snapshot. When false (default), the legacy native route is used, serialising every clone under the global mutex.
chunk_size Apertures per submitted task (chunked backward pass). >=2 enables the chunked path: every chunk becomes ONE work-pool task that clones the phase LP once and solves its inner apertures sequentially with warm- start reuse on the shared clone. Bound-only deltas keep the dual basis valid, so the second-and-later resolves typically converge in a fraction of a cold barrier. A per-chunk UID memo collapses adjacent duplicate apertures (the wetness sort applied in plp2gtopt keeps duplicates adjacent) to a single solve + N-fold weight. <=1 falls back to the legacy 1-aperture-per- task path (each chunk is a 1-element vector); the call site sees identical externally-observable behaviour.
pool_for_slot_release Optional work-pool reference used to grab a SlotReleaseGuard around the chunk-future gather loop. When non-null AND the caller is itself running on a worker thread of this pool, the guard temporarily releases the calling task's slot for the duration of the blocking wait, so the pool's CPU/thread gate sees one fewer active task and can dispatch the chunk tasks the caller is about to wait on. Without this, the cell-task block + CPU-gate combo wedges the pool — see the 2026-05-16 concurrency audit and work_pool.hpp:732-797 for the rationale. Defaults to nullptr (no slot release) for the in-tree unit-test callers that drive solve_apertures_for_phase without a live pool.
cut_links Optional override for the state-variable links used to BUILD each aperture cut. When non-empty it replaces src_state.outgoing_links in build_benders_cut_physical. The aperture-system path passes "hybrid" links: source_col/state_var from the forward source phase (so the cut installs onto the forward LP) but dependent_col pointing into the aperture clone (so the reduced cost is read from the matching column). Empty = use src_state.outgoing_links (the regular single-system path). Referenced storage must outlive the call (the caller's vector) — the chunk tasks read it while solving.
aperture_solve_mode Aperture solve / cut-recovery mode. cold: cold barrier + crossover per aperture. warm: first aperture in a chunk seeds a basis and subsequent apertures warm-start off it with a simplex re-solve (SolverOptions::advanced_basis; chunk_size > 1 only). reduced_cost (default): cold barrier without crossover, cut from interior-point reduced costs. dual_shared: solve the highest-weight representative aperture only and synthesize every other aperture's cut from its vertex duals (bound-delta intercept correction, dual_shared_bound_correction); forces a single chunk. screened: dual_shared + exact re-solve of the top aperture_screen_count synthesized cuts by |correction|. See ApertureSolveMode.
seed_basis Cross-iteration first-aperture warm-start seed (in): the previous iteration's first-aperture basis for this cell, or nullptr/empty to disable seeding. Each chunk's first solve is dual-warm-started from it (reconciled to the current dimensions). Read-only during parallel execution. Honoured for every basis-capable (vertex) mode — all modes except reduced_cost, which has no basis to capture.
captured_basis_out (out) When non-null, the basis of THIS iteration's first aperture (first chunk) is written here after the chunk futures join, for the caller to persist into the cell slot. Same mode restriction as seed_basis; both default off (legacy cold first solve).
aperture_screen_count Number of dual-shared cuts re-solved exactly under aperture_solve_mode = screened (largest |intercept correction| first). Ignored by every other mode. Both production call sites pass the resolved option; the default is the shared default_sddp_aperture_screen_count constant (sddp_enums.hpp).
last_basis_out (out) When non-null, the optimal basis left resident by the first chunk's LAST successful solve is written here after the futures join. It already prices this iteration's cuts on α, so it is a far better seed for the next forward solve of the cell than that cell's own previous forward basis. Unset ⇒ not captured.
drop_tracker Optional cross-iteration record of dropped (infeasible / timed-out) apertures. When non-null every drop of this cell is recorded under (scene_uid_val, phase_uid_val, iteration_index); the tracker escalates one "persistent aperture infeasibility" warning per triple and feeds the per-iteration drop count that blocks SDDP convergence. nullptr (unit-test callers) keeps the legacy per-cell warning only.

Solve all apertures for a single phase and return the expected cut.

For each effective aperture: clones the phase LP, updates flow column bounds to the aperture's source scenario, solves the clone, and builds a Benders cut from the reduced costs. The probability-weighted average of all feasible aperture cuts is returned as the expected cut.

Returns std::nullopt if all apertures are infeasible or skipped.

< physical reduced costs d_j

< physical col lower bounds

< physical col upper bounds

< representative's built cut

< index into results

< index into prepared

< intercept correction (for |corr| ranking)

std::vector<double> gtopt::solve_elastic_lp(LinearInterface& li, std::span<const int> int_cols, std::span<const double> candidate, double penalty, const SolverOptions& opts)

Returns the raw primal of the elastic LP, or empty on failure.

Elastic LP: keep integrality relaxed, add penalty · |x_j − candidate_j| for every integer column at a bound in the candidate (as a linear objective term toward that bound) to the original objective, solve, and restore the objective. penalty <= 0 solves a PURE feasibility LP instead (original costs zeroed, unit deviation weights) — the default: better conditioned, and primal feasible from the relaxation basis.

FixedLpResult gtopt::solve_fixed_integer_lp(LinearInterface& li, std::span<const int> int_cols, std::span<const double> candidate, const SolverOptions& opts)

Fix every int_cols column of li to round(candidate[j]) (clamped to its bounds), solve the continuous LP with opts, and restore the original bounds. Precondition: integrality is RELAXED on li.

std::expected<InvestmentMasterResult, Error> gtopt::solve_investment_master(const Planning& planning, const InvestmentMasterOptions& opts)

Parameters
planning Operational planning with expansion candidates.
opts Loop / SDDP / solver options.
Returns The converged (or capped) master result, or an Error if the master LP or an operational SDDP run failed.

Run the OptGen-style investment-master Benders loop on planning.

The input Planning supplies the operational model AND the expansion candidates; it is copied for each oracle run (with expmod pinned to the current master proposal) so the caller's object is never mutated.

template<typename SystemLPT>
std::optional<Real> gtopt::solved_stage_state(const SystemLPT& sys, const ScenarioLP& scenario, const StageLP& stage, LPClassName class_name, Uid uid, std::string_view col_name, std::optional<ColIndex> local_col = std::nullopt)

Physical value of a state column at the END of stage (a storage's efin) as produced by the last solve of the LP that owns stage.

Resolution order:

  1. The column's StateVariable (col_sol_physical()), written by SDDPMethod::capture_state_variable_values after EVERY forward solve, for every stage of the phase. It lives in the simulation registry, so it survives release_backend(), a compress reconstruct and any LP mutation — it is the same value under every LowMemoryMode. Only used once a solve has written it (has_col_sol()), so a genuine 0 is not mistaken for "unset".
  2. local_col of this LP when the LP is optimal (monolithic and other non-SDDP paths; elements without a registered state variable, e.g. daily-cycle reservoirs).
  3. nullopt — no solved value exists. Callers decide the initial estimate through initial_state_fallback, never silently.

Before this helper the readers tried (2) only and substituted the case eini otherwise. Under --memory-saving compress the LI's optimal flag and solution cache are cleared by the first mutation after a solve (propagate_trial_values pins the eini column right before update_lp_for_phase; backward cut rows; a reconstruct), so every update_lp read fell back to the case eini while off read the live backend: a volume rule saw (v0 + eini) / 2 instead of the stage's own trajectory and the two modes diverged.

std::string gtopt::solver_allow_unpinned_env(std::string_view solver)

Environment variable that lets a solver whose runtime library is not the pinned release load with a warning: GTOPT_<SOLVER>_ALLOW_UNPINNED (solver name upper-cased, e.g. GTOPT_HIGHS_ALLOW_UNPINNED).

bool gtopt::solver_allow_unpinned_from_env(std::string_view solver)

True when $GTOPT_<SOLVER>_ALLOW_UNPINNED is set to a true value (an unparsable value logs a warning and counts as false).

bool gtopt::solver_fallback_on_refused_from_env()

True when $GTOPT_SOLVER_FALLBACK_ON_REFUSED is true (an unparsable value logs a warning and counts as false).

std::vector<std::string> gtopt::solver_load_errors(std::string_view solver_name, const std::vector<std::string>& load_errors)

Load errors that concern solver_name: those naming Solver '<name>' (library version / pin / shadowing refusals) or its plugin file libgtopt_solver_<name> (build-id, build tag, dlopen, ABI).

std::string gtopt::solver_unavailable_message(std::string_view solver_name, const std::vector<std::string>& available, const std::vector<std::string>& load_errors)

Error text for a solver that was requested by name but is not available: names it, lists why its plugin was refused (from load_errors, see solver_load_errors()) and the solvers available instead. An explicit request never falls back to another solver.

char*const* gtopt::spawn_environment() noexcept

Environment block for posix_spawn (the current process environment).

void gtopt::split_config_defaults(MainOptions& opts, const MainOptions& conf)

Split config-file values into runtime-only fields and the planning-level defaults layer.

Implements the documented precedence CLI flag > --set > planning JSON > .gtopt.conf > default:

  • keys with no planning-JSON counterpart (lp-file, lp-format, matrix-eps, json-file, stats, trace-log, async-logger) and the [solver.<name>] sections are merged into opts only where the CLI left them unset (merge_config_defaults semantics; the [solver.<name>] values are later overlaid UNDER the planning solver_options, see prepare_matrix_options);
  • every other key is stored in opts.config_defaults and applied by apply_config_file_defaults() to the options the planning JSON left unset, before --set and the CLI flags.

LpFileTarget gtopt::split_lp_file_target(std::string filename, LpFileFormat requested = LpFileFormat::lp)

Split a --lp-file value. A trailing .mps selects MPS (overriding requested); a trailing .lp is stripped and requested is kept. Backends append the extension themselves, so it is always removed.

std::span<const Block> gtopt::stage_block_span(std::span<const Block> block_array, const Stage& stage)

The blocks of stage inside block_array. Throws std::out_of_range (naming the stage) when first_block / count_block do not fit in the array, so malformed input can never read out of bounds even when validate_planning was skipped.

double gtopt::startup_trajectory_power(const std::vector<double>& traj, double step, double pmin, double delta)

Start-up trajectory power f^SU(δ) [MW] at δ > 0 hours BEFORE the start instant (0 beyond the trajectory); pmin is f^SU(0).

template<typename StorageElement>
bool gtopt::storage_carries_state(const StorageElement& element, StorageStateDefaults defaults) noexcept

Effective use_state_variable of a storage element — the same rule as StorageLP::add_to_lp (daily_cycle ? false : use_state_variable). Elements without a daily_cycle field use the class default.

void gtopt::strip_cr(std::string& s) noexcept

Strip trailing carriage-return left by std::getline on DOS text files.

template<typename Pool, typename Func>
std::future<std::invoke_result_t<Func&>> gtopt::submit_or_run_inline(Pool& pool, Func&& func, const typename Pool::Requirements& req = {}, std::string_view refusal_warning = {})

Submit func to pool; when the pool refuses it (shutdown or enqueue failure) run it inline on the calling thread instead, so no unit of work is silently dropped and the caller always holds a valid future. A task exception, pooled or inline, is delivered through the returned future (never thrown from here), so a get_all_futures drain still joins every sibling before anything propagates. refusal_warning, when non-empty, is logged at WARN on the inline fallback. func must be copyable: the pool stores a copy and the original stays callable for the fallback.

void gtopt::switch_to_sync_default_logger()

Swap the default logger back to a synchronous one.

Reverses install_async_default_logger(): rebuilds the default logger as a plain spdlog::logger wrapping the same sinks, with the same level. Useful when the caller decides — after CLI parsing — that the run should NOT use the async wrapper, e.g.:

  • --no-async-logger / --async-logger=false was passed.
  • --trace-log / -T was passed: every trace line must land on disk, so we avoid the bounded queue's overrun_oldest policy.

Idempotent: a second call is a no-op (the default logger is already synchronous).

bool gtopt::table_has_column(const ArrowTable& table, std::string_view name) noexcept

Check whether table has a column named name. Returns false on a null table.

std::vector<double> gtopt::tail_risk_weights(std::span<const double> probability, std::span<const double> index, double alpha, double weight, RiskMeasure measure, RiskTail tail)

Exceptions
std::invalid_argument on bad α / λ, size mismatch, trim with α = 0 or a non-finite index.

Fixed risk-adjusted probabilities of an exogenous tail (risk_rank_by = index). The scenarios are ranked by index (descending for upper, ascending for lower; ties keep input order); the tail is the first (1 − α)·P of probability mass, the boundary scenario split. With t_s the tail mass of s: cvar: q_s = (1 − λ) p_s + λ t_s / (1 − α) trim: q_s = (1 − λ) p_s + λ (p_s − t_s) / α Σ q_s = Σ p_s.

bool gtopt::test_force_fix_duals_bail() noexcept

TEST-ONLY hook: true when the environment variable GTOPT_TEST_FORCE_SOS_BAIL=1 is set. Forces the dual-recovery pass (fix_mip_and_resolve_duals) to take its BAIL branch — both the portable default below and the CPLEX override's SOS-support verification block check it — so tests can exercise the full production bail contract (MIP incumbent restored + republished, duals_unavailable latched, dual-dependent outputs skipped at write-out) without needing a case where CPLEX actually un-pins the SOS support. Read fresh on every call (no static latch) so a test can scope it with setenv/unsetenv around a single fix pass. Never set this in production. Defined in source/solver_backend.cpp.

bool gtopt::time_window_finer_than_scope(TimeWindow window, ConstraintScope scope) noexcept

True iff a sum{...} over window, evaluated under a constraint of scope, is LOSSY — i.e. the window is FINER than the scope, so the single representative row built at coarse scope aggregates only the representative sub-unit and silently drops the rest. Block scope is never lossy (one row per block).

int gtopt::time_window_granularity(TimeWindow window) noexcept

std::string_view gtopt::time_window_name(TimeWindow window) noexcept

std::optional<LpScalesContext> gtopt::to_scales_context(const LpContext& context)

Maps the in-memory LpContext variant to its sidecar form (type tag + the uids of that alternative); std::monostate maps to std::nullopt (context-free column).

template<typename Tag>
std::size_t gtopt::to_size(StrongIndexType<Tag> idx) noexcept

template<typename Tag>
std::size_t gtopt::to_size(StrongPositionIndexType<Tag> idx) noexcept

Container offset of a strong index: its underlying value as std::size_t.

Named replacement for static_cast<std::size_t>(idx) when a strong index addresses a plain std::vector (per-scene counters, masses, …). Containers that are only ever indexed by one strong type should be a StrongIndexVector instead, which needs no unwrap at all.

std::string_view gtopt::to_string(Carrier c) noexcept

Human-readable name of a carrier (for diagnostics / error messages). Returned as a std::string_view so it can be used in std::format calls without allocation.

std::string_view gtopt::to_string(IntegrityVerdict v) noexcept

std::string_view gtopt::to_string(PluginCheckMode m) noexcept

std::string_view gtopt::to_string(PluginCheckSource s) noexcept

template<std::ranges::range Range, typename Transform = decltype([](const auto& x) { return x; }), typename RRef = decltype(*std::ranges::begin(std::declval<Range>()))>
auto gtopt::to_vector(Range&& range, Transform&& transform = {})

Converts range to vector, optionally transforming elements.

Template parameters
Range Input range type
Transform Unary transform operation (defaults to identity)
RRef
Parameters
range Input range
transform Transform operation (optional)
Returns std::vector containing transformed elements

bool gtopt::transition_cols_binary(TransitionIntegrality mode) noexcept

Whether v / w are declared integer (before any relax) for the mode: auto and binary → binary, continuous → continuous.

std::optional<std::string> gtopt::translate_solver_cfg_value(std::span<const SolverCfgEnumKey> enum_keys, std::string_view key, std::string_view value)

Translate one tuning value into the solver's numeric code.

Numbers pass through verbatim. A key present in enum_keys accepts its table's names (case-insensitive, aliases included); any other key accepts the generic boolean spellings. Returns std::nullopt — and logs a warning naming the expected values — when the value is symbolic but matches nothing; callers drop the pair.

std::expected<ArrowTable, std::string> gtopt::try_read_table(const std::filesystem::path& fpath, std::string_view format)

Try to read a table, preferring format and falling back to the other format on failure.

Parameters
fpath Path without extension.
format Preferred format: "parquet" or anything else (CSV).
Returns Loaded table or an error description.

IterationUid gtopt::uid_of(IterationIndex idx) noexcept

Convert a 0-based IterationIndex to the matching 1-based IterationUid. The only sanctioned way to produce an IterationUid from runtime iteration state, so the +1 convention stays in one place.

template<class Tag>
UidOf<Tag> gtopt::unknown_uid_of() noexcept

Named form of the default-constructed / "unknown" UID state. Equivalent to UidOf<Tag>{}, but more explicit at call sites.

std::optional<std::string> gtopt::validate_markov_config(const MarkovChainConfig& markov, std::size_t num_scenes)

Validate a Markov configuration against the scene count: M ≥ 1, square transition of matching dimension with finite non-negative entries and row sums within 1e-6 of 1, one assignment per scene, every assignment in range, and every state non-empty (an empty state has zero mass and the w = p_s·P/pi pricing divides by it). Returns the error message, or nullopt when valid.

std::optional<Error> gtopt::validate_nonanticipative_sddp(const SimulationLP& sim, const SDDPOptions& opts)

Refuse SDDP options that cannot honour a nonanticipative merge.

Returns nullopt when there is no merge or nothing conflicts; otherwise an InvalidInput Error naming the decision variable and the option.

A nonanticipative: true DecisionVariable folds the scenes into ONE LP scene (SimulationLP::scene_merge()). The SDDP machinery that assumes one LP per ORIGINAL scene, or one scenario per state column, would give a silently wrong answer on that scene, so it is a hard error instead:

  • active backward apertures (aperture_array, apertures, num_apertures …) — the aperture pass perturbs only the scene's first scenario;
  • cut_sharing_mode = markov — one Markov state per original scene;
  • boundary cuts (boundary_cuts_file) — one α tied to the first scenario's state;
  • loading cuts from a file (cuts_input_file, cut_recovery_mode under --recover) — cut files identify a state coefficient by (class, variable, uid) without the scenario, so they cannot address the per-scenario state columns of a merged scene.

ValidationResult gtopt::validate_planning(Planning& planning)

Validate a Planning object for semantic correctness.

Parameters
planning The parsed and merged Planning object (may be mutated if probability rescaling is enabled)
Returns ValidationResult with all errors and warnings

Checks performed:

  1. Referential integrity: cross-references between components (generator.bus, demand.bus, line.bus_a/bus_b, turbine.waterway, turbine.generator, flow.junction, waterway.junction_a/junction_b, converter.battery/generator/demand, reservoir.junction)
  2. Range checks: block duration > 0, stage count_block > 0 and first_block/count_block inside block_array, generator capacity non-negative
  3. Completeness: at least one bus, block, and stage
  4. Probability checks: scenario probability_factor values per scene should sum to 1.0; controlled by probability_check option.
  5. Model-sanity warnings (see check_model_sanity).

All issues are collected (not short-circuited) so the user sees every problem in a single run.

When probability_check is rescale (default), probabilities that do not sum to 1.0 are normalized in-place (hence the non-const reference).

template<class Tag>
uid_t gtopt::value_of(const UidOf<Tag>& u) noexcept

ADL-friendly accessor matching the rollbear/strong_type value_of free function used throughout the codebase (see source/user_constraint_lp.cpp, source/sddp_method.cpp etc.). Returning uid_t directly keeps existing call sites unchanged.

std::vector<int> gtopt::violated_integer_rows(const FlatLinearProblem& flat, std::span<const double> row_low, std::span<const double> row_upp, std::span<const int> int_cols, std::span<const double> values, double infinity = 1e20, double tol = 1e-6)

Rows of flat whose nonzeros are ALL integer columns ("pure-integer" rows: exclusivity, min up/down, logic, …) violated by values beyond tol · max(1, |rhs|). A cheap exact check of the combinatorial part of a candidate — the rows the legacy rounded start broke on PCP.

template<typename Collections, typename Op>
auto gtopt::visit_elements(Collections&& collections, Op op)

Parameters
collections Tuple of collections to visit
op Operation applied to each element; a truthy return value is counted as a successful visit
Returns Count of successful operations

Visits each element in multiple collections and applies an operation to every one of them.

void gtopt::warn_deprecated_cli(const std::optional<bool>& opt, std::string_view cli_flag, std::string_view set_path)

Specialisation for bool (prints true/false instead of 1/0).

void gtopt::warn_deprecated_cli(const std::optional<std::string>& opt, std::string_view cli_flag, std::string_view set_path)

Overload for string options — no conversion needed.

template<typename T>
void gtopt::warn_deprecated_cli(const std::optional<T>& opt, std::string_view cli_flag, std::string_view set_path)

Emit a deprecation warning for a CLI option replaceable by –set.

Parameters
opt The optional value to check (warning only if it has a value)
cli_flag The deprecated CLI flag name
set_path The –set key path that replaces it

void gtopt::warn_deprecated_cli_flags(const MainOptions& opts)

Emit the "--flag is deprecated, use --set" warnings for every deprecated CLI flag set in opts.

template<typename... Args>
void gtopt::warn_once(WarnOnceFlag& flag, spdlog::format_string_t<Args...> fmt, Args && ... args)

Emit spdlog::warn(fmt, args...) only on the first call that latches flag; every later call (from any thread) is a no-op.

template<typename... Args>
void gtopt::warn_once_per_key(std::string key, spdlog::format_string_t<Args...> fmt, Args && ... args)

Keyed variant: emit spdlog::warn(fmt, args...) only the first time key is seen in this process. Used for "once per element" warnings, where a function-local WarnOnceFlag would be once per call site (silencing every element after the first) and a member flag would repeat in every (scene, phase) cell. Build the key from the class name, the element uid and the reason, e.g. std::format("{}:{}:missing_waterway", cname, uid).

void gtopt::warn_profile_above_one(std::string_view class_name, Uid uid, std::string_view name, double max_value, bool clamped)

Warn that a profile value exceeds 1 (profiles are per-unit of the owner capacity, not MW). Process-wide summary: one line per (class, uid) — every scene/phase LP builds its own element copy — for the first max_detailed elements, then a single "suppressed" line.

void gtopt::warn_ref_once(std::string_view cname, Uid uid, std::string_view ref_what, Uid ref_uid)

Parameters
cname class of the element doing the referencing
uid its uid
ref_what what was omitted, e.g. "waterway flow term"
ref_uid uid of the referenced element (for the message)

One warning per (element, reason) for a reference whose term was omitted because the referenced element is inactive / not built.

SparseRow gtopt::weighted_average_benders_cut(const std::vector<SparseRow>& cuts, const std::vector<double>& weights)

Parameters
cuts Collection of Benders optimality cuts (SparseRow)
weights Per-cut probability weights (must be same size as cuts)

Compute a probability-weighted average cut from a collection of cuts.

Each cut is weighted by the corresponding element in weights. The weights are normalised internally so they need not sum to 1. If all weights are zero the function returns an empty SparseRow.

std::expected<void, std::string> gtopt::write_json_output(const Planning& planning, const std::string& json_file)

Write the merged Planning to a JSON file.

void gtopt::write_lp_fingerprint(const LpFingerprint& fingerprint, const std::string& filepath, int scene_uid = 0, int phase_uid = 0)

Parameters
fingerprint The fingerprint to serialize
filepath Output file path (will be created/overwritten)
scene_uid Scene UID for the JSON metadata
phase_uid Phase UID for the JSON metadata

Write an LP fingerprint to a JSON file.

std::expected<std::string, Error> gtopt::write_lp_scales(const SystemLP& system, std::string_view lp_path, LpScalesLevel level = LpScalesLevel::full, std::string_view compression = {})

Parameters
system
lp_path
level
compression Codec for the sidecar (--lp-compression); empty, none or uncompressed keep the plain .json. Failures (unwritable path, full disk, ...) are returned, not thrown. At the full level the scaled columns and rows also go to <stem>.scales_cols.parquet / <stem>.scales_rows.parquet (Parquet compresses internally; compression only applies to the JSON).
Returns Path of the written sidecar (with the codec extension when compressed).

Builds and writes the sidecar for the model file lp_path.

std::expected<void, Error> gtopt::write_lp_scales_tables(const LpScalesDetail& detail, Uid scene_uid, Uid phase_uid, std::string_view columns_path, std::string_view rows_path)

Writes detail as the two Parquet tables (zstd), with scene_uid / phase_uid columns so the tables of several cells can be concatenated.

void gtopt::write_solver_status(const std::string& filepath, const std::vector<SDDPIterationResult>& results, double elapsed_seconds, const SolverStatusSnapshot& snapshot, SolverMonitor& monitor)

Parameters
filepath Output JSON file path
results Vector of per-iteration results
elapsed_seconds Total elapsed time since solve() started
snapshot Current solver state snapshot Also registers the iteration portion + path with the monitor (via SolverMonitor::update_status) so the monitor's background sampling thread keeps rewriting the file every tick with fresh realtime/pool numbers between iterations. The monitor is the sole periodic writer; this call performs one immediate fresh write at the iteration boundary.
monitor SolverMonitor for real-time workpool stats

Write solver status JSON to a file.

Builds a JSON string with the solver's current state, per-iteration history, and real-time workpool statistics, then writes it atomically (via SolverMonitor::write_status()).

double gtopt::clock_of_day(double hours) noexcept

Clock hour of a time of day hours, reduced to [0, 24).

std::vector<double> gtopt::daily_cell_bounds(std::span<const double> breaks, double start_hour, double period)

Cell boundaries in STAGE time of the daily grid breaks (hours of the day, [0, 24), strictly increasing) over a stage of length period that starts at clock time start_hour: every stage time τ in (0, period) with clock_of_day(start_hour + τ) ∈ breaks, sorted. A boundary within 1e-9 h of the stage start or end is dropped (the stage ends there anyway). The cells of the stage are [0, τ_1), [τ_1, τ_2), ..., [τ_K, period].

std::size_t gtopt::cell_of_time(std::span<const double> bounds, double t, double tol = 1e-9) noexcept

Cell of stage time t on the boundaries bounds (see daily_cell_bounds): half-open cells [τ_c, τ_{c+1}), so a time exactly on a boundary (within tol) belongs to the LATER cell; times past the last boundary (incl. the period end) join the last cell. Cell 0 starts at the stage start.

bool gtopt::daily_cells_wrap(std::span<const double> breaks, double start_hour, double period) noexcept

True when the first and the last cell of a stage are the two pieces of ONE daily cell: the stage is a whole number of days long and does not start on a break, so on a cyclic (periodic) stage the cell straddling the period start wraps around it. False when the stage holds a single cell (no boundary).

std::string gtopt::gzip_lp_file_inline(const std::string& src_path)

Inline gzip compression via zlib. Returns .gz path or empty on failure.

std::string gtopt::zstd_lp_file_inline(const std::string& src_path)

Inline zstd compression via libzstd. Returns .zst path or empty on failure.

std::string gtopt::compress_lp_file(const std::string& src_path, const std::string& lp_compression = {})

Parameters
src_path Path to the source file to compress.
lp_compression "none", "", "gzip", "zstd", "lz4", "bzip2", "xz"

Compress a file using the named codec or auto-cascade.

Variable documentation

auto gtopt::active_fnc

Predicate that checks if element has is_active() member returning true.

auto gtopt::aperture_solve_mode_entries

Includes "warm_start" / "barrier" as back-compatible aliases.

std::size_t gtopt::aperture_summary_top_n

Number of phases / apertures listed in the end-of-run summary.

auto gtopt::basis_cross_mode_entries

Includes "fwd2bwd" / "bwd2fwd" / "cross" as convenience aliases.

auto gtopt::carrier_entries

NamedEnum table — lets Carrier round-trip through JSON via json_string_enum<>. See enum_option.hpp for the framework.

std::string_view gtopt::cvar_class_name

Column / row name tags of the CVaR construct.

std::string_view gtopt::cvar_eta_name

std::string_view gtopt::cvar_excess_name

double gtopt::days_per_year

Days in a standard year (non-leap).

double gtopt::DblMax

Maximum representable double value used for unbounded variable bounds.

auto gtopt::default_aperture_chunk_mode

THE single default for the backward-pass aperture grouping.

double gtopt::default_cvar_alpha

Default tail level α of model_options.cvar_alpha: CVaR averages the worst 1 − α = 5 % of the cost distribution.

double gtopt::default_cvar_weight

Default weight λ of model_options.cvar_weight. 0.5 rather than 1: with λ = 1 and few scenarios, the scenarios outside the tail get zero risk-adjusted probability, so their dispatch is no longer priced (any feasible dispatch is optimal and their reported duals are 0).

double gtopt::default_fast_start_max_hours

Default auto-rule threshold [h] for fast-start classification (ModelOptions::fast_start_max_hours).

int gtopt::default_sddp_aperture_drop_warn_after

Consecutive iterations an aperture must be dropped before the escalated "persistent aperture infeasibility" warning is emitted.

int gtopt::default_sddp_aperture_screen_count

THE single default for the number of dual-shared aperture cuts re-solved exactly under aperture_solve_mode = screened (largest |intercept correction| first). Referenced by the PlanningOptionsLP::sddp_aperture_screen_count() accessor, the runtime SDDPOptions::aperture_screen_count field default, and the solve_apertures_for_phase parameter default — one constant, three consumers.

std::string_view gtopt::EfinColName

Canonical state-variable column name that may appear as a cut coefficient column in boundary / hot-start cut CSV headers.

Mirrors the value of StorageLP<...>::EfinName (the LP assembly emits this name from StorageLP::add_to_lp for reservoir / battery / lng-terminal final energy). We define a local mirror — instead of reaching StorageLP::EfinName directly — because StorageLP is a class template and its static members aren't reachable without an instantiation.

Defined as a named constexpr constant — never spelled inline as a string literal — so a regression that breaks the allow-list shows up at the type/symbol level, not as a silent string mismatch.

auto gtopt::elastic_filter_mode_entries

Includes "cut" as a backward-compatible alias for "single_cut", "iis" as an alias for "chinneck", and "plp" as the legacy alias for "state_repair" (the canonical entry is listed FIRST so enum_name / JSON serialization emit "state_repair").

std::string_view gtopt::elastic_fix_constraint_name

Elastic-filter fix constraint (added by relax_fixed_state_variable in benders_cut.cpp to relax a fixed state variable into a slack pair when the master phase is infeasible at the trial state).

IntBool gtopt::False

False value for integer boolean.

std::string_view gtopt::flow_abs_constraint_name

Auxiliary v ≥ |f| envelope row used by the tangent_signed_flow loss model to tighten the upper bound on the loss column. Two rows per (line, block): v − f ≥ 0 and v + f ≥ 0.

std::string_view gtopt::flow_link_constraint_name

Flow conservation constraint on a node / waterway / line.

ProfileLPMode gtopt::generator_profile_lp_mode

Mode used by every generator profile (GeneratorProfile, CapacityProfile with owner_kind = generator).

auto gtopt::has_value_fnc

Predicate that checks if element exists (not nullopt).

double gtopt::hours_per_day

Hours in a standard day.

double gtopt::hours_per_year

Hours in a standard year.

double gtopt::interior_cut_rel_gap

Relative intercept shift applied to cuts built from interior (barrier, no crossover) forward data: the default barrier relative optimality gap of the supported backends (CPLEX / HiGHS: 1e-8).

auto gtopt::is_true_fnc

Predicate that checks if optional has value and value is true (C++23 value_or)

std::string_view gtopt::k_build_id_manifest_suffix

Suffix of the per-plugin manifest file: libgtopt_solver_x.so.build-id.

PluginCheckMode gtopt::k_default_plugin_check_mode

Compiled-in default mode, used when neither --plugin-check nor $GTOPT_PLUGIN_CHECK selects one. Set at configure time with the CMake option GTOPT_PLUGIN_CHECK_DEFAULT (error unless configured otherwise).

double gtopt::k_kappa_infinite

Smallest value a backend may report as kappa that is NOT a condition number but a solver "infinity": CPLEX fills CPXgetdblquality(CPX_KAPPA) with its huge-value sentinel 1e75 (the value of e.g. its default TiLim) and returns status 0 when it cannot bound the basis condition; other solvers use +inf. Huge FINITE estimates are kept: on the CEN PCP 2025-10-19 relaxed LP CPLEX reports a real CPX_KAPPA of 2.3e16 (CPX_EXACT_KAPPA 2.5e16) and, after a primal re-solve from that basis, 2.6e26 - numerically singular bases that the high-kappa warning must still flag.

std::string_view gtopt::k_kappa_mode_env

Environment variable selecting the default kappa mode.

std::string_view gtopt::k_plugin_check_env

Environment variable selecting the mode when no CLI override is set.

std::string_view gtopt::k_plugin_refused_marker

Text every refusal message contains (--solvers lists those errors).

int gtopt::k_solver_abi_version

ABI version for the SolverBackend plugin interface.

Bump this integer every time the SolverBackend vtable changes (new virtual methods, reordered methods, changed signatures, etc.). SolverRegistry checks the plugin's reported ABI version at load time and rejects incompatible plugins with a clear error instead of crashing.

int gtopt::k_solver_build_info_version

Current layout version of SolverBuildInfo.

std::string_view gtopt::k_solver_fallback_on_refused_env

Environment variable: when true (1/true/yes/on), a GTOPT_SOLVER whose plugin was REFUSED falls back to the automatic choice with a warning (the old behaviour) instead of failing.

int gtopt::k_solver_resource_desc_version

Bumped whenever SolverResourceDescriptor gains/reorders a field.

int gtopt::k_solver_version_pin_version

Current layout version of SolverVersionPin.

ArrowPresentMask gtopt::kArrowSparseZeroFillBit

High bit of an ArrowPresentMask flagging a long-direct (sparse) index. When set, a missing (uid, key) cell resolves to 0 instead of throwing — matching both the wide pivot's zero-fill and the long format's own zero-drop convention (gtopt long output drops exact zeros). The low bits (0..2) remain the scenario / stage / block present-axis flags, so project_key (which only inspects axis bits) is unaffected.

double gtopt::kDefaultGasCompressibility

Default gas compressibility factor Z.

double gtopt::kDefaultGasSpecificGravity

Default gas specific gravity (air = 1).

double gtopt::kDefaultGasTemperature

Default flowing gas temperature [K].

double gtopt::kDefaultSlpDamping

Default SLP damping ω.

double gtopt::kDefaultSlpInitialFlow

Default first-pass |f₀| as a fraction of fmax.

double gtopt::kDefaultSlpMinFlow

Default minimum |f₀| as a fraction of fmax.

double gtopt::kDefaultSlpProximalCost

Default SLP proximal cost ρ [$ / flow unit / h] on |f̄ − f₀|.

double gtopt::kDefaultSlpTolerance

Default SLP stopping tolerance on the relative flow change.

int gtopt::kDiagMaxLines

Maximum number of diagnostic output lines before truncation. When diagnostic output exceeds this limit, only the last kDiagTailLines lines are shown to avoid flooding the log.

int gtopt::kDiagTailLines

Number of trailing lines to keep when truncating diagnostic output.

std::string_view gtopt::kirchhoff_class_name

Kirchhoff Voltage Law cycle rows on a meshed network.

std::string_view gtopt::kirchhoff_cycle_constraint_name

Kirchhoff Voltage Law cycle constraint (Σ X·P = 0 around a loop).

double gtopt::kSddpGapFpEpsilon

Floating-point noise floor for the convergence gap.

SDDP theory says LB ≤ optimum ≤ UB, so the gap (UB-LB)/|UB| is non-negative at the optimum. A tiny negative gap (e.g. -1e-16 when UB ≈ LB exactly) is just IEEE-754 rounding noise and must NOT trigger the "cuts overshoot the optimum" guard. A significant negative gap (gap < -kSddpGapFpEpsilon) IS a real SDDP-theory violation that the convergence checks refuse to declare [CONVERGED] on.

Distinct from SDDPOptions::convergence_tol (the user-facing gap tolerance for declaring convergence): convergence_tol sets the upper bound of the converged band and may be set to a negative sentinel (e.g. -1.0) to disable the primary gap test in favour of the stationary criterion. kSddpGapFpEpsilon is a fixed lower bound for the same band, expressed in absolute terms because IEEE-754 rounding noise on (UB - LB)/|UB| for values up to ~1e9 stays comfortably below 1e-9.

double gtopt::kStatePinDetectEps

Raw-bound gap below which a dependent state column counts as PINNED (lowb ≈ uppb, i.e. fixed to a forward trial value). THE single pin-detection epsilon shared by relax_fixed_state_variable, the elastic-filter pre-pass (compute_relaxation_specs), and the strengthened-cut box relaxation (build_strengthened_benders_cut) — the strengthened-cut validity argument (theorem SB1's box domain) requires all three sites to agree on what "pinned" means, so keep them on this one constant.

int gtopt::kZstdCompressionLevel

Zstd compression level: 3 is the library default, offering a good balance between speed and ratio for LP debug files.

std::string_view gtopt::loss_lambda_convex_constraint_name

Lambda-form SOS2 L-secant convexity row Σ λ_l = 1 (issue #504 SOS2 path). Emitted once per (line, block) when tangent_signed_flow is paired with loss_use_sos2 = true and loss_secant_segments > 1.

std::string_view gtopt::loss_lambda_flow_constraint_name

Lambda-form SOS2 L-secant flow row f = Σ b_l · λ_l (issue #504 SOS2 path). Pins the signed flow to the breakpoint-weighted interpolation.

std::string_view gtopt::loss_link_constraint_name

Linearised line-loss constraint (segments approximating |P|² · R).

auto gtopt::lp_algo_entries

Compile-time table mapping each LPAlgo enumerator to its name.

Excludes the sentinel last_algo value.

std::string_view gtopt::lp_scales_cols_suffix

std::string_view gtopt::lp_scales_json_suffix

Suffixes of the sidecar files written next to a model file.

std::string_view gtopt::lp_scales_rows_suffix

std::string_view gtopt::lp_scales_schema

Schema identifier written in the "schema" field of every sidecar.

std::size_t gtopt::lp_type_count_v

Total number of LP element types.

template<typename T>
std::size_t gtopt::lp_type_index_v

Compile-time index of LP element type T in lp_element_types_t.

Used by SystemContext::get_element<T> to locate the Collection<T> pointer in the m_collection_ptrs_ array without including system_lp.hpp.

Example: lp_type_index_v<BusLP> is 0 (the first entry, pinned by the static_assert below). Never hard-code the index of any other type: positions shift whenever an entry is added to lp_element_types_t.

std::size_t gtopt::max_fail_segments

Maximum number of segments per demand (bounds the static fail_seg<k> output-field names).

double gtopt::max_mip_polish_reserve_s

Upper bound, in seconds, of the polish reserve taken from the MIP.

double gtopt::min_mip_polish_time_slice_s

The polish LP always gets at least this many seconds, even when the MIP consumed the whole time_limit budget (a fixed-integer LP warm-started from the incumbent basis is usually a few pivots; a cold barrier on a large UC needs more — the reserve above is what normally covers it).

double gtopt::min_retry_time_slice_s

A retry that would get less than this many seconds of the remaining SolverOptions::time_limit budget is skipped (no solver makes useful progress on a large LP / MIP in under a second, and a zero / negative limit is "no limit" for several backends).

double gtopt::mip_polish_reserve_fraction

Share of SolverOptions::time_limit held back from the MIP for the post-MIP polish LP (see SolverOptions::mip_polish), capped at max_mip_polish_reserve_s.

auto gtopt::month_type_entries

Name-value table for MonthType.

Accepts:

  • English full names ("january", "february", ...). These come first so reverse lookup (enum_name) returns the canonical English name.
  • Spanish full names ("enero", "febrero", ...), plus the alternate spelling "setiembre" for September.
  • English 3-letter abbreviations ("jan", "feb", ...).
  • Spanish 3-letter abbreviations ("ene", "feb", ...); "feb" maps to the same value as its English twin, so only one entry is needed for the shared abbreviations.

Comparison is ASCII case-insensitive (see enum_option.hpp), so "January", "JANUARY", "Enero" and "ENE" all resolve to MonthType::january.

auto gtopt::NumberOptsWithInf

Per-member number options that allow Infinity / -Infinity (and NaN) to round-trip through JSON as quoted strings.

daw-json-link's AllowNanInf mode requires LiteralAsStringOpt to be Maybe (or Always), so the value is read as a quoted literal like "Infinity" / "-Infinity" / "NaN" — see the cookbook for details: https://github.com/beached/daw_json_link/blob/release/docs/cookbook/member_options.md

Usage (per-field opt-in — daw-json-link does not provide a global "allow inf" flag on the parse policy; the option is on the member's number-options template parameter):

json_number_null<"x", OptReal, gtopt::NumberOptsWithInf>

When this is needed: only when a user-edited or third-party JSON might carry a literal "Infinity" token. plp2gtopt's own writer prefers to omit unbounded fields entirely (see gtopt_writer._sanitize_inf), which gtopt's struct defaults treat as +inf after the flatten-time clamp — so the round-trip is already complete for our own outputs without this option being applied. The constant is here so adding inf-tolerance to a specific field is one local edit, not a multi-file refactor.

auto gtopt::output_flags_entries

Named-enum table for the atomic flag values plus common abbreviations. all and none are shortcuts also accepted by the parser.

double gtopt::sddp_alpha_bootstrap_min

Bootstrap lower bound on α at iter-0 cold start, in physical ($) units. Divided by scale_alpha at the call site.

Value 0.0 matches the project's pre-existing default (proven across all integration tests). α has a positive objective coefficient, so without a lower bound the cold-start iter-0 LP would be unbounded; a loose bound (e.g. −1e10) admits negative-cost futures but produces very weak LB estimates that trigger premature stationary convergence in tight-tolerance tests. α ≥ 0 is a mild bias for problems where future cost is positive (almost all dispatch), and users with net-revenue phases can override via a custom cut.

A cleaner "lazy α" (create α only at first cut install) was tried and abandoned: it interacted badly with the low-memory cached col_sol/col_cost/col_scales vectors, producing out-of-bounds access in the aperture path and a convergence slowdown on the 3-phase hydro test. Revisit only with proper cached-vector invalidation work.

std::string_view gtopt::sddp_alpha_class_name

std::string_view gtopt::sddp_alpha_col_name

Uid gtopt::sddp_alpha_uid

Fixed uid used in the alpha StateVariable::Key. The state-variable map is partitioned by (scene_index, phase_index) and there is at most one alpha per cell, so any constant uid disambiguates the key. Uid{0} keeps the structured cut-key label as Sddp:alpha:0.

std::string_view gtopt::sddp_bcut_constraint_name

std::string_view gtopt::sddp_bcut_row_prefix

std::string_view gtopt::sddp_boundary_cut_class_name

std::string_view gtopt::sddp_class_name

SDDP-method coordinator rows / columns (e.g. α future-cost variables). Used in row labels where no per-element data-struct class_name applies.

std::string_view gtopt::sddp_ecut_constraint_name

std::string_view gtopt::sddp_ecut_row_prefix

std::string_view gtopt::sddp_elastic_sdn_col_name

std::string_view gtopt::sddp_elastic_sup_col_name

Variable-name tags for the elastic filter's slack columns added by relax_fixed_state_variable. Carried on SparseCol metadata so serialised LPs (CoinLpIO, LinearInterface::write_lp) emit distinct non-empty column labels — a hard requirement for the COIN LP writer, which replaces every row/col name with generic defaults when it encounters even one unnamed column.

std::string_view gtopt::sddp_elastic_zfc_col_name

Slack column added by apply_fcut_relaxations on every installed feasibility-cut row of the elastic clone under elastic_filter_mode = farkas_recursive (a_rᵀx + z_r ≥ b_r, the Füllner–Rebennack §17.2 + I z term). Distinct from the sup/sdn names so the disposable label dedup never collides.

std::string_view gtopt::sddp_fcut_constraint_name

std::string_view gtopt::sddp_fcut_row_prefix

std::string_view gtopt::sddp_frcut_constraint_name

Füllner–Rebennack recursive feasibility cut (elastic_filter_mode = farkas_recursive). One aggregated multi-variable row per event, tagged with sddp_alpha_class_name like the aggregated fcut.

std::string_view gtopt::sddp_loaded_cut_class_name

Class tags for cuts brought in by the loaders. Each loader path sets a distinct class_name so mixing loader sources never produces identical metadata:

  • sddp_loaded_cut_class_name – generic load_cuts_parquet
  • sddp_boundary_cut_class_name – load_boundary_cuts_csv Both share a single constraint-name constant (sddp_loaded_cut_constraint_name) since they describe the same kind of Benders optimality row. The legacy sddp_named_cut_class_name ("NamedHs") was retired in 2026-05 alongside load_named_cuts_csv.

std::string_view gtopt::sddp_loaded_cut_constraint_name

CutTag gtopt::sddp_loaded_cut_tag

Loader-class cut tags: cuts loaded from disk use a distinct class_name per source so a hot-start that mixes loaders produces unique row-metadata keys for the duplicate detector, while sharing the single sddp_loaded_cut_constraint_name constraint name (they describe the same kind of optimality row).

std::string_view gtopt::sddp_mcut_constraint_name

std::string_view gtopt::sddp_plpcut_constraint_name

PLP-exact per-link feasibility cut (elastic_filter_mode = state_repair, alias plp). Like mcut, each row is a single-variable bound constraint on one state variable, so the row is tagged with the source state variable's class name rather than sddp_alpha_class_name.

std::string_view gtopt::sddp_scut_constraint_name

Constraint-name tags carried on LP row metadata for each kind of Benders cut emitted by SDDP. Paired with sddp_alpha_class_name so the eager duplicate detector in LinearInterface::add_row keys SDDP cuts on ("Sddp", <tag>, uid, IterationContext) — the tag distinguishes the pass that produced the cut. Multi-cuts (mcut) are the only SDDP cut family tagged with the source state-variable's class name instead of sddp_alpha_class_name, since each multi-cut row is a per-link bound constraint on a single state variable.

std::string_view gtopt::sddp_scut_row_prefix

Row-name prefixes for the four SDDP pass-tagged cut types, for dispatching on row-name shape without re-parsing the (class, constraint) pair. Each prefix is verified at compile time against the corresponding sddp_alpha_lp_class.short_name()

  • sddp_<x>_constraint_name pair via the static_asserts below.

CutTag gtopt::sddp_scut_tag

SDDP-class cut tags: every Benders cut produced by an SDDP pass is keyed under (sddp_alpha_class_name, <pass-tag>) so the eager duplicate detector in LinearInterface::add_row distinguishes the seven pass types at the row-metadata level. These instances replace the cut.class_name = …; cut.constraint_name = …; pair at every cut-construction site.

std::string_view gtopt::sddp_share_cut_constraint_name

int gtopt::solution_status_limit_polished

solution.csv status of a MIP that stopped at a limit (time / node / memory) WITHOUT proving optimality and whose incumbent was then polished (integers fixed, LP re-solved — SolverOptions::mip_polish). The published objective / primal / duals are the polished LP's, but the cell is not optimal for the MIP: it gets its own code rather than 0.

std::string_view gtopt::storage_close_constraint_name

Storage / reservoir end-of-horizon closure constraint. Renamed from the legacy "eclose" for clarity.

auto gtopt::StrictParsePolicy

Strict parser with hash-comment support and full checking. Rejects unknown JSON members. Use for all JSON input — user-facing planning files and internally constructed overlays (e.g. –set) alike.

IEEE754Precise::yes is mandatory, not optional: daw-json-link's default (fast) real parser silently mis-parses number literals with more significant digits than fit in a uint64_t (> ~19) by orders of magnitude when the document is fed as a std::string — which is exactly how parse_planning_json feeds the canonicalised buffer. The strtod fallback that handles over-long significands is compiled out unless this flag is set. See https://github.com/beached/daw_json_link/issues/474 (daw 3.31.0).

std::string_view gtopt::system_class_name

Top-level system-wide constraint rows (e.g. emission cap).

const void* gtopt::this_thread_worker_pool

Identity of the pool (if any) whose worker_loop owns the current thread. Set once at worker start; never reset (the thread dies with its pool). Lets release_slot_for_blocking_ distinguish "called from one of MY workers" (release is correct) from "called from a coordinator / foreign-pool thread" (release would decrement some OTHER task's slot and over-admit) — a tasks_active_ > 0 check alone cannot tell those apart.

IntBool gtopt::True

True value for integer boolean.

auto gtopt::true_fnc

Predicate that always returns true.

GroupUid gtopt::unknown_group

Sentinel meaning "no group" — used for Stage and Phase scopes.