cobre-io 0.15.0

Case directory loading and validation for the Cobre power systems ecosystem
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! Assembly logic for scenario pipeline data.
//!
//! This module joins the flat row types produced by individual parsers into the
//! assembled types expected by [`cobre_core::System`]:
//!
//! - [`assemble_inflow_models`] — joins [`InflowSeasonalStatsRow`] with
//!   [`InflowArCoefficientRow`] by `(hydro_id, stage_id)` to produce
//!   `Vec<InflowModel>`.
//! - [`assemble_load_models`] — maps [`LoadSeasonalStatsRow`] 1:1 to
//!   `Vec<LoadModel>`.
//!
//! Both inputs are assumed to be pre-sorted by the individual parsers
//! The assembly step preserves that sort order in its output.

use std::collections::HashMap;
use std::path::Path;

use cobre_core::{
    EntityId,
    scenario::{AnnualComponent, InflowModel, LoadModel},
};

use crate::LoadError;
use crate::scenarios::{
    InflowAnnualComponentRow, InflowArCoefficientRow, InflowSeasonalStatsRow, LoadSeasonalStatsRow,
};

/// Assemble `Vec<InflowModel>` by joining seasonal stats with AR coefficients and
/// annual component rows.
///
/// All inputs must be pre-sorted by their respective parsers:
/// - `stats` sorted by `(hydro_id, stage_id)` ascending.
/// - `coefficients` sorted by `(hydro_id, stage_id, lag)` ascending.
/// - `annual_components` sorted by `(hydro_id, stage_id)` ascending.
///
/// For each [`InflowSeasonalStatsRow`], all [`InflowArCoefficientRow`] entries
/// with a matching `(hydro_id, stage_id)` are collected into `ar_coefficients`,
/// preserving lag order. The coefficient count determines the AR order; there is
/// no cross-check against a separate `ar_order` field.
///
/// Every resulting [`InflowModel`] gets `residual_std_ratio = 1.0` — a
/// placeholder immediately overwritten by
/// [`crate::scenarios::populate_derived_residual_ratios`] (the periodic-ACF
/// closure is the sole authority for this field; the file does not carry it).
///
/// When an [`InflowAnnualComponentRow`] exists for a (hydro, stage) pair, the
/// resulting [`InflowModel`] carries `annual: Some(AnnualComponent { ... })`;
/// otherwise `annual: None` (classical PAR(p), no annual extension).
///
/// When `stats` is empty (regardless of whether `coefficients` or
/// `annual_components` are non-empty), the function returns an empty `Vec`
/// without error. The `UserArHistoryStats` estimation path loads AR
/// coefficients independently via `parse_inflow_ar_coefficients` and does not
/// route them through this function.
///
/// # Errors
///
/// | Condition                                                     | Error variant              |
/// |---------------------------------------------------------------|----------------------------|
/// | Coefficient rows exist for a pair not in `stats`             | [`LoadError::SchemaError`] |
/// | Annual component rows exist for a pair not in `stats`        | [`LoadError::SchemaError`] |
/// | Duplicate `(hydro_id, stage_id)` in `annual_components`      | [`LoadError::SchemaError`] |
///
/// # Examples
///
/// ```
/// use cobre_core::EntityId;
/// use cobre_io::scenarios::{InflowSeasonalStatsRow, InflowArCoefficientRow};
/// use cobre_io::scenarios::assembly::assemble_inflow_models;
///
/// let stats = vec![
///     InflowSeasonalStatsRow { hydro_id: EntityId(1), stage_id: 0, mean_m3s: 100.0, std_m3s: 10.0 },
///     InflowSeasonalStatsRow { hydro_id: EntityId(1), stage_id: 1, mean_m3s: 80.0, std_m3s: 8.0 },
/// ];
/// let coefficients = vec![
///     InflowArCoefficientRow { hydro_id: EntityId(1), stage_id: 0, lag: 1, coefficient: 0.5 },
///     InflowArCoefficientRow { hydro_id: EntityId(1), stage_id: 0, lag: 2, coefficient: 0.2 },
/// ];
/// let models = assemble_inflow_models(stats, coefficients, vec![]).expect("valid join");
/// assert_eq!(models.len(), 2);
/// assert_eq!(models[0].ar_order(), 2);
/// assert!((models[0].residual_std_ratio - 1.0).abs() < f64::EPSILON);
/// assert!(models[1].ar_coefficients.is_empty());
/// assert!((models[1].residual_std_ratio - 1.0).abs() < f64::EPSILON);
/// ```
pub fn assemble_inflow_models(
    stats: Vec<InflowSeasonalStatsRow>,
    coefficients: Vec<InflowArCoefficientRow>,
    annual_components: Vec<InflowAnnualComponentRow>,
) -> Result<Vec<InflowModel>, LoadError> {
    if stats.is_empty() {
        return Ok(Vec::new());
    }

    let mut coeff_map: HashMap<(EntityId, i32), Vec<f64>> =
        HashMap::with_capacity(coefficients.len());
    for row in coefficients {
        coeff_map
            .entry((row.hydro_id, row.stage_id))
            .or_default()
            .push(row.coefficient);
    }

    let mut annual_map: HashMap<(EntityId, i32), AnnualComponent> =
        HashMap::with_capacity(annual_components.len());
    for row in annual_components {
        let key = (row.hydro_id, row.stage_id);
        let value = AnnualComponent {
            coefficient: row.annual_coefficient,
            mean_m3s: row.annual_mean_m3s,
            std_m3s: row.annual_std_m3s,
        };
        if annual_map.insert(key, value).is_some() {
            return Err(LoadError::SchemaError {
                path: Path::new("scenarios/inflow_annual_component.parquet").to_path_buf(),
                field: "inflow_annual_component".to_string(),
                message: format!(
                    "duplicate row for (hydro_id={}, stage_id={})",
                    key.0.0, key.1,
                ),
            });
        }
    }

    let mut models = Vec::with_capacity(stats.len());

    for row in stats {
        let key = (row.hydro_id, row.stage_id);

        let ar_coefficients = coeff_map.remove(&key).unwrap_or_default();

        let annual = annual_map.remove(&key);

        models.push(InflowModel {
            hydro_id: row.hydro_id,
            stage_id: row.stage_id,
            mean_m3s: row.mean_m3s,
            std_m3s: row.std_m3s,
            ar_coefficients,
            residual_std_ratio: 1.0,
            annual,
        });
    }

    if !coeff_map.is_empty() {
        return report_orphaned_keys(
            coeff_map.keys(),
            Path::new("scenarios/inflow_ar_coefficients.parquet"),
            "inflow_ar_coefficients",
            "AR coefficients",
        );
    }

    if !annual_map.is_empty() {
        return report_orphaned_keys(
            annual_map.keys(),
            Path::new("scenarios/inflow_annual_component.parquet"),
            "inflow_annual_component",
            "annual_component rows",
        );
    }

    Ok(models)
}

