cobre-sddp 0.4.4

Stochastic Dual Dynamic Programming (SDDP) for hydrothermal dispatch and energy planning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Configuration types for the SDDP training loop.
//!
//! [`TrainingConfig`] bundles all algorithm parameters that control the
//! training loop behaviour: iteration budget, forward scenario count,
//! checkpoint cadence, warm-start cut count, and the optional event channel
//! for real-time progress reporting.
//!
//! ## Construction
//!
//! `TrainingConfig` does not implement `Default` — every field must be
//! explicitly supplied by the caller to prevent silent misconfigurations
//! (e.g., a zero `forward_passes` count or an unintentionally large
//! `max_iterations`).
//!
//! ## Event channel
//!
//! The `event_sender` field carries an `Option<Sender<TrainingEvent>>`.
//! When `None`, the training loop emits no events and incurs no channel
//! overhead. When `Some(sender)`, typed [`cobre_core::TrainingEvent`] values
//! are moved into the channel at each lifecycle step boundary.
//!
//! Because `Sender<T>` is not `Clone` in the general sense (it can be cloned,
//! but ownership transfer is the primary pattern), `TrainingConfig` does not
//! derive `Clone`. Callers that need to pass config to multiple locations
//! should construct separate instances.
//!
//! # Examples
//!
//! ```rust
//! use cobre_sddp::TrainingConfig;
//!
//! let config = TrainingConfig {
//!     forward_passes: 10,
//!     max_iterations: 200,
//!     checkpoint_interval: Some(50),
//!     warm_start_cuts: 0,
//!     event_sender: None,
//!     cut_activity_tolerance: 1e-6,
//!     n_fwd_threads: 1,
//!     max_blocks: 1,
//!     cut_selection: None,
//!     shutdown_flag: None,
//!     start_iteration: 0,
//!     export_states: false,
//!     angular_pruning: None,
//!     budget: None,
//!     basis_padding_enabled: false,
//! };
//! assert_eq!(config.forward_passes, 10);
//! assert_eq!(config.max_iterations, 200);
//! assert_eq!(config.checkpoint_interval, Some(50));
//! ```

use std::sync::Arc;
use std::sync::atomic::AtomicBool;

use cobre_core::TrainingEvent;

use crate::angular_pruning::AngularPruningParams;
use crate::cut_selection::CutSelectionStrategy;

/// Parameters controlling the SDDP training loop.
///
/// Construct this struct directly — all fields are public and there is no
/// builder or `Default` implementation. Every field must be set explicitly
/// to prevent silent misconfiguration.
///
/// # Examples
///
/// ```rust
/// use cobre_sddp::TrainingConfig;
///
/// let config = TrainingConfig {
///     forward_passes: 10,
///     max_iterations: 100,
///     checkpoint_interval: None,
///     warm_start_cuts: 0,
///     event_sender: None,
///     cut_activity_tolerance: 1e-6,
///     n_fwd_threads: 1,
///     max_blocks: 1,
///     cut_selection: None,
///     shutdown_flag: None,
///     start_iteration: 0,
///     export_states: false,
///     angular_pruning: None,
///     budget: None,
///     basis_padding_enabled: false,
/// };
/// assert_eq!(config.forward_passes, 10);
/// assert_eq!(config.max_iterations, 100);
/// ```
#[derive(Debug)]
pub struct TrainingConfig {
    /// Total number of forward scenarios evaluated per iteration across all ranks.
    ///
    /// The work is divided among MPI ranks: each rank evaluates
    /// `forward_passes / num_ranks` scenarios (with remainder distributed to
    /// the first ranks). Must be at least 1.
    pub forward_passes: u32,

    /// Maximum number of training iterations before forced termination.
    ///
    /// Also used for cut pool pre-sizing: the cut pool allocates capacity
    /// for `max_iterations * forward_passes * num_stages` cuts at
    /// initialisation to avoid reallocation during the training loop.
    /// Must be at least 1.
    pub max_iterations: u64,

    /// Number of iterations between checkpoint writes.
    ///
    /// When `Some(n)`, the training loop writes a checkpoint after every `n`
    /// completed iterations (i.e., when `iteration % n == 0`). When `None`,
    /// no checkpoints are written during training (a final checkpoint may
    /// still be written at convergence depending on caller configuration).
    pub checkpoint_interval: Option<u64>,

    /// Number of pre-loaded cuts imported from a warm-start policy file.
    ///
    /// When non-zero, the cut pool is pre-populated from a serialised policy
    /// before the first training iteration begins. The warm-start cut count
    /// contributes to the cut pool capacity calculation alongside
    /// `max_iterations`.
    pub warm_start_cuts: u32,

