cobre-io 0.11.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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
//! Layer 4 — Dimensional consistency validation.
//!
//! Verifies that every entity which requires companion data actually has it,
//! and that companion data arrays have the expected dimensions. Coverage checks
//! are only performed when the optional data is present (non-empty `Vec` or
//! `Some`).
//!
//! The primary entry point is `validate_dimensional_consistency`.
//!
//! ## Rules implemented
//!
//! | # | Rule | Source File |
//! |---|------|-------------|
//! | 1 | Every active hydro must have an `InflowModel` for every study stage. | `scenarios/inflow_seasonal_stats.parquet` |
//! | 2 | Every bus must have a `LoadModel` for every study stage. | `scenarios/load_seasonal_stats.parquet` |
//! | 3 | For each `CorrelationGroup`, `matrix.len() == entities.len()`. | `scenarios/correlation.json` |
//! | 4 | For each `CorrelationGroup`, every row `matrix[i].len() == entities.len()`. | `scenarios/correlation.json` |
//! | 5 | Every `profile_name` in the correlation schedule exists in `profiles`. | `scenarios/correlation.json` |
//! | 6 | Every FPHA-configured hydro must have at least 1 row in `fpha_hyperplanes`. | `system/fpha_hyperplanes.parquet` |
//! | 7 | Every FPHA- or `LinearizedHead`-configured hydro must have ≥ 2 rows in `hydro_geometry`. | `system/hydro_geometry.parquet` |

use std::collections::{HashMap, HashSet};

use cobre_core::Hydro;
use cobre_core::entities::HydroGenerationModel;

use super::{ErrorKind, ValidationContext, schema::ParsedData};
use crate::extensions::{ProductionModelConfig, SelectionMode};

// ── validate_dimensional_consistency ─────────────────────────────────────────

