Skip to main content

powerio_matrix/
error.rs

1//! Failures the matrix and dataset builders raise.
2//!
3//! [`Error`] carries what this crate constructs and wraps [`powerio_tx::Error`]
4//! for everything the transmission model raises underneath, so `?` moves that failure across
5//! the boundary without restating it. A caller that only wants the coarse
6//! split reads [`Error::category`], which is the same taxonomy the hub uses.
7
8use powerio_core::DiagnosticInfo;
9use thiserror::Error as ThisError;
10
11use crate::diagnostics::codes;
12
13/// A matrix, sensitivity, or dataset failure.
14#[derive(Debug, ThisError)]
15#[non_exhaustive]
16pub enum Error {
17    /// A failure from the balanced model, its readers, or its writers.
18    #[error(transparent)]
19    Transmission(#[from] powerio_tx::Error),
20
21    /// An underlying I/O failure this crate raised itself.
22    ///
23    /// One the transmission model raised arrives as [`Error::Transmission`] wrapping
24    /// `powerio_tx::Error::Io`, so a caller telling I/O apart from the rest reads
25    /// [`Error::category`] rather than matching this variant.
26    #[error(transparent)]
27    Io(#[from] std::io::Error),
28
29    /// A refused or failed destination commit (an output collision, an
30    /// invalid inventory, a staging failure), carrying the registered core
31    /// failure. Code and category delegate to it.
32    #[error(transparent)]
33    Commit(#[from] powerio_core::Error),
34
35    #[error("output dimension mismatch: matrix is {n}x{n} but RHS has length {b_len}")]
36    DimensionMismatch { n: usize, b_len: usize },
37
38    #[error("dimension mismatch: `{what}` expected length {expected}, got {got}")]
39    ShapeMismatch {
40        what: &'static str,
41        expected: usize,
42        got: usize,
43    },
44
45    #[error("unsupported OPF objective: {reason}")]
46    UnsupportedOpfObjective { reason: String },
47
48    #[error("unsupported AC power flow bus specification")]
49    UnsupportedAcPfSpecification,
50
51    #[error("invalid LinDist3Flow coefficient input: {reason}")]
52    InvalidLinDist3FlowCoefficients { reason: String },
53
54    #[error("{family} constraint selection names unknown identity `{identity}`")]
55    UnknownConstraintIdentity {
56        family: &'static str,
57        identity: String,
58    },
59
60    #[error("{family} has duplicate stable identity `{identity}`")]
61    DuplicateElementIdentity {
62        family: &'static str,
63        identity: String,
64    },
65
66    #[error(
67        "DC sensitivity solve failed: the reference-grounded Laplacian is singular even though every component is grounded"
68    )]
69    SingularNetwork,
70
71    #[error("invalid DC sensitivity option: {reason}")]
72    InvalidSensitivityOptions { reason: String },
73
74    #[error(
75        "{element} between buses {from} and {to} has zero series impedance, so the stored voltages do not determine its flow; merge the buses it joins before evaluating the stated state (BalancedNetwork::merge_buses in Rust, or --merge-buses exact on the command line)"
76    )]
77    UnmergedZeroImpedance {
78        /// The branch or three winding transformer winding, as text.
79        element: String,
80        from: powerio_tx::BusId,
81        to: powerio_tx::BusId,
82    },
83
84    #[error("case has no generators; DC-OPF requires an `mpc.gen` block")]
85    NoGenerators,
86
87    #[error(
88        "generator {gen_index} has an unsupported cost model (model {model}, ncost {ncost}); need polynomial model 2 with degree ≤ 2"
89    )]
90    UnsupportedCostModel {
91        gen_index: usize,
92        model: u8,
93        ncost: usize,
94    },
95
96    #[error("generator {gen_index} has an invalid piecewise linear cost: {reason}")]
97    InvalidPiecewiseCost {
98        gen_index: usize,
99        reason: PiecewiseCostInvalidity,
100    },
101
102    #[error(
103        "generator {gen_index} has a nonconvex piecewise linear cost: segment {segment} has a lower slope than the preceding segment"
104    )]
105    NonconvexPiecewiseCost { gen_index: usize, segment: usize },
106
107    #[error(
108        "generator {gen_index} has a piecewise linear cost that cannot be projected to one nodal quadratic cost"
109    )]
110    PiecewiseNodalCost { gen_index: usize },
111
112    #[error(
113        "generator {gen_index} has a concave cost row (c2 = {c2}); need a nonnegative quadratic coefficient"
114    )]
115    ConcaveCost { gen_index: usize, c2: f64 },
116
117    #[error("matrix-market I/O: {0}")]
118    Mtx(String),
119
120    #[error("gridfm Parquet export: {0}")]
121    Parquet(String),
122
123    #[error("gridfm scenario batch is empty; provide at least one snapshot")]
124    EmptyScenarioBatch,
125
126    #[error("gridfm scenario id overflows i64 when numbering snapshot {index} from base {base}")]
127    ScenarioIdOverflow {
128        base: i64,
129        /// 0-based position of the snapshot whose `base + index` overflowed.
130        index: usize,
131    },
132
133    #[error(
134        "gridfm snapshot scenario {scenario} is normalized; gridfm export expects raw MW and degree fields"
135    )]
136    NormalizedGridfmSnapshot { scenario: i64 },
137
138    #[error(
139        "gridfm snapshot scenario {scenario} has non-finite {element} row {row} field `{field}`: {value}"
140    )]
141    NonFiniteGridfmValue {
142        scenario: i64,
143        element: &'static str,
144        row: usize,
145        field: &'static str,
146        value: f64,
147    },
148
149    #[error(
150        "gridfm snapshot {index} doesn't align with the scenario batch: {reason}; \
151         a batch requires unique scenario ids, one system base, and fixed bus/branch/gen row identities"
152    )]
153    ScenarioShapeMismatch {
154        /// 0-based position of the offending snapshot in the batch (independent
155        /// of the snapshot's scenario id).
156        index: usize,
157        reason: ScenarioMismatch,
158    },
159}
160
161impl Error {
162    /// The registry entry for this error. The match is exhaustive over the
163    /// variant set, so a new variant must be coded here before it compiles.
164    ///
165    /// A hub failure keeps the hub's own code: restating it here would give one
166    /// failure two identities.
167    #[must_use]
168    pub fn code(&self) -> &'static DiagnosticInfo {
169        match self {
170            Error::Transmission(inner) => inner.code(),
171            Error::Commit(inner) => inner.info().unwrap_or(&codes::EMIT_MTX_FAILED),
172            Error::Io(_) => &codes::READ_MATRIX_IO_FAILED,
173            Error::DimensionMismatch { .. } | Error::ShapeMismatch { .. } => {
174                &codes::BUILD_MATRIX_SHAPE_MISMATCH
175            }
176            Error::UnsupportedOpfObjective { .. } => &codes::BUILD_OPF_OBJECTIVE_UNSUPPORTED,
177            Error::UnsupportedAcPfSpecification => &codes::BUILD_AC_PF_SPECIFICATION_UNSUPPORTED,
178            Error::InvalidLinDist3FlowCoefficients { .. } => {
179                &codes::BUILD_LINDIST3FLOW_COEFFICIENT_INVALID
180            }
181            Error::UnknownConstraintIdentity { .. } => {
182                &codes::BUILD_OPF_CONSTRAINT_IDENTITY_UNKNOWN
183            }
184            Error::DuplicateElementIdentity { .. } => &codes::BUILD_OPF_ELEMENT_IDENTITY_DUPLICATE,
185            Error::SingularNetwork => &codes::BUILD_SENSITIVITY_SINGULAR,
186            Error::InvalidSensitivityOptions { .. } => &codes::BUILD_SENSITIVITY_INVALID_OPTION,
187            Error::UnmergedZeroImpedance { .. } => {
188                &powerio_tx::diagnostics::codes::BUILD_BRANCH_ZERO_IMPEDANCE
189            }
190            Error::EmptyScenarioBatch => &codes::BUILD_GRIDFM_EMPTY_BATCH,
191            Error::ScenarioIdOverflow { .. } => &codes::BUILD_GRIDFM_SCENARIO_ID_OVERFLOW,
192            Error::NormalizedGridfmSnapshot { .. } => &codes::BUILD_GRIDFM_NORMALIZED_SNAPSHOT,
193            Error::NonFiniteGridfmValue { .. } => &codes::BUILD_GRIDFM_NOT_A_NUMBER,
194            Error::ScenarioShapeMismatch { .. } => &codes::BUILD_GRIDFM_SCENARIO_SHAPE_MISMATCH,
195            Error::NoGenerators => &powerio_prob::diagnostics::codes::BUILD_INSTANCE_NO_GENERATORS,
196            Error::UnsupportedCostModel { .. } => {
197                &powerio_prob::diagnostics::codes::BUILD_INSTANCE_UNSUPPORTED_COST_MODEL
198            }
199            Error::InvalidPiecewiseCost { .. } => {
200                &powerio_prob::diagnostics::codes::BUILD_INSTANCE_PIECEWISE_COST_INVALID
201            }
202            Error::NonconvexPiecewiseCost { .. } => {
203                &powerio_prob::diagnostics::codes::BUILD_INSTANCE_PIECEWISE_COST_NONCONVEX
204            }
205            Error::PiecewiseNodalCost { .. } => &codes::BUILD_OPF_NODAL_COST_UNSUPPORTED,
206            Error::ConcaveCost { .. } => {
207                &powerio_prob::diagnostics::codes::BUILD_INSTANCE_CONCAVE_COST
208            }
209            Error::Mtx(_) => &codes::EMIT_MTX_FAILED,
210            Error::Parquet(_) => &codes::EMIT_PARQUET_FAILED,
211        }
212    }
213
214    /// Classify this error, using the hub's taxonomy.
215    ///
216    /// The match is exhaustive over the variant set, so a new variant must be
217    /// classified here before it compiles.
218    #[must_use]
219    pub fn category(&self) -> powerio_tx::ErrorCategory {
220        use powerio_tx::ErrorCategory as C;
221        match self {
222            Error::Transmission(inner) => inner.category(),
223            Error::Commit(inner) => inner.category(),
224            Error::Io(_) => C::Io,
225            // A well-formed case that cannot satisfy a requested operation.
226            Error::DimensionMismatch { .. }
227            | Error::ShapeMismatch { .. }
228            | Error::UnsupportedOpfObjective { .. }
229            | Error::UnsupportedAcPfSpecification
230            | Error::InvalidLinDist3FlowCoefficients { .. }
231            | Error::UnknownConstraintIdentity { .. }
232            | Error::DuplicateElementIdentity { .. }
233            | Error::SingularNetwork
234            | Error::InvalidSensitivityOptions { .. }
235            | Error::UnmergedZeroImpedance { .. }
236            | Error::EmptyScenarioBatch
237            | Error::ScenarioIdOverflow { .. }
238            | Error::NormalizedGridfmSnapshot { .. }
239            | Error::NonFiniteGridfmValue { .. }
240            | Error::ScenarioShapeMismatch { .. }
241            | Error::NoGenerators
242            | Error::UnsupportedCostModel { .. }
243            | Error::InvalidPiecewiseCost { .. }
244            | Error::NonconvexPiecewiseCost { .. }
245            | Error::ConcaveCost { .. } => C::Data,
246            Error::PiecewiseNodalCost { .. } => C::Request,
247            // Output-side serialization write failures.
248            Error::Mtx(_) | Error::Parquet(_) => C::Output,
249        }
250    }
251}
252
253/// Why a MATPOWER model 1 generator cost row is unusable.
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
255#[non_exhaustive]
256pub enum PiecewiseCostInvalidity {
257    FewerThanTwoBreakpoints { declared: usize },
258    Truncated { expected_values: usize, got: usize },
259    NonFinitePoint { point: usize },
260    NonIncreasingPower { point: usize },
261}
262
263impl std::fmt::Display for PiecewiseCostInvalidity {
264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265        match self {
266            Self::FewerThanTwoBreakpoints { declared } => {
267                write!(f, "need at least two breakpoints, got {declared}")
268            }
269            Self::Truncated {
270                expected_values,
271                got,
272            } => write!(
273                f,
274                "declared breakpoints require {expected_values} values, got {got}"
275            ),
276            Self::NonFinitePoint { point } => {
277                write!(f, "breakpoint {point} has a non-finite coordinate")
278            }
279            Self::NonIncreasingPower { point } => write!(
280                f,
281                "breakpoint {point} does not have greater power than its predecessor"
282            ),
283        }
284    }
285}
286
287/// The element counts that define a scenario batch's shared base shape. Named
288/// (rather than a bare `(usize, usize, usize)`) so the three same-typed fields
289/// can't be transposed silently in an error message or a comparison.
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291pub struct ElementCounts {
292    pub buses: usize,
293    pub branches: usize,
294    pub gens: usize,
295}
296
297impl std::fmt::Display for ElementCounts {
298    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
299        write!(
300            f,
301            "{} buses, {} branches, {} gens",
302            self.buses, self.branches, self.gens
303        )
304    }
305}
306
307/// Why a gridfm scenario snapshot doesn't line up with the first snapshot's
308/// batch (the row stack uses each table's row number as element identity).
309///
310/// This enum is `#[non_exhaustive]`; downstream matches must include a wildcard
311/// arm.
312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
313#[non_exhaustive]
314pub enum ScenarioMismatch {
315    /// Element counts differ.
316    Counts {
317        expected: ElementCounts,
318        got: ElementCounts,
319    },
320    /// Counts match, but the buses are listed in a different order (so the dense
321    /// bus index wouldn't mean the same bus across snapshots).
322    BusOrder,
323    /// A branch row has a different endpoint pair or component identity.
324    BranchOrder,
325    /// A generator row has a different bus or component identity.
326    GeneratorOrder,
327    /// The snapshot uses a different system power base.
328    BaseMva,
329    /// Another snapshot already uses this scenario id.
330    DuplicateScenarioId { scenario: i64, first_index: usize },
331}
332
333impl std::fmt::Display for ScenarioMismatch {
334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335        match self {
336            Self::Counts { expected, got } => {
337                write!(f, "got ({got}) vs the first snapshot's ({expected})")
338            }
339            Self::BusOrder => {
340                write!(f, "counts match but the bus ids are in a different order")
341            }
342            Self::BranchOrder => write!(
343                f,
344                "counts match but branch endpoints or identities differ by row"
345            ),
346            Self::GeneratorOrder => write!(
347                f,
348                "counts match but generator buses or identities differ by row"
349            ),
350            Self::BaseMva => write!(f, "base_mva differs from the first snapshot"),
351            Self::DuplicateScenarioId {
352                scenario,
353                first_index,
354            } => write!(
355                f,
356                "scenario id {scenario} is already used by snapshot {first_index}"
357            ),
358        }
359    }
360}
361
362/// The result type every fallible entry point in this crate returns.
363pub type Result<T> = std::result::Result<T, Error>;
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use powerio_tx::ErrorCategory::{Data, Output, Parse, Request};
369
370    #[test]
371    fn category_pins_the_intended_buckets() {
372        assert_eq!(Error::SingularNetwork.category(), Data);
373        assert_eq!(Error::EmptyScenarioBatch.category(), Data);
374        assert_eq!(Error::Mtx("write failed".into()).category(), Output);
375        assert_eq!(Error::Parquet("write failed".into()).category(), Output);
376    }
377
378    // Every error is a diagnostic that ended the operation, so the code's
379    // published category and `category()` are one fact.
380    #[test]
381    fn every_error_code_publishes_the_category_the_variant_reports() {
382        let every: Vec<Error> = vec![
383            powerio_tx::Error::MissingField("bus").into(),
384            std::io::Error::from(std::io::ErrorKind::NotFound).into(),
385            Error::DimensionMismatch { n: 2, b_len: 3 },
386            Error::ShapeMismatch {
387                what: "p",
388                expected: 2,
389                got: 3,
390            },
391            Error::UnsupportedOpfObjective {
392                reason: "term".into(),
393            },
394            Error::UnknownConstraintIdentity {
395                family: "branches",
396                identity: "missing".into(),
397            },
398            Error::DuplicateElementIdentity {
399                family: "branches",
400                identity: "duplicate".into(),
401            },
402            Error::SingularNetwork,
403            Error::InvalidSensitivityOptions {
404                reason: "tol".into(),
405            },
406            Error::EmptyScenarioBatch,
407            Error::ScenarioIdOverflow { base: 1, index: 0 },
408            Error::NormalizedGridfmSnapshot { scenario: 1 },
409            Error::NonFiniteGridfmValue {
410                scenario: 1,
411                element: "bus",
412                row: 0,
413                field: "vm",
414                value: f64::NAN,
415            },
416            Error::ScenarioShapeMismatch {
417                index: 1,
418                reason: ScenarioMismatch::BusOrder,
419            },
420            Error::NoGenerators,
421            Error::UnsupportedCostModel {
422                gen_index: 0,
423                model: 1,
424                ncost: 4,
425            },
426            Error::InvalidPiecewiseCost {
427                gen_index: 0,
428                reason: PiecewiseCostInvalidity::FewerThanTwoBreakpoints { declared: 1 },
429            },
430            Error::NonconvexPiecewiseCost {
431                gen_index: 0,
432                segment: 1,
433            },
434            Error::PiecewiseNodalCost { gen_index: 0 },
435            Error::ConcaveCost {
436                gen_index: 0,
437                c2: -0.5,
438            },
439            Error::Mtx("write failed".into()),
440            Error::Parquet("write failed".into()),
441        ];
442        for error in &every {
443            assert_eq!(
444                error.code().category,
445                Some(error.category()),
446                "{}",
447                error.code().code
448            );
449        }
450    }
451
452    #[test]
453    fn piecewise_cost_failures_keep_distinct_diagnostic_meanings() {
454        let malformed = Error::InvalidPiecewiseCost {
455            gen_index: 2,
456            reason: PiecewiseCostInvalidity::FewerThanTwoBreakpoints { declared: 1 },
457        };
458        let nonconvex = Error::NonconvexPiecewiseCost {
459            gen_index: 2,
460            segment: 1,
461        };
462        let nodal_projection = Error::PiecewiseNodalCost { gen_index: 2 };
463
464        assert_eq!(
465            malformed.code().code,
466            "BUILD.INSTANCE.PIECEWISE_COST_INVALID"
467        );
468        assert_eq!(
469            nonconvex.code().code,
470            "BUILD.INSTANCE.PIECEWISE_COST_NONCONVEX"
471        );
472        assert_eq!(
473            nodal_projection.code().code,
474            "BUILD.OPF.NODAL_COST_UNSUPPORTED"
475        );
476        assert_eq!(malformed.category(), Data);
477        assert_eq!(nonconvex.category(), Data);
478        assert_eq!(nodal_projection.category(), Request);
479    }
480
481    #[test]
482    fn a_wrapped_hub_error_keeps_its_own_category() {
483        let wrapped: Error = powerio_tx::Error::MissingField("bus").into();
484        assert_eq!(wrapped.category(), Parse);
485        // And its message, byte for byte: the C ABI reports errors as text, so
486        // a wrapper that restated the message would change what a binding sees.
487        assert_eq!(
488            wrapped.to_string(),
489            powerio_tx::Error::MissingField("bus").to_string()
490        );
491    }
492}