gtopt::SystemContext class

Base classes

class FlatHelper
Converts multi-dimensional optimization data into flat vectors for LP formulation.
class CostHelper
Handles cost calculations with time discounting for optimization problems.

Public static functions

static auto block_ecost(const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const double cost) -> double noexcept
Calculates the energy cost coefficient for a block.
static auto cost_factor(const double probability, const double discount, const double duration = 1.0) -> double noexcept
static auto cost_factor(const ScenarioLP& scenario, const StageLP& stage) -> double noexcept
static auto cost_factor(const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block) -> double noexcept
static auto cost_factor(const StageLP& stage, double probability = 1.0) -> double noexcept
static auto scenario_stage_ecost(const ScenarioLP& scenario, const StageLP& stage, const double cost) -> double noexcept
Calculates the energy cost coefficient for a scenario-stage pair.
static auto stage_ecost(const StageLP& stage, double cost, double probability = 1.0) -> double noexcept
Calculates the energy cost coefficient for a stage.

Constructors, destructors, conversion operators

SystemContext(SimulationLP& simulation, SystemLP& system, SystemKind kind = SystemKind::forward) explicit

Public functions

auto active_block_count() const -> size_t noexcept
auto active_blocks() const -> const auto& noexcept
auto active_scenario_count() const -> size_t noexcept
auto active_scenarios() const -> const auto& noexcept
auto active_stage_blocks() const -> const auto& noexcept
auto active_stage_count() const -> size_t noexcept
auto active_stages() const -> const auto& noexcept
void add_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, const ScenarioLP& scenario, const StageLP& stage, ColIndex stage_col) const
Register a stage-level scalar column (e.g., eini, efin, capainst).
void add_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, const ScenarioLP& scenario, const StageLP& stage, const BIndexHolder<ColIndex>& block_cols) const
void add_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, const ScenarioLP& scenario, const StageLP& stage, const BIndexHolder<ColIndex>& block_cols, const BIndexHolder<double>& block_offsets) const
void add_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, const ScenarioLP& scenario, const StageLP& stage, const BIndexHolder<std::vector<ColIndex>>& block_cols_sum) const
void add_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, const ScenarioLP& scenario, const StageLP& stage, const BIndexHolder<std::vector<std::pair<ColIndex, double>>>& block_cols_weighted_sum, const BIndexHolder<double>& block_offsets = {}) const
template<typename Element>
auto add_element(Element&& element) -> auto
template<typename Key, typename Col>
auto add_integer_col(LinearProblem& lp, Key&& key, Col&& col, IntegerDomain domain, IntegerScope scope, GroupUid group_uid, std::span<const BlockUid> blocks) -> ColIndex
template<typename Key>
void add_integer_variable(Key&& key, ColIndex col, IntegerDomain domain, IntegerScope scope, GroupUid group_uid, std::span<const BlockUid> blocks)
template<typename Key, typename Col>
auto add_state_col(LinearProblem& lp, Key&& key, Col&& col, double scost = 0.0, double var_scale = 1.0) -> ColIndex
template<typename Key>
void add_state_col(LinearProblem& lp, Key&& key, ColIndex col_idx, double scost, double var_scale, LpContext context)
template<typename Key>
void add_state_variable(Key&& key, ColIndex col, double scost, double var_scale, LpContext context)
auto ampl_attribute_candidates(std::string_view class_name, Uid element_uid, std::size_t max_attrs = 12) const -> std::vector<std::string_view>
auto ampl_element_name_candidates(std::string_view class_name, std::string_view target, std::size_t max_names = 5) const -> std::vector<std::string_view>
auto block_discount_icost_factors() const -> const block_factor_matrix_t&
Returns cached discount-only inverse cost factors for blocks.
auto block_icost_factors() const -> const block_factor_matrix_t&
Returns cached inverse cost factors for blocks (1/cost_factor).
auto block_icost_factors_no_duration() const -> const block_factor_matrix_t&
Inverse cost factors for blocks WITHOUT the duration term.
template<typename Max>
auto block_max_at(const StageLP& stage, const BlockLP& block, const Max& lmax, const double capacity_max = LinearProblem::DblMax) const -> auto
template<typename Min, typename Max>
auto block_maxmin_at(const StageLP& stage, const BlockLP& block, const Max& lmax, const Min& lmin, const double capacity_max, const double capacity_min = 0.0) const -> std::pair<double, double>
void defer_state_link(StateVariable::Key prev_key, ColIndex here_col) const
template<typename FailCost>
auto demand_fail_cost(const StageLP& stage, const BlockLP& block, const FailCost& fcost) const -> Real
template<typename Element, template<typename> class Id>
auto element(const Id<Element>& id) const -> auto&&
template<typename Element, template<typename> class Id>
auto element_index(const Id<Element>& id) const -> auto
template<typename Element>
auto elements() const -> auto&&
auto find_ampl_active(std::string_view class_name) const -> AmplActiveFn noexcept
auto find_ampl_class_attribute(std::string_view class_name, std::string_view attribute) const -> bool
auto find_ampl_col(std::string_view class_name, Uid element_uid, std::string_view attribute, ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid) const -> std::optional<ColIndex>
auto find_ampl_cols(std::string_view class_name, Uid element_uid, std::string_view attribute, ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid) const -> std::span<const ColIndex>
auto find_ampl_compound(std::string_view class_name, std::string_view compound_name) const -> const std::vector<AmplCompoundLeg>* noexcept
Look up a compound PAMPL attribute by (class, compound_name).
auto find_ampl_element_metadata(std::string_view class_name, Uid element_uid) const -> const AmplElementMetadata* noexcept
auto find_ampl_iter(std::string_view class_name) const -> AmplIterFn noexcept
auto find_ampl_offset(std::string_view class_name, Uid element_uid, std::string_view attribute, ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid) const -> double
auto find_ampl_param(std::string_view class_name, std::string_view attribute) const -> AmplParamFn noexcept
auto find_ampl_scalar(std::string_view class_name, std::string_view attribute) const -> std::optional<double> noexcept
auto find_ampl_scoped_element(std::string_view class_name, Uid element_uid) const -> const std::string* noexcept
auto find_ampl_suppression(std::string_view class_name, std::string_view attribute) const -> std::optional<std::string_view> noexcept
auto find_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, ScenarioUid scenario_uid, StageUid stage_uid) const -> const AmplVariable*
auto find_ampl_variable_for_element(std::string_view class_name, Uid element_uid, std::string_view attribute) const -> bool
auto find_ampl_weighted_cols(std::string_view class_name, Uid element_uid, std::string_view attribute, ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid) const -> std::span<const std::pair<ColIndex, double>>
template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
auto flat(const GSTBIndexHolder<Value>& hstb, Projection proj, const Factor& factor = Factor()) const -> auto
Flattens GSTB-indexed data into dense vectors with optional scaling.
template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
auto flat(const STBIndexHolder<Value>& hstb, Projection proj, const Factor& factor, const STIndexHolder<double>& st_scale) const -> auto
template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
auto flat(const STBIndexHolder<Value>& hstb, Projection proj, const Factor& factor = Factor()) const -> auto
template<typename Projection, typename Value = Index, typename Factor = scenario_stage_factor_matrix_t>
auto flat(const STIndexHolder<Value>& hst, Projection proj, const Factor& factor = Factor()) const -> auto
template<typename Projection = std::identity, typename Value = Index, typename Factor = stage_factor_matrix_t>
auto flat(const TIndexHolder<Value>& ht, Projection proj = {}, const Factor& factor = {}) const -> auto
template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
auto flat_sparse(const GSTBIndexHolder<Value>& hstb, Projection proj, const Factor& factor = Factor()) const -> SparseEntries
Sparse long-form counterpart of flat() for GSTB holders.
template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
auto flat_sparse(const STBIndexHolder<Value>& hstb, Projection proj, const Factor& factor, const STIndexHolder<double>& st_scale) const -> SparseEntries
template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
auto flat_sparse(const STBIndexHolder<Value>& hstb, Projection proj, const Factor& factor = Factor()) const -> SparseEntries
template<typename Projection, typename Value = Index, typename Factor = scenario_stage_factor_matrix_t>
auto flat_sparse(const STIndexHolder<Value>& hst, Projection proj, const Factor& factor = Factor()) const -> SparseEntries
template<typename Projection = std::identity, typename Value = Index, typename Factor = stage_factor_matrix_t>
auto flat_sparse(const TIndexHolder<Value>& ht, Projection proj = {}, const Factor& factor = {}) const -> SparseEntries
auto get_bus(const ObjectSingleId<BusLP>& id) const -> const BusLP&
auto get_bus_index(const ObjectSingleId<BusLP>& id) const -> ElementIndex<BusLP>
template<typename Element>
auto get_element(const ElementIndex<Element>& id) const -> const Element&
template<typename Element>
auto get_element(const ObjectSingleId<Element>& id) const -> const Element&
template<typename Key>
auto get_integer_variable(Key&& key) const -> auto noexcept
template<typename Key>
auto get_state_variable(Key&& key) const -> auto noexcept
auto is_first_scenario(const ScenarioUid& scenario_uid) const -> bool noexcept
auto is_first_stage(const StageLP& stage) const -> bool noexcept
auto is_first_stage(const StageUid& stage_uid) const -> bool noexcept
auto is_last_stage(const StageUid& stage_uid) const -> bool noexcept
auto kind() const -> SystemKind noexcept
auto line_decision(Uid line_uid) const -> line_direction::LineDecision noexcept
auto lookup_ampl_element_uid(std::string_view class_name, std::string_view element_name) const -> std::optional<Uid>
Resolve an element name to its Uid within a class.
auto options() const -> auto&& noexcept
auto prev_stage(const StageLP& stage) const -> auto noexcept
void rebind_system(SystemLP& sys) noexcept
void register_ampl_element_metadata(std::string_view class_name, Uid element_uid, AmplElementMetadata metadata) const
auto replay_ampl_registry() const -> bool noexcept
template<typename FailCost>
auto reserve_shortage_cost(const StageLP& stage, const BlockLP& block, const FailCost& fcost) const -> auto
auto scenario_stage_icost_factors() const -> const scenario_stage_factor_matrix_t&
Returns cached inverse cost factors for scenario-stage pairs.
auto scenario_stage_icost_factors_no_duration() const -> const scenario_stage_factor_matrix_t&
void set_line_decisions(flat_map<Uid, line_direction::LineDecision> decisions) noexcept
void set_replay_ampl_registry(bool v) noexcept
void set_silent_flatten_pass(bool v) noexcept
auto silent_flatten_pass() const -> bool noexcept
auto simulation() const -> const SimulationLP& noexcept
template<typename Self>
auto simulation(this Self&& self) -> auto&& noexcept
auto st_uids() const -> STUids
auto stage_icost_factors() const -> const stage_factor_matrix_t&
Returns cached inverse cost factors for stages (1/cost_factor).
auto stage_icost_factors_no_duration() const -> const stage_factor_matrix_t&
template<typename LossFactor>
auto stage_lossfactor(const StageLP& stage, const LossFactor& lfact) const -> auto
template<typename Min, typename Max>
auto stage_maxmin_at(const StageLP& stage, const Min& lmax, const Max& lmin, const double capacity_max, const double capacity_min = 0.0) const -> std::pair<double, double>
template<typename Reactance>
auto stage_reactance(const StageLP& stage, const Reactance& reactance) const -> auto
template<typename StateCost>
auto state_violation_cost(const StageLP& stage, const BlockLP& block, const StateCost& scost) const -> auto
auto stb_uids() const -> STBUids
template<typename Self>
auto system(this Self&& self) -> auto&& noexcept
auto t_uids() const -> TUids

