Reading and writing

Reading CIM/XML with cim-kit: lenient and strict modes, structured diagnostics, zip archives, and writing a model back as the file set it came from.

Reading#

The reader is a streaming pull parser over the IEC 61970-552 subset of RDF/XML; it never buffers the document. A read succeeds only for a whole, well-formed document, and only then touches the dataset: a read that fails changes nothing.

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

fn main() -> cim_kit::Result<()> {
    let mut grid = Dataset::new(SCHEMA);
    let load = grid.load_files(["EQ.xml", "SSH.xml"], &ReadOptions::lenient())?;

    // Deviations become structured diagnostics; nothing is dropped silently.
    for d in load.report.iter() {
        // warning[CIM0002] EQ.xml@8213: unknown property <cim:Vendor.x>, skipped
        println!("{d}");
    }
    Ok(())
}

Lenient and strict#

ReadOptions::lenient() (the default) reports deviations and continues; ReadOptions::strict() makes anything the schema does not define a hard error. Neither tolerates broken XML. Lenient reading tolerates:

DeviationWhat happens
A UUID written without hyphensKeeps its identity and its spelling; flagged CIM0004
A non-UUID identifierKept verbatim; flagged CIM0004
An rdf:ID that is not an XML name — rdf:ID="7d06…", no underscoreRepaired on write; flagged CIM0004 always, since the output differs from the input
A reference written as an absolute IRIResolves to the UUID in its fragment
An enumeration literal under the wrong namespaceRecovered by qualified name; flagged CIM0003
An unparseable valueDropped, object kept; flagged CIM0003
A comma that could be a decimal mark or a thousands separatorRefused rather than guessed at
An unknown class or propertySkipped; flagged CIM0001 / CIM0002
Markup nested inside a valueSkipped with its content; the value stays its own element's text
A single-valued property given twice in one elementThe later value is kept; CIM0018 error if they differ, CIM0008 warning if equal
One object described twice in a document (rdf:ID, then rdf:about)Combined into one object; a value given by both is checked as above, with both positions. Defined twice with rdf:ID, or under unrelated classes: CIM0005
An entity other than the five XML predefines, in text or in an attributeKept as text and flagged CIM0003 — never expanded, never fetched

An exchange that carries one self-contained FullModel can ask for each object to be described once per document: with_single_description(true) (--single-description) reports every second description as CIM0005, related to the first.

Limits#

The report grows with how broken the input is, so it is capped: 10,000 diagnostics by default. Past the cap the reader keeps reading, stops recording, and ends the report with a line saying so.

The bytes a load accepts are capped too: 8 GiB per load call by default, counting what the parser receives — for a zip archive, its decompressed entries — across every file and entry of the call, whatever sizes an archive declares for itself.

use cim_kit::prelude::*;

fn options() -> ReadOptions {
    ReadOptions::lenient()
        .with_max_diagnostics(100)
        .with_max_input_bytes(8 << 30) // 0 for no limit
}

Past the input budget the load fails with Error::InputTooLarge, naming the budget, the bytes read and the file it stopped in. It is never downgraded to a finding, even under lenient reading; discard the dataset.

Diagnostics#

use cim_kit::prelude::*;

fn describe(report: &cim_kit::Report) {
    for d in report.iter() {
        // `object` is an `Mrid` and `attribute` the schema's own name, not rendered text.
        println!("{} {:?} {:?} {:?}", d.rule, d.severity, d.object, d.attribute);
        if let (Some(source), Some(at)) = (&d.source, d.position) {
            println!("  {source} at byte {at}");
        }
    }
}

position is the byte offset of the element's <, not a line number; cim_kit::line_and_column(&text, offset) converts it. A finding about a repeat also has related_position, the first occurrence:

error[CIM0018] EQ.xml@236: ACLineSegment.r is given twice: 1 at byte 187, then 2; the later is kept

Broken documents#

InputError
Ends with an element open, or inside a tag — an interrupted transferError::Truncated, naming the innermost open element
An end tag that does not match, a second document element, text outside it, a bare &Error::Xml
A prefix not declared on the element or an ancestor, or a declaration Namespaces in XML forbids (xmlns:p="", rebinding xml)Error::Xml

Both carry source and position (also Error::position()), under either strictness.

Unreadable files#

Under lenient reading a file or archive entry that cannot be read — broken XML, truncated, an archive that will not open — is reported as CIM0022 with its name and position, listed in LoadReport::failed, contributes nothing, and the rest of the set is read. --strict refuses instead. Vintage detection asks each input in turn.

