cim-kit 0.4.0

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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Computing a difference model from two model states.
//!
//! # Why this exists
//!
//! IEC 61970-552 defines `dm:DifferenceModel` as the incremental form of exchange: rather
//! than resending a whole grid model, a producer sends the statements to retract and the
//! statements to assert. Reading, applying and writing one is
//! [`reader::read_difference`](crate::reader::read_difference),
//! [`Dataset::apply_difference`] and [`writer::write_difference`](crate::writer::write_difference).
//! This module supplies the piece those three imply and none of them provides:
//! **producing** a change set from a before and an after.
//!
//! It is the operation an EMS performs every time it publishes an update, and it is
//! decidable from what the crate already holds — objects keyed by mRID, values sorted by
//! attribute, profile provenance per value — so it costs a walk of the two models and no
//! new machinery.
//!
// 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. That round trip is a test, not a
//! claim — see `tests/difference.rs`.
//!
//! # What a statement-level difference cannot say
//!
//! Two limits are the standard's, not this implementation's, and both are reported rather
//! than papered over:
//!
//! * **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 present in the base and absent from the target therefore becomes
//!   a subject with no properties. [`Dataset::prune_empty`] removes such shells where a
//!   consumer wants them gone.
//! * **A compound has no statement form.** `Location.mainAddress` holds a `StreetAddress`
//!   inline, and IEC 61970-552's statement syntax has nowhere to put one. A changed
//!   compound is reported as [`Rule::Structure`] and left out,
//!   because emitting it as text would fabricate a value.

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 same rule as the CIM/XML writer
    /// ([`Schema::effective_profiles`]), so a change set restricted to Steady State
    /// Hypothesis contains exactly the values an SSH export would, and no equipment
    /// changes that belong in a different file.
    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;

        // Comparing models built from different vocabularies would compare `AttrId`s that
        // mean different things, which is worse than refusing.
        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 and diffable between runs — the same
        // reason the CIM/XML writer sorts.
        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)) => {
                    // Most objects are untouched even in a large update, and comparing
                    // their slot vectors directly is a linear scan that allocates nothing
                    // — where the per-attribute path builds a vector per attribute. A
                    // provenance-only difference falls through to the slow path and
                    // correctly produces no statements, so this is a fast path and not a
                    // second definition of equality.
                    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) => {}
            }
        }

        // The other thing a statement-level difference cannot express. A changed compound
        // is already reported; deletion was only *counted*, which left the two limits of
        // the same syntax documented to different standards — and a caller who applies this
        // change set and compares content identifiers finds an object that is empty rather
        // than absent, with nothing in the report to explain it.
        //
        // One diagnostic rather than one per object: the count is the fact, and a report
        // that grows with the size of the change is the thing `max_diagnostics` exists to
        // prevent elsewhere.
        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()),
                    // A change set that introduces an object identifies it with `rdf:ID`;
                    // one that retracts an existing object's statements refers to it with
                    // `rdf:about`, because it is not the file that defined it.
                    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();
        // A difference names an object's class only when it is saying something about it.
        // IEC 61970-552 treats the type as a statement like any other, and the published
        // conformity change sets use exactly this to replace a `LinearShuntCompensator`
        // with a `NonlinearShuntCompensator` under one identifier.
        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 has to be said, or applying
        // the difference would leave the object as the class it used to be.
        //
        // "No attribute change" is decided from the mark taken before this object was
        // handled, not by searching the accumulated statements: a change set can run to
        // hundreds of thousands of statements, and re-scanning them once per object turns
        // the whole comparison 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()),
                }),
                // A statement group names its class on a property element, so a class
                // change with no property to hang it on cannot be said at all. Every CGMES
                // class descends from `IdentifiedObject` and so has `mRID`, which is why
                // this is unreachable there — but "a profile is data", and a vocabulary
                // that declares a class outside that hierarchy would otherwise lose the
                // reclassification without a word.
                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.
    ///
    /// Applying a difference that retracts everything an object said leaves the identifier
    /// behind with nothing attached, because IEC 61970-552's statement syntax has no way to
    /// say "this object is gone". Returns how many were removed.
    ///
    /// Deliberately separate from [`Dataset::apply_difference`]: a model legitimately
    /// contains objects described entirely by files that are not loaded, and silently
    /// deleting those would be worse than keeping a shell.
    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.
///
/// Both slot vectors are already sorted by [`AttrId`], so this is a merge rather than a
/// sort — and it must consider attributes the *class* does not declare, since a document
/// may set one the profile puts elsewhere.
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 same rule the CIM/XML writer applies — [`Schema::effective_profiles`] — so a change
/// set restricted to a profile holds exactly what that profile's file would.
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 {
        // A reference is written the way an instance file writes one, so a consumer that
        // reads the change set resolves it 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))
        }
        // A compound is held inline, and `rdf:parseType="Statements"` has nowhere to put
        // one. Reporting that is the only honest answer.
        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 models being *replaced* — the base — which is what lets
/// a receiver check that it is applying the change to the model it was computed against.
/// Every change set ENTSO-E publishes does this; this function used to list the target's
/// models instead, so each change set claimed to replace the state it produced.
///
/// The identifier is derived rather than random: the same pair of models must produce the
/// same change file every time, or a change set stops being comparable with the last one.
/// It depends on both sides, because two bases changed into one target are two changes.
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);

    // A model loaded from files has header identifiers and they say what it is exactly; one
    // built in memory has none, so that side falls back to what it actually contains,
    // which costs a walk of the model but only where there is no cheaper answer.
    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
}