powerio-prob 0.9.0

Problem instance builders for power system analysis and optimization.
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
1168
1169
1170
1171
1172
1173
1174
1175
use std::collections::{BTreeMap, HashSet};

use powerio::BusId;
use powerio::format::goc3::Goc3Document;
use serde_json::{Map, Value};

use super::error::{ScopfError, ScopfResult};
use super::goc3::{
    Goc3Adapter, cost_cube, float_matrix, float_vec, initial_status, json_error, require_field,
    require_num, require_str,
};
use super::types::{
    ScopfAcContingencySurvivors, ScopfAcLineRow, ScopfAcLineSurvivorRow, ScopfActiveReserveRow,
    ScopfActiveReserveSetRow, ScopfBusRow, ScopfCostRow, ScopfDcContingencyFlowRow, ScopfDcLineRow,
    ScopfDeviceClassLayout, ScopfDeviceRow, ScopfEnergyWindowMaxCsRow, ScopfEnergyWindowMaxPrRow,
    ScopfEnergyWindowMinCsRow, ScopfEnergyWindowMinPrRow, ScopfEnergyWindowPeriodMaxCsRow,
    ScopfEnergyWindowPeriodMaxPrRow, ScopfEnergyWindowPeriodMinCsRow,
    ScopfEnergyWindowPeriodMinPrRow, ScopfEnergyWindows, ScopfFixedPhaseRow, ScopfFixedRatioRow,
    ScopfInstance, ScopfLengths, ScopfPriceBlockRow, ScopfPriceBlocks, ScopfReactiveReserveRow,
    ScopfReactiveReserveSetRow, ScopfShuntRow, ScopfStaticData, ScopfStaticDataProjection,
    ScopfTransformerRow, ScopfTransformerSurvivorRow, ScopfVariablePhaseRow, ScopfVariableRatioRow,
    ScopfViolationCost,
};

type Result<T> = ScopfResult<T>;

/// The device class of a `simple_dispatchable_device` row. An absent
/// `device_type` defaults to `producer`, the same rule the balanced GOC3
/// reader applies in `device_rows`.
fn sdd_device_type(obj: &Map<String, Value>) -> &str {
    obj.get("device_type")
        .and_then(Value::as_str)
        .unwrap_or("producer")
}

/// One required 0/1 mode flag on a `simple_dispatchable_device` row. GOC3
/// writes these as JSON numbers, so a boolean is rejected by name. A writer
/// that emits every number as a float states the same flag as `0.0`/`1.0`, so
/// the value is read as a number and then required to be one of the two.
fn require_flag(obj: &Map<String, Value>, uid: &str, key: &str) -> Result<i64> {
    let raw = obj.get(key).ok_or_else(|| {
        json_error(format!(
            "simple_dispatchable_device `{uid}` missing `{key}`"
        ))
    })?;
    // 0 and 1 are exact in binary floating point, so equality is the right
    // test here: it takes the two flags and nothing near them.
    #[allow(clippy::float_cmp)]
    let flag = raw.as_f64().and_then(|value| {
        if value == 0.0 {
            Some(0)
        } else if value == 1.0 {
            Some(1)
        } else {
            None
        }
    });
    flag.ok_or_else(|| {
        json_error(format!(
            "simple_dispatchable_device `{uid}` `{key}` is not 0 or 1"
        ))
    })
}

/// `initial_status.on_status` for a row of `kind`, validated to 0 or 1 the way
/// [`require_flag`] validates the capability flags.
fn initial_on_status(kind: &str, uid: &str, val: &Map<String, Value>) -> Result<i64> {
    let raw = require_num(initial_status(val)?, "on_status")?;
    // 0 and 1 are exact in binary floating point; see `require_flag`.
    #[allow(clippy::float_cmp)]
    if raw == 0.0 {
        Ok(0)
    } else if raw == 1.0 {
        Ok(1)
    } else {
        Err(json_error(format!(
            "{kind} `{uid}` `initial_status.on_status` is not 0 or 1"
        )))
    }
}

fn validate_period_len(
    kind: &str,
    uid: &str,
    field: &str,
    actual: usize,
    expected: usize,
) -> Result<()> {
    if actual == expected {
        return Ok(());
    }
    Err(json_error(format!(
        "{kind} `{uid}` `{field}` has {actual} periods; expected {expected}"
    )))
}

impl Goc3Adapter {
    fn cost_vector(&self, device_type: &str) -> Result<Vec<ScopfCostRow>> {
        let mut rows = Vec::new();
        for uid in self.sdd_order() {
            let val = self.sdd.get(&uid)?;
            if sdd_device_type(val) != device_type {
                continue;
            }
            let ts_val = self.sdd_ts.get(&uid)?;
            let bus = self.goc3_bus_id(require_str(val, "bus")?)?;
            let cost = ts_val.get("cost").ok_or_else(|| {
                json_error(format!(
                    "simple_dispatchable_device time series `{uid}` missing `cost`"
                ))
            })?;
            let cost = cost_cube(cost)?;
            validate_period_len(
                "simple_dispatchable_device time series",
                &uid,
                "cost",
                cost.len(),
                self.dt.len(),
            )?;
            rows.push(ScopfCostRow { bus, uid, cost });
        }
        Ok(rows)
    }

    fn twt_variable_phase(&self) -> Result<Vec<ScopfVariablePhaseRow>> {
        let mut rows = Vec::new();
        for (j_xf, uid) in self.twt.uids().iter().enumerate() {
            let val = self.twt.get(uid)?;
            let (lb, ub) = (require_num(val, "ta_lb")?, require_num(val, "ta_ub")?);
            if lb < ub {
                rows.push(ScopfVariablePhaseRow {
                    j_xf,
                    phi_min: lb,
                    phi_max: ub,
                });
            }
        }
        rows.sort_by_key(|r| r.j_xf);
        Ok(rows)
    }