/// Report orphaned keys (present in a map but not in the base stats).
fn report_orphaned_keys<'a, I>(
    keys: I,
    path: &Path,
    field: &str,
    label: &str,
) -> Result<Vec<InflowModel>, LoadError>
where
    I: IntoIterator<Item = &'a (EntityId, i32)>,
{
    let mut orphan_keys: Vec<_> = keys.into_iter().collect();
    orphan_keys.sort_by_key(|(id, stage)| (id.0, *stage));
    let orphan_descriptions: Vec<String> = orphan_keys
        .iter()
        .map(|(id, stage)| format!("(hydro_id={}, stage_id={})", id.0, stage))
        .collect();
    Err(LoadError::SchemaError {
        path: path.to_path_buf(),
        field: field.to_string(),
        message: format!(
            "orphaned {label} for {} have no matching inflow_seasonal_stats row",
            orphan_descriptions.join(", ")
        ),
    })
}

/// Assemble `Vec<LoadModel>` by mapping [`LoadSeasonalStatsRow`] 1:1 to [`LoadModel`].
///
/// This is a direct field mapping with no join logic. The input is expected to be
/// pre-sorted by `(bus_id, stage_id)` ascending (as produced by the parser).
/// That order is preserved in the output.
///
/// # Examples
///
/// ```
/// use cobre_core::EntityId;
/// use cobre_io::scenarios::LoadSeasonalStatsRow;
/// use cobre_io::scenarios::assembly::assemble_load_models;
///
/// let stats = vec![
///     LoadSeasonalStatsRow { bus_id: EntityId(1), stage_id: 0, mean_mw: 300.0, std_mw: 30.0 },
///     LoadSeasonalStatsRow { bus_id: EntityId(1), stage_id: 1, mean_mw: 280.0, std_mw: 28.0 },
///     LoadSeasonalStatsRow { bus_id: EntityId(2), stage_id: 0, mean_mw: 500.0, std_mw: 50.0 },
/// ];
/// let models = assemble_load_models(stats);
/// assert_eq!(models.len(), 3);
/// assert_eq!(models[0].bus_id, EntityId(1));
/// assert_eq!(models[0].mean_mw, 300.0);
/// ```
#[must_use]
pub fn assemble_load_models(stats: Vec<LoadSeasonalStatsRow>) -> Vec<LoadModel> {
    stats
        .into_iter()
        .map(|row| LoadModel {
            bus_id: row.bus_id,
            stage_id: row.stage_id,
            mean_mw: row.mean_mw,
            std_mw: row.std_mw,
        })
        .collect()
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::too_many_lines,
    clippy::doc_markdown
)]
mod tests {
    use super::*;
    use cobre_core::EntityId;