Function documentation

static double gtopt::SystemContext::block_ecost(const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block, const double cost) noexcept

Calculates the energy cost coefficient for a block.

Returns Total energy cost coefficient for LP formulation

Computes the total energy cost for a power variable over a block duration, applying:

  • Scenario probability weighting
  • Stage discount factor
  • Block duration

Formula: cost * probability * discount * duration

Note: scale_objective is NOT applied here. It is applied globally in LinearProblem::flatten() so that every objective coefficient is divided by the same scalar. Callers that place the result somewhere other than the objective column (e.g. as a constraint coefficient or RHS) must not rely on scale_objective being present.

static double gtopt::SystemContext::cost_factor(const double probability, const double discount, const double duration = 1.0) noexcept

static double gtopt::SystemContext::cost_factor(const ScenarioLP& scenario, const StageLP& stage) noexcept

static double gtopt::SystemContext::cost_factor(const ScenarioLP& scenario, const StageLP& stage, const BlockLP& block) noexcept

static double gtopt::SystemContext::cost_factor(const StageLP& stage, double probability = 1.0) noexcept

static double gtopt::SystemContext::scenario_stage_ecost(const ScenarioLP& scenario, const StageLP& stage, const double cost) noexcept

Calculates the energy cost coefficient for a scenario-stage pair.

