1use crate::network::{Load, LoadVoltageModel};
18
19pub use powerio_core::electrical::LOAD_VOLTAGE_RATIO_FLOOR;
22
23#[derive(Debug, Clone, Copy, PartialEq)]
26#[non_exhaustive]
27pub struct LoadVoltageTerm {
28 pub reactive: bool,
30 pub coefficient: f64,
32 pub v_nom: f64,
34 pub exponent: f64,
36}
37
38impl LoadVoltageTerm {
39 #[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 #[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 #[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#[derive(Debug, Clone, PartialEq)]
75#[non_exhaustive]
76pub enum LoadVoltageError {
77 NonFiniteCoefficient,
79 InvalidNominalVoltage { stated: f64 },
81 AmbiguousNominalVoltage {
84 stated: f64,
85 base_kv: f64,
86 as_kv: f64,
87 as_pu: f64,
88 },
89 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
122pub 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#[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 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 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 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 #[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}