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 not one file. It is a *set* of profile files — Equipment (EQ),
14//! Steady State Hypothesis (SSH), Topology (TP), State Variables (SV) and others — that
15//! describe the **same objects** from different angles. A `SynchronousMachine` gets its
16//! ratings from EQ and its dispatch from SSH, under one identifier.
17//!
18//! [`Dataset`] is built around that fact: loading several files merges each object's
19//! attributes rather than producing duplicates, and writing filters attributes back down
20//! to a single profile. Which file contributed a value is remembered, so a model set
21//! written back out is the file set it came from.
22//!
23//! Merging is order-independent for everything except a genuine contradiction — two files
24//! giving one single-valued attribute two different values. Resolving that means
25//! discarding one of them, so it is recorded rather than swallowed:
26//! [`Dataset::merge_conflicts`], reported by [`validate()`] as `CIM0018`.
27//!
28//! # Getting started
29//!
30//! [`Dataset::open`] is the shortest path in: it reads the vintage out of the document's own
31//! namespace declarations, so a directory, a zip archive or a single file loads without the
32//! caller knowing whether it is CGMES 3.0 or 2.4.15. Name the schema explicitly — as below —
33//! when a program only ever handles one vintage.
34//!
35// An example has to name a vintage, and a vintage is a feature — so it is written only
36// into a build that has the one it names. See `Dataset::view`.
37#![cfg_attr(
38 feature = "cgmes3",
39 doc = r#"
40```no_run
41use cim_kit::prelude::*;
42use cim_kit::cgmes3::views::ACLineSegment;
43
44# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
45// Assemble a model from its profile files. A model set is a directory in practice, so
46// [`Dataset::load_dir`] is usually the call; [`Dataset::merge`] combines datasets built
47// separately, for assembling one in parallel.
48let ds = Dataset::load(
49 cim_kit::cgmes3::SCHEMA,
50 ["model_EQ.xml", "model_SSH.xml", "model_TP.xml", "model_SV.xml"],
51)?;
52
53// Navigate it with typed views.
54for line in ds.view::<ACLineSegment>() {
55 println!("{:?}: r={:?} x={:?}", line.name(), line.r(), line.x());
56}
57
58// Check it, structurally, against the schema.
59for d in ds.validate().iter() {
60 println!("{d}");
61}
62# Ok(())
63# }
64```
65"#
66)]
67//!
68//! # Design
69//!
70//! Objects are stored **sparsely** — only attributes actually present are kept — because a
71//! `Terminal` has around thirty possible attributes and a Steady State Hypothesis file sets
72//! exactly one. Typed access comes from generated zero-cost [views](view::TypedView) rather
73//! than a struct per class, which keeps profile merging natural and compile times low.
74//!
75//! Everything model-specific is generated from the official RDFS vocabularies; everything
76//! else is written against the [`schema`] interface, so a new CIM vintage is a regeneration
77//! rather than a rewrite. Three facts about CGMES shape the I/O layer — attributes are
78//! declared far more widely than they are used, one file serves several profiles at once,
79//! and the form of a document is a property of the class within the profile. The
80//! [guide](https://hupe1980.github.io/cim-kit/docs/concepts/) explains each.
81//!
82//! # Changing a model, not resending it
83//!
84//! IEC 61970-552 defines `dm:DifferenceModel` as the incremental form of exchange: the
85//! statements to retract, then the statements to assert. [`diff`] computes one from a
86//! before and an after — [`Dataset::difference_to`] — and [`Dataset::apply_difference`]
87//! applies it. Applying a computed difference to its base reproduces the target exactly;
88//! that is a test against the published conformity models, not a claim.
89//!
90//! # Leaving for the wider RDF world
91//!
92//! CIM/XML looks like RDF/XML and is not, and it carries **no datatype information at
93//! all** — every value is element text, so `1` could be an integer, a float or a string.
94//! That is why a CGMES file cannot simply be handed to a triple store or to the SHACL
95//! shapes ENTSO-E publishes beside the RDFS.
96//!
97//! [`rdf`] closes that: it writes the model as ordinary N-Triples or Turtle with
98//! `urn:uuid:` subjects and every literal typed from the profile. The result loads in any
99//! RDF toolchain and validates against ENTSO-E's shapes as it stands.
100//!
101//! # Conformance
102//!
103//! * Serialization follows IEC 61970-552: `rdf:ID`/`rdf:about` identity, `md:FullModel`
104//! headers, `rdf:parseType="Resource"` compounds, `dm:` difference models. Both reading
105//! and writing are covered, and a model set re-exports as the files it came from.
106//! * Every document written is well-formed XML, checked over the whole published corpus
107//! with namespace resolution, duplicate-attribute detection and XML 1.0's character
108//! range — a tolerant reader accepting its own output proves nothing about anyone else's
109//! parser. Two constraints of the output syntax that the object model cannot express are
110//! enforced at the writer and reported by [`validate()`]: a value must hold only
111//! characters XML can represent (`CIM0019`), and an identifier must have an `rdf:ID` or
112//! `rdf:about` form (`CIM0020`). See [`xml`].
113//! * [`validate()`] performs the structural checks the RDFS vocabulary justifies:
114//! cardinality, value datatypes, fixed values, reference targets, profile membership,
115//! identifier form. The datatype check is not redundant with parsing — CIM/XML exchanges
116//! no type information at all, so a value's type is only decidable against the profile.
117//! Semantic rules ENTSO-E publishes as SHACL shapes are out of scope: export with
118//! [`rdf`] and run them with a SHACL engine.
119//! * Reading is tolerant by default ([`ReadOptions::lenient`]), because published models
120//! carry vendor extensions and identifier deviations. Nothing is silently dropped: every
121//! deviation becomes a [`Diagnostic`] with a stable rule code (`CIM0001`–`CIM0022`) and,
122//! from parsing, a byte offset that [`line_and_column`] turns into a line. The report
123//! grows with how broken the input is, so [`ReadOptions::max_diagnostics`] bounds it and
124//! the reader says when it stopped.
125//! * Identifiers are compared by the UUID they denote, not by how a producer spelled it.
126//! Published CGMES 2.4.15 files write `rdf:ID="_1fa19c281c8f4e1eaad9e1cab70f923e"`, and
127//! references as absolute IRIs; read as opaque text, such an object loses its
128//! `urn:uuid:` name in RDF and splits in two against a file that spells the same UUID
129//! conventionally. The spelling is remembered so re-export reproduces the document; the
130//! identity does not depend on it. See [`MridForm`].
131//! * Numbers are compared by value and written as they arrived. Published models write
132//! `2.62637E-05` and `250.000000`, and re-rendering an `f64` returns neither; [`Real`]
133//! carries the spelling beside the number, so a re-export is the file that was read and
134//! a difference never reports a reformatting as a change.
135//!
136//! # A command line
137//!
138//! The `cli` feature builds `cim`, a tool over this same API: `cim info`, `validate`,
139//! `export`, `rdf`, `diff`, `apply` and `schema` over a model set given as files, archives
140//! or directories. `cargo install cim-kit --features cli`.
141//!
142//! # Further reading
143//!
144//! This page is orientation and the rest of these docs are the reference. The **guide** —
145//! CGMES background, one page per task, and the full rule catalogue — is at
146//! <https://hupe1980.github.io/cim-kit/>.
147
148#![forbid(unsafe_code)]
149#![warn(missing_debug_implementations)]
150
151pub mod dataset;
152pub mod diff;
153pub mod error;
154pub mod header;
155pub mod load;
156pub mod mrid;
157pub mod object;
158pub mod rdf;
159pub mod reader;
160pub mod schema;
161pub mod validate;
162pub mod value;
163pub mod view;
164pub mod writer;
165pub mod xml;
166
167mod generated;
168
169/// The README's examples are compiled as doctests so the front page cannot drift from
170/// the API.
171///
172/// Gated on `cgmes3` for the same reason the site pages are: the examples name a vintage,
173/// because an example that named none would not be an example of anything. Without the
174/// gate `cargo test --no-default-features --features cgmes2` failed on the front page
175/// rather than on the code — a failure CI never saw, since the feature matrix runs
176/// `clippy --all-targets`, which does not compile doctests.
177#[cfg(all(doctest, feature = "cgmes3"))]
178#[doc = include_str!("../README.md")]
179struct ReadmeDoctests;
180
181/// The documentation site's examples, compiled for the same reason.
182///
183/// A guide whose code does not build is worse than no guide, and a guide is exactly the
184/// thing nobody re-runs. `site/` is repository machinery rather than published crate
185/// content, so this is gated on `doctest`: `cfg` stripping happens before macro expansion,
186/// which means an ordinary build — including the one `cargo package` runs to verify the
187/// tarball — never looks for the files.
188#[cfg(all(doctest, feature = "cgmes3"))]
189mod site_doctests {
190 macro_rules! page {
191 ($name:ident, $path:literal) => {
192 #[doc = include_str!($path)]
193 pub struct $name;
194 };
195 }
196 page!(GettingStarted, "../site/content/docs/getting-started.md");
197 page!(Concepts, "../site/content/docs/concepts.md");
198 page!(
199 ReadingWriting,
200 "../site/content/docs/reading-and-writing.md"
201 );
202 page!(Validation, "../site/content/docs/validation.md");
203 page!(Rdf, "../site/content/docs/rdf.md");
204 page!(
205 DifferenceModels,
206 "../site/content/docs/difference-models.md"
207 );
208 page!(Performance, "../site/content/docs/performance.md");
209 page!(Landing, "../site/content/_index.md");
210}
211
212// Re-exported so a vintage reads as `cim_kit::cgmes3`. With no vintage feature enabled the
213// module is empty and the glob imports nothing, which is the point of the feature.
214#[allow(unused_imports)]
215pub use generated::*;
216
217pub use dataset::{Dataset, InverseIndex, LinkPolicy, MergeConflict, ObjectId};
218pub use diff::{DiffOptions, DiffReport};
219pub use error::{Diagnostic, Error, Report, Result, Rule, Severity, line_and_column};
220pub use header::{
221 DifferenceModel, HeaderProperty, HeaderValue, ModelHeader, ModelKind, Statement, StatementValue,
222};
223pub use load::{LoadReport, SaveReport, instance_files};
224pub use mrid::{Mrid, MridForm};
225pub use object::{Compound, Object, Slot};
226pub use rdf::{RdfOptions, Syntax};
227pub use reader::{ReadOptions, Strictness};
228pub use schema::{AttrId, AttrKind, ClassId, Mult, Primitive, ProfileId, ProfileMask, Schema};
229pub use validate::{ValidateOptions, validate, validate_with};
230pub use value::{Real, Value};
231pub use view::{TypedRef, TypedView};
232pub use writer::{HeaderSource, IdStyle, WriteOptions};
233pub use xml::IdentifierForm;
234
235/// The imports most programs need.
236///
237/// `Result` is deliberately absent: importing an alias named `Result` would shadow
238/// `std::result::Result` in the caller's module. Use [`cim_kit::Result`](crate::Result)
239/// explicitly where you want it.
240pub mod prelude {
241 pub use crate::dataset::{Dataset, LinkPolicy, ObjectId};
242 pub use crate::error::{Diagnostic, Report, Severity};
243 pub use crate::mrid::Mrid;
244 pub use crate::object::Object;
245 pub use crate::reader::ReadOptions;
246 pub use crate::schema::{AttrId, ClassId, ProfileId};
247 pub use crate::value::Value;
248 pub use crate::view::{TypedRef, TypedView};
249 pub use crate::writer::{IdStyle, WriteOptions};
250}