cim-kit 0.6.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
//! Round-trip fidelity: read → write → read must preserve the model exactly.
//!
//! The guarantee tested here is *semantic*, not byte-level: a CGMES model is a set of
//! profile files, and re-exporting it legitimately redistributes objects across those
//! files. What must not change is the assembled model — the objects, their classes and
//! every attribute value.

#![cfg(feature = "cgmes3")]

mod common;

use std::collections::BTreeMap;

use cim_kit::cgmes3::SCHEMA;
use cim_kit::prelude::*;
use cim_kit::validate;

/// A comparable, order-independent projection of a dataset.
///
/// Objects are keyed by mRID and attributes by name, with values rendered to text, so
/// that differences report as readable strings rather than opaque ids.
type Projection = BTreeMap<String, (String, BTreeMap<String, Vec<String>>)>;

fn project(ds: &Dataset) -> Projection {
    let schema = ds.schema();
    let mut out = Projection::new();
    for (_, obj) in ds.iter() {
        let mut attrs: BTreeMap<String, Vec<String>> = BTreeMap::new();
        for (attr, value) in obj.values() {
            attrs
                .entry(schema.attr(attr).name.to_owned())
                .or_default()
                .push(cim_kit::value::display_value(schema, value));
        }
        for v in attrs.values_mut() {
            v.sort();
        }
        out.insert(
            obj.mrid().canonical(),
            (schema.class(obj.class()).name.to_owned(), attrs),
        );
    }
    out
}

/// Report the first few differences between two projections.
fn diff(a: &Projection, b: &Projection) -> Vec<String> {
    let mut out = Vec::new();
    for (mrid, (class, attrs)) in a {
        match b.get(mrid) {
            None => out.push(format!("missing after round-trip: {class} {mrid}")),
            Some((class_b, attrs_b)) => {
                if class != class_b {
                    out.push(format!("{mrid}: class {class} -> {class_b}"));
                }
                for (name, values) in attrs {
                    match attrs_b.get(name) {
                        None => out.push(format!("{mrid}: lost attribute {name} = {values:?}")),
                        Some(vb) if vb != values => {
                            out.push(format!("{mrid}: {name} {values:?} -> {vb:?}"))
                        }
                        _ => {}
                    }
                }
                for name in attrs_b.keys() {
                    if !attrs.contains_key(name) {
                        out.push(format!("{mrid}: gained attribute {name}"));
                    }
                }
            }
        }
    }
    for mrid in b.keys() {
        if !a.contains_key(mrid) {
            out.push(format!("appeared after round-trip: {mrid}"));
        }
    }
    out
}

/// Export every populated profile of `ds` and read the result back.
fn round_trip(ds: &Dataset) -> Dataset {
    let mut files: Vec<(cim_kit::ProfileId, Vec<u8>)> = Vec::new();
    for cov in validate::profile_coverage(ds) {
        if cov.objects == 0 {
            continue;
        }
        let mut buf = Vec::new();
        // `IdStyle::Auto`: rdf:ID or rdf:about is decided per class from the schema.
        let options = WriteOptions::default();
        cim_kit::writer::write_profile(ds, cov.profile, &mut buf, &options).unwrap();
        files.push((cov.profile, buf));
    }
    assert!(!files.is_empty(), "nothing was exported");

    let mut back = Dataset::new(ds.schema());
    for (profile, buf) in &files {
        let name = format!("{}.xml", ds.schema().profile(*profile).keyword);
        let outcome = cim_kit::reader::read_into(
            &mut back,
            buf.as_slice(),
            Some(&name),
            &ReadOptions::strict(),
        )
        .unwrap();
        assert!(
            !outcome.report.has_errors(),
            "re-reading {name} produced errors: {}",
            outcome.report
        );
    }
    back
}

fn check_model(rel: &str) {
    let dir = match common::cgmes3_model(rel) {
        Some(d) => d,
        None => {
            eprintln!("skipping {rel}: corpus not present");
            return;
        }
    };
    let files = common::xml_files(&dir);
    let mut original = Dataset::new(SCHEMA);
    original
        .load_files(&files, &ReadOptions::lenient())
        .unwrap();
    assert!(!original.is_empty(), "{rel} loaded nothing");

    let back = round_trip(&original);

    let a = project(&original);
    let b = project(&back);
    let differences = diff(&a, &b);
    if !differences.is_empty() {
        for d in differences.iter().take(20) {
            eprintln!("  {d}");
        }
        panic!(
            "{rel}: {} differences after round-trip ({} objects before, {} after)",
            differences.len(),
            original.len(),
            back.len()
        );
    }
    println!("{rel}: {} objects round-tripped exactly", original.len());
}

#[test]
fn microgrid_base_case_round_trips() {
    check_model("MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS");
}

#[test]
fn microgrid_assembled_round_trips() {
    check_model("MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged");
}

#[test]
fn minigrid_round_trips() {
    check_model("MiniGrid/MiniGrid-Merged");
}

