Skip to main content

StudySetup

Struct StudySetup 

Source
pub struct StudySetup {
    pub stage_data: StageData,
    pub stochastic: StochasticContext,
    pub fcf: FutureCostFunction,
    pub hydro_models: PrepareHydroModelsResult,
    pub scenario_libraries: ScenarioLibraries,
    pub loop_params: LoopParams,
    pub simulation_config: SimulationConfig,
    pub policy_path: String,
    /* private fields */
}
Expand description

All precomputed study state built once before training and simulation.

Constructed by StudySetup::new from a validated System and cobre_io::Config. Owns all data so it can be held across async boundaries (e.g., Python GIL release) without lifetime issues.

Callers build TrainingContext and StageContext by borrowing from StudySetup.

Fields§

§stage_data: StageData

Stage-indexed data: LP templates, indexer, stages, entity counts, blocks, lag transitions, noise groups, and scaling report.

§stochastic: StochasticContext

Stochastic context holding sampling distributions, libraries, and provenance.

§fcf: FutureCostFunction

Future cost function (cut pool) updated by the backward pass during training.

§hydro_models: PrepareHydroModelsResult

Pre-computed hydro production models (FPHA, turbine curves, etc.).

§scenario_libraries: ScenarioLibraries

Sampling schemes and pre-built libraries for training and simulation phases.

Replaces the 14 flat inflow_scheme / sim_inflow_scheme / … fields. Access via scenario_libraries.training.<field> or scenario_libraries.simulation.<field>.

§loop_params: LoopParams

Iteration-loop parameters projected from crate::config::LoopConfig.

Holds the five pure-data fields of crate::config::LoopConfig that are stable across training invocations. n_fwd_threads is excluded (derived at runtime) and supplied as a per-call argument to StudySetup::train.

§simulation_config: SimulationConfig

Simulation pipeline parameters, stored directly as crate::simulation::SimulationConfig.

§policy_path: String

Relative path to the policy output directory (e.g. "training/policy").

Implementations§

Source§

impl StudySetup

Source

pub fn replace_fcf(&mut self, fcf: FutureCostFunction)

Replace the FCF with a pre-loaded policy.

Source

pub fn set_start_iteration(&mut self, iteration: u64)

Set the starting iteration for resumed training.

Source

pub fn set_warm_start_basis_cache(&mut self, cache: Vec<Option<CapturedBasis>>)

Seed the per-stage warm-start basis cache for warm-start / resume training.

cache carries one entry per stage (as built by build_basis_cache_from_checkpoint from the checkpoint’s stored solver bases). StudySetup::train takes this out of self and replicates each stage’s basis across every forward-pass worker so iteration 1’s cut-loaded LPs warm-start.

Leave unset (the default None) for a fresh start.

Source

pub fn set_export_states(&mut self, export: bool)

Enable state archiving for export.

Source

pub fn set_budget(&mut self, budget: Option<u32>)

Set the active-cut budget cap per stage.

Source

pub fn energy_conversion(&self) -> &EnergyConversionSet

Return the pre-computed EnergyConversionSet for this study.

Provides ρ_eq, V_ref, Q_ref, and ρ_acum (accumulated cascade productivity) for every (hydro, stage) pair. Consumed by the energy-balance LP constraints and inflow-energy / stored-energy extraction.

Source

pub fn simulation_config(&self) -> &SimulationConfig

Return a reference to the simulation configuration.

Source

pub fn stage_indexer(&self) -> &StageIndexer

Return a reference to the per-stage LP column/row indexer.

Provides LP layout constants — column and row ranges for every entity class (storage, thermal, anticipated state, etc.) — so that callers can locate specific primal or state-vector entries without hard-coding offsets.

The same indexer applies to every stage (the layout is uniform across stages in a study).

Source

pub fn num_stages(&self) -> usize

Number of stages in the planning horizon.

Used by the CLI summary to express the pool-level active-row total on a per-stage basis, so it is directly comparable to the per-solve rows-in-LP metric reported for Dynamic Cut Selection.

Source

pub fn stage_ctx(&self) -> StageContext<'_>

Construct a StageContext borrowing from this setup.

Source§

impl StudySetup

Source

