cim-kit 0.4.1

IEC CIM/CGMES for power systems: CIM/XML I/O that reproduces the file set, profile-aware validation, typed RDF export
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! Computing a difference model from two model states.
//!
//! IEC 61970-552's `dm:DifferenceModel` exchanges an update as statements to retract and
//! statements to assert. [`reader::read_difference`](crate::reader::read_difference),
//! [`Dataset::apply_difference`] and [`writer::write_difference`](crate::writer::write_difference)
//! read, apply and write one; this module **produces** one from a before and an after.
//!
// An example has to name a vintage, and a vintage is a feature. See `Dataset::view`.
#![cfg_attr(
    feature = "cgmes3",
    doc = r#"
```no_run
use cim_kit::prelude::*;
use cim_kit::cgmes3::SCHEMA;
use cim_kit::diff::DiffOptions;

# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let base = Dataset::load(SCHEMA, ["base_EQ.xml", "base_SSH.xml"])?;
let updated = Dataset::load(SCHEMA, ["updated_EQ.xml", "updated_SSH.xml"])?;

let change = base.difference_to(&updated, &DiffOptions::default());
let out = std::fs::File::create("change_DIFF.xml")?;
cim_kit::writer::write_difference(SCHEMA, &change.model, out, &Default::default())?;
# Ok(())
# }
```
"#
)]
//!
//! # What the result guarantees
//!
//! Applying the result to the base reproduces the target:
//! `base.apply_difference(&base.difference_to(&target, o).model)` leaves `base` holding
//! every value `target` holds, and none it does not (tested in `tests/difference.rs`).
//!
//! # What a statement-level difference cannot say
//!
//! Two limits of the standard, both reported:
//!
//! * **An object cannot be deleted, only emptied.** `rdf:parseType="Statements"` retracts
//!   statements; there is no statement that says "this identifier no longer denotes
//!   anything". An object absent from the target becomes a subject with no properties;
//!   [`Dataset::prune_empty`] removes such shells.
//! * **A compound has no statement form.** `Location.mainAddress` holds a `StreetAddress`
//!   inline, which the statement syntax cannot carry. A changed compound is reported as
//!   [`Rule::Structure`] and left out.

use crate::dataset::{Dataset, ObjectId};
use crate::error::{Diagnostic, Report, Rule};
use crate::header::{
    DifferenceModel, ModelHeader, ModelKind, QualifiedName, Statement, StatementValue,
};
use crate::mrid::Mrid;
use crate::object::{Object, Slot};
use crate::schema::{AttrId, AttrKind, ClassId, Primitive, ProfileMask, Schema};
use crate::value::Value;

/// Options controlling how a difference is computed.
#[derive(Clone, Debug, Default)]
pub struct DiffOptions {
    /// Compare only values belonging to these profiles; zero means "everything".
    ///
    /// Filtering follows the CIM/XML writer ([`Schema::effective_profiles`]), so a change
    /// set restricted to SSH holds exactly the values an SSH export would.
    pub profiles: ProfileMask,
    /// Header to give the change set. Without one, a minimal `dm:DifferenceModel` header
    /// is derived from the target's own headers.
    pub header: Option<ModelHeader>,
}

impl DiffOptions {
    /// Restrict the comparison to a set of profiles.
    pub fn profiles(mut self, profiles: ProfileMask) -> Self {
        self.profiles = profiles;
        self
    }

    pub fn with_header(mut self, header: ModelHeader) -> Self {
        self.header = Some(header);
        self
    }
}

/// A computed change set, together with what could not be expressed.
#[derive(Debug)]
pub struct DiffReport {
    pub model: DifferenceModel,
    /// Differences the statement syntax cannot carry, and mismatches that prevented one.
    pub report: Report,
    /// Objects present only in the target.
    pub added: usize,
    /// Objects present only in the base.
    pub removed: usize,
    /// Objects present in both whose description changed.
    pub changed: usize,
}

impl DiffReport {
    /// Whether the two models describe the same thing.
    pub fn is_empty(&self) -> bool {
        self.model.forward.is_empty() && self.model.reverse.is_empty()
    }
}

