Skip to main content

powerio_tnd/formats/
ravens.rs

1//! MG-RAVENS, the LANL CIM-derived microgrid interchange schema
2//! (<https://github.com/lanl-ansi/MG-RAVENS>), across both electrical
3//! models.
4//!
5//! One token, `ravens-json`, names the format. The balanced profile, the
6//! register the upstream MATPOWER converter writes, is read and written by
7//! `powerio-tx` and parses to a [`BalancedNetwork`]. The multiconductor
8//! profile, the register the upstream OpenDSS converter writes, is read and
9//! written by `powerio-dist` and parses to a [`MulticonductorNetwork`]. The
10//! two readers each refuse the other's profile. This adapter is where they
11//! meet: [`parse`] reads the profile from the document
12//! ([`powerio_core::cim::ravens::detect_profile`]) and hands the source to
13//! the crate that owns it, so a caller need not know which register a file
14//! uses. The `powerio` facade routes the token here.
15//!
16//! A document carrying both profiles' classes is refused with
17//! `PARSE.RAVENS.MIXED_PROFILE`. Reading such a document into an
18//! [`IntegratedNetwork`](crate::IntegratedNetwork), with the balanced
19//! classes as the transmission module and the per-phase classes as feeders,
20//! is the follow-up this adapter is placed for.
21
22pub use powerio_core::cim::ravens::{
23    BALANCED_MARKERS, MULTICONDUCTOR_MARKERS, NAMESPACE, Profile, TOKEN, detect_profile,
24};
25use powerio_core::{Error, FormatId, PioModule, Source};
26use powerio_dist::MulticonductorNetwork;
27use powerio_tx::BalancedNetwork;
28
29/// A parsed MG-RAVENS document: the module of whichever network kind its
30/// profile selects.
31#[derive(Debug)]
32pub enum RavensModule {
33    /// The balanced profile, read by `powerio-tx`.
34    Balanced(PioModule<BalancedNetwork>),
35    /// The multiconductor profile, read by `powerio-dist`.
36    Multiconductor(PioModule<MulticonductorNetwork>),
37}
38
39impl RavensModule {
40    /// The profile the document was read as.
41    #[must_use]
42    pub fn profile(&self) -> Profile {
43        match self {
44            Self::Balanced(_) => Profile::Balanced,
45            Self::Multiconductor(_) => Profile::Multiconductor,
46        }
47    }
48}
49
50/// The profile of a source's primary document.
51///
52/// # Errors
53/// The source cannot be read, or its document is not UTF-8 text.
54pub fn profile_of(source: &Source) -> Result<Profile, Error> {
55    let buffer = source.primary_buffer()?;
56    let text = std::str::from_utf8(buffer.content_bytes()).map_err(|e| {
57        Error::new(
58            &powerio_tx::diagnostics::codes::PARSE_SOURCE_MALFORMED,
59            format!("MG-RAVENS JSON is not UTF-8 text: {e}"),
60        )
61    })?;
62    Ok(detect_profile(text))
63}
64
65/// Parse an MG-RAVENS document into the module its profile selects. The
66/// source is declared `ravens-json` on the way in, so an extension or an
67/// alias the caller passed does not matter; the module retains the source
68/// for the byte exact echo on a same format write.
69///
70/// # Errors
71/// The source cannot be read, the document carries both profiles
72/// (`PARSE.RAVENS.MIXED_PROFILE`), or the owning reader refuses it, with that
73/// reader's findings and the source attached.
74pub fn parse(source: Source) -> Result<RavensModule, Error> {
75    let source = source.with_format(FormatId::new(TOKEN)?);
76    match profile_of(&source) {
77        Ok(Profile::Multiconductor) => {
78            powerio_dist::parse(source).map(RavensModule::Multiconductor)
79        }
80        Ok(Profile::Mixed) => Err(Error::new(
81            &crate::diagnostics::PARSE_RAVENS_MIXED_PROFILE,
82            "the document carries classes of both MG-RAVENS profiles (the balanced \
83             AlgorithmSettings, ProducerCostFunction, or PowerTransformerEnd beside per-phase \
84             or tank classes); no reader takes both, and reading the two parts into an \
85             IntegratedNetwork is not implemented",
86        )
87        .with_source(source)),
88        Ok(_) => powerio_tx::parse(source).map(RavensModule::Balanced),
89        Err(error) => Err(error.with_source(source)),
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    fn memory(text: &str) -> Source {
98        Source::from_memory("case.json", text.as_bytes().to_vec()).unwrap()
99    }
100
101    #[test]
102    fn a_mixed_document_is_refused_with_its_own_code() {
103        let text = r#"{
104            "ConnectivityNode": {"a": {"Ravens.cimObjectType": "ConnectivityNode"}},
105            "PerLengthLineParameter": {},
106            "MySettings": {"Ravens.cimObjectType": "AlgorithmSettings"}
107        }"#;
108        let error = parse(memory(text)).unwrap_err();
109        assert_eq!(
110            error.info().map(|info| info.code),
111            Some("PARSE.RAVENS.MIXED_PROFILE"),
112            "{error}"
113        );
114    }
115
116    #[test]
117    fn the_multiconductor_example_reads_as_a_multiconductor_module() {
118        let path = concat!(
119            env!("CARGO_MANIFEST_DIR"),
120            "/../tests/data/dist/ravens/case3_balanced.json"
121        );
122        let module = parse(Source::open(path).unwrap()).unwrap();
123        assert_eq!(module.profile(), Profile::Multiconductor);
124        let RavensModule::Multiconductor(module) = module else {
125            unreachable!("profile checked");
126        };
127        // The finite-impedance source has its own internal EMF node.
128        assert_eq!(module.value().buses().len(), 4);
129        assert_eq!(
130            module
131                .source()
132                .and_then(|s| s.format())
133                .map(FormatId::as_str),
134            Some(TOKEN)
135        );
136    }
137}