cim_kit/lib.rs
1//! A Rust implementation of the IEC Common Information Model for power systems.
2//!
3//! `cim-kit` reads, navigates, validates and writes CIM grid models in both profile sets
4//! European transmission system operators use: **CGMES 3.0**
5//! (IEC TS 61970-600-1/-2:2021) and **CGMES 2.4.15**.
6//!
7//! Each vintage is a module behind a feature of the same name — [`cgmes3`] (default) and
8//! [`cgmes2`] — holding its schema tables, typed views and named constants. Identifiers
9//! are per-vintage and cannot be mixed by accident.
10//!
11//! # What this crate models
12//!
13//! A CGMES grid model is a *set* of profile files (Equipment, Steady State Hypothesis,
14//! Topology, State Variables, ...) describing the **same objects**: a `SynchronousMachine`
15//! gets its ratings from EQ and its dispatch from SSH, under one identifier.
16//!
17//! [`Dataset`] merges each object's attributes across files, remembers which file
18//! contributed what, and writes a model set back out as the file set it came from. Merging
19//! is order-independent except where two files give one single-valued attribute different
20//! values; those are kept in [`Dataset::merge_conflicts`] and reported by [`validate()`]
21//! as `CIM0018`.
22//!
23//! # Getting started
24//!
25//! [`Dataset::open`] is the shortest path in: it detects the vintage from the documents'
26//! namespaces and takes a directory, a zip archive or a single file. Name the schema
27//! explicitly, as below, when a program handles only one vintage.
28//!
29// The example names a vintage, so it is compiled only with that vintage's feature.
30#![cfg_attr(
31 feature = "cgmes3",
32 doc = r#"
33```no_run
34use cim_kit::prelude::*;
35use cim_kit::cgmes3::views::ACLineSegment;
36
37# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
38// Assemble a model from its profile files (`Dataset::load_dir` takes a directory).
39let ds = Dataset::load(
40 cim_kit::cgmes3::SCHEMA,
41 ["model_EQ.xml", "model_SSH.xml", "model_TP.xml", "model_SV.xml"],
42)?;
43
44// Navigate it with typed views.
45for line in ds.view::<ACLineSegment>() {
46 println!("{:?}: r={:?} x={:?}", line.name(), line.r(), line.x());
47}
48
49// Check it, structurally, against the schema.
50for d in ds.validate().iter() {
51 println!("{d}");
52}
53# Ok(())
54# }
55```
56"#
57)]
58//!
59//! # Design
60//!
61//! Objects are stored **sparsely** (only attributes present are kept), with typed access
62//! through generated zero-cost [views](view::TypedView) rather than a struct per class.
63//! Everything model-specific is generated from the official RDFS; everything else is
64//! written against the [`schema`] interface, so a new CIM vintage is a regeneration. The
65//! [guide](https://hupe1980.github.io/cim-kit/docs/concepts/) explains the design.
66//!
67//! # Changing a model, not resending it
68//!
69//! IEC 61970-552's `dm:DifferenceModel` is the incremental form of exchange.
70//! [`Dataset::difference_to`] ([`diff`]) computes one from a before and an after, and
71//! [`Dataset::apply_difference`] applies it; applying a computed difference to its base
72//! reproduces the target (tested against the published conformity models).
73//!
74//! # Leaving for the wider RDF world
75//!
76//! CIM/XML looks like RDF/XML and is not, and carries **no datatype information**. [`rdf`]
77//! writes N-Triples or Turtle with `urn:uuid:` subjects and every literal typed from the
78//! profile, ready for any RDF toolchain and ENTSO-E's SHACL shapes.
79//!
80//! # Conformance
81//!
82//! * Serialization follows IEC 61970-552: `rdf:ID`/`rdf:about` identity, `md:FullModel`
83//! headers, `rdf:parseType="Resource"` compounds, `dm:` difference models, for reading
84//! and writing; a model set re-exports as the files it came from.
85//! * Every document written is well-formed XML (checked over the published corpus with a
86//! strict parser). A value must hold only characters XML can represent (`CIM0019`) and
87//! an identifier must have an `rdf:ID` or `rdf:about` form (`CIM0020`); see [`xml`].
88//! * [`validate()`] performs the structural checks the RDFS justifies: cardinality, value
89//! datatypes, fixed values, reference targets, profile membership, identifier form.
90//! ENTSO-E's SHACL rules are out of scope: export with [`rdf`] and use a SHACL engine.
91//! * A read succeeds only for a whole, well-formed document — truncated input is
92//! [`Error::Truncated`], broken XML [`Error::Xml`] — and a read that fails leaves the
93//! dataset as it was.
94//! * Reading is tolerant by default ([`ReadOptions::lenient`]); every deviation becomes a
95//! [`Diagnostic`] with a stable rule code (`CIM0001`–`CIM0022`) and, from parsing, a
96//! byte offset ([`line_and_column`] turns it into a line). [`ReadOptions::max_diagnostics`]
97//! bounds the report, and [`ReadOptions::max_input_bytes`] (8 GiB by default) the input.
98//! * Identifiers are compared by the UUID they denote, not by spelling
99//! (a hyphenless `_1fa19c281c8f…` and its hyphenated form, or an absolute IRI, are one
100//! object); the spelling is kept for re-export. See [`MridForm`].
101//! * Numbers are compared by value and written as they arrived (`2.62637E-05`,
102//! `250.000000`): [`Real`] keeps the spelling beside the number.
103//!
104//! # A command line
105//!
106//! The `cli` feature builds `cim`, a tool over this same API: `cim info`, `validate`,
107//! `export`, `rdf`, `diff`, `apply` and `schema` over a model set given as files, archives
108//! or directories. `cargo install cim-kit --features cli`.
109//!
110//! # Further reading
111//!
112//! The **guide** (CGMES background, one page per task, the full rule catalogue) is at
113//! <https://hupe1980.github.io/cim-kit/>.
114
115#![forbid(unsafe_code)]
116#![warn(missing_debug_implementations)]
117
118pub mod dataset;
119pub mod diff;
120pub mod error;
121pub mod header;
122pub mod load;
123pub mod mrid;
124pub mod object;
125pub mod rdf;
126pub mod reader;
127pub mod schema;
128pub mod validate;
129pub mod value;
130pub mod view;
131pub mod writer;
132pub mod xml;
133
134mod generated;
135
136/// The README's examples, compiled as doctests. Gated on `cgmes3` because they name that
137/// vintage.
138#[cfg(all(doctest, feature = "cgmes3"))]
139#[doc = include_str!("../README.md")]
140struct ReadmeDoctests;
141
142/// The documentation site's examples, compiled for the same reason.
143///
144/// Gated on `doctest`, so an ordinary build (including `cargo package`'s) never reads them.
145#[cfg(all(doctest, feature = "cgmes3"))]
146mod site_doctests {
147 macro_rules! page {
148 ($name:ident, $path:literal) => {
149 #[doc = include_str!($path)]
150 pub struct $name;
151 };
152 }
153 page!(GettingStarted, "../site/content/docs/getting-started.md");
154 page!(Concepts, "../site/content/docs/concepts.md");
155 page!(
156 ReadingWriting,
157 "../site/content/docs/reading-and-writing.md"
158 );
159 page!(Validation, "../site/content/docs/validation.md");
160 page!(Rdf, "../site/content/docs/rdf.md");
161 page!(
162 DifferenceModels,
163 "../site/content/docs/difference-models.md"
164 );
165 page!(Performance, "../site/content/docs/performance.md");
166 page!(Landing, "../site/content/_index.md");
167}
168
169// Re-exported so a vintage reads as `cim_kit::cgmes3`; empty with no vintage feature.
170#[allow(unused_imports)]
171pub use generated::*;
172
173pub use dataset::{Dataset, InverseIndex, LinkPolicy, MergeConflict, ObjectId};
174pub use diff::{DiffOptions, DiffReport};
175pub use error::{Diagnostic, Error, Report, Result, Rule, Severity, line_and_column};
176pub use header::{
177 DifferenceModel, HeaderProperty, HeaderValue, ModelHeader, ModelKind, Statement, StatementValue,
178};
179pub use load::{LoadReport, SaveReport, instance_files};
180pub use mrid::{Mrid, MridForm};
181pub use object::{Compound, Object, Slot};
182pub use rdf::{RdfOptions, Syntax};
183pub use reader::{ReadOptions, Strictness};
184pub use schema::{AttrId, AttrKind, ClassId, Mult, Primitive, ProfileId, ProfileMask, Schema};
185pub use validate::{ValidateOptions, validate, validate_with};
186pub use value::{Real, Value};
187pub use view::{TypedRef, TypedView};
188pub use writer::{HeaderSource, IdStyle, WriteOptions};
189pub use xml::IdentifierForm;
190
191/// The imports most programs need.
192///
193/// `Result` is deliberately absent, so it does not shadow `std::result::Result`; use
194/// [`cim_kit::Result`](crate::Result) explicitly.
195pub mod prelude {
196 pub use crate::dataset::{Dataset, LinkPolicy, ObjectId};
197 pub use crate::error::{Diagnostic, Report, Severity};
198 pub use crate::mrid::Mrid;
199 pub use crate::object::Object;
200 pub use crate::reader::ReadOptions;
201 pub use crate::schema::{AttrId, ClassId, ProfileId};
202 pub use crate::value::Value;
203 pub use crate::view::{TypedRef, TypedView};
204 pub use crate::writer::{IdStyle, WriteOptions};
205}