powerio 0.11.7

Compiler infrastructure for power systems: parse, validate, transform, and emit 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
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
//! The module emission dispatcher. One dynamic module emits a named target
//! format; the concrete value routes to the family emitter that owns it.
//!
//! Same format emission keeps the family writers' echo tier: an unchanged
//! parsed module emits its retained source bytes exactly. Cross format
//! emission serializes the typed value and reports what the target cannot
//! represent through the returned diagnostics.

use powerio_core::{Destination, Diagnostic, EmitResult, Error, PioModule};
use powerio_prob::{
    BalancedOperatingPointFlag, BalancedOperatingPointQuantity, MulticonductorOperatingPointFlag,
    MulticonductorOperatingPointQuantity, OperatingPoint,
};
use powerio_tx::{BalancedNetwork, BranchSolution};

use crate::PioValue;

pub mod codes {
    powerio_core::diagnostic_codes! {
        REQUEST_EMIT_UNKNOWN_FORMAT = "REQUEST.EMIT.UNKNOWN_FORMAT", Error,
            "the requested target format name is not recognized", category = Request;
        REQUEST_EMIT_UNSUPPORTED_VALUE_TYPE = "REQUEST.EMIT.UNSUPPORTED_VALUE_TYPE", Error,
            "the module's value type cannot be emitted in the requested format", category = Request;
        EMIT_CALCULATION_DATA_OMITTED = "EMIT.CALCULATION.DATA_OMITTED", Warning,
            "the target grid exchange format does not represent the complete calculation definition", category = Output;
        EMIT_SOLUTION_DATA_OMITTED = "EMIT.SOLUTION.DATA_OMITTED", Warning,
            "the target grid exchange format does not represent every solution result", category = Output;
        EMIT_RELAXATION_DATA_OMITTED = "EMIT.RELAXATION.DATA_OMITTED", Warning,
            "the target grid exchange format does not represent an SOCWR relaxation result", category = Output;
        EMIT_OPERATING_POINT_DATA_OMITTED = "EMIT.OPERATING_POINT.DATA_OMITTED", Warning,
            "the target grid exchange format does not represent every operating point quantity", category = Output;
    }
}

/// True when `format` names the PyPSA CSV folder target.
fn is_pypsa_dir(format: &str) -> bool {
    crate::resolve_format(format).is_some_and(|info| info.token == "pypsa-csv")
}

fn is_cgmes_dir(format: &str) -> bool {
    crate::resolve_format(format).is_some_and(|info| info.token == "cgmes")
}

fn is_goc3(format: &str) -> bool {
    crate::resolve_format(format).is_some_and(|info| info.token == "goc3-json")
}

/// True when `format` names the GridFM directory target.
fn is_gridfm_dir(format: &str) -> bool {
    crate::resolve_format(format).is_some_and(|info| info.token == "gridfm")
}

/// True when two names identify the same supported directory format. The
/// retained source carries the format selected by the parser; this comparison
/// admits the public aliases at emission without treating an arbitrary
/// declared directory token as an echoable format.
fn same_directory_format(source: &str, requested: &str) -> bool {
    if is_pypsa_dir(source) && is_pypsa_dir(requested) {
        return true;
    }
    if is_cgmes_dir(source) && is_cgmes_dir(requested) {
        return true;
    }
    #[cfg(feature = "gridfm")]
    if source.eq_ignore_ascii_case("gridfm") && requested.eq_ignore_ascii_case("gridfm") {
        return true;
    }
    false
}

/// The exact artifact inventory of an unchanged directory source when the
/// requested format is that source's format. Entry names come from the
/// source's bounded portable directory walk, and every byte is acquired
/// through the source's confined, no-symlink path rather than by reopening a
/// caller-controlled path here.
fn echo_retained_directory(
    module: &PioModule<PioValue>,
    format: &str,
) -> Result<Option<Vec<powerio_core::MemoryArtifact>>, Error> {
    let Some(source) = module.source().filter(|source| source.is_directory()) else {
        return Ok(None);
    };
    let Some(source_format) = source.format() else {
        return Ok(None);
    };
    if !same_directory_format(source_format.as_str(), format) {
        return Ok(None);
    }

    let mut artifacts = Vec::new();
    for name in source.entry_names()? {
        let buffer = source.buffer(&name)?;
        artifacts.push(powerio_core::MemoryArtifact::new(
            name,
            buffer.bytes().to_vec(),
        ));
    }
    Ok(Some(artifacts))
}

/// A typed sibling module over `value` carrying every common record and the
/// retained source from the dynamic module. Source descriptors are added
/// first because source map and diagnostic spans validate against them.
fn typed_sibling<T>(module: &PioModule<PioValue>, value: T) -> Result<PioModule<T>, Error> {
    let mut out = PioModule::new(value).with_producer(module.producer().clone());
    for descriptor in module.sources() {
        out.add_source_descriptor(descriptor.clone())?;
    }
    for entry in module.source_map() {
        out.add_source_map_entry(entry.clone())?;
    }
    for diagnostic in module.diagnostics() {
        out.add_diagnostic(diagnostic.clone())?;
    }
    for entry in module.history() {
        out.add_history_entry(entry.clone())?;
    }
    for (namespace, value) in module.extensions() {
        out.insert_extension(namespace.clone(), value.clone())?;
    }
    Ok(match module.source() {
        Some(source) => out.with_source(source.clone()),
        None => out,
    })
}