/// Performs Layer 4 dimensional consistency validation on the parsed data.
///
/// Every coverage rule runs unconditionally — earlier failures do not
/// short-circuit later rules. A rule whose optional data is absent (empty `Vec`
/// or `None`) is silently skipped. Each failure adds one
/// [`ErrorKind::DimensionMismatch`] entry to `ctx`; the function is infallible.
// Rationale: all rules share one pass over the same parsed data and must run
// unconditionally so the caller receives a complete diagnostic set; one function per
// rule would force separate traversals or an intermediary structure with no benefit.
#[allow(clippy::too_many_lines)]
pub(crate) fn validate_dimensional_consistency(data: &ParsedData, ctx: &mut ValidationContext) {
    let study_stage_ids: Vec<i32> = data
        .stages
        .stages
        .iter()
        .filter(|s| s.id >= 0)
        .map(|s| s.id)
        .collect();

    if !data.inflow_seasonal_stats.is_empty() {
        let inflow_pairs: HashSet<(i32, i32)> = data
            .inflow_seasonal_stats
            .iter()
            .map(|row| (row.hydro_id.0, row.stage_id))
            .collect();

        for hydro in &data.hydros {
            for &stage_id in &study_stage_ids {
                if let Some(entry) = hydro.entry_stage_id
                    && stage_id < entry
                {
                    continue;
                }
                if let Some(exit) = hydro.exit_stage_id
                    && stage_id >= exit
                {
                    continue;
                }

                if !inflow_pairs.contains(&(hydro.id.0, stage_id)) {
                    ctx.add_error(
                        ErrorKind::DimensionMismatch,
                        "scenarios/inflow_seasonal_stats.parquet",
                        Some(format!("Hydro {}", hydro.id.0)),
                        format!(
                            "Hydro {} missing inflow seasonal stats for stage {}",
                            hydro.id.0, stage_id
                        ),
                    );
                }
            }
        }
    }

    if !data.load_seasonal_stats.is_empty() {
        let load_pairs: HashSet<(i32, i32)> = data
            .load_seasonal_stats
            .iter()
            .map(|row| (row.bus_id.0, row.stage_id))
            .collect();

        for bus in &data.buses {
            for &stage_id in &study_stage_ids {
                if !load_pairs.contains(&(bus.id.0, stage_id)) {
                    ctx.add_error(
                        ErrorKind::DimensionMismatch,
                        "scenarios/load_seasonal_stats.parquet",
                        Some(format!("Bus {}", bus.id.0)),
                        format!(
                            "Bus {} missing load seasonal stats for stage {}",
                            bus.id.0, stage_id
                        ),
                    );
                }
            }
        }
    }

    if let Some(correlation) = &data.correlation {
        for (profile_name, profile) in &correlation.profiles {
            for group in &profile.groups {
                let n_entities = group.entities.len();
                let n_rows = group.matrix.len();

                if n_rows != n_entities {
                    ctx.add_error(
                        ErrorKind::DimensionMismatch,
                        "scenarios/correlation.json",
                        Some(format!("group '{}' in profile '{}'", group.name, profile_name)),
                        format!(
                            "Correlation group '{}' in profile '{}': matrix has {} rows but {} entities",
                            group.name, profile_name, n_rows, n_entities
                        ),
                    );
                    continue;
                }

                for (i, row) in group.matrix.iter().enumerate() {
                    if row.len() != n_entities {
                        ctx.add_error(
                            ErrorKind::DimensionMismatch,
                            "scenarios/correlation.json",
                            Some(format!("group '{}' in profile '{}'", group.name, profile_name)),
                            format!(
                                "Correlation group '{}' in profile '{}': matrix row {} has {} columns but {} entities",
                                group.name, profile_name, i, row.len(), n_entities
                            ),
                        );
                    }
                }
            }
        }

        for entry in &correlation.schedule {
            if !correlation.profiles.contains_key(&entry.profile_name) {
                ctx.add_error(
                    ErrorKind::DimensionMismatch,
                    "scenarios/correlation.json",
                    Some(format!("schedule stage_id={}", entry.stage_id)),
                    format!(
                        "Correlation schedule references profile '{}' which does not exist in profiles",
                        entry.profile_name
                    ),
                );
            }
        }
    }

    if !data.fpha_hyperplanes.is_empty() {
        let hydros_with_hyperplanes: HashSet<i32> = data
            .fpha_hyperplanes
            .iter()
            .map(|row| row.hydro_id.0)
            .collect();

        let fpha_hydro_ids = collect_fpha_hydro_ids(&data.hydros, &data.production_models);

        for &hydro_id in &fpha_hydro_ids {
            if !hydros_with_hyperplanes.contains(&hydro_id) {
                ctx.add_error(
                    ErrorKind::DimensionMismatch,
                    "system/fpha_hyperplanes.parquet",
                    Some(format!("Hydro {hydro_id}")),
                    format!(
                        "Hydro {hydro_id} is configured with FPHA model but has no FPHA hyperplanes"
                    ),
                );
            }
        }
    }

    if !data.hydro_geometry.is_empty() {
        let mut geometry_row_counts: HashMap<i32, usize> = HashMap::new();
        for row in &data.hydro_geometry {
            *geometry_row_counts.entry(row.hydro_id.0).or_insert(0) += 1;
        }

        let head_hydro_ids =
            collect_head_dependent_hydro_ids(&data.hydros, &data.production_models);
        let fpha_hydro_ids = collect_fpha_hydro_ids(&data.hydros, &data.production_models);

        for &hydro_id in &head_hydro_ids {
            let count = geometry_row_counts.get(&hydro_id).copied().unwrap_or(0);
            // FPHA accepts a single geometry row (constant run-of-river forebay,
            // γ_V = 0); `linearized_head` needs ≥ 2 because it fits a head slope in
            // volume, which one point cannot define.
            let min_required = if fpha_hydro_ids.contains(&hydro_id) {
                1
            } else {
                2
            };
            if count < min_required {
                ctx.add_error(
                    ErrorKind::DimensionMismatch,
                    "system/hydro_geometry.parquet",
                    Some(format!("Hydro {hydro_id}")),
                    format!(
                        "Hydro {hydro_id} requires head-dependent model but has {count} hydro geometry row(s) (minimum {min_required} required)"
                    ),
                );
            }
        }
    }
}

// ── Private helpers ───────────────────────────────────────────────────────────

fn collect_fpha_hydro_ids(
    hydros: &[Hydro],
    production_models: &[ProductionModelConfig],
) -> HashSet<i32> {
    let mut ids = HashSet::new();

    for hydro in hydros {
        if matches!(hydro.generation_model, HydroGenerationModel::Fpha) {
            ids.insert(hydro.id.0);
        }
    }

    for config in production_models {
        if production_model_uses_fpha(config) {
            ids.insert(config.hydro_id.0);
        }
    }

    ids
}

fn collect_head_dependent_hydro_ids(
    hydros: &[Hydro],
    production_models: &[ProductionModelConfig],
) -> HashSet<i32> {
    let mut ids = HashSet::new();

    for hydro in hydros {
        if matches!(
            hydro.generation_model,
            HydroGenerationModel::Fpha | HydroGenerationModel::LinearizedHead
        ) {
            ids.insert(hydro.id.0);
        }
    }

    for config in production_models {
        if production_model_uses_head_dependent(config) {
            ids.insert(config.hydro_id.0);
        }
    }

    ids
}

