cobre-core 0.15.0

Power system data model — buses, branches, generators, loads, and network topology
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
//! Penalty resolution and pre-resolved penalty structures.
//!
//! The penalty system uses a three-tier resolution cascade: global defaults,
//! entity-level overrides, and stage-level overrides. After resolution,
//! penalties are stored as pre-computed per-(entity, stage) values so solvers
//! do not need to re-evaluate the cascade during execution.
//!
//! This module implements the first two tiers (global → entity). Stage-varying
//! overrides are handled by `cobre-io` and are not implemented here.

use crate::entities::{DeficitSegment, HydroPenalties};

/// Global default penalty values for all entity types.
///
/// Mirrors the structure of `penalties.json`; the fallback when entity-level
/// overrides are absent.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GlobalPenaltyDefaults {
    /// Piecewise-linear bus deficit cost segments.
    pub bus_deficit_segments: Vec<DeficitSegment>,
    /// Bus excess cost \[$/`MWh`\].
    pub bus_excess_cost: f64,
    /// Line exchange cost \[$/`MWh`\].
    pub line_exchange_cost: f64,
    /// Hydro penalty defaults for any field not overridden per entity.
    pub hydro: HydroPenalties,
    /// Non-controllable source curtailment cost \[$/`MWh`\].
    pub ncs_curtailment_cost: f64,
}

/// Optional entity-level hydro penalty overrides.
///
/// Each field mirrors a [`HydroPenalties`] field. `None` falls back to the global
/// default; `Some(x)` overrides. The four directional `*_pos_cost` / `*_neg_cost`
/// fields instead fall back to their resolved symmetric cost (see
/// [`resolve_hydro_penalties`]). Field docs carry only the unit.
///
/// This is an intermediate type used during System construction; the resolved
/// [`HydroPenalties`] (with no `Option`s) is stored on the `Hydro` entity.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct HydroPenaltyOverrides {
    /// Spillage cost [$/m³/s].
    pub spillage_cost: Option<f64>,
    /// Diversion cost [$/m³/s].
    pub diversion_cost: Option<f64>,
    /// Turbined cost \[$/`MWh`\].
    pub turbined_cost: Option<f64>,
    /// Storage violation below cost [$/hm³].
    pub storage_violation_below_cost: Option<f64>,
    /// Filling target violation cost [$/hm³].
    pub filling_target_violation_cost: Option<f64>,
    /// Turbined violation below cost [$/m³/s].
    pub turbined_violation_below_cost: Option<f64>,
    /// Outflow violation below cost [$/m³/s].
    pub outflow_violation_below_cost: Option<f64>,
    /// Outflow violation above cost [$/m³/s].
    pub outflow_violation_above_cost: Option<f64>,
    /// Generation violation below cost [$/MW].
    pub generation_violation_below_cost: Option<f64>,
    /// Evaporation violation cost [$/mm].
    pub evaporation_violation_cost: Option<f64>,
    /// Water withdrawal violation cost [$/m³/s].
    pub water_withdrawal_violation_cost: Option<f64>,
    /// Over-withdrawal violation cost [$/m³/s]. `None` = use symmetric.
    pub water_withdrawal_violation_pos_cost: Option<f64>,
    /// Under-withdrawal violation cost [$/m³/s]. `None` = use symmetric.
    pub water_withdrawal_violation_neg_cost: Option<f64>,
    /// Over-evaporation violation cost [$/mm]. `None` = use symmetric.
    pub evaporation_violation_pos_cost: Option<f64>,
    /// Under-evaporation violation cost [$/mm]. `None` = use symmetric.
    pub evaporation_violation_neg_cost: Option<f64>,
    /// Inflow non-negativity cost [$/m³/s].
    pub inflow_nonnegativity_cost: Option<f64>,
}