    /// Optional channel sender for real-time training progress events.
    ///
    /// When `Some(sender)`, the training loop emits [`TrainingEvent`] values
    /// at each lifecycle step boundary (forward pass, backward pass,
    /// convergence update, etc.). When `None`, no events are emitted and no
    /// channel allocation occurs on the hot path.
    ///
    /// The receiver end must be consumed on a separate thread or task to
    /// prevent the channel from filling and blocking the training loop.
    pub event_sender: Option<std::sync::mpsc::Sender<TrainingEvent>>,

    /// Activity tolerance for cut selection deactivation.
    ///
    /// Cuts with activity (dual value) below this threshold across all openings
    /// in a backward pass are candidates for deactivation. Typical value: `1e-6`.
    pub cut_activity_tolerance: f64,

    /// Number of rayon threads for forward pass parallelism.
    ///
    /// Controls how many worker threads execute forward scenarios in parallel.
    /// Set to `1` for single-threaded execution.
    pub n_fwd_threads: usize,

    /// Maximum number of demand blocks across all stages.
    ///
    /// Used for pre-sizing buffers and determining the LP column layout.
    pub max_blocks: usize,

    /// Optional cut selection strategy for deactivating dominated cuts.
    ///
    /// When `Some(strategy)`, the training loop applies cut selection after each
    /// backward pass, deactivating cuts that do not meet the strategy's activity
    /// criteria. When `None`, all generated cuts remain active.
    pub cut_selection: Option<CutSelectionStrategy>,

    /// Optional shutdown signal for graceful early termination.
    ///
    /// When `Some(flag)`, the training loop checks `flag.load(Relaxed)` at each
    /// iteration boundary. If the flag is `true`, the loop terminates early with
    /// a "shutdown requested" reason. When `None`, the loop runs until
    /// convergence or iteration limit.
    pub shutdown_flag: Option<Arc<AtomicBool>>,

    /// Starting iteration for resumed training runs.
    ///
    /// When resuming from a checkpoint, this is set to the checkpoint's
    /// `completed_iterations`. The training loop starts at
    /// `start_iteration + 1` and runs up to `max_iterations`.
    /// Default: `0` (fresh training).
    pub start_iteration: u64,

    /// Whether to allocate the visited-states archive for state export.
    ///
    /// When `true`, the archive is allocated so forward-pass trial points are
    /// recorded for checkpoint persistence. When `false`, the archive is only
    /// allocated if `cut_selection` requires it (i.e., `Dominated` variant).
    /// Default: `false`.
    pub export_states: bool,

    /// Optional angular diversity pruning parameters (stage 2 of the cut
    /// selection pipeline).
    ///
    /// When `Some(params)`, the training loop applies angular pruning after the
    /// strategy-based selection pass, using cosine similarity clustering as a
    /// computational accelerator for pointwise dominance verification.
    /// When `None`, angular pruning is disabled.
    pub angular_pruning: Option<AngularPruningParams>,

    /// Maximum number of active cuts per stage (stage 3 of the cut selection
    /// pipeline — hard cap on LP size).
    ///
    /// When `Some(n)`, the training loop enforces a hard cap of `n` active cuts
    /// per stage after strategy selection and angular pruning have completed.
    /// Cuts are evicted in order of staleness (`last_active_iter` ascending),
    /// tie-broken by usage frequency (`active_count` ascending). Cuts generated
    /// in the current iteration are never evicted.
    ///
    /// When `None`, no hard cap is enforced.
    pub budget: Option<u32>,

    /// Enable basis padding for warm-start (Epic 05).
    ///
    /// When `true`, the forward pass applies informed basis status assignment for
    /// new cut rows before warm-starting the LP solver, reducing the number of
    /// simplex pivots required after each cut addition.
    ///
    /// Disabled by default (`false`).
    pub basis_padding_enabled: bool,
}

#[cfg(test)]
mod tests {
    use super::TrainingConfig;
    use cobre_core::TrainingEvent;

    // ── Field access ─────────────────────────────────────────────────────────

    #[test]
    fn field_access_forward_passes_and_max_iterations() {
        let config = TrainingConfig {
            forward_passes: 10,
            max_iterations: 100,
            checkpoint_interval: None,
            warm_start_cuts: 0,
            event_sender: None,
            cut_activity_tolerance: 1e-6,
            n_fwd_threads: 1,
            max_blocks: 1,
            cut_selection: None,
            shutdown_flag: None,
            start_iteration: 0,
            export_states: false,
            angular_pruning: None,
            budget: None,
            basis_padding_enabled: false,
        };
        assert_eq!(config.forward_passes, 10);
        assert_eq!(config.max_iterations, 100);
    }