/// The module's retained source's exact original bytes, when that source's
/// content is already `format`: the byte exact echo tier every kind should
/// get, not just [`PioValue::BalancedNetwork`] and
/// [`PioValue::MulticonductorNetwork`] (whose family emitters already carry
/// it through `powerio_tx::emit` and `powerio_dist::emit`).
/// `None` when there is no retained source, or its content is not `format`.
///
/// A source declared with an explicit format token (the C ABI and bindings
/// route this way) is trusted directly; a source routed here by content (a
/// bare `.json` file with no declared format, the common case for the CLI
/// and a plain `Source::open`) is reclassified the same way `powerio::parse`'s
/// own routing already did once to land on this kind in the first place.
fn retained_source_matches_case_format(module: &PioModule<PioValue>, format: &str) -> bool {
    use powerio_tx::format::routing::{
        Detection, JsonClass, classify_format_name, classify_json_text,
    };

    let Some(source) = module.source() else {
        return false;
    };
    // A one file representation can echo its primary buffer. A source set
    // cannot: its primary file is only one input to the typed value (for
    // example, the problem file beside a GO Challenge 3 solution).
    if source.acquired_buffers().len() != 1 {
        return false;
    }
    let Some(requested) = classify_format_name(format).known() else {
        return false;
    };
    let actual = if let Some(declared) = source.format() {
        let Some(actual) = classify_format_name(declared.as_str()).known() else {
            return false;
        };
        actual
    } else {
        let Ok(buffer) = source.primary_buffer() else {
            return false;
        };
        let Ok(text) = std::str::from_utf8(buffer.content_bytes()) else {
            return false;
        };
        match classify_json_text(text) {
            JsonClass::Case(Detection::Known(found)) => found,
            _ => return false,
        }
    };
    requested == actual
}

fn echo_retained_source(module: &PioModule<PioValue>, format: &str) -> Option<Vec<u8>> {
    if !retained_source_matches_case_format(module, format) {
        return None;
    }
    let source = module.source()?;
    let buffer = source.primary_buffer().ok()?;
    Some(buffer.bytes().to_vec())
}

fn unsupported_type(module: &PioModule<PioValue>, format: &str) -> Error {
    Error::new(
        &codes::REQUEST_EMIT_UNSUPPORTED_VALUE_TYPE,
        format!(
            "a {} module cannot be emitted as {format}; serialize writes PowerIO IR",
            module.value().type_name()
        ),
    )
}

fn unknown_format(format: &str) -> Error {
    // The descriptor still resolves the token in a build without the GridFM
    // emitter, so the refusal names the missing feature rather than the name.
    if cfg!(not(feature = "gridfm")) && is_gridfm_dir(format) {
        return Error::new(
            &codes::REQUEST_EMIT_UNKNOWN_FORMAT,
            format!(
                "{format} names the GridFM Parquet directory format, which this build compiled without the `gridfm` feature"
            ),
        );
    }
    Error::new(
        &codes::REQUEST_EMIT_UNKNOWN_FORMAT,
        format!("{format} is not a recognized target format name"),
    )
}

/// Facade emission options. Defaults preserve the ordinary source-echo and
/// canonical writer behavior for every format.
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct EmitOptions {
    /// Fresh SINCAL generation is experimental and must be requested explicitly.
    /// When present, this bypasses retained-source echo even for unchanged input.
    #[cfg(feature = "sincal")]
    pub sincal_experimental: Option<crate::SincalExperimentalOptions>,
}

/// Emit one module as `format` into `output`. The concrete value routes to its
/// grid exchange format implementation. PowerIO IR uses [`crate::serialize`]
/// instead.
///
/// `output` names the file or directory to write, or is a
/// [`powerio_core::Destination`], which is how a memory destination and its
/// artifact root name are given.
///
/// # Errors
/// `REQUEST.EMIT.UNKNOWN_FORMAT` for a format name nothing recognizes,
/// `REQUEST.EMIT.UNSUPPORTED_VALUE_TYPE` for a value the
/// named format cannot state, and the family writer's own failure otherwise.
///
/// # Panics
/// Never on external input: the fixed artifact names are valid by
/// construction, and the solution columns a family writer reads are length
/// checked by the solution constructors.
pub fn emit<T>(
    module: &PioModule<T>,
    format: &str,
    output: impl powerio_core::IntoDestination,
) -> Result<EmitResult, Error>
where
    T: Clone + Into<PioValue>,
{
    emit_with_options(module, format, &EmitOptions::default(), output)
}

/// Emit with explicit facade options. An experimental SINCAL request always
/// creates fresh typed output; it does not fall back to retained source echo.
/// The default options are equivalent to [`emit`].
///
/// # Errors
/// The same failures as [`emit`], invalid options for the selected format/value,
/// or unsupported physics in the explicitly selected experimental profile.
pub fn emit_with_options<T>(
    module: &PioModule<T>,
    format: &str,
    options: &EmitOptions,
    output: impl powerio_core::IntoDestination,
) -> Result<EmitResult, Error>
where
    T: Clone + Into<PioValue>,
{
    let module = module.clone().map_value(Into::into);
    let destination = output.into_destination()?;
    #[cfg(feature = "sincal")]
    if let Some(options) = &options.sincal_experimental {
        return crate::sincal_write::emit(&module, format, options, destination);
    }
    // Without the sincal feature no option changes emission yet.
    #[cfg(not(feature = "sincal"))]
    let _: &EmitOptions = options;
    let result = emit_dynamic(&module, format, destination)?;
    let from_sincal = module.sources().iter().any(|source| {
        source
            .format()
            .is_some_and(|f| is_sincal_format(f.as_str()))
    });
    if from_sincal
        && !is_sincal_format(format)
        && !result.diagnostics().iter().any(|d| {
            matches!(
                d.code(),
                "EMIT.SINCAL.RETAINED_SOURCE_OMITTED" | "EMIT.DIST.SINCAL_RETAINED_SOURCE_OMITTED"
            )
        })
    {
        Ok(result.__with_diagnostics(vec![Diagnostic::of(
            &powerio_tx::diagnostics::codes::EMIT_SINCAL_RETAINED_SOURCE_OMITTED,
            "Cross-format emission includes the typed electrical profile; fault, dynamic, protection, diagram, result and other native source-only data are omitted.",
        )]))
    } else {
        Ok(result)
    }
}

fn calculation_data_omitted(value_type: &str, format: &str) -> Diagnostic {
    Diagnostic::of(
        &codes::EMIT_CALCULATION_DATA_OMITTED,
        format!(
            "{format} represents a grid case, not the complete {value_type}; emitted its electrical network"
        ),
    )
}