    fn twt_fixed_phase(&self) -> Result<Vec<ScopfFixedPhaseRow>> {
        let mut rows = Vec::new();
        for (j_xf, uid) in self.twt.uids().iter().enumerate() {
            let val = self.twt.get(uid)?;
            let (lb, ub) = (require_num(val, "ta_lb")?, require_num(val, "ta_ub")?);
            if lb >= ub {
                let phi_o = require_num(initial_status(val)?, "ta")?;
                rows.push(ScopfFixedPhaseRow { j_xf, phi_o });
            }
        }
        rows.sort_by_key(|r| r.j_xf);
        Ok(rows)
    }

    fn twt_variable_ratio(&self) -> Result<Vec<ScopfVariableRatioRow>> {
        let mut rows = Vec::new();
        for (j_xf, uid) in self.twt.uids().iter().enumerate() {
            let val = self.twt.get(uid)?;
            let (lb, ub) = (require_num(val, "tm_lb")?, require_num(val, "tm_ub")?);
            if lb < ub {
                rows.push(ScopfVariableRatioRow {
                    j_xf,
                    tau_min: lb,
                    tau_max: ub,
                });
            }
        }
        rows.sort_by_key(|r| r.j_xf);
        Ok(rows)
    }

    fn twt_fixed_ratio(&self) -> Result<Vec<ScopfFixedRatioRow>> {
        let mut rows = Vec::new();
        for (j_xf, uid) in self.twt.uids().iter().enumerate() {
            let val = self.twt.get(uid)?;
            let (lb, ub) = (require_num(val, "tm_lb")?, require_num(val, "tm_ub")?);
            if lb >= ub {
                let tau_o = require_num(initial_status(val)?, "tm")?;
                rows.push(ScopfFixedRatioRow { j_xf, tau_o });
            }
        }
        rows.sort_by_key(|r| r.j_xf);
        Ok(rows)
    }

    fn sdd_row(&self, uid: &str, j_dev: usize, j_sdd: usize) -> Result<ScopfDeviceRow> {
        const SDD: &str = "simple_dispatchable_device";
        const SDD_TS: &str = "simple_dispatchable_device time series";
        let val = self.sdd.get(uid)?;
        let ts_val = self.sdd_ts.get(uid)?;
        let initial = initial_status(val)?;
        let ts = |key| require_field(ts_val, SDD_TS, uid, key);
        // Both flags are required, so a document that omits one fails here
        // instead of reading as "no capability". A parameter is read only when
        // its own mode is selected.
        let q_bound_cap = require_flag(val, uid, "q_bound_cap")?;
        let q_linear_cap = require_flag(val, uid, "q_linear_cap")?;
        if q_bound_cap == 1 && q_linear_cap == 1 {
            return Err(json_error(format!(
                "{SDD} `{uid}` sets both `q_bound_cap` and `q_linear_cap`; the two modes are mutually exclusive"
            )));
        }
        let cap = |flag: i64, key: &str| -> Result<Option<f64>> {
            if flag == 1 {
                Ok(Some(require_num(val, key)?))
            } else {
                Ok(None)
            }
        };
        let row = ScopfDeviceRow {
            bus: self.goc3_bus_id(require_str(val, "bus")?)?,
            uid: uid.to_owned(),
            j_dev,
            j_sdd,
            c_on: require_num(val, "on_cost")?,
            c_su: require_num(val, "startup_cost")?,
            c_sd: require_num(val, "shutdown_cost")?,
            p_ru: require_num(val, "p_ramp_up_ub")?,
            p_rd: require_num(val, "p_ramp_down_ub")?,
            p_ru_su: require_num(val, "p_startup_ramp_ub")?,
            p_rd_sd: require_num(val, "p_shutdown_ramp_ub")?,
            c_rgu: float_vec(ts("p_reg_res_up_cost")?)?,
            c_rgd: float_vec(ts("p_reg_res_down_cost")?)?,
            c_scr: float_vec(ts("p_syn_res_cost")?)?,
            c_nsc: float_vec(ts("p_nsyn_res_cost")?)?,
            c_rru_on: float_vec(ts("p_ramp_res_up_online_cost")?)?,
            c_rru_off: float_vec(ts("p_ramp_res_up_offline_cost")?)?,
            c_rrd_on: float_vec(ts("p_ramp_res_down_online_cost")?)?,
            c_rrd_off: float_vec(ts("p_ramp_res_down_offline_cost")?)?,
            c_qru: float_vec(ts("q_res_up_cost")?)?,
            c_qrd: float_vec(ts("q_res_down_cost")?)?,
            p_rgu_max: require_num(val, "p_reg_res_up_ub")?,
            p_rgd_max: require_num(val, "p_reg_res_down_ub")?,
            p_scr_max: require_num(val, "p_syn_res_ub")?,
            p_nsc_max: require_num(val, "p_nsyn_res_ub")?,
            p_rru_on_max: require_num(val, "p_ramp_res_up_online_ub")?,
            p_rru_off_max: require_num(val, "p_ramp_res_up_offline_ub")?,
            p_rrd_on_max: require_num(val, "p_ramp_res_down_online_ub")?,
            p_rrd_off_max: require_num(val, "p_ramp_res_down_offline_ub")?,
            p_0: require_num(initial, "p")?,
            q_0: require_num(initial, "q")?,
            u_0: initial_on_status(SDD, uid, val)?,
            p_max: float_vec(ts("p_ub")?)?,
            p_min: float_vec(ts("p_lb")?)?,
            q_max: float_vec(ts("q_ub")?)?,
            q_min: float_vec(ts("q_lb")?)?,
            sus: float_matrix(require_field(val, SDD, uid, "startup_states")?)?,
            q_bound_cap,
            q_linear_cap,
            beta_ub: cap(q_bound_cap, "beta_ub")?,
            beta_lb: cap(q_bound_cap, "beta_lb")?,
            q_0_ub: cap(q_bound_cap, "q_0_ub")?,
            q_0_lb: cap(q_bound_cap, "q_0_lb")?,
            beta: cap(q_linear_cap, "beta")?,
            q_p0: cap(q_linear_cap, "q_0")?,
        };
        for (field, actual) in [
            ("p_reg_res_up_cost", row.c_rgu.len()),
            ("p_reg_res_down_cost", row.c_rgd.len()),
            ("p_syn_res_cost", row.c_scr.len()),
            ("p_nsyn_res_cost", row.c_nsc.len()),
            ("p_ramp_res_up_online_cost", row.c_rru_on.len()),
            ("p_ramp_res_up_offline_cost", row.c_rru_off.len()),
            ("p_ramp_res_down_online_cost", row.c_rrd_on.len()),
            ("p_ramp_res_down_offline_cost", row.c_rrd_off.len()),
            ("q_res_up_cost", row.c_qru.len()),
            ("q_res_down_cost", row.c_qrd.len()),
            ("p_ub", row.p_max.len()),
            ("p_lb", row.p_min.len()),
            ("q_ub", row.q_max.len()),
            ("q_lb", row.q_min.len()),
        ] {
            validate_period_len(SDD_TS, uid, field, actual, self.dt.len())?;
        }
        Ok(row)
    }

