powerio-tx 0.11.7

Compiler infrastructure for power systems: parse, convert, validate, and lower grid models
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
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
//! Electrical islands and one reference bus per island.
//!
//! A large case can hold several AC islands: asynchronous systems joined only
//! by HVDC, radial pockets behind an open breaker, and stranded equipment. A
//! power flow needs one reference bus in each island it solves, and an island
//! with no source cannot be solved at all. [`BalancedNetwork::calc_islands`]
//! partitions the energized buses; [`BalancedNetwork::assign_island_references`]
//! gives each supplied island one reference and de-energizes the rest, and
//! [`IslandReferencePolicy::PerIsland`] applies the same rule during
//! normalization.

use std::collections::{BTreeSet, HashMap};
use std::fmt::Write as _;

use crate::diagnostics::{Diagnostic, codes};
use crate::network::{BalancedNetwork, BusId, BusType, Generator};

/// How normalization and [`BalancedNetwork::assign_island_references`] treat
/// the reference buses of a network with several islands.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum IslandReferencePolicy {
    /// Keep the reference buses the case states. Normalization designates
    /// one only when none survives anywhere, and
    /// [`BalancedNetwork::assign_island_references`] changes nothing.
    #[default]
    Stated,
    /// One reference per island, on a bus that hosts an in-service
    /// generator. A stated reference that hosts none is demoted first. An
    /// island left with no reference takes the bus of its in-service
    /// generator with the largest `pmax` (the smallest bus id breaking ties);
    /// an island left with several keeps the one with the most generation and
    /// demotes the others; an island with no in-service generator cannot be
    /// solved and is de-energized. Normalization under this policy picks the
    /// same reference buses.
    PerIsland,
}

/// One AC island: energized buses joined by in-service branches, closed
/// switches, and in-service three winding transformers.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Island {
    /// The island's buses in ascending id order.
    pub buses: Vec<BusId>,
    /// Its reference (slack) buses, in ascending id order.
    pub references: Vec<BusId>,
    /// Rows of the in-service generators on its buses.
    pub generators: Vec<usize>,
    /// Rows of the in-service HVDC lines that tie it to another island: one
    /// terminal on its buses, the other on another island's.
    pub hvdc: Vec<usize>,
}

impl Island {
    /// Whether an in-service generator can supply the island.
    #[must_use]
    pub fn is_supplied(&self) -> bool {
        !self.generators.is_empty()
    }

    /// The one reference bus [`IslandReferencePolicy::PerIsland`] gives this
    /// island, without changing the network. Only a stated reference that
    /// hosts an in-service generator counts: the island keeps it when it
    /// states one, takes the bus of its largest `pmax` in-service generator
    /// (the smallest bus id breaking ties) when it states none, and keeps the
    /// one hosting the most in-service `pmax` (the smallest id breaking ties)
    /// when it states several. `None` when no in-service generator supplies
    /// the island, which that policy de-energizes. `generators` is the
    /// network's generator table.
    #[must_use]
    pub fn calc_reference_choice(&self, generators: &[Generator]) -> Option<BusId> {
        match self.supplied_references(generators).as_slice() {
            [bus] => Some(*bus),
            [] => largest_generator_bus(generators, &self.generators),
            references => kept_reference(references, generators, &self.generators),
        }
    }

    /// The stated references that host one of the island's in-service
    /// generators, in ascending id order.
    fn supplied_references(&self, generators: &[Generator]) -> Vec<BusId> {
        self.references
            .iter()
            .copied()
            .filter(|&bus| {
                self.generators
                    .iter()
                    .any(|&row| generators[row].bus == bus)
            })
            .collect()
    }
}

/// The result of [`BalancedNetwork::calc_islands`].
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct IslandPartition {
    /// Every island, largest first; islands of one size come in ascending
    /// order of their smallest bus id.
    pub islands: Vec<Island>,
    /// Buses typed isolated, which belong to no island.
    pub isolated: Vec<BusId>,
    island_of: HashMap<BusId, usize>,
}

impl IslandPartition {
    /// The position in [`islands`](Self::islands) of the island holding
    /// `bus`, or `None` for an isolated or unknown bus.
    #[must_use]
    pub fn island_of(&self, bus: BusId) -> Option<usize> {
        self.island_of.get(&bus).copied()
    }
}

/// The result of [`BalancedNetwork::assign_island_references`].
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct IslandReferenceReport {
    /// The islands after the assignment.
    pub partition: IslandPartition,
    /// Buses made the reference of their island.
    pub designated: Vec<BusId>,
    /// Reference buses demoted, because they host no in-service generator
    /// or because their island kept another, in ascending id order.
    pub demoted: Vec<BusId>,
    /// Buses of the islands that were de-energized, now typed isolated.
    pub de_energized: Vec<BusId>,
    /// One finding per island the assignment changed.
    pub diagnostics: Vec<Diagnostic>,
}

/// The `pmax` order the reference choice uses: a NaN bound never wins, and an
/// unbounded `+Inf` wins as the largest capacity.
fn pmax_key(generator: &Generator) -> f64 {
    if generator.pmax.is_nan() {
        f64::NEG_INFINITY
    } else {
        generator.pmax
    }
}

/// The bus of the in-service generator with the largest `pmax` among `rows`,
/// the smallest bus id breaking ties, so the choice does not depend on row
/// order.
pub(crate) fn largest_generator_bus(generators: &[Generator], rows: &[usize]) -> Option<BusId> {
    rows.iter()
        .copied()
        .max_by(|&a, &b| {
            pmax_key(&generators[a])
                .total_cmp(&pmax_key(&generators[b]))
                .then(generators[b].bus.cmp(&generators[a].bus))
        })
        .map(|row| generators[row].bus)
}

/// Of several reference buses, the one hosting the most in-service `pmax`,
/// the smallest id breaking ties.
pub(crate) fn kept_reference(
    references: &[BusId],
    generators: &[Generator],
    rows: &[usize],
) -> Option<BusId> {
    let capacity = |bus: BusId| -> f64 {
        rows.iter()
            .map(|&row| &generators[row])
            .filter(|generator| generator.bus == bus && !generator.pmax.is_nan())
            .map(|generator| generator.pmax)
            .sum()
    };
    references
        .iter()
        .copied()
        .max_by(|&a, &b| capacity(a).total_cmp(&capacity(b)).then(b.cmp(&a)))
}