    #[test]
    fn test_assemble_inflow_models_matching_join() {
        let stats = vec![
            InflowSeasonalStatsRow {
                hydro_id: EntityId(1),
                stage_id: 0,
                mean_m3s: 100.0,
                std_m3s: 10.0,
            },
            InflowSeasonalStatsRow {
                hydro_id: EntityId(1),
                stage_id: 1,
                mean_m3s: 80.0,
                std_m3s: 8.0,
            },
            InflowSeasonalStatsRow {
                hydro_id: EntityId(2),
                stage_id: 0,
                mean_m3s: 200.0,
                std_m3s: 20.0,
            },
        ];
        let coefficients = vec![
            InflowArCoefficientRow {
                hydro_id: EntityId(1),
                stage_id: 0,
                lag: 1,
                coefficient: 0.45,
            },
            InflowArCoefficientRow {
                hydro_id: EntityId(1),
                stage_id: 0,
                lag: 2,
                coefficient: 0.22,
            },
            InflowArCoefficientRow {
                hydro_id: EntityId(2),
                stage_id: 0,
                lag: 1,
                coefficient: 0.60,
            },
        ];

        let models = assemble_inflow_models(stats, coefficients, vec![]).unwrap();
        assert_eq!(models.len(), 3);

        let m0 = &models[0];
        assert_eq!(m0.hydro_id, EntityId(1));
        assert_eq!(m0.stage_id, 0);
        assert_eq!(m0.ar_order(), 2);
        assert_eq!(m0.ar_coefficients.len(), 2);
        assert!((m0.ar_coefficients[0] - 0.45).abs() < f64::EPSILON);
        assert!((m0.ar_coefficients[1] - 0.22).abs() < f64::EPSILON);
        assert!((m0.residual_std_ratio - 1.0).abs() < f64::EPSILON);

        let m1 = &models[1];
        assert_eq!(m1.hydro_id, EntityId(1));
        assert_eq!(m1.stage_id, 1);
        assert_eq!(m1.ar_order(), 0);
        assert!(m1.ar_coefficients.is_empty());
        assert!((m1.residual_std_ratio - 1.0).abs() < f64::EPSILON);

        let m2 = &models[2];
        assert_eq!(m2.hydro_id, EntityId(2));
        assert_eq!(m2.stage_id, 0);
        assert_eq!(m2.ar_order(), 1);
        assert_eq!(m2.ar_coefficients.len(), 1);
        assert!((m2.ar_coefficients[0] - 0.60).abs() < f64::EPSILON);
        assert!((m2.residual_std_ratio - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_assemble_inflow_models_no_coefficients() {
        let stats = vec![InflowSeasonalStatsRow {
            hydro_id: EntityId(3),
            stage_id: 5,
            mean_m3s: 50.0,
            std_m3s: 5.0,
        }];
        let models = assemble_inflow_models(stats, vec![], vec![]).unwrap();
        assert_eq!(models.len(), 1);
        assert!(models[0].ar_coefficients.is_empty());
        assert_eq!(models[0].ar_order(), 0);
        assert!((models[0].residual_std_ratio - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_assemble_inflow_models_orphaned_coefficients() {
        let stats = vec![InflowSeasonalStatsRow {
            hydro_id: EntityId(1),
            stage_id: 0,
            mean_m3s: 100.0,
            std_m3s: 10.0,
        }];
        let coefficients = vec![InflowArCoefficientRow {
            hydro_id: EntityId(5),
            stage_id: 0,
            lag: 1,
            coefficient: 0.3,
        }];

        let err = assemble_inflow_models(stats, coefficients, vec![]).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("inflow_ar_coefficients"),
                    "field should mention inflow_ar_coefficients, got: {field}"
                );
                assert!(
                    message.contains("orphaned"),
                    "message should contain 'orphaned', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    #[test]
    fn test_assemble_inflow_models_both_empty() {
        let models = assemble_inflow_models(vec![], vec![], vec![]).unwrap();
        assert!(models.is_empty());
    }

    /// Empty stats + non-empty AR is the estimation case: it must return an empty
    /// vec, not a SchemaError for "orphaned" AR entries (there is no base to join).
    #[test]
    fn test_assemble_inflow_models_empty_stats_non_empty_ar_returns_empty() {
        let coefficients = vec![InflowArCoefficientRow {
            hydro_id: EntityId(1),
            stage_id: 0,
            lag: 1,
            coefficient: 0.5,
        }];

        let result = assemble_inflow_models(vec![], coefficients, vec![]);
        assert!(
            result.is_ok(),
            "empty stats + non-empty AR must return Ok, got: {result:?}"
        );
        let models = result.unwrap();
        assert!(
            models.is_empty(),
            "empty stats must produce empty InflowModel vec, got {} models",
            models.len()
        );
    }

    #[test]
    fn test_assemble_load_models_four_rows() {
        let stats = vec![
            LoadSeasonalStatsRow {
                bus_id: EntityId(1),
                stage_id: 0,
                mean_mw: 300.0,
                std_mw: 30.0,
            },
            LoadSeasonalStatsRow {
                bus_id: EntityId(1),
                stage_id: 1,
                mean_mw: 280.0,
                std_mw: 28.0,
            },
            LoadSeasonalStatsRow {
                bus_id: EntityId(2),
                stage_id: 0,
                mean_mw: 500.0,
                std_mw: 50.0,
            },
            LoadSeasonalStatsRow {
                bus_id: EntityId(2),
                stage_id: 1,
                mean_mw: 450.0,
                std_mw: 45.0,
            },
        ];

        let models = assemble_load_models(stats);
        assert_eq!(models.len(), 4);

        assert_eq!(models[0].bus_id, EntityId(1));
        assert_eq!(models[0].stage_id, 0);
        assert!((models[0].mean_mw - 300.0).abs() < f64::EPSILON);
        assert!((models[0].std_mw - 30.0).abs() < f64::EPSILON);

        assert_eq!(models[1].bus_id, EntityId(1));
        assert_eq!(models[1].stage_id, 1);
        assert!((models[1].mean_mw - 280.0).abs() < f64::EPSILON);
        assert!((models[1].std_mw - 28.0).abs() < f64::EPSILON);

        assert_eq!(models[2].bus_id, EntityId(2));
        assert_eq!(models[2].stage_id, 0);
        assert!((models[2].mean_mw - 500.0).abs() < f64::EPSILON);
        assert!((models[2].std_mw - 50.0).abs() < f64::EPSILON);

        assert_eq!(models[3].bus_id, EntityId(2));
        assert_eq!(models[3].stage_id, 1);
        assert!((models[3].mean_mw - 450.0).abs() < f64::EPSILON);
        assert!((models[3].std_mw - 45.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_assemble_load_models_empty() {
        let models = assemble_load_models(vec![]);
        assert!(models.is_empty());
    }

    #[test]
    fn test_assemble_inflow_models_with_matching_annual_component() {
        let stats = vec![
            InflowSeasonalStatsRow {
                hydro_id: EntityId(1),
                stage_id: 0,
                mean_m3s: 100.0,
                std_m3s: 10.0,
            },
            InflowSeasonalStatsRow {
                hydro_id: EntityId(1),
                stage_id: 1,
                mean_m3s: 80.0,
                std_m3s: 8.0,
            },
        ];
        let annual_components = vec![InflowAnnualComponentRow {
            hydro_id: EntityId(1),
            stage_id: 0,
            annual_coefficient: 0.15,
            annual_mean_m3s: 90.0,
            annual_std_m3s: 12.0,
        }];

        let models = assemble_inflow_models(stats, vec![], annual_components).unwrap();
        assert_eq!(models.len(), 2);

        let m0 = &models[0];
        assert_eq!(m0.hydro_id, EntityId(1));
        assert_eq!(m0.stage_id, 0);
        let ann = m0.annual.as_ref().expect("models[0].annual should be Some");
        assert!((ann.coefficient - 0.15).abs() < f64::EPSILON);
        assert!((ann.mean_m3s - 90.0).abs() < f64::EPSILON);
        assert!((ann.std_m3s - 12.0).abs() < f64::EPSILON);

        let m1 = &models[1];
        assert_eq!(m1.hydro_id, EntityId(1));
        assert_eq!(m1.stage_id, 1);
        assert!(
            m1.annual.is_none(),
            "models[1].annual should be None (no matching annual row)"
        );
    }

    #[test]
    fn test_assemble_inflow_models_orphaned_annual_component() {
        let stats = vec![InflowSeasonalStatsRow {
            hydro_id: EntityId(1),
            stage_id: 0,
            mean_m3s: 100.0,
            std_m3s: 10.0,
        }];
        let annual_components = vec![InflowAnnualComponentRow {
            hydro_id: EntityId(2),
            stage_id: 0,
            annual_coefficient: 0.15,
            annual_mean_m3s: 90.0,
            annual_std_m3s: 12.0,
        }];

        let err = assemble_inflow_models(stats, vec![], annual_components).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("inflow_annual_component"),
                    "field should mention inflow_annual_component, got: {field}"
                );
                assert!(
                    message.contains("orphaned"),
                    "message should contain 'orphaned', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    #[test]
    fn test_assemble_inflow_models_duplicate_annual_component_rejected() {
        let stats = vec![InflowSeasonalStatsRow {
            hydro_id: EntityId(1),
            stage_id: 0,
            mean_m3s: 100.0,
            std_m3s: 10.0,
        }];
        let annual_components = vec![
            InflowAnnualComponentRow {
                hydro_id: EntityId(1),
                stage_id: 0,
                annual_coefficient: 0.15,
                annual_mean_m3s: 90.0,
                annual_std_m3s: 12.0,
            },
            InflowAnnualComponentRow {
                hydro_id: EntityId(1),
                stage_id: 0,
                annual_coefficient: 0.20,
                annual_mean_m3s: 95.0,
                annual_std_m3s: 13.0,
            },
        ];

        let err = assemble_inflow_models(stats, vec![], annual_components).unwrap_err();
        match &err {
            LoadError::SchemaError { field, message, .. } => {
                assert!(
                    field.contains("inflow_annual_component"),
                    "field should mention inflow_annual_component, got: {field}"
                );
                assert!(
                    message.contains("duplicate"),
                    "message should contain 'duplicate', got: {message}"
                );
            }
            other => panic!("expected SchemaError, got: {other:?}"),
        }
    }

    #[test]
    fn test_assemble_inflow_models_empty_stats_with_annual_returns_empty() {
        let annual_components = vec![InflowAnnualComponentRow {
            hydro_id: EntityId(1),
            stage_id: 0,
            annual_coefficient: 0.1,
            annual_mean_m3s: 90.0,
            annual_std_m3s: 12.0,
        }];

        let result = assemble_inflow_models(vec![], vec![], annual_components);
        assert!(
            result.is_ok(),
            "empty stats + non-empty annual_components must return Ok, got: {result:?}"
        );
        let models = result.unwrap();
        assert!(
            models.is_empty(),
            "empty stats must produce empty InflowModel vec, got {} models",
            models.len()
        );
    }
}