    /// `class_offset` places this class's block in the canonical device
    /// stacking (`j_sdd`): 0 for producers, the producer count for consumers.
    fn sdd_rows(&self, device_type: &str, class_offset: usize) -> Result<Vec<ScopfDeviceRow>> {
        let mut rows = Vec::new();
        for uid in self.sdd_order() {
            if sdd_device_type(self.sdd.get(&uid)?) == device_type {
                let j_dev = rows.len();
                rows.push(self.sdd_row(&uid, j_dev, class_offset + j_dev)?);
            }
        }
        Ok(rows)
    }

    /// One (bus, zone, device) membership set: `ids` is the reserve zone
    /// section's uid list in document order, so the `zone_index` passed to
    /// `mkrow` matches the `n_p`/`n_q` the reserve rows assign from the same
    /// order. `uids_key` names the bus field listing its zone uids and
    /// `device_type` filters the zone's devices. The Rust equivalent of
    /// `reserve_set` in `src/goc3.jl`, iterating buses in `members.bus_order`
    /// and devices in `members.devices_by_bus` order (`src/goc3.jl` iterates
    /// both as `Dict`s here). `members` is precomputed once by the caller;
    /// four membership sets share it.
    fn reserve_set<R>(
        &self,
        ids: &[String],
        uids_key: &str,
        device_type: &str,
        members: &ReserveMembers<'_>,
        mkrow: impl Fn(BusId, usize, String, usize, usize) -> R,
    ) -> Result<Vec<R>> {
        let mut rows = Vec::new();
        for (zone_index, id) in ids.iter().enumerate() {
            for bus_uid in members.bus_order {
                let bus_obj = self.bus.get(bus_uid)?;
                let member = bus_obj
                    .get(uids_key)
                    .and_then(Value::as_array)
                    .is_some_and(|zones| zones.iter().any(|z| z.as_str() == Some(id.as_str())));
                if !member {
                    continue;
                }
                let Some(devices) = members.devices_by_bus.get(bus_uid) else {
                    continue;
                };
                for dev_uid in devices {
                    let device = self.sdd.get(dev_uid)?;
                    if sdd_device_type(device) == device_type {
                        // Total by construction: the ordinal map and this
                        // filter classify with the same `sdd_device_type`.
                        let &(j_dev, j_sdd) = members.ordinals.get(dev_uid).ok_or_else(|| {
                            json_error(format!("reserve zone member `{dev_uid}` has no device row"))
                        })?;
                        rows.push(mkrow(
                            self.goc3_bus_id(bus_uid)?,
                            zone_index,
                            dev_uid.clone(),
                            j_dev,
                            j_sdd,
                        ));
                    }
                }
            }
        }
        Ok(rows)
    }
}

/// The shared context of the four reserve membership builders: bus iteration
/// order, each bus's devices, and every device's `(j_dev, j_sdd)` ordinals.
struct ReserveMembers<'a> {
    devices_by_bus: &'a BTreeMap<String, Vec<String>>,
    bus_order: &'a [String],
    ordinals: &'a BTreeMap<String, (usize, usize)>,
}