// `production_model_uses_fpha` and `production_model_uses_head_dependent`
// mirror the solver crate's `resolve_stage`/`selection_entries` resolver: a
// Seasonal season miss falls back to `default_model`, so each fold reads
// `default_model` too — keep in agreement with that resolver's season-miss
// semantics, not just the declared seasons.
fn production_model_uses_fpha(config: &ProductionModelConfig) -> bool {
    match &config.selection_mode {
        SelectionMode::StageRanges { ranges } => ranges.iter().any(|r| r.model == "fpha"),
        SelectionMode::Seasonal {
            default_model,
            seasons,
        } => default_model == "fpha" || seasons.iter().any(|s| s.model == "fpha"),
    }
}

// Same mirror contract as `production_model_uses_fpha` above, extended to
// `linearized_head`.
fn production_model_uses_head_dependent(config: &ProductionModelConfig) -> bool {
    match &config.selection_mode {
        SelectionMode::StageRanges { ranges } => ranges
            .iter()
            .any(|r| r.model == "fpha" || r.model == "linearized_head"),
        SelectionMode::Seasonal {
            default_model,
            seasons,
        } => {
            default_model == "fpha"
                || default_model == "linearized_head"
                || seasons
                    .iter()
                    .any(|s| s.model == "fpha" || s.model == "linearized_head")
        }
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::panic,
    clippy::too_many_lines,
    clippy::doc_markdown,
    clippy::cast_sign_loss,
    clippy::uninlined_format_args
)]
mod tests {
    use std::collections::BTreeMap;

    use cobre_core::{
        EntityId,
        entities::{Bus, HydroGenerationModel, HydroPenalties},
        scenario::{
            CorrelationEntity, CorrelationGroup, CorrelationModel, CorrelationProfile,
            CorrelationScheduleEntry,
        },
        temporal::{
            Block, BlockMode, NoiseMethod, PolicyGraph, ScenarioSourceConfig, Stage,
            StageRiskConfig, StageStateConfig,
        },
    };

    use crate::{
        extensions::{FphaHyperplaneRow, HydroGeometryRow, SeasonConfig},
        scenarios::{InflowSeasonalStatsRow, LoadSeasonalStatsRow},
        validation::{ErrorKind, ValidationContext},
    };

    use super::*;
    use chrono::NaiveDate;

    fn make_hydro(
        id: i32,
        generation_model: HydroGenerationModel,
        entry_stage_id: Option<i32>,
        exit_stage_id: Option<i32>,
    ) -> Hydro {
        Hydro {
            id: EntityId(id),
            name: format!("Hydro {id}"),
            operational_start_date: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            bus_id: EntityId(1),
            downstream_id: None,
            travel_time_hours: None,
            entry_stage_id,
            exit_stage_id,
            min_storage_hm3: 0.0,
            max_storage_hm3: 1000.0,
            min_outflow_m3s: 0.0,
            max_outflow_m3s: None,
            generation_model,
            min_turbined_m3s: 0.0,
            max_turbined_m3s: 100.0,
            specific_productivity_mw_per_m3s_per_m: None,
            min_generation_mw: 0.0,
            max_generation_mw: 500.0,
            tailrace: None,
            hydraulic_losses: None,
            efficiency: None,
            evaporation_coefficients_mm: None,
            evaporation_reference_volumes_hm3: None,
            diversion: None,
            filling: None,
            penalties: penalties_default(),
        }
    }

    fn make_bus(id: i32) -> Bus {
        Bus {
            id: EntityId(id),
            name: format!("Bus {id}"),
            operational_start_date: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            deficit_segments: vec![],
            excess_cost: 0.0,
        }
    }

    fn make_stage(id: i32) -> Stage {
        Stage {
            index: id as usize,
            id,
            start_date: chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            end_date: chrono::NaiveDate::from_ymd_opt(2024, 2, 1).unwrap(),
            season_id: None,
            blocks: vec![Block {
                index: 0,
                name: "FLAT".to_string(),
                duration_hours: 744.0,
            }],
            block_mode: BlockMode::Parallel,
            state_config: StageStateConfig {
                storage: true,
                inflow_lags: false,
            },
            risk_config: StageRiskConfig::Expectation,
            scenario_config: ScenarioSourceConfig {
                branching_factor: 50,
                noise_method: NoiseMethod::Saa,
            },
        }
    }

    fn make_pre_study_stage(id: i32) -> Stage {
        // Pre-study stages have negative IDs.
        Stage {
            index: 0,
            id,
            start_date: chrono::NaiveDate::from_ymd_opt(2023, 12, 1).unwrap(),
            end_date: chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            season_id: None,
            blocks: vec![],
            block_mode: BlockMode::Parallel,
            state_config: StageStateConfig {
                storage: false,
                inflow_lags: false,
            },
            risk_config: StageRiskConfig::Expectation,
            scenario_config: ScenarioSourceConfig {
                branching_factor: 1,
                noise_method: NoiseMethod::Saa,
            },
        }
    }

