1use powerio_tx::network::GenCost;
12
13use crate::{Error, PiecewiseCostInvalidity, PiecewiseLinearCost, Result};
14
15pub(crate) struct GeneratorCostTerms {
18 pub q: f64,
19 pub c: f64,
20 pub c0: f64,
21 pub piecewise_linear: Option<PiecewiseLinearCost>,
22}
23
24pub(crate) fn generator_cost_terms(
26 cost: &GenCost,
27 gen_index: usize,
28 power_scale: f64,
29) -> Result<GeneratorCostTerms> {
30 match cost.model {
31 1 => Ok(GeneratorCostTerms {
32 q: 0.0,
33 c: 0.0,
34 c0: 0.0,
35 piecewise_linear: Some(piecewise_linear_terms(cost, gen_index, power_scale)?),
36 }),
37 2 => {
38 let (q, c, c0) = quadratic_terms(cost, gen_index)?;
39 Ok(GeneratorCostTerms {
40 q,
41 c,
42 c0,
43 piecewise_linear: None,
44 })
45 }
46 _ => Err(Error::UnsupportedCostModel {
47 gen_index,
48 model: cost.model,
49 ncost: cost.ncost,
50 }),
51 }
52}
53
54fn piecewise_linear_terms(
55 cost: &GenCost,
56 gen_index: usize,
57 power_scale: f64,
58) -> Result<PiecewiseLinearCost> {
59 if cost.ncost < 2 {
60 return Err(Error::InvalidPiecewiseCost {
61 gen_index,
62 reason: PiecewiseCostInvalidity::FewerThanTwoBreakpoints {
63 declared: cost.ncost,
64 },
65 });
66 }
67 let expected_values = cost
68 .ncost
69 .checked_mul(2)
70 .ok_or(Error::InvalidPiecewiseCost {
71 gen_index,
72 reason: PiecewiseCostInvalidity::Truncated {
73 expected_values: usize::MAX,
74 got: cost.coeffs.len(),
75 },
76 })?;
77 if cost.coeffs.len() < expected_values {
78 return Err(Error::InvalidPiecewiseCost {
79 gen_index,
80 reason: PiecewiseCostInvalidity::Truncated {
81 expected_values,
82 got: cost.coeffs.len(),
83 },
84 });
85 }
86
87 let mut power = Vec::with_capacity(cost.ncost);
88 let mut value = Vec::with_capacity(cost.ncost);
89 for (point, pair) in cost.coeffs[..expected_values]
90 .as_chunks::<2>()
91 .0
92 .iter()
93 .enumerate()
94 {
95 let p = pair[0] * power_scale;
96 let v = pair[1];
97 if !p.is_finite() || !v.is_finite() {
98 return Err(Error::InvalidPiecewiseCost {
99 gen_index,
100 reason: PiecewiseCostInvalidity::NonFinitePoint { point },
101 });
102 }
103 if power.last().is_some_and(|previous| p <= *previous) {
104 return Err(Error::InvalidPiecewiseCost {
105 gen_index,
106 reason: PiecewiseCostInvalidity::NonIncreasingPower { point },
107 });
108 }
109 power.push(p);
110 value.push(v);
111 }
112
113 let mut previous_slope: Option<f64> = None;
114 for segment in 0..power.len() - 1 {
115 let slope = (value[segment + 1] - value[segment]) / (power[segment + 1] - power[segment]);
116 if !slope.is_finite() {
117 return Err(Error::InvalidPiecewiseCost {
118 gen_index,
119 reason: PiecewiseCostInvalidity::NonFinitePoint { point: segment + 1 },
120 });
121 }
122 if let Some(previous) = previous_slope {
123 let roundoff = 64.0 * f64::EPSILON * previous.abs().max(slope.abs()).max(1.0);
124 if previous > slope + roundoff {
125 return Err(Error::NonconvexPiecewiseCost { gen_index, segment });
126 }
127 }
128 previous_slope = Some(slope);
129 }
130
131 Ok(PiecewiseLinearCost { power, value })
132}
133
134pub(crate) fn quadratic_terms(cost: &GenCost, gen_index: usize) -> Result<(f64, f64, f64)> {
145 let (q, c, c0) = cost
150 .calc_quadratic_with_constant_tol(GenCost::LEADING_COEFF_TOL)
151 .ok_or(Error::UnsupportedCostModel {
152 gen_index,
153 model: cost.model,
154 ncost: cost.ncost,
155 })?;
156 if q < 0.0 {
160 return Err(Error::ConcaveCost {
161 gen_index,
162 c2: q / 2.0,
163 });
164 }
165 Ok((q, c, c0))
166}
167
168#[must_use]
177pub fn calc_bus_totals(n_buses: usize, bus_of_gen: &[usize], values: &[f64]) -> Vec<f64> {
178 let mut totals = vec![0.0; n_buses];
179 for (generator, &bus) in bus_of_gen.iter().enumerate() {
180 totals[bus] += values[generator];
181 }
182 totals
183}
184
185#[must_use]
190pub fn calc_bus_hosts(n_buses: usize, bus_of_gen: &[usize]) -> Vec<bool> {
191 let mut flags = vec![false; n_buses];
192 for &bus in bus_of_gen {
193 flags[bus] = true;
194 }
195 flags
196}
197
198pub(crate) struct NodalCosts {
200 pub q: Vec<f64>,
201 pub c: Vec<f64>,
202 pub c0: Vec<f64>,
203}
204
205pub(crate) fn combine_costs(
223 n_buses: usize,
224 bus_of_gen: &[usize],
225 q: &[f64],
226 c: &[f64],
227 c0: &[f64],
228) -> NodalCosts {
229 let mut accumulators = vec![BusCost::default(); n_buses];
230 for (generator, &bus) in bus_of_gen.iter().enumerate() {
231 accumulators[bus].add(q[generator], c[generator], c0[generator]);
232 }
233
234 let mut costs = NodalCosts {
235 q: Vec::with_capacity(n_buses),
236 c: Vec::with_capacity(n_buses),
237 c0: Vec::with_capacity(n_buses),
238 };
239 for accumulator in accumulators {
240 let (q, c, c0) = accumulator.finish();
241 costs.q.push(q);
242 costs.c.push(c);
243 costs.c0.push(c0);
244 }
245 costs
246}
247
248#[derive(Clone, Copy)]
249struct BusCost {
250 count: usize,
251 only: (f64, f64, f64),
252 reciprocal_q: f64,
254 weighted_c: f64,
256 weighted_c_squared: f64,
258 flat_c: f64,
260 c0: f64,
261}
262
263impl Default for BusCost {
264 fn default() -> Self {
265 Self {
266 count: 0,
267 only: (0.0, 0.0, 0.0),
268 reciprocal_q: 0.0,
269 weighted_c: 0.0,
270 weighted_c_squared: 0.0,
271 flat_c: f64::INFINITY,
272 c0: 0.0,
273 }
274 }
275}
276
277impl BusCost {
278 fn add(&mut self, q: f64, c: f64, c0: f64) {
279 debug_assert!(q >= 0.0, "concave cost row reached combine_costs: q = {q}");
282 self.count += 1;
283 if self.count == 1 {
284 self.only = (q, c, c0);
285 }
286 self.c0 += c0;
287 if q > 0.0 {
290 self.reciprocal_q += 1.0 / q;
291 self.weighted_c += c / q;
292 self.weighted_c_squared += c * c / q;
293 } else {
294 self.flat_c = self.flat_c.min(c);
295 }
296 }
297
298 fn finish(self) -> (f64, f64, f64) {
299 match self.count {
300 0 => (0.0, 0.0, 0.0),
301 1 => self.only,
302 _ if self.flat_c.is_finite() => {
307 let flat = self.flat_c;
308 let saving = flat * flat * self.reciprocal_q - 2.0 * flat * self.weighted_c
309 + self.weighted_c_squared;
310 (0.0, flat, self.c0 - 0.5 * saving)
311 }
312 _ => {
313 let q = 1.0 / self.reciprocal_q;
314 let c = q * self.weighted_c;
315 (
316 q,
317 c,
318 self.c0 + 0.5 * (c * self.weighted_c - self.weighted_c_squared),
319 )
320 }
321 }
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 #[test]
330 fn one_generator_at_a_bus_passes_through() {
331 let costs = combine_costs(2, &[1], &[0.3], &[7.0], &[11.0]);
332 assert_eq!(costs.q, vec![0.0, 0.3]);
333 assert_eq!(costs.c, vec![0.0, 7.0]);
334 assert_eq!(costs.c0, vec![0.0, 11.0]);
335 }
336
337 #[test]
341 fn a_rounding_artifact_reads_as_a_linear_curve() {
342 let artifact = GenCost::new(2, 0.0, 0.0, vec![1e-17, 3.0, 0.0]);
343 let (q, c, c0) = quadratic_terms(&artifact, 0).expect("a model 2 row");
344 assert_eq!((q, c, c0), (0.0, 3.0, 0.0));
345
346 let costs = combine_costs(1, &[0, 0], &[q, 0.2], &[c, 5.0], &[c0, 0.0]);
347 assert_eq!(costs.q, vec![0.0]);
348 assert_eq!(costs.c, vec![3.0], "the cheaper linear term sets the bus");
349 }
350
351 #[test]
352 fn a_concave_row_is_refused_with_its_source_coefficient() {
353 let concave = GenCost::new(2, 0.0, 0.0, vec![-0.5, 5.0, 0.0]);
354 let error = quadratic_terms(&concave, 3).expect_err("a concave row");
355 match error {
356 Error::ConcaveCost { gen_index, c2 } => {
357 assert_eq!(gen_index, 3);
358 assert_eq!(c2.to_bits(), (-0.5_f64).to_bits());
359 }
360 other => panic!("wrong error: {other}"),
361 }
362 }
363
364 #[test]
367 fn a_tiny_negative_artifact_still_reads_as_a_linear_curve() {
368 let artifact = GenCost::new(2, 0.0, 0.0, vec![-1e-17, 3.0, 0.0]);
369 let (q, c, c0) = quadratic_terms(&artifact, 0).expect("a model 2 row");
370 assert_eq!((q, c, c0), (0.0, 3.0, 0.0));
371 }
372
373 #[test]
374 fn quadratic_curves_combine_by_the_parallel_rule() {
375 let costs = combine_costs(1, &[0, 0], &[2.0, 2.0], &[1.0, 3.0], &[0.0, 0.0]);
376 assert_eq!(costs.q, vec![1.0]);
377 assert_eq!(costs.c, vec![2.0]);
378 assert_eq!(costs.c0, vec![-0.5]);
381 }
382
383 #[test]
384 fn combined_curve_equals_the_least_cost_split() {
385 let (q, c, c0) = ([2.0, 5.0], [1.0, 3.0], [4.0, 6.0]);
386 let costs = combine_costs(1, &[0, 0], &q, &c, &c0);
387 for total in [-2.0_f64, 0.0, 1.5, 40.0] {
388 let lambda = (total + c[0] / q[0] + c[1] / q[1]) / (1.0 / q[0] + 1.0 / q[1]);
390 let split = [(lambda - c[0]) / q[0], (lambda - c[1]) / q[1]];
391 let generator_cost: f64 = (0..2)
392 .map(|i| 0.5 * q[i] * split[i] * split[i] + c[i] * split[i] + c0[i])
393 .sum();
394 let bus_cost = 0.5 * costs.q[0] * total * total + costs.c[0] * total + costs.c0[0];
395 assert!((bus_cost - generator_cost).abs() < 1e-9);
396 }
397 }
398
399 #[test]
400 fn a_generator_without_a_quadratic_term_makes_the_bus_curve_linear() {
401 let costs = combine_costs(1, &[0, 0], &[2.0, 0.0], &[1.0, 3.0], &[1.0, 2.0]);
402 assert_eq!(costs.q, vec![0.0]);
403 assert_eq!(costs.c, vec![3.0]);
404 assert_eq!(costs.c0, vec![2.0]);
407 }
408
409 #[test]
414 fn a_flat_generator_still_leaves_its_neighbours_running() {
415 let (q, c, c0) = ([2.0, 5.0, 0.0], [1.0, 2.0, 3.0], [4.0, 6.0, 7.0]);
416 let costs = combine_costs(1, &[0, 0, 0], &q, &c, &c0);
417 assert_eq!(costs.q, vec![0.0]);
418 assert_eq!(costs.c, vec![3.0], "the flat rate is the bus marginal");
419
420 for total in [0.0_f64, 1.0, 7.5, 100.0] {
421 let split: Vec<f64> = (0..2).map(|i| (c[2] - c[i]) / q[i]).collect();
424 let flat = total - split.iter().sum::<f64>();
425 let generator_cost: f64 = (0..2)
426 .map(|i| 0.5 * q[i] * split[i] * split[i] + c[i] * split[i] + c0[i])
427 .sum::<f64>()
428 + c[2] * flat
429 + c0[2];
430 let bus_cost = costs.c[0] * total + costs.c0[0];
431 assert!(
432 (bus_cost - generator_cost).abs() < 1e-9,
433 "total {total}: bus {bus_cost} vs split {generator_cost}"
434 );
435 }
436 }
437
438 #[test]
439 fn bounds_sum_and_the_flags_mark_the_hosting_buses() {
440 assert_eq!(
441 calc_bus_totals(3, &[0, 2, 2], &[1.0, 2.0, 4.0]),
442 vec![1.0, 0.0, 6.0]
443 );
444 assert_eq!(calc_bus_hosts(3, &[0, 2, 2]), vec![true, false, true]);
445 }
446}