/// A short list of bus ids for a message: the first few, then a count.
pub(crate) fn bus_list(buses: &[BusId]) -> String {
    const SHOWN: usize = 5;
    let mut text = buses
        .iter()
        .take(SHOWN)
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join(", ");
    if buses.len() > SHOWN {
        let _ = write!(text, " and {} more", buses.len() - SHOWN);
    }
    text
}

impl BalancedNetwork {
    /// Partition the energized buses into AC islands.
    ///
    /// Two buses share an island when a path of in-service branches, closed
    /// switches, and in-service three winding transformers joins them. HVDC
    /// lines do not join islands: they tie asynchronous systems. Buses typed
    /// isolated belong to no island and are listed apart, and an element that
    /// touches one does not join anything through it. A three winding
    /// transformer joins the buses of its in-service windings
    /// ([`Transformer3W::winding_in_service`](crate::Transformer3W::winding_in_service)),
    /// so one whose tertiary sits on an isolated bus or is out of service
    /// still joins the other two. Carve an
    /// island out with [`subset_buses`](BalancedNetwork::subset_buses), which
    /// keeps such a transformer.
    #[must_use]
    pub fn calc_islands(&self) -> IslandPartition {
        let buses = self.buses();
        let index_of: HashMap<BusId, usize> = buses
            .iter()
            .enumerate()
            .filter(|(_, bus)| bus.kind != BusType::Isolated)
            .map(|(index, bus)| (bus.id, index))
            .collect();
        let mut sets = petgraph::unionfind::UnionFind::new(buses.len());
        let mut join = |a: BusId, b: BusId| {
            if let (Some(&i), Some(&j)) = (index_of.get(&a), index_of.get(&b)) {
                sets.union(i, j);
            }
        };
        for branch in self.branches().iter().filter(|branch| branch.in_service) {
            join(branch.from, branch.to);
        }
        for switch in self.switches().iter().filter(|switch| switch.closed) {
            join(switch.from, switch.to);
        }
        for transformer in self.transformers_3w().iter().filter(|t| t.in_service) {
            let connected: Vec<BusId> = transformer
                .windings
                .iter()
                .zip(transformer.winding_in_service())
                .filter(|(_, connected)| *connected)
                .map(|(winding, _)| winding.bus)
                .collect();
            for (i, &a) in connected.iter().enumerate() {
                for &b in &connected[i + 1..] {
                    join(a, b);
                }
            }
        }
        let labels = sets.into_labeling();

        let mut by_root: HashMap<usize, Island> = HashMap::new();
        let mut isolated = Vec::new();
        for (index, bus) in buses.iter().enumerate() {
            if bus.kind == BusType::Isolated {
                isolated.push(bus.id);
                continue;
            }
            let island = by_root.entry(labels[index]).or_insert_with(|| Island {
                buses: Vec::new(),
                references: Vec::new(),
                generators: Vec::new(),
                hvdc: Vec::new(),
            });
            island.buses.push(bus.id);
            if bus.kind == BusType::Ref {
                island.references.push(bus.id);
            }
        }
        self.attach_generators_and_hvdc(&mut by_root, &labels, &index_of);
        let mut islands: Vec<Island> = by_root.into_values().collect();
        for island in &mut islands {
            island.buses.sort_unstable();
            island.references.sort_unstable();
        }
        islands.sort_by(|a, b| {
            b.buses
                .len()
                .cmp(&a.buses.len())
                .then(a.buses[0].cmp(&b.buses[0]))
        });
        isolated.sort_unstable();
        let island_of = islands
            .iter()
            .enumerate()
            .flat_map(|(position, island)| island.buses.iter().map(move |&bus| (bus, position)))
            .collect();
        IslandPartition {
            islands,
            isolated,
            island_of,
        }
    }

    /// Record on each island, keyed by its union-find root, the rows of its
    /// in-service generators and of the in-service HVDC lines tying it to
    /// another island.
    fn attach_generators_and_hvdc(
        &self,
        by_root: &mut HashMap<usize, Island>,
        labels: &[usize],
        index_of: &HashMap<BusId, usize>,
    ) {
        for (row, generator) in self.generators().iter().enumerate() {
            if let Some(&index) = index_of.get(&generator.bus)
                && generator.in_service
                && let Some(island) = by_root.get_mut(&labels[index])
            {
                island.generators.push(row);
            }
        }
        for (row, line) in self.hvdc().iter().enumerate() {
            if let (Some(&from), Some(&to)) = (index_of.get(&line.from), index_of.get(&line.to))
                && line.in_service
                && labels[from] != labels[to]
            {
                for end in [from, to] {
                    if let Some(island) = by_root.get_mut(&labels[end]) {
                        island.hvdc.push(row);
                    }
                }
            }
        }
    }

