Skip to main content

cim_kit/
diff.rs

1//! Computing a difference model from two model states.
2//!
3//! IEC 61970-552's `dm:DifferenceModel` exchanges an update as statements to retract and
4//! statements to assert. [`reader::read_difference`](crate::reader::read_difference),
5//! [`Dataset::apply_difference`] and [`writer::write_difference`](crate::writer::write_difference)
6//! read, apply and write one; this module **produces** one from a before and an after.
7//!
8// An example has to name a vintage, and a vintage is a feature. See `Dataset::view`.
9#![cfg_attr(
10    feature = "cgmes3",
11    doc = r#"
12```no_run
13use cim_kit::prelude::*;
14use cim_kit::cgmes3::SCHEMA;
15use cim_kit::diff::DiffOptions;
16
17# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
18let base = Dataset::load(SCHEMA, ["base_EQ.xml", "base_SSH.xml"])?;
19let updated = Dataset::load(SCHEMA, ["updated_EQ.xml", "updated_SSH.xml"])?;
20
21let change = base.difference_to(&updated, &DiffOptions::default());
22let out = std::fs::File::create("change_DIFF.xml")?;
23cim_kit::writer::write_difference(SCHEMA, &change.model, out, &Default::default())?;
24# Ok(())
25# }
26```
27"#
28)]
29//!
30//! # What the result guarantees
31//!
32//! Applying the result to the base reproduces the target:
33//! `base.apply_difference(&base.difference_to(&target, o).model)` leaves `base` holding
34//! every value `target` holds, and none it does not (tested in `tests/difference.rs`).
35//!
36//! # What a statement-level difference cannot say
37//!
38//! Two limits of the standard, both reported:
39//!
40//! * **An object cannot be deleted, only emptied.** `rdf:parseType="Statements"` retracts
41//!   statements; there is no statement that says "this identifier no longer denotes
42//!   anything". An object absent from the target becomes a subject with no properties;
43//!   [`Dataset::prune_empty`] removes such shells.
44//! * **A compound has no statement form.** `Location.mainAddress` holds a `StreetAddress`
45//!   inline, which the statement syntax cannot carry. A changed compound is reported as
46//!   [`Rule::Structure`] and left out.
47
48use crate::dataset::{Dataset, ObjectId};
49use crate::error::{Diagnostic, Report, Rule};
50use crate::header::{
51    DifferenceModel, ModelHeader, ModelKind, QualifiedName, Statement, StatementValue,
52};
53use crate::mrid::Mrid;
54use crate::object::{Object, Slot};
55use crate::schema::{AttrId, AttrKind, ClassId, Primitive, ProfileMask, Schema};
56use crate::value::Value;
57
58/// Options controlling how a difference is computed.
59#[derive(Clone, Debug, Default)]
60pub struct DiffOptions {
61    /// Compare only values belonging to these profiles; zero means "everything".
62    ///
63    /// Filtering follows the CIM/XML writer ([`Schema::effective_profiles`]), so a change
64    /// set restricted to SSH holds exactly the values an SSH export would.
65    pub profiles: ProfileMask,
66    /// Header to give the change set. Without one, a minimal `dm:DifferenceModel` header
67    /// is derived from the target's own headers.
68    pub header: Option<ModelHeader>,
69}
70
71impl DiffOptions {
72    /// Restrict the comparison to a set of profiles.
73    pub fn profiles(mut self, profiles: ProfileMask) -> Self {
74        self.profiles = profiles;
75        self
76    }
77
78    pub fn with_header(mut self, header: ModelHeader) -> Self {
79        self.header = Some(header);
80        self
81    }
82}
83
84/// A computed change set, together with what could not be expressed.
85#[derive(Debug)]
86pub struct DiffReport {
87    pub model: DifferenceModel,
88    /// Differences the statement syntax cannot carry, and mismatches that prevented one.
89    pub report: Report,
90    /// Objects present only in the target.
91    pub added: usize,
92    /// Objects present only in the base.
93    pub removed: usize,
94    /// Objects present in both whose description changed.
95    pub changed: usize,
96}
97
98impl DiffReport {
99    /// Whether the two models describe the same thing.
100    pub fn is_empty(&self) -> bool {
101        self.model.forward.is_empty() && self.model.reverse.is_empty()
102    }
103}
104
105impl Dataset {
106    /// The change set that turns this model into `target`.
107    ///
108    /// See the [module documentation](self) for what the result guarantees and for the two
109    /// things a statement-level difference cannot express.
110    pub fn difference_to(&self, target: &Dataset, options: &DiffOptions) -> DiffReport {
111        let schema = self.schema();
112        let mut out = DiffReport {
113            model: DifferenceModel {
114                header: options
115                    .header
116                    .clone()
117                    .unwrap_or_else(|| derived_header(self, target)),
118                preconditions: Vec::new(),
119                reverse: Vec::new(),
120                forward: Vec::new(),
121            },
122            report: Report::default(),
123            added: 0,
124            removed: 0,
125            changed: 0,
126        };
127        out.model.header.kind = ModelKind::Difference;
128
129        // `AttrId`s from different vocabularies are not comparable.
130        if !std::ptr::eq(schema, target.schema()) {
131            out.report.push(Diagnostic::error(
132                Rule::Structure,
133                format!(
134                    "cannot diff a {} model against a {} model",
135                    schema.vintage,
136                    target.schema().vintage
137                ),
138            ));
139            return out;
140        }
141
142        // mRID order, so a change set is reproducible.
143        for mrid in union_of_identifiers(self, target) {
144            let before = self.by_mrid(&mrid);
145            let after = target.by_mrid(&mrid);
146            match (before, after) {
147                (None, Some(new)) => {
148                    let n = out.model.forward.len();
149                    self.emit_all(new, true, options, &mut out.model.forward, &mut out.report);
150                    if out.model.forward.len() > n {
151                        out.added += 1;
152                    }
153                }
154                (Some(old), None) => {
155                    let n = out.model.reverse.len();
156                    self.emit_all(old, false, options, &mut out.model.reverse, &mut out.report);
157                    if out.model.reverse.len() > n {
158                        out.removed += 1;
159                    }
160                }
161                (Some(old), Some(new)) => {
162                    // Fast path for untouched objects; a provenance-only difference falls
163                    // through to the slow path and produces no statements.
164                    if old.class() == new.class() && old.slots() == new.slots() {
165                        continue;
166                    }
167                    let (r, f) = (out.model.reverse.len(), out.model.forward.len());
168                    self.emit_changes(old, new, options, &mut out);
169                    if out.model.reverse.len() > r || out.model.forward.len() > f {
170                        out.changed += 1;
171                    }
172                }
173                (None, None) => {}
174            }
175        }
176
177        // Deletion cannot be expressed either; one diagnostic for all, not one per object.
178        if out.removed > 0 {
179            out.report.push(Diagnostic::warning(
180                Rule::Structure,
181                format!(
182                    "{} object(s) are absent from the target and a difference model cannot \
183                     say so: applying this retracts everything they said and leaves the \
184                     identifiers behind. Dataset::prune_empty removes such shells",
185                    out.removed
186                ),
187            ));
188        }
189        out
190    }
191
192    /// Every value of one object as statements, for an object that is wholly new or gone.
193    fn emit_all(
194        &self,
195        obj: &Object,
196        introduces: bool,
197        options: &DiffOptions,
198        into: &mut Vec<Statement>,
199        report: &mut Report,
200    ) {
201        let schema = self.schema();
202        let class = qualified(schema, obj.class());
203        for slot in obj.slots() {
204            if !in_scope(schema, slot, options.profiles) {
205                continue;
206            }
207            match statement(schema, slot.attr, &slot.value) {
208                Some(value) => into.push(Statement {
209                    subject: obj.mrid().clone(),
210                    class: Some(class.clone()),
211                    // `rdf:ID` for an object the change set introduces, `rdf:about` for
212                    // one it retracts from.
213                    defines_subject: introduces,
214                    predicate_ns: schema.namespace(schema.attr(slot.attr).ns).iri.to_owned(),
215                    predicate: schema.attr(slot.attr).name.to_owned(),
216                    value,
217                }),
218                None => report.push(inexpressible(schema, obj.mrid(), slot.attr)),
219            }
220        }
221    }
222
223    /// The statements that turn `old`'s description into `new`'s.
224    fn emit_changes(
225        &self,
226        old: &Object,
227        new: &Object,
228        options: &DiffOptions,
229        out: &mut DiffReport,
230    ) {
231        let schema = self.schema();
232        // The class is named only when it changed (552 treats the type as a statement).
233        let reclassified = old.class() != new.class();
234        let forward_class = reclassified.then(|| qualified(schema, new.class()));
235        let reverse_class = reclassified.then(|| qualified(schema, old.class()));
236        let forward_before = out.model.forward.len();
237
238        for attr in attributes_of_either(old, new) {
239            fn scoped<'o>(
240                schema: &Schema,
241                o: &'o Object,
242                attr: AttrId,
243                profiles: ProfileMask,
244            ) -> Vec<&'o Value> {
245                o.get_all(attr)
246                    .iter()
247                    .filter(|s| in_scope(schema, s, profiles))
248                    .map(|s| &s.value)
249                    .collect()
250            }
251            let before = scoped(schema, old, attr, options.profiles);
252            let after = scoped(schema, new, attr, options.profiles);
253            if before == after {
254                continue;
255            }
256            // Many-valued attributes are compared as multisets: two occurrences of the
257            // same value are two statements, and retracting one must not retract both.
258            let mut removed = before.clone();
259            let mut added: Vec<&Value> = Vec::new();
260            for v in after {
261                match removed.iter().position(|x| *x == v) {
262                    Some(i) => {
263                        removed.remove(i);
264                    }
265                    None => added.push(v),
266                }
267            }
268
269            for (values, class, defines, into) in [
270                (
271                    removed,
272                    reverse_class.clone(),
273                    false,
274                    &mut out.model.reverse,
275                ),
276                (added, forward_class.clone(), false, &mut out.model.forward),
277            ] {
278                for v in values {
279                    match statement(schema, attr, v) {
280                        Some(value) => into.push(Statement {
281                            subject: new.mrid().clone(),
282                            class: class.clone(),
283                            defines_subject: defines,
284                            predicate_ns: schema.namespace(schema.attr(attr).ns).iri.to_owned(),
285                            predicate: schema.attr(attr).name.to_owned(),
286                            value,
287                        }),
288                        None => out.report.push(inexpressible(schema, new.mrid(), attr)),
289                    }
290                }
291            }
292        }
293
294        // A reclassification with no attribute change still needs a statement. Checked
295        // against the mark taken before this object, not by rescanning (quadratic).
296        if reclassified && out.model.forward.len() == forward_before {
297            match mrid_attribute(schema, new) {
298                Some(attr) => out.model.forward.push(Statement {
299                    subject: new.mrid().clone(),
300                    class: forward_class,
301                    defines_subject: false,
302                    predicate_ns: schema.namespace(schema.attr(attr).ns).iri.to_owned(),
303                    predicate: schema.attr(attr).name.to_owned(),
304                    value: StatementValue::Literal(new.mrid().canonical()),
305                }),
306                // No property to carry the class. Unreachable for CGMES (every class has
307                // `mRID`), but possible for another vocabulary.
308                None => out.report.push(
309                    Diagnostic::warning(
310                        Rule::Structure,
311                        format!(
312                            "{} changed class from {} to {}, but {} has no attribute the \
313                             statement could carry, so the change is not in the change set",
314                            new.mrid().canonical(),
315                            schema.class(old.class()).name,
316                            schema.class(new.class()).name,
317                            schema.class(new.class()).name,
318                        ),
319                    )
320                    .with_class(schema.class(new.class()).name)
321                    .with_object(new.mrid().clone()),
322                ),
323            }
324        }
325    }
326
327    /// Remove objects that carry no values at all.
328    ///
329    /// A difference cannot delete an object, only retract all its values; this removes the
330    /// shells left behind. Returns how many were removed.
331    ///
332    /// Separate from [`Dataset::apply_difference`] because a model may legitimately hold
333    /// objects described only by files that are not loaded.
334    pub fn prune_empty(&mut self) -> usize {
335        let empty: Vec<ObjectId> = self
336            .iter()
337            .filter(|(_, o)| o.is_empty())
338            .map(|(id, _)| id)
339            .collect();
340        let n = empty.len();
341        for id in empty {
342            self.remove(id);
343        }
344        n
345    }
346}
347
348/// Every identifier either model knows, in a stable order.
349fn union_of_identifiers(a: &Dataset, b: &Dataset) -> Vec<Mrid> {
350    let mut out: Vec<Mrid> = a
351        .iter()
352        .chain(b.iter())
353        .map(|(_, o)| o.mrid().clone())
354        .collect();
355    out.sort();
356    out.dedup();
357    out
358}
359
360/// Attributes either object carries, in schema order.
361///
362/// A merge of two slot vectors sorted by [`AttrId`], including attributes the class
363/// does not declare.
364fn attributes_of_either(a: &Object, b: &Object) -> Vec<AttrId> {
365    let mut out: Vec<AttrId> = a
366        .slots()
367        .iter()
368        .chain(b.slots())
369        .map(|s: &Slot| s.attr)
370        .collect();
371    out.sort();
372    out.dedup();
373    out
374}
375
376/// Whether a stored value takes part in a comparison restricted to `profiles`.
377///
378/// The CIM/XML writer's rule, [`Schema::effective_profiles`].
379fn in_scope(schema: &Schema, slot: &Slot, profiles: ProfileMask) -> bool {
380    profiles == 0 || schema.effective_profiles(slot.attr, slot.profiles) & profiles != 0
381}
382
383fn qualified(schema: &Schema, class: ClassId) -> QualifiedName {
384    let def = schema.class(class);
385    QualifiedName {
386        ns: schema.namespace(def.ns).iri.to_owned(),
387        local: def.name.to_owned(),
388    }
389}
390
391/// `IdentifiedObject.mRID` as visible on this object, for a statement that carries no
392/// other payload.
393fn mrid_attribute(schema: &Schema, obj: &Object) -> Option<AttrId> {
394    schema.attr_by_label(obj.class(), "mRID")
395}
396
397/// One stored value as a difference statement's value, or `None` if it has no such form.
398fn statement(schema: &Schema, attr: AttrId, value: &Value) -> Option<StatementValue> {
399    let kind = schema.attr(attr).kind;
400    Some(match value {
401        // Written as an instance file writes it, so it resolves against the same model.
402        Value::Reference(m) => StatementValue::Resource(m.to_rdf_reference()),
403        Value::Enum(e) => {
404            let ev = schema.enum_value(*e);
405            StatementValue::Resource(format!("{}{}", schema.namespace(ev.ns).iri, ev.name))
406        }
407        // `rdf:parseType="Statements"` cannot carry an inline compound.
408        Value::Compound(_) => return None,
409        other => StatementValue::Literal(other.to_lexical_as(lexical(schema, kind))?),
410    })
411}
412
413fn lexical(schema: &Schema, kind: AttrKind) -> Primitive {
414    match kind {
415        AttrKind::Primitive(p) => p,
416        AttrKind::Datatype(d) => schema.datatype(d).value,
417        _ => Primitive::String,
418    }
419}
420
421fn inexpressible(schema: &Schema, mrid: &Mrid, attr: AttrId) -> Diagnostic {
422    let def = schema.attr(attr);
423    Diagnostic::warning(
424        Rule::Structure,
425        format!(
426            "{} changed, but IEC 61970-552 difference statements cannot carry a compound \
427             value; the change is not in the change set",
428            def.name
429        ),
430    )
431    .with_class(schema.class(def.owner).name)
432    .with_object(mrid.clone())
433    .with_attribute(def.name)
434}
435
436/// A minimal change-set header: the target's profiles, and the base as what it supersedes.
437///
438/// `md:Model.Supersedes` names the base, so a receiver can check it applies the change to
439/// the model it was computed against. The identifier is derived from both sides, so the
440/// same pair always gives the same change file.
441fn derived_header(base: &Dataset, target: &Dataset) -> ModelHeader {
442    let profiles: Vec<String> = target
443        .headers()
444        .iter()
445        .flat_map(|h| h.profiles.iter().cloned())
446        .collect();
447    let ids =
448        |ds: &Dataset| -> Vec<Mrid> { ds.headers().iter().filter_map(|h| h.id.clone()).collect() };
449    let supersedes = ids(base);
450
451    // Header identifiers where loaded from files; otherwise the content identifier.
452    let name_of = |ds: &Dataset, ids: Vec<Mrid>| -> String {
453        if ids.is_empty() {
454            ds.content_id().canonical()
455        } else {
456            ids.iter()
457                .map(Mrid::canonical)
458                .collect::<Vec<_>>()
459                .join(" ")
460        }
461    };
462    let name = format!(
463        "{} -> {}",
464        name_of(base, supersedes.clone()),
465        name_of(target, ids(target))
466    );
467
468    let mut header = ModelHeader::new(ModelKind::Difference);
469    header.id = Some(Mrid::new_v5(&Dataset::DERIVED_NS, name.as_bytes()));
470    header.version = Some("1".to_owned());
471    header.profiles = dedup(profiles);
472    header.supersedes = supersedes;
473    header
474}
475
476fn dedup(mut v: Vec<String>) -> Vec<String> {
477    let mut seen = Vec::new();
478    v.retain(|s| {
479        let new = !seen.contains(s);
480        if new {
481            seen.push(s.clone());
482        }
483        new
484    });
485    v
486}