1use std::collections::BTreeMap;
17
18use serde::{Deserialize, Serialize};
19
20use crate::geo::{DistGeoMeta, DistLocation};
21
22mod bus_index;
23mod located_network;
24
25pub type Extras = BTreeMap<String, serde_json::Value>;
26
27pub type ConductorMatrix = Vec<Vec<f64>>;
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
32#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
33#[serde(rename_all = "kebab-case")]
34#[non_exhaustive]
35pub enum DistSourceFormat {
36 Dss,
37 BmopfJson,
38 PmdJson,
39 CimDist,
40 Sincal,
41 RavensJson,
45 PmdMathJson,
47 PandapowerJson,
49}
50
51impl DistSourceFormat {
52 pub fn name(self) -> &'static str {
55 match self {
56 DistSourceFormat::Sincal => "sincal",
57 DistSourceFormat::Dss => "dss",
58 DistSourceFormat::PmdJson => "pmd-json",
59 DistSourceFormat::BmopfJson => "bmopf-json",
60 DistSourceFormat::CimDist => "cim-dist",
61 DistSourceFormat::RavensJson => "ravens-json",
62 DistSourceFormat::PmdMathJson => "pmd-math-json",
63 DistSourceFormat::PandapowerJson => "pandapower-json",
64 }
65 }
66}
67
68#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
69#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
70#[non_exhaustive]
71pub struct DistBus {
72 pub id: String,
73 pub terminals: Vec<String>,
75 pub grounded: Vec<String>,
77 pub v_min: Option<f64>,
83 pub v_max: Option<f64>,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub v_min_phase: Option<Vec<f64>>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub v_max_phase: Option<Vec<f64>>,
90 pub vpn_min: Option<Vec<f64>>,
91 pub vpn_max: Option<Vec<f64>>,
92 pub vpp_min: Option<Vec<f64>>,
93 pub vpp_max: Option<Vec<f64>>,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub vpos_min: Option<f64>,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub vpos_max: Option<f64>,
98 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub vneg_max: Option<f64>,
100 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub vzero_max: Option<f64>,
102 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub vn_max: Option<f64>,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub location: Option<DistLocation>,
107 pub extras: Extras,
108}
109
110impl DistBus {
111 #[must_use]
114 pub fn terminal_role(
115 &self,
116 terminal: &str,
117 conventions: Option<&serde_json::Value>,
118 ) -> TerminalRole {
119 calc_terminal_role(&self.terminals, terminal, conventions)
120 }
121
122 #[must_use]
126 pub fn phase_indices(&self, conventions: Option<&serde_json::Value>) -> Vec<usize> {
127 self.role_indices(TerminalRole::Phase, conventions)
128 }
129
130 #[must_use]
133 pub fn neutral_indices(&self, conventions: Option<&serde_json::Value>) -> Vec<usize> {
134 self.role_indices(TerminalRole::Neutral, conventions)
135 }
136
137 fn role_indices(
138 &self,
139 role: TerminalRole,
140 conventions: Option<&serde_json::Value>,
141 ) -> Vec<usize> {
142 self.terminals
143 .iter()
144 .enumerate()
145 .filter(|(_, terminal)| self.terminal_role(terminal, conventions) == role)
146 .map(|(index, _)| index)
147 .collect()
148 }
149
150 #[must_use]
151 pub fn new(id: impl Into<String>, terminals: Vec<String>) -> Self {
152 Self {
153 id: id.into(),
154 terminals,
155 grounded: Vec::new(),
156 v_min: None,
157 v_max: None,
158 v_min_phase: None,
159 v_max_phase: None,
160 vpn_min: None,
161 vpn_max: None,
162 vpp_min: None,
163 vpp_max: None,
164 vpos_min: None,
165 vpos_max: None,
166 vneg_max: None,
167 vzero_max: None,
168 vn_max: None,
169 location: None,
170 extras: Extras::new(),
171 }
172 }
173}
174
175#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
177#[non_exhaustive]
178pub enum TerminalRole {
179 Phase,
181 Neutral,
183 Earth,
185}
186
187#[must_use]
203pub fn calc_terminal_role<S: AsRef<str>>(
204 terminals: &[S],
205 terminal: &str,
206 conventions: Option<&serde_json::Value>,
207) -> TerminalRole {
208 if terminal == "0" {
209 return TerminalRole::Earth;
210 }
211 if let Some(roles) = conventions {
212 let named = |role: &str| {
213 roles
214 .get(role)
215 .and_then(serde_json::Value::as_array)
216 .is_some_and(|names| names.iter().any(|name| name.as_str() == Some(terminal)))
217 };
218 return if named("neutral") {
219 TerminalRole::Neutral
220 } else if named("earth") {
221 TerminalRole::Earth
222 } else {
223 TerminalRole::Phase
224 };
225 }
226 let numeric_four = terminals.len() == 4
227 && ["1", "2", "3", "4"]
228 .iter()
229 .all(|t| terminals.iter().any(|v| v.as_ref() == *t));
230 if terminal.eq_ignore_ascii_case("n") || (numeric_four && terminal == "4") {
231 TerminalRole::Neutral
232 } else {
233 TerminalRole::Phase
234 }
235}
236
237#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
238#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
239#[non_exhaustive]
240pub struct DistLineCode {
241 pub name: String,
242 pub n_conductors: usize,
243 pub r_series: ConductorMatrix,
245 pub x_series: ConductorMatrix,
246 pub g_from: ConductorMatrix,
248 pub b_from: ConductorMatrix,
249 pub g_to: ConductorMatrix,
250 pub b_to: ConductorMatrix,
251 #[serde(default)]
253 pub i_max: Option<Vec<f64>>,
254 #[serde(default)]
255 pub s_max: Option<Vec<f64>>,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
259 pub source: Option<String>,
260 pub extras: Extras,
261}
262
263impl DistLineCode {
264 #[must_use]
265 pub fn new(
266 name: impl Into<String>,
267 r_series: ConductorMatrix,
268 x_series: ConductorMatrix,
269 ) -> Self {
270 let n_conductors = matrix_extent(&r_series).max(matrix_extent(&x_series));
271 Self {
272 name: name.into(),
273 n_conductors,
274 r_series,
275 x_series,
276 g_from: zero_mat(n_conductors),
277 b_from: zero_mat(n_conductors),
278 g_to: zero_mat(n_conductors),
279 b_to: zero_mat(n_conductors),
280 i_max: None,
281 s_max: None,
282 source: None,
283 extras: Extras::new(),
284 }
285 }
286}
287
288#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
289#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
290#[non_exhaustive]
291pub struct DistLine {
292 pub name: String,
293 pub bus_from: String,
294 pub bus_to: String,
295 pub terminal_map_from: Vec<String>,
296 pub terminal_map_to: Vec<String>,
297 pub linecode: String,
298 pub length: f64,
300 #[serde(default, skip_serializing_if = "Option::is_none")]
305 pub route: Option<Vec<DistLocation>>,
306 #[serde(default, skip_serializing_if = "Option::is_none")]
309 pub i_max: Option<Vec<f64>>,
310 #[serde(default, skip_serializing_if = "Option::is_none")]
311 pub s_max: Option<Vec<f64>>,
312 pub extras: Extras,
313}
314
315impl DistLine {
316 #[must_use]
317 pub fn new(
318 name: impl Into<String>,
319 bus_from: impl Into<String>,
320 bus_to: impl Into<String>,
321 terminal_map_from: Vec<String>,
322 terminal_map_to: Vec<String>,
323 linecode: impl Into<String>,
324 length: f64,
325 ) -> Self {
326 Self {
327 name: name.into(),
328 bus_from: bus_from.into(),
329 bus_to: bus_to.into(),
330 terminal_map_from,
331 terminal_map_to,
332 linecode: linecode.into(),
333 length,
334 route: None,
335 i_max: None,
336 s_max: None,
337 extras: Extras::new(),
338 }
339 }
340}
341
342#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
348#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
349#[non_exhaustive]
350pub struct DistCapacitor {
351 pub name: String,
352 pub bus: String,
353 pub terminal_map: Vec<String>,
354 pub configuration: Configuration,
355 pub q_rated: f64,
357 pub v_nom: f64,
360 pub extras: Extras,
361}
362
363impl DistCapacitor {
364 #[must_use]
365 pub fn new(
366 name: impl Into<String>,
367 bus: impl Into<String>,
368 terminal_map: Vec<String>,
369 configuration: Configuration,
370 q_rated: f64,
371 v_nom: f64,
372 ) -> Self {
373 Self {
374 name: name.into(),
375 bus: bus.into(),
376 terminal_map,
377 configuration,
378 q_rated,
379 v_nom,
380 extras: Extras::new(),
381 }
382 }
383}
384
385#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
386#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
387#[non_exhaustive]
388pub struct DistSwitch {
389 pub name: String,
390 pub bus_from: String,
391 pub bus_to: String,
392 pub terminal_map_from: Vec<String>,
393 pub terminal_map_to: Vec<String>,
394 pub open: bool,
395 #[serde(default)]
397 pub i_max: Option<Vec<f64>>,
398 pub extras: Extras,
399}
400
401impl DistSwitch {
402 #[must_use]
403 pub fn new(
404 name: impl Into<String>,
405 bus_from: impl Into<String>,
406 bus_to: impl Into<String>,
407 terminal_map_from: Vec<String>,
408 terminal_map_to: Vec<String>,
409 open: bool,
410 ) -> Self {
411 Self {
412 name: name.into(),
413 bus_from: bus_from.into(),
414 bus_to: bus_to.into(),
415 terminal_map_from,
416 terminal_map_to,
417 open,
418 i_max: None,
419 extras: Extras::new(),
420 }
421 }
422}
423
424#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
425#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
426#[serde(rename_all = "snake_case")]
427#[non_exhaustive]
428pub enum Configuration {
429 Wye,
430 Delta,
431 SinglePhase,
432}
433
434#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
435#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
436#[non_exhaustive]
437pub struct DistLoad {
438 pub name: String,
439 pub bus: String,
440 pub terminal_map: Vec<String>,
441 pub configuration: Configuration,
442 pub p_nom: Vec<f64>,
444 pub q_nom: Vec<f64>,
446 pub voltage_model: DistLoadVoltageModel,
447 pub extras: Extras,
448}
449
450impl DistLoad {
451 #[must_use]
452 pub fn new(
453 name: impl Into<String>,
454 bus: impl Into<String>,
455 terminal_map: Vec<String>,
456 configuration: Configuration,
457 p_nom: Vec<f64>,
458 q_nom: Vec<f64>,
459 ) -> Self {
460 Self {
461 name: name.into(),
462 bus: bus.into(),
463 terminal_map,
464 configuration,
465 p_nom,
466 q_nom,
467 voltage_model: DistLoadVoltageModel::default(),
468 extras: Extras::new(),
469 }
470 }
471}
472
473#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
474#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
475#[serde(tag = "model", rename_all = "snake_case")]
476#[non_exhaustive]
477pub enum DistLoadVoltageModel {
478 ConstantPower { v_nom: Vec<f64> },
481 ConstantCurrent { v_nom: Vec<f64> },
483 ConstantImpedance { v_nom: Vec<f64> },
485 Zip {
489 v_nom: Vec<f64>,
490 alpha_z: Vec<f64>,
491 alpha_i: Vec<f64>,
492 alpha_p: Vec<f64>,
493 beta_z: Vec<f64>,
494 beta_i: Vec<f64>,
495 beta_p: Vec<f64>,
496 },
497 Exponential {
500 v_nom: Vec<f64>,
501 gamma_p: Vec<f64>,
502 gamma_q: Vec<f64>,
503 },
504 BoundedZip {
509 v_nom: Vec<f64>,
510 alpha_z: Vec<f64>,
511 alpha_i: Vec<f64>,
512 alpha_p: Vec<f64>,
513 beta_z: Vec<f64>,
514 beta_i: Vec<f64>,
515 beta_p: Vec<f64>,
516 v_low_pu: f64,
517 v_min_pu: f64,
518 v_max_pu: f64,
519 cutoff_pu: f64,
520 },
521 BoundedExponential {
527 v_nom: Vec<f64>,
528 gamma_p: Vec<f64>,
529 gamma_q: Vec<f64>,
530 v_low_pu: f64,
531 v_min_pu: f64,
532 v_max_pu: f64,
533 },
534 BoundedConstantPower {
540 v_nom: Vec<f64>,
541 v_min_pu: f64,
542 v_max_pu: f64,
543 current_limit_pu: Option<f64>,
544 },
545}
546
547impl Default for DistLoadVoltageModel {
548 fn default() -> Self {
549 Self::ConstantPower { v_nom: Vec::new() }
550 }
551}
552
553impl DistLoadVoltageModel {
554 #[must_use]
555 pub fn v_nom(&self) -> &[f64] {
556 match self {
557 Self::ConstantPower { v_nom }
558 | Self::ConstantCurrent { v_nom }
559 | Self::ConstantImpedance { v_nom }
560 | Self::Zip { v_nom, .. }
561 | Self::Exponential { v_nom, .. }
562 | Self::BoundedZip { v_nom, .. }
563 | Self::BoundedConstantPower { v_nom, .. }
564 | Self::BoundedExponential { v_nom, .. } => v_nom,
565 }
566 }
567}
568
569#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
570#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
571#[non_exhaustive]
572pub struct DistGenerator {
573 pub name: String,
574 pub bus: String,
575 pub terminal_map: Vec<String>,
576 pub configuration: Configuration,
577 pub p_nom: Vec<f64>,
579 pub q_nom: Vec<f64>,
580 #[serde(default)]
582 pub p_min: Option<Vec<f64>>,
583 #[serde(default)]
584 pub p_max: Option<Vec<f64>>,
585 #[serde(default)]
586 pub q_min: Option<Vec<f64>>,
587 #[serde(default)]
588 pub q_max: Option<Vec<f64>>,
589 pub cost: Option<Vec<f64>>,
594 #[serde(default, skip_serializing_if = "Option::is_none")]
597 pub s_max: Option<Vec<f64>>,
598 #[serde(default, skip_serializing_if = "Option::is_none")]
599 pub i_max: Option<Vec<f64>>,
600 pub extras: Extras,
601}
602
603impl DistGenerator {
604 #[must_use]
605 pub fn new(
606 name: impl Into<String>,
607 bus: impl Into<String>,
608 terminal_map: Vec<String>,
609 configuration: Configuration,
610 p_nom: Vec<f64>,
611 q_nom: Vec<f64>,
612 ) -> Self {
613 Self {
614 name: name.into(),
615 bus: bus.into(),
616 terminal_map,
617 configuration,
618 p_nom,
619 q_nom,
620 p_min: None,
621 p_max: None,
622 q_min: None,
623 q_max: None,
624 cost: None,
625 s_max: None,
626 i_max: None,
627 extras: Extras::new(),
628 }
629 }
630}
631
632#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
633#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
634#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
635#[non_exhaustive]
636pub enum IbrTopology {
637 SinglePhase,
638 ThreeLeg,
639 FourLeg,
640}
641
642#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
643#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
644#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
645#[non_exhaustive]
646pub enum IbrPrimeMover {
647 Pv,
648 Battery,
649 Generic,
650 Statcom,
651 Dstatcom,
652}
653
654#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
655#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
656#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
657#[non_exhaustive]
658pub enum IbrVoltageAggregation {
659 PerPhase,
660 Average,
661}
662
663#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
664#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
665#[non_exhaustive]
666pub struct DistIbr {
667 pub name: String,
668 pub bus: String,
669 pub terminal_map: Vec<String>,
670 pub topology: IbrTopology,
671 pub prime_mover: IbrPrimeMover,
672 pub s_max: Vec<f64>,
674 #[serde(default)]
676 pub i_max: Option<Vec<f64>>,
677 pub p_avail: Option<f64>,
679 #[serde(default)]
680 pub p_min: Option<Vec<f64>>,
681 #[serde(default)]
682 pub p_max: Option<Vec<f64>>,
683 #[serde(default)]
684 pub q_min: Option<Vec<f64>>,
685 #[serde(default)]
686 pub q_max: Option<Vec<f64>>,
687 pub control_profile: Option<String>,
688 pub voltage_aggregation: Option<IbrVoltageAggregation>,
689 pub extras: Extras,
690}
691
692impl DistIbr {
693 #[must_use]
694 pub fn new(
695 name: impl Into<String>,
696 bus: impl Into<String>,
697 terminal_map: Vec<String>,
698 topology: IbrTopology,
699 prime_mover: IbrPrimeMover,
700 s_max: Vec<f64>,
701 ) -> Self {
702 Self {
703 name: name.into(),
704 bus: bus.into(),
705 terminal_map,
706 topology,
707 prime_mover,
708 s_max,
709 i_max: None,
710 p_avail: None,
711 p_min: None,
712 p_max: None,
713 q_min: None,
714 q_max: None,
715 control_profile: None,
716 voltage_aggregation: None,
717 extras: Extras::new(),
718 }
719 }
720}
721
722#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
723#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
724#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
725#[non_exhaustive]
726pub enum ControlVoltageReference {
727 PnPerPhase,
728 PpPerPhase,
729 PpAveraged,
730 PgAveraged,
731 PnAveraged,
732 PgPerPhase,
733}
734
735#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
736#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
737#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
738#[non_exhaustive]
739pub enum ReactivePowerUnit {
740 VaFraction,
741 Var,
742}
743
744#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
745#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
746#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
747#[non_exhaustive]
748pub enum ActivePowerUnit {
749 VaFraction,
750 W,
751}
752
753#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
754#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
755#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
756#[non_exhaustive]
757pub enum ReactivePowerReference {
758 VarMax,
759 VarAvailable,
760}
761
762#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
763#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
764#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
765#[non_exhaustive]
766pub enum ActivePowerReference {
767 PAvailable,
768 PMax,
769 SMax,
770}
771
772#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
773#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
774#[non_exhaustive]
775pub struct PowerFactorControl {
776 pub pf: f64,
777}
778
779#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
780#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
781#[non_exhaustive]
782pub struct VoltVarControl {
783 pub voltage_reference: Option<ControlVoltageReference>,
784 pub breakpoints: Vec<f64>,
785 pub q_limits: Vec<f64>,
786 pub q_unit: Option<ReactivePowerUnit>,
787 pub q_ref: Option<ReactivePowerReference>,
788 pub p_min_for_q: Option<f64>,
789 pub p_min_for_q_max: Option<f64>,
790}
791
792#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
793#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
794#[non_exhaustive]
795pub struct VoltWattControl {
796 pub voltage_reference: Option<ControlVoltageReference>,
797 pub breakpoints: Vec<f64>,
798 pub p_limits: Vec<f64>,
799 pub p_unit: Option<ActivePowerUnit>,
800 pub p_ref: Option<ActivePowerReference>,
801}
802
803#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
804#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
805#[non_exhaustive]
806pub struct DistControlProfile {
807 pub name: String,
808 pub power_factor: Option<PowerFactorControl>,
809 pub volt_var: Option<VoltVarControl>,
810 pub volt_watt: Option<VoltWattControl>,
811 pub extras: Extras,
812}
813
814impl DistControlProfile {
815 #[must_use]
816 pub fn new(name: impl Into<String>) -> Self {
817 Self {
818 name: name.into(),
819 power_factor: None,
820 volt_var: None,
821 volt_watt: None,
822 extras: Extras::new(),
823 }
824 }
825}
826
827#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
828#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
829#[non_exhaustive]
830pub struct DistShunt {
831 pub name: String,
832 pub bus: String,
833 pub terminal_map: Vec<String>,
834 pub g: ConductorMatrix,
836 pub b: ConductorMatrix,
837 pub extras: Extras,
838}
839
840impl DistShunt {
841 #[must_use]
842 pub fn new(
843 name: impl Into<String>,
844 bus: impl Into<String>,
845 terminal_map: Vec<String>,
846 g: ConductorMatrix,
847 b: ConductorMatrix,
848 ) -> Self {
849 Self {
850 name: name.into(),
851 bus: bus.into(),
852 terminal_map,
853 g,
854 b,
855 extras: Extras::new(),
856 }
857 }
858}
859
860#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
861#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
862#[serde(rename_all = "snake_case")]
863#[non_exhaustive]
864pub enum DistWindingConn {
865 Wye,
866 Delta,
867}
868
869#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
870#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
871#[non_exhaustive]
872pub struct DistWinding {
873 pub bus: String,
874 pub terminal_map: Vec<String>,
875 pub conn: DistWindingConn,
876 pub v_ref: f64,
878 pub s_rating: f64,
880 pub r_pct: f64,
882 pub tap: f64,
883 #[serde(default, skip_serializing_if = "Option::is_none")]
884 pub r_neutral: Option<f64>,
885 #[serde(default, skip_serializing_if = "Option::is_none")]
886 pub x_neutral: Option<f64>,
887}
888
889impl DistWinding {
890 #[must_use]
891 pub fn new(
892 bus: impl Into<String>,
893 terminal_map: Vec<String>,
894 conn: DistWindingConn,
895 v_ref: f64,
896 s_rating: f64,
897 ) -> Self {
898 Self {
899 bus: bus.into(),
900 terminal_map,
901 conn,
902 v_ref,
903 s_rating,
904 r_pct: 0.0,
905 tap: 1.0,
906 r_neutral: None,
907 x_neutral: None,
908 }
909 }
910}
911
912#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
913#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
914#[non_exhaustive]
915pub struct DistTransformer {
916 pub name: String,
917 pub windings: Vec<DistWinding>,
918 pub xsc_pct: Vec<f64>,
922 pub phases: usize,
923 pub extras: Extras,
924}
925
926impl DistTransformer {
927 #[must_use]
928 pub fn new(
929 name: impl Into<String>,
930 windings: Vec<DistWinding>,
931 xsc_pct: Vec<f64>,
932 phases: usize,
933 ) -> Self {
934 Self {
935 name: name.into(),
936 windings,
937 xsc_pct,
938 phases,
939 extras: Extras::new(),
940 }
941 }
942}
943
944mod voltage_source;
945pub use voltage_source::VoltageSource;
946
947#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
950#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
951#[non_exhaustive]
952pub struct UntypedObject {
953 pub class: String,
954 pub name: String,
955 pub props: Vec<(Option<String>, String)>,
956}
957
958impl UntypedObject {
959 #[must_use]
960 pub fn new(
961 class: impl Into<String>,
962 name: impl Into<String>,
963 props: Vec<(Option<String>, String)>,
964 ) -> Self {
965 Self {
966 class: class.into(),
967 name: name.into(),
968 props,
969 }
970 }
971}
972
973#[derive(Clone)]
986pub struct MulticonductorNetwork {
987 tables: std::sync::Arc<MulticonductorNetworkTables>,
988 bus_index: std::sync::Arc<bus_index::BusIndex>,
991}
992
993#[allow(clippy::missing_fields_in_debug)]
995impl std::fmt::Debug for MulticonductorNetwork {
996 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
997 f.debug_struct("MulticonductorNetwork")
998 .field("tables", &self.tables)
999 .finish()
1000 }
1001}
1002
1003impl MulticonductorNetwork {
1004 pub(crate) fn from_tables(tables: MulticonductorNetworkTables) -> Self {
1005 Self {
1006 tables: std::sync::Arc::new(tables),
1007 bus_index: std::sync::Arc::default(),
1008 }
1009 }
1010
1011 pub(crate) fn tables_mut(&mut self) -> &mut MulticonductorNetworkTables {
1018 match std::sync::Arc::get_mut(&mut self.bus_index) {
1019 Some(index) => index.clear(),
1020 None => self.bus_index = std::sync::Arc::default(),
1021 }
1022 std::sync::Arc::make_mut(&mut self.tables)
1023 }
1024}
1025
1026#[derive(Clone, Debug, Serialize, Deserialize)]
1033#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1034#[cfg_attr(feature = "schema", schemars(rename = "MulticonductorNetwork"))]
1035#[serde(remote = "Self")]
1036pub(crate) struct MulticonductorNetworkTables {
1037 pub name: Option<String>,
1038 pub base_frequency: f64,
1040 #[serde(default, skip_serializing_if = "Option::is_none")]
1041 pub geo: Option<DistGeoMeta>,
1042 #[serde(skip)]
1045 pub component_locations: Vec<crate::DistComponentLocation>,
1046 pub buses: Vec<DistBus>,
1047 #[serde(rename = "linecodes")]
1048 pub line_codes: Vec<DistLineCode>,
1049 pub lines: Vec<DistLine>,
1050 pub switches: Vec<DistSwitch>,
1051 pub transformers: Vec<DistTransformer>,
1052 pub loads: Vec<DistLoad>,
1053 pub generators: Vec<DistGenerator>,
1054 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1055 pub ibrs: Vec<DistIbr>,
1056 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1057 pub control_profiles: Vec<DistControlProfile>,
1058 pub shunts: Vec<DistShunt>,
1059 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1060 pub capacitors: Vec<DistCapacitor>,
1061 pub sources: Vec<VoltageSource>,
1064 #[serde(rename = "untyped")]
1065 pub untyped_objects: Vec<UntypedObject>,
1066 pub commands: Vec<(String, String)>,
1069 pub options: Vec<(String, String)>,
1070 #[serde(skip)]
1077 pub defaulted: BTreeMap<String, Vec<&'static str>>,
1078 pub source_format: Option<DistSourceFormat>,
1079 pub extras: Extras,
1080}
1081
1082impl serde::Serialize for MulticonductorNetwork {
1087 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1088 located_network::serialize(self, serializer)
1089 }
1090}
1091
1092impl<'de> serde::Deserialize<'de> for MulticonductorNetwork {
1093 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1094 located_network::deserialize(deserializer)
1095 }
1096}
1097
1098#[cfg(feature = "schema")]
1099impl schemars::JsonSchema for MulticonductorNetwork {
1100 fn schema_name() -> std::borrow::Cow<'static, str> {
1101 <MulticonductorNetworkTables as schemars::JsonSchema>::schema_name()
1102 }
1103
1104 fn schema_id() -> std::borrow::Cow<'static, str> {
1105 <MulticonductorNetworkTables as schemars::JsonSchema>::schema_id()
1106 }
1107
1108 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1109 located_network::json_schema(generator)
1110 }
1111}
1112
1113macro_rules! dist_table_accessors {
1114 ($($field:ident, $field_mut:ident: $ty:ty;)+) => {
1115 impl MulticonductorNetwork {
1116 $(
1117 #[must_use]
1118 pub fn $field(&self) -> &$ty {
1119 &self.tables.$field
1120 }
1121
1122 #[must_use]
1126 pub fn $field_mut(&mut self) -> &mut $ty {
1127 &mut self.tables_mut().$field
1128 }
1129 )+
1130 }
1131 };
1132}
1133
1134dist_table_accessors! {
1135 name, name_mut: Option<String>;
1136 geo, geo_mut: Option<DistGeoMeta>;
1137 component_locations, component_locations_mut: Vec<crate::DistComponentLocation>;
1138 buses, buses_mut: Vec<DistBus>;
1139 line_codes, line_codes_mut: Vec<DistLineCode>;
1140 lines, lines_mut: Vec<DistLine>;
1141 switches, switches_mut: Vec<DistSwitch>;
1142 transformers, transformers_mut: Vec<DistTransformer>;
1143 loads, loads_mut: Vec<DistLoad>;
1144 generators, generators_mut: Vec<DistGenerator>;
1145 ibrs, ibrs_mut: Vec<DistIbr>;
1146 control_profiles, control_profiles_mut: Vec<DistControlProfile>;
1147 shunts, shunts_mut: Vec<DistShunt>;
1148 capacitors, capacitors_mut: Vec<DistCapacitor>;
1149 sources, sources_mut: Vec<VoltageSource>;
1150 untyped_objects, untyped_objects_mut: Vec<UntypedObject>;
1151 commands, commands_mut: Vec<(String, String)>;
1152 options, options_mut: Vec<(String, String)>;
1153 defaulted, defaulted_mut: BTreeMap<String, Vec<&'static str>>;
1154 source_format, source_format_mut: Option<DistSourceFormat>;
1155 extras, extras_mut: Extras;
1156}
1157
1158impl MulticonductorNetwork {
1159 #[must_use]
1166 pub fn terminal_conventions(&self) -> Option<&serde_json::Value> {
1167 self.tables
1168 .extras
1169 .get("bmopf_terminal_conventions")
1170 .or_else(|| match self.tables.source_format {
1171 Some(DistSourceFormat::CimDist | DistSourceFormat::RavensJson) => {
1172 Some(crate::cim::wire_conventions())
1173 }
1174 _ => None,
1175 })
1176 }
1177
1178 #[must_use]
1180 pub fn base_frequency(&self) -> f64 {
1181 self.tables.base_frequency
1182 }
1183
1184 #[must_use]
1185 pub fn base_frequency_mut(&mut self) -> &mut f64 {
1186 &mut self.tables_mut().base_frequency
1187 }
1188
1189 #[must_use]
1194 pub fn identifier_key(&self, name: &str) -> String {
1195 if self.tables.source_format == Some(crate::model::DistSourceFormat::Dss) {
1196 name.to_ascii_lowercase()
1197 } else {
1198 name.to_owned()
1199 }
1200 }
1201}
1202
1203impl Default for MulticonductorNetwork {
1204 fn default() -> Self {
1205 MulticonductorNetwork::from_tables(MulticonductorNetworkTables::default())
1206 }
1207}
1208
1209impl Default for MulticonductorNetworkTables {
1210 fn default() -> Self {
1214 MulticonductorNetworkTables {
1215 name: None,
1216 base_frequency: crate::dss::defaults::BASE_FREQUENCY,
1217 geo: None,
1218 component_locations: Vec::new(),
1219 buses: Vec::new(),
1220 line_codes: Vec::new(),
1221 lines: Vec::new(),
1222 switches: Vec::new(),
1223 transformers: Vec::new(),
1224 loads: Vec::new(),
1225 generators: Vec::new(),
1226 ibrs: Vec::new(),
1227 control_profiles: Vec::new(),
1228 shunts: Vec::new(),
1229 capacitors: Vec::new(),
1230 sources: Vec::new(),
1231 untyped_objects: Vec::new(),
1232 commands: Vec::new(),
1233 options: Vec::new(),
1234 defaulted: BTreeMap::new(),
1235 source_format: None,
1236 extras: Extras::new(),
1237 }
1238 }
1239}
1240
1241impl MulticonductorNetwork {
1242 #[must_use]
1243 pub fn new() -> Self {
1244 Self::default()
1245 }
1246
1247 #[must_use]
1248 pub fn named(name: impl Into<String>) -> Self {
1249 MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
1250 name: Some(name.into()),
1251 ..MulticonductorNetworkTables::default()
1252 })
1253 }
1254
1255 pub fn bus(&self, id: &str) -> Option<&DistBus> {
1257 self.bus_index.find(self.buses(), id)
1258 }
1259
1260 pub fn linecode(&self, name: &str) -> Option<&DistLineCode> {
1262 self.line_codes()
1263 .iter()
1264 .find(|c| c.name.eq_ignore_ascii_case(name))
1265 }
1266}
1267
1268pub(crate) fn warn_defaulted_frequency(
1274 net: &MulticonductorNetwork,
1275 field: &str,
1276 diags: &mut crate::collect::Diagnostics,
1277) {
1278 let charging = net.line_codes().iter().any(|c| {
1279 [&c.b_from, &c.b_to]
1280 .iter()
1281 .flat_map(|m| m.iter())
1282 .flatten()
1283 .any(|v| v.is_finite() && v.abs() > 0.0)
1284 });
1285 if charging {
1286 diags.push(
1287 &crate::diagnostics::codes::READ_MULTICONDUCTOR_VALUE_DEFAULTED,
1288 format!(
1289 "document states no {field} and carries line susceptance; read at {} Hz",
1290 net.base_frequency()
1291 ),
1292 );
1293 }
1294}
1295
1296#[must_use]
1307pub fn find_unresolved_references(net: &MulticonductorNetwork) -> Vec<String> {
1308 let mut diags = crate::collect::Diagnostics::new();
1309 warn_unresolved_references(net, &mut diags);
1310 diags
1311 .into_records()
1312 .into_iter()
1313 .map(|record| record.message().to_owned())
1314 .collect()
1315}
1316
1317pub(crate) fn warn_unresolved_references(
1318 net: &MulticonductorNetwork,
1319 diags: &mut crate::collect::Diagnostics,
1320) {
1321 use std::collections::BTreeSet;
1322 let buses: BTreeSet<String> = net
1323 .buses()
1324 .iter()
1325 .map(|b| b.id.to_ascii_lowercase())
1326 .collect();
1327 let linecodes: BTreeSet<String> = net
1328 .line_codes()
1329 .iter()
1330 .map(|c| c.name.to_ascii_lowercase())
1331 .collect();
1332 let mut warnings = Vec::new();
1333 {
1334 let mut bus = |what: &str, field: &str, id: &str| {
1335 if id.is_empty() {
1336 warnings.push(format!("{what}: `{field}` reference is empty or missing"));
1337 } else if !buses.contains(&id.to_ascii_lowercase()) {
1338 warnings.push(format!("{what}: references undefined bus `{id}`"));
1339 }
1340 };
1341 for l in net.lines() {
1342 let what = format!("line {}", l.name);
1343 bus(&what, "bus_from", &l.bus_from);
1344 bus(&what, "bus_to", &l.bus_to);
1345 }
1346 for sw in net.switches() {
1347 let what = format!("switch {}", sw.name);
1348 bus(&what, "bus_from", &sw.bus_from);
1349 bus(&what, "bus_to", &sw.bus_to);
1350 }
1351 for t in net.transformers() {
1352 let what = format!("transformer {}", t.name);
1353 for w in &t.windings {
1354 bus(&what, "bus", &w.bus);
1355 }
1356 }
1357 for (what, id) in std::iter::empty()
1358 .chain(
1359 net.loads()
1360 .iter()
1361 .map(|x| (format!("load {}", x.name), &x.bus)),
1362 )
1363 .chain(
1364 net.generators()
1365 .iter()
1366 .map(|x| (format!("generator {}", x.name), &x.bus)),
1367 )
1368 .chain(
1369 net.shunts()
1370 .iter()
1371 .map(|x| (format!("shunt {}", x.name), &x.bus)),
1372 )
1373 .chain(
1374 net.capacitors()
1375 .iter()
1376 .map(|x| (format!("capacitor {}", x.name), &x.bus)),
1377 )
1378 .chain(
1379 net.ibrs()
1380 .iter()
1381 .map(|x| (format!("ibr {}", x.name), &x.bus)),
1382 )
1383 .chain(
1384 net.sources()
1385 .iter()
1386 .map(|x| (format!("voltage_source {}", x.name), &x.bus)),
1387 )
1388 {
1389 bus(&what, "bus", id);
1390 }
1391 }
1392 for l in net.lines() {
1393 if l.linecode.is_empty() {
1394 warnings.push(format!(
1395 "line {}: `linecode` reference is empty or missing",
1396 l.name
1397 ));
1398 } else if !linecodes.contains(&l.linecode.to_ascii_lowercase()) {
1399 warnings.push(format!(
1400 "line {}: references undefined linecode `{}`",
1401 l.name, l.linecode
1402 ));
1403 }
1404 }
1405 for message in warnings {
1406 diags.push(
1407 &crate::diagnostics::codes::VALIDATE_MULTICONDUCTOR_REFERENCE_UNDEFINED,
1408 message,
1409 );
1410 }
1411}
1412
1413fn zero_mat(n: usize) -> ConductorMatrix {
1414 vec![vec![0.0; n]; n]
1415}
1416
1417fn matrix_extent(m: &ConductorMatrix) -> usize {
1418 m.iter().map(Vec::len).fold(m.len(), usize::max)
1419}
1420
1421pub(crate) fn winding_phase_pair(winding: &DistWinding) -> Option<(u8, u8)> {
1424 let [first, second] = winding.terminal_map.as_slice() else {
1425 return None;
1426 };
1427 let phase = |term: &String| term.parse::<u8>().ok().filter(|n| (1..=3).contains(n));
1428 match (phase(first), phase(second)) {
1429 (Some(lead), Some(lag)) if lead != lag => Some((lead, lag)),
1430 _ => None,
1431 }
1432}
1433
1434pub(crate) fn open_delta_connection(a: (u8, u8), b: (u8, u8)) -> Option<(&'static str, bool)> {
1438 match (a, b) {
1439 ((1, 2), (2, 3)) => Some(("ABBC", false)),
1440 ((2, 3), (1, 2)) => Some(("ABBC", true)),
1441 ((2, 3), (1, 3)) => Some(("BCAC", false)),
1442 ((1, 3), (2, 3)) => Some(("BCAC", true)),
1443 ((3, 1), (2, 1)) => Some(("CABA", false)),
1444 ((2, 1), (3, 1)) => Some(("CABA", true)),
1445 _ => None,
1446 }
1447}
1448
1449pub(crate) fn open_delta_pairable(a: &DistTransformer, b: &DistTransformer) -> bool {
1453 let ([a0, a1], [b0, b1]) = (a.windings.as_slice(), b.windings.as_slice()) else {
1454 return false;
1455 };
1456 let eq = |x: f64, y: f64| x.to_bits() == y.to_bits();
1457 eq(a0.v_ref, b0.v_ref)
1458 && eq(a1.v_ref, b1.v_ref)
1459 && eq(a0.s_rating, b0.s_rating)
1460 && eq(a1.s_rating, b1.s_rating)
1461 && eq(a0.r_pct, b0.r_pct)
1462 && eq(a1.r_pct, b1.r_pct)
1463 && a.xsc_pct.len() == b.xsc_pct.len()
1464 && a.xsc_pct.iter().zip(&b.xsc_pct).all(|(x, y)| eq(*x, *y))
1465 && ["%noloadloss", "%imag", "g_no_load", "b_no_load"]
1466 .iter()
1467 .all(|k| a.extras.get(*k) == b.extras.get(*k))
1468}
1469
1470pub(crate) fn pair_keys(n: usize) -> Vec<(usize, usize)> {
1473 let mut pairs = Vec::new();
1474 for i in 0..n {
1475 for j in i + 1..n {
1476 pairs.push((i, j));
1477 }
1478 }
1479 pairs
1480}
1481
1482pub(crate) fn transformer_no_load_percentages(t: &DistTransformer) -> Option<(f64, f64)> {
1485 let shunt = t.extras.get("no_load_shunt")?;
1486 if shunt.get("winding")?.as_u64()? != 2 {
1487 return None;
1488 }
1489 let g = shunt.get("g")?.as_f64()?;
1490 let b = shunt.get("b")?.as_f64()?;
1491 let voltage = crate::transformer::calc_coil_voltage(t, 1) * t.windings.get(1)?.tap;
1492 let rating = t.windings.first()?.s_rating;
1493 if !voltage.is_finite()
1494 || voltage <= 0.0
1495 || !rating.is_finite()
1496 || rating <= 0.0
1497 || g < 0.0
1498 || b > 0.0
1499 {
1500 return None;
1501 }
1502 let scale = 100.0
1503 * t.phases.max(1) as f64
1504 * powerio_core::electrical::calc_impedance_base(voltage, rating)?;
1505 Some((g * scale, -b * scale))
1506}
1507
1508#[cfg(test)]
1509mod tests {
1510 use super::*;
1511
1512 #[test]
1513 fn terminal_roles_follow_the_conventions_or_the_spellings() {
1514 let four = ["1", "2", "3", "4"];
1515 assert_eq!(calc_terminal_role(&four, "4", None), TerminalRole::Neutral);
1516 assert_eq!(
1517 calc_terminal_role(&["1", "4"], "4", None),
1518 TerminalRole::Phase
1519 );
1520 assert_eq!(
1521 calc_terminal_role(&["a", "N"], "N", None),
1522 TerminalRole::Neutral
1523 );
1524 assert_eq!(calc_terminal_role(&["1"], "0", None), TerminalRole::Earth);
1525 let conventions = serde_json::json!({"neutral": ["x"], "earth": ["g"]});
1526 let names = ["1", "x", "g", "n"];
1527 let role = |t| calc_terminal_role(&names, t, Some(&conventions));
1528 assert_eq!(role("x"), TerminalRole::Neutral);
1529 assert_eq!(role("g"), TerminalRole::Earth);
1530 assert_eq!(role("n"), TerminalRole::Phase);
1531 let bus = DistBus::new("b", names.iter().map(|t| (*t).to_owned()).collect());
1532 assert_eq!(bus.phase_indices(Some(&conventions)), vec![0, 3]);
1533 assert_eq!(bus.neutral_indices(Some(&conventions)), vec![1]);
1534 assert_eq!(bus.neutral_indices(None), vec![3]);
1535 }
1536
1537 #[test]
1538 fn multiconductor_json_uses_only_final_nonfinite_spellings() {
1539 let mut network = MulticonductorNetwork::named("strict-ir");
1540 let mut code = DistLineCode::new("lc", vec![vec![0.1]], vec![vec![0.2]]);
1541 code.i_max = Some(vec![f64::INFINITY]);
1542 network.line_codes_mut().push(code);
1543
1544 let text = serde_json::to_string(&network).unwrap();
1545 assert!(text.contains(r#""i_max":["Infinity"]"#), "{text}");
1546
1547 let invalid = text.replace(r#""i_max":["Infinity"]"#, r#""i_max":[null]"#);
1548 let error = serde_json::from_str::<MulticonductorNetwork>(&invalid).unwrap_err();
1549 assert!(error.to_string().contains("cannot be null"), "{error}");
1550 }
1551}