fn solution_data_omitted(value_type: &str, format: &str) -> Diagnostic {
    Diagnostic::of(
        &codes::EMIT_SOLUTION_DATA_OMITTED,
        format!(
            "{format} cannot represent every {value_type} result; emitted the network values it supports, while PowerIO IR retains the complete solution"
        ),
    )
}

fn relaxation_data_omitted(format: &str) -> Diagnostic {
    Diagnostic::of(
        &codes::EMIT_RELAXATION_DATA_OMITTED,
        format!(
            "{format} cannot represent SOCWR W-space values or the objective lower bound; emitted the instance network without treating the relaxation as an AC power flow solution"
        ),
    )
}

fn operating_point_data_omitted(format: &str) -> Diagnostic {
    Diagnostic::of(
        &codes::EMIT_OPERATING_POINT_DATA_OMITTED,
        format!(
            "{format} has no source-neutral field for net bus injection columns; emitted the other operating point quantities"
        ),
    )
}

pub(crate) fn network_with_balanced_operating_point(
    point: &OperatingPoint<BalancedNetwork>,
    format: &str,
) -> (BalancedNetwork, Vec<Diagnostic>) {
    let mut network = point.network().clone();

    if let Some(values) = point.values(BalancedOperatingPointQuantity::BusVoltageMagnitude) {
        for (bus, (_, value)) in network.buses_mut().iter_mut().zip(values) {
            bus.vm = value;
        }
    }
    if let Some(values) = point.values(BalancedOperatingPointQuantity::BusVoltageAngle) {
        for (bus, (_, value)) in network.buses_mut().iter_mut().zip(values) {
            bus.va = value.to_degrees();
        }
    }
    if let Some(values) = point.values(BalancedOperatingPointQuantity::GeneratorActivePower) {
        for (generator, (_, value)) in network.generators_mut().iter_mut().zip(values) {
            generator.pg = value;
        }
    }
    if let Some(values) = point.values(BalancedOperatingPointQuantity::GeneratorReactivePower) {
        for (generator, (_, value)) in network.generators_mut().iter_mut().zip(values) {
            generator.qg = value;
        }
    }
    if let Some(values) = point.values(BalancedOperatingPointQuantity::GeneratorVoltageSetpoint) {
        for (generator, (_, value)) in network.generators_mut().iter_mut().zip(values) {
            generator.vg = value;
        }
    }
    if let Some(flags) = point.flags(BalancedOperatingPointFlag::GeneratorInService) {
        for (generator, (_, value)) in network.generators_mut().iter_mut().zip(flags) {
            generator.in_service = value;
        }
    }
    if let Some(values) = point.values(BalancedOperatingPointQuantity::LoadActivePower) {
        for (load, (_, value)) in network.loads_mut().iter_mut().zip(values) {
            load.p = value;
        }
    }
    if let Some(values) = point.values(BalancedOperatingPointQuantity::LoadReactivePower) {
        for (load, (_, value)) in network.loads_mut().iter_mut().zip(values) {
            load.q = value;
        }
    }
    if let Some(flags) = point.flags(BalancedOperatingPointFlag::BranchInService) {
        for (branch, (_, value)) in network.branches_mut().iter_mut().zip(flags) {
            branch.in_service = value;
        }
    }
    if let Some(values) = point.values(BalancedOperatingPointQuantity::BranchTapRatio) {
        for (branch, (_, value)) in network.branches_mut().iter_mut().zip(values) {
            branch.tap = value;
        }
    }
    if let Some(values) = point.values(BalancedOperatingPointQuantity::BranchPhaseShift) {
        for (branch, (_, value)) in network.branches_mut().iter_mut().zip(values) {
            branch.shift = value;
        }
    }
    if let Some(flags) = point.flags(BalancedOperatingPointFlag::SwitchClosed) {
        for (switch, (_, value)) in network.switches_mut().iter_mut().zip(flags) {
            switch.closed = value;
        }
    }

    let has_unrepresented_injections = point
        .values(BalancedOperatingPointQuantity::BusActiveInjection)
        .is_some()
        || point
            .values(BalancedOperatingPointQuantity::BusReactiveInjection)
            .is_some();
    let diagnostics = has_unrepresented_injections
        .then(|| operating_point_data_omitted(format))
        .into_iter()
        .collect();
    (network, diagnostics)
}

fn network_with_multiconductor_operating_point(
    point: &OperatingPoint<powerio_dist::MulticonductorNetwork>,
    format: &str,
) -> (powerio_dist::MulticonductorNetwork, Vec<Diagnostic>) {
    let mut network = point.network().clone();

    if let Some(values) = point.values(MulticonductorOperatingPointQuantity::LoadActivePower) {
        let mut values = values.map(|(_, value)| value);
        for load in network.loads_mut() {
            for value in &mut load.p_nom {
                *value = values
                    .next()
                    .expect("an operating point has one value per load terminal");
            }
        }
        debug_assert!(values.next().is_none());
    }
    if let Some(values) = point.values(MulticonductorOperatingPointQuantity::LoadReactivePower) {
        let mut values = values.map(|(_, value)| value);
        for load in network.loads_mut() {
            for value in &mut load.q_nom {
                *value = values
                    .next()
                    .expect("an operating point has one value per load terminal");
            }
        }
        debug_assert!(values.next().is_none());
    }
    if let Some(values) = point.values(MulticonductorOperatingPointQuantity::GeneratorActivePower) {
        let mut values = values.map(|(_, value)| value);
        for generator in network.generators_mut() {
            for value in &mut generator.p_nom {
                *value = values
                    .next()
                    .expect("an operating point has one value per generator terminal");
            }
        }
        debug_assert!(values.next().is_none());
    }
    if let Some(values) = point.values(MulticonductorOperatingPointQuantity::GeneratorReactivePower)
    {
        let mut values = values.map(|(_, value)| value);
        for generator in network.generators_mut() {
            for value in &mut generator.q_nom {
                *value = values
                    .next()
                    .expect("an operating point has one value per generator terminal");
            }
        }
        debug_assert!(values.next().is_none());
    }
    if let Some(flags) = point.flags(MulticonductorOperatingPointFlag::SwitchClosed) {
        for (switch, (_, closed)) in network.switches_mut().iter_mut().zip(flags) {
            switch.open = !closed;
        }
    }

    let mut omitted = Vec::new();
    if point
        .values(MulticonductorOperatingPointQuantity::TerminalVoltageMagnitude)
        .is_some()
    {
        omitted.push("terminal voltage magnitude");
    }
    if point
        .values(MulticonductorOperatingPointQuantity::TerminalVoltageAngle)
        .is_some()
    {
        omitted.push("terminal voltage angle");
    }
    if point
        .values(MulticonductorOperatingPointQuantity::TransformerTap)
        .is_some()
    {
        omitted.push("transformer tap");
    }
    if point
        .values(MulticonductorOperatingPointQuantity::CapacitorSteps)
        .is_some()
    {
        omitted.push("capacitor steps");
    }
    let diagnostics = if omitted.is_empty() {
        Vec::new()
    } else {
        vec![Diagnostic::of(
            &codes::EMIT_OPERATING_POINT_DATA_OMITTED,
            format!(
                "{format} cannot represent these operating point quantities in the source-neutral network model: {}; emitted the other quantities",
                omitted.join(", ")
            ),
        )]
    };
    (network, diagnostics)
}