Returns Total energy cost coefficient for LP formulation

Computes the total energy cost for a power variable over a stage duration, applying:

  • Scenario probability weighting
  • Stage discount factor
  • Stage duration

Formula: cost * probability * discount * duration

Note: scale_objective is NOT applied here; it is applied globally in LinearProblem::flatten().

static double gtopt::SystemContext::stage_ecost(const StageLP& stage, double cost, double probability = 1.0) noexcept

Calculates the energy cost coefficient for a stage.

Returns Total energy cost coefficient for LP formulation

Computes the total energy cost for a power variable over a stage duration, applying:

  • Probability weighting (default 1.0)
  • Stage discount factor
  • Stage duration

Formula: cost * probability * discount * duration

Note: scale_objective is NOT applied here; it is applied globally in LinearProblem::flatten().

size_t gtopt::SystemContext::active_block_count() const noexcept

const auto& gtopt::SystemContext::active_blocks() const noexcept

size_t gtopt::SystemContext::active_scenario_count() const noexcept

const auto& gtopt::SystemContext::active_scenarios() const noexcept

const auto& gtopt::SystemContext::active_stage_blocks() const noexcept

size_t gtopt::SystemContext::active_stage_count() const noexcept

const auto& gtopt::SystemContext::active_stages() const noexcept