/// Resolve a bus's deficit segments: use entity override if present, else global default.
///
/// Returns an owned `Vec<DeficitSegment>` cloned from whichever source wins the cascade.
///
/// # Examples
///
/// ```
/// use cobre_core::penalty::{GlobalPenaltyDefaults, resolve_bus_deficit_segments};
/// use cobre_core::entities::{DeficitSegment, HydroPenalties};
///
/// let global = GlobalPenaltyDefaults {
///     bus_deficit_segments: vec![DeficitSegment { depth_mw: None, cost_per_mwh: 500.0 }],
///     bus_excess_cost: 10.0,
///     line_exchange_cost: 5.0,
///     hydro: HydroPenalties {
///         spillage_cost: 0.01, diversion_cost: 0.02, turbined_cost: 0.03,
///         storage_violation_below_cost: 1.0, filling_target_violation_cost: 2.0,
///         turbined_violation_below_cost: 3.0, outflow_violation_below_cost: 4.0,
///         outflow_violation_above_cost: 5.0, generation_violation_below_cost: 6.0,
///         evaporation_violation_cost: 7.0, water_withdrawal_violation_cost: 8.0,
///         water_withdrawal_violation_pos_cost: 8.0, water_withdrawal_violation_neg_cost: 8.0,
///         evaporation_violation_pos_cost: 7.0, evaporation_violation_neg_cost: 7.0,
///         inflow_nonnegativity_cost: 1000.0,
///     },
///     ncs_curtailment_cost: 50.0,
/// };
///
/// // No entity override -> returns global default segments.
/// let resolved = resolve_bus_deficit_segments(&None, &global);
/// assert_eq!(resolved.len(), 1);
/// assert_eq!(resolved[0].cost_per_mwh, 500.0);
/// ```
#[must_use]
pub fn resolve_bus_deficit_segments(
    entity_deficit_segments: &Option<Vec<DeficitSegment>>,
    global: &GlobalPenaltyDefaults,
) -> Vec<DeficitSegment> {
    entity_deficit_segments
        .clone()
        .unwrap_or_else(|| global.bus_deficit_segments.clone())
}

/// Resolve a bus's excess cost: use entity override if present, else global default.
///
/// # Examples
///
/// ```
/// use cobre_core::penalty::{GlobalPenaltyDefaults, resolve_bus_excess_cost};
/// use cobre_core::entities::{DeficitSegment, HydroPenalties};
///
/// let global = GlobalPenaltyDefaults {
///     bus_deficit_segments: vec![DeficitSegment { depth_mw: None, cost_per_mwh: 500.0 }],
///     bus_excess_cost: 100.0,
///     line_exchange_cost: 5.0,
///     hydro: HydroPenalties {
///         spillage_cost: 0.01, diversion_cost: 0.02, turbined_cost: 0.03,
///         storage_violation_below_cost: 1.0, filling_target_violation_cost: 2.0,
///         turbined_violation_below_cost: 3.0, outflow_violation_below_cost: 4.0,
///         outflow_violation_above_cost: 5.0, generation_violation_below_cost: 6.0,
///         evaporation_violation_cost: 7.0, water_withdrawal_violation_cost: 8.0,
///         water_withdrawal_violation_pos_cost: 8.0, water_withdrawal_violation_neg_cost: 8.0,
///         evaporation_violation_pos_cost: 7.0, evaporation_violation_neg_cost: 7.0,
///         inflow_nonnegativity_cost: 1000.0,
///     },
///     ncs_curtailment_cost: 50.0,
/// };
///
/// assert_eq!(resolve_bus_excess_cost(None, &global), 100.0);
/// assert_eq!(resolve_bus_excess_cost(Some(250.0), &global), 250.0);
/// ```
#[must_use]
pub fn resolve_bus_excess_cost(
    entity_excess_cost: Option<f64>,
    global: &GlobalPenaltyDefaults,
) -> f64 {
    entity_excess_cost.unwrap_or(global.bus_excess_cost)
}

