powerio-dist 0.6.3

Multiconductor distribution network model and lossless converters for OpenDSS, PMD JSON, and BMOPF JSON.
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
//! The canonical multiconductor network model.
//!
//! Wire coordinates with BMOPF semantics: string bus ids, ordered string
//! terminal names per bus, explicit grounding on buses, terminal maps on
//! every element, SI units (V, W, var, ohm, S, meters) and radians. Terminal
//! names are the OpenDSS node numbers as strings; implicit ground
//! connections materialize as an explicit perfectly grounded neutral
//! terminal on the bus (named 4 on a three phase bus), the convention
//! PowerModelsDistribution and the public BMOPF examples share.
//!
//! Transformer impedances stay in the per unit form the source formats use
//! (`r_pct`, `xsc_pct` as percent of the winding base); the BMOPF writer
//! converts to ohms on the wye side at emission. Everything an element
//! carries beyond the typed fields lives in its `extras` map.

use std::collections::BTreeMap;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::geo::{GeoMeta, Location};

pub type Extras = BTreeMap<String, serde_json::Value>;

/// A square matrix in conductor order, row major.
pub type Mat = Vec<Vec<f64>>;

/// Where the network came from; fixes the echo tier target.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum DistSourceFormat {
    Dss,
    BmopfJson,
    PmdJson,
}

