Skip to main content

cim_kit/
header.rs

1//! Model headers: `md:FullModel` and `dm:DifferenceModel` (IEC 61970-552).
2//!
3//! Every CIM/XML instance file starts with a header describing what the file contains,
4//! which profiles it conforms to, and which other models it depends on. Assembling a
5//! multi-file model correctly requires reading these, so headers are first-class here
6//! rather than metadata to be skipped.
7
8use crate::mrid::Mrid;
9
10/// Namespace of the model description vocabulary.
11pub const MD_NS: &str = "http://iec.ch/TC57/61970-552/ModelDescription/1#";
12/// Namespace of the difference model vocabulary.
13pub const DM_NS: &str = "http://iec.ch/TC57/61970-552/DifferenceModel/1#";
14
15/// What kind of header a file carries.
16#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
17pub enum ModelKind {
18    /// `md:FullModel` — a complete model instance.
19    #[default]
20    Full,
21    /// `dm:DifferenceModel` — a change set against a superseded model.
22    Difference,
23}
24
25/// The header of one instance file.
26#[derive(Clone, Debug, Default)]
27pub struct ModelHeader {
28    pub kind: ModelKind,
29    /// Identifier of this model, written as `rdf:about="urn:uuid:..."`.
30    pub id: Option<Mrid>,
31    /// `md:Model.created`, in the file's lexical form.
32    pub created: Option<String>,
33    /// `md:Model.scenarioTime`.
34    pub scenario_time: Option<String>,
35    pub description: Option<String>,
36    pub version: Option<String>,
37    pub modeling_authority_set: Option<String>,
38    /// `md:Model.profile`, repeatable: one file may serve several profiles, as CGMES 3.0
39    /// does when Equipment, Operation and ShortCircuit share an instance file.
40    pub profiles: Vec<String>,
41    /// `md:Model.DependentOn` — models that must be loaded for this one to resolve.
42    pub dependent_on: Vec<Mrid>,
43    /// `md:Model.Supersedes` — models this one replaces.
44    pub supersedes: Vec<Mrid>,
45    /// Header properties outside the vocabulary above, preserved verbatim.
46    ///
47    /// CGMES 3.0 headers may carry W3C DCAT properties alongside `md:Model.*`, and
48    /// producers add their own. Each keeps the prefix, namespace and value form it was
49    /// read with, so a header round-trips through this crate unchanged rather than being
50    /// flattened into `md:` element text.
51    pub extra: Vec<HeaderProperty>,
52    /// Name of the file this header came from, when read from disk or an archive.
53    pub source: Option<String>,
54}
55
56/// A header property this crate does not model explicitly.
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct HeaderProperty {
59    /// Prefix as written in the source document, e.g. `dcat`.
60    pub prefix: String,
61    /// Namespace the prefix resolved to.
62    pub ns: String,
63    /// Local name, e.g. `Model.something`.
64    pub local: String,
65    pub value: HeaderValue,
66}
67
68/// Whether a header property was written as element text or as an `rdf:resource`.
69///
70/// The distinction matters: re-emitting a resource as text changes an IRI-valued property
71/// into a literal, which no longer resolves.
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub enum HeaderValue {
74    Text(String),
75    Resource(String),
76}
77
78impl HeaderProperty {
79    pub fn text(prefix: &str, ns: &str, local: &str, value: impl Into<String>) -> HeaderProperty {
80        HeaderProperty {
81            prefix: prefix.to_owned(),
82            ns: ns.to_owned(),
83            local: local.to_owned(),
84            value: HeaderValue::Text(value.into()),
85        }
86    }
87
88    pub fn resource(
89        prefix: &str,
90        ns: &str,
91        local: &str,
92        value: impl Into<String>,
93    ) -> HeaderProperty {
94        HeaderProperty {
95            prefix: prefix.to_owned(),
96            ns: ns.to_owned(),
97            local: local.to_owned(),
98            value: HeaderValue::Resource(value.into()),
99        }
100    }
101
102    /// The value as text, whichever form it was written in.
103    pub fn as_str(&self) -> &str {
104        match &self.value {
105            HeaderValue::Text(s) | HeaderValue::Resource(s) => s,
106        }
107    }
108}
109
110impl ModelHeader {
111    pub fn new(kind: ModelKind) -> ModelHeader {
112        ModelHeader {
113            kind,
114            ..Default::default()
115        }
116    }
117
118    /// Whether this header declares `profile_iri`, ignoring the version segment.
119    pub fn declares_profile(&self, profile_iri: &str) -> bool {
120        let stem = |s: &str| s.rsplit_once('/').map(|(a, _)| a).unwrap_or(s).to_owned();
121        let want = stem(profile_iri);
122        self.profiles
123            .iter()
124            .any(|p| p == profile_iri || stem(p) == want)
125    }
126
127    /// The short profile keyword, derived from the first declared profile IRI.
128    ///
129    /// For example `http://iec.ch/TC57/ns/CIM/CoreEquipment-EU/3.0` yields
130    /// `CoreEquipment-EU`.
131    pub fn primary_profile_name(&self) -> Option<&str> {
132        let iri = self.profiles.first()?;
133        let without_version = iri.rsplit_once('/').map(|(a, _)| a).unwrap_or(iri);
134        without_version.rsplit('/').next()
135    }
136}
137
138/// A difference model: statements to remove, then statements to add.
139///
140/// IEC 61970-552 defines a difference as a pair of RDF statement sets. Applying it means
141/// removing every reverse statement and then asserting every forward statement.
142#[derive(Clone, Debug, Default)]
143pub struct DifferenceModel {
144    pub header: ModelHeader,
145    /// Statements that must hold in the model before the change applies
146    /// (`dm:preconditions`). Every published change set carries the element and leaves it
147    /// empty; one that does not is refused by
148    /// [`Dataset::apply_difference`](crate::Dataset::apply_difference) when they fail.
149    pub preconditions: Vec<Statement>,
150    /// Statements describing the *previous* state, to be removed.
151    pub reverse: Vec<Statement>,
152    /// Statements describing the *new* state, to be added.
153    pub forward: Vec<Statement>,
154}
155
156/// One statement inside a difference model: a subject, a predicate and a value.
157///
158/// Statements are kept in unresolved form (IRIs, raw text) because a difference model
159/// may legitimately reference objects and properties that are not in the dataset yet.
160#[derive(Clone, Debug, PartialEq)]
161pub struct Statement {
162    /// mRID of the object the statement is about.
163    pub subject: Mrid,
164    /// Class named on the statement group's element.
165    ///
166    /// A difference names its subject either with a bare `rdf:Description` — in which
167    /// case this is `None` — or with the class element itself. The latter carries real
168    /// information: a difference may *reclassify* an object, and the published CGMES
169    /// conformity tests do exactly that, replacing a `LinearShuntCompensator` with a
170    /// `NonlinearShuntCompensator` under the same identifier.
171    pub class: Option<QualifiedName>,
172    /// Whether the statement group introduced its subject (`rdf:ID`) rather than updating
173    /// one defined elsewhere (`rdf:about`).
174    ///
175    /// Both forms occur in the published change sets: an Equipment difference that adds
176    /// breakers writes `rdf:ID`, while one that edits a limit writes `rdf:about`. Keeping
177    /// the distinction is what lets a difference be written back as it was read.
178    pub defines_subject: bool,
179    /// Namespace IRI of the predicate.
180    pub predicate_ns: String,
181    /// Qualified predicate name, e.g. `TapChangerTablePoint.x`.
182    pub predicate: String,
183    pub value: StatementValue,
184}
185
186/// A namespace-qualified name as it appeared in a document.
187#[derive(Clone, Debug, PartialEq, Eq)]
188pub struct QualifiedName {
189    pub ns: String,
190    pub local: String,
191}
192
193#[derive(Clone, Debug, PartialEq)]
194pub enum StatementValue {
195    /// Element text.
196    Literal(String),
197    /// An `rdf:resource` IRI: another object, or an enumeration literal.
198    Resource(String),
199}
200
201impl DifferenceModel {
202    /// Objects touched by this difference, in first-seen order.
203    pub fn affected_objects(&self) -> Vec<Mrid> {
204        let mut seen = Vec::new();
205        for s in self.reverse.iter().chain(&self.forward) {
206            if !seen.contains(&s.subject) {
207                seen.push(s.subject.clone());
208            }
209        }
210        seen
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn profile_matching_ignores_the_version_segment() {
220        let h = ModelHeader {
221            profiles: vec!["http://iec.ch/TC57/ns/CIM/CoreEquipment-EU/3.0".into()],
222            ..Default::default()
223        };
224        assert!(h.declares_profile("http://iec.ch/TC57/ns/CIM/CoreEquipment-EU/3.0"));
225        assert!(h.declares_profile("http://iec.ch/TC57/ns/CIM/CoreEquipment-EU/4.0"));
226        assert!(!h.declares_profile("http://iec.ch/TC57/ns/CIM/Topology-EU/3.0"));
227        assert_eq!(h.primary_profile_name(), Some("CoreEquipment-EU"));
228    }
229
230    #[test]
231    fn affected_objects_are_deduplicated_in_order() {
232        let mk = |m: &str, p: &str| Statement {
233            subject: Mrid::parse(m),
234            class: None,
235            defines_subject: false,
236            predicate_ns: "http://iec.ch/TC57/CIM100#".into(),
237            predicate: p.into(),
238            value: StatementValue::Literal("1".into()),
239        };
240        let a = "70c4656c-f7a0-4319-98bb-84fb5e2e9b37";
241        let b = "c4e8eb3a-76b0-4192-91fe-c2f0a60af0df";
242        let d = DifferenceModel {
243            reverse: vec![mk(a, "X.y"), mk(b, "X.y")],
244            forward: vec![mk(a, "X.z")],
245            ..Default::default()
246        };
247        assert_eq!(d.affected_objects(), vec![Mrid::parse(a), Mrid::parse(b)]);
248    }
249}