    /// Give every island one reference bus under `policy`, returning what
    /// changed.
    ///
    /// Under [`IslandReferencePolicy::PerIsland`], in a supplied island:
    ///
    /// - A stated reference that hosts no in-service generator cannot balance
    ///   the island and is demoted to PQ first. What follows counts only the
    ///   references that remain.
    /// - An island with one reference keeps it.
    /// - An island with none gets the bus of its largest `pmax` in-service
    ///   generator (the smallest bus id breaking ties) as its reference.
    /// - An island with several keeps the one hosting the most in-service
    ///   `pmax` (the smallest id breaking ties) and demotes the others to PV.
    /// - An island with no in-service generator has no source to balance it,
    ///   so it is de-energized: its buses are typed isolated, and the
    ///   in-service loads, shunts, static var compensators, storage, and every
    ///   branch and HVDC line touching them are taken out of service. A three
    ///   winding transformer loses the windings on those buses and goes out
    ///   whole only when fewer than two windings remain.
    ///
    /// Each change records one finding. Normalization under the same policy
    /// picks the same reference buses. [`IslandReferencePolicy::Stated`]
    /// changes nothing and reports the partition.
    #[allow(clippy::too_many_lines)] // one stanza per island outcome
    pub fn assign_island_references(
        &mut self,
        policy: IslandReferencePolicy,
    ) -> IslandReferenceReport {
        let partition = self.calc_islands();
        if policy == IslandReferencePolicy::Stated {
            return IslandReferenceReport {
                partition,
                ..IslandReferenceReport::default()
            };
        }

        let mut designated = Vec::new();
        let mut demoted: Vec<(BusId, BusType)> = Vec::new();
        let mut dead: BTreeSet<BusId> = BTreeSet::new();
        let mut diagnostics = Vec::new();
        for island in &partition.islands {
            if !island.is_supplied() {
                let load: f64 = self
                    .loads()
                    .iter()
                    .filter(|load| load.in_service && island.buses.binary_search(&load.bus).is_ok())
                    .map(|load| load.p)
                    .sum();
                diagnostics.push(self.unsupplied_island_finding(
                    island,
                    &format!(
                        "was de-energized; its {load} MW of in-service load is no longer served"
                    ),
                ));
                dead.extend(island.buses.iter().copied());
                continue;
            }
            let supplied = island.supplied_references(self.generators());
            let unsupplied: Vec<BusId> = island
                .references
                .iter()
                .copied()
                .filter(|bus| !supplied.contains(bus))
                .collect();
            if !unsupplied.is_empty() {
                diagnostics.push(Diagnostic::of(
                    &codes::CANONICALIZE_ISLAND_REFERENCE_DEMOTED,
                    format!(
                        "the island of {} bus(es) ({}) states reference bus(es) {} that host no \
                         in-service generator and cannot balance it; they were demoted to PQ",
                        island.buses.len(),
                        bus_list(&island.buses),
                        bus_list(&unsupplied)
                    ),
                ));
                demoted.extend(unsupplied.iter().map(|&bus| (bus, BusType::Pq)));
            }
            let Some(kept) = island.calc_reference_choice(self.generators()) else {
                continue;
            };
            match supplied.as_slice() {
                [_] => {}
                [] => {
                    diagnostics.push(Diagnostic::of(
                        &codes::CANONICALIZE_ISLAND_REFERENCE_DESIGNATED,
                        format!(
                            "the island of {} bus(es) ({}) states no reference bus that hosts an \
                             in-service generator; bus {kept} hosts its largest pmax in-service \
                             generator and was designated the reference",
                            island.buses.len(),
                            bus_list(&island.buses)
                        ),
                    ));
                    designated.push(kept);
                }
                references => {
                    let others: Vec<BusId> = references
                        .iter()
                        .copied()
                        .filter(|&bus| bus != kept)
                        .collect();
                    diagnostics.push(Diagnostic::of(
                        &codes::CANONICALIZE_ISLAND_REFERENCE_DEMOTED,
                        format!(
                            "the island of {} bus(es) states {} reference buses that host \
                             generation; bus {kept} hosts the most and stays the reference, and \
                             bus(es) {} were demoted to PV",
                            island.buses.len(),
                            references.len(),
                            bus_list(&others)
                        ),
                    ));
                    demoted.extend(others.into_iter().map(|bus| (bus, BusType::Pv)));
                }
            }
        }

        if !designated.is_empty() || !demoted.is_empty() {
            let designated_set: BTreeSet<BusId> = designated.iter().copied().collect();
            let demoted_kind: HashMap<BusId, BusType> = demoted.iter().copied().collect();
            for bus in self.buses_mut() {
                if designated_set.contains(&bus.id) {
                    bus.kind = BusType::Ref;
                } else if let Some(&kind) = demoted_kind.get(&bus.id) {
                    bus.kind = kind;
                }
            }
        }
        if !dead.is_empty() {
            self.de_energize_buses(&dead);
        }

        let mut demoted: Vec<BusId> = demoted.into_iter().map(|(bus, _)| bus).collect();
        demoted.sort_unstable();
        IslandReferenceReport {
            partition: self.calc_islands(),
            designated,
            demoted,
            de_energized: dead.into_iter().collect(),
            diagnostics,
        }
    }

    /// The finding for an island no in-service generator supplies, whose
    /// `outcome` completes the sentence. An island an HVDC line still feeds
    /// gets its own code, naming the lines and the power they schedule into
    /// it, since supply counts generators only and that infeed goes too.
    pub(crate) fn unsupplied_island_finding(&self, island: &Island, outcome: &str) -> Diagnostic {
        let size = island.buses.len();
        let buses = bus_list(&island.buses);
        if island.hvdc.is_empty() {
            return Diagnostic::of(
                &codes::CANONICALIZE_ISLAND_DE_ENERGIZED,
                format!(
                    "the island of {size} bus(es) ({buses}) has no in-service generator and {outcome}"
                ),
            );
        }
        let inside = |bus: BusId| island.buses.binary_search(&bus).is_ok();
        let mut infeed = 0.0;
        let mut lines = Vec::with_capacity(island.hvdc.len());
        for &row in &island.hvdc {
            let line = &self.hvdc()[row];
            // MATPOWER's dcline convention: `pf` leaves the from bus and `pt`
            // arrives at the to bus.
            infeed += if inside(line.to) { line.pt } else { -line.pf };
            lines.push(format!("{}-{}", line.from, line.to));
        }
        Diagnostic::of(
            &codes::CANONICALIZE_ISLAND_HVDC_FED_DE_ENERGIZED,
            format!(
                "the island of {size} bus(es) ({buses}) has no in-service generator and {outcome}; \
                 {} in-service HVDC line(s) ({}) schedule {infeed} MW into it, and only \
                 generators count as supply, so they were taken out of service with it and the \
                 other island(s) no longer exchange that power. To keep the island, model the \
                 infeed as a generator at its converter bus",
                lines.len(),
                lines.join(", ")
            ),
        )
    }

    /// Keep `island` energized and de-energize every other bus not already
    /// typed isolated, with [`de_energize_buses`](Self::de_energize_buses),
    /// returning the buses de-energized in ascending order.
    ///
    /// This is the in-place counterpart of
    /// [`subset_buses`](BalancedNetwork::subset_buses): every table keeps all
    /// its rows, so a source row index still names the same element, and the
    /// elements outside `island` stay in the network out of service. Pass the
    /// buses of one [`Island`] of [`calc_islands`](Self::calc_islands), or
    /// the union of several.
    pub fn keep_island(&mut self, island: &BTreeSet<BusId>) -> Vec<BusId> {
        let others: BTreeSet<BusId> = self
            .buses()
            .iter()
            .filter(|bus| bus.kind != BusType::Isolated && !island.contains(&bus.id))
            .map(|bus| bus.id)
            .collect();
        if !others.is_empty() {
            self.de_energize_buses(&others);
        }
        others.into_iter().collect()
    }