/// Build the static SCOPF index sets from parsed GOC3 tables
/// (`_build_static_projection` in `src/goc3.jl`). Pure function of `tables`; no unit
/// commitment solution is used.
// One flat builder mirroring `_build_static_projection`'s single `sc_data` literal
// in `src/goc3.jl`; splitting it into a builder per row family would scatter
// the one-to-one correspondence with the Julia source this port is checked
// against. `additional_shunt` is a discrete 0/1 flag read straight from
// JSON, not an accumulated float, so the exact comparison is intentional.
#[allow(clippy::too_many_lines, clippy::float_cmp)]
fn build_static_projection(tables: &Goc3Adapter) -> Result<ScopfStaticDataProjection> {
    let l_j_xf = tables.twt.uids().len();
    let l_j_ln = tables.ac_line.uids().len();
    let l_j_ac = l_j_ln + l_j_xf;
    let l_j_dc = tables.dc_line.uids().len();
    let l_j_br = l_j_ac + l_j_dc;
    let l_j_cs = tables.sdd_ids_consumer.len();
    let l_j_pr = tables.sdd_ids_producer.len();
    let l_j_cspr = l_j_cs + l_j_pr;
    let l_j_sh = tables.shunt.uids().len();
    let i = tables.bus.uids().len();
    let l_t = tables.dt.len();
    let l_n_p = tables.azr.uids().len();
    let l_n_q = tables.rzr.uids().len();
    // The survivor builders read the same section. A client that sizes a per
    // contingency array must not have to reach back into the source document
    // for the one number that fixes its extent.
    let k = tables.contingencies()?.len();

    let lengths = ScopfLengths {
        l_j_xf,
        l_j_ln,
        l_j_ac,
        l_j_dc,
        l_j_br,
        l_j_cs,
        l_j_pr,
        l_j_cspr,
        l_j_sh,
        i,
        l_t,
        l_n_p,
        l_n_q,
        k,
    };

    let mut bus: Vec<ScopfBusRow> = tables
        .bus
        .uids()
        .iter()
        .map(|uid| {
            let val = tables.bus.get(uid)?;
            Ok(ScopfBusRow {
                i: tables.goc3_bus_id(uid)?,
                uid: uid.clone(),
                v_min: require_num(val, "vm_lb")?,
                v_max: require_num(val, "vm_ub")?,
            })
        })
        .collect::<Result<_>>()?;
    bus.sort_by_key(|r| r.i);

    let shunt: Vec<ScopfShuntRow> = tables
        .shunt
        .uids()
        .iter()
        .enumerate()
        .map(|(j_sh, uid)| {
            let val = tables.shunt.get(uid)?;
            Ok(ScopfShuntRow {
                j_sh,
                uid: uid.clone(),
                bus: tables.goc3_bus_id(require_str(val, "bus")?)?,
                g_sh: require_num(val, "gs")?,
                b_sh: require_num(val, "bs")?,
            })
        })
        .collect::<Result<_>>()?;
    let mut acl_branch: Vec<ScopfAcLineRow> = tables
        .ac_line
        .uids()
        .iter()
        .enumerate()
        .map(|(j_ln, uid)| {
            let val = tables.ac_line.get(uid)?;
            let (g_sr, b_sr, b_ch, g_fr, g_to, b_fr, b_to) = branch_admittance(uid, val)?;
            Ok(ScopfAcLineRow {
                j_ln,
                uid: uid.clone(),
                to_bus: tables.goc3_bus_id(require_str(val, "to_bus")?)?,
                fr_bus: tables.goc3_bus_id(require_str(val, "fr_bus")?)?,
                c_su: require_num(val, "connection_cost")?,
                c_sd: require_num(val, "disconnection_cost")?,
                u_0: initial_on_status("ac_line", uid, val)?,
                s_max: require_num(val, "mva_ub_nom")?,
                g_sr,
                b_sr,
                b_ch,
                g_fr,
                g_to,
                b_fr,
                b_to,
            })
        })
        .collect::<Result<_>>()?;
    acl_branch.sort_by_key(|r| r.j_ln);

    let mut acx_branch: Vec<ScopfTransformerRow> = tables
        .twt
        .uids()
        .iter()
        .enumerate()
        .map(|(j_xf, uid)| {
            let val = tables.twt.get(uid)?;
            let (g_sr, b_sr, b_ch, g_fr, g_to, b_fr, b_to) = branch_admittance(uid, val)?;
            Ok(ScopfTransformerRow {
                j_xf,
                uid: uid.clone(),
                to_bus: tables.goc3_bus_id(require_str(val, "to_bus")?)?,
                fr_bus: tables.goc3_bus_id(require_str(val, "fr_bus")?)?,
                c_su: require_num(val, "connection_cost")?,
                c_sd: require_num(val, "disconnection_cost")?,
                u_0: initial_on_status("two_winding_transformer", uid, val)?,
                s_max: require_num(val, "mva_ub_nom")?,
                g_sr,
                b_sr,
                b_ch,
                g_fr,
                g_to,
                b_fr,
                b_to,
            })
        })
        .collect::<Result<_>>()?;
    acx_branch.sort_by_key(|r| r.j_xf);

    let mut dc_branch: Vec<ScopfDcLineRow> = tables
        .dc_line
        .uids()
        .iter()
        .enumerate()
        .map(|(j_dc, uid)| {
            let val = tables.dc_line.get(uid)?;
            Ok(ScopfDcLineRow {
                j_dc,
                uid: uid.clone(),
                pdc_max: require_num(val, "pdc_ub")?,
                qdc_fr_min: require_num(val, "qdc_fr_lb")?,
                qdc_to_min: require_num(val, "qdc_to_lb")?,
                qdc_fr_max: require_num(val, "qdc_fr_ub")?,
                qdc_to_max: require_num(val, "qdc_to_ub")?,
                to_bus: tables.goc3_bus_id(require_str(val, "to_bus")?)?,
                fr_bus: tables.goc3_bus_id(require_str(val, "fr_bus")?)?,
            })
        })
        .collect::<Result<_>>()?;
    dc_branch.sort_by_key(|r| r.j_dc);

    let cost_vector_pr = tables.cost_vector("producer")?;
    let cost_vector_cs = tables.cost_vector("consumer")?;
    let prod = tables.sdd_rows("producer", 0)?;
    let cons = tables.sdd_rows("consumer", prod.len())?;
    let device_ordinals: BTreeMap<String, (usize, usize)> = prod
        .iter()
        .chain(cons.iter())
        .map(|r| (r.uid.clone(), (r.j_dev, r.j_sdd)))
        .collect();

    let mut active_reserve: Vec<ScopfActiveReserveRow> = tables
        .azr
        .uids()
        .iter()
        .enumerate()
        .map(|(n_p, uid)| {
            let val = tables.azr.get(uid)?;
            let ts_val = tables.azr_ts.get(uid)?;
            let row = ScopfActiveReserveRow {
                n_p,
                uid: uid.clone(),
                c_rgu: require_num(val, "REG_UP_vio_cost")?,
                c_rgd: require_num(val, "REG_DOWN_vio_cost")?,
                c_scr: require_num(val, "SYN_vio_cost")?,
                c_nsc: require_num(val, "NSYN_vio_cost")?,
                c_rru: require_num(val, "RAMPING_RESERVE_UP_vio_cost")?,
                c_rrd: require_num(val, "RAMPING_RESERVE_DOWN_vio_cost")?,
                sigma_rgu: require_num(val, "REG_UP")?,
                sigma_rgd: require_num(val, "REG_DOWN")?,
                sigma_scr: require_num(val, "SYN")?,
                sigma_nsc: require_num(val, "NSYN")?,
                p_rru_min: float_vec(ts_val.get("RAMPING_RESERVE_UP").ok_or_else(|| {
                    json_error(format!(
                        "active_zonal_reserve time series `{uid}` missing `RAMPING_RESERVE_UP`"
                    ))
                })?)?,
                p_rrd_min: float_vec(ts_val.get("RAMPING_RESERVE_DOWN").ok_or_else(|| {
                    json_error(format!(
                        "active_zonal_reserve time series `{uid}` missing `RAMPING_RESERVE_DOWN`"
                    ))
                })?)?,
            };
            validate_period_len(
                "active_zonal_reserve time series",
                uid,
                "RAMPING_RESERVE_UP",
                row.p_rru_min.len(),
                tables.dt.len(),
            )?;
            validate_period_len(
                "active_zonal_reserve time series",
                uid,
                "RAMPING_RESERVE_DOWN",
                row.p_rrd_min.len(),
                tables.dt.len(),
            )?;
            Ok(row)
        })
        .collect::<Result<_>>()?;
    active_reserve.sort_by_key(|r| r.n_p);

    let mut reactive_reserve: Vec<ScopfReactiveReserveRow> = tables
        .rzr
        .uids()
        .iter()
        .enumerate()
        .map(|(n_q, uid)| {
            let val = tables.rzr.get(uid)?;
            let ts_val = tables.rzr_ts.get(uid)?;
            let row = ScopfReactiveReserveRow {
                n_q,
                uid: uid.clone(),
                c_qru: require_num(val, "REACT_UP_vio_cost")?,
                c_qrd: require_num(val, "REACT_DOWN_vio_cost")?,
                q_qru_min: float_vec(ts_val.get("REACT_UP").ok_or_else(|| {
                    json_error(format!(
                        "reactive_zonal_reserve time series `{uid}` missing `REACT_UP`"
                    ))
                })?)?,
                q_qrd_min: float_vec(ts_val.get("REACT_DOWN").ok_or_else(|| {
                    json_error(format!(
                        "reactive_zonal_reserve time series `{uid}` missing `REACT_DOWN`"
                    ))
                })?)?,
            };
            validate_period_len(
                "reactive_zonal_reserve time series",
                uid,
                "REACT_UP",
                row.q_qru_min.len(),
                tables.dt.len(),
            )?;
            validate_period_len(
                "reactive_zonal_reserve time series",
                uid,
                "REACT_DOWN",
                row.q_qrd_min.len(),
                tables.dt.len(),
            )?;
            Ok(row)
        })
        .collect::<Result<_>>()?;
    reactive_reserve.sort_by_key(|r| r.n_q);

    let devices_by_bus = tables.devices_by_bus()?;
    let bus_order = tables.bus_order();
    let members = ReserveMembers {
        devices_by_bus: &devices_by_bus,
        bus_order: &bus_order,
        ordinals: &device_ordinals,
    };
    let active_reserve_set_pr = tables.reserve_set(
        tables.azr.uids(),
        "active_reserve_uids",
        "producer",
        &members,
        |i, n_p, uid, j_dev, j_sdd| ScopfActiveReserveSetRow {
            i,
            n_p,
            uid,
            j_dev,
            j_sdd,
        },
    )?;
    let active_reserve_set_cs = tables.reserve_set(
        tables.azr.uids(),
        "active_reserve_uids",
        "consumer",
        &members,
        |i, n_p, uid, j_dev, j_sdd| ScopfActiveReserveSetRow {
            i,
            n_p,
            uid,
            j_dev,
            j_sdd,
        },
    )?;
    let reactive_reserve_set_pr = tables.reserve_set(
        tables.rzr.uids(),
        "reactive_reserve_uids",
        "producer",
        &members,
        |i, n_q, uid, j_dev, j_sdd| ScopfReactiveReserveSetRow {
            i,
            n_q,
            uid,
            j_dev,
            j_sdd,
        },
    )?;
    let reactive_reserve_set_cs = tables.reserve_set(
        tables.rzr.uids(),
        "reactive_reserve_uids",
        "consumer",
        &members,
        |i, n_q, uid, j_dev, j_sdd| ScopfReactiveReserveSetRow {
            i,
            n_q,
            uid,
            j_dev,
            j_sdd,
        },
    )?;

    let static_data = ScopfStaticData {
        bus,
        shunt,
        acl_branch,
        acx_branch,
        vpd: tables.twt_variable_phase()?,
        fpd: tables.twt_fixed_phase()?,
        vwr: tables.twt_variable_ratio()?,
        fwr: tables.twt_fixed_ratio()?,
        dc_branch,
        prod,
        cons,
        active_reserve,
        reactive_reserve,
        active_reserve_set_pr,
        active_reserve_set_cs,
        reactive_reserve_set_pr,
        reactive_reserve_set_cs,
    };

    Ok(ScopfStaticDataProjection {
        static_data,
        lengths,
        cost_vector_pr,
        cost_vector_cs,
    })
}