fn network_with_dc_pf_solution(solution: &powerio_prob::DcPfSolution) -> BalancedNetwork {
    let mut network = solution.network().clone();
    for bus in network.buses_mut() {
        bus.va = solution
            .bus_voltage_angle(bus.id)
            .expect("a solution contains one angle per network bus");
    }
    if let Some(dispatch) = solution.generator_dispatch() {
        for (generator, active_power) in network.generators_mut().iter_mut().zip(&dispatch.p_mw) {
            generator.pg = *active_power;
        }
        if !dispatch.q_mvar.is_empty() {
            for (generator, reactive_power) in
                network.generators_mut().iter_mut().zip(&dispatch.q_mvar)
            {
                generator.qg = *reactive_power;
            }
        }
    }
    network
}

fn network_with_ac_pf_solution(solution: &powerio_prob::AcPfSolution) -> BalancedNetwork {
    let mut network = solution.network().clone();
    for bus in network.buses_mut() {
        bus.vm = solution
            .bus_voltage_magnitude(bus.id)
            .expect("a solution contains one magnitude per network bus");
        bus.va = solution
            .bus_voltage_angle(bus.id)
            .expect("a solution contains one angle per network bus");
    }
    for (branch, identity) in network
        .branches_mut()
        .iter_mut()
        .zip(solution.branch_order())
    {
        branch.solution = Some(BranchSolution::new(
            solution
                .branch_from_active_flow(&identity)
                .expect("a solution contains one from active flow per branch"),
            solution
                .branch_from_reactive_flow(&identity)
                .expect("a solution contains one from reactive flow per branch"),
            solution
                .branch_to_active_flow(&identity)
                .expect("a solution contains one to active flow per branch"),
            solution
                .branch_to_reactive_flow(&identity)
                .expect("a solution contains one to reactive flow per branch"),
        ));
    }
    if let Some(dispatch) = solution.generator_dispatch() {
        for (generator, active_power) in network.generators_mut().iter_mut().zip(&dispatch.p_mw) {
            generator.pg = *active_power;
        }
        if !dispatch.q_mvar.is_empty() {
            for (generator, reactive_power) in
                network.generators_mut().iter_mut().zip(&dispatch.q_mvar)
            {
                generator.qg = *reactive_power;
            }
        }
    }
    network
}

fn network_with_dc_opf_solution(solution: &powerio_prob::DcOpfSolution) -> BalancedNetwork {
    let mut network = solution.network().clone();
    for bus in network.buses_mut() {
        bus.va = solution
            .bus_voltage_angle(bus.id)
            .expect("a solution contains one angle per network bus");
    }
    for (generator, identity) in network
        .generators_mut()
        .iter_mut()
        .zip(solution.generator_order())
    {
        generator.pg = solution
            .generator_active_power(&identity)
            .expect("a solution contains one active power per generator");
    }
    network
}

pub(crate) fn network_with_ac_opf_solution(
    solution: &powerio_prob::AcOpfSolution,
) -> BalancedNetwork {
    let mut network = solution.network().clone();
    for bus in network.buses_mut() {
        bus.vm = solution
            .bus_voltage_magnitude(bus.id)
            .expect("a solution contains one magnitude per network bus");
        bus.va = solution
            .bus_voltage_angle(bus.id)
            .expect("a solution contains one angle per network bus");
    }
    for (branch, identity) in network
        .branches_mut()
        .iter_mut()
        .zip(solution.branch_order())
    {
        branch.solution = Some(BranchSolution::new(
            solution
                .branch_from_active_flow(&identity)
                .expect("a solution contains one from active flow per branch"),
            solution
                .branch_from_reactive_flow(&identity)
                .expect("a solution contains one from reactive flow per branch"),
            solution
                .branch_to_active_flow(&identity)
                .expect("a solution contains one to active flow per branch"),
            solution
                .branch_to_reactive_flow(&identity)
                .expect("a solution contains one to reactive flow per branch"),
        ));
    }
    for (generator, identity) in network
        .generators_mut()
        .iter_mut()
        .zip(solution.generator_order())
    {
        generator.pg = solution
            .generator_active_power(&identity)
            .expect("a solution contains one active power per generator");
        generator.qg = solution
            .generator_reactive_power(&identity)
            .expect("a solution contains one reactive power per generator");
    }
    network
}