    fn penalties_default() -> HydroPenalties {
        HydroPenalties {
            spillage_cost: 1.0,
            diversion_cost: 1.0,
            turbined_cost: 1.0,
            storage_violation_below_cost: 1.0,
            filling_target_violation_cost: 1.0,
            turbined_violation_below_cost: 1.0,
            outflow_violation_below_cost: 1.0,
            outflow_violation_above_cost: 1.0,
            generation_violation_below_cost: 1.0,
            evaporation_violation_cost: 1.0,
            water_withdrawal_violation_cost: 1.0,
            water_withdrawal_violation_pos_cost: 1.0,
            water_withdrawal_violation_neg_cost: 1.0,
            evaporation_violation_pos_cost: 1.0,
            evaporation_violation_neg_cost: 1.0,
            inflow_nonnegativity_cost: 1000.0,
        }
    }

    fn inflow_stats_row(hydro_id: i32, stage_id: i32) -> InflowSeasonalStatsRow {
        InflowSeasonalStatsRow {
            hydro_id: EntityId(hydro_id),
            stage_id,
            mean_m3s: 100.0,
            std_m3s: 10.0,
        }
    }

    fn load_stats_row(bus_id: i32, stage_id: i32) -> LoadSeasonalStatsRow {
        LoadSeasonalStatsRow {
            bus_id: EntityId(bus_id),
            stage_id,
            mean_mw: 500.0,
            std_mw: 50.0,
        }
    }

    fn fpha_row(hydro_id: i32) -> FphaHyperplaneRow {
        FphaHyperplaneRow {
            hydro_id: EntityId(hydro_id),
            stage_id: None,
            plane_id: 0,
            gamma_0: 100.0,
            gamma_v: 0.001,
            gamma_q: 0.9,
            gamma_s: -0.01,
            kappa: 1.0,
            valid_v_min_hm3: None,
            valid_v_max_hm3: None,
            valid_q_max_m3s: None,
        }
    }

    fn geometry_row(hydro_id: i32, volume: f64) -> HydroGeometryRow {
        HydroGeometryRow {
            hydro_id: EntityId(hydro_id),
            volume_hm3: volume,
            height_m: volume * 0.1,
            area_km2: volume * 0.001,
        }
    }

    fn make_correlation_model(
        groups: Vec<CorrelationGroup>,
        schedule: Vec<CorrelationScheduleEntry>,
    ) -> CorrelationModel {
        let mut profiles = BTreeMap::new();
        profiles.insert("default".to_string(), CorrelationProfile { groups });
        CorrelationModel {
            method: "spectral".to_string(),
            profiles,
            schedule,
        }
    }

    // Minimal ParsedData builder — only sets the fields needed for each test.
    fn base_parsed_data() -> ParsedData {
        use crate::{
            config::{
                Config, EstimationConfig, ExportsConfig, ModelingConfig, PolicyConfig,
                RowSelectionConfig, SimulationConfig, StoppingRuleConfig, TrainingConfig,
                TrainingSolverConfig, UpperBoundEvaluationConfig,
            },
            stages::StagesData,
        };
        use cobre_core::{
            entities::DeficitSegment, initial_conditions::InitialConditions,
            penalty::GlobalPenaltyDefaults,
        };

        let config = Config {
            schema: None,
            modeling: ModelingConfig::default(),
            training: TrainingConfig {
                enabled: true,
                tree_seed: None,
                forward_passes: Some(10),
                stopping_rules: Some(vec![StoppingRuleConfig::IterationLimit { limit: 100 }]),
                stopping_mode: "any".to_string(),
                cut_selection: RowSelectionConfig::default(),
                solver: TrainingSolverConfig::default(),
                scenario_source: None,
            },
            upper_bound_evaluation: UpperBoundEvaluationConfig::default(),
            policy: PolicyConfig::default(),
            simulation: SimulationConfig::default(),
            exports: ExportsConfig::default(),
            estimation: EstimationConfig::default(),
        };

        ParsedData {
            config,
            penalties: GlobalPenaltyDefaults {
                bus_deficit_segments: vec![DeficitSegment {
                    depth_mw: None,
                    cost_per_mwh: 1.0,
                }],
                bus_excess_cost: 1.0,
                line_exchange_cost: 1.0,
                hydro: HydroPenalties {
                    spillage_cost: 1.0,
                    diversion_cost: 1.0,
                    turbined_cost: 1.0,
                    storage_violation_below_cost: 1.0,
                    filling_target_violation_cost: 1.0,
                    turbined_violation_below_cost: 1.0,
                    outflow_violation_below_cost: 1.0,
                    outflow_violation_above_cost: 1.0,
                    generation_violation_below_cost: 1.0,
                    evaporation_violation_cost: 1.0,
                    water_withdrawal_violation_cost: 1.0,
                    water_withdrawal_violation_pos_cost: 1.0,
                    water_withdrawal_violation_neg_cost: 1.0,
                    evaporation_violation_pos_cost: 1.0,
                    evaporation_violation_neg_cost: 1.0,
                    inflow_nonnegativity_cost: 1000.0,
                },
                ncs_curtailment_cost: 1.0,
            },
            stages: StagesData {
                stages: vec![make_stage(0), make_stage(1)],
                policy_graph: PolicyGraph::default(),
            },
            initial_conditions: InitialConditions {
                storage: vec![],
                filling_storage: vec![],
                past_inflows: vec![],
                past_anticipated_commitments: vec![],
                recent_observations: vec![],
                past_defluences: vec![],
            },
            buses: vec![],
            thermals: vec![],
            hydros: vec![],
            lines: vec![],
            non_controllable_sources: vec![],
            pumping_stations: vec![],
            energy_contracts: vec![],
            hydro_geometry: vec![],
            production_models: vec![],
            plane_reduction: None,
            hydro_energy_productivity_rows: vec![],
            fpha_hyperplanes: vec![],
            scalar_parameters: vec![],
            inflow_history: vec![],
            inflow_seasonal_stats: vec![],
            inflow_ar_coefficients: vec![],
            inflow_annual_components: vec![],
            external_scenarios: vec![],
            external_load_scenarios: vec![],
            external_ncs_scenarios: vec![],
            load_seasonal_stats: vec![],
            load_factors: vec![],
            correlation: None,
            non_controllable_factors: vec![],
            ncs_models: vec![],
            thermal_bounds: vec![],
            hydro_bounds: vec![],
            line_bounds: vec![],
            pumping_bounds: vec![],
            contract_bounds: vec![],
            exchange_factors: vec![],
            generic_constraints: vec![],
            generic_constraint_bounds: vec![],
            penalty_overrides_bus: vec![],
            penalty_overrides_line: vec![],
            penalty_overrides_hydro: vec![],
            penalty_overrides_ncs: vec![],
            ncs_bounds: vec![],
        }
    }