$ cim validate broken-set/
  error[CIM0022] 20210125T1900Z_1D_ELIA_EQ_001.xml@109115: malformed XML: expected `</cim:ConformLoadGroup>`, but `</rdf:RDF>` was found
  warning[CIM0014] 20210125T1900Z_1D_ELIA_SSH_001.xml: model depends on 359ea4dd-… which was not loaded
  …

Zip archives#

With the zip feature, an archive is just another input:

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

fn main() -> cim_kit::Result<()> {
    let grid = Dataset::load(SCHEMA, ["MicroGrid_BE_v2.zip"])?;
    println!("{} objects", grid.len());
    Ok(())
}

cim_kit::instance_files(path) walks a directory (or returns a single file), keeping the inputs that look like CIM, sorted so a load is reproducible.

Headers#

Each instance file's md:FullModel header declares its profiles and dependencies:

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

fn main() -> cim_kit::Result<()> {
    let grid = Dataset::load_dir(SCHEMA, "MicroGrid-BE")?;
    for header in grid.headers() {
        println!("{:?} {:?} {:?}", header.source, header.profiles, header.scenario_time);
    }

    // Or read only the headers, to decide what to load.
    let plan = Dataset::peek_headers(SCHEMA, ["EQ.xml", "SSH.xml"])?;
    println!("{} file(s) inspected", plan.len());
    Ok(())
}

Header properties outside the md: vocabulary (DCAT terms, vendor extensions) round-trip with their original prefix, namespace and value form.

Writing#

Output is deterministic: objects in mRID order, attributes in schema order. Re-writing an unchanged model is byte-identical.

Writing a model back#

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

fn main() -> cim_kit::Result<()> {
    let grid = Dataset::load_dir(SCHEMA, "MicroGrid-BE")?;
    let dir = std::path::Path::new("out");

    // As the file set it was read from, headers included.
    let saved = grid.save_as_loaded(dir)?;
    println!("{} file(s) written", saved.written.len());

    // Or one file per profile, for a model built programmatically.
    let written = grid.save_all_profiles(dir, "MyModel")?;
    println!("{} profile file(s)", written.len());
    Ok(())
}

save_as_loaded writes one file per loaded header, with that header, its declared profiles and every object whose element appeared in that document — so a merged model's files keep their own authority's objects, and boundary sets come back as they were.

A document with no md:FullModel declares no profile: its header is skipped, and objects that came only from it are counted in SaveReport::unwritten. cim export then writes one file per profile and says so on stderr; --assume-profile names the profile instead:

cim export headerless/ --out out/                      # one file per profile, with a note
cim export headerless/ --assume-profile EQ --out out/  # the file, as itself

The form of the document#

Both rules are read from the vocabulary:

  • Element class. A file names only classes its own profiles declare and whose mandatory attributes the data supplies — an SSH file writes <cim:Equipment rdf:about="…"> for an ACLineSegment.
  • rdf:ID or rdf:about, per class per profile (see Concepts): a class the file's profiles define gets rdf:ID; one they mention but do not define gets rdf:about; one they do not mention gets rdf:ID.
use cim_kit::cgmes3::{SCHEMA, classes};

fn how_is_a_terminal_identified_in_ssh() -> cim_kit::writer::IdStyle {
    let ssh = SCHEMA.profile_by_keyword("SSH").expect("the SSH profile");
    cim_kit::writer::id_style_for(SCHEMA, classes::Terminal, ssh.mask())
}

Every document the writer produces is well-formed XML with correct namespaces.

Values keep their spelling#

A Real keeps its number and the spelling it was read with (2.62637E-05, 250.000000), and writes the spelling back. Equality compares numbers, so a reformatting is never a change and Dataset::content_id() is unaffected.

# use cim_kit::value::Value;
# use cim_kit::schema::Primitive;
let read = Value::parse_primitive(Primitive::Float, "250.000000")?;

assert_eq!(read.as_f64(), Some(250.0));                       // the number
assert_eq!(read.to_lexical().as_deref(), Some("250.000000")); // as the document wrote it
assert_eq!(read, Value::from(250.0));                         // and equal to the number
# Ok::<(), cim_kit::value::ParseValueError>(())

Only conforming lexical forms are kept; tolerated deviations such as 1,5 or 1.5D+3 are written in canonical form. Values set programmatically render canonically.

Models built in memory#

A model without a header gets an md:FullModel by default, declaring the profiles written and identified by a version-5 UUID derived from Dataset::content_id() — the same model always yields the same document. WriteOptions::header is a HeaderSource: supply your own with WriteOptions::with_header, or omit it with WriteOptions::headerless (the result is then not a conforming instance file). The build_model example shows the full write path.