cim-kit 0.5.1

IEC CIM/CGMES for power systems: CIM/XML I/O that reproduces the file set, profile-aware validation, typed RDF export
Documentation
//! A Rust implementation of the IEC Common Information Model for power systems.
//!
//! `cim-kit` reads, navigates, validates and writes CIM grid models in both profile sets
//! European transmission system operators use: **CGMES 3.0**
//! (IEC TS 61970-600-1/-2:2021) and **CGMES 2.4.15**.
//!
//! Each vintage is a module behind a feature of the same name — [`cgmes3`] (default) and
//! [`cgmes2`] — holding its schema tables, typed views and named constants. Identifiers
//! are per-vintage and cannot be mixed by accident.
//!
//! # What this crate models
//!
//! A CGMES grid model is a *set* of profile files (Equipment, Steady State Hypothesis,
//! Topology, State Variables, ...) describing the **same objects**: a `SynchronousMachine`
//! gets its ratings from EQ and its dispatch from SSH, under one identifier.
//!
//! [`Dataset`] merges each object's attributes across files, remembers which file
//! contributed what, and writes a model set back out as the file set it came from. Merging
//! is order-independent except where two files give one single-valued attribute different
//! values; those are kept in [`Dataset::merge_conflicts`] and reported by [`validate()`]
//! as `CIM0018`.
//!
//! # Getting started
//!
//! [`Dataset::open`] is the shortest path in: it detects the vintage from the documents'
//! namespaces and takes a directory, a zip archive or a single file. Name the schema
//! explicitly, as below, when a program handles only one vintage.
//!
// The example names a vintage, so it is compiled only with that vintage's feature.
#![cfg_attr(
    feature = "cgmes3",
    doc = r#"
```no_run
use cim_kit::prelude::*;
use cim_kit::cgmes3::views::ACLineSegment;

# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
// Assemble a model from its profile files (`Dataset::load_dir` takes a directory).
let ds = Dataset::load(
    cim_kit::cgmes3::SCHEMA,
    ["model_EQ.xml", "model_SSH.xml", "model_TP.xml", "model_SV.xml"],
)?;

// Navigate it with typed views.
for line in ds.view::<ACLineSegment>() {
    println!("{:?}: r={:?} x={:?}", line.name(), line.r(), line.x());
}

// Check it, structurally, against the schema.
for d in ds.validate().iter() {
    println!("{d}");
}
# Ok(())
# }
```
"#
)]
//!
//! # Design
//!
//! Objects are stored **sparsely** (only attributes present are kept), with typed access
//! through generated zero-cost [views](view::TypedView) rather than a struct per class.
//! Everything model-specific is generated from the official RDFS; everything else is
//! written against the [`schema`] interface, so a new CIM vintage is a regeneration. The
//! [guide](https://hupe1980.github.io/cim-kit/docs/concepts/) explains the design.
//!
//! # Changing a model, not resending it
//!
//! IEC 61970-552's `dm:DifferenceModel` is the incremental form of exchange.
//! [`Dataset::difference_to`] ([`diff`]) computes one from a before and an after, and
//! [`Dataset::apply_difference`] applies it; applying a computed difference to its base
//! reproduces the target (tested against the published conformity models).
//!
//! # Leaving for the wider RDF world
//!
//! CIM/XML looks like RDF/XML and is not, and carries **no datatype information**. [`rdf`]
//! writes N-Triples or Turtle with `urn:uuid:` subjects and every literal typed from the
//! profile, ready for any RDF toolchain and ENTSO-E's SHACL shapes.
//!
//! # Conformance
//!
//! * Serialization follows IEC 61970-552: `rdf:ID`/`rdf:about` identity, `md:FullModel`
//!   headers, `rdf:parseType="Resource"` compounds, `dm:` difference models, for reading
//!   and writing; a model set re-exports as the files it came from.
//! * Every document written is well-formed XML (checked over the published corpus with a
//!   strict parser). A value must hold only characters XML can represent (`CIM0019`) and
//!   an identifier must have an `rdf:ID` or `rdf:about` form (`CIM0020`); see [`xml`].
//! * [`validate()`] performs the structural checks the RDFS justifies: cardinality, value
//!   datatypes, fixed values, reference targets, profile membership, identifier form.
//!   ENTSO-E's SHACL rules are out of scope: export with [`rdf`] and use a SHACL engine.
//! * A read succeeds only for a whole, well-formed document — truncated input is
//!   [`Error::Truncated`], broken XML [`Error::Xml`] — and a read that fails leaves the
//!   dataset as it was.
//! * Reading is tolerant by default ([`ReadOptions::lenient`]); every deviation becomes a
//!   [`Diagnostic`] with a stable rule code (`CIM0001`–`CIM0022`) and, from parsing, a
//!   byte offset ([`line_and_column`] turns it into a line). [`ReadOptions::max_diagnostics`]
//!   bounds the report, and [`ReadOptions::max_input_bytes`] (8 GiB by default) the input.
//! * Identifiers are compared by the UUID they denote, not by spelling
//!   (a hyphenless `_1fa19c281c8f…` and its hyphenated form, or an absolute IRI, are one
//!   object); the spelling is kept for re-export. See [`MridForm`].
//! * Numbers are compared by value and written as they arrived (`2.62637E-05`,
//!   `250.000000`): [`Real`] keeps the spelling beside the number.
//!
//! # A command line
//!
//! The `cli` feature builds `cim`, a tool over this same API: `cim info`, `validate`,
//! `export`, `rdf`, `diff`, `apply` and `schema` over a model set given as files, archives
//! or directories. `cargo install cim-kit --features cli`.
//!
//! # Further reading
//!
//! The **guide** (CGMES background, one page per task, the full rule catalogue) is at
//! <https://hupe1980.github.io/cim-kit/>.

