Skip to main content

powerio_dist/ravens/
mod.rs

1//! MG-RAVENS JSON import and export for the multiconductor
2//! [`MulticonductorNetwork`](crate::model::MulticonductorNetwork).
3//!
4//! MG-RAVENS (<https://github.com/lanl-ansi/MG-RAVENS>, Apache-2.0) is the
5//! LANL/Triad microgrid data schema: one JSON document of name-keyed hash
6//! tables nested under the CIM class hierarchy, with `Ravens.cimObjectType`
7//! naming each object's concrete class and `Class::'name'` strings pointing
8//! between tables. Values are SI (volts, watts, ohms, meters) and radians.
9//!
10//! This is the multiconductor sibling of the balanced MG-RAVENS support in
11//! the `powerio-tx` crate: that reader takes the MATPOWER-derived transmission
12//! profile and refuses documents with per-phase detail; this one takes the
13//! OpenDSS-derived distribution profile — `ACLineSegmentPhase`,
14//! `EnergyConsumerPhase`, `PerLengthPhaseImpedance` matrices,
15//! `TransformerTank` ends with catalog `TransformerEndInfo` records,
16//! `EnergySource` Thevenin sources — and refuses the balanced profile's
17//! markers, pointing back. Because it lands in `MulticonductorNetwork`, a
18//! RAVENS feeder converts to OpenDSS `.dss`, PowerModelsDistribution
19//! ENGINEERING JSON, BMOPF JSON, and distribution CIM through the same
20//! [`DistTargetFormat`](crate::DistTargetFormat) machinery as every other
21//! distribution source, and any of those convert into RAVENS.
22//!
23//! The writer emits deterministic UUID-shaped mRIDs derived from class and
24//! name (imported mRIDs pass through the `ravens_mrid` extras), so write,
25//! read, write is byte stable; a parse retains its source on the module for
26//! the byte-exact echo tier.
27//!
28//! The reader's findings use the `READ.RAVENS_DIST.*` codes and the writer's the
29//! `EMIT.RAVENS_DIST.*` codes of [`crate::diagnostics`]. The vocabulary the two
30//! profiles share (the profile markers, deterministic mRIDs, and the phase
31//! kinds) is [`powerio_core::cim`]; the balanced profile is read and written
32//! by `powerio-tx`, and `powerio-tnd` routes a document to its profile.
33//!
34//! # Phase convention
35//!
36//! CIM `SinglePhaseKind`/`PhaseCode` letters map to the wire-coordinate
37//! terminal names (OpenDSS node numbers) the rest of the crate uses:
38//! `A`→`1`, `B`→`2`, `C`→`3`, `N`→`4`, and the split-phase secondary codes
39//! `s1`/`s2`→`1`/`2`.
40
41mod neutral;
42pub(crate) mod read;
43mod source;
44mod write;
45
46pub(crate) use write::emit_ravens_json_text;
47
48/// Extras key carrying an imported `IdentifiedObject.mRID`. Prefixed like
49/// `pmd_*` so the other writers treat it as converter bookkeeping, not data.
50pub(crate) const MRID_KEY: &str = "ravens_mrid";
51
52/// The distribution CIM reader's extras key for the same
53/// `IdentifiedObject.mRID`; the writer reuses it for every element but a
54/// transformer, and the CIM writer reads [`MRID_KEY`] back the same way.
55pub(crate) const CIM_MRID_KEY: &str = "cim_mrid";
56
57/// Extras key carrying `Switch.normalOpen` when it differs from the live
58/// state (the typed model only has `open`).
59pub(crate) const NORMAL_OPEN_KEY: &str = "ravens_normal_open";
60
61/// A deterministic mRID for an element with no imported id: the shared CIM
62/// derivation under the MG-RAVENS namespace, the same one the balanced
63/// profile writer in `powerio-tx` uses. The upstream converters write a
64/// fresh random UUID per run; a name-derived id keeps canonical output
65/// idempotent (write, parse, write is byte stable) and diffs meaningful.
66/// When the element carries a round-tripped source mRID in its extras, the
67/// caller passes that through instead.
68pub(crate) fn det_mrid(kind: &str, name: &str) -> String {
69    powerio_core::cim::deterministic_mrid(powerio_core::cim::ravens::NAMESPACE, kind, name)
70}
71
72/// Split a trailing digit run so hash keys order numerically (`line10` after
73/// `line2`); the upstream converters number elements, and hash tables carry
74/// no order of their own.
75pub(crate) fn natural_key(name: &str) -> (String, u64, String) {
76    let stem_len = name.len() - name.bytes().rev().take_while(u8::is_ascii_digit).count();
77    let (stem, digits) = name.split_at(stem_len);
78    (
79        stem.to_owned(),
80        digits.parse().unwrap_or(0),
81        name.to_owned(),
82    )
83}
84
85// The phase vocabulary is the shared CIM one, so a terminal named by a BMOPF
86// convention (`a`, `b`, `c`, `n`) and one named by an OpenDSS node number
87// write the same letters, and the cim-dist writer agrees.
88pub(crate) use powerio_core::cim::{expand_phase_code, phase_terminal, terminal_phase};
89
90/// Concrete switch classes accepted from CIM-derived RAVENS documents.
91pub(crate) const SWITCH_CLASSES: &[&str] = &[
92    "Switch",
93    "ProtectedSwitch",
94    "LoadBreakSwitch",
95    "Breaker",
96    "Recloser",
97    "Cut",
98    "Fuse",
99    "Disconnector",
100    "GroundDisconnector",
101    "Sectionaliser",
102    "Jumper",
103];
104pub(crate) const SWITCH_CLASS_KEY: &str = "ravens_switch_class";
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn det_mrid_is_a_stable_version_5_uuid() {
112        let a = det_mrid("ACLineSegment", "ohline");
113        assert_eq!(a, det_mrid("ACLineSegment", "ohline"));
114        assert_ne!(a, det_mrid("ACLineSegment", "quad"));
115        assert_eq!(a.len(), 36);
116        assert_eq!(a.as_bytes()[14], b'5', "version nibble: {a}");
117    }
118
119    #[test]
120    fn natural_keys_order_numerically() {
121        let mut names = vec!["line10", "line2", "line1"];
122        names.sort_by_key(|n| natural_key(n));
123        assert_eq!(names, ["line1", "line2", "line10"]);
124    }
125}