fn emit_balanced_network(
    module: &PioModule<PioValue>,
    network: &BalancedNetwork,
    format: &str,
    destination: Destination,
    preserve_retained_source: bool,
    diagnostics: Vec<Diagnostic>,
) -> Result<EmitResult, Error> {
    let typed = typed_sibling(module, network.clone())?;
    let typed = if preserve_retained_source && retained_source_matches_case_format(module, format) {
        typed
    } else {
        typed.sever_source()
    };
    let result = if is_pypsa_dir(format) {
        powerio_tx::__emit_pypsa_csv(&typed, destination)
    } else {
        #[cfg(feature = "gridfm")]
        if is_gridfm_dir(format) {
            let mut diagnostics = diagnostics;
            let dataset = powerio_matrix::build_gridfm_dataset(
                network,
                0,
                &powerio_matrix::GridfmOptions::default(),
            )
            .map_err(|error| Error::new(error.code(), error.to_string()).with_cause(error))?;
            diagnostics.extend(dataset.diagnostics);
            return destination.__commit_artifacts(
                true,
                powerio_core::Fidelity::Canonical,
                dataset.artifacts,
                diagnostics,
            );
        }
        let Some(target) = powerio_tx::format::parse_target_format(format) else {
            return Err(unknown_format(format));
        };
        powerio_tx::emit(&typed, target, destination)
    }?;
    Ok(result.__with_diagnostics(diagnostics))
}

fn emit_multiconductor_network(
    module: &PioModule<PioValue>,
    network: powerio_dist::MulticonductorNetwork,
    format: &str,
    destination: Destination,
    preserve_retained_source: bool,
    diagnostics: Vec<Diagnostic>,
) -> Result<EmitResult, Error> {
    let Some(target) = powerio_dist::parse_dist_target_format(format) else {
        return Err(unknown_format(format));
    };
    let typed = typed_sibling(module, network)?;
    let retained_project = matches!(
        target,
        powerio_dist::DistTargetFormat::Dss
            | powerio_dist::DistTargetFormat::Gridlabd
            | powerio_dist::DistTargetFormat::GridlabdArras
    ) && module
        .source()
        .and_then(powerio_core::Source::format)
        .and_then(|id| powerio_dist::parse_dist_target_format(id.as_str()))
        == Some(target);
    let typed = if preserve_retained_source
        && (retained_project || retained_source_matches_case_format(module, format))
    {
        typed
    } else {
        typed.sever_source()
    };
    powerio_dist::emit(&typed, target, destination)
        .map(|result| result.__with_diagnostics(diagnostics))
}

fn emit_goc3_solution(
    solution: &powerio_prob::AcScucSolution,
    destination: Destination,
) -> Result<EmitResult, Error> {
    let text = powerio_prob::__internal::__emit_goc3_output(solution)?;
    let artifact = powerio_core::MemoryArtifact::new(
        powerio_core::ArtifactPath::new("solution.json")
            .expect("static name is a valid artifact path"),
        text.into_bytes(),
    );
    destination.__commit_artifacts(
        false,
        powerio_core::Fidelity::Canonical,
        vec![artifact],
        Vec::new(),
    )
}

/// Write one geographic layer as the canonical `.geo.json` document. No grid
/// exchange format states a standalone layer, so any other target is refused
/// by value type.
fn emit_geo_layer(
    layer: &powerio_tx::GeoLayer,
    format: &str,
    destination: Destination,
) -> Result<EmitResult, Error> {
    if !crate::is_geo_layer_token(format) {
        // A `.pwd` display reads into a layer but has no writer, so naming it
        // as the target is a different mistake from naming a grid case.
        return Err(if crate::is_pwd_display_token(format) {
            Error::new(
                &codes::REQUEST_EMIT_UNSUPPORTED_VALUE_TYPE,
                format!(
                    "{format} names the PowerWorld display file, which has no writer; write the layer as `geo-json`"
                ),
            )
        } else if known_format_name(format) {
            Error::new(
                &codes::REQUEST_EMIT_UNSUPPORTED_VALUE_TYPE,
                format!(
                    "{format} states a grid case, not powerio.GeoLayer; write a layer as `geo-json` or place it onto a case with apply_geo_layer"
                ),
            )
        } else {
            unknown_format(format)
        });
    }
    let text = layer
        .to_geojson_checked()
        .map_err(|error| Error::new(error.code(), error.to_string()).with_cause(error))?;
    let artifact = powerio_core::MemoryArtifact::new(
        powerio_core::ArtifactPath::new(powerio_tx::geo::GEO_LAYER_EXTENSION)
            .expect("static name is a valid artifact path"),
        text.into_bytes(),
    );
    destination.__commit_artifacts(
        false,
        powerio_core::Fidelity::Canonical,
        vec![artifact],
        Vec::new(),
    )
}

/// The three PSS/E contingency analysis files that a module value can be, or
/// `None` for every other value.
fn contingency_file_of_value(value: &PioValue) -> Option<crate::ContingencyFile> {
    match value {
        PioValue::ContingencySet(_) => Some(crate::ContingencyFile::Con),
        PioValue::SubsystemSet(_) => Some(crate::ContingencyFile::Sub),
        PioValue::MonitoredSet(_) => Some(crate::ContingencyFile::Mon),
        _ => None,
    }
}

/// The module's retained source bytes when the value is a PSS/E contingency
/// analysis file and `format` names that same file. The three tokens are not
/// grid case names, so `retained_source_matches_case_format` never claims
/// them; this is the same rule stated over the contingency tokens.
fn retained_contingency_source(module: &PioModule<PioValue>, format: &str) -> Option<Vec<u8>> {
    let kind = contingency_file_of_value(module.value())?;
    if crate::contingency_file_of_token(format)? != kind {
        return None;
    }
    let source = module.source()?;
    if source.acquired_buffers().len() != 1 {
        return None;
    }
    if crate::contingency_file_of_token(source.format()?.as_str())? != kind {
        return None;
    }
    Some(source.primary_buffer().ok()?.bytes().to_vec())
}