#[test]
fn smallgrid_round_trips() {
    check_model("SmallGrid/SmallGrid-Merged");
}

#[test]
fn fullgrid_round_trips() {
    check_model("FullGrid/FullGrid-Merged");
}

#[test]
fn writing_is_deterministic() {
    let dir = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS"
    ));
    let files = common::xml_files(&dir);
    let mut ds = Dataset::new(SCHEMA);
    ds.load_files(&files, &ReadOptions::lenient()).unwrap();

    let eq = SCHEMA.profile_by_keyword("EQ").unwrap();
    let render = || {
        let mut buf = Vec::new();
        cim_kit::writer::write_profile(&ds, eq, &mut buf, &WriteOptions::default()).unwrap();
        buf
    };
    assert_eq!(
        render(),
        render(),
        "two writes of one model must be identical"
    );
}

#[test]
fn output_is_valid_xml_and_reparses_strictly() {
    let dir = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS"
    ));
    let files = common::xml_files(&dir);
    let mut ds = Dataset::new(SCHEMA);
    ds.load_files(&files, &ReadOptions::lenient()).unwrap();

    let eq = SCHEMA.profile_by_keyword("EQ").unwrap();
    let header = cim_kit::ModelHeader {
        kind: cim_kit::ModelKind::Full,
        id: Some(Mrid::parse("87da6373-3b6c-47a2-9493-1918a8d9df61")),
        created: Some("2021-03-25T23:16:27Z".into()),
        scenario_time: Some("2021-03-25T15:30:00Z".into()),
        version: Some("001".into()),
        modeling_authority_set: Some("http://tennet.nl/CGMES".into()),
        profiles: vec![SCHEMA.profile(eq).version_iri.to_owned()],
        ..Default::default()
    };
    let mut buf = Vec::new();
    cim_kit::writer::write_profile(
        &ds,
        eq,
        &mut buf,
        &WriteOptions::default().with_header(header),
    )
    .unwrap();

    let text = String::from_utf8(buf.clone()).expect("output must be UTF-8");
    assert!(text.starts_with("<?xml"), "missing XML declaration");
    assert!(text.contains("md:FullModel"), "missing header element");
    assert!(
        text.contains("Model.scenarioTime"),
        "header fields not written"
    );

    // Strict re-read proves every element we wrote is one the schema recognises.
    let mut back = Dataset::new(SCHEMA);
    let outcome = cim_kit::reader::read_into(
        &mut back,
        buf.as_slice(),
        Some("EQ.xml"),
        &ReadOptions::strict(),
    )
    .unwrap();
    assert!(!outcome.report.has_errors(), "{}", outcome.report);
    let h = outcome.header.expect("header must round-trip");
    assert_eq!(h.scenario_time.as_deref(), Some("2021-03-25T15:30:00Z"));
    assert_eq!(
        h.modeling_authority_set.as_deref(),
        Some("http://tennet.nl/CGMES")
    );
    assert_eq!(h.profiles.len(), 1);
}

/// Export as the file set the model was read from, and read that back.
fn round_trip_as_loaded(ds: &Dataset, dir: &std::path::Path) -> (Dataset, usize) {
    let saved = ds.save_as_loaded(dir).unwrap();
    assert!(
        saved.skipped.is_empty(),
        "unresolved headers: {:?}",
        saved.skipped
    );

    let mut back = Dataset::new(ds.schema());
    back.load_files(&saved.written, &ReadOptions::lenient())
        .unwrap();
    (back, saved.written.len())
}

#[test]
fn saving_as_loaded_reproduces_the_input_file_set() {
    let dir = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged"
    ));
    let files = common::xml_files(&dir);
    let mut original = Dataset::new(SCHEMA);
    original
        .load_files(&files, &ReadOptions::lenient())
        .unwrap();

    let out = std::env::temp_dir().join(format!("cim-as-loaded-{}", std::process::id()));
    std::fs::create_dir_all(&out).unwrap();
    let (back, written) = round_trip_as_loaded(&original, &out);

    // One output file per input file, not one per profile.
    assert_eq!(
        written,
        files.len(),
        "export produced {written} files from {} inputs",
        files.len()
    );

    // And the model itself is unchanged.
    let differences = diff(&project(&original), &project(&back));
    if !differences.is_empty() {
        for d in differences.iter().take(10) {
            eprintln!("  {d}");
        }
        panic!(
            "{} differences after file-set round-trip",
            differences.len()
        );
    }

    // Headers survive, including their full profile declarations.
    assert_eq!(back.headers().len(), original.headers().len());
    let profiles_of = |d: &Dataset| {
        let mut v: Vec<Vec<String>> = d.headers().iter().map(|h| h.profiles.clone()).collect();
        v.sort();
        v
    };
    assert_eq!(
        profiles_of(&original),
        profiles_of(&back),
        "header profile declarations changed"
    );

    std::fs::remove_dir_all(&out).ok();
}