impl Dataset {
    /// The change set that turns this model into `target`.
    ///
    /// See the [module documentation](self) for what the result guarantees and for the two
    /// things a statement-level difference cannot express.
    pub fn difference_to(&self, target: &Dataset, options: &DiffOptions) -> DiffReport {
        let schema = self.schema();
        let mut out = DiffReport {
            model: DifferenceModel {
                header: options
                    .header
                    .clone()
                    .unwrap_or_else(|| derived_header(self, target)),
                preconditions: Vec::new(),
                reverse: Vec::new(),
                forward: Vec::new(),
            },
            report: Report::default(),
            added: 0,
            removed: 0,
            changed: 0,
        };
        out.model.header.kind = ModelKind::Difference;

        // `AttrId`s from different vocabularies are not comparable.
        if !std::ptr::eq(schema, target.schema()) {
            out.report.push(Diagnostic::error(
                Rule::Structure,
                format!(
                    "cannot diff a {} model against a {} model",
                    schema.vintage,
                    target.schema().vintage
                ),
            ));
            return out;
        }

        // mRID order, so a change set is reproducible.
        for mrid in union_of_identifiers(self, target) {
            let before = self.by_mrid(&mrid);
            let after = target.by_mrid(&mrid);
            match (before, after) {
                (None, Some(new)) => {
                    let n = out.model.forward.len();
                    self.emit_all(new, true, options, &mut out.model.forward, &mut out.report);
                    if out.model.forward.len() > n {
                        out.added += 1;
                    }
                }
                (Some(old), None) => {
                    let n = out.model.reverse.len();
                    self.emit_all(old, false, options, &mut out.model.reverse, &mut out.report);
                    if out.model.reverse.len() > n {
                        out.removed += 1;
                    }
                }
                (Some(old), Some(new)) => {
                    // Fast path for untouched objects; a provenance-only difference falls
                    // through to the slow path and produces no statements.
                    if old.class() == new.class() && old.slots() == new.slots() {
                        continue;
                    }
                    let (r, f) = (out.model.reverse.len(), out.model.forward.len());
                    self.emit_changes(old, new, options, &mut out);
                    if out.model.reverse.len() > r || out.model.forward.len() > f {
                        out.changed += 1;
                    }
                }
                (None, None) => {}
            }
        }

        // Deletion cannot be expressed either; one diagnostic for all, not one per object.
        if out.removed > 0 {
            out.report.push(Diagnostic::warning(
                Rule::Structure,
                format!(
                    "{} object(s) are absent from the target and a difference model cannot \
                     say so: applying this retracts everything they said and leaves the \
                     identifiers behind. Dataset::prune_empty removes such shells",
                    out.removed
                ),
            ));
        }
        out
    }

    /// Every value of one object as statements, for an object that is wholly new or gone.
    fn emit_all(
        &self,
        obj: &Object,
        introduces: bool,
        options: &DiffOptions,
        into: &mut Vec<Statement>,
        report: &mut Report,
    ) {
        let schema = self.schema();
        let class = qualified(schema, obj.class());
        for slot in obj.slots() {
            if !in_scope(schema, slot, options.profiles) {
                continue;
            }
            match statement(schema, slot.attr, &slot.value) {
                Some(value) => into.push(Statement {
                    subject: obj.mrid().clone(),
                    class: Some(class.clone()),
                    // `rdf:ID` for an object the change set introduces, `rdf:about` for
                    // one it retracts from.
                    defines_subject: introduces,
                    predicate_ns: schema.namespace(schema.attr(slot.attr).ns).iri.to_owned(),
                    predicate: schema.attr(slot.attr).name.to_owned(),
                    value,
                }),
                None => report.push(inexpressible(schema, obj.mrid(), slot.attr)),
            }
        }
    }

