Skip to main content

cimmodel/
difference.rs

1//! Difference models: a CGMES `dm:DifferenceModel`'s or an NC
2//! `dcatcim:DifferenceSet`'s statements, applied to a model, and computed
3//! between two.
4//!
5//! IEC 61970-552 describes a change to a model as statements: the reverse
6//! differences, removed from the model; the forward differences, added to it;
7//! and preconditions, which must hold in the model first. The decoder reads
8//! each block into a dataset of its own ([`CimDataset::differences`]): a
9//! typed element states the object's type and its values, an
10//! `rdf:Description` only its values, and lands among the block's foreign
11//! objects, its keys `Class.attr` as written. A changed value is a statement
12//! in each block, the old one reverse, the new one forward; a new object's
13//! type and values are forward statements, a removed one's reverse.
14
15use std::error::Error;
16use std::fmt::Write;
17
18use crate::base::{foreign_class, ClassDef, Element, FastMap, FastSet, FieldValue, Value};
19use crate::convert_nc::Prefixes;
20use crate::decode::{CimDataset, FieldForm};
21use crate::registry::type_registry;
22
23/// RDF's namespace, whose `Description` an untyped statement is written as.
24const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
25/// A CGMES `dm:DifferenceModel`'s namespace, its blocks' names in it.
26pub(crate) const DM: &str = "http://iec.ch/TC57/61970-552/DifferenceModel/1#";
27/// An NC `dcatcim:DifferenceSet`'s namespace, its blocks' names in it.
28pub(crate) const DCATCIM: &str = "https://cim4.eu/ns/dcatcim#";
29
30/// A block of a difference header.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Block {
33    /// Statements added to the model.
34    Forward,
35    /// Statements removed from the model.
36    Reverse,
37    /// Statements that must hold in the model first (CGMES only).
38    Preconditions,
39}
40
41/// The statements of one difference header ([`CimDataset::differences`]).
42#[derive(Clone)]
43pub struct Differences {
44    /// The header's identifier (`urn:uuid:…`); empty for differences computed
45    /// ([`Differences::between`]) until the caller gives them one.
46    pub header: String,
47    pub forward: CimDataset,
48    pub reverse: CimDataset,
49    pub preconditions: CimDataset,
50    /// The blocks the header held, in the order written, for the encoder.
51    pub blocks: Vec<Block>,
52}
53
54impl Differences {
55    pub(crate) fn new(header: &str) -> Self {
56        Self {
57            header: header.to_string(),
58            forward: CimDataset::new(),
59            reverse: CimDataset::new(),
60            preconditions: CimDataset::new(),
61            blocks: Vec::new(),
62        }
63    }
64
65    /// The dataset of block `which`, recorded as held.
66    pub(crate) fn block_mut(&mut self, which: Block) -> &mut CimDataset {
67        if !self.blocks.contains(&which) {
68            self.blocks.push(which);
69        }
70        match which {
71            Block::Forward => &mut self.forward,
72            Block::Reverse => &mut self.reverse,
73            Block::Preconditions => &mut self.preconditions,
74        }
75    }
76
77    /// The statements that take `before` to `after`: what `after` lacks of
78    /// `before` reverse, what it adds forward. An object in one only is
79    /// written whole, typed; an object in both, where its values differ, as
80    /// an `rdf:Description` of the values that differ, typed only where its
81    /// types do. Applied to `before` ([`CimDataset::apply`]), they give
82    /// `after`. The header is empty: the caller names it.
83    pub fn between(before: &CimDataset, after: &CimDataset) -> Self {
84        let mut d = Self::new("");
85        d.blocks = vec![Block::Reverse, Block::Forward];
86        let ids: FastSet<&str> = before
87            .entries
88            .keys()
89            .chain(before.foreign.keys())
90            .chain(after.entries.keys())
91            .chain(after.foreign.keys())
92            .map(String::as_str)
93            .collect();
94        let mut ids: Vec<&str> = ids.into_iter().collect();
95        ids.sort_unstable();
96        for id in ids {
97            let (was, now) = (lookup(before, id), lookup(after, id));
98            match (was, now) {
99                (Some((b, foreign)), None) => put(&mut d.reverse, b.clone(), foreign),
100                (None, Some((a, foreign))) => put(&mut d.forward, a.clone(), foreign),
101                (Some((b, foreign)), Some((a, _))) => {
102                    let gone = without(b, a);
103                    let came = without(a, b);
104                    let types = |e: &Element| e.types().map(|c| c.qualified).collect::<FastSet<_>>();
105                    let (tb, ta) = (types(b), types(a));
106                    let lost: Vec<&'static ClassDef> = b.types().filter(|c| !ta.contains(c.qualified)).collect();
107                    let gained: Vec<&'static ClassDef> = a.types().filter(|c| !tb.contains(c.qualified)).collect();
108                    if !gone.is_empty() || !lost.is_empty() {
109                        put(&mut d.reverse, statements(id, &lost, gone), foreign);
110                        named(&mut d.reverse, before, id, b);
111                    }
112                    if !came.is_empty() || !gained.is_empty() {
113                        put(&mut d.forward, statements(id, &gained, came), foreign);
114                        named(&mut d.forward, after, id, a);
115                    }
116                }
117                (None, None) => {}
118            }
119        }
120        d
121    }
122}
123
124/// `id`'s object in `ds`, and whether it is foreign: among the CIM objects
125/// by mRID (an IRI's text after its last `#`), else among the foreign ones as
126/// written.
127fn lookup<'a>(ds: &'a CimDataset, id: &str) -> Option<(&'a Element, bool)> {
128    ds.entries
129        .get(id)
130        .or_else(|| ds.entries.get(fragment(id)))
131        .map(|e| (e, false))
132        .or_else(|| ds.foreign.get(id).map(|e| (e, true)))
133}
134
135/// The key a CIM object has for identifier `id`: its text after the last `#`.
136fn fragment(id: &str) -> &str {
137    id.rsplit_once('#').map_or(id, |(_, f)| if f.is_empty() { id } else { f })
138}
139
140/// Into a block: a typed CIM object among its objects, anything else among
141/// its foreign ones.
142fn put(ds: &mut CimDataset, element: Element, foreign: bool) {
143    let id = element.mrid().to_string();
144    if foreign || element.class().qualified.starts_with(RDF) {
145        ds.foreign.insert(id, element);
146    } else {
147        ds.set(id, element);
148    }
149}
150
151/// `a`'s values `b` lacks, by key.
152fn without(a: &Element, b: &Element) -> Vec<(&'static str, FieldValue)> {
153    let mut out = Vec::new();
154    let mut keys: Vec<&'static str> = a.fields().keys().copied().collect();
155    keys.sort_unstable();
156    for key in keys {
157        for v in a.fields()[key].values() {
158            if !b.has_value(key, &v.owned()) {
159                out.push((key, v.owned()));
160            }
161        }
162    }
163    out
164}
165
166/// Statements about `id`, an object both models hold: its types `types` and
167/// `values`, as a typed element of the first type (the rest beside it), or an
168/// `rdf:Description` without one; written `rdf:about`, as they describe an
169/// object defined elsewhere.
170fn statements(id: &str, types: &[&'static ClassDef], values: Vec<(&'static str, FieldValue)>) -> Element {
171    let mut e = Element::new(foreign_class(RDF, "Description"), id.to_string());
172    e.set_types(types);
173    e.mark_described();
174    for (key, value) in values {
175        e.add_field(key, value);
176    }
177    e
178}
179
180/// The namespaces the fields of statement `id` in `block` are written in, an
181/// `rdf:Description`'s keys being declared by no class of its: as `like`
182/// (the object they are about, in `from`) has them, read or declared.
183fn named(block: &mut CimDataset, from: &CimDataset, id: &str, like: &Element) {
184    let Some(e) = block.foreign.get(id).filter(|e| untyped(e)) else { return };
185    let reg = type_registry();
186    let class = e.class().qualified;
187    for &key in e.fields().keys() {
188        let form = from.field_forms.get(&(like.type_name(), key)).copied().unwrap_or_default();
189        let ns = form.ns.or_else(|| reg.attr_of(like.class(), key).map(|a| a.ns));
190        let resource_ns = form.resource_ns;
191        block.field_forms.insert((class, key), FieldForm { ns, datatype: form.datatype, resource_ns });
192    }
193}
194
195/// A difference header's blocks inside it, in the order read: each a field of
196/// the header in namespace `ns` ([`DM`] or [`DCATCIM`]) holding its
197/// statements (`rdf:parseType="Statements"`), written as a document's objects
198/// are.
199pub(crate) fn write_blocks(out: &mut String, prefixes: &mut Prefixes, d: &Differences, ns: &'static str) -> Result<(), Box<dyn Error>> {
200    let nc = ns == DCATCIM;
201    let prefix = prefixes.of(ns);
202    for &which in &d.blocks {
203        let (name, ds) = match (which, nc) {
204            (Block::Forward, false) => ("forwardDifferences", &d.forward),
205            (Block::Forward, true) => ("forwardDifference", &d.forward),
206            (Block::Reverse, false) => ("reverseDifferences", &d.reverse),
207            (Block::Reverse, true) => ("reverseDifference", &d.reverse),
208            (Block::Preconditions, false) => ("preconditions", &d.preconditions),
209            (Block::Preconditions, true) => continue,
210        };
211        let mut inner = String::new();
212        crate::convert::write_objects(&mut inner, prefixes, ds)?;
213        if inner.is_empty() {
214            write!(out, "\n    <{prefix}:{name} rdf:parseType=\"Statements\"/>")?;
215        } else {
216            write!(out, "\n    <{prefix}:{name} rdf:parseType=\"Statements\">\n{inner}    </{prefix}:{name}>")?;
217        }
218    }
219    Ok(())
220}
221
222/// A block's statements, typed and untyped, by subject.
223fn sorted(ds: &CimDataset) -> Vec<(&String, &Element)> {
224    let mut all: Vec<(&String, &Element)> = ds.entries.iter().chain(&ds.foreign).collect();
225    all.sort_unstable_by_key(|(id, _)| id.as_str());
226    all
227}
228
229/// Whether `e` states no type: an `rdf:Description`.
230fn untyped(e: &Element) -> bool {
231    e.class().qualified == "http://www.w3.org/1999/02/22-rdf-syntax-ns#Description"
232}
233
234/// One statement a difference could not apply.
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub enum Statement {
237    /// That the object is of a class, by its qualified name.
238    Type(&'static str),
239    /// That a field holds a value.
240    Value(&'static str, FieldValue),
241}
242
243/// A statement that does not hold where a difference needs it: a reverse
244/// statement or a precondition the model lacks, a forward statement about an
245/// object that neither exists nor is given a type.
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub struct Unmatched {
248    pub block: Block,
249    pub subject: String,
250    pub statement: Statement,
251}
252
253/// A field a difference changed: its value before and after, `None` where
254/// it had none.
255#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct FieldChange {
257    pub key: &'static str,
258    pub before: Option<FieldValue>,
259    pub after: Option<FieldValue>,
260}
261
262/// An object a difference changed, there before and after.
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub struct Changed {
265    pub id: String,
266    /// Its class before and after, where that changed.
267    pub retyped: Option<(&'static str, &'static str)>,
268    pub fields: Vec<FieldChange>,
269}
270
271/// What applying a difference did ([`CimDataset::apply`]). Each list is in
272/// identifier order.
273#[derive(Debug, Default)]
274pub struct Applied {
275    /// The objects it created.
276    pub added: Vec<String>,
277    /// The objects it removed, as they were.
278    pub removed: Vec<Element>,
279    pub changed: Vec<Changed>,
280    /// The statements that did not hold where they had to.
281    pub unmatched: Vec<Unmatched>,
282    /// Objects whose every type was removed while values of theirs stayed:
283    /// kept, with their types, as an object needs a class.
284    pub untyped: Vec<String>,
285}
286
287impl CimDataset {
288    /// Apply a difference: its preconditions checked, its reverse statements
289    /// removed, its forward statements added, as IEC 61970-552 describes. An
290    /// object left with neither type nor values is removed; one given a type
291    /// it lacked is created. A statement that does not hold is reported
292    /// ([`Applied::unmatched`]) and passed over, not fatal. Several
293    /// differences apply in turn, in the order the caller gives (along their
294    /// headers' `Model.Supersedes`, say).
295    pub fn apply(&mut self, d: &Differences) -> Applied {
296        let mut applied = Applied::default();
297        let miss = |applied: &mut Applied, block, subject: &str, statement| {
298            applied.unmatched.push(Unmatched { block, subject: subject.to_string(), statement });
299        };
300
301        // Preconditions hold in the model as it is.
302        for (id, e) in sorted(&d.preconditions) {
303            let held = lookup(self, id).map(|(o, _)| o);
304            if !untyped(e) {
305                for t in e.types() {
306                    if !held.is_some_and(|o| o.types().any(|c| c.qualified == t.qualified)) {
307                        miss(&mut applied, Block::Preconditions, id, Statement::Type(t.qualified));
308                    }
309                }
310            }
311            for (key, fv) in e.fields() {
312                for v in fv.values() {
313                    if !held.is_some_and(|o| o.has_value(key, &v.owned())) {
314                        miss(&mut applied, Block::Preconditions, id, Statement::Value(key, v.owned()));
315                    }
316                }
317            }
318        }
319
320        // Each object the difference is about, as it was, and its types as they become.
321        let mut touched: Vec<&str> = d
322            .reverse
323            .entries
324            .keys()
325            .chain(d.reverse.foreign.keys())
326            .chain(d.forward.entries.keys())
327            .chain(d.forward.foreign.keys())
328            .map(String::as_str)
329            .collect::<FastSet<&str>>()
330            .into_iter()
331            .collect();
332        touched.sort_unstable();
333        // By the key the object has in the model, or will have.
334        let mut was: FastMap<&str, Option<(Element, bool)>> = FastMap::default();
335        let mut types: FastMap<&str, Vec<&'static ClassDef>> = FastMap::default();
336        for &id in &touched {
337            let found = lookup(self, id).map(|(e, f)| (e.clone(), f));
338            types.insert(id, found.as_ref().map_or_else(Vec::new, |(e, _)| e.types().collect()));
339            was.insert(id, found);
340        }
341
342        for (id, e) in sorted(&d.reverse) {
343            let id = id.as_str();
344            let Some(object) = self.object_mut(id) else {
345                if !untyped(e) {
346                    for t in e.types() {
347                        miss(&mut applied, Block::Reverse, id, Statement::Type(t.qualified));
348                    }
349                }
350                for (key, fv) in e.fields() {
351                    for v in fv.values() {
352                        miss(&mut applied, Block::Reverse, id, Statement::Value(key, v.owned()));
353                    }
354                }
355                continue;
356            };
357            let mut missed = Vec::new();
358            for (key, fv) in e.fields() {
359                for v in fv.values() {
360                    if !object.remove_value(key, &v.owned()) {
361                        missed.push(Statement::Value(key, v.owned()));
362                    }
363                }
364            }
365            if !untyped(e) {
366                let held = types.get_mut(id).expect("touched");
367                for t in e.types() {
368                    match held.iter().position(|c| c.qualified == t.qualified) {
369                        Some(i) => {
370                            held.remove(i);
371                        }
372                        None => missed.push(Statement::Type(t.qualified)),
373                    }
374                }
375            }
376            for statement in missed {
377                miss(&mut applied, Block::Reverse, id, statement);
378            }
379        }
380
381        for (id, e) in sorted(&d.forward) {
382            let id = id.as_str();
383            let stated: Vec<&'static ClassDef> = if untyped(e) { Vec::new() } else { e.types().collect() };
384            let held = types.get_mut(id).expect("touched");
385            for t in &stated {
386                if !held.iter().any(|c| c.qualified == t.qualified) {
387                    held.push(t);
388                }
389            }
390            if self.object_mut(id).is_none() {
391                let Some(&class) = stated.first() else {
392                    // Values for an object that neither is nor is given a type.
393                    for (key, fv) in e.fields() {
394                        for v in fv.values() {
395                            miss(&mut applied, Block::Forward, id, Statement::Value(key, v.owned()));
396                        }
397                    }
398                    continue;
399                };
400                let mut created = Element::new(class, e.mrid().to_string());
401                if !e.defined() {
402                    created.mark_described();
403                }
404                let foreign = d.forward.foreign.contains_key(id);
405                put(self, created, foreign);
406            }
407            let object = self.object_mut(id).expect("just made");
408            for (key, fv) in e.fields() {
409                for v in fv.values() {
410                    let value = v.owned();
411                    if !object.has_value(key, &value) {
412                        object.add_field(key, value);
413                    }
414                }
415            }
416        }
417
418        // What became of each object.
419        for &id in &touched {
420            let now_types = &types[id];
421            let Some((key, foreign)) = self.key_of(id) else { continue };
422            match &was[id] {
423                None => applied.added.push(key),
424                Some((before, _)) => {
425                    let object = if foreign { &self.foreign[&key] } else { &self.entries[&key] };
426                    if now_types.is_empty() {
427                        if object.fields().is_empty() {
428                            let removed = if foreign { self.foreign.remove(&key) } else { self.remove(&key) };
429                            applied.removed.extend(removed.map(|_| before.clone()));
430                        } else {
431                            applied.untyped.push(key.clone());
432                            if let Some(c) = changes(&key, before, object) {
433                                applied.changed.push(c);
434                            }
435                        }
436                        continue;
437                    }
438                    let mut object = object.clone();
439                    if !now_types.iter().map(|c| c.qualified).eq(object.types().map(|c| c.qualified)) {
440                        object.set_types(now_types);
441                    }
442                    if let Some(c) = changes(&key, before, &object) {
443                        applied.changed.push(c);
444                    }
445                    if foreign {
446                        self.foreign.insert(key, object);
447                    } else {
448                        self.set(key, object);
449                    }
450                }
451            }
452        }
453        applied.added.sort_unstable();
454        applied.added.dedup();
455        applied
456    }
457
458    /// The object identifier `id` names, to change.
459    fn object_mut(&mut self, id: &str) -> Option<&mut Element> {
460        let (key, foreign) = self.key_of(id)?;
461        if foreign { self.foreign.get_mut(&key) } else { self.entries.get_mut(&key) }
462    }
463
464    /// The key identifier `id`'s object has here, and whether it is foreign.
465    fn key_of(&self, id: &str) -> Option<(String, bool)> {
466        if self.entries.contains_key(id) {
467            Some((id.to_string(), false))
468        } else if self.entries.contains_key(fragment(id)) {
469            Some((fragment(id).to_string(), false))
470        } else if self.foreign.contains_key(id) {
471            Some((id.to_string(), true))
472        } else {
473            None
474        }
475    }
476}
477
478/// How `after` differs from `before`, the same object: its class, and each
479/// field whose values differ. `None` where nothing does.
480fn changes(id: &str, before: &Element, after: &Element) -> Option<Changed> {
481    let retyped = (before.class().qualified != after.class().qualified).then(|| (before.class().qualified, after.class().qualified));
482    let mut keys: Vec<&'static str> = before.fields().keys().chain(after.fields().keys()).copied().collect::<FastSet<_>>().into_iter().collect();
483    keys.sort_unstable();
484    let same = |a: Option<&FieldValue>, b: Option<&FieldValue>| match (a, b) {
485        (None, None) => true,
486        (Some(a), Some(b)) => {
487            let mut x: Vec<Value> = a.values().collect();
488            let mut y: Vec<Value> = b.values().collect();
489            x.sort_unstable();
490            y.sort_unstable();
491            x == y
492        }
493        _ => false,
494    };
495    let fields: Vec<FieldChange> = keys
496        .into_iter()
497        .filter(|k| !same(before.fields().get(k), after.fields().get(k)))
498        .map(|k| FieldChange { key: k, before: before.fields().get(k).cloned(), after: after.fields().get(k).cloned() })
499        .collect();
500    (retyped.is_some() || !fields.is_empty()).then(|| Changed { id: id.to_string(), retyped, fields })
501}