#[test]
fn a_multi_profile_file_is_not_split_apart() {
    // The MicroGrid Equipment file declares both CoreEquipment and ShortCircuit. Writing
    // that profile set must produce one file containing both, and it must not duplicate
    // the Equipment content into a separate ShortCircuit file.
    let dir = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS"
    ));
    let files = common::xml_files(&dir);
    let mut ds = Dataset::new(SCHEMA);
    ds.load_files(&files, &ReadOptions::lenient()).unwrap();

    let eq = SCHEMA.profile_by_keyword("EQ").unwrap();
    let sc = SCHEMA.profile_by_keyword("SC").unwrap();

    let render = |mask| {
        let mut buf = Vec::new();
        cim_kit::writer::write_profiles(&ds, mask, &mut buf, &WriteOptions::default()).unwrap();
        buf
    };

    let eq_only = render(eq.mask());
    let sc_only = render(sc.mask());
    let both = render(eq.mask() | sc.mask());

    assert_ne!(
        eq_only, sc_only,
        "the ShortCircuit export is a copy of the Equipment export"
    );
    assert!(
        both.len() > eq_only.len() && both.len() > sc_only.len(),
        "the combined export should carry more than either alone"
    );

    // Short-circuit attributes belong to the ShortCircuit slice, not the Equipment one.
    let text = |b: &[u8]| String::from_utf8(b.to_vec()).unwrap();
    assert!(
        text(&sc_only).contains("ACLineSegment.r0"),
        "SC lost its own data"
    );
    assert!(
        !text(&eq_only).contains("ACLineSegment.r0"),
        "ShortCircuit data leaked into the Equipment export"
    );
    assert!(text(&both).contains("ACLineSegment.r0"));
    // The plain (Equipment) resistance is present alongside the zero-sequence one.
    assert!(text(&both).contains("<cim:ACLineSegment.r>"));
}

/// A model built in memory must export as documents this crate's own validator accepts.
///
/// IEC 61970-552 requires `md:FullModel rdf:about`, and a header without one was written
/// as the nil UUID — a document `validate` rejects with `CIM0013`, produced by the very
/// convenience method (`save_all_profiles`) a caller reaches for when there is no header to
/// reuse. The identifier is now derived from the model's content, which keeps the export
/// deterministic while still telling two different models apart.
#[test]
fn a_programmatic_export_writes_a_conforming_header() {
    use cim_kit::cgmes3::{attributes as attrs, classes};
    use cim_kit::object::Object;
    use cim_kit::value::Value;

    let mut ds = Dataset::new(SCHEMA);
    let mut o = Object::new(
        classes::ACLineSegment,
        Mrid::parse("11111111-1111-4111-8111-111111111111"),
    );
    o.set(
        attrs::identified_object::mRID,
        Value::Text("11111111-1111-4111-8111-111111111111".into()),
    );
    o.set(attrs::identified_object::name, Value::Text("L".into()));
    o.set(attrs::ac_line_segment::r, Value::from(1.5));
    ds.insert(o);

    let dir = std::env::temp_dir().join(format!("cim-progheader-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let written = ds.save_all_profiles(&dir, "Model").unwrap();
    assert!(!written.is_empty(), "nothing was exported");

    for path in &written {
        let text = std::fs::read_to_string(path).unwrap();
        common::assert_well_formed(&path.display().to_string(), &text);
        assert!(
            !text.contains("urn:uuid:00000000-0000-0000-0000-000000000000"),
            "{}: header identified by the nil UUID",
            path.display()
        );
        let header = cim_kit::reader::read_header(SCHEMA, text.as_bytes(), None)
            .unwrap()
            .expect("a md:FullModel header");
        let report = cim_kit::validate::validate_header(&header);
        assert_eq!(
            report.count(Severity::Error),
            0,
            "{}: {report}",
            path.display()
        );
        assert!(header.id.as_ref().is_some_and(|m| m.is_conforming()));
    }

    // Deterministic: exporting the same model again gives the same identifiers.
    let again = std::env::temp_dir().join(format!("cim-progheader2-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&again);
    let written2 = ds.save_all_profiles(&again, "Model").unwrap();
    for (a, b) in written.iter().zip(&written2) {
        assert_eq!(
            std::fs::read_to_string(a).unwrap(),
            std::fs::read_to_string(b).unwrap(),
            "exporting an unchanged model twice differed"
        );
    }

    // …and a changed model gets a different identifier.
    let before = ds.content_id();
    ds.get_mut(
        ds.find(&Mrid::parse("11111111-1111-4111-8111-111111111111"))
            .unwrap(),
    )
    .unwrap()
    .set(attrs::ac_line_segment::r, Value::from(9.0));
    assert_ne!(before, ds.content_id(), "an edited model kept its identity");

    std::fs::remove_dir_all(&dir).ok();
    std::fs::remove_dir_all(&again).ok();
}