    /// De-energize `buses`, as [`assign_island_references`] does to an island
    /// with no source.
    ///
    /// Each bus is typed isolated, and the loads, shunts, static var
    /// compensators, storage, and generators at them, and every branch and
    /// HVDC line touching them, are taken out of service. A three winding
    /// transformer loses the windings on those buses and goes out whole only
    /// when fewer than two windings remain. Switches keep their state: a
    /// closed switch joins nothing through an isolated bus. No row is added
    /// or removed, so data keyed by source rows stays valid. Ids the network
    /// does not declare are ignored, and only a table with an element to
    /// change is copied.
    ///
    /// [`assign_island_references`]: BalancedNetwork::assign_island_references
    pub fn de_energize_buses(&mut self, buses: &BTreeSet<BusId>) {
        let at = |bus: BusId| buses.contains(&bus);
        if self
            .buses()
            .iter()
            .any(|b| b.kind != BusType::Isolated && at(b.id))
        {
            for bus in self.buses_mut().iter_mut().filter(|b| at(b.id)) {
                bus.kind = BusType::Isolated;
            }
        }
        if self.generators().iter().any(|g| g.in_service && at(g.bus)) {
            for generator in self.generators_mut().iter_mut().filter(|g| at(g.bus)) {
                generator.in_service = false;
            }
        }
        if self.loads().iter().any(|l| l.in_service && at(l.bus)) {
            for load in self.loads_mut().iter_mut().filter(|l| at(l.bus)) {
                load.in_service = false;
            }
        }
        if self.shunts().iter().any(|s| s.in_service && at(s.bus)) {
            for shunt in self.shunts_mut().iter_mut().filter(|s| at(s.bus)) {
                shunt.in_service = false;
            }
        }
        if self
            .static_var_compensators()
            .iter()
            .any(|s| s.in_service && at(s.bus))
        {
            for svc in self
                .static_var_compensators_mut()
                .iter_mut()
                .filter(|s| at(s.bus))
            {
                svc.in_service = false;
            }
        }
        if self.storage().iter().any(|s| s.in_service && at(s.bus)) {
            for storage in self.storage_mut().iter_mut().filter(|s| at(s.bus)) {
                storage.in_service = false;
            }
        }
        let touches = |from: BusId, to: BusId| at(from) || at(to);
        if self
            .branches()
            .iter()
            .any(|b| b.in_service && touches(b.from, b.to))
        {
            for branch in self
                .branches_mut()
                .iter_mut()
                .filter(|b| touches(b.from, b.to))
            {
                branch.in_service = false;
            }
        }
        if self
            .hvdc()
            .iter()
            .any(|d| d.in_service && touches(d.from, d.to))
        {
            for line in self.hvdc_mut().iter_mut().filter(|d| touches(d.from, d.to)) {
                line.in_service = false;
            }
        }
        // A winding on a de-energized bus goes out; a transformer left with
        // fewer than two windings couples nothing and goes out whole.
        let live_after = |t: &crate::network::Transformer3W| -> [bool; 3] {
            let mut live = t.winding_in_service();
            for (state, winding) in live.iter_mut().zip(&t.windings) {
                *state &= !at(winding.bus);
            }
            live
        };
        if self
            .transformers_3w()
            .iter()
            .any(|t| t.in_service && live_after(t) != t.winding_in_service())
        {
            for transformer in self.transformers_3w_mut().iter_mut() {
                let live = live_after(transformer);
                if live == transformer.winding_in_service() {
                    continue;
                }
                if live.iter().filter(|&&on| on).count() < 2 {
                    transformer.in_service = false;
                } else {
                    transformer.set_winding_in_service(live);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::network::{Branch, Bus, Hvdc, Impedance, Load, Switch, Transformer3W, Winding};
    use crate::{ClosedSwitchPolicy, IslandReferencePolicy, NormalizeOptions, NormalizeSettings};

    fn generator(bus: usize, pmax: f64) -> Generator {
        let mut generator = Generator::new(BusId(bus));
        generator.pmax = pmax;
        generator.pg = pmax / 2.0;
        generator
    }

    /// Island A {1, 2, 9} holds the reference bus 1; island B {3, 4, 5}
    /// holds generation and no reference, bus 5 joined by a closed switch;
    /// island C {6, 7} holds only a load and an HVDC end; bus 8 is isolated.
    fn three_islands() -> BalancedNetwork {
        let mut buses: Vec<Bus> = (1..=9)
            .map(|id| Bus::new(BusId(id), BusType::Pq, 230.0))
            .collect();
        buses[0].kind = BusType::Ref;
        buses[7].kind = BusType::Isolated;
        let line = |from, to| Branch::new(BusId(from), BusId(to), 0.01, 0.1);
        let mut net = BalancedNetwork::in_memory(
            "islands",
            100.0,
            buses,
            vec![line(1, 2), line(2, 9), line(3, 4), line(6, 7), line(7, 8)],
        );
        net.switches_mut()
            .push(Switch::new(BusId(4), BusId(5), true));
        net.generators_mut()
            .extend([generator(1, 200.0), generator(4, 50.0), generator(5, 80.0)]);
        net.loads_mut().extend([
            Load::new(BusId(2), 60.0, 0.0),
            Load::new(BusId(3), 40.0, 0.0),
            Load::new(BusId(7), 25.0, 0.0),
        ]);
        // An HVDC line from island A feeds island C, which has no generator.
        let mut tie = Hvdc::new(BusId(1), BusId(6));
        tie.pf = 30.0;
        tie.pt = 29.0;
        // One inside island A ties nothing.
        let inside = Hvdc::new(BusId(1), BusId(2));
        net.hvdc_mut().extend([tie, inside]);
        net
    }

    fn kind(net: &BalancedNetwork, id: usize) -> BusType {
        net.buses().iter().find(|b| b.id == BusId(id)).unwrap().kind
    }

    fn codes(diagnostics: &[Diagnostic]) -> Vec<&str> {
        diagnostics.iter().map(Diagnostic::code).collect()
    }

    #[test]
    fn islands_follow_branches_closed_switches_and_not_hvdc() {
        let net = three_islands();
        let partition = net.calc_islands();
        let buses: Vec<Vec<usize>> = partition
            .islands
            .iter()
            .map(|island| island.buses.iter().map(|b| b.0).collect())
            .collect();
        assert_eq!(buses, [vec![1, 2, 9], vec![3, 4, 5], vec![6, 7]]);
        assert_eq!(partition.isolated, [BusId(8)]);
        assert_eq!(partition.islands[0].references, [BusId(1)]);
        assert_eq!(partition.islands[1].generators, [1, 2]);
        assert!(!partition.islands[2].is_supplied());
        assert_eq!(partition.island_of(BusId(5)), Some(1));
        assert_eq!(partition.island_of(BusId(8)), None);
        // The HVDC tie belongs to both islands it joins; the line inside
        // island A ties nothing.
        assert_eq!(partition.islands[0].hvdc, [0]);
        assert_eq!(partition.islands[1].hvdc, [] as [usize; 0]);
        assert_eq!(partition.islands[2].hvdc, [0]);
    }

    #[test]
    fn a_three_winding_transformer_joins_its_windings_while_in_service() {
        let buses = (1..=3)
            .map(|id| Bus::new(BusId(id), BusType::Pq, 230.0))
            .collect();
        let mut net = BalancedNetwork::in_memory("t3w", 100.0, buses, Vec::new());
        net.transformers_3w_mut().push(Transformer3W::new(
            [1, 2, 3].map(|bus| Winding::new(BusId(bus))),
            [Impedance::new(0.0, 0.1, 100.0); 3],
        ));
        assert_eq!(net.calc_islands().islands.len(), 1);
        net.transformers_3w_mut()[0].in_service = false;
        assert_eq!(net.calc_islands().islands.len(), 3);
    }

    #[test]
    fn a_winding_on_an_isolated_bus_leaves_the_other_two_joined() {
        // Normalization takes the winding on the isolated bus out of service
        // and keeps the transformer, so the two other windings stay joined.
        let mut buses: Vec<Bus> = (1..=3)
            .map(|id| Bus::new(BusId(id), BusType::Pq, 230.0))
            .collect();
        buses[0].kind = BusType::Ref;
        buses[1].kind = BusType::Isolated;
        let mut net = BalancedNetwork::in_memory("t3w", 100.0, buses, Vec::new());
        net.transformers_3w_mut().push(Transformer3W::new(
            [1, 2, 3].map(|bus| Winding::new(BusId(bus))),
            [Impedance::new(0.0, 0.1, 100.0); 3],
        ));
        net.generators_mut().push(generator(1, 100.0));
        net.loads_mut().push(Load::new(BusId(3), 10.0, 0.0));
        let partition = net.calc_islands();
        assert_eq!(partition.islands.len(), 1);
        assert_eq!(partition.islands[0].buses, [BusId(1), BusId(3)]);

        let settings =
            NormalizeSettings::default().with_island_references(IslandReferencePolicy::PerIsland);
        let (normalized, _) = net.to_normalized_with(&settings).unwrap();
        assert_eq!(normalized.network.buses().len(), 2);
        let transformer = &normalized.network.transformers_3w()[0];
        assert_eq!(transformer.winding_in_service(), [true, false, true]);
        assert!(transformer.in_service);
        assert_eq!(normalized.network.calc_islands().islands.len(), 1);
        let found = codes(&normalized.diagnostics);
        assert!(found.contains(&"CANONICALIZE.NORMALIZE.WINDING_TAKEN_OUT"));
        assert!(!found.contains(&"CANONICALIZE.ISLAND.DE_ENERGIZED"));
        crate::IndexedNetwork::new(&normalized.network)
            .check_reference_coverage()
            .unwrap();
        normalized.network.validate().unwrap();
    }

    #[test]
    fn de_energizing_takes_out_the_windings_on_the_dead_island() {
        let mut net = three_islands();
        // A transformer inside the dead island {6, 7}, plus one joining the
        // live island B to a dead bus only through a winding already out.
        net.transformers_3w_mut().push(Transformer3W::new(
            [6, 7, 6].map(|bus| Winding::new(BusId(bus))),
            [Impedance::new(0.0, 0.1, 100.0); 3],
        ));
        let mut partial = Transformer3W::new(
            [3, 4, 7].map(|bus| Winding::new(BusId(bus))),
            [Impedance::new(0.0, 0.1, 100.0); 3],
        );
        partial.set_winding_in_service([true, true, false]);
        net.transformers_3w_mut().push(partial);
        net.assign_island_references(IslandReferencePolicy::PerIsland);
        assert!(
            !net.transformers_3w()[0].in_service,
            "nothing left to couple"
        );
        let partial = &net.transformers_3w()[1];
        assert!(partial.in_service, "its live windings stay");
        assert_eq!(partial.winding_in_service(), [true, true, false]);
        net.validate().unwrap();
    }

    #[test]
    fn each_island_gets_one_reference_and_an_unsupplied_one_is_de_energized() {
        let mut net = three_islands();
        let unchanged = net.assign_island_references(IslandReferencePolicy::Stated);
        assert_eq!(unchanged.diagnostics.as_slice(), []);
        assert_eq!(kind(&net, 5), BusType::Pq);

        let report = net.assign_island_references(IslandReferencePolicy::PerIsland);
        // Island A keeps bus 1; island B takes bus 5, its largest generator.
        assert_eq!(report.designated, [BusId(5)]);
        assert_eq!(kind(&net, 1), BusType::Ref);
        assert_eq!(kind(&net, 5), BusType::Ref);
        // Island C has no generator: its buses are isolated and everything
        // on or touching them is out of service.
        assert_eq!(report.de_energized, [BusId(6), BusId(7)]);
        assert_eq!(kind(&net, 6), BusType::Isolated);
        assert!(!net.loads()[2].in_service);
        assert!(!net.branches()[3].in_service);
        assert!(!net.branches()[4].in_service, "the branch onto bus 8");
        assert!(!net.hvdc()[0].in_service);
        assert!(net.hvdc()[1].in_service, "the line inside island A");
        assert!(net.branches()[0].in_service && net.loads()[0].in_service);
        // Island C was fed over HVDC, so its finding has its own code and
        // names the line and the power it scheduled into the island.
        assert_eq!(
            codes(&report.diagnostics),
            [
                "CANONICALIZE.ISLAND.REFERENCE_DESIGNATED",
                "CANONICALIZE.ISLAND.HVDC_FED_DE_ENERGIZED"
            ]
        );
        let message = report.diagnostics[1].message();
        assert!(message.contains("25 MW of in-service load"), "{message}");
        assert!(
            message.contains("(1-6) schedule 29 MW into it"),
            "{message}"
        );
        assert_eq!(report.partition.islands.len(), 2);
        assert!(
            report
                .partition
                .islands
                .iter()
                .all(|island| island.references.len() == 1)
        );
        net.validate().unwrap();

        // A second pass has nothing left to do.
        let again = net.assign_island_references(IslandReferencePolicy::PerIsland);
        assert_eq!(again.diagnostics.as_slice(), []);
    }

    #[test]
    fn of_two_references_in_one_island_the_larger_source_stays() {
        let mut net = three_references();
        let report = net.assign_island_references(IslandReferencePolicy::PerIsland);
        assert_eq!(report.demoted, [BusId(1), BusId(3)]);
        assert_eq!(kind(&net, 2), BusType::Ref);
        assert_eq!(kind(&net, 1), BusType::Pv, "it hosts a generator");
        assert_eq!(kind(&net, 3), BusType::Pq);
        // Bus 3 hosts no generator and goes first; then bus 1 yields to bus 2.
        assert_eq!(
            codes(&report.diagnostics),
            [
                "CANONICALIZE.ISLAND.REFERENCE_DEMOTED",
                "CANONICALIZE.ISLAND.REFERENCE_DEMOTED"
            ]
        );
    }

    /// Buses 1-2-3-4 in a line, the reference on bus 1 with no generator,
    /// and generators of 50 MW on bus 3 and 120 MW on bus 4.
    fn lone_generator_less_reference() -> BalancedNetwork {
        let mut buses: Vec<Bus> = (1..=4)
            .map(|id| Bus::new(BusId(id), BusType::Pq, 230.0))
            .collect();
        buses[0].kind = BusType::Ref;
        let line = |from, to| Branch::new(BusId(from), BusId(to), 0.01, 0.1);
        let mut net = BalancedNetwork::in_memory(
            "generator-less-reference",
            100.0,
            buses,
            vec![line(1, 2), line(2, 3), line(3, 4)],
        );
        net.generators_mut()
            .extend([generator(3, 50.0), generator(4, 120.0)]);
        net.loads_mut().push(Load::new(BusId(2), 60.0, 0.0));
        net
    }

    /// Buses 1, 2, and 3 all stated references, generators on buses 1 and 2.
    fn three_references() -> BalancedNetwork {
        let buses = (1..=3)
            .map(|id| Bus::new(BusId(id), BusType::Ref, 230.0))
            .collect();
        let line = |from, to| Branch::new(BusId(from), BusId(to), 0.01, 0.1);
        let mut net =
            BalancedNetwork::in_memory("refs", 100.0, buses, vec![line(1, 2), line(2, 3)]);
        net.generators_mut()
            .extend([generator(1, 100.0), generator(2, 300.0)]);
        net
    }

    #[test]
    fn a_lone_generator_less_reference_yields_to_the_largest_generator() {
        let mut net = lone_generator_less_reference();
        let island = &net.calc_islands().islands[0];
        assert_eq!(island.references, [BusId(1)]);
        assert_eq!(
            island.calc_reference_choice(net.generators()),
            Some(BusId(4))
        );

        let report = net.assign_island_references(IslandReferencePolicy::PerIsland);
        assert_eq!(report.demoted, [BusId(1)]);
        assert_eq!(report.designated, [BusId(4)]);
        assert_eq!(report.de_energized, []);
        assert_eq!(kind(&net, 1), BusType::Pq);
        assert_eq!(kind(&net, 4), BusType::Ref);
        assert_eq!(
            kind(&net, 3),
            BusType::Pq,
            "the smaller generator stays put"
        );
        assert_eq!(
            codes(&report.diagnostics),
            [
                "CANONICALIZE.ISLAND.REFERENCE_DEMOTED",
                "CANONICALIZE.ISLAND.REFERENCE_DESIGNATED"
            ]
        );
        assert_eq!(report.partition.islands[0].references, [BusId(4)]);
        net.validate().unwrap();
        let again = net.assign_island_references(IslandReferencePolicy::PerIsland);
        assert_eq!(again.diagnostics.as_slice(), []);

        // Stated keeps the source's designation.
        let mut stated = lone_generator_less_reference();
        let report = stated.assign_island_references(IslandReferencePolicy::Stated);
        assert_eq!(report.diagnostics.as_slice(), []);
        assert_eq!(kind(&stated, 1), BusType::Ref);
    }

    #[test]
    fn equal_generators_go_to_the_smallest_bus_id() {
        let mut net = lone_generator_less_reference();
        // A second 120 MW generator, on a smaller bus but a later row.
        net.generators_mut().push(generator(2, 120.0));
        let report = net.assign_island_references(IslandReferencePolicy::PerIsland);
        assert_eq!(report.designated, [BusId(2)]);
    }

    /// The raw assignment and normalization under the per island policy
    /// pick the same reference buses. Closed switches are kept so that bus
    /// ids survive normalization.
    #[test]
    fn raw_and_normalized_per_island_references_agree() {
        let references = |network: &BalancedNetwork| -> Vec<BusId> {
            let mut ids: Vec<BusId> = network
                .buses()
                .iter()
                .filter(|bus| bus.kind == BusType::Ref)
                .map(|bus| bus.id)
                .collect();
            ids.sort_unstable();
            ids
        };
        let settings = NormalizeSettings::default()
            .with_island_references(IslandReferencePolicy::PerIsland)
            .with_closed_switches(ClosedSwitchPolicy::Keep);
        let fixtures = [
            ("three islands", three_islands(), vec![1, 5]),
            (
                "dead tertiary",
                line_with_a_tertiary(BusType::Isolated),
                vec![1],
            ),
            ("live tertiary", line_with_a_tertiary(BusType::Pq), vec![1]),
            (
                "generator-less reference",
                lone_generator_less_reference(),
                vec![4],
            ),
            ("three references", three_references(), vec![2]),
        ];
        for (name, net, expected) in fixtures {
            let expected: Vec<BusId> = expected.into_iter().map(BusId).collect();
            let (normalized, _) = net.to_normalized_with(&settings).unwrap();
            assert_eq!(
                references(&normalized.network),
                expected,
                "{name}: normalized"
            );
            let mut raw = net.clone();
            raw.assign_island_references(IslandReferencePolicy::PerIsland);
            assert_eq!(references(&raw), expected, "{name}: raw");
            let choices: Vec<BusId> = net
                .calc_islands()
                .islands
                .iter()
                .filter_map(|island| island.calc_reference_choice(net.generators()))
                .collect();
            let mut choices = choices;
            choices.sort_unstable();
            assert_eq!(choices, expected, "{name}: calc_reference_choice");
        }
    }

    #[test]
    fn normalization_per_island_references_every_island_and_drops_the_unsupplied() {
        let net = three_islands();
        let stated = net
            .to_normalized_with_options(&NormalizeOptions::default())
            .unwrap();
        assert_eq!(
            stated.network.buses().len(),
            7,
            "the typed isolated bus goes, and the closed switch merges bus 5 into bus 4"
        );
        let references: Vec<BusId> = stated
            .network
            .buses()
            .iter()
            .filter(|bus| bus.kind == BusType::Ref)
            .map(|bus| bus.id)
            .collect();
        assert_eq!(references, [BusId(1)]);
        assert!(
            codes(&stated.diagnostics).contains(&"CANONICALIZE.NORMALIZE.GENERATOR_BUS_RETYPED")
        );

        let settings =
            NormalizeSettings::default().with_island_references(IslandReferencePolicy::PerIsland);
        let references = |network: &BalancedNetwork| -> Vec<BusId> {
            network
                .buses()
                .iter()
                .filter(|bus| bus.kind == BusType::Ref)
                .map(|bus| bus.id)
                .collect()
        };
        // Kept as data, the closed switch still joins island B, whose largest
        // generator, on bus 5, becomes its reference.
        let (kept, _) = net
            .to_normalized_with(&settings.with_closed_switches(ClosedSwitchPolicy::Keep))
            .unwrap();
        let ids: Vec<usize> = kept.network.buses().iter().map(|b| b.id.0).collect();
        assert_eq!(ids, [1, 2, 3, 4, 5, 9]);
        assert_eq!(references(&kept.network), [BusId(1), BusId(5)]);
        // Merged by default, both of island B's generators sit on bus 4.
        let (per_island, _) = net.to_normalized_with(&settings).unwrap();
        let ids: Vec<usize> = per_island.network.buses().iter().map(|b| b.id.0).collect();
        assert_eq!(ids, [1, 2, 3, 4, 9]);
        assert_eq!(references(&per_island.network), [BusId(1), BusId(4)]);
        assert_eq!(
            per_island.network.hvdc().len(),
            1,
            "only the line inside island A"
        );
        let found = codes(&per_island.diagnostics);
        assert!(found.contains(&"CANONICALIZE.ISLAND.HVDC_FED_DE_ENERGIZED"));
        assert!(!found.contains(&"CANONICALIZE.ISLAND.DE_ENERGIZED"));
        assert!(found.contains(&"CANONICALIZE.ISLAND.REFERENCE_DESIGNATED"));
        crate::IndexedNetwork::new(&per_island.network)
            .check_reference_coverage()
            .unwrap();
    }

    /// Buses 1-2-3 in a line, the reference on bus 1, and a three winding
    /// transformer on buses 2, 4, and 5.
    fn line_with_a_tertiary(tertiary: BusType) -> BalancedNetwork {
        let mut buses: Vec<Bus> = (1..=5)
            .map(|id| Bus::new(BusId(id), BusType::Pq, 230.0))
            .collect();
        buses[0].kind = BusType::Ref;
        buses[4].kind = tertiary;
        let line = |from, to| Branch::new(BusId(from), BusId(to), 0.01, 0.1);
        let mut net =
            BalancedNetwork::in_memory("tertiary", 100.0, buses, vec![line(1, 2), line(2, 3)]);
        net.transformers_3w_mut().push(Transformer3W::new(
            [2, 4, 5].map(|bus| Winding::new(BusId(bus))),
            [Impedance::new(0.0, 0.1, 100.0); 3],
        ));
        net.generators_mut().push(generator(1, 100.0));
        net
    }

    #[test]
    fn an_island_joined_through_a_dead_tertiary_carves_out_whole() {
        let net = line_with_a_tertiary(BusType::Isolated);
        let partition = net.calc_islands();
        assert_eq!(partition.islands.len(), 1);
        assert_eq!(
            partition.islands[0].buses,
            [BusId(1), BusId(2), BusId(3), BusId(4)]
        );
        assert_eq!(partition.isolated, [BusId(5)]);

        let island: BTreeSet<BusId> = partition.islands[0].buses.iter().copied().collect();
        let mut sub = net.subset_buses(&island).network;
        assert_eq!(sub.transformers_3w().len(), 1, "the transformer is kept");
        let stub = sub.buses().iter().find(|b| b.id == BusId(5)).unwrap();
        assert_eq!(stub.kind, BusType::Isolated);
        assert_eq!(
            stub.extras.get("tie_bus"),
            Some(&serde_json::Value::Bool(true))
        );
        sub.validate().unwrap();
        let again = sub.calc_islands();
        assert_eq!(again.islands.len(), 1);
        assert_eq!(again.islands[0].buses, partition.islands[0].buses);
        let report = sub.assign_island_references(IslandReferencePolicy::PerIsland);
        assert_eq!(report.diagnostics.as_slice(), []);
    }

    #[test]
    fn a_winding_stated_out_of_service_joins_nothing() {
        let mut net = line_with_a_tertiary(BusType::Pq);
        net.transformers_3w_mut()[0].extras.insert(
            "winding_in_service".into(),
            serde_json::json!([true, true, false]),
        );
        let partition = net.calc_islands();
        assert_eq!(partition.islands.len(), 2);
        assert_eq!(partition.islands[1].buses, [BusId(5)]);

        let island: BTreeSet<BusId> = partition.islands[0].buses.iter().copied().collect();
        let sub = net.subset_buses(&island).network;
        assert_eq!(sub.transformers_3w().len(), 1);
        assert_eq!(sub.calc_islands().islands.len(), 1);
        sub.validate().unwrap();
    }

    #[test]
    fn one_island_carves_out_with_its_elements() {
        let net = three_islands();
        let partition = net.calc_islands();
        let island: BTreeSet<BusId> = partition.islands[1].buses.iter().copied().collect();
        let cut = net.subset_buses(&island);
        assert_eq!(cut.branch_rows, [None, None, Some(0), None, None]);
        assert_eq!(cut.switch_rows, [Some(0)]);
        assert_eq!(cut.generator_rows, [None, Some(0), Some(1)]);
        assert_eq!(cut.load_rows, [None, Some(0), None]);
        assert_eq!(cut.hvdc_rows, [None, None]);
        let sub = cut.network;
        assert_eq!(sub.buses().len(), 3);
        assert_eq!(sub.branches().len(), 1);
        assert_eq!(sub.switches().len(), 1);
        assert_eq!(sub.generators().len(), 2);
        assert_eq!(sub.loads().len(), 1);
        assert_eq!(sub.hvdc().as_slice(), []);
        sub.validate().unwrap();
    }

    /// Every source row of every table maps to its row in the cut, in order,
    /// or to `None` exactly when the cut leaves it out.
    #[test]
    fn island_cut_row_maps_agree_with_the_cut_network() {
        let fixtures = [
            three_islands(),
            line_with_a_tertiary(BusType::Isolated),
            line_with_a_tertiary(BusType::Pq),
        ];
        for net in fixtures {
            for island in net.calc_islands().islands {
                let island: BTreeSet<BusId> = island.buses.iter().copied().collect();
                let cut = net.subset_buses(&island);
                let kept: BTreeSet<BusId> = cut.network.buses().iter().map(|b| b.id).collect();
                assert!(island.is_subset(&kept));
                macro_rules! check {
                    ($map:ident, $table:ident, $kept:expr) => {{
                        let source = net.$table();
                        let result = cut.network.$table();
                        assert_eq!(cut.$map.len(), source.len(), stringify!($map));
                        let rows: Vec<usize> = cut.$map.iter().flatten().copied().collect();
                        assert_eq!(rows, (0..result.len()).collect::<Vec<_>>());
                        for (row, target) in cut.$map.iter().enumerate() {
                            let element = &source[row];
                            #[allow(clippy::redundant_closure_call)]
                            let expected = ($kept)(element);
                            assert_eq!(
                                target.is_some(),
                                expected,
                                "{} row {row}",
                                stringify!($map)
                            );
                            if let Some(target) = target {
                                assert_eq!(&result[*target], element);
                            }
                        }
                    }};
                }
                for (row, target) in cut.bus_rows.iter().enumerate() {
                    let id = net.buses()[row].id;
                    assert_eq!(target.is_some(), kept.contains(&id));
                    if let Some(target) = target {
                        assert_eq!(cut.network.buses()[*target].id, id);
                    }
                }
                let at = |bus: &BusId| island.contains(bus);
                let spans = |from: &BusId, to: &BusId| kept.contains(from) && kept.contains(to);
                check!(load_rows, loads, |e: &Load| at(&e.bus));
                check!(generator_rows, generators, |e: &Generator| at(&e.bus));
                check!(branch_rows, branches, |e: &Branch| spans(&e.from, &e.to));
                check!(switch_rows, switches, |e: &Switch| spans(&e.from, &e.to));
                check!(hvdc_rows, hvdc, |e: &Hvdc| spans(&e.from, &e.to));
                check!(transformer_3w_rows, transformers_3w, |e: &Transformer3W| e
                    .windings
                    .iter()
                    .all(|w| kept.contains(&w.bus))
                    && e.windings.iter().any(|w| at(&w.bus)));
                assert_eq!(cut.shunt_rows.len(), net.shunts().len());
                assert_eq!(cut.storage_rows.len(), net.storage().len());
                assert_eq!(
                    cut.static_var_compensator_rows.len(),
                    net.static_var_compensators().len()
                );
            }
        }
    }

    #[test]
    fn de_energizing_buses_keeps_every_row() {
        let mut net = three_islands();
        let rows = |net: &BalancedNetwork| {
            [
                net.buses().len(),
                net.branches().len(),
                net.switches().len(),
                net.generators().len(),
                net.loads().len(),
                net.hvdc().len(),
            ]
        };
        let before = rows(&net);
        // Island B {3, 4, 5} holds generation; de-energizing takes it out too.
        net.de_energize_buses(&[BusId(3), BusId(4), BusId(5), BusId(99)].into());
        assert_eq!(rows(&net), before, "no row is added or removed");
        for bus in [3, 4, 5] {
            assert_eq!(kind(&net, bus), BusType::Isolated);
        }
        assert_eq!(kind(&net, 2), BusType::Pq);
        assert!(!net.branches()[2].in_service, "the line 3-4");
        assert!(net.switches()[0].closed, "switches keep their state");
        assert!(net.generators()[0].in_service);
        assert!(!net.generators()[1].in_service && !net.generators()[2].in_service);
        assert!(!net.loads()[1].in_service && net.loads()[0].in_service);
        let partition = net.calc_islands();
        assert_eq!(partition.island_of(BusId(4)), None);
        assert_eq!(partition.islands.len(), 2);
        net.validate().unwrap();
    }

    #[test]
    fn keeping_one_island_de_energizes_the_others_in_place() {
        let mut net = three_islands();
        let partition = net.calc_islands();
        let island: BTreeSet<BusId> = partition.islands[1].buses.iter().copied().collect();
        let cut = net.subset_buses(&island);
        let dead = net.keep_island(&island);
        // Bus 8 was already isolated; the buses of islands A and C go.
        assert_eq!(dead, [1, 2, 6, 7, 9].map(BusId));
        let after = net.calc_islands();
        assert_eq!(after.islands.len(), 1);
        assert_eq!(after.islands[0].buses, partition.islands[1].buses);
        // The in-service elements are exactly the ones the cut keeps, at
        // their source rows.
        for (row, target) in cut.branch_rows.iter().enumerate() {
            assert_eq!(net.branches()[row].in_service, target.is_some());
        }
        for (row, target) in cut.generator_rows.iter().enumerate() {
            assert_eq!(net.generators()[row].in_service, target.is_some());
        }
        for (row, target) in cut.load_rows.iter().enumerate() {
            assert_eq!(net.loads()[row].in_service, target.is_some());
        }
        for (row, target) in cut.hvdc_rows.iter().enumerate() {
            assert_eq!(net.hvdc()[row].in_service, target.is_some());
        }
        assert_eq!(
            net.keep_island(&island),
            [],
            "a second call changes nothing"
        );
        let report = net.assign_island_references(IslandReferencePolicy::PerIsland);
        assert_eq!(report.de_energized, []);
        net.validate().unwrap();
    }
}