    /// The statements that turn `old`'s description into `new`'s.
    fn emit_changes(
        &self,
        old: &Object,
        new: &Object,
        options: &DiffOptions,
        out: &mut DiffReport,
    ) {
        let schema = self.schema();
        // The class is named only when it changed (552 treats the type as a statement).
        let reclassified = old.class() != new.class();
        let forward_class = reclassified.then(|| qualified(schema, new.class()));
        let reverse_class = reclassified.then(|| qualified(schema, old.class()));
        let forward_before = out.model.forward.len();

        for attr in attributes_of_either(old, new) {
            fn scoped<'o>(
                schema: &Schema,
                o: &'o Object,
                attr: AttrId,
                profiles: ProfileMask,
            ) -> Vec<&'o Value> {
                o.get_all(attr)
                    .iter()
                    .filter(|s| in_scope(schema, s, profiles))
                    .map(|s| &s.value)
                    .collect()
            }
            let before = scoped(schema, old, attr, options.profiles);
            let after = scoped(schema, new, attr, options.profiles);
            if before == after {
                continue;
            }
            // Many-valued attributes are compared as multisets: two occurrences of the
            // same value are two statements, and retracting one must not retract both.
            let mut removed = before.clone();
            let mut added: Vec<&Value> = Vec::new();
            for v in after {
                match removed.iter().position(|x| *x == v) {
                    Some(i) => {
                        removed.remove(i);
                    }
                    None => added.push(v),
                }
            }

            for (values, class, defines, into) in [
                (
                    removed,
                    reverse_class.clone(),
                    false,
                    &mut out.model.reverse,
                ),
                (added, forward_class.clone(), false, &mut out.model.forward),
            ] {
                for v in values {
                    match statement(schema, attr, v) {
                        Some(value) => into.push(Statement {
                            subject: new.mrid().clone(),
                            class: class.clone(),
                            defines_subject: defines,
                            predicate_ns: schema.namespace(schema.attr(attr).ns).iri.to_owned(),
                            predicate: schema.attr(attr).name.to_owned(),
                            value,
                        }),
                        None => out.report.push(inexpressible(schema, new.mrid(), attr)),
                    }
                }
            }
        }

        // A reclassification with no attribute change still needs a statement. Checked
        // against the mark taken before this object, not by rescanning (quadratic).
        if reclassified && out.model.forward.len() == forward_before {
            match mrid_attribute(schema, new) {
                Some(attr) => out.model.forward.push(Statement {
                    subject: new.mrid().clone(),
                    class: forward_class,
                    defines_subject: false,
                    predicate_ns: schema.namespace(schema.attr(attr).ns).iri.to_owned(),
                    predicate: schema.attr(attr).name.to_owned(),
                    value: StatementValue::Literal(new.mrid().canonical()),
                }),
                // No property to carry the class. Unreachable for CGMES (every class has
                // `mRID`), but possible for another vocabulary.
                None => out.report.push(
                    Diagnostic::warning(
                        Rule::Structure,
                        format!(
                            "{} changed class from {} to {}, but {} has no attribute the \
                             statement could carry, so the change is not in the change set",
                            new.mrid().canonical(),
                            schema.class(old.class()).name,
                            schema.class(new.class()).name,
                            schema.class(new.class()).name,
                        ),
                    )
                    .with_class(schema.class(new.class()).name)
                    .with_object(new.mrid().clone()),
                ),
            }
        }
    }

    /// Remove objects that carry no values at all.
    ///
    /// A difference cannot delete an object, only retract all its values; this removes the
    /// shells left behind. Returns how many were removed.
    ///
    /// Separate from [`Dataset::apply_difference`] because a model may legitimately hold
    /// objects described only by files that are not loaded.
    pub fn prune_empty(&mut self) -> usize {
        let empty: Vec<ObjectId> = self
            .iter()
            .filter(|(_, o)| o.is_empty())
            .map(|(id, _)| id)
            .collect();
        let n = empty.len();
        for id in empty {
            self.remove(id);
        }
        n
    }
}

/// Every identifier either model knows, in a stable order.
fn union_of_identifiers(a: &Dataset, b: &Dataset) -> Vec<Mrid> {
    let mut out: Vec<Mrid> = a
        .iter()
        .chain(b.iter())
        .map(|(_, o)| o.mrid().clone())
        .collect();
    out.sort();
    out.dedup();
    out
}

/// Attributes either object carries, in schema order.
///
/// A merge of two slot vectors sorted by [`AttrId`], including attributes the class
/// does not declare.
fn attributes_of_either(a: &Object, b: &Object) -> Vec<AttrId> {
    let mut out: Vec<AttrId> = a
        .slots()
        .iter()
        .chain(b.slots())
        .map(|s: &Slot| s.attr)
        .collect();
    out.sort();
    out.dedup();
    out
}