    #[test]
    fn checkpoint_interval_none_and_some() {
        let config_none = TrainingConfig {
            forward_passes: 5,
            max_iterations: 50,
            checkpoint_interval: None,
            warm_start_cuts: 0,
            event_sender: None,
            cut_activity_tolerance: 1e-6,
            n_fwd_threads: 1,
            max_blocks: 1,
            cut_selection: None,
            shutdown_flag: None,
            start_iteration: 0,
            export_states: false,
            angular_pruning: None,
            budget: None,
            basis_padding_enabled: false,
        };
        assert!(config_none.checkpoint_interval.is_none());

        let config_some = TrainingConfig {
            forward_passes: 5,
            max_iterations: 50,
            checkpoint_interval: Some(10),
            warm_start_cuts: 0,
            event_sender: None,
            cut_activity_tolerance: 1e-6,
            n_fwd_threads: 1,
            max_blocks: 1,
            cut_selection: None,
            shutdown_flag: None,
            start_iteration: 0,
            export_states: false,
            angular_pruning: None,
            budget: None,
            basis_padding_enabled: false,
        };
        assert_eq!(config_some.checkpoint_interval, Some(10));
    }

    #[test]
    fn warm_start_cuts_field_accessible() {
        let config = TrainingConfig {
            forward_passes: 1,
            max_iterations: 10,
            checkpoint_interval: None,
            warm_start_cuts: 500,
            event_sender: None,
            cut_activity_tolerance: 1e-6,
            n_fwd_threads: 1,
            max_blocks: 1,
            cut_selection: None,
            shutdown_flag: None,
            start_iteration: 0,
            export_states: false,
            angular_pruning: None,
            budget: None,
            basis_padding_enabled: false,
        };
        assert_eq!(config.warm_start_cuts, 500);
    }

    // ── Event sender ─────────────────────────────────────────────────────────

    #[test]
    fn event_sender_none() {
        let config = TrainingConfig {
            forward_passes: 1,
            max_iterations: 1,
            checkpoint_interval: None,
            warm_start_cuts: 0,
            event_sender: None,
            cut_activity_tolerance: 1e-6,
            n_fwd_threads: 1,
            max_blocks: 1,
            cut_selection: None,
            shutdown_flag: None,
            start_iteration: 0,
            export_states: false,
            angular_pruning: None,
            budget: None,
            basis_padding_enabled: false,
        };
        assert!(config.event_sender.is_none());
    }

    #[test]
    fn event_sender_some_can_send_training_event() {
        let (tx, rx) = std::sync::mpsc::channel::<TrainingEvent>();
        let config = TrainingConfig {
            forward_passes: 4,
            max_iterations: 200,
            checkpoint_interval: Some(50),
            warm_start_cuts: 100,
            event_sender: Some(tx),
            cut_activity_tolerance: 1e-6,
            n_fwd_threads: 1,
            max_blocks: 1,
            cut_selection: None,
            shutdown_flag: None,
            start_iteration: 0,
            export_states: false,
            angular_pruning: None,
            budget: None,
            basis_padding_enabled: false,
        };

        assert!(config.event_sender.is_some());

        // Verify the sender in the config can actually send events.
        if let Some(sender) = &config.event_sender {
            sender
                .send(TrainingEvent::TrainingFinished {
                    reason: "test".to_string(),
                    iterations: 1,
                    final_lb: 0.0,
                    final_ub: 1.0,
                    total_time_ms: 100,
                    total_cuts: 4,
                })
                .unwrap();
        }

        let received = rx.recv().unwrap();
        assert!(matches!(received, TrainingEvent::TrainingFinished { .. }));
    }

    // ── Debug output ─────────────────────────────────────────────────────────

    #[test]
    fn debug_output_non_empty() {
        let config = TrainingConfig {
            forward_passes: 8,
            max_iterations: 500,
            checkpoint_interval: Some(100),
            warm_start_cuts: 0,
            event_sender: None,
            cut_activity_tolerance: 1e-6,
            n_fwd_threads: 1,
            max_blocks: 1,
            cut_selection: None,
            shutdown_flag: None,
            start_iteration: 0,
            export_states: false,
            angular_pruning: None,
            budget: None,
            basis_padding_enabled: false,
        };
        let debug = format!("{config:?}");
        assert!(!debug.is_empty());
        assert!(
            debug.contains("forward_passes"),
            "debug must contain field name: {debug}"
        );
        assert!(
            debug.contains("max_iterations"),
            "debug must contain field name: {debug}"
        );
    }
}