/// Write one PSS/E contingency analysis file as canonical text. Each of the
/// three files is its own target: a `.con` written as `psse-sub` would state
/// a different grammar, so only the token naming this value's own file is
/// accepted.
fn emit_contingency_file(
    value: &PioValue,
    kind: crate::ContingencyFile,
    format: &str,
    destination: Destination,
) -> Result<EmitResult, Error> {
    if crate::contingency_file_of_token(format) != Some(kind) {
        return Err(if crate::contingency_file_of_token(format).is_some() {
            Error::new(
                &codes::REQUEST_EMIT_UNSUPPORTED_VALUE_TYPE,
                format!(
                    "{format} names another PSS/E contingency analysis file, not {}; write this one as `{}`",
                    kind.type_name(),
                    kind.token()
                ),
            )
        } else if known_format_name(format) {
            Error::new(
                &codes::REQUEST_EMIT_UNSUPPORTED_VALUE_TYPE,
                format!(
                    "{format} states a grid case, not {}; write this file as `{}`",
                    kind.type_name(),
                    kind.token()
                ),
            )
        } else {
            unknown_format(format)
        });
    }
    let text = match value {
        PioValue::ContingencySet(set) => set.to_con(),
        PioValue::SubsystemSet(set) => set.to_sub(),
        PioValue::MonitoredSet(set) => set.to_mon(),
        _ => unreachable!("the value variant selected the file kind"),
    };
    let artifact = powerio_core::MemoryArtifact::new(
        powerio_core::ArtifactPath::new(kind.artifact_name())
            .expect("static name is a valid artifact path"),
        text.into_bytes(),
    );
    destination.__commit_artifacts(
        false,
        powerio_core::Fidelity::Canonical,
        vec![artifact],
        Vec::new(),
    )
}

fn balanced_calculation_network(value: &PioValue) -> Option<&BalancedNetwork> {
    match value {
        PioValue::DcPfInstance(instance) => Some(instance.network()),
        PioValue::AcPfInstance(instance) => Some(instance.network()),
        PioValue::DcOpfInstance(instance) => Some(instance.network()),
        PioValue::AcOpfInstance(instance) => Some(instance.network()),
        PioValue::AcScucInstance(instance) => Some(instance.network()),
        _ => None,
    }
}

fn multiconductor_calculation_network(
    value: &PioValue,
) -> Option<&powerio_dist::MulticonductorNetwork> {
    match value {
        PioValue::McAcPfInstance(instance) => Some(instance.network()),
        PioValue::McAcOpfInstance(instance) => Some(instance.network()),
        // The source network, not the prepared formulation network: emitting
        // the latter would silently drop lowered and omitted components.
        PioValue::LinDist3FlowPfInstance(instance) => Some(instance.source_network()),
        PioValue::LinDist3FlowOpfInstance(instance) => Some(instance.source_network()),
        _ => None,
    }
}

fn emit_network_or_calculation(
    module: &PioModule<PioValue>,
    format: &str,
    destination: Destination,
) -> Result<EmitResult, Error> {
    if matches!(module.value(), PioValue::AcScucInstance(_)) && is_goc3(format) {
        return Err(unsupported_type(module, format));
    }
    if let Some(network) = balanced_calculation_network(module.value()) {
        return emit_balanced_network(
            module,
            network,
            format,
            destination,
            false,
            vec![calculation_data_omitted(module.value().type_name(), format)],
        );
    }
    if let Some(network) = multiconductor_calculation_network(module.value()) {
        return emit_multiconductor_network(
            module,
            network.clone(),
            format,
            destination,
            false,
            vec![calculation_data_omitted(module.value().type_name(), format)],
        );
    }
    match &module.value() {
        PioValue::BalancedNetwork(network) => {
            emit_balanced_network(module, network, format, destination, true, Vec::new())
        }
        PioValue::MulticonductorNetwork(network) => emit_multiconductor_network(
            module,
            network.clone(),
            format,
            destination,
            true,
            Vec::new(),
        ),
        PioValue::BalancedOperatingPoint(point) => {
            let (network, diagnostics) = network_with_balanced_operating_point(point, format);
            emit_balanced_network(module, &network, format, destination, false, diagnostics)
        }
        PioValue::MulticonductorOperatingPoint(point) => {
            let (network, diagnostics) = network_with_multiconductor_operating_point(point, format);
            emit_multiconductor_network(module, network, format, destination, false, diagnostics)
        }
        _ => unreachable!("caller selected a value that is not a network or calculation"),
    }
}

fn emit_balanced_solution_network(
    module: &PioModule<PioValue>,
    network: &BalancedNetwork,
    format: &str,
    destination: Destination,
) -> Result<EmitResult, Error> {
    emit_balanced_network(
        module,
        network,
        format,
        destination,
        false,
        vec![solution_data_omitted(module.value().type_name(), format)],
    )
}

fn emit_multiconductor_solution_network(
    module: &PioModule<PioValue>,
    network: &powerio_dist::MulticonductorNetwork,
    format: &str,
    destination: Destination,
) -> Result<EmitResult, Error> {
    emit_multiconductor_network(
        module,
        network.clone(),
        format,
        destination,
        false,
        vec![solution_data_omitted(module.value().type_name(), format)],
    )
}

fn emit_solution(
    module: &PioModule<PioValue>,
    format: &str,
    destination: Destination,
) -> Result<EmitResult, Error> {
    match &module.value() {
        PioValue::DcPfSolution(solution) => emit_balanced_solution_network(
            module,
            &network_with_dc_pf_solution(solution),
            format,
            destination,
        ),
        PioValue::AcPfSolution(solution) => emit_balanced_solution_network(
            module,
            &network_with_ac_pf_solution(solution),
            format,
            destination,
        ),
        PioValue::DcOpfSolution(solution) => emit_balanced_solution_network(
            module,
            &network_with_dc_opf_solution(solution),
            format,
            destination,
        ),
        PioValue::AcOpfSolution(solution) => emit_balanced_solution_network(
            module,
            &network_with_ac_opf_solution(solution),
            format,
            destination,
        ),
        PioValue::SocwrOpfSolution(solution) => emit_balanced_network(
            module,
            solution.network(),
            format,
            destination,
            false,
            vec![relaxation_data_omitted(format)],
        ),
        PioValue::McAcPfSolution(solution) => {
            emit_multiconductor_solution_network(module, solution.network(), format, destination)
        }
        PioValue::McAcOpfSolution(solution) => {
            emit_multiconductor_solution_network(module, solution.network(), format, destination)
        }
        PioValue::LinDist3FlowPfSolution(solution) => emit_multiconductor_solution_network(
            module,
            solution.instance().source_network(),
            format,
            destination,
        ),
        PioValue::LinDist3FlowOpfSolution(solution) => emit_multiconductor_solution_network(
            module,
            solution.instance().source_network(),
            format,
            destination,
        ),
        PioValue::AcScucSolution(solution) if is_goc3(format) => {
            emit_goc3_solution(solution, destination)
        }
        PioValue::AcScucSolution(solution) => emit_balanced_solution_network(
            module,
            solution.instance().network(),
            format,
            destination,
        ),
        _ => unreachable!("caller selected a value that is not a solution"),
    }
}