fn interval_midpoints(dt: &[f64]) -> Vec<f64> {
    let mut a_end = 0.0;
    dt.iter()
        .map(|d| {
            let start = a_end;
            a_end += d;
            f64::midpoint(start, a_end)
        })
        .collect()
}

/// One `(window_index, uid, start, end, bound)` row, before it is packed
/// into a [`ScopfEnergyWindowMaxPrRow`]-family struct.
type EnergyWindowTuple = (usize, String, f64, f64, f64);
/// One `(window_index, uid, period, duration)` row, before it is packed into
/// a [`ScopfEnergyWindowPeriodMaxPrRow`]-family struct.
type EnergyWindowPeriodTuple = (usize, String, usize, f64);

/// One energy-requirement window set and its per-period membership rows in
/// one pass: `device_type`/`req_key` select the producer/consumer max/min
/// window list. The Rust equivalent of `windows` and `window_periods`
/// together in `src/goc3.jl`'s `_build_energy_windows` (there, two separate
/// passes over the same device/window set; fused here since a window row and
/// its period memberships come from the same parsed `(start, end, bound)`).
/// Device iteration uses [`Goc3Adapter::sdd_order`] (see the module-level
/// order note; `src/goc3.jl` iterates `keys(data.sdd_lookup)`, a `Dict`,
/// here).
fn sdd_windows(
    tables: &Goc3Adapter,
    a_mid: &[f64],
    device_type: &str,
    req_key: &str,
    eps: f64,
) -> Result<(Vec<EnergyWindowTuple>, Vec<EnergyWindowPeriodTuple>)> {
    let mut windows = Vec::new();
    let mut window_periods = Vec::new();
    let mut ind = 0usize;
    for uid in tables.sdd_order() {
        let val = tables.sdd.get(&uid)?;
        if sdd_device_type(val) != device_type {
            continue;
        }
        let req = require_field(val, "simple_dispatchable_device", &uid, req_key)?
            .as_array()
            .ok_or_else(|| {
                json_error(format!(
                    "simple_dispatchable_device `{uid}` `{req_key}` is not an array"
                ))
            })?;
        for w in req {
            let w = float_vec(w)?;
            let [start, end, bound] = w[..] else {
                return Err(json_error(format!(
                    "simple_dispatchable_device `{uid}` `{req_key}` window is not a 3-element array"
                )));
            };
            windows.push((ind, uid.clone(), start, end, bound));
            for (t0, &m) in a_mid.iter().enumerate() {
                if start + eps < m && m <= end + eps {
                    window_periods.push((ind, uid.clone(), t0, tables.dt[t0]));
                }
            }
            ind += 1;
        }
    }
    Ok((windows, window_periods))
}

