cobre-core 0.12.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
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
//! User-defined generic linear constraints.
//!
//! This module defines the in-memory representation of generic constraints
//! that users can specify to add custom linear relationships between LP
//! variables. The expression parser (string → [`ConstraintExpression`])
//! lives in `cobre-io`, not here. This module contains only the output types.
//!
//! See `internal-structures.md §15` and `input-constraints.md §3` for the
//! full specification, grammar, and validation rules.
//!
//! # Variable Reference Catalog
//!
//! [`VariableRef`] covers all 24 LP variable types defined in the spec (§15).
//! Each variant carries the entity ID and, for block-capable variables, an
//! optional block ID. `Some(i)` references block `i`. `None` is not
//! block-specific and resolves by the variable's nature: per-block flows (e.g.
//! [`VariableRef::HydroInflow`]) follow the materialized row's block — a single
//! collapsed stage-level row for a block-independent expression, one row per
//! block otherwise; stage-level stocks ([`VariableRef::HydroStorage`] and the
//! storage-boundary variants at their stage endpoints S⁰/Sᴷ) resolve to a single
//! fixed column; [`VariableRef::HydroEvaporation`] with `None` resolves to block 0
//! (the stage evaporation in parallel mode). No variant sums over blocks.
//!
//! # Examples
//!
//! ```
//! use cobre_core::{
//!     EntityId, GenericConstraint, ConstraintExpression, ConstraintSense,
//!     LinearTerm, SlackConfig, VariableRef,
//! };
//!
//! // Represents: hydro_generation(10) + hydro_generation(11)
//! let expr = ConstraintExpression {
//!     terms: vec![
//!         LinearTerm::literal(1.0, VariableRef::HydroGeneration {
//!             hydro_id: EntityId(10),
//!             block_id: None,
//!         }),
//!         LinearTerm::literal(1.0, VariableRef::HydroGeneration {
//!             hydro_id: EntityId(11),
//!             block_id: None,
//!         }),
//!     ],
//! };
//!
//! assert_eq!(expr.terms.len(), 2);
//!
//! let gc = GenericConstraint {
//!     id: EntityId(0),
//!     name: "min_southeast_hydro".to_string(),
//!     description: Some("Minimum hydro generation in Southeast region".to_string()),
//!     expression: expr,
//!     sense: ConstraintSense::GreaterEqual,
//!     slack: SlackConfig { enabled: true, penalty: Some(5_000.0) },
//! };
//!
//! assert_eq!(gc.expression.terms.len(), 2);
//! ```

use crate::CoefficientRef;
use crate::EntityId;