/// Resolve a line's exchange cost: use entity override if present, else global default.
///
/// # Examples
///
/// ```
/// use cobre_core::penalty::{GlobalPenaltyDefaults, resolve_line_exchange_cost};
/// use cobre_core::entities::{DeficitSegment, HydroPenalties};
///
/// let global = GlobalPenaltyDefaults {
///     bus_deficit_segments: vec![DeficitSegment { depth_mw: None, cost_per_mwh: 500.0 }],
///     bus_excess_cost: 100.0,
///     line_exchange_cost: 5.0,
///     hydro: HydroPenalties {
///         spillage_cost: 0.01, diversion_cost: 0.02, turbined_cost: 0.03,
///         storage_violation_below_cost: 1.0, filling_target_violation_cost: 2.0,
///         turbined_violation_below_cost: 3.0, outflow_violation_below_cost: 4.0,
///         outflow_violation_above_cost: 5.0, generation_violation_below_cost: 6.0,
///         evaporation_violation_cost: 7.0, water_withdrawal_violation_cost: 8.0,
///         water_withdrawal_violation_pos_cost: 8.0, water_withdrawal_violation_neg_cost: 8.0,
///         evaporation_violation_pos_cost: 7.0, evaporation_violation_neg_cost: 7.0,
///         inflow_nonnegativity_cost: 1000.0,
///     },
///     ncs_curtailment_cost: 50.0,
/// };
///
/// assert_eq!(resolve_line_exchange_cost(None, &global), 5.0);
/// assert_eq!(resolve_line_exchange_cost(Some(12.0), &global), 12.0);
/// ```
#[must_use]
pub fn resolve_line_exchange_cost(
    entity_exchange_cost: Option<f64>,
    global: &GlobalPenaltyDefaults,
) -> f64 {
    entity_exchange_cost.unwrap_or(global.line_exchange_cost)
}

/// Resolve a hydro plant's penalty values.
///
/// Each field uses the entity override if `Some`, else the `global.hydro` default;
/// the four directional `*_pos_cost` / `*_neg_cost` fields fall back to their
/// resolved symmetric cost. A `None` `entity_overrides` yields `global.hydro` exactly.
///
/// # Examples
///
/// ```
/// use cobre_core::penalty::{
///     GlobalPenaltyDefaults, HydroPenaltyOverrides, resolve_hydro_penalties,
/// };
/// use cobre_core::entities::{DeficitSegment, HydroPenalties};
///
/// let global_hydro = HydroPenalties {
///     spillage_cost: 0.01, diversion_cost: 0.02, turbined_cost: 0.03,
///     storage_violation_below_cost: 1.0, filling_target_violation_cost: 2.0,
///     turbined_violation_below_cost: 3.0, outflow_violation_below_cost: 4.0,
///     outflow_violation_above_cost: 5.0, generation_violation_below_cost: 6.0,
///     evaporation_violation_cost: 7.0, water_withdrawal_violation_cost: 8.0,
///     water_withdrawal_violation_pos_cost: 8.0, water_withdrawal_violation_neg_cost: 8.0,
///     evaporation_violation_pos_cost: 7.0, evaporation_violation_neg_cost: 7.0,
///     inflow_nonnegativity_cost: 1000.0,
/// };
/// let global = GlobalPenaltyDefaults {
///     bus_deficit_segments: vec![],
///     bus_excess_cost: 100.0,
///     line_exchange_cost: 5.0,
///     hydro: global_hydro,
///     ncs_curtailment_cost: 50.0,
/// };
///
/// // All-None overrides -> result equals global hydro exactly.
/// let resolved = resolve_hydro_penalties(&None, &global);
/// assert_eq!(resolved, global.hydro);
///
/// // Partial override: only spillage_cost overridden.
/// let overrides = HydroPenaltyOverrides {
///     spillage_cost: Some(0.05),
///     ..Default::default()
/// };
/// let resolved = resolve_hydro_penalties(&Some(overrides), &global);
/// assert!((resolved.spillage_cost - 0.05).abs() < f64::EPSILON);
/// assert!((resolved.diversion_cost - 0.02).abs() < f64::EPSILON);
/// ```
#[must_use]
pub fn resolve_hydro_penalties(
    entity_overrides: &Option<HydroPenaltyOverrides>,
    global: &GlobalPenaltyDefaults,
) -> HydroPenalties {
    let g = &global.hydro;
    match entity_overrides {
        None => *g,
        Some(ov) => {
            // Resolve symmetric costs first — directional costs default to these.
            let evap_cost = ov
                .evaporation_violation_cost
                .unwrap_or(g.evaporation_violation_cost);
            let withdrawal_cost = ov
                .water_withdrawal_violation_cost
                .unwrap_or(g.water_withdrawal_violation_cost);
            HydroPenalties {
                spillage_cost: ov.spillage_cost.unwrap_or(g.spillage_cost),
                diversion_cost: ov.diversion_cost.unwrap_or(g.diversion_cost),
                turbined_cost: ov.turbined_cost.unwrap_or(g.turbined_cost),
                storage_violation_below_cost: ov
                    .storage_violation_below_cost
                    .unwrap_or(g.storage_violation_below_cost),
                filling_target_violation_cost: ov
                    .filling_target_violation_cost
                    .unwrap_or(g.filling_target_violation_cost),
                turbined_violation_below_cost: ov
                    .turbined_violation_below_cost
                    .unwrap_or(g.turbined_violation_below_cost),
                outflow_violation_below_cost: ov
                    .outflow_violation_below_cost
                    .unwrap_or(g.outflow_violation_below_cost),
                outflow_violation_above_cost: ov
                    .outflow_violation_above_cost
                    .unwrap_or(g.outflow_violation_above_cost),
                generation_violation_below_cost: ov
                    .generation_violation_below_cost
                    .unwrap_or(g.generation_violation_below_cost),
                evaporation_violation_cost: evap_cost,
                water_withdrawal_violation_cost: withdrawal_cost,
                // Fall back to the resolved symmetric cost, NOT g.*_pos_cost: the
                // latter would make an entity's symmetric-only override unreachable.
                water_withdrawal_violation_pos_cost: ov
                    .water_withdrawal_violation_pos_cost
                    .unwrap_or(withdrawal_cost),
                water_withdrawal_violation_neg_cost: ov
                    .water_withdrawal_violation_neg_cost
                    .unwrap_or(withdrawal_cost),
                evaporation_violation_pos_cost: ov
                    .evaporation_violation_pos_cost
                    .unwrap_or(evap_cost),
                evaporation_violation_neg_cost: ov
                    .evaporation_violation_neg_cost
                    .unwrap_or(evap_cost),
                inflow_nonnegativity_cost: ov
                    .inflow_nonnegativity_cost
                    .unwrap_or(g.inflow_nonnegativity_cost),
            }
        }
    }
}