#![forbid(unsafe_code)]
#![warn(missing_debug_implementations)]

pub mod dataset;
pub mod diff;
pub mod error;
pub mod header;
pub mod load;
pub mod mrid;
pub mod object;
pub mod rdf;
pub mod reader;
pub mod schema;
pub mod validate;
pub mod value;
pub mod view;
pub mod writer;
pub mod xml;

mod generated;

/// The README's examples, compiled as doctests. Gated on `cgmes3` because they name that
/// vintage.
#[cfg(all(doctest, feature = "cgmes3"))]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;

/// The documentation site's examples, compiled for the same reason.
///
/// Gated on `doctest`, so an ordinary build (including `cargo package`'s) never reads them.
#[cfg(all(doctest, feature = "cgmes3"))]
mod site_doctests {
    macro_rules! page {
        ($name:ident, $path:literal) => {
            #[doc = include_str!($path)]
            pub struct $name;
        };
    }
    page!(GettingStarted, "../site/content/docs/getting-started.md");
    page!(Concepts, "../site/content/docs/concepts.md");
    page!(
        ReadingWriting,
        "../site/content/docs/reading-and-writing.md"
    );
    page!(Validation, "../site/content/docs/validation.md");
    page!(Rdf, "../site/content/docs/rdf.md");
    page!(
        DifferenceModels,
        "../site/content/docs/difference-models.md"
    );
    page!(Performance, "../site/content/docs/performance.md");
    page!(Landing, "../site/content/_index.md");
}

// Re-exported so a vintage reads as `cim_kit::cgmes3`; empty with no vintage feature.
#[allow(unused_imports)]
pub use generated::*;

pub use dataset::{Dataset, InverseIndex, LinkPolicy, MergeConflict, ObjectId};
pub use diff::{DiffOptions, DiffReport};
pub use error::{Diagnostic, Error, Report, Result, Rule, Severity, line_and_column};
pub use header::{
    DifferenceModel, HeaderProperty, HeaderValue, ModelHeader, ModelKind, Statement, StatementValue,
};
pub use load::{LoadReport, SaveReport, instance_files};
pub use mrid::{Mrid, MridForm};
pub use object::{Compound, Object, Slot};
pub use rdf::{RdfOptions, Syntax};
pub use reader::{ReadOptions, Strictness};
pub use schema::{AttrId, AttrKind, ClassId, Mult, Primitive, ProfileId, ProfileMask, Schema};
pub use validate::{ValidateOptions, validate, validate_with};
pub use value::{Real, Value};
pub use view::{TypedRef, TypedView};
pub use writer::{HeaderSource, IdStyle, WriteOptions};
pub use xml::IdentifierForm;

/// The imports most programs need.
///
/// `Result` is deliberately absent, so it does not shadow `std::result::Result`; use
/// [`cim_kit::Result`](crate::Result) explicitly.
pub mod prelude {
    pub use crate::dataset::{Dataset, LinkPolicy, ObjectId};
    pub use crate::error::{Diagnostic, Report, Severity};
    pub use crate::mrid::Mrid;
    pub use crate::object::Object;
    pub use crate::reader::ReadOptions;
    pub use crate::schema::{AttrId, ClassId, ProfileId};
    pub use crate::value::Value;
    pub use crate::view::{TypedRef, TypedView};
    pub use crate::writer::{IdStyle, WriteOptions};
}