void gtopt::SystemContext::add_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, const ScenarioLP& scenario, const StageLP& stage, const BIndexHolder<ColIndex>& block_cols) const

Register a per-block column map (e.g., generator.generation). Stores a copy of block_cols; the element need not keep it alive.

Marked const (logical-const): the underlying SimulationLP is held via reference_wrapper, so const SystemContext methods may still mutate the simulation's ampl variable registry. This lets elements whose add_to_lp takes const SystemContext& register their PAMPL-visible columns without signature churn.

Routes to the per-(scene, phase) cell of the current SystemLP — system().scene().index() / system().phase().index() — so the write needs no synchronization (one writer per cell, sequential across phases within a scene). Defined out-of-line in system_context.cpp because reaching the SystemLP accessors requires the full system_lp.hpp definition.

void gtopt::SystemContext::add_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, const ScenarioLP& scenario, const StageLP& stage, const BIndexHolder<ColIndex>& block_cols, const BIndexHolder<double>& block_offsets) const

Same as above but with per-block additive offsets. Used by shifted-variable encodings (e.g., demand's Option C neg_fail = load − lmax). The offsets feed into the user- constraint resolver's param_shift accumulator so references to demand.load resolve to (col + offset) physically.

void gtopt::SystemContext::add_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, const ScenarioLP& scenario, const StageLP& stage, const BIndexHolder<std::vector<ColIndex>>& block_cols_sum) const

Register a per-block sum of LP cols for a virtual aggregator attribute. Used by LineLP::add_to_lp under piecewise_direct line-loss mode so AMPL references to line.flowp / line.flown expand to Σ flowp_seg_k / Σ flown_seg_k without ever materialising an aggregator LP column. See AmplVariable::block_cols_sum for the data layout.

void gtopt::SystemContext::add_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, const ScenarioLP& scenario, const StageLP& stage, const BIndexHolder<std::vector<std::pair<ColIndex, double>>>& block_cols_weighted_sum, const BIndexHolder<double>& block_offsets = {}) const

Register a per-block weighted sum of LP cols — every leg carries its own coefficient. Used by FuelLP::add_to_lp to expose fuel("X").offtake = Σ_g heat_rate_g · dur_b · generation_g[b] without creating an aggregator LP column + equality binding row (the substitute-out anti-pattern fix, mirror of the EmissionZone.production removal). Resolver stamps row[col] += base_coef · weight per leg. See AmplVariable::block_cols_weighted_sum for the data layout. Optional block_offsets add a per-block constant (folded onto the row RHS by the resolver) — used by demand.fail = lmax − Σ load_k.

template<typename Key, typename Col>
ColIndex gtopt::SystemContext::add_integer_col(LinearProblem& lp, Key&& key, Col&& col, IntegerDomain domain, IntegerScope scope, GroupUid group_uid, std::span<const BlockUid> blocks)

Atomic helper: add an integer LP column AND register it in the integer-variable map. The preferred API for every producer of an integer column.

domain selects {Binary, Integer, Relaxed}; Relaxed keeps the column continuous (is_integer = false). The producer is responsible for the relax precedence: per-element relax flag wins over the global option, which wins over the call-site default — Commitment.relax is already resolved before this call.

blocks is the per-block fan-out for the registry's IntegerVariable::blocks() accessor. For Block scope it is the single block uid; for Group scope it is every block in the group; for Stage scope it is every block of the stage; for Phase scope it should be empty (the registry returns std::nullopt to callers regardless of what is passed).

template<typename Key>
void gtopt::SystemContext::add_integer_variable(Key&& key, ColIndex col, IntegerDomain domain, IntegerScope scope, GroupUid group_uid, std::span<const BlockUid> blocks)

Register one integer LP column in the simulation's integer-variable map. Mirrors add_state_variable (void wrapper around SimulationLP::add_integer_variable).

Honours the silent-flatten gate: under rebuild, the registry already holds an equivalent entry, so this call is a no-op (same rationale as the state-variable wrapper).

template<typename Key, typename Col>
ColIndex gtopt::SystemContext::add_state_col(LinearProblem& lp, Key&& key, Col&& col, double scost = 0.0, double var_scale = 1.0)

Atomic helper: add a new state-variable column to the LP AND register it in the state-variable map. Sets is_state = true on the column so it is recognized as a state variable; column names are available at LpNamesLevel::all, but state variable I/O uses the StateVariable map (ColIndex-based) directly. The column's context field is also used as the StateVariable's context, keeping the two in sync.