/// Resolve a non-controllable source's curtailment cost: use entity override if present,
/// else global default.
///
/// # Examples
///
/// ```
/// use cobre_core::penalty::{GlobalPenaltyDefaults, resolve_ncs_curtailment_cost};
/// use cobre_core::entities::{DeficitSegment, HydroPenalties};
///
/// let global = GlobalPenaltyDefaults {
///     bus_deficit_segments: vec![],
///     bus_excess_cost: 100.0,
///     line_exchange_cost: 5.0,
///     hydro: HydroPenalties {
///         spillage_cost: 0.01, diversion_cost: 0.02, turbined_cost: 0.03,
///         storage_violation_below_cost: 1.0, filling_target_violation_cost: 2.0,
///         turbined_violation_below_cost: 3.0, outflow_violation_below_cost: 4.0,
///         outflow_violation_above_cost: 5.0, generation_violation_below_cost: 6.0,
///         evaporation_violation_cost: 7.0, water_withdrawal_violation_cost: 8.0,
///         water_withdrawal_violation_pos_cost: 8.0, water_withdrawal_violation_neg_cost: 8.0,
///         evaporation_violation_pos_cost: 7.0, evaporation_violation_neg_cost: 7.0,
///         inflow_nonnegativity_cost: 1000.0,
///     },
///     ncs_curtailment_cost: 50.0,
/// };
///
/// assert_eq!(resolve_ncs_curtailment_cost(None, &global), 50.0);
/// assert_eq!(resolve_ncs_curtailment_cost(Some(75.0), &global), 75.0);
/// ```
#[must_use]
pub fn resolve_ncs_curtailment_cost(
    entity_curtailment_cost: Option<f64>,
    global: &GlobalPenaltyDefaults,
) -> f64 {
    entity_curtailment_cost.unwrap_or(global.ncs_curtailment_cost)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_global() -> GlobalPenaltyDefaults {
        GlobalPenaltyDefaults {
            bus_deficit_segments: vec![
                DeficitSegment {
                    depth_mw: Some(100.0),
                    cost_per_mwh: 500.0,
                },
                DeficitSegment {
                    depth_mw: None,
                    cost_per_mwh: 5000.0,
                },
            ],
            bus_excess_cost: 100.0,
            line_exchange_cost: 5.0,
            hydro: HydroPenalties {
                spillage_cost: 0.01,
                diversion_cost: 0.02,
                turbined_cost: 0.03,
                storage_violation_below_cost: 1.0,
                filling_target_violation_cost: 2.0,
                turbined_violation_below_cost: 3.0,
                outflow_violation_below_cost: 4.0,
                outflow_violation_above_cost: 5.0,
                generation_violation_below_cost: 6.0,
                evaporation_violation_cost: 7.0,
                water_withdrawal_violation_cost: 8.0,
                water_withdrawal_violation_pos_cost: 8.0,
                water_withdrawal_violation_neg_cost: 8.0,
                evaporation_violation_pos_cost: 7.0,
                evaporation_violation_neg_cost: 7.0,
                inflow_nonnegativity_cost: 1000.0,
            },
            ncs_curtailment_cost: 50.0,
        }
    }

    #[test]
    fn test_resolve_bus_excess_cost_global() {
        let global = make_global();
        let result = resolve_bus_excess_cost(None, &global);
        assert!((result - 100.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_bus_excess_cost_override() {
        let global = make_global();
        let result = resolve_bus_excess_cost(Some(250.0), &global);
        assert!((result - 250.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_bus_deficit_segments_global() {
        let global = make_global();
        let result = resolve_bus_deficit_segments(&None, &global);
        assert_eq!(result, global.bus_deficit_segments);
        assert_eq!(result.len(), 2);
        assert!((result[0].cost_per_mwh - 500.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_bus_deficit_segments_override() {
        let global = make_global();
        let override_segments = vec![DeficitSegment {
            depth_mw: None,
            cost_per_mwh: 9999.0,
        }];
        let result = resolve_bus_deficit_segments(&Some(override_segments.clone()), &global);
        assert_eq!(result, override_segments);
        assert_eq!(result.len(), 1);
        assert!((result[0].cost_per_mwh - 9999.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_line_exchange_cost_global() {
        let global = make_global();
        let result = resolve_line_exchange_cost(None, &global);
        assert!((result - 5.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_line_exchange_cost_override() {
        let global = make_global();
        let result = resolve_line_exchange_cost(Some(12.0), &global);
        assert!((result - 12.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_hydro_penalties_all_global() {
        let global = make_global();
        let result = resolve_hydro_penalties(&None, &global);
        assert_eq!(result, global.hydro);
    }

    #[test]
    fn test_resolve_hydro_penalties_partial_override() {
        let global = make_global();
        let overrides = HydroPenaltyOverrides {
            spillage_cost: Some(0.05),
            ..Default::default()
        };
        let result = resolve_hydro_penalties(&Some(overrides), &global);

        assert!((result.spillage_cost - 0.05).abs() < f64::EPSILON);
        assert!((result.diversion_cost - 0.02).abs() < f64::EPSILON);
        assert!((result.turbined_cost - 0.03).abs() < f64::EPSILON);
        assert!((result.storage_violation_below_cost - 1.0).abs() < f64::EPSILON);
        assert!((result.filling_target_violation_cost - 2.0).abs() < f64::EPSILON);
        assert!((result.turbined_violation_below_cost - 3.0).abs() < f64::EPSILON);
        assert!((result.outflow_violation_below_cost - 4.0).abs() < f64::EPSILON);
        assert!((result.outflow_violation_above_cost - 5.0).abs() < f64::EPSILON);
        assert!((result.generation_violation_below_cost - 6.0).abs() < f64::EPSILON);
        assert!((result.evaporation_violation_cost - 7.0).abs() < f64::EPSILON);
        assert!((result.water_withdrawal_violation_cost - 8.0).abs() < f64::EPSILON);
        // Directional `None` -> resolved symmetric, here the global 8.0 / 7.0.
        assert!((result.water_withdrawal_violation_pos_cost - 8.0).abs() < f64::EPSILON);
        assert!((result.water_withdrawal_violation_neg_cost - 8.0).abs() < f64::EPSILON);
        assert!((result.evaporation_violation_pos_cost - 7.0).abs() < f64::EPSILON);
        assert!((result.evaporation_violation_neg_cost - 7.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_hydro_penalties_all_override() {
        let global = make_global();
        let overrides = HydroPenaltyOverrides {
            spillage_cost: Some(10.0),
            diversion_cost: Some(20.0),
            turbined_cost: Some(30.0),
            storage_violation_below_cost: Some(40.0),
            filling_target_violation_cost: Some(50.0),
            turbined_violation_below_cost: Some(60.0),
            outflow_violation_below_cost: Some(70.0),
            outflow_violation_above_cost: Some(80.0),
            generation_violation_below_cost: Some(90.0),
            evaporation_violation_cost: Some(100.0),
            water_withdrawal_violation_cost: Some(110.0),
            water_withdrawal_violation_pos_cost: Some(110.0),
            water_withdrawal_violation_neg_cost: Some(110.0),
            evaporation_violation_pos_cost: Some(100.0),
            evaporation_violation_neg_cost: Some(100.0),
            inflow_nonnegativity_cost: Some(500.0),
        };
        let result = resolve_hydro_penalties(&Some(overrides), &global);

        assert!((result.spillage_cost - 10.0).abs() < f64::EPSILON);
        assert!((result.diversion_cost - 20.0).abs() < f64::EPSILON);
        assert!((result.turbined_cost - 30.0).abs() < f64::EPSILON);
        assert!((result.storage_violation_below_cost - 40.0).abs() < f64::EPSILON);
        assert!((result.filling_target_violation_cost - 50.0).abs() < f64::EPSILON);
        assert!((result.turbined_violation_below_cost - 60.0).abs() < f64::EPSILON);
        assert!((result.outflow_violation_below_cost - 70.0).abs() < f64::EPSILON);
        assert!((result.outflow_violation_above_cost - 80.0).abs() < f64::EPSILON);
        assert!((result.generation_violation_below_cost - 90.0).abs() < f64::EPSILON);
        assert!((result.evaporation_violation_cost - 100.0).abs() < f64::EPSILON);
        assert!((result.water_withdrawal_violation_cost - 110.0).abs() < f64::EPSILON);
        assert!((result.water_withdrawal_violation_pos_cost - 110.0).abs() < f64::EPSILON);
        assert!((result.water_withdrawal_violation_neg_cost - 110.0).abs() < f64::EPSILON);
        assert!((result.evaporation_violation_pos_cost - 100.0).abs() < f64::EPSILON);
        assert!((result.evaporation_violation_neg_cost - 100.0).abs() < f64::EPSILON);
        assert!((result.inflow_nonnegativity_cost - 500.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_hydro_penalties_default_overrides_equals_global() {
        let global = make_global();
        let result = resolve_hydro_penalties(&Some(HydroPenaltyOverrides::default()), &global);
        assert_eq!(result, global.hydro);
    }

    #[test]
    fn test_resolve_ncs_curtailment_cost_global() {
        let global = make_global();
        let result = resolve_ncs_curtailment_cost(None, &global);
        assert!((result - 50.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_ncs_curtailment_cost_override() {
        let global = make_global();
        let result = resolve_ncs_curtailment_cost(Some(75.0), &global);
        assert!((result - 75.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_hydro_directional_override_pos_only() {
        let global = make_global();
        let overrides = HydroPenaltyOverrides {
            water_withdrawal_violation_pos_cost: Some(9999.0),
            ..Default::default()
        };
        let result = resolve_hydro_penalties(&Some(overrides), &global);
        assert!((result.water_withdrawal_violation_pos_cost - 9999.0).abs() < f64::EPSILON);
        assert!(
            (result.water_withdrawal_violation_neg_cost - 8.0).abs() < f64::EPSILON,
            "neg should fall back to the resolved symmetric cost"
        );
        assert!((result.water_withdrawal_violation_cost - 8.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_hydro_directional_evaporation_asymmetric() {
        let global = make_global();
        let overrides = HydroPenaltyOverrides {
            evaporation_violation_pos_cost: Some(111.0),
            evaporation_violation_neg_cost: Some(222.0),
            ..Default::default()
        };
        let result = resolve_hydro_penalties(&Some(overrides), &global);
        assert!((result.evaporation_violation_pos_cost - 111.0).abs() < f64::EPSILON);
        assert!((result.evaporation_violation_neg_cost - 222.0).abs() < f64::EPSILON);
        assert!((result.evaporation_violation_cost - 7.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_resolve_hydro_no_overrides_directional_equals_symmetric() {
        let global = make_global();
        let result = resolve_hydro_penalties(&None, &global);
        assert!(
            (result.water_withdrawal_violation_pos_cost - result.water_withdrawal_violation_cost)
                .abs()
                < f64::EPSILON
        );
        assert!(
            (result.water_withdrawal_violation_neg_cost - result.water_withdrawal_violation_cost)
                .abs()
                < f64::EPSILON
        );
        assert!(
            (result.evaporation_violation_pos_cost - result.evaporation_violation_cost).abs()
                < f64::EPSILON
        );
        assert!(
            (result.evaporation_violation_neg_cost - result.evaporation_violation_cost).abs()
                < f64::EPSILON
        );
    }

    #[test]
    fn test_resolve_hydro_directional_inherits_entity_symmetric_override() {
        let global = make_global();

        // Symmetric-only override must reach the directional fields, not g.*_pos_cost (8.0).
        let overrides = HydroPenaltyOverrides {
            water_withdrawal_violation_cost: Some(999.0),
            ..Default::default()
        };
        let result = resolve_hydro_penalties(&Some(overrides), &global);
        assert!((result.water_withdrawal_violation_cost - 999.0).abs() < f64::EPSILON);
        assert!(
            (result.water_withdrawal_violation_pos_cost - 999.0).abs() < f64::EPSILON,
            "pos must inherit the entity symmetric override, not global directional 8.0"
        );
        assert!(
            (result.water_withdrawal_violation_neg_cost - 999.0).abs() < f64::EPSILON,
            "neg must inherit the entity symmetric override, not global directional 8.0"
        );

        let overrides = HydroPenaltyOverrides {
            evaporation_violation_cost: Some(555.0),
            ..Default::default()
        };
        let result = resolve_hydro_penalties(&Some(overrides), &global);
        assert!((result.evaporation_violation_cost - 555.0).abs() < f64::EPSILON);
        assert!(
            (result.evaporation_violation_pos_cost - 555.0).abs() < f64::EPSILON,
            "evap pos must inherit the entity symmetric override, not global directional 7.0"
        );
        assert!(
            (result.evaporation_violation_neg_cost - 555.0).abs() < f64::EPSILON,
            "evap neg must inherit the entity symmetric override, not global directional 7.0"
        );

        // A directional override wins over the symmetric tier; neg (`None`) still inherits it.
        let overrides = HydroPenaltyOverrides {
            water_withdrawal_violation_cost: Some(999.0),
            water_withdrawal_violation_pos_cost: Some(7777.0),
            ..Default::default()
        };
        let result = resolve_hydro_penalties(&Some(overrides), &global);
        assert!((result.water_withdrawal_violation_pos_cost - 7777.0).abs() < f64::EPSILON);
        assert!((result.water_withdrawal_violation_neg_cost - 999.0).abs() < f64::EPSILON);
    }
}