fn emit_versioned_bmopf(
    module: &PioModule<PioValue>,
    version: &str,
    destination: Destination,
) -> Result<EmitResult, Error> {
    let format = format!("bmopf-json@{version}");
    let profile = match version {
        "0.1.0" => powerio_dist::BmopfSchemaVersion::Bmopf010,
        "0.2.0" => powerio_dist::BmopfSchemaVersion::Bmopf020,
        _ => return Err(unknown_format(&format)),
    };
    let (network, diagnostics) = match module.value() {
        PioValue::MulticonductorNetwork(network) => (network.clone(), Vec::new()),
        PioValue::McAcPfInstance(instance) => (
            instance.network().clone(),
            vec![calculation_data_omitted(
                module.value().type_name(),
                &format,
            )],
        ),
        PioValue::McAcOpfInstance(instance) => (
            instance.network().clone(),
            vec![calculation_data_omitted(
                module.value().type_name(),
                &format,
            )],
        ),
        PioValue::LinDist3FlowPfInstance(instance) => (
            instance.source_network().clone(),
            vec![calculation_data_omitted(
                module.value().type_name(),
                &format,
            )],
        ),
        PioValue::LinDist3FlowOpfInstance(instance) => (
            instance.source_network().clone(),
            vec![calculation_data_omitted(
                module.value().type_name(),
                &format,
            )],
        ),
        PioValue::MulticonductorOperatingPoint(point) => {
            network_with_multiconductor_operating_point(point, &format)
        }
        PioValue::McAcPfSolution(solution) => (
            solution.instance().network().clone(),
            vec![solution_data_omitted(module.value().type_name(), &format)],
        ),
        PioValue::McAcOpfSolution(solution) => (
            solution.instance().network().clone(),
            vec![solution_data_omitted(module.value().type_name(), &format)],
        ),
        PioValue::LinDist3FlowPfSolution(solution) => (
            solution.instance().source_network().clone(),
            vec![solution_data_omitted(module.value().type_name(), &format)],
        ),
        PioValue::LinDist3FlowOpfSolution(solution) => (
            solution.instance().source_network().clone(),
            vec![solution_data_omitted(module.value().type_name(), &format)],
        ),
        _ => return Err(unsupported_type(module, &format)),
    };
    let typed = typed_sibling(module, network)?.sever_source();
    let mut options = powerio_dist::EmitOptions::default();
    options.bmopf.schema_version = profile;
    powerio_dist::emit_with_options(
        &typed,
        powerio_dist::DistTargetFormat::BmopfJson,
        &options,
        destination,
    )
    .map(|result| result.__with_diagnostics(diagnostics))
}

pub(crate) fn is_sincal_format(format: &str) -> bool {
    crate::resolve_format(format).is_some_and(|f| {
        matches!(
            f.token,
            "sincal" | "sincal-balanced" | "sincal-multiconductor"
        )
    })
}

/// Binary retained-source echo is separate from fresh electrical writing.
#[cfg(feature = "sincal")]
fn echo_sincal(
    module: &PioModule<PioValue>,
    format: &str,
    destination: Destination,
) -> Result<EmitResult, Error> {
    if !matches!(
        module.value(),
        PioValue::BalancedNetwork(_) | PioValue::MulticonductorNetwork(_)
    ) {
        return Err(unsupported_type(module, "sincal"));
    }
    let target = crate::resolve_format(format).map(|f| f.token);
    if matches!(
        (target, module.value()),
        (Some("sincal-balanced"), PioValue::MulticonductorNetwork(_))
            | (Some("sincal-multiconductor"), PioValue::BalancedNetwork(_))
    ) {
        return Err(unsupported_type(module, format));
    }
    let source = module.source().filter(|source| source.format().is_some_and(|f| is_sincal_format(f.as_str())))
        .ok_or_else(|| Error::new(&powerio_tx::diagnostics::codes::EMIT_SINCAL_FRESH_UNSUPPORTED,
            "SINCAL currently supports unchanged retained-source echo only. Edited, constructed, or IR-restored networks require the separate experimental fresh writer."))?;
    let primary = source.primary_buffer()?;
    // deserialize retains the IR document as its acquired source. A caller
    // supplying a native format hint must not relabel those JSON bytes as a
    // SINCAL project and enable an invalid native echo.
    if !primary.bytes().starts_with(b"SQLite format 3\0")
        && !primary.bytes().starts_with(b"PK\x03\x04")
        && !primary.bytes().starts_with(b"\0\x01\0\0Standard Jet DB\0")
    {
        return Err(Error::new(
            &powerio_tx::diagnostics::codes::EMIT_SINCAL_FRESH_UNSUPPORTED,
            "The retained bytes are not a native SINCAL database or archive; source metadata alone cannot enable native echo.",
        ));
    }
    destination.__commit_artifacts(
        false,
        powerio_core::Fidelity::ExactSameFormat,
        vec![powerio_core::MemoryArtifact::new(
            powerio_core::ArtifactPath::new("case.sinx")?,
            primary.bytes().to_vec(),
        )],
        Vec::new(),
    )
}