/// Reference to a single LP variable in a generic constraint expression.
///
/// See the module header for the `block_id = None` block-independent vs
/// block-dependent row-materialization contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum VariableRef {
    /// Reservoir storage level for a hydro plant (stage-level, not block-specific).
    HydroStorage {
        /// Hydro plant identifier.
        hydro_id: EntityId,
    },
    /// Turbined water flow for a hydro plant (m³/s).
    HydroTurbined {
        /// Hydro plant identifier.
        hydro_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Spillage flow for a hydro plant (m³/s).
    HydroSpillage {
        /// Hydro plant identifier.
        hydro_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Diversion flow for a hydro plant (m³/s). Only valid for hydros with diversion.
    HydroDiversion {
        /// Hydro plant identifier.
        hydro_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Total outflow for a hydro plant (m³/s): a derived alias for
    /// turbined + spillage, not an independent LP column.
    HydroOutflow {
        /// Hydro plant identifier.
        hydro_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Electrical generation from a hydro plant (MW).
    HydroGeneration {
        /// Hydro plant identifier.
        hydro_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Signed evaporation flow from a hydro reservoir (m³/s). Positive values
    /// represent net evaporative outflow; negative values represent net rainfall
    /// input absorbed by the reservoir. `Some(k)` selects block `k`; `None` selects
    /// block 0, which in parallel mode is the stage evaporation (every block shares
    /// the same stage endpoints). In chronological mode with `K > 1` the blocks
    /// differ, so a `None` reference is rejected by generic-constraint validation —
    /// a block must be named.
    HydroEvaporation {
        /// Hydro plant identifier.
        hydro_id: EntityId,
        /// Block selector; `None` = block 0 (the stage evaporation in parallel mode).
        block_id: Option<usize>,
    },
    /// Water withdrawal from a hydro reservoir (m³/s). Stage-level, not block-specific.
    HydroWithdrawal {
        /// Hydro plant identifier.
        hydro_id: EntityId,
    },
    /// Electrical generation from a thermal unit (MW).
    ThermalGeneration {
        /// Thermal unit identifier.
        thermal_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Direct (forward) power flow on a transmission line (MW).
    LineDirect {
        /// Transmission line identifier.
        line_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Reverse power flow on a transmission line (MW).
    LineReverse {
        /// Transmission line identifier.
        line_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Net exchange flow on a transmission line (direct - reverse) (MW).
    ///
    /// Derived: maps to two LP columns (forward `+1.0`, reverse `-1.0`),
    /// net flow source-to-target.
    LineExchange {
        /// Transmission line identifier.
        line_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Load deficit (unserved energy) at a bus (MW).
    BusDeficit {
        /// Bus identifier.
        bus_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Load excess (over-generation) at a bus (MW).
    BusExcess {
        /// Bus identifier.
        bus_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Pumped water flow at a pumping station (m³/s).
    PumpingFlow {
        /// Pumping station identifier.
        station_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Electrical power consumed by a pumping station (MW).
    PumpingPower {
        /// Pumping station identifier.
        station_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Energy imported via a contract (MW).
    ContractImport {
        /// Energy contract identifier.
        contract_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Energy exported via a contract (MW).
    ContractExport {
        /// Energy contract identifier.
        contract_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Generation from a non-controllable source (wind, solar, etc.) (MW).
    NonControllableGeneration {
        /// Non-controllable source identifier.
        source_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Curtailment of a non-controllable source (MW).
    NonControllableCurtailment {
        /// Non-controllable source identifier.
        source_id: EntityId,
        /// Block selector.
        block_id: Option<usize>,
    },
    /// Forward-commitment decision for an anticipated thermal unit (MW).
    ///
    /// The commitment placed at stage `t` for delivery at `t + lead_stages`. A
    /// per-plant per-stage scalar — **no `block_id`**, the commitment is uniform
    /// across blocks. The column exists only for plants with
    /// `anticipated_config: Some(_)`; referencing a non-anticipated thermal is a
    /// referential-validation error. At boundary stages (`t + K_i >= n_stages`)
    /// the column has `[0.0, 0.0]` bounds, so a constraint there is a no-op.
    ///
    /// Appended at the END of the enum to preserve every existing variant's
    /// postcard discriminant (postcard encodes variants by declaration order; a
    /// mid-enum insertion breaks serialized policies — pinned by
    /// `test_variable_ref_postcard_discriminant_pin`).
    AnticipatedDecision {
        /// Thermal unit identifier. Must satisfy `anticipated_config: Some(_)`.
        thermal_id: EntityId,
    },
    /// Total realized inflow into a hydro reservoir (m³/s). Block-capable.
    ///
    /// Local natural inflow PLUS the immediately-upstream cascade releases
    /// (turbined + spilled + diverted) routed down — the inflow side of the water
    /// balance, not the `z_inflow` column alone. Coefficients are unit `+1.0` on
    /// every rate column (rate identity in m³/s, NOT the `−τ` volume weighting of
    /// the storage-balance row). Block-dependent (upstream releases are per-block
    /// LP columns), so `None` always expands to one row per block, never a
    /// collapsed stage-level row.
    ///
    /// Appended at the END of the enum to preserve every existing variant's
    /// postcard discriminant.
    HydroInflow {
        /// Hydro plant identifier.
        hydro_id: EntityId,
        /// Block selector; `None` expands to one row per block.
        block_id: Option<usize>,
    },
    /// Start-of-block storage boundary for a hydro reservoir (hm³).
    ///
    /// `Some(k)` references the incoming storage column of block `k` (boundary
    /// `Sᵏ`); `None` references the stage-initial anchor `S⁰`. A stage-level stock:
    /// resolves to a single fixed column, never a per-block expansion.
    ///
    /// Appended at the END of the enum to keep its postcard discriminant stable.
    HydroStorageInitial {
        /// Hydro plant identifier.
        hydro_id: EntityId,
        /// Block selector; `None` = stage-initial `S⁰`.
        block_id: Option<usize>,
    },
    /// End-of-block storage boundary for a hydro reservoir (hm³).
    ///
    /// `Some(k)` references the outgoing storage column of block `k` (boundary
    /// `Sᵏ⁺¹`); `None` references the stage-final `Sᴷ`, equal to `HydroStorage`.
    /// A stage-level stock: resolves to a single fixed column, never a per-block
    /// expansion.
    ///
    /// Appended at the END of the enum to keep its postcard discriminant stable.
    HydroStorageFinal {
        /// Hydro plant identifier.
        hydro_id: EntityId,
        /// Block selector; `None` = stage-final `Sᴷ`.
        block_id: Option<usize>,
    },
}

/// One term in a linear constraint expression: `coefficient * scale * variable`.
///
/// The LP coefficient is `resolve(coefficient, stage) * scale`, the
/// stage-resolved scalar for a `Parameter` or the literal value for a `Literal`.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LinearTerm {
    /// Coefficient reference, resolved to a scalar per stage at LP build time.
    pub coefficient: CoefficientRef,
    /// Multiplicative scale applied after the coefficient is resolved.
    pub scale: f64,
    /// The LP variable being referenced.
    pub variable: VariableRef,
}

impl LinearTerm {
    /// Construct a literal-coefficient `LinearTerm` with `scale = 1.0`.
    #[must_use]
    pub fn literal(coef: f64, variable: VariableRef) -> Self {
        Self {
            coefficient: CoefficientRef::Literal(coef),
            scale: 1.0,
            variable,
        }
    }

    /// Construct a named-parameter-coefficient `LinearTerm`.
    ///
    /// `scale` carries the literal multiplier from the expression (e.g. `2.5`
    /// for `"2.5 * @rho_eq * x"`, or `sign` for `"@rho_eq * x"`).
    #[must_use]
    pub fn parameter(id: EntityId, scale: f64, variable: VariableRef) -> Self {
        Self {
            coefficient: CoefficientRef::Parameter(id),
            scale,
            variable,
        }
    }
}

/// Parsed left-hand side of a generic constraint as weighted variable
/// references. An empty `terms` vector is valid (constant-only expression, not
/// rejected at this layer).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ConstraintExpression {
    /// Ordered list of linear terms that form the left-hand side of the constraint.
    pub terms: Vec<LinearTerm>,
}

/// Comparison sense for a generic constraint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ConstraintSense {
    /// The expression must be greater than or equal to the bound (`>=`).
    GreaterEqual,
    /// The expression must be less than or equal to the bound (`<=`).
    LessEqual,
    /// The expression must be exactly equal to the bound (`==`).
    Equal,
}

/// Slack variable configuration for a generic constraint.
///
/// An enabled slack lets the constraint be violated at a cost (entering the LP
/// objective), preventing infeasibility under tight or conflicting bounds.
/// `penalty` must be `Some(positive)` when `enabled`, `None` otherwise.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SlackConfig {
    /// Whether a slack variable is added to allow soft violation of the constraint.
    pub enabled: bool,
    /// Penalty cost per unit of constraint violation.
    pub penalty: Option<f64>,
}

/// A user-defined generic linear constraint.
///
/// Sorted by `id` after loading to satisfy declaration-order invariance.
/// Parsing, referential validation, and bounds loading happen in `cobre-io`.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GenericConstraint {
    /// Unique constraint identifier.
    pub id: EntityId,
    /// Short name used in reports and log output.
    pub name: String,
    /// Optional human-readable description.
    pub description: Option<String>,
    /// Parsed left-hand-side expression of the constraint.
    pub expression: ConstraintExpression,
    /// Comparison sense (`>=`, `<=`, or `==`).
    pub sense: ConstraintSense,
    /// Slack variable configuration.
    pub slack: SlackConfig,
}

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

    #[test]
    fn test_variable_ref_variants() {
        let variants: &[(&str, VariableRef)] = &[
            (
                "HydroStorage",
                VariableRef::HydroStorage {
                    hydro_id: EntityId(0),
                },
            ),
            (
                "HydroTurbined",
                VariableRef::HydroTurbined {
                    hydro_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "HydroSpillage",
                VariableRef::HydroSpillage {
                    hydro_id: EntityId(0),
                    block_id: Some(1),
                },
            ),
            (
                "HydroDiversion",
                VariableRef::HydroDiversion {
                    hydro_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "HydroOutflow",
                VariableRef::HydroOutflow {
                    hydro_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "HydroGeneration",
                VariableRef::HydroGeneration {
                    hydro_id: EntityId(0),
                    block_id: Some(0),
                },
            ),
            (
                "HydroEvaporation",
                VariableRef::HydroEvaporation {
                    hydro_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "HydroWithdrawal",
                VariableRef::HydroWithdrawal {
                    hydro_id: EntityId(0),
                },
            ),
            (
                "ThermalGeneration",
                VariableRef::ThermalGeneration {
                    thermal_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "LineDirect",
                VariableRef::LineDirect {
                    line_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "LineReverse",
                VariableRef::LineReverse {
                    line_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "LineExchange",
                VariableRef::LineExchange {
                    line_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "BusDeficit",
                VariableRef::BusDeficit {
                    bus_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "BusExcess",
                VariableRef::BusExcess {
                    bus_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "PumpingFlow",
                VariableRef::PumpingFlow {
                    station_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "PumpingPower",
                VariableRef::PumpingPower {
                    station_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "ContractImport",
                VariableRef::ContractImport {
                    contract_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "ContractExport",
                VariableRef::ContractExport {
                    contract_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "NonControllableGeneration",
                VariableRef::NonControllableGeneration {
                    source_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "NonControllableCurtailment",
                VariableRef::NonControllableCurtailment {
                    source_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "AnticipatedDecision",
                VariableRef::AnticipatedDecision {
                    thermal_id: EntityId(0),
                },
            ),
            (
                "HydroInflow",
                VariableRef::HydroInflow {
                    hydro_id: EntityId(0),
                    block_id: None,
                },
            ),
            (
                "HydroStorageInitial",
                VariableRef::HydroStorageInitial {
                    hydro_id: EntityId(0),
                    block_id: Some(0),
                },
            ),
            (
                "HydroStorageFinal",
                VariableRef::HydroStorageFinal {
                    hydro_id: EntityId(0),
                    block_id: None,
                },
            ),
        ];

        assert_eq!(
            variants.len(),
            24,
            "VariableRef must have exactly 24 variants"
        );

        for (name, variant) in variants {
            let debug_str = format!("{variant:?}");
            assert!(
                debug_str.contains(name),
                "Debug output for {name} does not contain the variant name: {debug_str}"
            );
        }
    }

    /// Pins the postcard discriminants of the tail variants. Postcard encodes
    /// the variant index as a varint; for discriminants `< 0x80` the first byte
    /// equals the discriminant. `AnticipatedDecision` (index 20 = `0x14`),
    /// `HydroInflow` (index 21 = `0x15`), `HydroStorageInitial` (index 22 =
    /// `0x16`), and `HydroStorageFinal` (index 23 = `0x17`) must keep their
    /// indices — a mid-enum insertion would shift them and silently break
    /// previously serialized policies.
    #[cfg(feature = "serde")]
    #[test]
    fn test_variable_ref_postcard_discriminant_pin() {
        let hydro_inflow = postcard::to_allocvec(&VariableRef::HydroInflow {
            hydro_id: EntityId(0),
            block_id: None,
        })
        .expect("HydroInflow serializes");
        assert_eq!(
            hydro_inflow[0], 0x15,
            "HydroInflow must serialize to postcard discriminant 0x15"
        );

        let anticipated = postcard::to_allocvec(&VariableRef::AnticipatedDecision {
            thermal_id: EntityId(0),
        })
        .expect("AnticipatedDecision serializes");
        assert_eq!(
            anticipated[0], 0x14,
            "AnticipatedDecision must keep postcard discriminant 0x14"
        );

        let storage_initial = postcard::to_allocvec(&VariableRef::HydroStorageInitial {
            hydro_id: EntityId(0),
            block_id: None,
        })
        .expect("HydroStorageInitial serializes");
        assert_eq!(
            storage_initial[0], 0x16,
            "HydroStorageInitial must serialize to postcard discriminant 0x16"
        );

        let storage_final = postcard::to_allocvec(&VariableRef::HydroStorageFinal {
            hydro_id: EntityId(0),
            block_id: None,
        })
        .expect("HydroStorageFinal serializes");
        assert_eq!(
            storage_final[0], 0x17,
            "HydroStorageFinal must serialize to postcard discriminant 0x17"
        );
    }

    #[test]
    fn test_generic_constraint_construction() {
        let expr = ConstraintExpression {
            terms: vec![
                LinearTerm::literal(
                    1.0,
                    VariableRef::HydroGeneration {
                        hydro_id: EntityId(10),
                        block_id: None,
                    },
                ),
                LinearTerm::literal(
                    1.0,
                    VariableRef::HydroGeneration {
                        hydro_id: EntityId(11),
                        block_id: None,
                    },
                ),
            ],
        };

        let gc = GenericConstraint {
            id: EntityId(0),
            name: "min_southeast_hydro".to_string(),
            description: Some("Minimum hydro generation in Southeast region".to_string()),
            expression: expr,
            sense: ConstraintSense::GreaterEqual,
            slack: SlackConfig {
                enabled: true,
                penalty: Some(5_000.0),
            },
        };

        assert_eq!(gc.expression.terms.len(), 2);
        assert_eq!(gc.id, EntityId(0));
        assert_eq!(gc.name, "min_southeast_hydro");
        assert!(gc.description.is_some());
        assert_eq!(gc.sense, ConstraintSense::GreaterEqual);
        assert!(gc.slack.enabled);
        assert_eq!(gc.slack.penalty, Some(5_000.0));
    }

    #[test]
    fn test_slack_config_disabled_has_no_penalty() {
        let slack = SlackConfig {
            enabled: false,
            penalty: None,
        };
        assert!(!slack.enabled);
        assert!(slack.penalty.is_none());
    }

    #[test]
    fn test_constraint_sense_variants() {
        assert_ne!(ConstraintSense::GreaterEqual, ConstraintSense::LessEqual);
        assert_ne!(ConstraintSense::GreaterEqual, ConstraintSense::Equal);
        assert_ne!(ConstraintSense::LessEqual, ConstraintSense::Equal);
    }

    fn lit(term: &LinearTerm) -> f64 {
        match term.coefficient {
            CoefficientRef::Literal(v) => v,
            CoefficientRef::Parameter(_) => panic!("expected literal"),
        }
    }

    #[test]
    fn test_linear_term_with_coefficient() {
        let term = LinearTerm::literal(
            2.5,
            VariableRef::ThermalGeneration {
                thermal_id: EntityId(5),
                block_id: None,
            },
        );
        assert!((lit(&term) - 2.5).abs() < f64::EPSILON);
        let debug = format!("{:?}", term.variable);
        assert!(debug.contains("ThermalGeneration"));
    }

    #[test]
    fn linear_term_literal_constructor() {
        let term = LinearTerm::literal(
            3.0,
            VariableRef::ThermalGeneration {
                thermal_id: EntityId(1),
                block_id: None,
            },
        );
        assert_eq!(term.coefficient, CoefficientRef::Literal(3.0));
        assert!((term.scale - 1.0).abs() < f64::EPSILON);
        assert_eq!(
            term.variable,
            VariableRef::ThermalGeneration {
                thermal_id: EntityId(1),
                block_id: None,
            }
        );
    }

    #[test]
    fn linear_term_explicit_scale() {
        let term = LinearTerm {
            coefficient: CoefficientRef::Literal(2.0),
            scale: 0.5,
            variable: VariableRef::HydroStorage {
                hydro_id: EntityId(1),
            },
        };
        assert!((term.scale - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_variable_ref_block_none_vs_some() {
        let all_blocks = VariableRef::HydroTurbined {
            hydro_id: EntityId(3),
            block_id: None,
        };
        let specific_block = VariableRef::HydroTurbined {
            hydro_id: EntityId(3),
            block_id: Some(0),
        };
        assert_ne!(all_blocks, specific_block);
    }

    #[test]
    fn anticipated_decision_constructs() {
        let v = VariableRef::AnticipatedDecision {
            thermal_id: EntityId(5),
        };
        let debug_str = format!("{v:?}");
        assert!(
            debug_str.contains("AnticipatedDecision"),
            "Debug output should contain variant name: {debug_str}"
        );
        assert!(
            debug_str.contains("thermal_id"),
            "Debug output should contain field name: {debug_str}"
        );
    }

    #[test]
    fn anticipated_decision_copy_and_eq() {
        let v1 = VariableRef::AnticipatedDecision {
            thermal_id: EntityId(5),
        };
        let v2 = v1;
        assert_eq!(v1, v2);

        let v3 = VariableRef::AnticipatedDecision {
            thermal_id: EntityId(9),
        };
        assert_ne!(v1, v3);
    }

    /// Postcard round-trip preserves `AnticipatedDecision`, and pins its
    /// discriminant byte so no variant can be inserted before it without
    /// breaking this assertion (postcard encodes variants by declaration order).
    #[cfg(feature = "serde")]
    #[test]
    fn anticipated_decision_postcard_roundtrip() {
        let original = VariableRef::AnticipatedDecision {
            thermal_id: EntityId(5),
        };
        let bytes = postcard::to_allocvec(&original).expect("serialize");
        let recovered: VariableRef = postcard::from_bytes(&bytes).expect("deserialize");
        assert_eq!(
            original, recovered,
            "postcard round-trip must preserve the variant"
        );

        assert_eq!(
            bytes[0], 20,
            "AnticipatedDecision must be discriminant 20 (end-of-enum); \
             got {}. Did you insert a variant before it?",
            bytes[0]
        );
    }

    /// Regression: no insertion before `NonControllableCurtailment` shifted its
    /// discriminant (index 19).
    #[cfg(feature = "serde")]
    #[test]
    fn non_controllable_curtailment_discriminant_is_19() {
        let v = VariableRef::NonControllableCurtailment {
            source_id: EntityId(0),
            block_id: None,
        };
        let bytes = postcard::to_allocvec(&v).expect("serialize");
        assert_eq!(
            bytes[0], 19,
            "NonControllableCurtailment must remain discriminant 19; \
             got {}. A variant was inserted before it.",
            bytes[0]
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_generic_constraint_serde_roundtrip() {
        let gc = GenericConstraint {
            id: EntityId(0),
            name: "test".to_string(),
            description: None,
            expression: ConstraintExpression {
                terms: vec![
                    LinearTerm::literal(
                        1.0,
                        VariableRef::HydroGeneration {
                            hydro_id: EntityId(10),
                            block_id: None,
                        },
                    ),
                    LinearTerm::literal(
                        1.0,
                        VariableRef::HydroGeneration {
                            hydro_id: EntityId(11),
                            block_id: None,
                        },
                    ),
                ],
            },
            sense: ConstraintSense::GreaterEqual,
            slack: SlackConfig {
                enabled: true,
                penalty: Some(5_000.0),
            },
        };

        let json = serde_json::to_string(&gc).unwrap();
        let deserialized: GenericConstraint = serde_json::from_str(&json).unwrap();
        assert_eq!(gc, deserialized);
        assert_eq!(deserialized.expression.terms.len(), 2);
    }
}