pub fn train<S, C: Communicator>( &mut self, solver: &mut S, comm: &C, n_threads: usize, solver_factory: impl Fn() -> Result<S, SolverError>, event_sender: Option<Sender<TrainingEvent>>, shutdown_flag: Option<&Arc<AtomicBool>>, ) -> Result<TrainingOutcome, SddpError>
where S: SolverInterface<Profile = ActiveProfile> + Send,

Execute the training loop.

Constructs TrainingConfig and TrainingContext, then delegates to crate::train. Mutates self.fcf to store generated cuts.

§Errors

Returns SddpError::Infeasible, SddpError::Solver, or SddpError::Communication on LP, solver, or MPI failure.

Source

pub fn simulate<S, C: Communicator>( &self, workspaces: &mut [SolverWorkspace<S>], comm: &C, result_tx: &SyncSender<SimulationScenarioResult>, event_sender: Option<Sender<TrainingEvent>>, baked_templates: Option<&[StageTemplate]>, stage_bases: &[Option<CapturedBasis>], ) -> Result<SimulationRunResult, SimulationError>
where S: SolverInterface<Profile = ActiveProfile> + Send,

Run simulation using the trained future cost function.

The caller provides channels, event sender, and thread management. baked_templates enables the baked-template LP load path (no add_rows per stage); pass None for the legacy load_model + add_rows fallback. stage_bases enables warm-start; pass &[] for cold-start.

§Errors

Returns SimulationError on LP infeasibility, solver failure, channel closure, or if baked_templates.len() != num_stages.

Source

pub fn build_training_output( &self, result: &TrainingResult, events: &[TrainingEvent], ) -> TrainingOutput

Convert TrainingResult and events into training output.

Delegates to crate::build_training_output with cut statistics from self.fcf.

Source

pub fn create_workspace_pool<S: SolverInterface + Send, C: Communicator>( &self, comm: &C, n_threads: usize, solver_factory: impl Fn() -> Result<S, SolverError>, ) -> Result<WorkspacePool<S>, SolverError>

Create a WorkspacePool sized for this study.

Pool size equals n_threads. Each workspace gets a fresh solver instance. comm is used to read the MPI rank that is stamped into each workspace’s rank field for downstream per-worker observability.

§Errors

Returns SolverError if solver creation fails.

§Panics

Panics if comm.rank() > i32::MAX. MPI world sizes are bounded well below this on all real systems.

Source§

impl StudySetup

Source

pub fn new( system: &System, config: &Config, stochastic: StochasticContext, hydro_models: PrepareHydroModelsResult, ) -> Result<Self, SddpError>

Build all precomputed study state from a validated system and config.

The constructor performs:

  1. Config field extraction (seed, forward passes, stopping rules, etc.)
  2. Delegates to StudySetup::from_broadcast_params with the extracted values.
§Errors
  • SddpError::Validation — if build_stage_templates succeeds but the template list is empty (“system has no study stages”).
  • SddpError::Solver — propagated from build_stage_templates on LP construction failure.
  • SddpError::Validation — if parse_cut_selection_config returns an invalid config string.
Source

pub fn from_broadcast_params( system: &System, stochastic: StochasticContext, config: ConstructionConfig, hydro_models: PrepareHydroModelsResult, training_source: &ScenarioSource, simulation_source: &ScenarioSource, ) -> Result<Self, SddpError>

Build all precomputed study state from pre-resolved broadcast parameters.

This constructor accepts the scalar fields already extracted from either a cobre_io::Config (on rank 0) or a broadcast config struct (on non-root ranks). It performs the expensive computation steps that cannot be serialised:

  1. build_stage_templates — constructs LP skeletons for each stage
  2. StageIndexer::with_equipment — computes LP column/row offsets
  3. build_initial_state — extracts initial storage and past inflows from system IC
  4. max_iterations_from_rules — sizes the FCF cut pool
  5. FutureCostFunction::new — pre-allocates cut storage
  6. HorizonMode::Finite — wraps stage count
  7. Risk measures from stage configs
  8. build_entity_counts — entity ID and productivity vectors
  9. Block layout derivation (block_counts_per_stage, max_blocks)
§Errors
  • SddpError::Validation — if build_stage_templates succeeds but the template list is empty (“system has no study stages”).
  • SddpError::Solver — propagated from build_stage_templates on LP construction failure.

Trait Implementations§

Source§

impl Debug for StudySetup

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Allocation for T
where T: RefUnwindSafe + Send + Sync,

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more