Skip to main content

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//! * Reading is tolerant by default ([`ReadOptions::lenient`]); every deviation becomes a
92//!   [`Diagnostic`] with a stable rule code (`CIM0001`–`CIM0022`) and, from parsing, a
93//!   byte offset ([`line_and_column`] turns it into a line). [`ReadOptions::max_diagnostics`]
94//!   bounds the report, and [`ReadOptions::max_input_bytes`] (2 GiB by default) the input.
95//! * Identifiers are compared by the UUID they denote, not by spelling
96//!   (a hyphenless `_1fa19c281c8f…` and its hyphenated form, or an absolute IRI, are one
97//!   object); the spelling is kept for re-export. See [`MridForm`].
98//! * Numbers are compared by value and written as they arrived (`2.62637E-05`,
99//!   `250.000000`): [`Real`] keeps the spelling beside the number.
100//!
101//! # A command line
102//!
103//! The `cli` feature builds `cim`, a tool over this same API: `cim info`, `validate`,
104//! `export`, `rdf`, `diff`, `apply` and `schema` over a model set given as files, archives
105//! or directories. `cargo install cim-kit --features cli`.
106//!
107//! # Further reading
108//!
109//! The **guide** (CGMES background, one page per task, the full rule catalogue) is at
110//! <https://hupe1980.github.io/cim-kit/>.
111
112#![forbid(unsafe_code)]
113#![warn(missing_debug_implementations)]
114
115pub mod dataset;
116pub mod diff;
117pub mod error;
118pub mod header;
119pub mod load;
120pub mod mrid;
121pub mod object;
122pub mod rdf;
123pub mod reader;
124pub mod schema;
125pub mod validate;
126pub mod value;
127pub mod view;
128pub mod writer;
129pub mod xml;
130
131mod generated;
132
133/// The README's examples, compiled as doctests. Gated on `cgmes3` because they name that
134/// vintage.
135#[cfg(all(doctest, feature = "cgmes3"))]
136#[doc = include_str!("../README.md")]
137struct ReadmeDoctests;
138
139/// The documentation site's examples, compiled for the same reason.
140///
141/// Gated on `doctest`, so an ordinary build (including `cargo package`'s) never reads them.
142#[cfg(all(doctest, feature = "cgmes3"))]
143mod site_doctests {
144    macro_rules! page {
145        ($name:ident, $path:literal) => {
146            #[doc = include_str!($path)]
147            pub struct $name;
148        };
149    }
150    page!(GettingStarted, "../site/content/docs/getting-started.md");
151    page!(Concepts, "../site/content/docs/concepts.md");
152    page!(
153        ReadingWriting,
154        "../site/content/docs/reading-and-writing.md"
155    );
156    page!(Validation, "../site/content/docs/validation.md");
157    page!(Rdf, "../site/content/docs/rdf.md");
158    page!(
159        DifferenceModels,
160        "../site/content/docs/difference-models.md"
161    );
162    page!(Performance, "../site/content/docs/performance.md");
163    page!(Landing, "../site/content/_index.md");
164}
165
166// Re-exported so a vintage reads as `cim_kit::cgmes3`; empty with no vintage feature.
167#[allow(unused_imports)]
168pub use generated::*;
169
170pub use dataset::{Dataset, InverseIndex, LinkPolicy, MergeConflict, ObjectId};
171pub use diff::{DiffOptions, DiffReport};
172pub use error::{Diagnostic, Error, Report, Result, Rule, Severity, line_and_column};
173pub use header::{
174    DifferenceModel, HeaderProperty, HeaderValue, ModelHeader, ModelKind, Statement, StatementValue,
175};
176pub use load::{LoadReport, SaveReport, instance_files};
177pub use mrid::{Mrid, MridForm};
178pub use object::{Compound, Object, Slot};
179pub use rdf::{RdfOptions, Syntax};
180pub use reader::{ReadOptions, Strictness};
181pub use schema::{AttrId, AttrKind, ClassId, Mult, Primitive, ProfileId, ProfileMask, Schema};
182pub use validate::{ValidateOptions, validate, validate_with};
183pub use value::{Real, Value};
184pub use view::{TypedRef, TypedView};
185pub use writer::{HeaderSource, IdStyle, WriteOptions};
186pub use xml::IdentifierForm;
187
188/// The imports most programs need.
189///
190/// `Result` is deliberately absent, so it does not shadow `std::result::Result`; use
191/// [`cim_kit::Result`](crate::Result) explicitly.
192pub mod prelude {
193    pub use crate::dataset::{Dataset, LinkPolicy, ObjectId};
194    pub use crate::error::{Diagnostic, Report, Severity};
195    pub use crate::mrid::Mrid;
196    pub use crate::object::Object;
197    pub use crate::reader::ReadOptions;
198    pub use crate::schema::{AttrId, ClassId, ProfileId};
199    pub use crate::value::Value;
200    pub use crate::view::{TypedRef, TypedView};
201    pub use crate::writer::{IdStyle, WriteOptions};
202}