Skip to main content

powerio_matrix/dcopf/
nodal.rs

1//! Aggregation of generator column data into bus space.
2//!
3//! Several generators at one bus are usual in a case file. A bus space
4//! formulation carries one variable for the bus total, so the generator data
5//! must become one entry for each bus.
6//!
7//! Bound aggregation is exact: the sum of the generator ranges is the range
8//! the bus total can reach. Cost aggregation is an approximation, stated in
9//! [`combine_costs`].
10
11use powerio_tx::network::GenCost;
12
13use crate::{Error, PiecewiseCostInvalidity, PiecewiseLinearCost, Result};
14
15/// The complete supported cost data for one generator before unit scaling of
16/// polynomial coefficients.
17pub(crate) struct GeneratorCostTerms {
18    pub q: f64,
19    pub c: f64,
20    pub c0: f64,
21    pub piecewise_linear: Option<PiecewiseLinearCost>,
22}
23
24/// Compile one generator cost without changing its mathematical form.
25pub(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
134/// `(q, c, c0)` of one generator's cost row, as both instance builders read it.
135///
136/// A MATPOWER model 2 row often carries a leading coefficient near 1e-17 that
137/// the source produced by rounding. It states a linear curve, and reading it as
138/// quadratic gives `1/q` near 1e17 wherever the curvature is inverted.
139///
140/// # Errors
141/// [`Error::UnsupportedCostModel`] for a row that states no quadratic curve;
142/// [`Error::ConcaveCost`] for a negative quadratic coefficient, which the
143/// least cost split in [`combine_costs`] cannot price.
144pub(crate) fn quadratic_terms(cost: &GenCost, gen_index: usize) -> Result<(f64, f64, f64)> {
145    // One rule, stated once on the hub type. Rolling it again here diverged
146    // twice: the threshold applied to `2*c2` rather than to the source
147    // coefficient the artifact lives in, and a longer row whose leading
148    // coefficients are artifacts errored here while the hub read it.
149    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    // The readers keep a concave row; the convexity assumption is this
157    // crate's, so the instance builders refuse it here, before bus count
158    // decides whether the row passes through or joins a merge.
159    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/// The per bus totals of an element column: `values[e]` added to bus
169/// `bus_of[e]` for each element, in element order, over `n_buses` buses. The
170/// one sum of a generator (or any element) column onto buses: the nodal
171/// generator data of the DC and AC preparations reads it, and a caller
172/// summing scheduled outputs or reactive limits by bus calls it.
173///
174/// # Panics
175/// Panics if a bus is `>= n_buses` or `values` is shorter than `bus_of`.
176#[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/// Which of `n_buses` buses host at least one element of `bus_of`.
186///
187/// # Panics
188/// Panics if a bus is `>= n_buses`.
189#[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
198/// One cost curve `0.5 q p² + c p + c0` for each bus, in dense bus order.
199pub(crate) struct NodalCosts {
200    pub q: Vec<f64>,
201    pub c: Vec<f64>,
202    pub c0: Vec<f64>,
203}
204
205/// Combine the generator cost curves at each bus into one curve of the bus
206/// total.
207///
208/// The split of a total over quadratic curves that costs least equalizes the
209/// marginal cost of the generators. That split gives the parallel rule
210/// `q = 1 / Σ(1/qᵢ)`, the marginal weighted term `c = q Σ(cᵢ/qᵢ)`, and a
211/// constant that holds the cost of the split at zero total. A generator with
212/// no quadratic term keeps one marginal cost at every output, so it makes the
213/// bus curve linear at the lowest such cost. It does not make the quadratic
214/// generators beside it free: each still runs where its marginal meets that
215/// flat rate, and the saving it books there is the constant
216/// `−½ Σ (c_flat − cᵢ)² / qᵢ`, independent of the bus total.
217///
218/// The result is an approximation. It agrees with the generator space cost
219/// only while the least cost split stays inside the bound of each generator at
220/// the bus. A bus with one generator keeps that generator's coefficients as
221/// they are.
222pub(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    /// `Σ(1/qᵢ)` over the generators with a positive quadratic term.
253    reciprocal_q: f64,
254    /// `Σ(cᵢ/qᵢ)` over the same generators.
255    weighted_c: f64,
256    /// `Σ(cᵢ²/qᵢ)` over the same generators.
257    weighted_c_squared: f64,
258    /// Lowest linear term over the generators with no quadratic term.
259    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        // `quadratic_terms` refuses a negative `q`, so the flat arm below only
280        // ever takes `q == 0` rows.
281        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        // `quadratic_terms` has already zeroed a rounding artifact, which would
288        // otherwise give `1/q` near 1e17 and price the whole bus as free.
289        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            // A flat generator holds the bus marginal at its own rate, so each
303            // quadratic generator sits at the output where its marginal meets
304            // that rate. `Σ (c_flat - cᵢ)² / qᵢ` is what that split saves
305            // against paying the flat rate for the whole total.
306            _ 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    /// A rounding artifact states a linear curve. Read as quadratic it gives
338    /// `1/q` near 1e17, which swamps the parallel sum and prices the bus as
339    /// nearly free.
340    #[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    /// A negative coefficient within the artifact tolerance is the same
365    /// rounding artifact as a positive one: the row reads flat, no refusal.
366    #[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        // The two generators split every total, so the bus curve holds the cost
379        // of the split at zero total.
380        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            // The split that costs least equalizes q p + c over the pair.
389            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        // The quadratic generator runs at (3 - 1) / 2 = 1 whatever the total,
405        // and the 1 the bus saves there comes off the constant.
406        assert_eq!(costs.c0, vec![2.0]);
407    }
408
409    /// The flat branch, held to the same standard as the quadratic one: the
410    /// combined curve must equal the least cost split at every total, not just
411    /// carry the right slope. Reading `c0` as the plain sum of the generators'
412    /// constants overstated the bus by a fixed amount at every dispatch.
413    #[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            // Every quadratic generator meets the flat marginal; the flat one
422            // carries the remainder.
423            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}