This is the preferred API for creating state variables — calling lp.add_col() and add_state_variable() separately risks forgetting one step and silently breaking cut I/O.

template<typename Key>
void gtopt::SystemContext::add_state_col(LinearProblem& lp, Key&& key, ColIndex col_idx, double scost, double var_scale, LpContext context)

Atomic helper: mark an already-added column as a state variable AND register it in the state-variable map. Used when the state-variable role is decided after the column was first added (e.g. storage_lp registers the last block's energy column as efin after the whole block loop is done).

std::vector<std::string_view> gtopt::SystemContext::ampl_attribute_candidates(std::string_view class_name, Uid element_uid, std::size_t max_attrs = 12) const

Diagnostic-only: attribute names registered as LP variables for the (class_name, element_uid) pair. Used to build a "valid attributes are ..." hint when a user constraint references a known element with an unknown attribute. Only called on the strict-mode error path.

std::vector<std::string_view> gtopt::SystemContext::ampl_element_name_candidates(std::string_view class_name, std::string_view target, std::size_t max_names = 5) const

Diagnostic-only: registered element names for class_name nearest to target (edit-distance ordered). Used to build a "did you mean ...?" hint when a user constraint references an unknown element name. Only called on the strict-mode error path.

const block_factor_matrix_t& gtopt::SystemContext::block_discount_icost_factors() const

Returns cached discount-only inverse cost factors for blocks.

Returns Const reference to cached matrix of discount-only inverse cost factors

Lazily computed on first call, then cached. Formula: scale_objective / discount[t] (same for all s, b in stage t)

const block_factor_matrix_t& gtopt::SystemContext::block_icost_factors() const

Returns cached inverse cost factors for blocks (1/cost_factor).

Returns Const reference to cached matrix of inverse cost factors

Lazily computed on first call, then cached for subsequent accesses. Formula: 1 / (probability * discount * duration / scale_objective)

const block_factor_matrix_t& gtopt::SystemContext::block_icost_factors_no_duration() const

Inverse cost factors for blocks WITHOUT the duration term.

Returns Const reference to cached matrix of duration-free inverse factors

Lazily computed, then cached. Formula: 1 / (probability * discount) (same for all blocks in a stage)

Use for duals of stock constraints (storage energy balance → water value / energy shadow price, $ per stored-unit), which must not be divided by block duration the way per-block power-balance duals (LMP) are.

void gtopt::SystemContext::defer_state_link(StateVariable::Key prev_key, ColIndex here_col) const

Queue a deferred dependent-variable link to be resolved later by the per-scene tightening pass. Use this in element add_to_lp instead of calling get_state_variable(prev_key)->add_dependent_variable directly: under parallel phase construction within a scene, the previous phase's StateVariable may not yet exist when phase N+1 runs, and concurrent vector growth on its dependent-variable list would race.

prev_key identifies the producing StateVariable in the previous phase (its lp_key.scene_index / lp_key.phase_index are the previous phase's identity, set by the caller via StateVariable::key(scenario, *prev_stage, ...)). here_col is the dependent column just added to this phase's LP — its (scene, phase) identity is taken from the bound SystemLP, so the caller need not pass it explicitly.

Defined out-of-line in system_context.cpp because reaching system().scene() / system().phase() and system().defer_state_link requires the full system_lp.hpp definition.

template<typename FailCost>
Real gtopt::SystemContext::demand_fail_cost(const StageLP& stage, const BlockLP& block, const FailCost& fcost) const

Resolves a Demand.fcost (OptTBRealSched) at the (stage, block) grain, falling back to the global model_options.demand_fail_cost when unset (which itself defaults to PlanningOptionsLP::default_demand_fail_cost). Returned in [$/MWh].

AmplActiveFn gtopt::SystemContext::find_ampl_active(std::string_view class_name) const noexcept

Class-level element activity probe (see AmplActiveFn); nullptr when the class registered none.

bool gtopt::SystemContext::find_ampl_class_attribute(std::string_view class_name, std::string_view attribute) const

Is the (class, attribute) pair registered as an LP variable for any element of the class? Used to extend the user-constraint resolver's silent-0 leniency to the LP-attr-dormant case: the element name is known but ITS particular column was never materialised because it has zero capacity over the entire horizon — yet the attribute IS a valid LP variable on the class (some other element registers it). PLEXOS treats the term as a constant 0 contribution to the LHS; gtopt should match. Delegates to SimulationLP::find_ampl_class_attribute.

std::optional<ColIndex> gtopt::SystemContext::find_ampl_col(std::string_view class_name, Uid element_uid, std::string_view attribute, ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid) const

Look up a registered variable column. Returns nullopt if the (class, uid, attribute, scenario, stage, block) combination was never registered. Reads from the current SystemLP's (scene, phase) cell — the resolver always queries within the LP that owns the row being assembled.

std::span<const ColIndex> gtopt::SystemContext::find_ampl_cols(std::string_view class_name, Uid element_uid, std::string_view attribute, ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid) const

Look up a registered sum-of-cols attribute (virtual aggregator). Returns an empty span when the attribute is not registered as a sum (callers fall back to find_ampl_col).

const AmplElementMetadata* gtopt::SystemContext::find_ampl_element_metadata(std::string_view class_name, Uid element_uid) const noexcept

Look up an element's metadata bundle (F9). Returns nullptr when the element has no registered metadata.

AmplIterFn gtopt::SystemContext::find_ampl_iter(std::string_view class_name) const noexcept

Look up the class-level iterator function for class_name. Returns nullptr when the class is not registered (means the class does not participate in sum(class(all)...) enumeration).

double gtopt::SystemContext::find_ampl_offset(std::string_view class_name, Uid element_uid, std::string_view attribute, ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid) const

Look up the per-block additive offset registered alongside a shifted variable (e.g., demand's Option C col). Returns 0.0 when the variable has no offsets — the common case.

AmplParamFn gtopt::SystemContext::find_ampl_param(std::string_view class_name, std::string_view attribute) const noexcept

Look up the class-level parameter resolver for (class, attribute). Returns nullptr when the pair is not registered — see SimulationLP::register_ampl_param for the population side. Used by element_column_resolver.cpp::resolve_single_param to replace the legacy per-class if/else dispatch with a single map lookup + indirect call.

std::optional<double> gtopt::SystemContext::find_ampl_scalar(std::string_view class_name, std::string_view attribute) const noexcept

Look up a class-level scalar (e.g. options.scale_objective). Returns nullopt when the (class, attribute) pair is not in the allow-list registered by system_lp.cpp::register_all_ampl_element_names.

const std::string* gtopt::SystemContext::find_ampl_scoped_element(std::string_view class_name, Uid element_uid) const noexcept

Scope description of a scope-restricted element (a coarse-scope or single-block DecisionVariable), or nullptr. See SimulationLP::register_ampl_scoped_element.

std::optional<std::string_view> gtopt::SystemContext::find_ampl_suppression(std::string_view class_name, std::string_view attribute) const noexcept

Returns the suppression reason if the class or (class, attribute) pair has been marked unavailable by the current planning mode (e.g. line under use_single_bus, bus.theta when Kirchhoff is disabled). A non-empty result means the resolver should silently drop the referencing term instead of throwing.

const AmplVariable* gtopt::SystemContext::find_ampl_variable(std::string_view class_name, Uid element_uid, std::string_view attribute, ScenarioUid scenario_uid, StageUid stage_uid) const

Look up a registered AMPL variable by key (no block). Returns a node-stable pointer to the registry entry, or nullptr when unregistered. The resolver uses this to hash the key ONCE per (term, block) and then read every per-block shape (col_at / cols_at / weighted_cols_at / offset_at) directly off the entry.

bool gtopt::SystemContext::find_ampl_variable_for_element(std::string_view class_name, Uid element_uid, std::string_view attribute) const

Is the (class, element_uid, attribute) triple registered as an LP variable somewhere in the simulation? Used by the user-constraint resolver to distinguish "element/attribute exist, just no column for this specific (scene, phase, scenario, stage, block)" (treat-as-zero) from "attribute is a typo or unsupported on this element" (strict-mode error). Delegates to SimulationLP::find_ampl_variable_for_element.

std::span<const std::pair<ColIndex, double>> gtopt::SystemContext::find_ampl_weighted_cols(std::string_view class_name, Uid element_uid, std::string_view attribute, ScenarioUid scenario_uid, StageUid stage_uid, BlockUid block_uid) const

Look up a registered weighted sum-of-cols attribute. Returns an empty span when the attribute is not registered with weighted legs (callers fall through to single-col / unweighted-sum paths in that case). Stamping rule: row[col] += base_coef · weight per leg.

template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
auto gtopt::SystemContext::flat(const GSTBIndexHolder<Value>& hstb, Projection proj, const Factor& factor = Factor()) const

Flattens GSTB-indexed data into dense vectors with optional scaling.

Parameters
hstb The GSTB-indexed data holder
proj Projection function to apply to each value
factor Optional scaling factors (applied after projection)
Returns Pair of (values, valid) vectors

Processes a 3D (Scenario/Stage/Block) indexed container into:

  • Values vector with projected/scaled values
  • Valid vector marking which indices had data

Implemented as flat_sparse() + a dense scatter, preserving the historical dense contract exactly (see scatter_flat). The write-out path no longer uses this — OutputContext consumes flat_sparse() directly — but the dense form remains for reference/tests and any consumer that wants the full grid.

template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
auto gtopt::SystemContext::flat(const STBIndexHolder<Value>& hstb, Projection proj, const Factor& factor, const STIndexHolder<double>& st_scale) const

flat() overload that applies an additional per-(scenario,stage) scale factor on top of the block-level factor. Used by StorageLP::add_to_output to back-scale volume-balance duals when the daily-cycle option was active for a stage (scale = 24/stage_dur).

The st_scale lookup is performed once per (scenario,stage) pair, outside the block loop, so there is no per-block overhead. When a (suid,tuid) key is absent from st_scale the scale defaults to 1.0 (i.e. no scaling is applied for that stage), making this a safe drop-in for the plain flat() call when st_scale is empty.

template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
auto gtopt::SystemContext::flat(const STBIndexHolder<Value>& hstb, Projection proj, const Factor& factor = Factor()) const

template<typename Projection, typename Value = Index, typename Factor = scenario_stage_factor_matrix_t>
auto gtopt::SystemContext::flat(const STIndexHolder<Value>& hst, Projection proj, const Factor& factor = Factor()) const

template<typename Projection = std::identity, typename Value = Index, typename Factor = stage_factor_matrix_t>
auto gtopt::SystemContext::flat(const TIndexHolder<Value>& ht, Projection proj = {}, const Factor& factor = {}) const

template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
SparseEntries gtopt::SystemContext::flat_sparse(const GSTBIndexHolder<Value>& hstb, Projection proj, const Factor& factor = Factor()) const

Sparse long-form counterpart of flat() for GSTB holders.

Parameters
hstb The GSTB-indexed data holder
proj Projection function to apply to each value
factor Optional scaling factors (applied after projection)
Returns (grid-slot, value) entries, slot-ascending

Collects ONLY the holder's own entries as (grid-slot, value) pairs sorted ascending by slot. The slot index is exactly the position the dense flat() vector fills for the same entry (si * stride + block_base + bi), so callers can label each sample with the slot's (scenario, stage, block) uids without materialising the dense grid. This is the write-out hot path: per element-field stream the work is O(H log H) in the holder size H instead of O(active grid).

Stray holder keys (inactive scenario/stage uid, unknown uid, block uid filed under the wrong stage, P1 zero-bound-elided blocks) are skipped exactly as the dense fill skips them. Explicit zero values are KEPT (the long-form writer drops them at emission time, after any post-collection value snapping).

template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
SparseEntries gtopt::SystemContext::flat_sparse(const STBIndexHolder<Value>& hstb, Projection proj, const Factor& factor, const STIndexHolder<double>& st_scale) const

flat_sparse() overload that applies an additional per-(scenario,stage) scale factor on top of the block-level factor — sparse counterpart of the st_scale flat() overload below (StorageLP daily-cycle dual back-scaling).

template<typename Projection, typename Value = Index, typename Factor = block_factor_matrix_t>
SparseEntries gtopt::SystemContext::flat_sparse(const STBIndexHolder<Value>& hstb, Projection proj, const Factor& factor = Factor()) const

Sparse long-form counterpart of flat() for STB holders. See the GSTB overload for the contract. Blocks not present in a stage's active block list are simply skipped: the P1 zero-bound skip in generator_lp.cpp:131 / waterway_lp.cpp:72 / demand_lp.cpp:206 may have elided individual block entries while leaving the outer (scenario, stage) key populated; elided slots emit no entry, same as the outer-key-missing case.

template<typename Projection, typename Value = Index, typename Factor = scenario_stage_factor_matrix_t>
SparseEntries gtopt::SystemContext::flat_sparse(const STIndexHolder<Value>& hst, Projection proj, const Factor& factor = Factor()) const

Sparse long-form counterpart of flat() for ST holders. Slot index is si * active_stage_count + ti.

template<typename Projection = std::identity, typename Value = Index, typename Factor = stage_factor_matrix_t>
SparseEntries gtopt::SystemContext::flat_sparse(const TIndexHolder<Value>& ht, Projection proj = {}, const Factor& factor = {}) const

Sparse long-form counterpart of flat() for T holders. Slot index is the active-stage position.

bool gtopt::SystemContext::is_first_scenario(const ScenarioUid& scenario_uid) const noexcept

bool gtopt::SystemContext::is_first_stage(const StageLP& stage) const noexcept

bool gtopt::SystemContext::is_first_stage(const StageUid& stage_uid) const noexcept

bool gtopt::SystemContext::is_last_stage(const StageUid& stage_uid) const noexcept

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

Which LP registry (forward vs aperture) this context's state-variable and link registrations are routed to. Set once at construction.

auto gtopt::SystemContext::prev_stage(const StageLP& stage) const noexcept

void gtopt::SystemContext::rebind_system(SystemLP& sys) noexcept

Re-point the back-reference to a new SystemLP owner (used by SystemLP's move-ctor/assign so the embedded SystemContext stays consistent after the SystemLP is relocated). Also rebuilds m_collection_ptrs_ from the new owner's collections tuple, because each pointer is an interior pointer into the SystemLP that just moved. Defined out-of-line in system_context.cpp because reaching SystemLP::collections() requires system_lp.hpp.

void gtopt::SystemContext::register_ampl_element_metadata(std::string_view class_name, Uid element_uid, AmplElementMetadata metadata) const

Register filter metadata for one element (F9). See SimulationLP::register_ampl_element_metadata.

bool gtopt::SystemContext::replay_ampl_registry() const noexcept

Whether the AMPL variable/metadata registry should be repopulated even during a silent rebuild pass (see silent_flatten_pass).

template<typename FailCost>
auto gtopt::SystemContext::reserve_shortage_cost(const StageLP& stage, const BlockLP& block, const FailCost& fcost) const

Resolves a ReserveZone.urcost / ReserveZone.drcost / InertiaZone.cost (OptTBRealSched) at the (stage, block) grain, falling back to the global model_options.reserve_shortage_cost. Returned in [$/MW] (reserves) or [$/MWs] (inertia).

const scenario_stage_factor_matrix_t& gtopt::SystemContext::scenario_stage_icost_factors() const

Returns cached inverse cost factors for scenario-stage pairs.

Returns Const reference to cached matrix of inverse cost factors

Lazily computed on first call, then cached. Formula: 1 / (probability * discount * duration / scale_objective)

const scenario_stage_factor_matrix_t& gtopt::SystemContext::scenario_stage_icost_factors_no_duration() const

Per-(scenario, stage) inverse factors WITHOUT duration: 1 / (probability * discount). Use for per-stage STOCK / commodity duals & reduced costs (storage efin / soft_emin / eini state, per-stage fuel offtake $/fuel-unit).

void gtopt::SystemContext::set_line_decisions(flat_map<Uid, line_direction::LineDecision> decisions) noexcept

Structural line-direction decisions (line_direction_mode / Line.flow_direction = "auto"), computed once by SystemLP before the first flatten. Lines without an entry get the default (both, KVL kept) — i.e. today's LP.

bool gtopt::SystemContext::silent_flatten_pass() const noexcept

Rebuild-pass flag. Set to true by SystemLP::rebuild_collections_if_needed while a throw-away flatten regenerates the per-element XLP state (under LowMemoryMode::compress, after release_backend() dropped the disposable element wrappers). Cross-phase / engine registry side-effects (add_state_variable, add_integer_variable, defer_state_link) become no-ops when the flag is set — the initial pass already populated those registries with matching col indices, and re-registering on rebuild would duplicate cross-phase links or burn CPU for zero gain.

EXCEPTION — the per-cell AMPL variable/metadata registry (add_ampl_variable, register_ampl_element_metadata): the production solve path frees it after the initial flatten (LpMatrixOptions::release_ampl_after_flatten → SimulationLP::release_ampl_cell). A subsequent rebuild flatten (e.g. write_out) re-runs UserConstraintLP::add_to_lp, which resolves element columns through that registry — so it MUST be repopulated, or user constraints fail with "unknown attribute". set_replay_ampl_registry(true) makes those two registrations run even on the silent pass; the writes are idempotent (same deterministic col indices) so replaying when the registry was NOT released is harmless.

const SimulationLP& gtopt::SystemContext::simulation() const noexcept

STUids gtopt::SystemContext::st_uids() const

const stage_factor_matrix_t& gtopt::SystemContext::stage_icost_factors() const

Returns cached inverse cost factors for stages (1/cost_factor).

Returns Const reference to cached vector of inverse cost factors

Lazily computed on first call (probability = 1.0), then cached. Formula: 1 / (discount * duration / scale_objective)

const stage_factor_matrix_t& gtopt::SystemContext::stage_icost_factors_no_duration() const

Per-stage inverse factors WITHOUT duration: 1 / discount. Use for per-stage STOCK / commodity duals (e.g. emission cap $/tonne).

template<typename StateCost>
auto gtopt::SystemContext::state_violation_cost(const StageLP& stage, const BlockLP& block, const StateCost& scost) const

Resolves an OptTBRealSched-typed state cost (e.g. Reservoir.scost, LngTerminal.scost) at the (stage, block) grain, falling back to the global model_options.state_violation_cost. Returned in [$/MWh] (energy-equivalent — multiplied by element-specific mean_production_factor at the caller).

STBUids gtopt::SystemContext::stb_uids() const

TUids gtopt::SystemContext::t_uids() const