powerio_core/electrical.rs
1//! The scalar electrical formulas both network families share: the per unit
2//! impedance base, the power factor relations and the voltage power law
3//! term. Each is the one implementation the transmission, distribution,
4//! composition and matrix crates call.
5
6use std::ops::Div;
7
8/// The impedance base `V² / S` of a voltage base and a power base in
9/// consistent units (volts and volt amperes give ohms, kilovolts and
10/// megavolt amperes give ohms as well). `None` unless both bases are
11/// positive and finite and the quotient is finite; the caller states what an
12/// unusable base means for its own quantity. The same quantity as
13/// [`calc_branch_impedance_base`] with one voltage at both ends.
14#[must_use]
15pub fn calc_impedance_base(voltage: f64, power: f64) -> Option<f64> {
16 calc_branch_impedance_base(voltage, voltage, power)
17}
18
19/// The order in which [`calc_impedance_rebase`] forms `value · Z_base(from)
20/// / Z_base(to)`. Each reader keeps the order it has always used, so its
21/// results stay bit for bit the same; the quantity is the same in every
22/// order.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum RebaseOrder {
25 /// `value · (Z_base(from) / Z_base(to))`, each base by
26 /// [`calc_impedance_base`]; `NaN` when either base is unusable. The
27 /// SINCAL balanced transformer's series impedance.
28 BaseQuotient,
29 /// `value · (S_to / S_from) · (V_from / V_to)²`, unchecked. The PSS/E
30 /// `CM=2` exciting current and the integrated transmission and
31 /// distribution transformer lowering.
32 PowerRatio,
33 /// `value / (S_from / S_to) · (V_from / V_to)²`, unchecked. The PSS/E
34 /// `CM=2` no load loss.
35 InversePowerRatio,
36}
37
38/// `value` taken from the per unit base `(from_voltage, from_power)` to the
39/// base `(to_voltage, to_power)` when it is a per unit impedance, the factor
40/// `Z_base(from) / Z_base(to)`; with the bases swapped it takes a per unit
41/// admittance from `from` to `to`. `order` picks the operation order
42/// ([`RebaseOrder`]). The one per unit rebase: the SINCAL balanced
43/// transformer's series impedance, the PSS/E `CM=2` magnetizing admittance
44/// and the integrated transmission and distribution transformer lowering
45/// read it.
46#[must_use]
47pub fn calc_impedance_rebase(
48 value: f64,
49 from_voltage: f64,
50 from_power: f64,
51 to_voltage: f64,
52 to_power: f64,
53 order: RebaseOrder,
54) -> f64 {
55 let voltage_ratio = || (from_voltage / to_voltage).powi(2);
56 match order {
57 RebaseOrder::BaseQuotient => {
58 match (
59 calc_impedance_base(from_voltage, from_power),
60 calc_impedance_base(to_voltage, to_power),
61 ) {
62 (Some(from), Some(to)) => value * (from / to),
63 _ => f64::NAN,
64 }
65 }
66 RebaseOrder::PowerRatio => value * (to_power / from_power) * voltage_ratio(),
67 RebaseOrder::InversePowerRatio => value / (from_power / to_power) * voltage_ratio(),
68 }
69}
70
71/// The impedance base `V₁ V₂ / S` of a branch between two voltage bases at
72/// a power base, formed as `from_voltage · to_voltage / power`, in
73/// consistent units: the base on which a line joining two nominal voltages
74/// (an IIDM line between voltage levels) states its per unit series
75/// impedance. With `from_voltage == to_voltage` it is
76/// [`calc_impedance_base`]. `None` unless all three bases are positive and
77/// finite and the quotient is positive and finite.
78#[must_use]
79pub fn calc_branch_impedance_base(from_voltage: f64, to_voltage: f64, power: f64) -> Option<f64> {
80 let positive = |x: f64| x.is_finite() && x > 0.0;
81 if !positive(from_voltage) || !positive(to_voltage) || !positive(power) {
82 return None;
83 }
84 Some(calc_squared_voltage_impedance(
85 from_voltage * to_voltage,
86 power,
87 ))
88 .filter(|base| positive(*base))
89}
90
91/// The impedance `V² / S` that draws the power `power` at a voltage whose
92/// squared magnitude is `voltage_squared`, formed as `voltage_squared /
93/// power`, for a real or a complex power (`|V|² / conj(S)` takes
94/// `conj(S)`). With an impedance in place of the power it is the power that
95/// impedance draws, the same quotient. Unchecked: the caller states what an
96/// unusable voltage or power means. The one voltage squared over a power:
97/// [`calc_branch_impedance_base`] (over `V₁ V₂`), the distribution ZIP
98/// coefficient and nominal power conversions and the OpenDSS rated reactor
99/// read it.
100#[must_use]
101pub fn calc_squared_voltage_impedance<T>(voltage_squared: f64, power: T) -> T
102where
103 f64: Div<T, Output = T>,
104{
105 voltage_squared / power
106}
107
108/// The admittance `S / V²` that draws the power `power` at a voltage whose
109/// squared magnitude is `voltage_squared`, formed as `power /
110/// voltage_squared`, for a real or a complex power (`conj(S) / |V|²` takes
111/// `conj(S)`). Unchecked, as [`calc_squared_voltage_impedance`]. The one
112/// power over voltage squared: [`calc_rated_admittance`] is it at
113/// `voltage · voltage`, and the distribution load's nominal admittance and
114/// the transformer magnetizing base read it.
115#[must_use]
116pub fn calc_squared_voltage_admittance<T>(power: T, voltage_squared: f64) -> T
117where
118 T: Div<f64, Output = T>,
119{
120 power / voltage_squared
121}
122
123/// The admittance base `S / V²` of a voltage base and a power base in
124/// consistent units (volts and volt amperes give siemens, kilovolts and
125/// megavolt amperes give siemens as well), formed as `power / (voltage ·
126/// voltage)`. `None` unless both bases are positive and finite and the
127/// quotient is positive and finite. The one admittance base: dividing by it
128/// takes a susceptance or conductance to per unit as dividing by
129/// [`calc_impedance_base`] takes an impedance.
130#[must_use]
131pub fn calc_admittance_base(voltage: f64, power: f64) -> Option<f64> {
132 let positive = |x: f64| x.is_finite() && x > 0.0;
133 if !positive(voltage) || !positive(power) {
134 return None;
135 }
136 Some(calc_rated_admittance(power, voltage)).filter(|base| positive(*base))
137}
138
139/// The admittance that draws `power` at `voltage`, `power / V²`, formed as
140/// `power / (voltage · voltage)` in consistent units: a susceptance from a
141/// rated reactive power (a capacitor bank or a shunt section in Mvar at
142/// kilovolts), a conductance from an active power. The one power over
143/// voltage squared at a real power ([`calc_squared_voltage_admittance`]):
144/// [`calc_admittance_base`], the capacitor stamp, the BMOPF capacitor
145/// lowering, the OpenDSS common return bank and the CGMES and PSS/E shunt
146/// and SVC conversions read it.
147#[must_use]
148pub fn calc_rated_admittance(power: f64, voltage: f64) -> f64 {
149 calc_squared_voltage_admittance(power, voltage * voltage)
150}
151
152/// The power an admittance draws at `voltage`, `admittance · V²`, formed as
153/// `admittance · (voltage · voltage)`: the inverse of
154/// [`calc_rated_admittance`].
155#[must_use]
156pub fn calc_rated_power(admittance: f64, voltage: f64) -> f64 {
157 admittance * (voltage * voltage)
158}
159
160/// `√3`, the line to line over line to neutral voltage ratio of a balanced
161/// three phase system.
162pub const SQRT_3: f64 = 1.732_050_807_568_877_2;
163
164/// The line to neutral voltage of a balanced three phase system from its
165/// line to line voltage, `V_LL / √3`. The one line to neutral conversion
166/// (OpenDSS, MG-RAVENS, pandapower, the transmission and distribution
167/// coupling).
168#[must_use]
169pub fn calc_wye_phase_voltage(line_voltage: f64) -> f64 {
170 line_voltage / SQRT_3
171}
172
173/// The line to line voltage of a balanced three phase system from its line
174/// to neutral voltage, `√3 V_LN`: the inverse of [`calc_wye_phase_voltage`].
175#[must_use]
176pub fn calc_wye_line_voltage(phase_voltage: f64) -> f64 {
177 phase_voltage * SQRT_3
178}
179
180/// The order [`calc_line_apparent_power`] multiplies in. The orders are the
181/// same product and can differ in the last place.
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183#[non_exhaustive]
184pub enum ApparentPowerOrder {
185 /// `factor · V · I`: every reader and writer that follows no other
186 /// tool's rounding.
187 FactorFirst,
188 /// `I · factor · V`: PowSybl's `AbstractConverter.convertToMva`
189 /// (`I / 1000 · √3 · Vnom`, the current passed in kiloamperes).
190 CurrentFirst,
191}
192
193/// The apparent power of a balanced current `current` at the voltage
194/// `voltage`: `factor · V · I`, with `factor` [`SQRT_3`] for a three phase
195/// rating at its line to line voltage and `1` for a single phase one, in
196/// consistent units (kilovolts and kiloamperes give megavolt amperes), the
197/// product taken in `order`. The one rating conversion from current: the
198/// CGMES, UCTE, PowSybl PSS/E and SINCAL readers, the multiconductor to
199/// balanced lowering and the OpenDSS source read it.
200#[must_use]
201pub fn calc_line_apparent_power(
202 voltage: f64,
203 current: f64,
204 factor: f64,
205 order: ApparentPowerOrder,
206) -> f64 {
207 match order {
208 ApparentPowerOrder::FactorFirst => factor * voltage * current,
209 ApparentPowerOrder::CurrentFirst => current * factor * voltage,
210 }
211}
212
213/// The balanced current of an apparent power `power` at `voltage`,
214/// `S / (factor · V)`: the inverse of [`calc_line_apparent_power`]. The
215/// CGMES, UCTE and SINCAL writers and the OpenDSS source and Thevenin
216/// writer read it.
217#[must_use]
218pub fn calc_line_current(power: f64, voltage: f64, factor: f64) -> f64 {
219 power / (factor * voltage)
220}
221
222/// The quadrature leg `√(m² − r²)` of a magnitude `m` and its in phase
223/// part `r`, formed as `√((m − |r|)(m + |r|))`, free of the cancellation of
224/// `m² − r²` near `|r| = m`, and as `m √((1 − q)(1 + q))` with
225/// `q = |r| / m` where that product overflows: the reactance of a short
226/// circuit test from its impedance and
227/// resistance, the magnetizing current of a no load test from its exciting
228/// current and loss, the reactive power of an apparent power and its active
229/// part, and with `m = 1` the sine of a power factor
230/// ([`calc_power_factor_sine`]). Zero when both are zero; `NaN` when
231/// `|r| > m` or either is `NaN`. The caller states what an excess means for
232/// its quantity.
233#[must_use]
234pub fn calc_quadrature(magnitude: f64, real: f64) -> f64 {
235 let real = real.abs();
236 let product = (magnitude - real) * (magnitude + real);
237 if product.is_finite() {
238 return product.sqrt();
239 }
240 let ratio = real / magnitude;
241 magnitude * ((1.0 - ratio) * (1.0 + ratio)).sqrt()
242}
243
244/// Which ratio [`calc_impedance_from_ratio`] reads and how it forms the
245/// split. The forms can differ in the last place.
246#[derive(Clone, Copy, Debug, PartialEq, Eq)]
247#[non_exhaustive]
248pub enum ImpedanceRatioForm {
249 /// An `R / X` ratio: `X = |Z| / hypot(R/X, 1)`, `R = |Z| (R/X) / hypot(R/X, 1)`
250 /// (the SINCAL transformer, source and rated shunt readers).
251 ResistanceOverReactance,
252 /// An `X / R` ratio as OpenDSS `VSource` splits a short circuit
253 /// impedance: `X = |Z| / √(1 + 1 / (X/R)²)`, `R = X / (X/R)`.
254 OpenDssReactanceOverResistance,
255}
256
257/// The divisor `|Z| / X` of an impedance with the given ratio, formed as
258/// `form` states: `hypot(R/X, 1)` or `√(1 + 1 / (X/R)²)`.
259#[must_use]
260pub fn calc_impedance_ratio_divisor(ratio: f64, form: ImpedanceRatioForm) -> f64 {
261 match form {
262 ImpedanceRatioForm::ResistanceOverReactance => ratio.hypot(1.0),
263 ImpedanceRatioForm::OpenDssReactanceOverResistance => (1.0 + 1.0 / (ratio * ratio)).sqrt(),
264 }
265}
266
267/// The resistance and reactance `(R, X)` of an impedance of magnitude
268/// `magnitude` with the given `R / X` or `X / R` ratio, split as `form`
269/// states over [`calc_impedance_ratio_divisor`]. The one impedance from a
270/// magnitude and a ratio: the SINCAL multiconductor transformer, source and
271/// rated shunt readers and the OpenDSS source's short circuit impedance
272/// read it.
273#[must_use]
274pub fn calc_impedance_from_ratio(
275 magnitude: f64,
276 ratio: f64,
277 form: ImpedanceRatioForm,
278) -> (f64, f64) {
279 let divisor = calc_impedance_ratio_divisor(ratio, form);
280 match form {
281 ImpedanceRatioForm::ResistanceOverReactance => {
282 (magnitude * (ratio / divisor), magnitude / divisor)
283 }
284 ImpedanceRatioForm::OpenDssReactanceOverResistance => {
285 let reactance = magnitude / divisor;
286 (reactance / ratio, reactance)
287 }
288 }
289}
290
291/// The sine of a power factor's angle, `sin(acos |pf|) = √((1 − |pf|)(1 + |pf|))`,
292/// formed without the cancellation of `1 − pf²` near unity: the
293/// [`calc_quadrature`] of a unit magnitude. Reactive power
294/// is `S` times this for an apparent power `S`. `NaN` when `|pf| > 1`.
295#[must_use]
296pub fn calc_power_factor_sine(pf: f64) -> f64 {
297 calc_quadrature(1.0, pf)
298}
299
300/// How [`calc_reactive_ratio`] forms `tan(acos |pf|)`. The forms are the
301/// same ratio and can differ in the last place.
302#[derive(Clone, Copy, Debug, PartialEq, Eq)]
303#[non_exhaustive]
304pub enum ReactiveRatioForm {
305 /// [`calc_power_factor_sine`]` / pf`, free of the cancellation of
306 /// `1 − pf²` near unity: every reader and model that follows no
307 /// engine's rounding.
308 Sine,
309 /// `√(1 / pf² − 1)`, negated for `pf < 0`: OpenDSS's `Load`,
310 /// `Generator`, `Storage` and `PVSystem`
311 /// (`kvarBase := kWBase * Sqrt(1.0 / Sqr(PFNominal) - 1.0)`, DSS C-API
312 /// 0.14.5).
313 OpenDss,
314}
315
316/// The reactive over active power ratio a power factor fixes, OpenDSS and
317/// BMOPF by sign: `Q / P = tan(acos |pf|)` with `pf > 0`, Q on the same side
318/// as P, and the opposite sign for `pf < 0`, formed as `form` states.
319/// Infinite at `pf = ±0` and `NaN` when `|pf| > 1`.
320#[must_use]
321pub fn calc_reactive_ratio(pf: f64, form: ReactiveRatioForm) -> f64 {
322 match form {
323 ReactiveRatioForm::Sine => calc_power_factor_sine(pf) / pf,
324 ReactiveRatioForm::OpenDss => {
325 let ratio = (1.0 / (pf * pf) - 1.0).sqrt();
326 if pf < 0.0 { -ratio } else { ratio }
327 }
328 }
329}
330
331/// The derivative of [`calc_reactive_ratio`] with respect to `pf` (either
332/// form),
333/// `−1 / (pf² √(1 − pf²))` on `0 < |pf| < 1`.
334#[must_use]
335pub fn calc_reactive_ratio_derivative(pf: f64) -> f64 {
336 -1.0 / (pf * pf * calc_power_factor_sine(pf))
337}
338
339/// The coefficients `[a, b]` of a fixed power factor written as the row
340/// `a P + b Q = 0`: `a = √((1 − |pf|)(1 + |pf|))` and `b = −pf`, so that
341/// `Q / P = a / pf` ([`calc_reactive_ratio`]'s [`ReactiveRatioForm::Sine`]) and a tiny nonzero power factor
342/// keeps a finite row.
343#[must_use]
344pub fn calc_power_factor_coefficients(pf: f64) -> [f64; 2] {
345 [calc_power_factor_sine(pf), -pf]
346}
347
348/// The derivatives of [`calc_power_factor_coefficients`] with respect to
349/// `pf`: `[−pf / √(1 − pf²), −1]` on `|pf| < 1`.
350#[must_use]
351pub fn calc_power_factor_coefficients_derivative(pf: f64) -> [f64; 2] {
352 [-pf / calc_power_factor_sine(pf), -1.0]
353}
354
355/// Below this voltage ratio a power law term with exponent below one is
356/// continued by its tangent at the floor ([`calc_voltage_power_term`]):
357/// `x^γ` has an unbounded slope at zero for `γ < 1` (and is itself unbounded
358/// for `γ < 0`), and an iterate can pass near zero on its way to a solution.
359pub const LOAD_VOLTAGE_RATIO_FLOOR: f64 = 1e-3;
360
361/// One voltage power law term `c x^γ` at the voltage ratio `x = |V| / V_nom`
362/// and its derivative `γ c x^(γ−1)` with respect to `x`. Exponents 0, 1 and 2
363/// (constant power, current and impedance) are evaluated without `powf`. For
364/// any other `γ < 1` and `x` below [`LOAD_VOLTAGE_RATIO_FLOOR`] the term
365/// follows its tangent at the floor, `c (f₀ + f₀' (x − x₀))`, so value and
366/// slope stay finite and consistent as a voltage approaches zero.
367///
368/// The one voltage dependent load law evaluation: the balanced load terms,
369/// the distribution ZIP, exponential, constant current and impedance laws,
370/// and the multiconductor OPF load law read it.
371#[must_use]
372#[allow(clippy::float_cmp)] // the integer exponents are exact spellings
373pub fn calc_voltage_power_term(coefficient: f64, exponent: f64, ratio: f64) -> (f64, f64) {
374 let (c, g, x) = (coefficient, exponent, ratio);
375 if g == 0.0 {
376 (c, 0.0)
377 } else if g == 1.0 {
378 (c * x, c)
379 } else if g == 2.0 {
380 (c * x * x, 2.0 * c * x)
381 } else if g < 1.0 && x < LOAD_VOLTAGE_RATIO_FLOOR {
382 let f0 = LOAD_VOLTAGE_RATIO_FLOOR.powf(g);
383 let d0 = g * LOAD_VOLTAGE_RATIO_FLOOR.powf(g - 1.0);
384 (c * (f0 + d0 * (x - LOAD_VOLTAGE_RATIO_FLOOR)), c * d0)
385 } else {
386 (c * x.powf(g), c * g * x.powf(g - 1.0))
387 }
388}
389
390/// One voltage power law term `c x^γ` over the log voltage ratio
391/// `ℓ = ln x`, formed as `c e^{γ ℓ}`, with its derivative `γ c e^{γ ℓ}` with
392/// respect to `ℓ`: [`calc_voltage_power_term`] on the positive voltage
393/// domain a log voltage lift defines, where no floor is needed. The one log
394/// voltage term evaluation: the multiconductor OPF load parameter
395/// sensitivity over its log voltage coordinate reads it.
396#[must_use]
397pub fn calc_log_voltage_power_term(coefficient: f64, exponent: f64, log_ratio: f64) -> (f64, f64) {
398 let value = coefficient * (exponent * log_ratio).exp();
399 (value, exponent * value)
400}
401
402/// The sum of voltage power law terms `[coefficient, exponent]` at the
403/// voltage ratio `x`, with its derivative with respect to `x`, each term by
404/// [`calc_voltage_power_term`].
405#[must_use]
406pub fn calc_voltage_power_terms(terms: &[[f64; 2]], ratio: f64) -> (f64, f64) {
407 terms.iter().fold((0.0, 0.0), |(value, slope), &[c, g]| {
408 let (v, d) = calc_voltage_power_term(c, g, ratio);
409 (value + v, slope + d)
410 })
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 #[test]
418 fn impedance_base_needs_positive_finite_bases() {
419 assert_eq!(calc_impedance_base(12.47, 10.0), Some(12.47 * 12.47 / 10.0));
420 assert_eq!(calc_impedance_base(0.0, 10.0), None);
421 assert_eq!(calc_impedance_base(12.47, 0.0), None);
422 assert_eq!(calc_impedance_base(f64::NAN, 1.0), None);
423 assert_eq!(calc_impedance_base(1e300, 1e-300), None);
424 }
425
426 #[test]
427 fn admittance_base_needs_positive_finite_bases() {
428 assert_eq!(
429 calc_admittance_base(12.47, 10.0),
430 Some(10.0 / (12.47 * 12.47))
431 );
432 assert_eq!(calc_admittance_base(0.0, 10.0), None);
433 assert_eq!(calc_admittance_base(12.47, -1.0), None);
434 assert_eq!(calc_admittance_base(f64::INFINITY, 1.0), None);
435 assert_eq!(calc_admittance_base(1e300, 1e-300), None);
436 }
437
438 #[test]
439 #[allow(clippy::float_cmp)] // each order states its exact spelling
440 fn the_rebase_orders_spell_their_operations() {
441 let (value, v1, s1, v2, s2) = (0.37, 13.8, 100.0, 12.47, 37.5);
442 assert_eq!(
443 calc_impedance_rebase(value, v1, s1, v2, s2, RebaseOrder::BaseQuotient),
444 value * ((v1 * v1 / s1) / (v2 * v2 / s2))
445 );
446 assert_eq!(
447 calc_impedance_rebase(value, v1, s1, v2, s2, RebaseOrder::PowerRatio),
448 value * (s2 / s1) * (v1 / v2).powi(2)
449 );
450 assert_eq!(
451 calc_impedance_rebase(value, v1, s1, v2, s2, RebaseOrder::InversePowerRatio),
452 value / (s1 / s2) * (v1 / v2).powi(2)
453 );
454 assert!(calc_impedance_rebase(value, 0.0, s1, v2, s2, RebaseOrder::BaseQuotient).is_nan());
455 }
456
457 #[test]
458 #[allow(clippy::float_cmp)] // each conversion states its exact spelling
459 fn the_rating_conversions_spell_their_products() {
460 assert_eq!(SQRT_3, 3f64.sqrt());
461 assert_eq!(calc_rated_admittance(1.2, 12.47), 1.2 / (12.47 * 12.47));
462 assert_eq!(calc_rated_power(0.5, 12.47), 0.5 * (12.47 * 12.47));
463 assert_eq!(calc_wye_phase_voltage(12_470.0), 12_470.0 / 3f64.sqrt());
464 assert_eq!(calc_wye_line_voltage(7_200.0), 7_200.0 * 3f64.sqrt());
465 let (kv, amps) = (110.0, 650.0);
466 assert_eq!(
467 calc_line_apparent_power(kv, amps, SQRT_3, ApparentPowerOrder::FactorFirst),
468 3f64.sqrt() * kv * amps
469 );
470 assert_eq!(
471 calc_line_apparent_power(kv, amps / 1000.0, SQRT_3, ApparentPowerOrder::CurrentFirst),
472 amps / 1000.0 * 3f64.sqrt() * kv
473 );
474 assert_eq!(
475 calc_line_current(120.0, kv, SQRT_3),
476 120.0 / (3f64.sqrt() * kv)
477 );
478 }
479
480 #[test]
481 fn the_quadrature_leg_and_the_ratio_split_close_their_triangles() {
482 assert!((calc_quadrature(5.0, 3.0) - 4.0).abs() < 1e-15);
483 assert!((calc_quadrature(5.0, -3.0) - 4.0).abs() < 1e-15);
484 assert_eq!(calc_quadrature(0.0, 0.0), 0.0);
485 assert_eq!(calc_quadrature(2.0, 2.0), 0.0);
486 assert!(calc_quadrature(1.0, 1.5).is_nan());
487 assert!(calc_quadrature(0.0, 1.0).is_nan());
488 assert!((calc_quadrature(1e300, 6e299) - 8e299).abs() < 1e285);
489 for form in [
490 ImpedanceRatioForm::ResistanceOverReactance,
491 ImpedanceRatioForm::OpenDssReactanceOverResistance,
492 ] {
493 let (r, x) = calc_impedance_from_ratio(5.0, 0.75, form);
494 assert!((r.hypot(x) - 5.0).abs() < 1e-14);
495 let ratio = match form {
496 ImpedanceRatioForm::ResistanceOverReactance => r / x,
497 _ => x / r,
498 };
499 assert!((ratio - 0.75).abs() < 1e-14);
500 }
501 }
502
503 #[test]
504 fn power_factor_relations_agree_with_the_trigonometric_forms() {
505 for pf in [0.9_f64, -0.85, 0.3, 1.0, -1.0] {
506 let ratio = pf.abs().acos().tan().copysign(pf);
507 assert!((calc_reactive_ratio(pf, ReactiveRatioForm::Sine) - ratio).abs() < 1e-12);
508 assert!((calc_reactive_ratio(pf, ReactiveRatioForm::OpenDss) - ratio).abs() < 1e-12);
509 let [a, b] = calc_power_factor_coefficients(pf);
510 assert!((-a / b - ratio).abs() < 1e-12);
511 }
512 let (pf, h) = (0.8_f64, 1e-6);
513 let fd = (calc_reactive_ratio(pf + h, ReactiveRatioForm::Sine)
514 - calc_reactive_ratio(pf - h, ReactiveRatioForm::Sine))
515 / (2.0 * h);
516 assert!((calc_reactive_ratio_derivative(pf) - fd).abs() < 1e-6);
517 let fd = (calc_power_factor_coefficients(pf + h)[0]
518 - calc_power_factor_coefficients(pf - h)[0])
519 / (2.0 * h);
520 assert!((calc_power_factor_coefficients_derivative(pf)[0] - fd).abs() < 1e-6);
521 }
522
523 #[test]
524 fn a_power_term_continues_by_its_tangent_below_the_floor() {
525 let (v, d) = calc_voltage_power_term(2.0, 1.5, 0.9);
526 assert!((v - 2.0 * 0.9_f64.powf(1.5)).abs() < 1e-15);
527 assert!((d - 3.0 * 0.9_f64.sqrt()).abs() < 1e-15);
528 let (v, d) = calc_voltage_power_term(1.0, 0.5, 0.0);
529 assert!(v.is_finite() && d.is_finite() && v > 0.0);
530 assert_eq!(calc_voltage_power_term(3.0, 0.0, 0.0), (3.0, 0.0));
531 let (v, d) = calc_voltage_power_terms(&[[1.0, 2.0], [0.5, 1.0]], 0.5);
532 assert!((v - 0.5).abs() < 1e-15 && (d - 1.5).abs() < 1e-15);
533 let (v, d) = calc_log_voltage_power_term(2.0, 1.5, 0.9_f64.ln());
534 assert!((v - 2.0 * 0.9_f64.powf(1.5)).abs() < 1e-15);
535 assert!((d - 1.5 * v).abs() < 1e-15);
536 }
537}