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::{ClassDef, Element, FastMap, FastSet, FieldValue, Value, foreign_class};
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 =
105                        |e: &Element| e.types().map(|c| c.qualified).collect::<FastSet<_>>();
106                    let (tb, ta) = (types(b), types(a));
107                    let lost: Vec<&'static ClassDef> =
108                        b.types().filter(|c| !ta.contains(c.qualified)).collect();
109                    let gained: Vec<&'static ClassDef> =
110                        a.types().filter(|c| !tb.contains(c.qualified)).collect();
111                    if !gone.is_empty() || !lost.is_empty() {
112                        put(&mut d.reverse, statements(id, &lost, gone), foreign);
113                        named(&mut d.reverse, before, id, b);
114                    }
115                    if !came.is_empty() || !gained.is_empty() {
116                        put(&mut d.forward, statements(id, &gained, came), foreign);
117                        named(&mut d.forward, after, id, a);
118                    }
119                }
120                (None, None) => {}
121            }
122        }
123        d
124    }
125}
126
127/// `id`'s object in `ds`, and whether it is foreign: among the CIM objects
128/// by mRID (an IRI's text after its last `#`), else among the foreign ones as
129/// written.
130fn lookup<'a>(ds: &'a CimDataset, id: &str) -> Option<(&'a Element, bool)> {
131    ds.entries
132        .get(id)
133        .or_else(|| ds.entries.get(fragment(id)))
134        .map(|e| (e, false))
135        .or_else(|| ds.foreign.get(id).map(|e| (e, true)))
136}
137
138/// The key a CIM object has for identifier `id`: its text after the last `#`.
139fn fragment(id: &str) -> &str {
140    id.rsplit_once('#')
141        .map_or(id, |(_, f)| if f.is_empty() { id } else { f })
142}
143
144/// Into a block: a typed CIM object among its objects, anything else among
145/// its foreign ones.
146fn put(ds: &mut CimDataset, element: Element, foreign: bool) {
147    let id = element.mrid().to_string();
148    if foreign || element.class().qualified.starts_with(RDF) {
149        ds.foreign.insert(id, element);
150    } else {
151        ds.set(id, element);
152    }
153}
154
155/// `a`'s values `b` lacks, by key.
156fn without(a: &Element, b: &Element) -> Vec<(&'static str, FieldValue)> {
157    let mut out = Vec::new();
158    let mut keys: Vec<&'static str> = a.fields().keys().copied().collect();
159    keys.sort_unstable();
160    for key in keys {
161        for v in a.fields()[key].values() {
162            if !b.has_value(key, &v.owned()) {
163                out.push((key, v.owned()));
164            }
165        }
166    }
167    out
168}
169
170/// Statements about `id`, an object both models hold: its types `types` and
171/// `values`, as a typed element of the first type (the rest beside it), or an
172/// `rdf:Description` without one; written `rdf:about`, as they describe an
173/// object defined elsewhere.
174fn statements(
175    id: &str,
176    types: &[&'static ClassDef],
177    values: Vec<(&'static str, FieldValue)>,
178) -> Element {
179    let mut e = Element::new(foreign_class(RDF, "Description"), id.to_string());
180    e.set_types(types);
181    e.mark_described();
182    for (key, value) in values {
183        e.add_field(key, value);
184    }
185    e
186}
187
188/// The namespaces the fields of statement `id` in `block` are written in, an
189/// `rdf:Description`'s keys being declared by no class of its: as `like`
190/// (the object they are about, in `from`) has them, read or declared.
191fn named(block: &mut CimDataset, from: &CimDataset, id: &str, like: &Element) {
192    let Some(e) = block.foreign.get(id).filter(|e| untyped(e)) else {
193        return;
194    };
195    let reg = type_registry();
196    let class = e.class().qualified;
197    for &key in e.fields().keys() {
198        let form = from
199            .field_forms
200            .get(&(like.type_name(), key))
201            .copied()
202            .unwrap_or_default();
203        let ns = form
204            .ns
205            .or_else(|| reg.attr_of(like.class(), key).map(|a| a.ns));
206        let resource_ns = form.resource_ns;
207        block.field_forms.insert(
208            (class, key),
209            FieldForm {
210                ns,
211                datatype: form.datatype,
212                resource_ns,
213            },
214        );
215    }
216}
217
218/// A difference header's blocks inside it, in the order read: each a field of
219/// the header in namespace `ns` ([`DM`] or [`DCATCIM`]) holding its
220/// statements (`rdf:parseType="Statements"`), written as a document's objects
221/// are.
222pub(crate) fn write_blocks(
223    out: &mut String,
224    prefixes: &mut Prefixes,
225    d: &Differences,
226    ns: &'static str,
227) -> Result<(), Box<dyn Error>> {
228    let nc = ns == DCATCIM;
229    let prefix = prefixes.of(ns);
230    for &which in &d.blocks {
231        let (name, ds) = match (which, nc) {
232            (Block::Forward, false) => ("forwardDifferences", &d.forward),
233            (Block::Forward, true) => ("forwardDifference", &d.forward),
234            (Block::Reverse, false) => ("reverseDifferences", &d.reverse),
235            (Block::Reverse, true) => ("reverseDifference", &d.reverse),
236            (Block::Preconditions, false) => ("preconditions", &d.preconditions),
237            (Block::Preconditions, true) => continue,
238        };
239        let mut inner = String::new();
240        crate::convert::write_objects(&mut inner, prefixes, ds)?;
241        if inner.is_empty() {
242            write!(out, "\n    <{prefix}:{name} rdf:parseType=\"Statements\"/>")?;
243        } else {
244            write!(
245                out,
246                "\n    <{prefix}:{name} rdf:parseType=\"Statements\">\n{inner}    </{prefix}:{name}>"
247            )?;
248        }
249    }
250    Ok(())
251}
252
253/// A block's statements, typed and untyped, by subject.
254fn sorted(ds: &CimDataset) -> Vec<(&String, &Element)> {
255    let mut all: Vec<(&String, &Element)> = ds.entries.iter().chain(&ds.foreign).collect();
256    all.sort_unstable_by_key(|(id, _)| id.as_str());
257    all
258}
259
260/// Whether `e` states no type: an `rdf:Description`.
261fn untyped(e: &Element) -> bool {
262    e.class().qualified == "http://www.w3.org/1999/02/22-rdf-syntax-ns#Description"
263}
264
265/// One statement a difference could not apply.
266#[derive(Debug, Clone, PartialEq, Eq)]
267pub enum Statement {
268    /// That the object is of a class, by its qualified name.
269    Type(&'static str),
270    /// That a field holds a value.
271    Value(&'static str, FieldValue),
272}
273
274/// A statement that does not hold where a difference needs it: a reverse
275/// statement or a precondition the model lacks, a forward statement about an
276/// object that neither exists nor is given a type.
277#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct Unmatched {
279    pub block: Block,
280    pub subject: String,
281    pub statement: Statement,
282}
283
284/// A field a difference changed: its value before and after, `None` where
285/// it had none.
286#[derive(Debug, Clone, PartialEq, Eq)]
287pub struct FieldChange {
288    pub key: &'static str,
289    pub before: Option<FieldValue>,
290    pub after: Option<FieldValue>,
291}
292
293/// An object a difference changed, there before and after.
294#[derive(Debug, Clone, PartialEq, Eq)]
295pub struct Changed {
296    pub id: String,
297    /// Its class before and after, where that changed.
298    pub retyped: Option<(&'static str, &'static str)>,
299    pub fields: Vec<FieldChange>,
300}
301
302/// What applying a difference did ([`CimDataset::apply`]). Each list is in
303/// identifier order.
304#[derive(Debug, Default)]
305pub struct Applied {
306    /// The objects it created.
307    pub added: Vec<String>,
308    /// The objects it removed, as they were.
309    pub removed: Vec<Element>,
310    pub changed: Vec<Changed>,
311    /// The statements that did not hold where they had to.
312    pub unmatched: Vec<Unmatched>,
313    /// Objects whose every type was removed while values of theirs stayed:
314    /// kept, with their types, as an object needs a class.
315    pub untyped: Vec<String>,
316}
317
318impl CimDataset {
319    /// Apply a difference: its preconditions checked, its reverse statements
320    /// removed, its forward statements added, as IEC 61970-552 describes. An
321    /// object left with neither type nor values is removed; one given a type
322    /// it lacked is created. A statement that does not hold is reported
323    /// ([`Applied::unmatched`]) and passed over, not fatal. Several
324    /// differences apply in turn, in the order the caller gives (along their
325    /// headers' `Model.Supersedes`, say).
326    pub fn apply(&mut self, d: &Differences) -> Applied {
327        let mut applied = Applied::default();
328        let miss = |applied: &mut Applied, block, subject: &str, statement| {
329            applied.unmatched.push(Unmatched {
330                block,
331                subject: subject.to_string(),
332                statement,
333            });
334        };
335
336        // Preconditions hold in the model as it is.
337        for (id, e) in sorted(&d.preconditions) {
338            let held = lookup(self, id).map(|(o, _)| o);
339            if !untyped(e) {
340                for t in e.types() {
341                    if !held.is_some_and(|o| o.types().any(|c| c.qualified == t.qualified)) {
342                        miss(
343                            &mut applied,
344                            Block::Preconditions,
345                            id,
346                            Statement::Type(t.qualified),
347                        );
348                    }
349                }
350            }
351            for (key, fv) in e.fields() {
352                for v in fv.values() {
353                    if !held.is_some_and(|o| o.has_value(key, &v.owned())) {
354                        miss(
355                            &mut applied,
356                            Block::Preconditions,
357                            id,
358                            Statement::Value(key, v.owned()),
359                        );
360                    }
361                }
362            }
363        }
364
365        // Each object the difference is about, as it was, and its types as they become.
366        let mut touched: Vec<&str> = d
367            .reverse
368            .entries
369            .keys()
370            .chain(d.reverse.foreign.keys())
371            .chain(d.forward.entries.keys())
372            .chain(d.forward.foreign.keys())
373            .map(String::as_str)
374            .collect::<FastSet<&str>>()
375            .into_iter()
376            .collect();
377        touched.sort_unstable();
378        // By the key the object has in the model, or will have.
379        let mut was: FastMap<&str, Option<(Element, bool)>> = FastMap::default();
380        let mut types: FastMap<&str, Vec<&'static ClassDef>> = FastMap::default();
381        for &id in &touched {
382            let found = lookup(self, id).map(|(e, f)| (e.clone(), f));
383            types.insert(
384                id,
385                found
386                    .as_ref()
387                    .map_or_else(Vec::new, |(e, _)| e.types().collect()),
388            );
389            was.insert(id, found);
390        }
391
392        for (id, e) in sorted(&d.reverse) {
393            let id = id.as_str();
394            let Some(object) = self.object_mut(id) else {
395                if !untyped(e) {
396                    for t in e.types() {
397                        miss(
398                            &mut applied,
399                            Block::Reverse,
400                            id,
401                            Statement::Type(t.qualified),
402                        );
403                    }
404                }
405                for (key, fv) in e.fields() {
406                    for v in fv.values() {
407                        miss(
408                            &mut applied,
409                            Block::Reverse,
410                            id,
411                            Statement::Value(key, v.owned()),
412                        );
413                    }
414                }
415                continue;
416            };
417            let mut missed = Vec::new();
418            for (key, fv) in e.fields() {
419                for v in fv.values() {
420                    if !object.remove_value(key, &v.owned()) {
421                        missed.push(Statement::Value(key, v.owned()));
422                    }
423                }
424            }
425            if !untyped(e) {
426                let held = types.get_mut(id).expect("touched");
427                for t in e.types() {
428                    match held.iter().position(|c| c.qualified == t.qualified) {
429                        Some(i) => {
430                            held.remove(i);
431                        }
432                        None => missed.push(Statement::Type(t.qualified)),
433                    }
434                }
435            }
436            for statement in missed {
437                miss(&mut applied, Block::Reverse, id, statement);
438            }
439        }
440
441        for (id, e) in sorted(&d.forward) {
442            let id = id.as_str();
443            let stated: Vec<&'static ClassDef> = if untyped(e) {
444                Vec::new()
445            } else {
446                e.types().collect()
447            };
448            let held = types.get_mut(id).expect("touched");
449            for t in &stated {
450                if !held.iter().any(|c| c.qualified == t.qualified) {
451                    held.push(t);
452                }
453            }
454            if self.object_mut(id).is_none() {
455                let Some(&class) = stated.first() else {
456                    // Values for an object that neither is nor is given a type.
457                    for (key, fv) in e.fields() {
458                        for v in fv.values() {
459                            miss(
460                                &mut applied,
461                                Block::Forward,
462                                id,
463                                Statement::Value(key, v.owned()),
464                            );
465                        }
466                    }
467                    continue;
468                };
469                let mut created = Element::new(class, e.mrid().to_string());
470                if !e.defined() {
471                    created.mark_described();
472                }
473                let foreign = d.forward.foreign.contains_key(id);
474                put(self, created, foreign);
475            }
476            let object = self.object_mut(id).expect("just made");
477            for (key, fv) in e.fields() {
478                for v in fv.values() {
479                    let value = v.owned();
480                    if !object.has_value(key, &value) {
481                        object.add_field(key, value);
482                    }
483                }
484            }
485        }
486
487        // What became of each object.
488        for &id in &touched {
489            let now_types = &types[id];
490            let Some((key, foreign)) = self.key_of(id) else {
491                continue;
492            };
493            match &was[id] {
494                None => applied.added.push(key),
495                Some((before, _)) => {
496                    let object = if foreign {
497                        &self.foreign[&key]
498                    } else {
499                        &self.entries[&key]
500                    };
501                    if now_types.is_empty() {
502                        if object.fields().is_empty() {
503                            let removed = if foreign {
504                                self.foreign.remove(&key)
505                            } else {
506                                self.remove(&key)
507                            };
508                            applied.removed.extend(removed.map(|_| before.clone()));
509                        } else {
510                            applied.untyped.push(key.clone());
511                            if let Some(c) = changes(&key, before, object) {
512                                applied.changed.push(c);
513                            }
514                        }
515                        continue;
516                    }
517                    let mut object = object.clone();
518                    if !now_types
519                        .iter()
520                        .map(|c| c.qualified)
521                        .eq(object.types().map(|c| c.qualified))
522                    {
523                        object.set_types(now_types);
524                    }
525                    if let Some(c) = changes(&key, before, &object) {
526                        applied.changed.push(c);
527                    }
528                    if foreign {
529                        self.foreign.insert(key, object);
530                    } else {
531                        self.set(key, object);
532                    }
533                }
534            }
535        }
536        applied.added.sort_unstable();
537        applied.added.dedup();
538        applied
539    }
540
541    /// The object identifier `id` names, to change.
542    fn object_mut(&mut self, id: &str) -> Option<&mut Element> {
543        let (key, foreign) = self.key_of(id)?;
544        if foreign {
545            self.foreign.get_mut(&key)
546        } else {
547            self.entries.get_mut(&key)
548        }
549    }
550
551    /// The key identifier `id`'s object has here, and whether it is foreign.
552    fn key_of(&self, id: &str) -> Option<(String, bool)> {
553        if self.entries.contains_key(id) {
554            Some((id.to_string(), false))
555        } else if self.entries.contains_key(fragment(id)) {
556            Some((fragment(id).to_string(), false))
557        } else if self.foreign.contains_key(id) {
558            Some((id.to_string(), true))
559        } else {
560            None
561        }
562    }
563}
564
565/// How `after` differs from `before`, the same object: its class, and each
566/// field whose values differ. `None` where nothing does.
567fn changes(id: &str, before: &Element, after: &Element) -> Option<Changed> {
568    let retyped = (before.class().qualified != after.class().qualified)
569        .then(|| (before.class().qualified, after.class().qualified));
570    let mut keys: Vec<&'static str> = before
571        .fields()
572        .keys()
573        .chain(after.fields().keys())
574        .copied()
575        .collect::<FastSet<_>>()
576        .into_iter()
577        .collect();
578    keys.sort_unstable();
579    let same = |a: Option<&FieldValue>, b: Option<&FieldValue>| match (a, b) {
580        (None, None) => true,
581        (Some(a), Some(b)) => {
582            let mut x: Vec<Value> = a.values().collect();
583            let mut y: Vec<Value> = b.values().collect();
584            x.sort_unstable();
585            y.sort_unstable();
586            x == y
587        }
588        _ => false,
589    };
590    let fields: Vec<FieldChange> = keys
591        .into_iter()
592        .filter(|k| !same(before.fields().get(k), after.fields().get(k)))
593        .map(|k| FieldChange {
594            key: k,
595            before: before.fields().get(k).cloned(),
596            after: after.fields().get(k).cloned(),
597        })
598        .collect();
599    (retyped.is_some() || !fields.is_empty()).then(|| Changed {
600        id: id.to_string(),
601        retyped,
602        fields,
603    })
604}