impl DistSourceFormat {
    /// The canonical format name (`dss`, `pmd-json`, `bmopf-json`), accepted
    /// back by [`crate::dist_target_from_name`].
    pub fn name(self) -> &'static str {
        match self {
            DistSourceFormat::Dss => "dss",
            DistSourceFormat::PmdJson => "pmd-json",
            DistSourceFormat::BmopfJson => "bmopf-json",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistBus {
    pub id: String,
    /// Ordered terminal names; OpenDSS node numbers as strings.
    pub terminals: Vec<String>,
    /// Terminals tied to ground with zero impedance.
    pub grounded: Vec<String>,
    /// Voltage magnitude bounds, volts: the scalar pair plus the phase to
    /// neutral, phase to phase, and symmetrical component families (the
    /// four BMOPF bound families).
    pub v_min: Option<f64>,
    pub v_max: Option<f64>,
    pub vpn_min: Option<Vec<f64>>,
    pub vpn_max: Option<Vec<f64>>,
    pub vpp_min: Option<Vec<f64>>,
    pub vpp_max: Option<Vec<f64>>,
    pub vsym_min: Option<Vec<f64>>,
    pub vsym_max: Option<Vec<f64>>,
    /// Optional bus coordinates in the network coordinate space.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub location: Option<Location>,
    pub extras: Extras,
}

impl DistBus {
    #[must_use]
    pub fn new(id: impl Into<String>, terminals: Vec<String>) -> Self {
        Self {
            id: id.into(),
            terminals,
            grounded: Vec::new(),
            v_min: None,
            v_max: None,
            vpn_min: None,
            vpn_max: None,
            vpp_min: None,
            vpp_max: None,
            vsym_min: None,
            vsym_max: None,
            location: None,
            extras: Extras::new(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistLineCode {
    pub name: String,
    pub n_conductors: usize,
    /// Series impedance, ohm per meter.
    pub r_series: Mat,
    pub x_series: Mat,
    /// Shunt admittance halves at each end, S per meter.
    pub g_from: Mat,
    pub b_from: Mat,
    pub g_to: Mat,
    pub b_to: Mat,
    /// Ampacity per conductor.
    pub i_max: Option<Vec<f64>>,
    pub s_max: Option<Vec<f64>>,
    pub extras: Extras,
}

impl DistLineCode {
    #[must_use]
    pub fn new(name: impl Into<String>, r_series: Mat, x_series: Mat) -> Self {
        let n_conductors = matrix_extent(&r_series).max(matrix_extent(&x_series));
        Self {
            name: name.into(),
            n_conductors,
            r_series,
            x_series,
            g_from: zero_mat(n_conductors),
            b_from: zero_mat(n_conductors),
            g_to: zero_mat(n_conductors),
            b_to: zero_mat(n_conductors),
            i_max: None,
            s_max: None,
            extras: Extras::new(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistLine {
    pub name: String,
    pub bus_from: String,
    pub bus_to: String,
    pub terminal_map_from: Vec<String>,
    pub terminal_map_to: Vec<String>,
    pub linecode: String,
    /// Meters.
    pub length: f64,
    pub extras: Extras,
}

impl DistLine {
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        bus_from: impl Into<String>,
        bus_to: impl Into<String>,
        terminal_map_from: Vec<String>,
        terminal_map_to: Vec<String>,
        linecode: impl Into<String>,
        length: f64,
    ) -> Self {
        Self {
            name: name.into(),
            bus_from: bus_from.into(),
            bus_to: bus_to.into(),
            terminal_map_from,
            terminal_map_to,
            linecode: linecode.into(),
            length,
            extras: Extras::new(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistSwitch {
    pub name: String,
    pub bus_from: String,
    pub bus_to: String,
    pub terminal_map_from: Vec<String>,
    pub terminal_map_to: Vec<String>,
    pub open: bool,
    pub i_max: Option<Vec<f64>>,
    pub extras: Extras,
}

impl DistSwitch {
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        bus_from: impl Into<String>,
        bus_to: impl Into<String>,
        terminal_map_from: Vec<String>,
        terminal_map_to: Vec<String>,
        open: bool,
    ) -> Self {
        Self {
            name: name.into(),
            bus_from: bus_from.into(),
            bus_to: bus_to.into(),
            terminal_map_from,
            terminal_map_to,
            open,
            i_max: None,
            extras: Extras::new(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Configuration {
    Wye,
    Delta,
    SinglePhase,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistLoad {
    pub name: String,
    pub bus: String,
    pub terminal_map: Vec<String>,
    pub configuration: Configuration,
    /// Watts per phase.
    pub p_nom: Vec<f64>,
    /// Vars per phase.
    pub q_nom: Vec<f64>,
    pub voltage_model: DistLoadVoltageModel,
    pub extras: Extras,
}

impl DistLoad {
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        bus: impl Into<String>,
        terminal_map: Vec<String>,
        configuration: Configuration,
        p_nom: Vec<f64>,
        q_nom: Vec<f64>,
    ) -> Self {
        Self {
            name: name.into(),
            bus: bus.into(),
            terminal_map,
            configuration,
            p_nom,
            q_nom,
            voltage_model: DistLoadVoltageModel::default(),
            extras: Extras::new(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "model", rename_all = "snake_case")]
#[non_exhaustive]
pub enum DistLoadVoltageModel {
    /// Constant power load. `v_nom` is volts per active phase when the source
    /// states it.
    ConstantPower { v_nom: Vec<f64> },
    /// Constant current load. `v_nom` is volts per active phase.
    ConstantCurrent { v_nom: Vec<f64> },
    /// Constant impedance load. `v_nom` is volts per active phase.
    ConstantImpedance { v_nom: Vec<f64> },
    /// ZIP load coefficients by active phase. `v_nom` is volts per active
    /// phase; alpha terms apply to active power and beta terms to reactive
    /// power.
    Zip {
        v_nom: Vec<f64>,
        alpha_z: Vec<f64>,
        alpha_i: Vec<f64>,
        alpha_p: Vec<f64>,
        beta_z: Vec<f64>,
        beta_i: Vec<f64>,
        beta_p: Vec<f64>,
    },
    /// Exponential voltage model by active phase. `v_nom` is volts per active
    /// phase.
    Exponential {
        v_nom: Vec<f64>,
        gamma_p: Vec<f64>,
        gamma_q: Vec<f64>,
    },
}

impl Default for DistLoadVoltageModel {
    fn default() -> Self {
        Self::ConstantPower { v_nom: Vec::new() }
    }
}

impl DistLoadVoltageModel {
    #[must_use]
    pub fn v_nom(&self) -> &[f64] {
        match self {
            Self::ConstantPower { v_nom }
            | Self::ConstantCurrent { v_nom }
            | Self::ConstantImpedance { v_nom }
            | Self::Zip { v_nom, .. }
            | Self::Exponential { v_nom, .. } => v_nom,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistGenerator {
    pub name: String,
    pub bus: String,
    pub terminal_map: Vec<String>,
    pub configuration: Configuration,
    /// Setpoint, watts per phase.
    pub p_nom: Vec<f64>,
    pub q_nom: Vec<f64>,
    pub p_min: Option<Vec<f64>>,
    pub p_max: Option<Vec<f64>>,
    pub q_min: Option<Vec<f64>>,
    pub q_max: Option<Vec<f64>>,
    /// $/kWh; no OpenDSS equivalent, so it is None until a format supplies it.
    pub cost: Option<f64>,
    pub extras: Extras,
}

impl DistGenerator {
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        bus: impl Into<String>,
        terminal_map: Vec<String>,
        configuration: Configuration,
        p_nom: Vec<f64>,
        q_nom: Vec<f64>,
    ) -> Self {
        Self {
            name: name.into(),
            bus: bus.into(),
            terminal_map,
            configuration,
            p_nom,
            q_nom,
            p_min: None,
            p_max: None,
            q_min: None,
            q_max: None,
            cost: None,
            extras: Extras::new(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum IbrTopology {
    SinglePhase,
    ThreeLeg,
    FourLeg,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum IbrPrimeMover {
    Pv,
    Battery,
    Generic,
    Statcom,
    Dstatcom,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum IbrVoltageAggregation {
    PerPhase,
    Average,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistIbr {
    pub name: String,
    pub bus: String,
    pub terminal_map: Vec<String>,
    pub topology: IbrTopology,
    pub prime_mover: IbrPrimeMover,
    /// Per phase apparent power nameplate ratings, volt amperes.
    pub s_max: Vec<f64>,
    /// Per conductor current limits, amperes.
    pub i_max: Option<Vec<f64>>,
    /// Available active power, watts.
    pub p_avail: Option<f64>,
    pub p_min: Option<Vec<f64>>,
    pub p_max: Option<Vec<f64>>,
    pub q_min: Option<Vec<f64>>,
    pub q_max: Option<Vec<f64>>,
    pub control_profile: Option<String>,
    pub voltage_aggregation: Option<IbrVoltageAggregation>,
    pub extras: Extras,
}

impl DistIbr {
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        bus: impl Into<String>,
        terminal_map: Vec<String>,
        topology: IbrTopology,
        prime_mover: IbrPrimeMover,
        s_max: Vec<f64>,
    ) -> Self {
        Self {
            name: name.into(),
            bus: bus.into(),
            terminal_map,
            topology,
            prime_mover,
            s_max,
            i_max: None,
            p_avail: None,
            p_min: None,
            p_max: None,
            q_min: None,
            q_max: None,
            control_profile: None,
            voltage_aggregation: None,
            extras: Extras::new(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum ControlVoltageReference {
    PnPerPhase,
    PpPerPhase,
    PpAveraged,
    PgAveraged,
    PnAveraged,
    PgPerPhase,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum ReactivePowerUnit {
    VaFraction,
    Var,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum ActivePowerUnit {
    VaFraction,
    W,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum ReactivePowerReference {
    VarMax,
    VarAvailable,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum ActivePowerReference {
    PAvailable,
    PMax,
    SMax,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct PowerFactorControl {
    pub pf: f64,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct VoltVarControl {
    pub voltage_reference: Option<ControlVoltageReference>,
    pub breakpoints: Vec<f64>,
    pub q_limits: Vec<f64>,
    pub q_unit: Option<ReactivePowerUnit>,
    pub q_ref: Option<ReactivePowerReference>,
    pub p_min_for_q: Option<f64>,
    pub p_min_for_q_max: Option<f64>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct VoltWattControl {
    pub voltage_reference: Option<ControlVoltageReference>,
    pub breakpoints: Vec<f64>,
    pub p_limits: Vec<f64>,
    pub p_unit: Option<ActivePowerUnit>,
    pub p_ref: Option<ActivePowerReference>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistControlProfile {
    pub name: String,
    pub power_factor: Option<PowerFactorControl>,
    pub volt_var: Option<VoltVarControl>,
    pub volt_watt: Option<VoltWattControl>,
    pub extras: Extras,
}

impl DistControlProfile {
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            power_factor: None,
            volt_var: None,
            volt_watt: None,
            extras: Extras::new(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistShunt {
    pub name: String,
    pub bus: String,
    pub terminal_map: Vec<String>,
    /// Total siemens in conductor order.
    pub g: Mat,
    pub b: Mat,
    pub extras: Extras,
}

impl DistShunt {
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        bus: impl Into<String>,
        terminal_map: Vec<String>,
        g: Mat,
        b: Mat,
    ) -> Self {
        Self {
            name: name.into(),
            bus: bus.into(),
            terminal_map,
            g,
            b,
            extras: Extras::new(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum WindingConn {
    Wye,
    Delta,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct Winding {
    pub bus: String,
    pub terminal_map: Vec<String>,
    pub conn: WindingConn,
    /// Rated winding voltage, volts (line to line for 2 and 3 phase).
    pub v_ref: f64,
    /// Volt amperes.
    pub s_rating: f64,
    /// Winding resistance, percent of the winding base.
    pub r_pct: f64,
    pub tap: f64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r_neutral: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub x_neutral: Option<f64>,
}

impl Winding {
    #[must_use]
    pub fn new(
        bus: impl Into<String>,
        terminal_map: Vec<String>,
        conn: WindingConn,
        v_ref: f64,
        s_rating: f64,
    ) -> Self {
        Self {
            bus: bus.into(),
            terminal_map,
            conn,
            v_ref,
            s_rating,
            r_pct: 0.0,
            tap: 1.0,
            r_neutral: None,
            x_neutral: None,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistTransformer {
    pub name: String,
    pub windings: Vec<Winding>,
    /// Short circuit reactances between winding pairs, percent:
    /// `[xhl]` for two windings, `[xhl, xht, xlt]` for three.
    pub xsc_pct: Vec<f64>,
    pub phases: usize,
    pub extras: Extras,
}

impl DistTransformer {
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        windings: Vec<Winding>,
        xsc_pct: Vec<f64>,
        phases: usize,
    ) -> Self {
        Self {
            name: name.into(),
            windings,
            xsc_pct,
            phases,
            extras: Extras::new(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct VoltageSource {
    pub name: String,
    pub bus: String,
    pub terminal_map: Vec<String>,
    /// Volts per terminal (0.0 on grounded terminals).
    pub v_magnitude: Vec<f64>,
    /// Radians per terminal.
    pub v_angle: Vec<f64>,
    pub extras: Extras,
}

impl VoltageSource {
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        bus: impl Into<String>,
        terminal_map: Vec<String>,
        v_magnitude: Vec<f64>,
        v_angle: Vec<f64>,
    ) -> Self {
        Self {
            name: name.into(),
            bus: bus.into(),
            terminal_map,
            v_magnitude,
            v_angle,
            extras: Extras::new(),
        }
    }
}

/// An object the reader recognized but does not type: preserved by class,
/// name, and raw property text so conversions can warn precisely.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct UntypedObject {
    pub class: String,
    pub name: String,
    pub props: Vec<(Option<String>, String)>,
}

impl UntypedObject {
    #[must_use]
    pub fn new(
        class: impl Into<String>,
        name: impl Into<String>,
        props: Vec<(Option<String>, String)>,
    ) -> Self {
        Self {
            class: class.into(),
            name: name.into(),
            props,
        }
    }
}

/// A multiconductor distribution network.
///
/// `source` retains the original text for the byte exact echo tier;
/// `defaulted` records, per element (`"class.name"` key), the fields the
/// reader materialized from format defaults rather than the source text.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DistNetwork {
    pub name: Option<String>,
    /// Hz.
    pub base_frequency: f64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub geo: Option<GeoMeta>,
    pub buses: Vec<DistBus>,
    pub linecodes: Vec<DistLineCode>,
    pub lines: Vec<DistLine>,
    pub switches: Vec<DistSwitch>,
    pub transformers: Vec<DistTransformer>,
    pub loads: Vec<DistLoad>,
    pub generators: Vec<DistGenerator>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ibrs: Vec<DistIbr>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub control_profiles: Vec<DistControlProfile>,
    pub shunts: Vec<DistShunt>,
    /// BMOPF allows exactly one; the model allows any number and the BMOPF
    /// writer warns beyond the first.
    pub sources: Vec<VoltageSource>,
    pub untyped: Vec<UntypedObject>,
    /// Source commands and options the typed model does not interpret
    /// (`solve`, `set mode=...`), in order, as (verb, args).
    pub commands: Vec<(String, String)>,
    pub options: Vec<(String, String)>,
    /// Per-element record of which fields were materialized from a format
    /// default. Skipped in the `.pio.json` payload: the field holds
    /// `&'static str` (no `Deserialize`), and this provenance belongs in the
    /// compiler package's `source_maps` as `mapping_kind = defaulted`, not in
    /// the raw IR payload. See
    /// <https://eigenergy.github.io/powerio/guide/pio-json-schema.html>.
    #[serde(skip)]
    pub defaulted: BTreeMap<String, Vec<&'static str>>,
    pub warnings: Vec<String>,
    /// Retained source text for the byte-exact echo tier. Skipped in the
    /// `.pio.json` payload (mirrors `powerio::Network::source`): keeping it out
    /// avoids serde's `rc` feature, and retained source is an envelope concern
    /// surfaced through `Origin::File { retained_source, .. }`.
    #[serde(skip)]
    pub source: Option<Arc<String>>,
    pub source_format: Option<DistSourceFormat>,
    pub extras: Extras,
}

/// v1-facing name for the canonical multiconductor distribution model.
pub type MulticonductorNetwork = DistNetwork;

impl Default for DistNetwork {
    /// An empty network at the OpenDSS default frequency. A derived 0 Hz
    /// default would put NaN into every capacitance the dss writer converts
    /// through omega.
    fn default() -> Self {
        DistNetwork {
            name: None,
            base_frequency: crate::dss::defaults::BASE_FREQUENCY,
            geo: None,
            buses: Vec::new(),
            linecodes: Vec::new(),
            lines: Vec::new(),
            switches: Vec::new(),
            transformers: Vec::new(),
            loads: Vec::new(),
            generators: Vec::new(),
            ibrs: Vec::new(),
            control_profiles: Vec::new(),
            shunts: Vec::new(),
            sources: Vec::new(),
            untyped: Vec::new(),
            commands: Vec::new(),
            options: Vec::new(),
            defaulted: BTreeMap::new(),
            warnings: Vec::new(),
            source: None,
            source_format: None,
            extras: Extras::new(),
        }
    }
}

impl DistNetwork {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn named(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            ..Self::default()
        }
    }

    /// Case insensitive, matching the source formats' name semantics.
    pub fn bus(&self, id: &str) -> Option<&DistBus> {
        self.buses.iter().find(|b| b.id.eq_ignore_ascii_case(id))
    }

    /// Case insensitive, matching the source formats' name semantics.
    pub fn linecode(&self, name: &str) -> Option<&DistLineCode> {
        self.linecodes
            .iter()
            .find(|c| c.name.eq_ignore_ascii_case(name))
    }
}

fn zero_mat(n: usize) -> Mat {
    vec![vec![0.0; n]; n]
}

fn matrix_extent(m: &Mat) -> usize {
    m.iter().map(Vec::len).fold(m.len(), usize::max)
}

/// Windings per phase for an n-winding transformer terminal map: WYE counts
/// the hot terminals (excluding the shared neutral), DELTA counts terminals
/// directly except the phase to phase two terminal case.
pub(crate) fn n_winding_phase_count(conn: WindingConn, terminal_map: &[String]) -> usize {
    match conn {
        WindingConn::Wye => terminal_map.len().saturating_sub(1).max(1),
        WindingConn::Delta => {
            if terminal_map.len() == 2 {
                1
            } else {
                terminal_map.len().max(1)
            }
        }
    }
}

/// `phases * v_nom^2 / s`, the impedance base for an n-winding transformer
/// winding, or `None` if any input isn't a positive finite number.
pub(crate) fn n_winding_impedance_base(phases: usize, v_nom: f64, s: f64) -> Option<f64> {
    let phases = phases as f64;
    (phases > 0.0 && v_nom.is_finite() && v_nom > 0.0 && s.is_finite() && s > 0.0)
        .then_some(phases * v_nom * v_nom / s)
}

/// Upper triangular `(i, j)` winding index pairs for `n` windings, the order
/// short circuit test pairs (`x_sc`/`xsc_pct`) are keyed by.
pub(crate) fn pair_keys(n: usize) -> Vec<(usize, usize)> {
    let mut pairs = Vec::new();
    for i in 0..n {
        for j in i + 1..n {
            pairs.push((i, j));
        }
    }
    pairs
}

/// Builds an `n`x`n` matrix from lower triangle rows (the OpenDSS matrix
/// entry convention) or full rows; symmetric completion for the triangle.
pub(crate) fn square_from_rows(rows: &[Vec<f64>], n: usize) -> Option<Mat> {
    let mut m = vec![vec![0.0; n]; n];
    if rows.len() != n {
        return None;
    }
    let lower = rows.iter().enumerate().all(|(i, r)| r.len() == i + 1);
    let full = rows.iter().all(|r| r.len() == n);
    if lower {
        for (i, row) in rows.iter().enumerate() {
            for (j, &v) in row.iter().enumerate() {
                m[i][j] = v;
                m[j][i] = v;
            }
        }
    } else if full {
        for (i, row) in rows.iter().enumerate() {
            m[i].clone_from_slice(&row[..n]);
        }
    } else {
        return None;
    }
    Some(m)
}

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

    #[test]
    #[allow(clippy::float_cmp)]
    fn lower_triangle_completes_symmetrically() {
        let rows = vec![vec![1.0], vec![0.5, 2.0], vec![0.3, 0.4, 3.0]];
        let m = square_from_rows(&rows, 3).unwrap();
        assert_eq!(m[0][1], 0.5);
        assert_eq!(m[1][0], 0.5);
        assert_eq!(m[2][2], 3.0);
        assert_eq!(m[0][2], 0.3);
    }

    #[test]
    #[allow(clippy::float_cmp)]
    fn full_rows_pass_through() {
        let rows = vec![vec![1.0, 9.0], vec![8.0, 2.0]];
        let m = square_from_rows(&rows, 2).unwrap();
        assert_eq!(m[0][1], 9.0);
        assert_eq!(m[1][0], 8.0);
    }

    #[test]
    fn wrong_shape_is_rejected() {
        assert!(square_from_rows(&[vec![1.0], vec![2.0]], 2).is_none());
        assert!(square_from_rows(&[vec![1.0, 2.0]], 2).is_none());
    }
}