Skip to main content

powerio_tx/
load_voltage.rs

1//! Voltage dependent load power: the one evaluation of a balanced load's
2//! [`LoadVoltageModel`] at a bus voltage magnitude, with its derivative.
3//!
4//! With `x = vm / vn`, the bus voltage magnitude against the load's nominal
5//! voltage (both per unit on the bus base), a load draws
6//!
7//! ```text
8//! P(vm) = p - Σ c_k + Σ c_k x^γ_k        (and Q alike)
9//! ```
10//!
11//! where `p` is the stated [`Load::p`] and each term `c_k x^γ_k` is a ZIP
12//! constant current part (`γ = 1`), a ZIP constant impedance part (`γ = 2`),
13//! or an exponential side (its `γ`, when not zero). The stated power stays
14//! authoritative for everything beyond the terms: the ZIP constant power
15//! part, an exponential `γ = 0` side, or a demand edit written onto `p`.
16
17use crate::network::{Load, LoadVoltageModel};
18
19/// The voltage ratio floor of the one power law term evaluation
20/// ([`powerio_core::electrical::calc_voltage_power_term`]).
21pub use powerio_core::electrical::LOAD_VOLTAGE_RATIO_FLOOR;
22
23/// One voltage dependent part of a load: `coefficient · (vm / v_nom)^exponent`
24/// in the load's power unit.
25#[derive(Debug, Clone, Copy, PartialEq)]
26#[non_exhaustive]
27pub struct LoadVoltageTerm {
28    /// Reactive (`true`) or active (`false`) power.
29    pub reactive: bool,
30    /// The part's power at the nominal voltage.
31    pub coefficient: f64,
32    /// The nominal voltage, per unit on the bus base, positive.
33    pub v_nom: f64,
34    /// The voltage exponent (1 constant current, 2 constant impedance).
35    pub exponent: f64,
36}
37
38impl LoadVoltageTerm {
39    /// A term from its parts.
40    #[must_use]
41    pub const fn new(reactive: bool, coefficient: f64, v_nom: f64, exponent: f64) -> Self {
42        Self {
43            reactive,
44            coefficient,
45            v_nom,
46            exponent,
47        }
48    }
49
50    /// The term's power at magnitude `vm` (per unit) and its derivative with
51    /// respect to `vm`: with `x = vm / v_nom`, `(c x^γ, γ c x^(γ−1) / v_nom)`,
52    /// the one power law term
53    /// ([`powerio_core::electrical::calc_voltage_power_term`], which follows
54    /// the tangent at [`LOAD_VOLTAGE_RATIO_FLOOR`] for `γ < 1`).
55    #[must_use]
56    pub fn calc_power(&self, vm: f64) -> (f64, f64) {
57        let (value, slope) = powerio_core::electrical::calc_voltage_power_term(
58            self.coefficient,
59            self.exponent,
60            vm / self.v_nom,
61        );
62        (value, slope / self.v_nom)
63    }
64
65    /// Whether `vm` lies below the term's ratio floor: a collapsed voltage
66    /// rather than an operating point.
67    #[must_use]
68    pub fn is_below_floor(&self, vm: f64) -> bool {
69        self.exponent != 0.0 && vm / self.v_nom < LOAD_VOLTAGE_RATIO_FLOOR
70    }
71}
72
73/// Why a load's voltage model cannot be evaluated.
74#[derive(Debug, Clone, PartialEq)]
75#[non_exhaustive]
76pub enum LoadVoltageError {
77    /// A stated power, coefficient, or exponent is not finite.
78    NonFiniteCoefficient,
79    /// The stated nominal voltage is not positive and finite.
80    InvalidNominalVoltage { stated: f64 },
81    /// The stated nominal voltage reads as two different usual per unit
82    /// values, in kV against the bus base and in per unit.
83    AmbiguousNominalVoltage {
84        stated: f64,
85        base_kv: f64,
86        as_kv: f64,
87        as_pu: f64,
88    },
89    /// The stated nominal voltage is plausible neither in kV nor in per unit.
90    ImplausibleNominalVoltage { stated: f64, base_kv: f64 },
91}
92
93impl std::fmt::Display for LoadVoltageError {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        match self {
96            Self::NonFiniteCoefficient => write!(f, "states a non-finite coefficient"),
97            Self::InvalidNominalVoltage { stated } => {
98                write!(f, "states a nominal voltage of {stated}")
99            }
100            Self::AmbiguousNominalVoltage {
101                stated,
102                base_kv,
103                as_kv,
104                as_pu,
105            } => write!(
106                f,
107                "states a nominal voltage of {stated}, which reads as {as_kv:.4} pu in kV \
108                 against the bus base of {base_kv} kV and as {as_pu:.4} pu in per unit; state \
109                 it unambiguously (or leave it out for the bus base voltage)"
110            ),
111            Self::ImplausibleNominalVoltage { stated, base_kv } => write!(
112                f,
113                "states a nominal voltage of {stated}, plausible neither in kV against the bus \
114                 base of {base_kv} kV nor in per unit"
115            ),
116        }
117    }
118}
119
120impl std::error::Error for LoadVoltageError {}
121
122/// A load's nominal voltage in per unit on its bus base.
123///
124/// No stated `v_nom` is the bus base voltage (1 per unit), the convention
125/// every PowerIO reader writes. The balanced model does not state the unit of
126/// a stated one, and sources use both, so it is read against the bus base
127/// voltage `base_kv`: as kV giving `v_nom / base_kv`, or as per unit giving
128/// `v_nom`. A reading is plausible in `[0.5, 2]` and usual in `[0.8, 1.25]`.
129/// When the two readings agree, or only one is plausible, or only one is
130/// usual (`v_nom = 0.69` on a 0.69 kV bus is 1 pu in kV, not 0.69 pu), that
131/// reading is taken. When both are usual and differ (a 0.9 kV bus with
132/// `v_nom = 1`), both are plausible and neither usual, or neither is
133/// plausible, the nominal voltage is refused rather than guessed.
134///
135/// # Errors
136/// A non-positive or non-finite `v_nom`, or one no reading makes plausible
137/// or two readings make plausible differently.
138pub fn calc_load_nominal_voltage(
139    v_nom: Option<f64>,
140    base_kv: f64,
141) -> Result<f64, LoadVoltageError> {
142    let Some(stated) = v_nom else {
143        return Ok(1.0);
144    };
145    if !(stated.is_finite() && stated > 0.0) {
146        return Err(LoadVoltageError::InvalidNominalVoltage { stated });
147    }
148    let plausible = |ratio: f64| (0.5..=2.0).contains(&ratio);
149    let usual = |ratio: f64| (0.8..=1.25).contains(&ratio);
150    let mut as_kv = (base_kv.is_finite() && base_kv > 0.0)
151        .then(|| stated / base_kv)
152        .filter(|&ratio| plausible(ratio));
153    let mut as_pu = plausible(stated).then_some(stated);
154    if let (Some(kv), Some(pu)) = (as_kv, as_pu) {
155        match (usual(kv), usual(pu)) {
156            (true, false) => as_pu = None,
157            (false, true) => as_kv = None,
158            _ => {}
159        }
160    }
161    match (as_kv, as_pu) {
162        (Some(kv), Some(pu)) if (kv - pu).abs() <= 1e-9 * kv.max(pu) => Ok(kv),
163        (Some(kv), None) => Ok(kv),
164        (None, Some(pu)) => Ok(pu),
165        (Some(as_kv), Some(as_pu)) => Err(LoadVoltageError::AmbiguousNominalVoltage {
166            stated,
167            base_kv,
168            as_kv,
169            as_pu,
170        }),
171        (None, None) => Err(LoadVoltageError::ImplausibleNominalVoltage { stated, base_kv }),
172    }
173}
174
175/// A load's power at a voltage magnitude, in its own unit, with the
176/// derivatives with respect to the magnitude.
177#[derive(Debug, Clone, Copy, PartialEq)]
178#[non_exhaustive]
179pub struct LoadPowerAtVoltage {
180    pub p: f64,
181    pub q: f64,
182    pub dp_dvm: f64,
183    pub dq_dvm: f64,
184}
185
186impl Load {
187    /// The voltage dependent terms of this load on a bus of base `base_kv`,
188    /// in the load's power unit, or `Ok(None)` for a constant power load.
189    /// A ZIP constant power part and an exponential `γ = 0` side add no
190    /// term, and neither does a zero coefficient.
191    ///
192    /// # Errors
193    /// A non-finite stated power, coefficient or exponent, or a nominal
194    /// voltage [`calc_load_nominal_voltage`] refuses.
195    pub fn calc_voltage_terms(
196        &self,
197        base_kv: f64,
198    ) -> Result<Option<Vec<LoadVoltageTerm>>, LoadVoltageError> {
199        let finite = |values: &[f64]| {
200            if values.iter().all(|value| value.is_finite()) {
201                Ok(())
202            } else {
203                Err(LoadVoltageError::NonFiniteCoefficient)
204            }
205        };
206        match self.voltage_model.as_ref() {
207            Some(LoadVoltageModel::Zip {
208                p_constant_power,
209                q_constant_power,
210                p_constant_current,
211                q_constant_current,
212                p_constant_impedance,
213                q_constant_impedance,
214                v_nom,
215                ..
216            }) => {
217                finite(&[
218                    self.p,
219                    self.q,
220                    *p_constant_power,
221                    *q_constant_power,
222                    *p_constant_current,
223                    *q_constant_current,
224                    *p_constant_impedance,
225                    *q_constant_impedance,
226                ])?;
227                let vn = calc_load_nominal_voltage(*v_nom, base_kv)?;
228                Ok(Some(
229                    [
230                        (false, *p_constant_current, 1.0),
231                        (true, *q_constant_current, 1.0),
232                        (false, *p_constant_impedance, 2.0),
233                        (true, *q_constant_impedance, 2.0),
234                    ]
235                    .into_iter()
236                    .filter(|&(_, c, _)| c != 0.0)
237                    .map(|(reactive, c, g)| LoadVoltageTerm::new(reactive, c, vn, g))
238                    .collect(),
239                ))
240            }
241            Some(LoadVoltageModel::Exponential {
242                p,
243                q,
244                v_nom,
245                gamma_p,
246                gamma_q,
247            }) => {
248                finite(&[self.p, self.q, *p, *q, *gamma_p, *gamma_q])?;
249                let vn = calc_load_nominal_voltage(*v_nom, base_kv)?;
250                Ok(Some(
251                    [(false, *p, *gamma_p), (true, *q, *gamma_q)]
252                        .into_iter()
253                        .filter(|&(_, c, g)| c != 0.0 && g != 0.0)
254                        .map(|(reactive, c, g)| LoadVoltageTerm::new(reactive, c, vn, g))
255                        .collect(),
256                ))
257            }
258            _ => Ok(None),
259        }
260    }
261
262    /// The power this load draws at voltage magnitude `vm` (per unit) on a bus
263    /// of base `base_kv`, in its own unit, and the derivatives with respect to
264    /// `vm`: the stated power less every term's nominal power, plus every
265    /// term at `vm` ([`calc_voltage_terms`](Self::calc_voltage_terms)).
266    ///
267    /// # Errors
268    /// As [`calc_voltage_terms`](Self::calc_voltage_terms).
269    pub fn calc_power_at(
270        &self,
271        vm: f64,
272        base_kv: f64,
273    ) -> Result<LoadPowerAtVoltage, LoadVoltageError> {
274        let mut power = LoadPowerAtVoltage {
275            p: self.p,
276            q: self.q,
277            dp_dvm: 0.0,
278            dq_dvm: 0.0,
279        };
280        for term in self.calc_voltage_terms(base_kv)?.unwrap_or_default() {
281            let (value, slope) = term.calc_power(vm);
282            if term.reactive {
283                power.q += value - term.coefficient;
284                power.dq_dvm += slope;
285            } else {
286                power.p += value - term.coefficient;
287                power.dp_dvm += slope;
288            }
289        }
290        Ok(power)
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297    use crate::network::BusId;
298
299    #[test]
300    fn nominal_voltage_reads_against_the_bus_base() {
301        assert_eq!(calc_load_nominal_voltage(None, 0.4), Ok(1.0));
302        assert!((calc_load_nominal_voltage(Some(0.42), 0.4).unwrap() - 1.05).abs() < 1e-12);
303        assert_eq!(calc_load_nominal_voltage(Some(1.0), 0.4), Ok(1.0));
304        assert_eq!(calc_load_nominal_voltage(Some(0.98), 230.0), Ok(0.98));
305        // A per unit nominal on a 12.47 kV bus is 1 pu, not 1/12.47 or 12.47.
306        assert_eq!(calc_load_nominal_voltage(Some(1.0), 12.47), Ok(1.0));
307        assert!(matches!(
308            calc_load_nominal_voltage(Some(1.0), 0.9),
309            Err(LoadVoltageError::AmbiguousNominalVoltage { .. })
310        ));
311        assert!(calc_load_nominal_voltage(Some(11.0), 230.0).is_err());
312        assert!(calc_load_nominal_voltage(Some(f64::NAN), 230.0).is_err());
313    }
314
315    /// A ZIP load's power at a voltage is its constant power part plus the
316    /// current and impedance parts scaled by the voltage ratio.
317    #[test]
318    fn zip_power_at_a_voltage() {
319        let mut load = Load::new(BusId(1), 30.0, 10.0);
320        load.voltage_model = Some(LoadVoltageModel::Zip {
321            p_constant_power: 12.0,
322            q_constant_power: 4.0,
323            p_constant_current: 9.0,
324            q_constant_current: 3.0,
325            p_constant_impedance: 9.0,
326            q_constant_impedance: 3.0,
327            v_nom: None,
328            load_type: None,
329            scaling: None,
330        });
331        let power = load.calc_power_at(0.95, 230.0).unwrap();
332        assert!((power.p - (12.0 + 9.0 * 0.95 + 9.0 * 0.95 * 0.95)).abs() < 1e-12);
333        assert!((power.q - (4.0 + 3.0 * 0.95 + 3.0 * 0.95 * 0.95)).abs() < 1e-12);
334        assert!((power.dp_dvm - (9.0 + 18.0 * 0.95)).abs() < 1e-12);
335    }
336}