/// Build the multi-interval energy requirement window sets and their
/// per-period membership sets (`_build_energy_windows` in `src/goc3.jl`).
/// Pure function of `tables`.
// Four max/min x producer/consumer variants, each packed into its own
// distinctly-named row struct to keep Julia's exact field spelling on the
// document (see the module doc comment); the packing is what pushes this over
// the line budget.
#[allow(clippy::too_many_lines)]
fn build_energy_windows(tables: &Goc3Adapter) -> Result<ScopfEnergyWindows> {
    const EPS_TIME: f64 = 1e-6;
    let a_mid = interval_midpoints(&tables.dt);

    let (max_pr, t_max_pr) = sdd_windows(tables, &a_mid, "producer", "energy_req_ub", EPS_TIME)?;
    let (max_cs, t_max_cs) = sdd_windows(tables, &a_mid, "consumer", "energy_req_ub", EPS_TIME)?;
    let (min_pr, t_min_pr) = sdd_windows(tables, &a_mid, "producer", "energy_req_lb", EPS_TIME)?;
    let (min_cs, t_min_cs) = sdd_windows(tables, &a_mid, "consumer", "energy_req_lb", EPS_TIME)?;

    let w_en_max_pr = max_pr
        .into_iter()
        .map(
            |(w_en_max_pr_ind, uid, a_en_max_start, a_en_max_end, e_max)| {
                ScopfEnergyWindowMaxPrRow {
                    w_en_max_pr_ind,
                    uid,
                    a_en_max_start,
                    a_en_max_end,
                    e_max,
                }
            },
        )
        .collect();
    let w_en_max_cs = max_cs
        .into_iter()
        .map(
            |(w_en_max_cs_ind, uid, a_en_max_start, a_en_max_end, e_max)| {
                ScopfEnergyWindowMaxCsRow {
                    w_en_max_cs_ind,
                    uid,
                    a_en_max_start,
                    a_en_max_end,
                    e_max,
                }
            },
        )
        .collect();
    let w_en_min_pr = min_pr
        .into_iter()
        .map(
            |(w_en_min_pr_ind, uid, a_en_min_start, a_en_min_end, e_min)| {
                ScopfEnergyWindowMinPrRow {
                    w_en_min_pr_ind,
                    uid,
                    a_en_min_start,
                    a_en_min_end,
                    e_min,
                }
            },
        )
        .collect();
    let w_en_min_cs = min_cs
        .into_iter()
        .map(
            |(w_en_min_cs_ind, uid, a_en_min_start, a_en_min_end, e_min)| {
                ScopfEnergyWindowMinCsRow {
                    w_en_min_cs_ind,
                    uid,
                    a_en_min_start,
                    a_en_min_end,
                    e_min,
                }
            },
        )
        .collect();

    let t_w_en_max_pr = t_max_pr
        .into_iter()
        .map(
            |(w_en_max_pr_ind, uid, t, dt)| ScopfEnergyWindowPeriodMaxPrRow {
                w_en_max_pr_ind,
                uid,
                t,
                dt,
            },
        )
        .collect();
    let t_w_en_max_cs = t_max_cs
        .into_iter()
        .map(
            |(w_en_max_cs_ind, uid, t, dt)| ScopfEnergyWindowPeriodMaxCsRow {
                w_en_max_cs_ind,
                uid,
                t,
                dt,
            },
        )
        .collect();
    let t_w_en_min_pr = t_min_pr
        .into_iter()
        .map(
            |(w_en_min_pr_ind, uid, t, dt)| ScopfEnergyWindowPeriodMinPrRow {
                w_en_min_pr_ind,
                uid,
                t,
                dt,
            },
        )
        .collect();
    let t_w_en_min_cs = t_min_cs
        .into_iter()
        .map(
            |(w_en_min_cs_ind, uid, t, dt)| ScopfEnergyWindowPeriodMinCsRow {
                w_en_min_cs_ind,
                uid,
                t,
                dt,
            },
        )
        .collect();

    Ok(ScopfEnergyWindows {
        w_en_max_pr,
        w_en_max_cs,
        w_en_min_pr,
        w_en_min_cs,
        t_w_en_max_pr,
        t_w_en_max_cs,
        t_w_en_min_pr,
        t_w_en_min_cs,
    })
}

