Skip to main content

cim_kit/
diff.rs

1//! Computing a difference model from two model states.
2//!
3//! # Why this exists
4//!
5//! IEC 61970-552 defines `dm:DifferenceModel` as the incremental form of exchange: rather
6//! than resending a whole grid model, a producer sends the statements to retract and the
7//! statements to assert. Reading, applying and writing one is
8//! [`reader::read_difference`](crate::reader::read_difference),
9//! [`Dataset::apply_difference`] and [`writer::write_difference`](crate::writer::write_difference).
10//! This module supplies the piece those three imply and none of them provides:
11//! **producing** a change set from a before and an after.
12//!
13//! It is the operation an EMS performs every time it publishes an update, and it is
14//! decidable from what the crate already holds — objects keyed by mRID, values sorted by
15//! attribute, profile provenance per value — so it costs a walk of the two models and no
16//! new machinery.
17//!
18// An example has to name a vintage, and a vintage is a feature. See `Dataset::view`.
19#![cfg_attr(
20    feature = "cgmes3",
21    doc = r#"
22```no_run
23use cim_kit::prelude::*;
24use cim_kit::cgmes3::SCHEMA;
25use cim_kit::diff::DiffOptions;
26
27# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
28let base = Dataset::load(SCHEMA, ["base_EQ.xml", "base_SSH.xml"])?;
29let updated = Dataset::load(SCHEMA, ["updated_EQ.xml", "updated_SSH.xml"])?;
30
31let change = base.difference_to(&updated, &DiffOptions::default());
32let out = std::fs::File::create("change_DIFF.xml")?;
33cim_kit::writer::write_difference(SCHEMA, &change.model, out, &Default::default())?;
34# Ok(())
35# }
36```
37"#
38)]
39//!
40//! # What the result guarantees
41//!
42//! Applying the result to the base reproduces the target:
43//! `base.apply_difference(&base.difference_to(&target, o).model)` leaves `base` holding
44//! every value `target` holds, and none it does not. That round trip is a test, not a
45//! claim — see `tests/difference.rs`.
46//!
47//! # What a statement-level difference cannot say
48//!
49//! Two limits are the standard's, not this implementation's, and both are reported rather
50//! than papered over:
51//!
52//! * **An object cannot be deleted, only emptied.** `rdf:parseType="Statements"` retracts
53//!   statements; there is no statement that says "this identifier no longer denotes
54//!   anything". An object present in the base and absent from the target therefore becomes
55//!   a subject with no properties. [`Dataset::prune_empty`] removes such shells where a
56//!   consumer wants them gone.
57//! * **A compound has no statement form.** `Location.mainAddress` holds a `StreetAddress`
58//!   inline, and IEC 61970-552's statement syntax has nowhere to put one. A changed
59//!   compound is reported as [`Rule::Structure`] and left out,
60//!   because emitting it as text would fabricate a value.
61
62use crate::dataset::{Dataset, ObjectId};
63use crate::error::{Diagnostic, Report, Rule};
64use crate::header::{
65    DifferenceModel, ModelHeader, ModelKind, QualifiedName, Statement, StatementValue,
66};
67use crate::mrid::Mrid;
68use crate::object::{Object, Slot};
69use crate::schema::{AttrId, AttrKind, ClassId, Primitive, ProfileMask, Schema};
70use crate::value::Value;
71
72/// Options controlling how a difference is computed.
73#[derive(Clone, Debug, Default)]
74pub struct DiffOptions {
75    /// Compare only values belonging to these profiles; zero means "everything".
76    ///
77    /// Filtering follows the same rule as the CIM/XML writer
78    /// ([`Schema::effective_profiles`]), so a change set restricted to Steady State
79    /// Hypothesis contains exactly the values an SSH export would, and no equipment
80    /// changes that belong in a different file.
81    pub profiles: ProfileMask,
82    /// Header to give the change set. Without one, a minimal `dm:DifferenceModel` header
83    /// is derived from the target's own headers.
84    pub header: Option<ModelHeader>,
85}
86
87impl DiffOptions {
88    /// Restrict the comparison to a set of profiles.
89    pub fn profiles(mut self, profiles: ProfileMask) -> Self {
90        self.profiles = profiles;
91        self
92    }
93
94    pub fn with_header(mut self, header: ModelHeader) -> Self {
95        self.header = Some(header);
96        self
97    }
98}
99
100/// A computed change set, together with what could not be expressed.
101#[derive(Debug)]
102pub struct DiffReport {
103    pub model: DifferenceModel,
104    /// Differences the statement syntax cannot carry, and mismatches that prevented one.
105    pub report: Report,
106    /// Objects present only in the target.
107    pub added: usize,
108    /// Objects present only in the base.
109    pub removed: usize,
110    /// Objects present in both whose description changed.
111    pub changed: usize,
112}
113
114impl DiffReport {
115    /// Whether the two models describe the same thing.
116    pub fn is_empty(&self) -> bool {
117        self.model.forward.is_empty() && self.model.reverse.is_empty()
118    }
119}
120
121impl Dataset {
122    /// The change set that turns this model into `target`.
123    ///
124    /// See the [module documentation](self) for what the result guarantees and for the two
125    /// things a statement-level difference cannot express.
126    pub fn difference_to(&self, target: &Dataset, options: &DiffOptions) -> DiffReport {
127        let schema = self.schema();
128        let mut out = DiffReport {
129            model: DifferenceModel {
130                header: options
131                    .header
132                    .clone()
133                    .unwrap_or_else(|| derived_header(self, target)),
134                preconditions: Vec::new(),
135                reverse: Vec::new(),
136                forward: Vec::new(),
137            },
138            report: Report::default(),
139            added: 0,
140            removed: 0,
141            changed: 0,
142        };
143        out.model.header.kind = ModelKind::Difference;
144
145        // Comparing models built from different vocabularies would compare `AttrId`s that
146        // mean different things, which is worse than refusing.
147        if !std::ptr::eq(schema, target.schema()) {
148            out.report.push(Diagnostic::error(
149                Rule::Structure,
150                format!(
151                    "cannot diff a {} model against a {} model",
152                    schema.vintage,
153                    target.schema().vintage
154                ),
155            ));
156            return out;
157        }
158
159        // mRID order, so a change set is reproducible and diffable between runs — the same
160        // reason the CIM/XML writer sorts.
161        for mrid in union_of_identifiers(self, target) {
162            let before = self.by_mrid(&mrid);
163            let after = target.by_mrid(&mrid);
164            match (before, after) {
165                (None, Some(new)) => {
166                    let n = out.model.forward.len();
167                    self.emit_all(new, true, options, &mut out.model.forward, &mut out.report);
168                    if out.model.forward.len() > n {
169                        out.added += 1;
170                    }
171                }
172                (Some(old), None) => {
173                    let n = out.model.reverse.len();
174                    self.emit_all(old, false, options, &mut out.model.reverse, &mut out.report);
175                    if out.model.reverse.len() > n {
176                        out.removed += 1;
177                    }
178                }
179                (Some(old), Some(new)) => {
180                    // Most objects are untouched even in a large update, and comparing
181                    // their slot vectors directly is a linear scan that allocates nothing
182                    // — where the per-attribute path builds a vector per attribute. A
183                    // provenance-only difference falls through to the slow path and
184                    // correctly produces no statements, so this is a fast path and not a
185                    // second definition of equality.
186                    if old.class() == new.class() && old.slots() == new.slots() {
187                        continue;
188                    }
189                    let (r, f) = (out.model.reverse.len(), out.model.forward.len());
190                    self.emit_changes(old, new, options, &mut out);
191                    if out.model.reverse.len() > r || out.model.forward.len() > f {
192                        out.changed += 1;
193                    }
194                }
195                (None, None) => {}
196            }
197        }
198
199        // The other thing a statement-level difference cannot express. A changed compound
200        // is already reported; deletion was only *counted*, which left the two limits of
201        // the same syntax documented to different standards — and a caller who applies this
202        // change set and compares content identifiers finds an object that is empty rather
203        // than absent, with nothing in the report to explain it.
204        //
205        // One diagnostic rather than one per object: the count is the fact, and a report
206        // that grows with the size of the change is the thing `max_diagnostics` exists to
207        // prevent elsewhere.
208        if out.removed > 0 {
209            out.report.push(Diagnostic::warning(
210                Rule::Structure,
211                format!(
212                    "{} object(s) are absent from the target and a difference model cannot \
213                     say so: applying this retracts everything they said and leaves the \
214                     identifiers behind. Dataset::prune_empty removes such shells",
215                    out.removed
216                ),
217            ));
218        }
219        out
220    }
221
222    /// Every value of one object as statements, for an object that is wholly new or gone.
223    fn emit_all(
224        &self,
225        obj: &Object,
226        introduces: bool,
227        options: &DiffOptions,
228        into: &mut Vec<Statement>,
229        report: &mut Report,
230    ) {
231        let schema = self.schema();
232        let class = qualified(schema, obj.class());
233        for slot in obj.slots() {
234            if !in_scope(schema, slot, options.profiles) {
235                continue;
236            }
237            match statement(schema, slot.attr, &slot.value) {
238                Some(value) => into.push(Statement {
239                    subject: obj.mrid().clone(),
240                    class: Some(class.clone()),
241                    // A change set that introduces an object identifies it with `rdf:ID`;
242                    // one that retracts an existing object's statements refers to it with
243                    // `rdf:about`, because it is not the file that defined it.
244                    defines_subject: introduces,
245                    predicate_ns: schema.namespace(schema.attr(slot.attr).ns).iri.to_owned(),
246                    predicate: schema.attr(slot.attr).name.to_owned(),
247                    value,
248                }),
249                None => report.push(inexpressible(schema, obj.mrid(), slot.attr)),
250            }
251        }
252    }
253
254    /// The statements that turn `old`'s description into `new`'s.
255    fn emit_changes(
256        &self,
257        old: &Object,
258        new: &Object,
259        options: &DiffOptions,
260        out: &mut DiffReport,
261    ) {
262        let schema = self.schema();
263        // A difference names an object's class only when it is saying something about it.
264        // IEC 61970-552 treats the type as a statement like any other, and the published
265        // conformity change sets use exactly this to replace a `LinearShuntCompensator`
266        // with a `NonlinearShuntCompensator` under one identifier.
267        let reclassified = old.class() != new.class();
268        let forward_class = reclassified.then(|| qualified(schema, new.class()));
269        let reverse_class = reclassified.then(|| qualified(schema, old.class()));
270        let forward_before = out.model.forward.len();
271
272        for attr in attributes_of_either(old, new) {
273            fn scoped<'o>(
274                schema: &Schema,
275                o: &'o Object,
276                attr: AttrId,
277                profiles: ProfileMask,
278            ) -> Vec<&'o Value> {
279                o.get_all(attr)
280                    .iter()
281                    .filter(|s| in_scope(schema, s, profiles))
282                    .map(|s| &s.value)
283                    .collect()
284            }
285            let before = scoped(schema, old, attr, options.profiles);
286            let after = scoped(schema, new, attr, options.profiles);
287            if before == after {
288                continue;
289            }
290            // Many-valued attributes are compared as multisets: two occurrences of the
291            // same value are two statements, and retracting one must not retract both.
292            let mut removed = before.clone();
293            let mut added: Vec<&Value> = Vec::new();
294            for v in after {
295                match removed.iter().position(|x| *x == v) {
296                    Some(i) => {
297                        removed.remove(i);
298                    }
299                    None => added.push(v),
300                }
301            }
302
303            for (values, class, defines, into) in [
304                (
305                    removed,
306                    reverse_class.clone(),
307                    false,
308                    &mut out.model.reverse,
309                ),
310                (added, forward_class.clone(), false, &mut out.model.forward),
311            ] {
312                for v in values {
313                    match statement(schema, attr, v) {
314                        Some(value) => into.push(Statement {
315                            subject: new.mrid().clone(),
316                            class: class.clone(),
317                            defines_subject: defines,
318                            predicate_ns: schema.namespace(schema.attr(attr).ns).iri.to_owned(),
319                            predicate: schema.attr(attr).name.to_owned(),
320                            value,
321                        }),
322                        None => out.report.push(inexpressible(schema, new.mrid(), attr)),
323                    }
324                }
325            }
326        }
327
328        // A reclassification with no attribute change still has to be said, or applying
329        // the difference would leave the object as the class it used to be.
330        //
331        // "No attribute change" is decided from the mark taken before this object was
332        // handled, not by searching the accumulated statements: a change set can run to
333        // hundreds of thousands of statements, and re-scanning them once per object turns
334        // the whole comparison quadratic.
335        if reclassified && out.model.forward.len() == forward_before {
336            match mrid_attribute(schema, new) {
337                Some(attr) => out.model.forward.push(Statement {
338                    subject: new.mrid().clone(),
339                    class: forward_class,
340                    defines_subject: false,
341                    predicate_ns: schema.namespace(schema.attr(attr).ns).iri.to_owned(),
342                    predicate: schema.attr(attr).name.to_owned(),
343                    value: StatementValue::Literal(new.mrid().canonical()),
344                }),
345                // A statement group names its class on a property element, so a class
346                // change with no property to hang it on cannot be said at all. Every CGMES
347                // class descends from `IdentifiedObject` and so has `mRID`, which is why
348                // this is unreachable there — but "a profile is data", and a vocabulary
349                // that declares a class outside that hierarchy would otherwise lose the
350                // reclassification without a word.
351                None => out.report.push(
352                    Diagnostic::warning(
353                        Rule::Structure,
354                        format!(
355                            "{} changed class from {} to {}, but {} has no attribute the \
356                             statement could carry, so the change is not in the change set",
357                            new.mrid().canonical(),
358                            schema.class(old.class()).name,
359                            schema.class(new.class()).name,
360                            schema.class(new.class()).name,
361                        ),
362                    )
363                    .with_class(schema.class(new.class()).name)
364                    .with_object(new.mrid().clone()),
365                ),
366            }
367        }
368    }
369
370    /// Remove objects that carry no values at all.
371    ///
372    /// Applying a difference that retracts everything an object said leaves the identifier
373    /// behind with nothing attached, because IEC 61970-552's statement syntax has no way to
374    /// say "this object is gone". Returns how many were removed.
375    ///
376    /// Deliberately separate from [`Dataset::apply_difference`]: a model legitimately
377    /// contains objects described entirely by files that are not loaded, and silently
378    /// deleting those would be worse than keeping a shell.
379    pub fn prune_empty(&mut self) -> usize {
380        let empty: Vec<ObjectId> = self
381            .iter()
382            .filter(|(_, o)| o.is_empty())
383            .map(|(id, _)| id)
384            .collect();
385        let n = empty.len();
386        for id in empty {
387            self.remove(id);
388        }
389        n
390    }
391}
392
393/// Every identifier either model knows, in a stable order.
394fn union_of_identifiers(a: &Dataset, b: &Dataset) -> Vec<Mrid> {
395    let mut out: Vec<Mrid> = a
396        .iter()
397        .chain(b.iter())
398        .map(|(_, o)| o.mrid().clone())
399        .collect();
400    out.sort();
401    out.dedup();
402    out
403}
404
405/// Attributes either object carries, in schema order.
406///
407/// Both slot vectors are already sorted by [`AttrId`], so this is a merge rather than a
408/// sort — and it must consider attributes the *class* does not declare, since a document
409/// may set one the profile puts elsewhere.
410fn attributes_of_either(a: &Object, b: &Object) -> Vec<AttrId> {
411    let mut out: Vec<AttrId> = a
412        .slots()
413        .iter()
414        .chain(b.slots())
415        .map(|s: &Slot| s.attr)
416        .collect();
417    out.sort();
418    out.dedup();
419    out
420}
421
422/// Whether a stored value takes part in a comparison restricted to `profiles`.
423///
424/// The same rule the CIM/XML writer applies — [`Schema::effective_profiles`] — so a change
425/// set restricted to a profile holds exactly what that profile's file would.
426fn in_scope(schema: &Schema, slot: &Slot, profiles: ProfileMask) -> bool {
427    profiles == 0 || schema.effective_profiles(slot.attr, slot.profiles) & profiles != 0
428}
429
430fn qualified(schema: &Schema, class: ClassId) -> QualifiedName {
431    let def = schema.class(class);
432    QualifiedName {
433        ns: schema.namespace(def.ns).iri.to_owned(),
434        local: def.name.to_owned(),
435    }
436}
437
438/// `IdentifiedObject.mRID` as visible on this object, for a statement that carries no
439/// other payload.
440fn mrid_attribute(schema: &Schema, obj: &Object) -> Option<AttrId> {
441    schema.attr_by_label(obj.class(), "mRID")
442}
443
444/// One stored value as a difference statement's value, or `None` if it has no such form.
445fn statement(schema: &Schema, attr: AttrId, value: &Value) -> Option<StatementValue> {
446    let kind = schema.attr(attr).kind;
447    Some(match value {
448        // A reference is written the way an instance file writes one, so a consumer that
449        // reads the change set resolves it against the same model.
450        Value::Reference(m) => StatementValue::Resource(m.to_rdf_reference()),
451        Value::Enum(e) => {
452            let ev = schema.enum_value(*e);
453            StatementValue::Resource(format!("{}{}", schema.namespace(ev.ns).iri, ev.name))
454        }
455        // A compound is held inline, and `rdf:parseType="Statements"` has nowhere to put
456        // one. Reporting that is the only honest answer.
457        Value::Compound(_) => return None,
458        other => StatementValue::Literal(other.to_lexical_as(lexical(schema, kind))?),
459    })
460}
461
462fn lexical(schema: &Schema, kind: AttrKind) -> Primitive {
463    match kind {
464        AttrKind::Primitive(p) => p,
465        AttrKind::Datatype(d) => schema.datatype(d).value,
466        _ => Primitive::String,
467    }
468}
469
470fn inexpressible(schema: &Schema, mrid: &Mrid, attr: AttrId) -> Diagnostic {
471    let def = schema.attr(attr);
472    Diagnostic::warning(
473        Rule::Structure,
474        format!(
475            "{} changed, but IEC 61970-552 difference statements cannot carry a compound \
476             value; the change is not in the change set",
477            def.name
478        ),
479    )
480    .with_class(schema.class(def.owner).name)
481    .with_object(mrid.clone())
482    .with_attribute(def.name)
483}
484
485/// A minimal change-set header: the target's profiles, and the base as what it supersedes.
486///
487/// `md:Model.Supersedes` names the models being *replaced* — the base — which is what lets
488/// a receiver check that it is applying the change to the model it was computed against.
489/// Every change set ENTSO-E publishes does this; this function used to list the target's
490/// models instead, so each change set claimed to replace the state it produced.
491///
492/// The identifier is derived rather than random: the same pair of models must produce the
493/// same change file every time, or a change set stops being comparable with the last one.
494/// It depends on both sides, because two bases changed into one target are two changes.
495fn derived_header(base: &Dataset, target: &Dataset) -> ModelHeader {
496    let profiles: Vec<String> = target
497        .headers()
498        .iter()
499        .flat_map(|h| h.profiles.iter().cloned())
500        .collect();
501    let ids =
502        |ds: &Dataset| -> Vec<Mrid> { ds.headers().iter().filter_map(|h| h.id.clone()).collect() };
503    let supersedes = ids(base);
504
505    // A model loaded from files has header identifiers and they say what it is exactly; one
506    // built in memory has none, so that side falls back to what it actually contains,
507    // which costs a walk of the model but only where there is no cheaper answer.
508    let name_of = |ds: &Dataset, ids: Vec<Mrid>| -> String {
509        if ids.is_empty() {
510            ds.content_id().canonical()
511        } else {
512            ids.iter()
513                .map(Mrid::canonical)
514                .collect::<Vec<_>>()
515                .join(" ")
516        }
517    };
518    let name = format!(
519        "{} -> {}",
520        name_of(base, supersedes.clone()),
521        name_of(target, ids(target))
522    );
523
524    let mut header = ModelHeader::new(ModelKind::Difference);
525    header.id = Some(Mrid::new_v5(&Dataset::DERIVED_NS, name.as_bytes()));
526    header.version = Some("1".to_owned());
527    header.profiles = dedup(profiles);
528    header.supersedes = supersedes;
529    header
530}
531
532fn dedup(mut v: Vec<String>) -> Vec<String> {
533    let mut seen = Vec::new();
534    v.retain(|s| {
535        let new = !seen.contains(s);
536        if new {
537            seen.push(s.clone());
538        }
539        new
540    });
541    v
542}