fn emit_dynamic(
    module: &PioModule<PioValue>,
    format: &str,
    destination: Destination,
) -> Result<EmitResult, Error> {
    if is_sincal_format(format) {
        #[cfg(feature = "sincal")]
        return echo_sincal(module, format, destination);
        #[cfg(not(feature = "sincal"))]
        return Err(crate::sincal_feature_disabled());
    }
    if let Some(version) = format.strip_prefix("bmopf-json@") {
        return emit_versioned_bmopf(module, version, destination);
    }
    if let Some(artifacts) = echo_retained_directory(module, format)? {
        return destination.__commit_artifacts(
            true,
            powerio_core::Fidelity::ExactSameFormat,
            artifacts,
            Vec::new(),
        );
    }

    // A parse-only calculation format can still reproduce an unchanged
    // retained source exactly. A derived module has no retained source, so a
    // solved result never falls through to stale input bytes here.
    if !matches!(
        &module.value(),
        PioValue::BalancedNetwork(_) | PioValue::MulticonductorNetwork(_)
    ) && let Some(bytes) = echo_retained_source(module, format)
    {
        let artifact = powerio_core::MemoryArtifact::new(
            powerio_core::ArtifactPath::new("case").expect("static name is a valid artifact path"),
            bytes,
        );
        return destination.__commit_artifacts(
            false,
            powerio_core::Fidelity::ExactSameFormat,
            vec![artifact],
            Vec::new(),
        );
    }

    if let PioValue::GeoLayer(layer) = &module.value() {
        return emit_geo_layer(layer, format, destination);
    }

    if let Some(kind) = contingency_file_of_value(module.value()) {
        if let Some(bytes) = retained_contingency_source(module, format) {
            let artifact = powerio_core::MemoryArtifact::new(
                powerio_core::ArtifactPath::new(kind.artifact_name())
                    .expect("static name is a valid artifact path"),
                bytes,
            );
            return destination.__commit_artifacts(
                false,
                powerio_core::Fidelity::ExactSameFormat,
                vec![artifact],
                Vec::new(),
            );
        }
        return emit_contingency_file(module.value(), kind, format, destination);
    }

    match &module.value() {
        PioValue::BalancedNetwork(_)
        | PioValue::MulticonductorNetwork(_)
        | PioValue::BalancedOperatingPoint(_)
        | PioValue::MulticonductorOperatingPoint(_)
        | PioValue::DcPfInstance(_)
        | PioValue::AcPfInstance(_)
        | PioValue::DcOpfInstance(_)
        | PioValue::AcOpfInstance(_)
        | PioValue::McAcPfInstance(_)
        | PioValue::McAcOpfInstance(_)
        | PioValue::LinDist3FlowPfInstance(_)
        | PioValue::LinDist3FlowOpfInstance(_)
        | PioValue::AcScucInstance(_) => emit_network_or_calculation(module, format, destination),
        PioValue::DcPfSolution(_)
        | PioValue::AcPfSolution(_)
        | PioValue::DcOpfSolution(_)
        | PioValue::AcOpfSolution(_)
        | PioValue::SocwrOpfSolution(_)
        | PioValue::McAcPfSolution(_)
        | PioValue::McAcOpfSolution(_)
        | PioValue::LinDist3FlowPfSolution(_)
        | PioValue::LinDist3FlowOpfSolution(_)
        | PioValue::AcScucSolution(_) => emit_solution(module, format, destination),
        _ => {
            if known_format_name(format) {
                Err(unsupported_type(module, format))
            } else {
                Err(unknown_format(format))
            }
        }
    }
}

/// True when `format` is a name some family recognizes, used to tell "wrong
/// kind for this format" apart from "no such format".
fn known_format_name(format: &str) -> bool {
    crate::resolve_format(format).is_some()
}

#[cfg(test)]
mod tests {
    use super::*;
    use powerio_core::{
        DiagnosticCode, DiagnosticSeverity, HistoryEntry, HistoryId, HistoryKind, Producer,
        SourceDescriptor, SourceId, SourceMapEntry, SourceRelation, SourceSpan,
    };
    use powerio_tx::{BalancedNetwork, Bus, BusId, BusType};

    #[test]
    fn a_typed_writer_sibling_preserves_every_common_record() {
        let network = BalancedNetwork::in_memory(
            "records",
            100.0,
            vec![Bus::new(BusId(1), BusType::Ref, 230.0)],
            vec![],
        );
        let source = powerio_core::Source::from_memory("case.m", b"case bytes".to_vec())
            .unwrap()
            .with_format(powerio_core::FormatId::new("matpower").unwrap());
        let source_id = SourceId::new("source-1").unwrap();
        let mut module = PioModule::new(PioValue::BalancedNetwork(network.clone()))
            .with_producer(Producer::new("records-test", "1").unwrap())
            .with_source(source);
        module
            .add_source_descriptor(SourceDescriptor::new(source_id.clone(), "case.m", 10).unwrap())
            .unwrap();
        module
            .add_source_map_entry(
                SourceMapEntry::new(
                    "/buses/0",
                    SourceRelation::Exact,
                    vec![SourceSpan::new(source_id, 0, 4).unwrap()],
                )
                .unwrap(),
            )
            .unwrap();
        module
            .add_diagnostic(powerio_core::Diagnostic::new(
                DiagnosticCode::new("READ.TEST.RECORD").unwrap(),
                DiagnosticSeverity::Remark,
                "record carried to the family writer",
            ))
            .unwrap();
        module
            .add_history_entry(
                HistoryEntry::new(
                    HistoryId::new("history-1").unwrap(),
                    HistoryKind::Parse,
                    "parse",
                )
                .unwrap(),
            )
            .unwrap();
        module
            .insert_extension("test.writer", serde_json::json!({"kept": true}))
            .unwrap();

        let sibling = typed_sibling(&module, network).unwrap();
        assert_eq!(sibling.producer(), module.producer());
        assert_eq!(sibling.sources(), module.sources());
        assert_eq!(sibling.source_map(), module.source_map());
        assert_eq!(sibling.diagnostics(), module.diagnostics());
        assert_eq!(sibling.history(), module.history());
        assert_eq!(sibling.extensions(), module.extensions());
        let sibling_source = sibling.source().unwrap();
        assert_eq!(sibling_source.name(), "case.m");
        assert_eq!(
            sibling_source.primary_buffer().unwrap().bytes(),
            b"case bytes"
        );
    }
}