fn flatten_price_blocks(cost_vector: &[ScopfCostRow]) -> Vec<ScopfPriceBlockRow> {
    let mut rows = Vec::new();
    let mut flat_k = 0usize;
    for pc in cost_vector {
        for (t0, cost_t) in pc.cost.iter().enumerate() {
            for (m0, cost_tm) in cost_t.iter().enumerate() {
                let (c_en, p_max) = (cost_tm[0], cost_tm[1]);
                rows.push(ScopfPriceBlockRow {
                    flat_k,
                    uid: pc.uid.clone(),
                    t: t0,
                    m: m0,
                    c_en,
                    p_max,
                });
                flat_k += 1;
            }
        }
    }
    rows
}

/// Flatten the per-device energy cost curves into one row per (device,
/// period, cost block), unscaled in the GOC3 document's own per-unit
/// convention (`_build_price_blocks` in `src/goc3.jl`). Pure function of the
/// cost vectors [`build_static_projection`] returns; infallible, since
/// [`ScopfCostRow::cost`](ScopfCostRow) is already validated numeric data.
fn build_price_blocks(
    cost_vector_pr: &[ScopfCostRow],
    cost_vector_cs: &[ScopfCostRow],
) -> ScopfPriceBlocks {
    ScopfPriceBlocks {
        producer: flatten_price_blocks(cost_vector_pr),
        consumer: flatten_price_blocks(cost_vector_cs),
    }
}

/// Series admittance `(g_sr, b_sr) = (r, -x) / (r² + x²)` for one GOC3
/// branch record. A zero or non-finite `r² + x²` is rejected by name instead
/// of writing NaN into the instance; `src/goc3.jl` computes the same formula
/// unguarded, so this is deliberately stricter than the Julia parser.
fn series_terms(r: f64, x: f64, uid: &str) -> Result<(f64, f64)> {
    let denom = x * x + r * r;
    if denom == 0.0 {
        return Err(json_error(format!(
            "branch `{uid}` has zero series impedance (r = x = 0)"
        )));
    }
    if !denom.is_finite() {
        return Err(json_error(format!(
            "branch `{uid}` has non-finite series impedance"
        )));
    }
    Ok((r / denom, -x / denom))
}

/// Series admittance and terminal shunt parameters shared by AC lines and
/// transformers: `(g_sr, b_sr, b_ch, g_fr, g_to, b_fr, b_to)`, from
/// `r`/`x`/`b` and, when `additional_shunt` is set, `g_fr`/`g_to`/`b_fr`/
/// `b_to`. The common body of `acl_branch`/`acx_branch` in
/// `_build_static_projection` (`src/goc3.jl`). `additional_shunt` is a discrete 0/1
/// flag read straight from JSON, not an accumulated float, so the exact
/// comparison is intentional.
#[allow(clippy::type_complexity, clippy::float_cmp)]
fn branch_admittance(
    uid: &str,
    val: &Map<String, Value>,
) -> Result<(f64, f64, f64, f64, f64, f64, f64)> {
    let (r, x) = (require_num(val, "r")?, require_num(val, "x")?);
    let (g_sr, b_sr) = series_terms(r, x, uid)?;
    let additional_shunt = require_num(val, "additional_shunt")? == 1.0;
    let (g_fr, g_to, b_fr, b_to) = if additional_shunt {
        (
            require_num(val, "g_fr")?,
            require_num(val, "g_to")?,
            require_num(val, "b_fr")?,
            require_num(val, "b_to")?,
        )
    } else {
        (0.0, 0.0, 0.0, 0.0)
    };
    Ok((g_sr, b_sr, require_num(val, "b")?, g_fr, g_to, b_fr, b_to))
}

/// One contingency index and its outaged component UIDs.
fn contingency_outages(ctg_idx: usize, ctg: &Value) -> Result<(usize, HashSet<&str>)> {
    let ctg_obj = ctg
        .as_object()
        .ok_or_else(|| json_error("reliability.contingency item is not an object"))?;
    let ctg_uid = require_str(ctg_obj, "uid")?;
    let outaged = require_field(ctg_obj, "contingency", ctg_uid, "components")?
        .as_array()
        .ok_or_else(|| {
            json_error(format!(
                "contingency `{ctg_uid}` `components` is not an array"
            ))
        })?
        .iter()
        .map(|v| {
            v.as_str()
                .ok_or_else(|| json_error("component uid is not a string"))
        })
        .collect::<Result<_>>()?;
    Ok((ctg_idx, outaged))
}

