Skip to main content

powerio_dist/
sequence.rs

1//! Symmetrical components: the one transform pair between sequence and
2//! phase quantities.
3//!
4//! A transposed (symmetric) element with positive sequence value `z₁` and
5//! zero sequence value `z₀` has the phase matrix with self entries
6//! `(2 z₁ + z₀) / 3` and mutual entries `(z₀ − z₁) / 3`; the inverse reads
7//! `z₁ = self − mutual` and `z₀ = self + 2 mutual`. A full three phase
8//! matrix or phasor vector transforms with Fortescue's operator
9//! `a = e^{j 2π/3}`.
10
11use std::ops::{Add, Div, Mul, Sub};
12
13use num_complex::Complex64;
14
15use crate::VoltageSource;
16
17/// How a sequence to phase expansion takes its third. The spellings are
18/// the same transform and can differ in the last place (and, for
19/// [`SequenceThird::DivideFirst`], in where a large finite value
20/// overflows); the reference engines use several, so a reader reproducing
21/// one names the order its element class uses.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum SequenceThird {
25    /// Divide by three: OpenDSS `Line` (`RecalcElementData`:
26    /// `Zs := (Ztemp + Cmplx(R0, X0)) / 3`) and `VSource`
27    /// (`(2.0 * X1 + X0) / 3.0`), and every reader that follows no engine's
28    /// rounding.
29    Divide,
30    /// Multiply by the rounded reciprocal `1.0 / 3.0`: OpenDSS `LineCode`
31    /// alone (`CalcMatricesFromZ1Z0` multiplies by its local
32    /// `OneThird := 1.0 / 3.0`).
33    Reciprocal,
34    /// Divide each sequence value by three before combining them, self
35    /// `2 (z₁ / 3) + z₀ / 3` and mutual `z₀ / 3 − z₁ / 3`, so no
36    /// intermediate sum of two large finite values overflows: the SINCAL
37    /// multiconductor line and rated shunt readers.
38    DivideFirst,
39    /// The self entry divided by three as [`SequenceThird::Divide`] and the
40    /// mutual entry as that self entry less `z₁`: OpenDSS `VSource` given
41    /// its sequence impedances (`Xm := Xs − X1` in `RecalcElementData`).
42    SelfLessPositive,
43}
44
45/// The self (diagonal) phase entry of a transposed element:
46/// `(2 z₁ + z₀) / 3`, the third taken as `third` states.
47#[must_use]
48pub fn calc_sequence_self<T>(positive: T, zero: T, third: SequenceThird) -> T
49where
50    T: Copy + Add<Output = T> + Mul<f64, Output = T> + Div<f64, Output = T>,
51{
52    match third {
53        SequenceThird::Divide | SequenceThird::SelfLessPositive => (positive * 2.0 + zero) / 3.0,
54        SequenceThird::Reciprocal => (positive * 2.0 + zero) * (1.0 / 3.0),
55        SequenceThird::DivideFirst => (positive / 3.0) * 2.0 + zero / 3.0,
56    }
57}
58
59/// The mutual (off diagonal) phase entry of a transposed element:
60/// `(z₀ − z₁) / 3`, the third taken as `third` states.
61#[must_use]
62pub fn calc_sequence_mutual<T>(positive: T, zero: T, third: SequenceThird) -> T
63where
64    T: Copy + Add<Output = T> + Sub<Output = T> + Mul<f64, Output = T> + Div<f64, Output = T>,
65{
66    match third {
67        SequenceThird::Divide => (zero - positive) / 3.0,
68        SequenceThird::Reciprocal => (zero - positive) * (1.0 / 3.0),
69        SequenceThird::DivideFirst => zero / 3.0 - positive / 3.0,
70        SequenceThird::SelfLessPositive => calc_sequence_self(positive, zero, third) - positive,
71    }
72}
73
74/// The `n × n` phase matrix of a transposed element from its positive and
75/// zero sequence values ([`calc_sequence_self`] on the diagonal,
76/// [`calc_sequence_mutual`] off it). The one sequence to phase expansion:
77/// the OpenDSS line code, line and source readers and the pandapower reader
78/// read it, for impedance, resistance, reactance and susceptance alike.
79#[must_use]
80pub fn calc_phase_from_sequence<T>(
81    n: usize,
82    positive: T,
83    zero: T,
84    third: SequenceThird,
85) -> Vec<Vec<T>>
86where
87    T: Copy + Add<Output = T> + Sub<Output = T> + Mul<f64, Output = T> + Div<f64, Output = T>,
88{
89    let mutual = calc_sequence_mutual(positive, zero, third);
90    let own = calc_sequence_self(positive, zero, third);
91    (0..n)
92        .map(|i| (0..n).map(|j| if i == j { own } else { mutual }).collect())
93        .collect()
94}
95
96/// OpenDSS's rotation operator `DSSGlobals.CALPHA`, `-0.5 + j 0.866025`:
97/// rounded to six places, unlike Fortescue's exact `a`. The reference
98/// engine's unequal sequence (`Z1 ≠ Z2`) source matrix uses it; replacing
99/// it with `sin 120°` changes those impedances.
100pub const OPENDSS_ALPHA: Complex64 = Complex64::new(-0.5, 0.866_025);
101
102/// Entry `(i, j)`, `i ≠ j`, of the three phase circulant matrix of an
103/// element with unequal sequence impedances `[z₀, z₁, z₂]` as OpenDSS
104/// `VSource` forms it: `(z₀ + z₁ α^((j−i) mod 3) + z₂ α^((i−j) mod 3)) / 3`
105/// with [`OPENDSS_ALPHA`], summed in `VSource.RecalcElementData`'s order,
106/// the `α²` term, then the `α` term, then `z₀` (`Calpha2 * Z2 + Calpha1 *
107/// Z1 + Z0` above the diagonal, `Calpha2 * Z1 + Calpha1 * Z2 + Z0` below
108/// it, DSS C-API 0.14.5), with `α² = α · α`. The diagonal is
109/// `(z₂ + z₁ + z₀) / 3`. [`calc_circulant_sequence_from_phase`] is its
110/// inverse.
111#[must_use]
112pub fn calc_circulant_phase_entry(sequence: [Complex64; 3], i: usize, j: usize) -> Complex64 {
113    let [zero, positive, negative] = sequence;
114    if i == j {
115        return (negative + positive + zero) / 3.0;
116    }
117    let alpha_squared = OPENDSS_ALPHA * OPENDSS_ALPHA;
118    // Above the diagonal (j = i + 1 mod 3) z₁ takes α and z₂ takes α².
119    let (by_alpha_squared, by_alpha) = if (j + 3 - i) % 3 == 1 {
120        (negative, positive)
121    } else {
122        (positive, negative)
123    };
124    (alpha_squared * by_alpha_squared + OPENDSS_ALPHA * by_alpha + zero) / 3.0
125}
126
127/// The sequence impedances `[z₀, z₁, z₂]` of a three phase circulant matrix
128/// from its first row `[z₀₀, z₀₁, z₀₂]`, the inverse of
129/// [`calc_circulant_phase_entry`] over the same [`OPENDSS_ALPHA`].
130#[must_use]
131pub fn calc_circulant_sequence_from_phase(row: [Complex64; 3]) -> [Complex64; 3] {
132    let first_rotation = OPENDSS_ALPHA - 1.0;
133    let second_rotation = OPENDSS_ALPHA * OPENDSS_ALPHA - 1.0;
134    let upper_delta = 3.0 * (row[1] - row[0]);
135    let lower_delta = 3.0 * (row[2] - row[0]);
136    let denominator = first_rotation * first_rotation - second_rotation * second_rotation;
137    let positive = (upper_delta * first_rotation - lower_delta * second_rotation) / denominator;
138    let negative = (lower_delta * first_rotation - upper_delta * second_rotation) / denominator;
139    let zero = 3.0 * row[0] - positive - negative;
140    [zero, positive, negative]
141}
142
143/// The positive and zero sequence values `(z₁, z₀)` of a transposed element
144/// from its self and mutual phase entries: `(self − mutual, self + 2 mutual)`.
145/// The one phase to sequence inverse of [`calc_phase_from_sequence`]: the
146/// OpenDSS source and switch writers, the CIM source writer and the SINCAL
147/// multiconductor writer read it.
148#[must_use]
149pub fn calc_sequence_from_phase<T>(own: T, mutual: T) -> (T, T)
150where
151    T: Copy + Add<Output = T> + Sub<Output = T> + Mul<f64, Output = T>,
152{
153    (own - mutual, own + mutual * 2.0)
154}
155
156/// The rotation operator `a` a symmetrical component transform is built
157/// on. The variants are the same transform to within their rounding of
158/// `sin 120°`; the reference tools use several, so a reader reproducing one
159/// names the operator it uses.
160#[derive(Clone, Copy, Debug, PartialEq, Eq)]
161#[non_exhaustive]
162pub enum SequenceRotation {
163    /// Fortescue's `a = e^{j 2π/3}` from its polar form, `a² = a · a`, and
164    /// the inverse `A⁻¹ = conj(A)ᵀ / 3`: every reader and model that follows
165    /// no engine's rounding.
166    Fortescue,
167    /// `a = −½ + j √3/2` written in rectangular form, `a² = conj(a)`, and
168    /// the inverse `conj(A)ᵀ / 3`: the SINCAL multiconductor transformer
169    /// port expansion.
170    Rectangular,
171    /// OpenDSS `mathutil.pas`'s `SetAMatrix` as upstream OpenDSS builds it
172    /// (and DSS C-API under its `BadPrecision` compatibility flag):
173    /// `a = −½ + j 0.866025403`, truncated, `a² = conj(a)`, and `A⁻¹` the
174    /// closed form of the inverse of that `A`, whose sequence rows are
175    /// `[⅓, w, conj(w)]` and `[⅓, conj(w), w]` with
176    /// `w = −1/6 + j / (4 · 0.866025403)`; `conj(A)ᵀ / 3` is not its inverse.
177    /// `mathutil.pas` forms `Ap2s` numerically (`TcMatrix.Invert`), whose
178    /// sweep differs from this closed form in the last place (its `⅓`
179    /// entries and `w.re`, with residues of order `2⁻⁵⁴` in their imaginary
180    /// parts), so values through this operator agree with the engine's to
181    /// within that rounding, not bit for bit. The IndMach012a user model's
182    /// sequence admittance reads it.
183    OpenDssMathutil,
184}
185
186/// `sin 120°` as `mathutil.pas`'s `SetAMatrix` spells it.
187const MATHUTIL_SINE: f64 = 0.866_025_403;
188
189/// The transform `A` (columns: the phase phasors of a unit zero, positive
190/// and negative sequence quantity) and its inverse under `rotation`.
191fn transform(rotation: SequenceRotation) -> ([[Complex64; 3]; 3], [[Complex64; 3]; 3]) {
192    let one = Complex64::new(1.0, 0.0);
193    let (a, a2) = match rotation {
194        SequenceRotation::Fortescue => {
195            let a = Complex64::from_polar(1.0, 2.0 * std::f64::consts::PI / 3.0);
196            (a, a * a)
197        }
198        SequenceRotation::Rectangular => {
199            let a = Complex64::new(-0.5, crate::electrical::SQRT_3 / 2.0);
200            (a, a.conj())
201        }
202        SequenceRotation::OpenDssMathutil => {
203            let a = Complex64::new(-0.5, MATHUTIL_SINE);
204            (a, a.conj())
205        }
206    };
207    let forward = [[one, one, one], [one, a2, a], [one, a, a2]];
208    let third = one / 3.0;
209    let inverse = if rotation == SequenceRotation::OpenDssMathutil {
210        let w = Complex64::new(-1.0 / 6.0, 1.0 / (4.0 * MATHUTIL_SINE));
211        [
212            [third, third, third],
213            [third, w, w.conj()],
214            [third, w.conj(), w],
215        ]
216    } else {
217        [
218            [third, third, third],
219            [third, a / 3.0, a2 / 3.0],
220            [third, a2 / 3.0, a / 3.0],
221        ]
222    };
223    (forward, inverse)
224}
225
226/// The zero, positive and negative sequence components of three phase
227/// phasors `[a, b, c]`: `V₀ = (Va + Vb + Vc)/3`, `V₁ = (Va + a Vb + a² Vc)/3`,
228/// `V₂ = (Va + a² Vb + a Vc)/3`, under `rotation` (for
229/// [`SequenceRotation::OpenDssMathutil`], the rows of its exact inverse).
230#[must_use]
231pub fn calc_sequence_components(
232    phase: [Complex64; 3],
233    rotation: SequenceRotation,
234) -> [Complex64; 3] {
235    let (forward, inverse) = transform(rotation);
236    let [va, vb, vc] = phase;
237    if rotation == SequenceRotation::OpenDssMathutil {
238        return inverse.map(|row| row[0] * va + row[1] * vb + row[2] * vc);
239    }
240    let (a, a2) = (forward[2][1], forward[1][1]);
241    [
242        (va + vb + vc) / 3.0,
243        (va + a * vb + a2 * vc) / 3.0,
244        (va + a2 * vb + a * vc) / 3.0,
245    ]
246}
247
248/// The three phase phasors `[a, b, c]` of zero, positive and negative
249/// sequence components `[V₀, V₁, V₂]`: `Va = V₀ + V₁ + V₂`,
250/// `Vb = V₀ + a² V₁ + a V₂`, `Vc = V₀ + a V₁ + a² V₂` under `rotation`, the
251/// inverse of [`calc_sequence_components`]. The GridLAB-D sequence voltage
252/// substation reads it.
253#[must_use]
254pub fn calc_phase_components(
255    sequence: [Complex64; 3],
256    rotation: SequenceRotation,
257) -> [Complex64; 3] {
258    let (forward, _) = transform(rotation);
259    let (a, a2) = (forward[2][1], forward[1][1]);
260    let [zero, positive, negative] = sequence;
261    [
262        zero + positive + negative,
263        zero + a2 * positive + a * negative,
264        zero + a * positive + a2 * negative,
265    ]
266}
267
268/// The three phase matrix `A diag(d₀, d₁, d₂) A⁻¹` of an element whose
269/// sequence networks are uncoupled, with sequence values
270/// `diagonal = [d₀, d₁, d₂]` (impedances or admittances), under `rotation`.
271/// For an operator whose inverse is `conj(A)ᵀ / 3` entry `(i, j)` is
272/// `(d₀ + d₁ f + d₂ conj(f)) / 3` with `f = p_i conj(p_j)` and
273/// `p = [1, a², a]`; for [`SequenceRotation::OpenDssMathutil`] it is
274/// `Σₛ A_is dₛ A⁻¹_sj` over its exact inverse. The one sequence diagonal to
275/// phase expansion: the SINCAL multiconductor transformer ports
276/// ([`SequenceRotation::Rectangular`]) and the OpenDSS IndMach012a motor
277/// ([`SequenceRotation::OpenDssMathutil`]) read it.
278#[must_use]
279pub fn calc_phase_matrix_from_sequence(
280    diagonal: [Complex64; 3],
281    rotation: SequenceRotation,
282) -> [[Complex64; 3]; 3] {
283    let (forward, inverse) = transform(rotation);
284    let mut matrix = [[Complex64::default(); 3]; 3];
285    for (i, row) in matrix.iter_mut().enumerate() {
286        for (j, entry) in row.iter_mut().enumerate() {
287            *entry = if rotation == SequenceRotation::OpenDssMathutil {
288                forward[i][1] * diagonal[1] * inverse[1][j]
289                    + forward[i][2] * diagonal[2] * inverse[2][j]
290                    + forward[i][0] * diagonal[0] * inverse[0][j]
291            } else {
292                let p = [forward[0][1], forward[1][1], forward[2][1]];
293                let factor = p[i] * p[j].conj();
294                (diagonal[0] + diagonal[1] * factor + diagonal[2] * factor.conj()) / 3.0
295            };
296        }
297    }
298    matrix
299}
300
301/// The sequence matrix `A⁻¹ Z A` of a three phase matrix (rows and columns
302/// zero, positive, negative), with `A` Fortescue's transform. A transposed
303/// matrix is diagonal here, `diag(z₀, z₁, z₁)`; its off diagonal entries
304/// measure the coupling between sequences.
305///
306/// # Panics
307/// When `matrix` is smaller than three by three.
308#[must_use]
309pub fn calc_sequence_matrix(matrix: &[Vec<Complex64>]) -> [[Complex64; 3]; 3] {
310    // Columns of A: the phase phasors of a unit zero, positive and negative
311    // sequence quantity; A⁻¹ = conj(A)ᵀ / 3.
312    let (basis, _) = transform(SequenceRotation::Fortescue);
313    let mut seq = [[Complex64::new(0.0, 0.0); 3]; 3];
314    for (p, row) in seq.iter_mut().enumerate() {
315        for (q, out) in row.iter_mut().enumerate() {
316            for (i, matrix_row) in matrix.iter().take(3).enumerate() {
317                for (j, value) in matrix_row.iter().take(3).enumerate() {
318                    *out += basis[i][p].conj() * value * basis[j][q];
319                }
320            }
321            *out /= 3.0;
322        }
323    }
324    seq
325}
326
327/// The line to line over line to neutral ratio of `phases` phasors of one
328/// magnitude spaced `2π / phases` apart, `2 sin(π / phases)` (`√3` for
329/// three, `2` for two): OpenDSS `VSource`'s per phase magnitude
330/// (`kVBase · PerUnit · 1000 / 2 / Sin(180 / Fnphases · π / 180)`) and the
331/// CIM and MG-RAVENS `nominalVoltage` read and written over it. The one
332/// polygon chord.
333#[must_use]
334pub fn calc_polygon_chord(phases: usize) -> f64 {
335    2.0 * (std::f64::consts::PI / phases as f64).sin()
336}
337
338/// The angle, radians, of phase `phase` (counted from zero) of a balanced
339/// positive sequence set of `phases` phasors whose first phase is at zero:
340/// each phase lags the one before by `2π / phases`, stated in `(−π, π]`
341/// (`0`, `−2π/3`, `+2π/3` for three phases), `+0.0` for `m = phase mod n`
342/// zero, formed as `−(m · τ / n)` for `0 < 2m < n` and as `(n − m) · τ / n`
343/// otherwise. Zero for `phases` zero. The one balanced phase rotation: the
344/// GridLAB-D nominal phasors and sequence voltage substation, the
345/// multiconductor OPF start point, the SINCAL multiconductor source writer
346/// and the integrated transmission and distribution coupling read it.
347#[must_use]
348pub fn calc_balanced_phase_angle(phase: usize, phases: usize) -> f64 {
349    if phases == 0 {
350        return 0.0;
351    }
352    let m = phase % phases;
353    if m == 0 {
354        return 0.0;
355    }
356    let (n, tau) = (phases as f64, std::f64::consts::TAU);
357    if 2 * m < phases {
358        -(m as f64 * tau / n)
359    } else {
360        (phases - m) as f64 * tau / n
361    }
362}
363
364/// Which phasors [`VoltageSource::calc_line_to_line_voltage`] reads a
365/// source's line to line base from.
366#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367#[non_exhaustive]
368pub enum LineVoltageForm {
369    /// The balanced equivalent of every phasor: `√3 |V₁|` for three phases
370    /// ([`calc_sequence_components`], Fortescue), the phasor difference
371    /// `|Va − Vb|` for two (a split phase pair), the phasor's magnitude for
372    /// one (a single phase source's own voltage). The multiconductor to
373    /// balanced lowering reads it.
374    PositiveSequence,
375    /// The first phase's magnitude times the chord of the `n` phase polygon
376    /// ([`calc_polygon_chord`]), and for one phase the line to line
377    /// equivalent `√3 |V|` of its magnitude, which is line to neutral
378    /// ([`crate::electrical::calc_wye_line_voltage`]): the form an MG-RAVENS
379    /// or CIM `EnergySource`, which states one magnitude for a balanced set,
380    /// takes its `nominalVoltage` in. The MG-RAVENS writer reads it.
381    FirstPhase,
382}
383
384impl VoltageSource {
385    /// The source's line to line voltage base over its phase positions
386    /// `phases` (indices into its voltage vectors), volts, in `form`
387    /// ([`LineVoltageForm`]).
388    ///
389    /// Under [`LineVoltageForm::PositiveSequence`]: `√3 |V₁|` for three
390    /// phases, `|Va − Vb|` for two, `|V|` for one; `None` for any other
391    /// count, a stated
392    /// magnitude or angle that is missing or not finite, or a base that is
393    /// not positive. Under [`LineVoltageForm::FirstPhase`]: the first
394    /// position's stated magnitude times `calc_polygon_chord(n)` for `n` of
395    /// two or more and times `√3` for one, formed as stated (a zero, negative or nonfinite
396    /// magnitude gives that base, for the caller's own check); `None` only
397    /// when no position is given or its magnitude is missing.
398    ///
399    /// The one source voltage base: the multiconductor to balanced lowering
400    /// bases a source's zone on it, and the MG-RAVENS writer states it as a
401    /// source's `nominalVoltage` and seeds the source bus's `BaseVoltage`
402    /// with it when the source carries no `basekv`.
403    #[must_use]
404    pub fn calc_line_to_line_voltage(
405        &self,
406        phases: &[usize],
407        form: LineVoltageForm,
408    ) -> Option<f64> {
409        if form == LineVoltageForm::FirstPhase {
410            let magnitude = *self.v_magnitude.get(*phases.first()?)?;
411            return Some(if phases.len() == 1 {
412                crate::electrical::calc_wye_line_voltage(magnitude)
413            } else {
414                magnitude * calc_polygon_chord(phases.len())
415            });
416        }
417        let phasor = |index: usize| {
418            let magnitude = *self.v_magnitude.get(index)?;
419            let angle = *self.v_angle.get(index)?;
420            (magnitude.is_finite() && angle.is_finite())
421                .then(|| Complex64::from_polar(magnitude, angle))
422        };
423        let base = match *phases {
424            [a, b, c] => {
425                let [_, positive, _] = calc_sequence_components(
426                    [phasor(a)?, phasor(b)?, phasor(c)?],
427                    SequenceRotation::Fortescue,
428                );
429                crate::electrical::calc_wye_line_voltage(positive.norm())
430            }
431            [a, b] => (phasor(a)? - phasor(b)?).norm(),
432            [a] => phasor(a)?.norm(),
433            _ => return None,
434        };
435        (base.is_finite() && base > 0.0).then_some(base)
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442
443    #[test]
444    fn the_transform_pair_inverts() {
445        let (positive, zero) = (Complex64::new(0.1, 0.4), Complex64::new(0.3, 1.2));
446        let matrix = calc_phase_from_sequence(3, positive, zero, SequenceThird::Divide);
447        let (p, z) = calc_sequence_from_phase(matrix[0][0], matrix[0][1]);
448        assert!((p - positive).norm() < 1e-15 && (z - zero).norm() < 1e-15);
449        let seq = calc_sequence_matrix(&matrix);
450        assert!((seq[0][0] - zero).norm() < 1e-14);
451        assert!((seq[1][1] - positive).norm() < 1e-14);
452        assert!(seq[0][1].norm() < 1e-14 && seq[1][2].norm() < 1e-14);
453        let real = calc_phase_from_sequence(2, 1.0, 4.0, SequenceThird::Reciprocal);
454        assert_eq!(real, vec![vec![2.0, 1.0], vec![1.0, 2.0]]);
455        // The two thirds are the same transform, apart in the last place.
456        let (a, b) = (0.7_f64, 0.1784_f64);
457        let divide = calc_sequence_self(a, b, SequenceThird::Divide);
458        let reciprocal = calc_sequence_self(a, b, SequenceThird::Reciprocal);
459        assert_eq!(divide, (2.0 * a + b) / 3.0);
460        assert_eq!(reciprocal, (2.0 * a + b) * (1.0 / 3.0));
461        assert!((divide - reciprocal).abs() <= f64::EPSILON);
462        // Dividing first keeps a large finite expansion finite.
463        let large = f64::MAX / 2.0;
464        assert!(calc_sequence_self(large, large, SequenceThird::Divide).is_infinite());
465        let first = calc_sequence_self(large, large, SequenceThird::DivideFirst);
466        assert_eq!(first, (large / 3.0) * 2.0 + large / 3.0);
467        assert_eq!(
468            calc_sequence_mutual(-large, large, SequenceThird::DivideFirst),
469            large / 3.0 - -large / 3.0
470        );
471        // OpenDSS VSource's sequence setters take the mutual as Xs − X1.
472        let own = calc_sequence_self(a, b, SequenceThird::SelfLessPositive);
473        assert_eq!(own, divide);
474        assert_eq!(
475            calc_sequence_mutual(a, b, SequenceThird::SelfLessPositive),
476            own - a
477        );
478        let sequence = [
479            Complex64::new(0.3, 1.2),
480            Complex64::new(0.1, 0.4),
481            Complex64::new(0.12, 0.5),
482        ];
483        for rotation in [
484            SequenceRotation::Fortescue,
485            SequenceRotation::Rectangular,
486            SequenceRotation::OpenDssMathutil,
487        ] {
488            let phase = calc_phase_components(sequence, rotation);
489            for (back, value) in calc_sequence_components(phase, rotation)
490                .iter()
491                .zip(sequence)
492            {
493                assert!((back - value).norm() < 1e-12, "{rotation:?}");
494            }
495            // A diag A⁻¹ applied to the phasors is A diag of their sequence.
496            let matrix = calc_phase_matrix_from_sequence(sequence, rotation);
497            let unit = [
498                Complex64::new(1.0, 0.0),
499                Complex64::new(0.2, -0.3),
500                Complex64::new(-0.4, 0.1),
501            ];
502            let image = calc_phase_components(
503                {
504                    let components = calc_sequence_components(unit, rotation);
505                    [
506                        components[0] * sequence[0],
507                        components[1] * sequence[1],
508                        components[2] * sequence[2],
509                    ]
510                },
511                rotation,
512            );
513            for (i, row) in matrix.iter().enumerate() {
514                let value: Complex64 = row.iter().zip(unit).map(|(m, v)| m * v).sum();
515                assert!((value - image[i]).norm() < 1e-12, "{rotation:?}");
516            }
517        }
518        let row = [0, 1, 2].map(|j| calc_circulant_phase_entry(sequence, 0, j));
519        for (back, value) in calc_circulant_sequence_from_phase(row).iter().zip(sequence) {
520            assert!((back - value).norm() < 1e-12);
521        }
522    }
523
524    #[test]
525    fn the_balanced_phase_angles_are_the_positive_sequence_rotation() {
526        use std::f64::consts::{PI, TAU};
527        assert_eq!(
528            [0, 1, 2].map(|k| calc_balanced_phase_angle(k, 3)),
529            [0.0, -2.0 * PI / 3.0, 2.0 * PI / 3.0]
530        );
531        assert_eq!(calc_balanced_phase_angle(4, 3), -TAU / 3.0);
532        assert_eq!(calc_balanced_phase_angle(1, 2), PI);
533        assert_eq!(calc_balanced_phase_angle(0, 0), 0.0);
534        for phases in 1..=4 {
535            assert!(calc_balanced_phase_angle(0, phases).is_sign_positive());
536            assert!(calc_balanced_phase_angle(phases, phases).is_sign_positive());
537        }
538    }
539
540    #[test]
541    fn a_balanced_source_has_its_line_voltage_as_base() {
542        let third = 2.0 * std::f64::consts::PI / 3.0;
543        let terminals = vec!["1".to_owned(), "2".to_owned(), "3".to_owned()];
544        let mut source = VoltageSource::new(
545            "s",
546            "b",
547            terminals,
548            vec![100.0; 3],
549            vec![0.0, -third, third],
550        );
551        let base = source
552            .calc_line_to_line_voltage(&[0, 1, 2], LineVoltageForm::PositiveSequence)
553            .unwrap();
554        assert!((base - 100.0 * 3f64.sqrt()).abs() < 1e-9);
555        source.v_magnitude = vec![120.0, 120.0];
556        source.v_angle = vec![0.0, std::f64::consts::PI];
557        assert!(
558            (source
559                .calc_line_to_line_voltage(&[0, 1], LineVoltageForm::PositiveSequence)
560                .unwrap()
561                - 240.0)
562                .abs()
563                < 1e-9
564        );
565        assert_eq!(
566            source.calc_line_to_line_voltage(&[0, 1, 2, 3], LineVoltageForm::PositiveSequence),
567            None
568        );
569        assert_eq!(
570            source.calc_line_to_line_voltage(&[0], LineVoltageForm::PositiveSequence),
571            Some(120.0)
572        );
573        assert_eq!(
574            source.calc_line_to_line_voltage(&[0], LineVoltageForm::FirstPhase),
575            Some(crate::electrical::calc_wye_line_voltage(120.0))
576        );
577        // The first phase form reads one magnitude: a split phase pair's is
578        // twice it, whatever the second phasor states.
579        source.v_magnitude = vec![120.0, 100.0];
580        assert_eq!(
581            source.calc_line_to_line_voltage(&[0, 1], LineVoltageForm::FirstPhase),
582            Some(240.0)
583        );
584    }
585}