Skip to main content

powerio_tx/
diagnostics.rs

1//! The codes this crate emits, and the registry gates over them.
2//!
3//! The record, the code grammar, the severity ladder, and the stage family live
4//! in `powerio-core`. What lives here is the transmission side registry: one
5//! [`DiagnosticInfo`] per code, declared once, so an emission site names an
6//! entry rather than a loose string and every emitted code is registered by
7//! construction.
8//!
9//! Codes are families, not one per site: what differs between two sites of a
10//! family is which field or record it was, which belongs in `details` where a
11//! consumer can read it, rather than in a code nobody can enumerate.
12
13// The collector is crate-private implementation support, not API: each
14// emitting crate carries its own copy (src/collect.rs) and never exports it.
15pub(crate) use crate::collect::Diagnostics;
16
17pub use powerio_core::{
18    Diagnostic, DiagnosticCode, DiagnosticInfo, DiagnosticSeverity, DiagnosticStage, ErrorCategory,
19    check_registry, code_is_well_formed, render_diagnostic, render_diagnostics,
20};
21
22use crate::format::TargetFormat;
23
24/// The write side family every target shares.
25///
26/// A writer's fidelity losses are the same eleven questions for every target —
27/// what was dropped, what was defaulted, what was collapsed — so the family is
28/// declared once per target and the shared writer passes take the target's
29/// family rather than a label they cannot turn into a code.
30#[derive(Clone, Copy, Debug)]
31pub struct EmitFamily {
32    /// A field the target format has no column or key for.
33    pub field_dropped: DiagnosticInfo,
34    /// A whole element or record the target does not model.
35    pub record_dropped: DiagnosticInfo,
36    /// A value the target requires and the source never stated.
37    pub value_defaulted: DiagnosticInfo,
38    /// Richer structure reduced to what the target's one field can hold.
39    pub value_collapsed: DiagnosticInfo,
40    /// A stated value replaced by another the target can represent.
41    pub value_substituted: DiagnosticInfo,
42    /// A value shortened to the target's width, e.g. a cost curve order.
43    pub value_truncated: DiagnosticInfo,
44    /// A branch rating set beyond the target's rate_a/rate_b/rate_c.
45    pub rating_set_dropped: DiagnosticInfo,
46    /// Source format passthrough fields the writer does not replay.
47    pub extras_dropped: DiagnosticInfo,
48    /// The area table, which is typed rather than passthrough.
49    pub areas_dropped: DiagnosticInfo,
50    /// A non-finite value written as a sentinel or a JSON null.
51    pub not_a_number: DiagnosticInfo,
52    /// The network has no reference bus for the target's solver to key on.
53    pub reference_missing: DiagnosticInfo,
54    /// A normalized line lands in the target's transformer section.
55    pub element_relabeled: DiagnosticInfo,
56}
57
58macro_rules! emit_family {
59    ($name:ident, $scope:literal, $label:literal) => {
60        /// The write side family for this target.
61        pub const $name: EmitFamily = EmitFamily {
62            field_dropped: DiagnosticInfo::new(
63                concat!("EMIT.", $scope, ".FIELD_DROPPED"),
64                DiagnosticSeverity::Warning,
65                concat!("a field ", $label, " has no place for was dropped"),
66            ),
67            record_dropped: DiagnosticInfo::new(
68                concat!("EMIT.", $scope, ".RECORD_DROPPED"),
69                DiagnosticSeverity::Warning,
70                concat!("an element ", $label, " does not model was dropped"),
71            ),
72            value_defaulted: DiagnosticInfo::new(
73                concat!("EMIT.", $scope, ".VALUE_DEFAULTED"),
74                DiagnosticSeverity::Warning,
75                concat!("a value ", $label, " requires was synthesized"),
76            ),
77            value_collapsed: DiagnosticInfo::new(
78                concat!("EMIT.", $scope, ".VALUE_COLLAPSED"),
79                DiagnosticSeverity::Warning,
80                concat!("structure reduced to what ", $label, " can carry"),
81            ),
82            value_substituted: DiagnosticInfo::new(
83                concat!("EMIT.", $scope, ".VALUE_SUBSTITUTED"),
84                DiagnosticSeverity::Warning,
85                concat!("a stated value was replaced by one ", $label, " can hold"),
86            ),
87            value_truncated: DiagnosticInfo::new(
88                concat!("EMIT.", $scope, ".VALUE_TRUNCATED"),
89                DiagnosticSeverity::Warning,
90                concat!("a value was shortened to the width ", $label, " carries"),
91            ),
92            rating_set_dropped: DiagnosticInfo::new(
93                concat!("EMIT.", $scope, ".RATING_SET_DROPPED"),
94                DiagnosticSeverity::Warning,
95                concat!(
96                    "a branch rating set beyond rate_a/rate_b/rate_c was dropped: ",
97                    $label,
98                    " has no field for it"
99                ),
100            ),
101            extras_dropped: DiagnosticInfo::new(
102                concat!("EMIT.", $scope, ".EXTRAS_DROPPED"),
103                DiagnosticSeverity::Warning,
104                concat!(
105                    "source format passthrough fields the ",
106                    $label,
107                    " writer does not replay were dropped"
108                ),
109            ),
110            areas_dropped: DiagnosticInfo::new(
111                concat!("EMIT.", $scope, ".AREAS_DROPPED"),
112                DiagnosticSeverity::Warning,
113                concat!("the area table was dropped: ", $label, " emits none"),
114            ),
115            not_a_number: DiagnosticInfo::new(
116                concat!("EMIT.", $scope, ".NOT_A_NUMBER"),
117                DiagnosticSeverity::Warning,
118                concat!(
119                    "a non-finite value was written as the sentinel ",
120                    $label,
121                    " uses, because it has no Inf or NaN"
122                ),
123            ),
124            reference_missing: DiagnosticInfo::new(
125                concat!("EMIT.", $scope, ".REFERENCE_MISSING"),
126                DiagnosticSeverity::Warning,
127                concat!(
128                    "the network has no reference bus, which ",
129                    $label,
130                    " consumers reject"
131                ),
132            ),
133            element_relabeled: DiagnosticInfo::new(
134                concat!("EMIT.", $scope, ".ELEMENT_RELABELED"),
135                DiagnosticSeverity::Warning,
136                concat!(
137                    "a normalized line reads as a transformer in the ",
138                    $label,
139                    " layout"
140                ),
141            ),
142        };
143    };
144}
145
146impl EmitFamily {
147    /// Every entry, for the registry gates and the generated reference.
148    #[must_use]
149    pub fn entries(&'static self) -> [&'static DiagnosticInfo; 12] {
150        [
151            &self.field_dropped,
152            &self.record_dropped,
153            &self.value_defaulted,
154            &self.value_collapsed,
155            &self.value_substituted,
156            &self.value_truncated,
157            &self.rating_set_dropped,
158            &self.extras_dropped,
159            &self.areas_dropped,
160            &self.not_a_number,
161            &self.reference_missing,
162            &self.element_relabeled,
163        ]
164    }
165}
166
167/// One [`EmitFamily`] per write target, plus the codes a single reader or a
168/// single writer owns.
169pub mod codes {
170    use super::{DiagnosticInfo, DiagnosticSeverity, EmitFamily};
171
172    emit_family!(EMIT_MATPOWER, "MATPOWER", "MATPOWER .m");
173    emit_family!(EMIT_PSSE, "PSSE", "PSS/E .raw");
174    emit_family!(EMIT_PSLF, "PSLF", "PSLF .epc");
175    emit_family!(EMIT_PANDAPOWER, "PANDAPOWER", "pandapower JSON");
176    emit_family!(EMIT_PYPSA, "PYPSA", "the PyPSA CSV folder");
177    emit_family!(EMIT_POWERWORLD, "POWERWORLD", "PowerWorld .aux");
178    emit_family!(EMIT_POWERMODELS, "POWERMODELS", "PowerModels JSON");
179    emit_family!(EMIT_EGRET, "EGRET", "egret JSON");
180    emit_family!(EMIT_SURGE, "SURGE", "Surge JSON");
181    emit_family!(EMIT_PIO_JSON, "PIO_JSON", "the .pio.json snapshot");
182
183    powerio_core::diagnostic_codes! {
184        // PARSE: the source text could not be decoded as given.
185        /// A leading UTF-8 byte order mark was removed before the reader saw
186        /// the text, so a same-format echo differs by exactly those bytes.
187        PARSE_SOURCE_BOM_STRIPPED = "PARSE.SOURCE.BOM_STRIPPED", Remark,
188            "a leading UTF-8 byte order mark was removed before the reader ran", retired = "0.10.0";
189        PARSE_MATPOWER_MALFORMED = "PARSE.MATPOWER.MALFORMED", Error,
190            "a MATPOWER matrix is missing, short, unparseable, or unbalanced", category = Parse;
191        PARSE_SOURCE_MALFORMED = "PARSE.SOURCE.MALFORMED", Error,
192            "a format reader refused the source it was given", category = Parse;
193
194        // READ: decoded, but not representable in the canonical model.
195        READ_PSSE_FIELD_DROPPED = "READ.PSSE.FIELD_DROPPED", Warning,
196            "a PSS/E field with no canonical home was dropped";
197        READ_PSSE_VALUE_SUBSTITUTED = "READ.PSSE.VALUE_SUBSTITUTED", Warning,
198            "a PSS/E value the record states could not be used as given";
199        READ_PSSE_VALUE_UNSUPPORTED = "READ.PSSE.VALUE_UNSUPPORTED", Warning,
200            "a PSS/E code word (CZ, CW, CM) outside the modeled set was read as the default";
201        READ_PSSE_REFERENCE_DROPPED = "READ.PSSE.REFERENCE_DROPPED", Warning,
202            "a PSS/E control pointer names a bus the case does not declare";
203        READ_PSSE_SECTION_UNSUPPORTED = "READ.PSSE.SECTION_UNSUPPORTED", Warning,
204            "a PSS/E section is preserved in a same-format echo only";
205        READ_PSSE_RETAINED_SOURCE_ONLY = "READ.PSSE.RETAINED_SOURCE_ONLY", Remark,
206            "a PSS/E field survives in extras rather than in a typed field";
207
208        READ_PSLF_VALUE_DEFAULTED = "READ.PSLF.VALUE_DEFAULTED", Warning,
209            "a PSLF value the model needs was not in the source and was defaulted";
210        READ_PSLF_VALUE_APPROXIMATED = "READ.PSLF.VALUE_APPROXIMATED", Warning,
211            "a PSLF value was read through an approximation the .epc model forces";
212        READ_PSLF_RECORD_DROPPED = "READ.PSLF.RECORD_DROPPED", Warning,
213            "a PSLF record could not be mapped and was dropped";
214        READ_PSLF_SOURCE_MALFORMED = "READ.PSLF.SOURCE_MALFORMED", Warning,
215            "a PSLF section header, count, or end marker disagrees with the records";
216        READ_PSLF_RETAINED_SOURCE_ONLY = "READ.PSLF.RETAINED_SOURCE_ONLY", Remark,
217            "a PSLF section survives in the retained source or in extras only";
218
219        READ_PANDAPOWER_FIELD_DROPPED = "READ.PANDAPOWER.FIELD_DROPPED", Warning,
220            "a pandapower field with no canonical home was dropped";
221        READ_PANDAPOWER_VALUE_INFERRED = "READ.PANDAPOWER.VALUE_INFERRED", Warning,
222            "a value pandapower does not store was reconstructed on a declared convention";
223        READ_PANDAPOWER_TABLE_UNSUPPORTED = "READ.PANDAPOWER.TABLE_UNSUPPORTED", Warning,
224            "a pandapower table is not mapped into the canonical model";
225
226        READ_PYPSA_TABLE_UNSUPPORTED = "READ.PYPSA.TABLE_UNSUPPORTED", Warning,
227            "a PyPSA table is not mapped into the canonical model";
228        READ_PYPSA_VALUE_APPROXIMATED = "READ.PYPSA.VALUE_APPROXIMATED", Warning,
229            "a PyPSA element was read through the nearest canonical element";
230        READ_PYPSA_NAME_REMAPPED = "READ.PYPSA.NAME_REMAPPED", Warning,
231            "a PyPSA bus name collides with another and was keyed by its numeric id";
232
233        READ_POWERWORLD_VALUE_DEFAULTED = "READ.POWERWORLD.VALUE_DEFAULTED", Warning,
234            "a PowerWorld field this binary vintage does not locate was defaulted";
235        READ_POWERWORLD_RETAINED_SOURCE_ONLY = "READ.POWERWORLD.RETAINED_SOURCE_ONLY", Warning,
236            "a PowerWorld aux data block survives in the retained source only";
237
238        READ_POWERMODELS_RECORD_DROPPED = "READ.POWERMODELS.RECORD_DROPPED", Warning,
239            "a PowerModels document states more than the canonical snapshot holds";
240        READ_POWERMODELS_FIELD_DROPPED = "READ.POWERMODELS.FIELD_DROPPED", Warning,
241            "a PowerModels field the canonical model cannot state was dropped";
242
243        READ_GOC3_VALUE_INFERRED = "READ.GOC3.VALUE_INFERRED", Warning,
244            "a GO Challenge 3 value the document never states was inferred";
245        READ_GOC3_RETAINED_SOURCE_ONLY = "READ.GOC3.RETAINED_SOURCE_ONLY", Warning,
246            "a GO Challenge 3 section survives in the retained source only";
247
248        READ_OPFDATA_FIELD_DROPPED = "READ.OPFDATA.FIELD_DROPPED", Warning,
249            "an OPFData field outside the published schema is not in the snapshot";
250        READ_OPFDATA_VALUE_INFERRED = "READ.OPFDATA.VALUE_INFERRED", Warning,
251            "OPFData carries no identity or frequency, so the reader synthesized them";
252        READ_OPFDATA_RETAINED_SOURCE_ONLY = "READ.OPFDATA.RETAINED_SOURCE_ONLY", Warning,
253            "an OPFData generator's solver initial values are carried in the parsed solution instead of the network snapshot";
254
255        READ_SURGE_RETAINED_SOURCE_ONLY = "READ.SURGE.RETAINED_SOURCE_ONLY", Warning,
256            "a Surge section survives in the retained source only";
257
258        READ_GEO_SOURCE_MALFORMED = "READ.GEO.SOURCE_MALFORMED", Warning,
259            "a geo layer row could not be read and was skipped";
260        READ_GEO_NOTES_TRUNCATED = "READ.GEO.NOTES_TRUNCATED", Warning,
261            "the geo reader stopped recording notes at its budget";
262
263        READ_IO_FAILED = "READ.IO.FAILED", Error,
264            "the case file could not be read", category = Io;
265
266        // CANONICALIZE: normalization of an already-read network.
267        CANONICALIZE_NORMALIZE_BOUNDS_CLAMPED = "CANONICALIZE.NORMALIZE.BOUNDS_CLAMPED", Remark,
268            "a branch angle difference bound was clamped into the modeled range";
269        CANONICALIZE_NORMALIZE_NO_REFERENCE_BUS = "CANONICALIZE.NORMALIZE.NO_REFERENCE_BUS", Error,
270            "no reference bus can be established: no bus hosts an in-service generator",
271            category = Data;
272        CANONICALIZE_NORMALIZE_REFERENCE_DESIGNATED =
273            "CANONICALIZE.NORMALIZE.REFERENCE_DESIGNATED", Warning,
274            "the case states no surviving reference bus, so normalization designated a slack";
275        CANONICALIZE_NORMALIZE_GEN_COST_ABSENT =
276            "CANONICALIZE.NORMALIZE.GEN_COST_ABSENT", Warning,
277            "the solver-ready copy has in-service generators and no cost data, so any cost objective built from it is zero";
278        CANONICALIZE_NORMALIZE_INVALID_OPTION = "CANONICALIZE.NORMALIZE.INVALID_OPTION", Error,
279            "a normalize option is outside the range it is defined on", category = Data;
280        CANONICALIZE_NORMALIZE_INVALID_BASE_MVA = "CANONICALIZE.NORMALIZE.INVALID_BASE_MVA", Error,
281            "the case base MVA is not a positive finite number", category = Data;
282
283        // BUILD: assembling a derived object from a network that already parsed.
284        BUILD_INDEX_UNKNOWN_BUS = "BUILD.INDEX.UNKNOWN_BUS", Error,
285            "an element references a bus id the case does not declare", category = Data;
286        BUILD_INDEX_REFERENCE_BUS_COUNT = "BUILD.INDEX.REFERENCE_BUS_COUNT", Error,
287            "the index needs exactly one reference bus", category = Data;
288        BUILD_INDEX_UNGROUNDED_COMPONENT = "BUILD.INDEX.UNGROUNDED_COMPONENT", Error,
289            "a connected component has no reference bus to ground", category = Data;
290        BUILD_BRANCH_ZERO_IMPEDANCE = "BUILD.BRANCH.ZERO_IMPEDANCE", Error,
291            "a branch has a zero matrix denominator under the selected build options",
292            category = Data;
293        BUILD_BRANCH_NOT_A_NUMBER = "BUILD.BRANCH.NOT_A_NUMBER", Error,
294            "a branch susceptance is not finite", category = Data;
295        BUILD_BRANCH_DEGENERATE_TAP = "BUILD.BRANCH.DEGENERATE_TAP", Error,
296            "a branch tap ratio is too small to divide by", category = Data;
297        BUILD_GEO_UNLOCATED_ELEMENTS = "BUILD.GEO.UNLOCATED_ELEMENTS", Error,
298            "a geo apply left elements with no location or route", category = Data;
299        BUILD_GEO_APPLY_SUMMARY = "BUILD.GEO.APPLY_SUMMARY", Remark,
300            "how many elements a geo apply located";
301        BUILD_GEO_UNMATCHED_FEATURE = "BUILD.GEO.UNMATCHED_FEATURE", Warning,
302            "a geo feature matched no element in the network";
303
304        // VALIDATE: the case's own internal consistency.
305        /// Emitted by the stored document's payload validation in the facade;
306        /// declared here because this crate owns the balanced model.
307        VALIDATE_BALANCED_STRUCTURE = "VALIDATE.BALANCED.STRUCTURE", Error,
308            "a balanced payload's referential integrity does not hold";
309        VALIDATE_BALANCED_VALUE_DOMAIN = "VALIDATE.BALANCED.VALUE_DOMAIN", Warning,
310            "a balanced payload value is outside the domain the model states";
311        VALIDATE_BALANCED_PAYLOAD_IDENTITY = "VALIDATE.BALANCED.PAYLOAD_IDENTITY", Error,
312            "a balanced payload's uid identity does not hold";
313        /// Retired in 0.9.0: every transmission read finding now carries its
314        /// own code, so the stored document no longer wraps them under one
315        /// catch-all.
316        READ_TRANSMISSION_PARSE_WARNING = "READ.TRANSMISSION.PARSE_WARNING", Warning,
317            "a transmission parse finding with no identity of its own", retired = "0.9.0";
318        VALIDATE_GEN_COST_MISSING = "VALIDATE.GEN_COST.MISSING", Error,
319            "a generator carries no cost data under a policy that requires one", category = Data;
320        VALIDATE_GEN_COST_NOT_A_NUMBER = "VALIDATE.GEN_COST.NOT_A_NUMBER", Error,
321            "a default generator cost field is not finite", category = Data;
322        VALIDATE_GEN_COST_PATCH_INVALID = "VALIDATE.GEN_COST.PATCH_INVALID", Error,
323            "a generator cost patch row is not usable", category = Data;
324        VALIDATE_GEN_COST_COUNT_MISMATCH = "VALIDATE.GEN_COST.COUNT_MISMATCH", Error,
325            "the cost table has neither one row per generator nor two", category = Data;
326        VALIDATE_DC_LINE_COST_COUNT_MISMATCH = "VALIDATE.DC_LINE_COST.COUNT_MISMATCH", Error,
327            "the dcline cost table has other than one row per dcline", category = Data;
328
329        // LOWER: a policy applied on the way into a target.
330        TRANSFORM_GEN_COST_POLICY_APPLIED = "TRANSFORM.GEN_COST.POLICY_APPLIED", Remark,
331            "a write time generator cost policy patched or synthesized costs";
332
333        // REQUEST: the call named something powerio does not provide.
334        REQUEST_FORMAT_UNKNOWN = "REQUEST.FORMAT.UNKNOWN", Error,
335            "the named case format is not one powerio reads", category = Request;
336        REQUEST_FORMAT_WRITE_UNSUPPORTED = "REQUEST.FORMAT.WRITE_UNSUPPORTED", Error,
337            "the named case format is read only and has no writer", category = Request;
338
339        // Write side codes a single target owns.
340        /// The default `.raw` target is revision 33, so writing a newer source
341        /// through it re-emits the older layout.
342        EMIT_PSSE_DOWNGRADED = "EMIT.PSSE.DOWNGRADED", Warning,
343            "a newer PSS/E revision was written into an older layout";
344        EMIT_PSSE_RATING_SET_REMAPPED = "EMIT.PSSE.RATING_SET_REMAPPED", Remark,
345            "a named branch rating set was written into a PSS/E numbered rating slot";
346    }
347
348    /// Every write target's family, in the order [`super::registry`] reports
349    /// them.
350    pub const EMIT_FAMILIES: [&EmitFamily; 10] = [
351        &EMIT_MATPOWER,
352        &EMIT_PSSE,
353        &EMIT_PSLF,
354        &EMIT_PANDAPOWER,
355        &EMIT_PYPSA,
356        &EMIT_POWERWORLD,
357        &EMIT_POWERMODELS,
358        &EMIT_EGRET,
359        &EMIT_SURGE,
360        &EMIT_PIO_JSON,
361    ];
362}
363
364/// Every code this crate declares.
365#[must_use]
366pub fn registry() -> Vec<&'static DiagnosticInfo> {
367    let mut all: Vec<&'static DiagnosticInfo> = codes::ALL.to_vec();
368    for family in codes::EMIT_FAMILIES {
369        all.extend(family.entries());
370    }
371    all
372}
373
374impl TargetFormat {
375    /// The write side family for this target.
376    #[must_use]
377    pub fn emit_family(self) -> &'static EmitFamily {
378        match self {
379            TargetFormat::Matpower => &codes::EMIT_MATPOWER,
380            TargetFormat::Psse { .. } => &codes::EMIT_PSSE,
381            TargetFormat::Pslf => &codes::EMIT_PSLF,
382            TargetFormat::PandapowerJson => &codes::EMIT_PANDAPOWER,
383            TargetFormat::PowerWorld => &codes::EMIT_POWERWORLD,
384            TargetFormat::PowerModelsJson => &codes::EMIT_POWERMODELS,
385            TargetFormat::EgretJson => &codes::EMIT_EGRET,
386            TargetFormat::SurgeJson => &codes::EMIT_SURGE,
387            // Neither GOC3 nor OPFData has a writer: the request is refused
388            // before any family is consulted, and
389            // `REQUEST.FORMAT.WRITE_UNSUPPORTED` carries it.
390            TargetFormat::Goc3Json | TargetFormat::DeepMindOpfDataJson => &codes::EMIT_PIO_JSON,
391        }
392    }
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398
399    #[test]
400    fn the_registry_is_sound() {
401        let problems = check_registry(registry());
402        assert!(problems.is_empty(), "{problems:#?}");
403    }
404
405    #[test]
406    fn every_write_target_has_a_family_of_its_own() {
407        let mut scopes: Vec<&str> = codes::EMIT_FAMILIES
408            .iter()
409            .map(|f| f.field_dropped.code.split('.').nth(1).unwrap())
410            .collect();
411        scopes.sort_unstable();
412        scopes.dedup();
413        assert_eq!(scopes.len(), codes::EMIT_FAMILIES.len());
414        assert_eq!(
415            TargetFormat::Psse { rev: 33 }
416                .emit_family()
417                .field_dropped
418                .code,
419            "EMIT.PSSE.FIELD_DROPPED"
420        );
421    }
422}