/// Enumerate, for each contingency, the AC lines and transformers that
/// remain in service: the branch is not among the contingency's outaged
/// components (`_build_ac_contingency_survivors` in `src/goc3.jl`). The outer
/// vector follows `reliability.contingency`'s document order (which need not
/// match ascending `ctg`); rows within one contingency follow the section's
/// document order (see the module-level order note; `src/goc3.jl` iterates
/// `values(lookup)`, a `Dict`, here).
fn build_ac_contingency_survivors(tables: &Goc3Adapter) -> Result<ScopfAcContingencySurvivors> {
    let contingencies = tables.contingencies()?;

    let mut ln = Vec::with_capacity(contingencies.len());
    let mut xf = Vec::with_capacity(contingencies.len());
    for (ctg_idx, ctg) in contingencies.iter().enumerate() {
        let (ctg_idx, outaged) = contingency_outages(ctg_idx, ctg)?;

        let mut ln_rows = Vec::new();
        for (j_ln, uid) in tables.ac_line.uids().iter().enumerate() {
            if outaged.contains(uid.as_str()) {
                continue;
            }
            let val = tables.ac_line.get(uid)?;
            let (r, x) = (require_num(val, "r")?, require_num(val, "x")?);
            let (_, b_sr) = series_terms(r, x, uid)?;
            ln_rows.push(ScopfAcLineSurvivorRow {
                ctg: ctg_idx,
                j_ln,
                uid: uid.clone(),
                to_bus: tables.goc3_bus_id(require_str(val, "to_bus")?)?,
                fr_bus: tables.goc3_bus_id(require_str(val, "fr_bus")?)?,
                b_sr,
                s_max_ctg: require_num(val, "mva_ub_em")?,
            });
        }
        ln.push(ln_rows);

        let mut xf_rows = Vec::new();
        for (j_xf, uid) in tables.twt.uids().iter().enumerate() {
            if outaged.contains(uid.as_str()) {
                continue;
            }
            let val = tables.twt.get(uid)?;
            let (r, x) = (require_num(val, "r")?, require_num(val, "x")?);
            let (_, b_sr) = series_terms(r, x, uid)?;
            xf_rows.push(ScopfTransformerSurvivorRow {
                ctg: ctg_idx,
                j_xf,
                uid: uid.clone(),
                to_bus: tables.goc3_bus_id(require_str(val, "to_bus")?)?,
                fr_bus: tables.goc3_bus_id(require_str(val, "fr_bus")?)?,
                b_sr,
                s_max_ctg: require_num(val, "mva_ub_em")?,
            });
        }
        xf.push(xf_rows);
    }

    Ok(ScopfAcContingencySurvivors { ln, xf })
}

fn build_dc_contingency_flows(tables: &Goc3Adapter) -> Result<Vec<ScopfDcContingencyFlowRow>> {
    let contingencies = tables.contingencies()?;
    let mut rows = Vec::new();
    let mut flat_jtk_dc = 0usize;
    for (ctg_idx, ctg) in contingencies.iter().enumerate() {
        let (ctg_idx, outaged) = contingency_outages(ctg_idx, ctg)?;

        for (t0, &dt) in tables.dt.iter().enumerate() {
            for (j_dc, uid) in tables.dc_line.uids().iter().enumerate() {
                if outaged.contains(uid.as_str()) {
                    continue;
                }
                let val = tables.dc_line.get(uid)?;
                rows.push(ScopfDcContingencyFlowRow {
                    flat_jtk_dc,
                    ctg: ctg_idx,
                    j_dc,
                    to_bus: tables.goc3_bus_id(require_str(val, "to_bus")?)?,
                    fr_bus: tables.goc3_bus_id(require_str(val, "fr_bus")?)?,
                    t: t0,
                    dt,
                });
                flat_jtk_dc += 1;
            }
        }
    }
    Ok(rows)
}

/// The case's four violation prices. Each one is separately optional: the 14
/// bus validation case has no `e_vio_cost`, so a required field would refuse a
/// document GOCompetition ships.
fn build_violation_cost(tables: &Goc3Adapter) -> ScopfViolationCost {
    let price = |key: &str| tables.violation_cost.get(key).and_then(Value::as_f64);
    ScopfViolationCost {
        p_bus: price("p_bus_vio_cost"),
        q_bus: price("q_bus_vio_cost"),
        s: price("s_vio_cost"),
        e: price("e_vio_cost"),
    }
}

/// How the two device classes sit in the `simple_dispatchable_device`
/// section, read in document order. Document order is the index rule for
/// every per-class index here, so this needs no UID shape.
fn device_class_blocks(tables: &Goc3Adapter) -> Result<ScopfDeviceClassLayout> {
    let mut runs: Vec<&str> = Vec::new();
    for uid in tables.sdd.uids() {
        let kind = sdd_device_type(tables.sdd.get(uid)?);
        let kind = if kind == "consumer" {
            "consumer"
        } else {
            "producer"
        };
        if runs.last() != Some(&kind) {
            runs.push(kind);
        }
    }
    if runs.len() > 2 {
        return Ok(ScopfDeviceClassLayout::Interleaved);
    }
    Ok(ScopfDeviceClassLayout::Contiguous {
        producers_first: runs.first() != Some(&"consumer"),
    })
}

fn project_scopf_instance(tables: &Goc3Adapter) -> Result<ScopfInstance> {
    let ScopfStaticDataProjection {
        static_data,
        lengths,
        cost_vector_pr,
        cost_vector_cs,
    } = build_static_projection(tables)?;
    let device_class_layout = device_class_blocks(tables)?;
    Ok(ScopfInstance {
        static_data,
        lengths,
        energy_windows: build_energy_windows(tables)?,
        price_blocks: build_price_blocks(&cost_vector_pr, &cost_vector_cs),
        ac_contingency_survivors: build_ac_contingency_survivors(tables)?,
        dc_contingency_flows: build_dc_contingency_flows(tables)?,
        violation_cost: build_violation_cost(tables),
        device_class_layout,
        dt: tables.dt.clone(),
    })
}

fn build_scopf_instance(document: &Goc3Document) -> Result<ScopfInstance> {
    let tables = Goc3Adapter::from_document(document)?;
    project_scopf_instance(&tables)
}

/// Parse source text and build its SCOPF instance.
/// The 0.8 spelling of [`parse_scopf_str`]. The alias goes away at 1.0.0.
#[deprecated(
    since = "0.9.0",
    note = "renamed to parse_scopf_str in 0.9.0; the alias goes away at 1.0.0"
)]
pub fn build_scopf_instance_from_str(text: &str, from: &str) -> Result<ScopfInstance> {
    parse_scopf_str(text, from)
}

pub fn parse_scopf_str(text: &str, from: &str) -> Result<ScopfInstance> {
    if from != "goc3-json" {
        return Err(ScopfError::UnsupportedFormat(from.to_owned()));
    }
    let document = Goc3Document::parse(text)?;
    build_scopf_instance(&document)
}