1use std::collections::BTreeMap;
12
13use num_complex::Complex64;
14
15use crate::diagnostics::codes;
16use crate::{
17 Configuration, ConnectionChannel, DistTransformer, DistWinding, DistWindingConn,
18 MulticonductorNetwork, calc_element_connection, orient_delta_ring,
19};
20
21type Result<T> = std::result::Result<T, powerio_core::Error>;
22
23fn unsupported(name: &str, reason: impl std::fmt::Display) -> powerio_core::Error {
24 powerio_core::Error::new(
25 &codes::BUILD_DIST_TRANSFORMER_UNSUPPORTED,
26 format!("transformer `{name}` is unsupported: {reason}"),
27 )
28}
29
30fn invalid(
31 name: &str,
32 field: impl std::fmt::Display,
33 reason: impl std::fmt::Display,
34) -> powerio_core::Error {
35 powerio_core::Error::new(
36 &codes::BUILD_DIST_TRANSFORMER_INVALID,
37 format!("transformer `{name}` has invalid {field}: {reason}"),
38 )
39}
40
41fn invalid_leakage(transformer: &DistTransformer, reason: &str) -> powerio_core::Error {
42 invalid(&transformer.name, "leakage data", reason)
43}
44
45#[must_use]
51pub fn transformer_extra_number(
52 extras: &BTreeMap<String, serde_json::Value>,
53 key: &str,
54) -> Option<f64> {
55 extras.get(key).map(|value| {
56 value
57 .as_f64()
58 .or_else(|| value.as_str()?.trim().parse().ok())
59 .unwrap_or(f64::NAN)
60 })
61}
62
63fn subtype(transformer: &DistTransformer) -> Option<&str> {
64 transformer
65 .extras
66 .get("bmopf_subtype")
67 .and_then(serde_json::Value::as_str)
68}
69
70fn uses_autotransformer_impedance(transformer: &DistTransformer) -> bool {
74 subtype(transformer) == Some("single_phase_autotransformer")
75 && (transformer.xsc_pct.is_empty()
76 || [
77 "r_series_from",
78 "x_series_from",
79 "r_series_to",
80 "x_series_to",
81 ]
82 .iter()
83 .any(|key| transformer.extras.contains_key(*key)))
84}
85
86#[must_use]
90pub fn is_transformer_regulator(transformer: &DistTransformer) -> bool {
91 matches!(
92 subtype(transformer),
93 Some("single_phase_autotransformer" | "open_delta_regulator")
94 )
95}
96
97#[derive(Clone, Debug, PartialEq)]
105#[non_exhaustive]
106pub enum TransformerLeakageBase {
107 Nameplate,
111 WindingPhase {
115 power_base: f64,
118 phases: Vec<f64>,
120 },
121 StatedOhms,
128}
129
130pub fn calc_transformer_leakage_impedances(
158 transformer: &DistTransformer,
159 base: &TransformerLeakageBase,
160) -> Result<Vec<Vec<Complex64>>> {
161 let windings = &transformer.windings;
162 let count = windings.len();
163 if count < 2 {
164 return Err(invalid_leakage(transformer, "fewer than two windings"));
165 }
166 if let TransformerLeakageBase::StatedOhms = base {
167 return stated_ohms_leakage(transformer);
168 }
169 if windings
170 .iter()
171 .any(|w| !w.s_rating.is_finite() || w.s_rating <= 0.0 || !w.r_pct.is_finite())
172 {
173 return Err(invalid_leakage(
174 transformer,
175 "a winding rating is not finite and positive or a resistance is not finite",
176 ));
177 }
178 if transformer.xsc_pct.len() != count * (count - 1) / 2 {
179 return Err(invalid_leakage(
180 transformer,
181 "xsc_pct does not state one reactance per winding pair",
182 ));
183 }
184 let (reference_rating, winding_base): (f64, Vec<f64>) = match base {
185 TransformerLeakageBase::WindingPhase { power_base, phases } => {
186 if !power_base.is_finite() || *power_base <= 0.0 {
187 return Err(invalid_leakage(
188 transformer,
189 "the power base is not finite and positive",
190 ));
191 }
192 if phases.len() != count || phases.iter().any(|p| !p.is_finite() || *p <= 0.0) {
193 return Err(invalid_leakage(
194 transformer,
195 "a winding phase count is missing or not finite and positive",
196 ));
197 }
198 (
199 power_base / phases[0],
200 windings
201 .iter()
202 .zip(phases)
203 .map(|(w, p)| w.s_rating / p)
204 .collect(),
205 )
206 }
207 _ => (
208 windings[0].s_rating,
209 windings.iter().map(|w| w.s_rating).collect(),
210 ),
211 };
212 let resistance: Vec<f64> = windings
213 .iter()
214 .zip(&winding_base)
215 .map(|(w, base)| w.r_pct / 100.0 * reference_rating / base)
216 .collect();
217 let mut impedance = vec![vec![Complex64::new(0.0, 0.0); count]; count];
218 let mut pair = 0;
219 for a in 0..count {
220 for b in a + 1..count {
221 let z = Complex64::new(
222 resistance[a] + resistance[b],
223 transformer.xsc_pct[pair] / 100.0,
224 );
225 impedance[a][b] = z;
226 impedance[b][a] = z;
227 pair += 1;
228 }
229 }
230 Ok(impedance)
231}
232
233fn stated_ohms_leakage(transformer: &DistTransformer) -> Result<Vec<Vec<Complex64>>> {
236 if transformer.windings.len() != 2 {
237 return Err(invalid_leakage(
238 transformer,
239 "a stated ohmic impedance needs exactly two windings",
240 ));
241 }
242 let tap = transformer.windings[1].tap;
243 if !tap.is_finite() || tap <= 0.0 {
244 return Err(invalid_leakage(
245 transformer,
246 "the regulated winding tap is not finite and positive",
247 ));
248 }
249 let n = 1.0 / tap;
250 let [r_from, x_from, r_to, x_to] = calc_regulator_series_ohms(transformer)?;
251 let z = Complex64::new(r_from + n.powi(2) * r_to, x_from + n.powi(2) * x_to);
252 let zero = Complex64::new(0.0, 0.0);
253 Ok(vec![vec![zero, z], vec![z, zero]])
254}
255
256pub fn calc_regulator_series_ohms(transformer: &DistTransformer) -> Result<[f64; 4]> {
265 let read = |key: &str| -> Result<f64> {
266 let value = transformer_extra_number(&transformer.extras, key).unwrap_or(0.0);
267 if !value.is_finite() || value < 0.0 {
268 return Err(invalid_leakage(
269 transformer,
270 &format!("{key} must be finite and nonnegative"),
271 ));
272 }
273 Ok(value)
274 };
275 Ok([
276 read("r_series_from")?,
277 read("x_series_from")?,
278 read("r_series_to")?,
279 read("x_series_to")?,
280 ])
281}
282
283#[must_use]
300pub fn calc_reduced_leakage(leakage: &[Vec<Complex64>], reference: usize) -> Vec<Vec<Complex64>> {
301 assert!(reference < leakage.len(), "reference winding out of range");
302 let others: Vec<usize> = (0..leakage.len()).filter(|&w| w != reference).collect();
303 others
304 .iter()
305 .map(|&i| {
306 others
307 .iter()
308 .map(|&j| {
309 if i == j {
310 leakage[i][reference]
311 } else {
312 (leakage[i][reference] + leakage[j][reference] - leakage[i][j]) / 2.0
313 }
314 })
315 .collect()
316 })
317 .collect()
318}
319
320pub fn calc_transformer_winding_admittance(
336 transformer: &DistTransformer,
337) -> Result<Option<Vec<Vec<Complex64>>>> {
338 let leakage =
339 calc_transformer_leakage_impedances(transformer, &TransformerLeakageBase::Nameplate)?;
340 if transformer.phases == 0 {
341 return Err(invalid_leakage(transformer, "zero phases"));
342 }
343 let count = leakage.len();
344 let reference = count - 1;
345 let base = transformer.phases as f64 / transformer.windings[0].s_rating;
346 let scaled: Vec<Vec<Complex64>> = leakage
347 .iter()
348 .map(|row| row.iter().map(|z| z * base).collect())
349 .collect();
350 let reduced = calc_reduced_leakage(&scaled, reference);
351 let finite = |value: &Complex64| value.re.is_finite() && value.im.is_finite();
352 if reduced.iter().flatten().any(|value| !finite(value)) {
353 return Ok(None);
354 }
355 let Some(inverse) =
356 crate::dense::invert_dense_matrix(&reduced, crate::dense::DensePivot::Partial, 0.0, 0.0)
357 else {
358 return Ok(None);
359 };
360 if inverse.iter().flatten().any(|value| !finite(value)) {
361 return Ok(None);
362 }
363 let mut admittance = vec![vec![Complex64::new(0.0, 0.0); count]; count];
364 for i in 0..reference {
365 for j in 0..reference {
366 let value = inverse[i][j];
367 admittance[i][j] += value;
368 admittance[i][reference] -= value;
369 admittance[reference][j] -= value;
370 admittance[reference][reference] += value;
371 }
372 }
373 Ok(Some(admittance))
374}
375
376#[must_use]
382pub fn calc_coil_voltage_ratio(conn: DistWindingConn, phases: usize) -> f64 {
383 if conn == DistWindingConn::Wye && matches!(phases, 2 | 3) {
384 crate::electrical::SQRT_3
385 } else {
386 1.0
387 }
388}
389
390#[must_use]
396pub fn calc_coil_voltage(transformer: &DistTransformer, winding: usize) -> f64 {
397 let w = &transformer.windings[winding];
398 w.v_ref / calc_coil_voltage_ratio(w.conn, transformer.phases)
399}
400
401#[must_use]
406pub fn calc_winding_phase_count(conn: DistWindingConn, terminal_map: &[String]) -> usize {
407 match conn {
408 DistWindingConn::Wye => terminal_map.len().saturating_sub(1).max(1),
409 DistWindingConn::Delta => {
410 if terminal_map.len() == 2 {
411 1
412 } else {
413 terminal_map.len().max(1)
414 }
415 }
416 }
417}
418
419#[must_use]
427pub fn calc_winding_impedance_base(
428 transformer: &DistTransformer,
429 winding: usize,
430 power: f64,
431) -> Option<f64> {
432 let w = &transformer.windings[winding];
433 let phases = calc_winding_phase_count(w.conn, &w.terminal_map);
434 powerio_core::electrical::calc_impedance_base(
435 calc_coil_voltage(transformer, winding),
436 power / phases as f64,
437 )
438}
439
440fn low_voltage_leads(transformer: &DistTransformer) -> Result<bool> {
445 let Some(value) = transformer.extras.get("leadlag") else {
446 return Ok(false);
447 };
448 match value.as_str().map(str::to_ascii_lowercase).as_deref() {
449 Some("lead" | "euro") => Ok(true),
450 Some("lag" | "ansi") => Ok(false),
451 _ => Err(invalid(
452 &transformer.name,
453 "leadlag",
454 "expected lead, lag, ansi or euro",
455 )),
456 }
457}
458
459pub fn calc_delta_direction(transformer: &DistTransformer, winding: usize) -> Result<i8> {
478 if let Some(rolls) = transformer.extras.get("bmopf_delta_rolls") {
479 let rolls = rolls
480 .as_object()
481 .ok_or_else(|| invalid(&transformer.name, "bmopf_delta_rolls", "must be an object"))?;
482 if let Some(roll) = rolls.get(&(winding + 1).to_string()) {
483 return match roll.as_i64() {
484 Some(1) => Ok(1),
485 Some(-1) => Ok(-1),
486 _ => Err(invalid(
487 &transformer.name,
488 "bmopf_delta_rolls",
489 "a delta roll must be +1 or -1",
490 )),
491 };
492 }
493 }
494 match subtype(transformer) {
495 Some("n_winding" | "wye_delta") => return Ok(1),
496 Some("delta_wye") => return Ok(-1),
497 _ => {}
498 }
499 let lv_leads = low_voltage_leads(transformer)?;
500 let [a, b, ..] = transformer.windings.as_slice() else {
501 return Ok(1);
502 };
503 if a.conn == b.conn {
504 return Ok(1);
505 }
506 let hv = if a.v_ref >= b.v_ref { a } else { b };
507 Ok(match (hv.conn, lv_leads) {
508 (DistWindingConn::Delta, false) | (DistWindingConn::Wye, true) => -1,
509 _ => 1,
510 })
511}
512
513pub fn calc_transformer_phase_shift(transformer: &DistTransformer) -> Result<f64> {
520 if transformer.windings.len() < 2 {
521 return Err(unsupported(
522 &transformer.name,
523 "a phase shift needs two windings",
524 ));
525 }
526 calc_winding_phase_shift(transformer, 1)
527}
528
529pub(crate) fn calc_winding_phase_shift(
540 transformer: &DistTransformer,
541 winding: usize,
542) -> Result<f64> {
543 let (Some(a), Some(b)) = (
544 transformer.windings.first(),
545 transformer.windings.get(winding),
546 ) else {
547 return Err(unsupported(
548 &transformer.name,
549 format!("winding {} is outside the unit", winding + 1),
550 ));
551 };
552 if a.conn == b.conn {
553 return Ok(0.0);
554 }
555 if a.conn == DistWindingConn::Delta {
556 Ok(-30.0 * f64::from(calc_delta_direction(transformer, 0)?))
557 } else {
558 Ok(30.0 * f64::from(calc_delta_direction(transformer, winding)?))
559 }
560}
561
562fn terminal_count(w: &DistWinding, phases: usize) -> usize {
566 if phases == 1 {
567 2.min(w.terminal_map.len())
568 } else if w.conn == DistWindingConn::Wye {
569 (phases + 1).min(w.terminal_map.len())
570 } else {
571 phases
572 }
573}
574
575pub fn calc_winding_connection(
587 network: &MulticonductorNetwork,
588 transformer: &DistTransformer,
589 winding: usize,
590) -> Result<Vec<ConnectionChannel>> {
591 let name = transformer.name.as_str();
592 let w = transformer
593 .windings
594 .get(winding)
595 .ok_or_else(|| invalid(name, format!("windings[{winding}]"), "is not stated"))?;
596 let phases = transformer.phases;
597 let configuration = if phases == 1 {
598 Configuration::SinglePhase
599 } else if w.conn == DistWindingConn::Wye {
600 Configuration::Wye
601 } else {
602 Configuration::Delta
603 };
604 let count = terminal_count(w, phases);
605 let map = w.terminal_map.get(..count).ok_or_else(|| {
606 invalid(
607 name,
608 format!("windings[{winding}].terminal_map"),
609 format!("expected {count} terminals"),
610 )
611 })?;
612 let mut channels =
613 calc_element_connection(network, &w.bus, map, configuration, Some(phases))
614 .map_err(|reason| invalid(name, format!("windings[{winding}].terminal_map"), reason))?;
615 if configuration == Configuration::Delta {
616 orient_delta_ring(&mut channels, calc_delta_direction(transformer, winding)?);
617 }
618 Ok(channels)
619}
620
621#[derive(Clone, Copy, Debug, PartialEq)]
624#[non_exhaustive]
625pub struct TransformerMagnetizing {
626 pub winding: usize,
628 pub admittance: Complex64,
630}
631
632#[allow(clippy::too_many_lines)] pub fn calc_transformer_magnetizing(
655 transformer: &DistTransformer,
656) -> Result<Option<TransformerMagnetizing>> {
657 let name = transformer.name.as_str();
658 let windings = transformer.windings.len();
659 let explicit = transformer.extras.get("no_load_shunt");
660 let legacy = transformer_extra_number(&transformer.extras, "g_no_load")
661 .or_else(|| transformer_extra_number(&transformer.extras, "b_no_load"))
662 .is_some();
663 if explicit.is_some() && legacy {
664 return Err(invalid(
665 name,
666 "no_load_shunt",
667 "cannot coexist with g_no_load or b_no_load",
668 ));
669 }
670 let checked = |field: &str, g: f64, b: f64| -> Result<Complex64> {
671 if !g.is_finite() || g < 0.0 || !b.is_finite() {
672 return Err(invalid(name, field, "requires finite g >= 0 and finite b"));
673 }
674 Ok(Complex64::new(g, b))
675 };
676 if let Some(shunt) = explicit {
677 let object = shunt.as_object().ok_or_else(|| {
678 invalid(
679 name,
680 "no_load_shunt",
681 "expected an object containing winding, g, and b",
682 )
683 })?;
684 if let Some(key) = object
685 .keys()
686 .find(|key| !["winding", "g", "b"].contains(&key.as_str()))
687 {
688 return Err(invalid(
689 name,
690 "no_load_shunt",
691 format!("unknown field `{key}`"),
692 ));
693 }
694 let winding = object
695 .get("winding")
696 .and_then(serde_json::Value::as_u64)
697 .and_then(|w| usize::try_from(w).ok())
698 .filter(|w| *w >= 1 && *w <= windings)
699 .ok_or_else(|| {
700 invalid(
701 name,
702 "no_load_shunt.winding",
703 format!("must be a one based winding between 1 and {windings}"),
704 )
705 })?;
706 let component = |key: &str| {
707 object
708 .get(key)
709 .and_then(serde_json::Value::as_f64)
710 .ok_or_else(|| invalid(name, format!("no_load_shunt.{key}"), "expected siemens"))
711 };
712 return Ok(Some(TransformerMagnetizing {
713 winding: winding - 1,
714 admittance: checked("no_load_shunt", component("g")?, component("b")?)?,
715 }));
716 }
717 if legacy {
718 let g = transformer_extra_number(&transformer.extras, "g_no_load").unwrap_or(0.0);
719 let b = transformer_extra_number(&transformer.extras, "b_no_load").unwrap_or(0.0);
720 let admittance = checked("g_no_load/b_no_load", g, b)?;
721 let winding = usize::from(!is_transformer_regulator(transformer));
722 if winding >= windings {
723 return Err(invalid(
724 name,
725 "g_no_load/b_no_load",
726 "has no winding to sit on",
727 ));
728 }
729 let divisor = if matches!(
730 subtype(transformer),
731 Some("single_phase" | "wye_delta" | "delta_wye")
732 ) {
733 transformer.phases.max(1) as f64
734 } else {
735 1.0
736 };
737 return Ok(Some(TransformerMagnetizing {
738 winding,
739 admittance: admittance / divisor,
740 }));
741 }
742 let loss = transformer_extra_number(&transformer.extras, "%noloadloss");
743 let imag = transformer_extra_number(&transformer.extras, "%imag");
744 if loss.is_none() && imag.is_none() {
745 return Ok(None);
746 }
747 let loss = loss.unwrap_or(0.0);
748 let imag = imag.unwrap_or(0.0);
749 if !loss.is_finite() || loss < 0.0 || !imag.is_finite() || imag < 0.0 {
750 return Err(invalid(
751 name,
752 "%noloadloss/%imag",
753 "requires finite nonnegative percentages",
754 ));
755 }
756 if windings < 2 || transformer.phases == 0 {
757 return Err(invalid(
758 name,
759 "%noloadloss/%imag",
760 "needs a second winding and a phase",
761 ));
762 }
763 let v = calc_coil_voltage(transformer, 1) * transformer.windings[1].tap;
764 let ybase = crate::electrical::calc_squared_voltage_admittance(
765 transformer.windings[0].s_rating,
766 transformer.phases as f64 * v * v,
767 );
768 Ok(Some(TransformerMagnetizing {
769 winding: 1,
770 admittance: Complex64::new(loss / 100.0 * ybase, -imag / 100.0 * ybase),
771 }))
772}
773
774#[derive(Clone, Copy, Debug, PartialEq)]
776#[non_exhaustive]
777pub enum WindingNeutralGrounding {
778 Unstated,
781 Floating,
784 Solid,
787 Impedance(Complex64),
790}
791
792#[must_use]
801pub fn calc_stated_neutral_grounding(winding: &DistWinding) -> WindingNeutralGrounding {
802 if winding.r_neutral.is_none() && winding.x_neutral.is_none() {
803 return WindingNeutralGrounding::Unstated;
804 }
805 let r = winding.r_neutral.unwrap_or(0.0);
806 let x = winding.x_neutral.unwrap_or(0.0);
807 if r < 0.0 {
808 WindingNeutralGrounding::Floating
809 } else if r == 0.0 && x == 0.0 {
810 WindingNeutralGrounding::Solid
811 } else {
812 WindingNeutralGrounding::Impedance(Complex64::new(1.0, 0.0) / Complex64::new(r, x))
813 }
814}
815
816pub fn calc_winding_neutral_grounding(
823 transformer: &DistTransformer,
824 winding: usize,
825) -> Result<WindingNeutralGrounding> {
826 let name = transformer.name.as_str();
827 let w = &transformer.windings[winding];
828 let stated = [w.r_neutral, w.x_neutral];
829 if stated.iter().any(Option::is_some) && !stated.iter().flatten().all(|v| v.is_finite()) {
830 return Err(invalid(
831 name,
832 format!("windings[{winding}].neutral impedance"),
833 "expected finite resistance and reactance",
834 ));
835 }
836 let grounding = calc_stated_neutral_grounding(w);
837 if w.conn == DistWindingConn::Delta
838 && !matches!(
839 grounding,
840 WindingNeutralGrounding::Floating | WindingNeutralGrounding::Unstated
841 )
842 {
843 return Err(unsupported(
844 name,
845 "neutral impedance on a delta winding has no physical neutral terminal",
846 ));
847 }
848 Ok(grounding)
849}
850
851#[must_use]
856pub fn calc_coil_shunt_primitive(
857 y: Complex64,
858 returns_through_ground: bool,
859) -> Vec<Vec<Complex64>> {
860 if returns_through_ground {
861 vec![vec![y]]
862 } else {
863 vec![vec![y, -y], vec![-y, y]]
864 }
865}
866
867#[derive(Clone, Debug)]
873#[non_exhaustive]
874pub struct TransformerPrimitive<'a> {
875 pub name: &'a str,
876 pub terminals: Vec<(&'a str, &'a str)>,
878 pub series: Vec<Vec<Complex64>>,
880 pub shunt: Vec<Vec<Complex64>>,
882 pub primitive: Vec<Vec<Complex64>>,
884 pub grounded: Vec<(&'a str, &'a str)>,
888 pub delta_direction: i8,
891 pub winding_admittance: Vec<Vec<Complex64>>,
895}
896
897#[must_use]
903pub fn transformer_states_no_leakage(transformer: &DistTransformer) -> bool {
904 if uses_autotransformer_impedance(transformer) {
905 return [
906 "r_series_from",
907 "x_series_from",
908 "r_series_to",
909 "x_series_to",
910 ]
911 .iter()
912 .all(|key| {
913 transformer_extra_number(&transformer.extras, key).is_none_or(|value| value == 0.0)
914 });
915 }
916 transformer.xsc_pct.iter().all(|value| *value == 0.0)
917 && transformer.windings.iter().all(|w| w.r_pct == 0.0)
918}
919
920fn terminal_index(terminals: &[(&str, &str)], bus: &str, terminal: &str) -> Option<usize> {
921 terminals
922 .iter()
923 .position(|(b, t)| b.eq_ignore_ascii_case(bus) && *t == terminal)
924}
925
926fn coil_positions(
929 network: &MulticonductorNetwork,
930 transformer: &DistTransformer,
931 winding: usize,
932 terminals: &[(&str, &str)],
933) -> Result<Vec<(Option<usize>, Option<usize>)>> {
934 let w = &transformer.windings[winding];
935 let position = |terminal: usize| terminal_index(terminals, &w.bus, &w.terminal_map[terminal]);
936 Ok(calc_winding_connection(network, transformer, winding)?
937 .iter()
938 .map(|channel| (position(channel.from), channel.to.and_then(position)))
939 .collect())
940}
941
942fn add_coil_shunt(
943 y: &mut [Vec<Complex64>],
944 (from, to): (Option<usize>, Option<usize>),
945 value: Complex64,
946) {
947 let stamp = calc_coil_shunt_primitive(value, to.is_none());
948 let rows = [from, to];
949 for (i, row) in stamp.iter().enumerate() {
950 for (j, entry) in row.iter().enumerate() {
951 if let (Some(a), Some(b)) = (rows[i], rows[j]) {
952 y[a][b] += entry;
953 }
954 }
955 }
956}
957
958fn checked_tap(w: &DistWinding, name: &str) -> Result<f64> {
959 if !w.tap.is_finite() || w.tap <= 0.0 {
960 return Err(invalid(name, "winding.tap", "must be positive and finite"));
961 }
962 Ok(w.tap)
963}
964
965fn sum_matrices(a: &[Vec<Complex64>], b: &[Vec<Complex64>]) -> Vec<Vec<Complex64>> {
966 let mut sum = a.to_vec();
967 for (row, other) in sum.iter_mut().zip(b) {
968 for (value, add) in row.iter_mut().zip(other) {
969 *value += add;
970 }
971 }
972 sum
973}
974
975#[allow(clippy::too_many_lines)] pub fn calc_transformer_primitive_admittance<'a>(
1013 network: &MulticonductorNetwork,
1014 transformer: &'a DistTransformer,
1015) -> Result<TransformerPrimitive<'a>> {
1016 for key in ["xrconst", "core"] {
1018 if transformer.extras.contains_key(key) {
1019 return Err(unsupported(
1020 &transformer.name,
1021 format!("raw OpenDSS property `{key}` requires normalization"),
1022 ));
1023 }
1024 }
1025 let anti_float = transformer_extra_number(&transformer.extras, "ppm_antifloat").unwrap_or(
1026 if *network.source_format() == Some(crate::model::DistSourceFormat::Dss) {
1027 1.0
1028 } else {
1029 0.0
1030 },
1031 );
1032 if !anti_float.is_finite() {
1033 return Err(invalid(
1034 &transformer.name,
1035 "ppm_antifloat",
1036 "must be finite",
1037 ));
1038 }
1039 if uses_autotransformer_impedance(transformer) {
1040 if anti_float != 0.0 {
1041 return Err(unsupported(
1042 &transformer.name,
1043 "ppm_antifloat is not supported for BMOPF autotransformers",
1044 ));
1045 }
1046 return autotransformer_primitive(transformer);
1047 }
1048 validate_primitive_shape(transformer)?;
1049 let phases = transformer.phases;
1050 let name = transformer.name.as_str();
1051 let windings = transformer.windings.len();
1052
1053 let turns: Vec<f64> = (0..windings)
1054 .map(|index| {
1055 Ok(calc_coil_voltage(transformer, index)
1056 * checked_tap(&transformer.windings[index], name)?)
1057 })
1058 .collect::<Result<_>>()?;
1059 let y_1volt = calc_transformer_winding_admittance(transformer)
1060 .map_err(|error| unsupported(name, error))?
1061 .ok_or_else(|| invalid(name, "leakage impedance", "is singular"))?;
1062
1063 let mut terminals: Vec<(&str, &str)> = Vec::new();
1064 for winding in &transformer.windings {
1067 for terminal in winding
1068 .terminal_map
1069 .iter()
1070 .take(terminal_count(winding, phases))
1071 {
1072 if terminal_index(&terminals, &winding.bus, terminal).is_none() {
1073 terminals.push((winding.bus.as_str(), terminal.as_str()));
1074 }
1075 }
1076 }
1077 let nterm = terminals.len();
1078 if nterm == 0 {
1079 return Err(invalid(name, "terminal_map", "no physical terminals"));
1080 }
1081 let coils: Vec<Vec<(Option<usize>, Option<usize>)>> = (0..windings)
1082 .map(|index| coil_positions(network, transformer, index, &terminals))
1083 .collect::<Result<_>>()?;
1084 if coils.iter().any(|winding| winding.len() != phases) {
1085 return Err(invalid(
1086 name,
1087 "terminal_map",
1088 "every winding needs one coil per phase",
1089 ));
1090 }
1091 let mut y_series = vec![vec![Complex64::new(0.0, 0.0); nterm]; nterm];
1092 let mut y_shunt = vec![vec![Complex64::new(0.0, 0.0); nterm]; nterm];
1093
1094 for phase in 0..phases {
1097 let mut b = vec![vec![Complex64::new(0.0, 0.0); nterm]; windings];
1098 for (index, winding_coils) in coils.iter().enumerate() {
1099 let (a, z) = winding_coils[phase];
1100 let k = Complex64::new(1.0 / turns[index], 0.0);
1101 if let Some(i) = a {
1102 b[index][i] += k;
1103 }
1104 if let Some(i) = z {
1105 b[index][i] -= k;
1106 }
1107 }
1108 for i in 0..nterm {
1109 for j in 0..nterm {
1110 let mut value = Complex64::new(0.0, 0.0);
1111 for p in 0..windings {
1112 for q in 0..windings {
1113 value += b[p][i] * y_1volt[p][q] * b[q][j];
1114 }
1115 }
1116 y_series[i][j] += value;
1117 }
1118 }
1119 }
1120
1121 let mut grounded = Vec::new();
1124 for (index, winding) in transformer.windings.iter().enumerate() {
1125 let grounding = calc_winding_neutral_grounding(transformer, index)?;
1126 if matches!(
1127 grounding,
1128 WindingNeutralGrounding::Unstated | WindingNeutralGrounding::Floating
1129 ) {
1130 continue;
1131 }
1132 let neutral = calc_winding_connection(network, transformer, index)?
1133 .first()
1134 .and_then(|coil| coil.to)
1135 .ok_or_else(|| {
1136 unsupported(
1137 name,
1138 "neutral impedance is declared but the WYE neutral is implicit ground",
1139 )
1140 })?;
1141 match grounding {
1142 WindingNeutralGrounding::Solid => {
1143 grounded.push((winding.bus.as_str(), winding.terminal_map[neutral].as_str()));
1144 }
1145 WindingNeutralGrounding::Impedance(y) => {
1146 if let Some(i) =
1147 terminal_index(&terminals, &winding.bus, &winding.terminal_map[neutral])
1148 {
1149 y_series[i][i] += y;
1150 }
1151 }
1152 _ => {}
1153 }
1154 }
1155
1156 if let Some(core) = calc_transformer_magnetizing(transformer)? {
1157 for &coil in &coils[core.winding] {
1158 add_coil_shunt(&mut y_shunt, coil, core.admittance);
1159 }
1160 }
1161 for (index, winding_coils) in coils.iter().enumerate() {
1164 let voltage = calc_coil_voltage(transformer, index);
1165 let admittance = Complex64::new(
1166 0.0,
1167 -anti_float * 1e-6 * transformer.windings[0].s_rating
1168 / phases as f64
1169 / voltage.powi(2)
1170 / 2.0,
1171 );
1172 if !admittance.im.is_finite() {
1173 return Err(invalid(
1174 name,
1175 "ppm_antifloat",
1176 "grounding admittance is not finite",
1177 ));
1178 }
1179 for &(a, z) in winding_coils {
1180 for terminal in [a, z].into_iter().flatten() {
1181 y_shunt[terminal][terminal] += admittance;
1182 }
1183 }
1184 if transformer.windings[index].conn == DistWindingConn::Wye
1185 && matches!(
1186 calc_winding_neutral_grounding(transformer, index)?,
1187 WindingNeutralGrounding::Floating | WindingNeutralGrounding::Unstated
1188 )
1189 && let Some(neutral) = winding_coils.first().and_then(|coil| coil.1)
1190 {
1191 y_shunt[neutral][neutral] += admittance;
1192 }
1193 }
1194 let y_prim = sum_matrices(&y_series, &y_shunt);
1195 let delta_direction = match transformer
1196 .windings
1197 .iter()
1198 .position(|w| w.conn == DistWindingConn::Delta)
1199 {
1200 Some(index) => calc_delta_direction(transformer, index)?,
1201 None => 1,
1202 };
1203 Ok(TransformerPrimitive {
1204 name,
1205 terminals,
1206 series: y_series,
1207 shunt: y_shunt,
1208 primitive: y_prim,
1209 grounded,
1210 delta_direction,
1211 winding_admittance: y_1volt,
1212 })
1213}
1214
1215#[allow(clippy::too_many_lines)] fn autotransformer_primitive(transformer: &DistTransformer) -> Result<TransformerPrimitive<'_>> {
1222 let name = transformer.name.as_str();
1223 if transformer.phases != 1 || transformer.windings.len() != 2 {
1224 return Err(unsupported(
1225 name,
1226 format!(
1227 "single_phase_autotransformer requires one phase and two windings; got {} phases and {} windings",
1228 transformer.phases,
1229 transformer.windings.len()
1230 ),
1231 ));
1232 }
1233 let from = &transformer.windings[0];
1234 let to = &transformer.windings[1];
1235 for (idx, winding) in [from, to].iter().enumerate() {
1236 if winding.conn != DistWindingConn::Wye || winding.terminal_map.len() != 2 {
1237 return Err(invalid(
1238 name,
1239 format!("windings[{idx}].terminal_map"),
1240 "autotransformer winding requires phase and reference terminals",
1241 ));
1242 }
1243 }
1244 let tap_ratio = checked_tap(to, name)?;
1245 let regulator_type = transformer
1246 .extras
1247 .get("regulator_type")
1248 .and_then(serde_json::Value::as_str)
1249 .unwrap_or("B")
1250 .trim()
1251 .to_ascii_uppercase();
1252 if !matches!(regulator_type.as_str(), "A" | "B") {
1253 return Err(invalid(
1254 name,
1255 "regulator_type",
1256 format!("expected A or B, got `{regulator_type}`"),
1257 ));
1258 }
1259 let n_eff = 1.0 / tap_ratio;
1260 let z = calc_transformer_leakage_impedances(transformer, &TransformerLeakageBase::StatedOhms)?
1261 [0][1];
1262 if z.norm() == 0.0 {
1263 return Err(unsupported(
1264 name,
1265 "zero series impedance requires an ideal regulator voltage constraint",
1266 ));
1267 }
1268 let y = z.finv();
1269 let y_1volt = vec![vec![y, -n_eff * y], vec![-n_eff * y, n_eff.powi(2) * y]];
1270
1271 let mut terminals: Vec<(&str, &str)> = Vec::new();
1274 for (winding, terminal) in [
1275 (from, &from.terminal_map[0]),
1276 (to, &to.terminal_map[0]),
1277 (from, &from.terminal_map[1]),
1278 (to, &to.terminal_map[1]),
1279 ] {
1280 if terminal_index(&terminals, &winding.bus, terminal).is_none() {
1281 terminals.push((winding.bus.as_str(), terminal.as_str()));
1282 }
1283 }
1284 let nterm = terminals.len();
1285 let position = |winding: &DistWinding, terminal: usize| {
1286 terminal_index(&terminals, &winding.bus, &winding.terminal_map[terminal])
1287 .expect("every winding terminal is listed")
1288 };
1289 let mut from_incidence = vec![0.0; nterm];
1290 let mut to_incidence = vec![0.0; nterm];
1291 for (incidence, winding) in [(&mut from_incidence, from), (&mut to_incidence, to)] {
1292 incidence[position(winding, 0)] += 1.0;
1293 incidence[position(winding, 1)] -= 1.0;
1294 }
1295 let winding_difference: Vec<f64> = from_incidence
1296 .iter()
1297 .zip(&to_incidence)
1298 .map(|(from, to)| from - n_eff * to)
1299 .collect();
1300 let mut y_series = vec![vec![Complex64::default(); nterm]; nterm];
1301 for i in 0..nterm {
1302 for j in 0..nterm {
1303 y_series[i][j] = y * winding_difference[i] * winding_difference[j];
1304 }
1305 }
1306 let mut y_shunt = vec![vec![Complex64::default(); nterm]; nterm];
1307 if let Some(core) = calc_transformer_magnetizing(transformer)? {
1308 let winding = &transformer.windings[core.winding];
1309 add_coil_shunt(
1310 &mut y_shunt,
1311 (Some(position(winding, 0)), Some(position(winding, 1))),
1312 core.admittance,
1313 );
1314 }
1315 let y_prim = sum_matrices(&y_series, &y_shunt);
1316 Ok(TransformerPrimitive {
1317 name,
1318 terminals,
1319 series: y_series,
1320 shunt: y_shunt,
1321 primitive: y_prim,
1322 grounded: Vec::new(),
1323 delta_direction: 1,
1324 winding_admittance: y_1volt,
1325 })
1326}
1327
1328#[allow(clippy::too_many_lines)] fn validate_primitive_shape(t: &DistTransformer) -> Result<()> {
1330 let name = t.name.as_str();
1331 let center_tap = subtype(t) == Some("center_tap");
1332 let winding_count = t.windings.len();
1333 if !(2..=3).contains(&winding_count) || (center_tap && winding_count != 3) {
1334 return Err(unsupported(
1335 name,
1336 "finite primitives require two or three windings",
1337 ));
1338 }
1339 if center_tap && t.phases != 1 {
1340 return Err(unsupported(
1341 name,
1342 format!(
1343 "BMOPF centre-tap primitives require one phase; got {}",
1344 t.phases
1345 ),
1346 ));
1347 }
1348 if t.phases == 0 || t.phases > 3 {
1349 return Err(unsupported(
1350 name,
1351 format!(
1352 "{} phases are outside the supported 1, 2, and 3 phase shapes",
1353 t.phases
1354 ),
1355 ));
1356 }
1357 let expected_xsc = winding_count * (winding_count - 1) / 2;
1358 if t.xsc_pct.len() != expected_xsc {
1359 return Err(invalid(
1360 name,
1361 "xsc_pct",
1362 format!(
1363 "{} requires exactly {expected_xsc} pairwise short-circuit values",
1364 if center_tap {
1365 "a centre-tap transformer"
1366 } else {
1367 "a finite transformer"
1368 }
1369 ),
1370 ));
1371 }
1372 if t.xsc_pct
1373 .iter()
1374 .any(|value| !value.is_finite() || *value < 0.0)
1375 {
1376 return Err(invalid(name, "xsc_pct", "must be finite and nonnegative"));
1377 }
1378 for (idx, w) in t.windings.iter().enumerate() {
1379 if !w.v_ref.is_finite() || w.v_ref <= 0.0 {
1380 return Err(invalid(
1381 name,
1382 format!("windings[{idx}].v_ref"),
1383 "must be positive and finite",
1384 ));
1385 }
1386 if !w.s_rating.is_finite() || w.s_rating <= 0.0 {
1387 return Err(invalid(
1388 name,
1389 format!("windings[{idx}].s_rating"),
1390 "must be positive and finite",
1391 ));
1392 }
1393 if !w.r_pct.is_finite() || w.r_pct < 0.0 {
1394 return Err(invalid(
1395 name,
1396 format!("windings[{idx}].r_pct"),
1397 "must be finite and nonnegative",
1398 ));
1399 }
1400 checked_tap(w, name)?;
1401 let expected = terminal_count(w, t.phases);
1402 if t.phases == 1 && w.conn == DistWindingConn::Delta && w.terminal_map.len() < 2 {
1403 return Err(invalid(
1404 name,
1405 format!("windings[{idx}].terminal_map"),
1406 "a one-phase DELTA winding requires two coil endpoints",
1407 ));
1408 }
1409 let stated = w.terminal_map.len();
1410 let wye_expected = if t.phases == 1 { 2 } else { t.phases + 1 };
1411 let accepted = if w.conn == DistWindingConn::Wye {
1412 stated == wye_expected || stated == t.phases
1413 } else {
1414 stated == expected
1415 };
1416 if !accepted {
1417 return Err(invalid(
1418 name,
1419 format!("windings[{idx}].terminal_map"),
1420 format!(
1421 "expected {} terminals (or {} phase terminals with an implicit WYE ground), got {stated}",
1422 if w.conn == DistWindingConn::Wye {
1423 wye_expected
1424 } else {
1425 expected
1426 },
1427 t.phases,
1428 ),
1429 ));
1430 }
1431 }
1432 if transformer_states_no_leakage(t) {
1433 return Err(unsupported(
1434 name,
1435 "zero leakage requires ideal voltage constraints and cannot be represented by an admittance primitive",
1436 ));
1437 }
1438 Ok(())
1439}
1440
1441#[cfg(test)]
1442mod tests {
1443 use super::*;
1444
1445 fn unit(conn: [DistWindingConn; 2], v: [f64; 2]) -> DistTransformer {
1446 let windings = conn
1447 .iter()
1448 .zip(v)
1449 .map(|(&conn, v_ref)| DistWinding::new("b", vec![], conn, v_ref, 1.0))
1450 .collect();
1451 DistTransformer::new("t", windings, vec![1.0], 3)
1452 }
1453
1454 #[test]
1455 fn opendss_dy_orientation_and_shift_follow_leadlag() {
1456 let mut dy = unit(
1457 [DistWindingConn::Delta, DistWindingConn::Wye],
1458 [12.47e3, 0.48e3],
1459 );
1460 assert_eq!(calc_delta_direction(&dy, 0).unwrap(), -1);
1461 assert_eq!(calc_transformer_phase_shift(&dy).unwrap(), 30.0);
1462 dy.extras
1463 .insert("leadlag".into(), serde_json::json!("Euro"));
1464 assert_eq!(calc_delta_direction(&dy, 0).unwrap(), 1);
1465 assert_eq!(calc_transformer_phase_shift(&dy).unwrap(), -30.0);
1466 let yd = unit(
1467 [DistWindingConn::Wye, DistWindingConn::Delta],
1468 [12.47e3, 0.48e3],
1469 );
1470 assert_eq!(calc_delta_direction(&yd, 1).unwrap(), 1);
1471 assert_eq!(calc_transformer_phase_shift(&yd).unwrap(), 30.0);
1472 let mut bmopf = unit(
1473 [DistWindingConn::Delta, DistWindingConn::Wye],
1474 [12.47e3, 0.48e3],
1475 );
1476 bmopf
1477 .extras
1478 .insert("bmopf_subtype".into(), serde_json::json!("delta_wye"));
1479 assert_eq!(calc_delta_direction(&bmopf, 0).unwrap(), -1);
1480 bmopf
1481 .extras
1482 .insert("bmopf_delta_rolls".into(), serde_json::json!({"1": 2}));
1483 assert!(calc_delta_direction(&bmopf, 0).is_err());
1484 }
1485
1486 #[test]
1487 fn reduced_leakage_against_either_reference() {
1488 let z = |re: f64| Complex64::new(re, 0.0);
1489 let leakage = vec![
1490 vec![z(0.0), z(1.0), z(2.0)],
1491 vec![z(1.0), z(0.0), z(4.0)],
1492 vec![z(2.0), z(4.0), z(0.0)],
1493 ];
1494 assert_eq!(
1495 calc_reduced_leakage(&leakage, 0),
1496 vec![vec![z(1.0), z(-0.5)], vec![z(-0.5), z(2.0)]]
1497 );
1498 assert_eq!(
1499 calc_reduced_leakage(&leakage, 2),
1500 vec![vec![z(2.0), z(2.5)], vec![z(2.5), z(4.0)]]
1501 );
1502 }
1503
1504 #[test]
1505 fn neutral_grounding_reads_opendss_conventions() {
1506 let mut t = unit([DistWindingConn::Wye, DistWindingConn::Delta], [1.0, 1.0]);
1507 assert_eq!(
1508 calc_winding_neutral_grounding(&t, 0).unwrap(),
1509 WindingNeutralGrounding::Unstated
1510 );
1511 t.windings[0].r_neutral = Some(0.0);
1512 assert_eq!(
1513 calc_winding_neutral_grounding(&t, 0).unwrap(),
1514 WindingNeutralGrounding::Solid
1515 );
1516 t.windings[0].r_neutral = Some(-1.0);
1517 assert_eq!(
1518 calc_winding_neutral_grounding(&t, 0).unwrap(),
1519 WindingNeutralGrounding::Floating
1520 );
1521 t.windings[1].r_neutral = Some(2.0);
1522 assert!(calc_winding_neutral_grounding(&t, 1).is_err());
1523 t.windings[1].r_neutral = Some(-1.0);
1524 assert_eq!(
1525 calc_winding_neutral_grounding(&t, 1).unwrap(),
1526 WindingNeutralGrounding::Floating
1527 );
1528 }
1529
1530 #[test]
1531 fn legacy_core_sits_on_the_bmopf_winding() {
1532 let mut t = unit([DistWindingConn::Wye, DistWindingConn::Delta], [1.0, 1.0]);
1533 t.extras
1534 .insert("bmopf_subtype".into(), serde_json::json!("wye_delta"));
1535 t.extras.insert("g_no_load".into(), serde_json::json!(3.0));
1536 let core = calc_transformer_magnetizing(&t).unwrap().unwrap();
1537 assert_eq!(core.winding, 1);
1538 assert_eq!(core.admittance, Complex64::new(1.0, 0.0));
1539 t.extras.insert(
1540 "no_load_shunt".into(),
1541 serde_json::json!({"winding": 1, "g": 1.0, "b": 0.0}),
1542 );
1543 assert!(calc_transformer_magnetizing(&t).is_err());
1544 }
1545}