/// Whether a stored value takes part in a comparison restricted to `profiles`.
///
/// The CIM/XML writer's rule, [`Schema::effective_profiles`].
fn in_scope(schema: &Schema, slot: &Slot, profiles: ProfileMask) -> bool {
    profiles == 0 || schema.effective_profiles(slot.attr, slot.profiles) & profiles != 0
}

fn qualified(schema: &Schema, class: ClassId) -> QualifiedName {
    let def = schema.class(class);
    QualifiedName {
        ns: schema.namespace(def.ns).iri.to_owned(),
        local: def.name.to_owned(),
    }
}

/// `IdentifiedObject.mRID` as visible on this object, for a statement that carries no
/// other payload.
fn mrid_attribute(schema: &Schema, obj: &Object) -> Option<AttrId> {
    schema.attr_by_label(obj.class(), "mRID")
}

/// One stored value as a difference statement's value, or `None` if it has no such form.
fn statement(schema: &Schema, attr: AttrId, value: &Value) -> Option<StatementValue> {
    let kind = schema.attr(attr).kind;
    Some(match value {
        // Written as an instance file writes it, so it resolves against the same model.
        Value::Reference(m) => StatementValue::Resource(m.to_rdf_reference()),
        Value::Enum(e) => {
            let ev = schema.enum_value(*e);
            StatementValue::Resource(format!("{}{}", schema.namespace(ev.ns).iri, ev.name))
        }
        // `rdf:parseType="Statements"` cannot carry an inline compound.
        Value::Compound(_) => return None,
        other => StatementValue::Literal(other.to_lexical_as(lexical(schema, kind))?),
    })
}

fn lexical(schema: &Schema, kind: AttrKind) -> Primitive {
    match kind {
        AttrKind::Primitive(p) => p,
        AttrKind::Datatype(d) => schema.datatype(d).value,
        _ => Primitive::String,
    }
}

fn inexpressible(schema: &Schema, mrid: &Mrid, attr: AttrId) -> Diagnostic {
    let def = schema.attr(attr);
    Diagnostic::warning(
        Rule::Structure,
        format!(
            "{} changed, but IEC 61970-552 difference statements cannot carry a compound \
             value; the change is not in the change set",
            def.name
        ),
    )
    .with_class(schema.class(def.owner).name)
    .with_object(mrid.clone())
    .with_attribute(def.name)
}

/// A minimal change-set header: the target's profiles, and the base as what it supersedes.
///
/// `md:Model.Supersedes` names the base, so a receiver can check it applies the change to
/// the model it was computed against. The identifier is derived from both sides, so the
/// same pair always gives the same change file.
fn derived_header(base: &Dataset, target: &Dataset) -> ModelHeader {
    let profiles: Vec<String> = target
        .headers()
        .iter()
        .flat_map(|h| h.profiles.iter().cloned())
        .collect();
    let ids =
        |ds: &Dataset| -> Vec<Mrid> { ds.headers().iter().filter_map(|h| h.id.clone()).collect() };
    let supersedes = ids(base);

    // Header identifiers where loaded from files; otherwise the content identifier.
    let name_of = |ds: &Dataset, ids: Vec<Mrid>| -> String {
        if ids.is_empty() {
            ds.content_id().canonical()
        } else {
            ids.iter()
                .map(Mrid::canonical)
                .collect::<Vec<_>>()
                .join(" ")
        }
    };
    let name = format!(
        "{} -> {}",
        name_of(base, supersedes.clone()),
        name_of(target, ids(target))
    );

    let mut header = ModelHeader::new(ModelKind::Difference);
    header.id = Some(Mrid::new_v5(&Dataset::DERIVED_NS, name.as_bytes()));
    header.version = Some("1".to_owned());
    header.profiles = dedup(profiles);
    header.supersedes = supersedes;
    header
}

fn dedup(mut v: Vec<String>) -> Vec<String> {
    let mut seen = Vec::new();
    v.retain(|s| {
        let new = !seen.contains(s);
        if new {
            seen.push(s.clone());
        }
        new
    });
    v
}