    // ── AC 1: Valid coverage — no errors ──────────────────────────────────────

    /// Given ParsedData where every hydro has InflowModel entries for every
    /// study stage and all other coverage rules are satisfied,
    /// `validate_dimensional_consistency` produces no errors.
    #[test]
    fn test_valid_coverage_no_errors() {
        let mut data = base_parsed_data();

        // 2 hydros, 2 study stages — all 4 (hydro, stage) pairs present.
        data.hydros = vec![
            make_hydro(1, HydroGenerationModel::ConstantProductivity, None, None),
            make_hydro(2, HydroGenerationModel::ConstantProductivity, None, None),
        ];
        data.inflow_seasonal_stats = vec![
            inflow_stats_row(1, 0),
            inflow_stats_row(1, 1),
            inflow_stats_row(2, 0),
            inflow_stats_row(2, 1),
        ];

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        assert!(
            !ctx.has_errors(),
            "expected no errors for valid coverage, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC 2: Missing inflow stats for one hydro at one stage → 1 error ───────

    /// Given ParsedData with 3 hydros and 2 study stages where hydro id=2 is
    /// missing inflow stats for stage id=1, exactly 1 DimensionMismatch error
    /// is produced with message containing "Hydro 2" and "stage 1".
    #[test]
    fn test_missing_inflow_stats_one_hydro_one_stage() {
        let mut data = base_parsed_data();

        data.hydros = vec![
            make_hydro(1, HydroGenerationModel::ConstantProductivity, None, None),
            make_hydro(2, HydroGenerationModel::ConstantProductivity, None, None),
            make_hydro(3, HydroGenerationModel::ConstantProductivity, None, None),
        ];

        // Hydro 2 is missing stage 1.
        data.inflow_seasonal_stats = vec![
            inflow_stats_row(1, 0),
            inflow_stats_row(1, 1),
            inflow_stats_row(2, 0), // stage 1 missing for hydro 2
            inflow_stats_row(3, 0),
            inflow_stats_row(3, 1),
        ];

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        let errors = ctx.errors();
        assert_eq!(
            errors.len(),
            1,
            "expected exactly 1 error, got {}: {:?}",
            errors.len(),
            errors
        );
        assert_eq!(errors[0].kind, ErrorKind::DimensionMismatch);
        assert!(
            errors[0].message.contains("Hydro 2"),
            "error message should contain 'Hydro 2', got: {}",
            errors[0].message
        );
        assert!(
            errors[0].message.contains("stage 1"),
            "error message should contain 'stage 1', got: {}",
            errors[0].message
        );
    }

    // ── AC 3: Correlation matrix row count mismatch → 1 error ─────────────────

    /// Given a ParsedData where a CorrelationGroup named "Southeast" has
    /// 3 entities but a 2x2 matrix, one DimensionMismatch error is produced
    /// with message containing "Southeast" and "3 entities".
    #[test]
    fn test_correlation_matrix_row_count_mismatch() {
        let mut data = base_parsed_data();

        let group = CorrelationGroup {
            name: "Southeast".to_string(),
            entities: vec![
                CorrelationEntity {
                    entity_type: "inflow".to_string(),
                    id: EntityId(1),
                },
                CorrelationEntity {
                    entity_type: "inflow".to_string(),
                    id: EntityId(2),
                },
                CorrelationEntity {
                    entity_type: "inflow".to_string(),
                    id: EntityId(3),
                },
            ],
            // Only 2 rows — mismatch: entities.len() == 3 but matrix.len() == 2.
            matrix: vec![vec![1.0, 0.8], vec![0.8, 1.0]],
        };

        data.correlation = Some(make_correlation_model(vec![group], vec![]));

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        let errors = ctx.errors();
        assert!(
            !errors.is_empty(),
            "expected at least 1 error for row count mismatch"
        );
        assert_eq!(errors[0].kind, ErrorKind::DimensionMismatch);
        assert!(
            errors[0].message.contains("Southeast"),
            "error should mention group name 'Southeast', got: {}",
            errors[0].message
        );
        assert!(
            errors[0].message.contains("3 entities"),
            "error should mention '3 entities', got: {}",
            errors[0].message
        );
    }

    // ── AC 4: Correlation matrix non-square → 1 error ─────────────────────────

    /// Given a CorrelationGroup with 2 entities but one row has only 1 column,
    /// one DimensionMismatch error is produced.
    #[test]
    fn test_correlation_matrix_non_square_row() {
        let mut data = base_parsed_data();

        let group = CorrelationGroup {
            name: "North".to_string(),
            entities: vec![
                CorrelationEntity {
                    entity_type: "inflow".to_string(),
                    id: EntityId(1),
                },
                CorrelationEntity {
                    entity_type: "inflow".to_string(),
                    id: EntityId(2),
                },
            ],
            // 2 rows, but row 1 has only 1 column → non-square.
            matrix: vec![vec![1.0, 0.5], vec![0.5]],
        };

        data.correlation = Some(make_correlation_model(vec![group], vec![]));

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        let errors = ctx.errors();
        assert_eq!(
            errors.len(),
            1,
            "expected exactly 1 column mismatch error, got: {:?}",
            errors
        );
        assert_eq!(errors[0].kind, ErrorKind::DimensionMismatch);
        assert!(
            errors[0].message.contains("North"),
            "error should mention group name 'North', got: {}",
            errors[0].message
        );
    }

    // ── AC 5: Empty optional data — no false positives ────────────────────────

    /// Given ParsedData with empty inflow_seasonal_stats, empty
    /// load_seasonal_stats, and empty fpha_hyperplanes, no DimensionMismatch
    /// errors are produced.
    #[test]
    fn test_empty_optional_data_no_false_positives() {
        let mut data = base_parsed_data();
        data.hydros = vec![make_hydro(1, HydroGenerationModel::Fpha, None, None)];
        data.buses = vec![make_bus(1)];
        // All optional data is empty — every data-gated rule is skipped.

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        assert!(
            !ctx.has_errors(),
            "expected no errors for empty optional data, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC 6: FPHA hydro missing hyperplane rows → 1 error ───────────────────

    /// Given a ParsedData where a hydro uses HydroGenerationModel::Fpha but
    /// fpha_hyperplanes has no rows for that hydro, one DimensionMismatch error
    /// is produced mentioning the hydro ID and "FPHA hyperplanes".
    #[test]
    fn test_fpha_hydro_missing_hyperplane_rows() {
        let mut data = base_parsed_data();

        data.hydros = vec![
            make_hydro(1, HydroGenerationModel::Fpha, None, None),
            make_hydro(2, HydroGenerationModel::ConstantProductivity, None, None),
        ];

        // Only hydro 2 has a hyperplane row — hydro 1 (FPHA) is missing.
        data.fpha_hyperplanes = vec![fpha_row(2)];

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        let errors = ctx.errors();
        assert_eq!(
            errors.len(),
            1,
            "expected exactly 1 error for missing FPHA hyperplanes, got: {:?}",
            errors
        );
        assert_eq!(errors[0].kind, ErrorKind::DimensionMismatch);
        assert!(
            errors[0].message.contains('1'),
            "error should mention hydro ID 1, got: {}",
            errors[0].message
        );
        assert!(
            errors[0]
                .message
                .to_lowercase()
                .contains("fpha hyperplanes"),
            "error should mention 'FPHA hyperplanes', got: {}",
            errors[0].message
        );
    }

    // ── AC 7: Hydro with entry_stage_id skips earlier stages ─────────────────

    /// Given a hydro with entry_stage_id=1, inflow stats are only required
    /// for stage 1, not stage 0. Providing only stage 1 produces no errors.
    #[test]
    fn test_hydro_lifecycle_entry_stage_id_skips_earlier_stages() {
        let mut data = base_parsed_data();
        // Stages 0 and 1 are study stages.
        // Hydro enters service at stage 1: only stage 1 requires inflow stats.
        data.hydros = vec![make_hydro(
            1,
            HydroGenerationModel::ConstantProductivity,
            Some(1), // enters service at stage 1
            None,
        )];

        // Only provide inflow stats for stage 1.
        data.inflow_seasonal_stats = vec![inflow_stats_row(1, 1)];

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        assert!(
            !ctx.has_errors(),
            "expected no errors when stage 0 is before hydro entry, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC 8: Hydro with exit_stage_id skips later stages ────────────────────

    /// Given a hydro with exit_stage_id=1 (exclusive), inflow stats are
    /// only required for stage 0. Providing only stage 0 produces no errors.
    #[test]
    fn test_hydro_lifecycle_exit_stage_id_skips_later_stages() {
        let mut data = base_parsed_data();
        // Stages 0 and 1 are study stages.
        // Hydro exits at stage 1 (exclusive): only stage 0 requires inflow stats.
        data.hydros = vec![make_hydro(
            1,
            HydroGenerationModel::ConstantProductivity,
            None,
            Some(1), // decommissioned at stage 1 (exclusive)
        )];

        // Only provide inflow stats for stage 0.
        data.inflow_seasonal_stats = vec![inflow_stats_row(1, 0)];

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        assert!(
            !ctx.has_errors(),
            "expected no errors when stage 1 is after hydro exit, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC 9: Pre-study stages are not checked ────────────────────────────────

    /// Pre-study stages (negative IDs) must not appear in the coverage check.
    #[test]
    fn test_pre_study_stages_not_checked() {
        use crate::stages::StagesData;
        let mut data = base_parsed_data();
        // Include one pre-study stage (id = -1) alongside the study stages.
        data.stages = StagesData {
            stages: vec![make_pre_study_stage(-1), make_stage(0), make_stage(1)],
            policy_graph: PolicyGraph::default(),
        };

        data.hydros = vec![make_hydro(
            1,
            HydroGenerationModel::ConstantProductivity,
            None,
            None,
        )];

        // Provide inflow stats for study stages 0 and 1 only — not pre-study.
        data.inflow_seasonal_stats = vec![inflow_stats_row(1, 0), inflow_stats_row(1, 1)];

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        assert!(
            !ctx.has_errors(),
            "pre-study stages should not require inflow stats, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC 10: Load stats coverage missing ────────────────────────────────────

    /// Given a bus that has no load stats for one stage, exactly 1 error is
    /// produced.
    #[test]
    fn test_load_stats_missing_for_one_stage() {
        let mut data = base_parsed_data();
        data.buses = vec![make_bus(1), make_bus(2)];

        // Bus 2 is missing stage 1.
        data.load_seasonal_stats = vec![
            load_stats_row(1, 0),
            load_stats_row(1, 1),
            load_stats_row(2, 0), // stage 1 missing for bus 2
        ];

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        let errors = ctx.errors();
        assert_eq!(
            errors.len(),
            1,
            "expected 1 error for missing load stats, got: {:?}",
            errors
        );
        assert_eq!(errors[0].kind, ErrorKind::DimensionMismatch);
        assert!(
            errors[0].message.contains("Bus 2"),
            "error should mention 'Bus 2', got: {}",
            errors[0].message
        );
        assert!(
            errors[0].message.contains("stage 1"),
            "error should mention 'stage 1', got: {}",
            errors[0].message
        );
    }

    // ── AC 11 (renumbered 12): Correlation schedule references non-existent profile ───────────

    /// A schedule entry referencing a profile name that does not exist in
    /// `profiles` produces one DimensionMismatch error.
    #[test]
    fn test_correlation_schedule_missing_profile() {
        let mut data = base_parsed_data();

        data.correlation = Some(make_correlation_model(
            vec![],
            vec![CorrelationScheduleEntry {
                stage_id: 0,
                profile_name: "nonexistent_profile".to_string(),
            }],
        ));

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        let errors = ctx.errors();
        assert!(
            !errors.is_empty(),
            "expected error for missing profile reference"
        );
        assert_eq!(errors[0].kind, ErrorKind::DimensionMismatch);
        assert!(
            errors[0].message.contains("nonexistent_profile"),
            "error should mention the missing profile name, got: {}",
            errors[0].message
        );
    }

    // ── AC 13: LinearizedHead hydro missing geometry rows ────────────────────

    /// A hydro using LinearizedHead model must have at least 2 geometry rows.
    /// Missing rows produce a DimensionMismatch error.
    #[test]
    fn test_linearized_head_hydro_missing_geometry() {
        let mut data = base_parsed_data();

        data.hydros = vec![make_hydro(
            1,
            HydroGenerationModel::LinearizedHead,
            None,
            None,
        )];

        // Only 1 geometry row — minimum is 2.
        data.hydro_geometry = vec![geometry_row(1, 100.0)];

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        let errors = ctx.errors();
        assert_eq!(
            errors.len(),
            1,
            "expected 1 error for insufficient geometry rows, got: {:?}",
            errors
        );
        assert_eq!(errors[0].kind, ErrorKind::DimensionMismatch);
    }

    /// An FPHA hydro with a SINGLE geometry row is accepted: a run-of-river plant
    /// has one operating volume → a constant forebay → a valid single-volume FPHA
    /// fit. This is the relaxation that `linearized_head` does NOT share.
    #[test]
    fn test_fpha_hydro_single_geometry_row_accepted() {
        let mut data = base_parsed_data();
        data.hydros = vec![make_hydro(1, HydroGenerationModel::Fpha, None, None)];
        // One geometry row — valid for FPHA (constant run-of-river forebay).
        data.hydro_geometry = vec![geometry_row(1, 100.0)];

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        assert!(
            ctx.errors().is_empty(),
            "a single geometry row must be valid for an FPHA plant, got: {:?}",
            ctx.errors()
        );
    }

    /// An FPHA hydro with ZERO geometry rows (while other plants have geometry) is
    /// still rejected — there is no forebay to evaluate at all.
    #[test]
    fn test_fpha_hydro_zero_geometry_rows_rejected() {
        let mut data = base_parsed_data();
        data.hydros = vec![
            make_hydro(1, HydroGenerationModel::Fpha, None, None),
            make_hydro(2, HydroGenerationModel::ConstantProductivity, None, None),
        ];
        // Geometry present for hydro 2 only; the FPHA hydro 1 has none.
        data.hydro_geometry = vec![geometry_row(2, 100.0), geometry_row(2, 200.0)];

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        assert!(
            ctx.errors().iter().any(|e| {
                e.kind == ErrorKind::DimensionMismatch
                    && e.message.contains("Hydro 1")
                    && e.message.contains("minimum 1 required")
            }),
            "FPHA hydro with zero geometry rows must fail with minimum-1, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC 14: All 7 rules checked independently ─────────────────────────────

    /// Errors in one rule do not suppress checking of subsequent rules.
    #[test]
    fn test_all_rules_checked_independently() {
        let mut data = base_parsed_data();

        // Trigger rule 1 violation: hydro 1 missing stage 1.
        data.hydros = vec![make_hydro(
            1,
            HydroGenerationModel::ConstantProductivity,
            None,
            None,
        )];
        data.inflow_seasonal_stats = vec![inflow_stats_row(1, 0)]; // missing stage 1

        // Trigger rule 2 violation: bus 1 missing stage 1.
        data.buses = vec![make_bus(1)];
        data.load_seasonal_stats = vec![load_stats_row(1, 0)]; // missing stage 1

        let mut ctx = ValidationContext::new();
        validate_dimensional_consistency(&data, &mut ctx);

        // Both rules fire — at least 2 errors.
        let errors = ctx.errors();
        assert!(
            errors.len() >= 2,
            "expected at least 2 errors (rules 1 and 2), got {}: {:?}",
            errors.len(),
            errors
        );
        assert!(
            errors
                .iter()
                .all(|e| e.kind == ErrorKind::DimensionMismatch),
            "all errors should be DimensionMismatch"
        );
    }

    // ── Cross-crate agreement with the solver crate's resolve_stage/selection_entries ──

    /// `production_model_uses_fpha` agrees with the solver crate's
    /// `resolve_stage`/`selection_entries` classification: a `Seasonal` config
    /// with `default_model == "fpha"` and every listed season non-FPHA still
    /// classifies as using FPHA.
    #[test]
    fn test_production_model_uses_fpha_agrees_with_resolve_stage_on_seasonal_default() {
        let config = ProductionModelConfig {
            hydro_id: EntityId(0),
            selection_mode: SelectionMode::Seasonal {
                default_model: "fpha".to_string(),
                seasons: vec![SeasonConfig {
                    season_id: 1,
                    model: "constant_productivity".to_string(),
                    fpha_config: None,
                    reference_volume: None,
                    productivity_mw_per_m3s: Some(0.5),
                }],
            },
        };

        assert!(
            production_model_uses_fpha(&config),
            "production_model_uses_fpha must agree with the solver crate's \
             resolve_stage/selection_entries: default_model == \"fpha\" classifies \
             as FPHA even when every listed season is non-FPHA"
        );
    }
}