Skip to main content

Dataset

Struct Dataset 

Source
pub struct Dataset { /* private fields */ }
Expand description

A set of CIM objects together with the headers of the files that produced them.

A dataset is the unit of real-world exchange: CGMES splits one grid model across several profile files (EQ, SSH, TP, SV, …) that describe the same objects. Loading them into one dataset merges each object’s attributes across profiles.

Implementations§

Source§

impl Dataset

Source

pub const MAX_CONFLICTS: usize = 1000

How many merge conflicts are retained before only their number is kept.

A model set assembled from mismatched files can disagree about every object; the cap keeps that from turning into memory proportional to the model.

Source

pub const DERIVED_NS: Mrid

The namespace under which this crate derives identifiers.

A fixed version-4 UUID, so that a derived mRID cannot collide with one derived for a different purpose, here or anywhere else.

Source

pub fn new(schema: &'static Schema) -> Dataset

Source

pub fn schema(&self) -> &'static Schema

Source

pub fn headers(&self) -> &[ModelHeader]

Headers of every file loaded into this dataset, in load order.

Source

pub fn push_header(&mut self, header: ModelHeader) -> usize

Register a file’s header and return the source slot its objects belong to.

The reader calls this before storing a file’s objects, so each object is recorded against the file it came from and an export can reproduce that file set.

Source

pub fn set_header(&mut self, index: usize, header: ModelHeader)

Replace the header in slot index, keeping the objects already recorded against it.

A document that names itself only after its first object — legal XML, and not what IEC 61970-552’s layout suggests — claims a slot before its md:FullModel is read. Pushing the real header afterwards would leave the file described twice and its objects attached to the placeholder.

Source

pub fn record_source(&mut self, source: usize, id: ObjectId)

Record that the file in header slot source contained id.

Source

pub fn objects_from(&self, source: usize) -> impl Iterator<Item = ObjectId> + '_

Objects the file in header slot source contributed, in the order it listed them.

Profile provenance alone cannot say which file a value came from, and in a merged common grid model that matters: two modelling authorities each contribute an Equipment file, and writing the model back must put each authority’s equipment in its own file rather than the union in both.

Objects since removed with Dataset::remove are skipped. The index is not rebuilt on removal — an object appears in as many files as there are profiles describing it, so cleaning it out would mean either a per-object source set or a scan of every file’s list — so the liveness check happens here instead, where it costs one lookup per entry and cannot be forgotten by a caller.

Source

pub fn differences(&self) -> &[DifferenceModel]

Difference models read into this dataset, in load order.

A difference is not applied on load — Dataset::apply_difference does that — but it is kept so that a model set containing change files can be written back whole.

Source

pub fn model_ids(&self) -> impl Iterator<Item = &Mrid> + '_

The model states this dataset holds now: its headers’ identifiers, less every model an applied change set superseded, plus the change sets applied. A difference file merely read as part of a model set is not among them — it has not been applied — and neither is a model a change set has replaced, which is why a second variant computed against the same base is refused after the first.

Source

pub fn push_difference(&mut self, diff: DifferenceModel)

Source

pub fn profiles(&self) -> ProfileMask

Profiles present across all loaded headers.

Source

pub fn len(&self) -> usize

Number of live objects.

Source

pub fn is_empty(&self) -> bool

Source

pub fn get(&self, id: ObjectId) -> Option<&Object>

Source

pub fn get_mut(&mut self, id: ObjectId) -> Option<&mut Object>

Source

pub fn find(&self, mrid: &Mrid) -> Option<ObjectId>

Source

pub fn by_mrid(&self, mrid: &Mrid) -> Option<&Object>

Source

pub fn insert(&mut self, object: Object) -> ObjectId

Insert an object, or merge into the existing one with the same mRID.

Merging is what makes multi-profile assembly work: when an SSH file describes an object already known from EQ, its attributes are added rather than replacing the object. A more specific class wins, since profiles may describe the same object through a base class.

Source

pub fn merge(&mut self, other: Dataset) -> Result<()>

Absorb another dataset: its objects, its file headers, which file each object came from, and any change files it carries.

The point is assembly that is not sequential. load_files reads one document after another into one dataset because the merge has to happen somewhere, but reading is the expensive half and it is embarrassingly parallel — a model set is a handful of independent files. With this, each can be parsed into its own dataset on its own thread and the results combined afterwards, and the outcome is the same model: merging by mRID is what makes multi-profile assembly work, and it does not care which dataset an object arrived in.

let mut model = Dataset::new(SCHEMA);
for part in ["EQ.xml", "SSH.xml", "TP.xml", "SV.xml"]
    .map(|f| Dataset::load(SCHEMA, [f]))
{
    model.merge(part?)?;
}

One order-dependence survives, and it is the same one load_files has: where two files give a single-valued attribute two different values, the later merge wins and the discarded reading is recorded as a MergeConflict. Conflicts other recorded on its own are carried over rather than lost.

Fails if the two datasets were built from different schema vintages, because their AttrIds index different tables.

Source

pub fn merge_conflicts(&self) -> &[MergeConflict]

Single-valued attributes two loaded files gave different values for.

Empty for a consistent model set. A non-empty result means the model this dataset holds is not the union of its files: for each entry, one file’s value was discarded. validate turns these into Rule::ConflictingValue diagnostics.

Source

pub fn merge_conflicts_dropped(&self) -> usize

Conflicts that occurred beyond Dataset::MAX_CONFLICTS and were only counted.

Source

pub fn reclassify(&mut self, id: ObjectId, class: ClassId) -> Vec<Slot>

Change an object’s class, keeping the per-class index consistent, and return any values the new class cannot carry.

Used when a difference model reclassifies an object — IEC 61970-552 treats an object’s type as a statement like any other, and the published conformity change sets replace a LinearShuntCompensator with a NonlinearShuntCompensator under one identifier.

Values are shed, not kept. Narrowing to a subclass sheds nothing, because a subclass has every attribute its parent has. Moving sideways does: LinearShuntCompensator.bPerSection has no meaning on a NonlinearShuntCompensator and no place in one’s instance file. Keeping such a value looks harmless and is not — nothing afterwards would ever look at it, because the writer emits a class’s own attributes and validation checks a class’s own attributes, so it would vanish without a word on the next export. Handing it back makes the loss the caller’s to report, which is what Dataset::apply_difference does.

Source

pub fn remove(&mut self, id: ObjectId) -> Option<Object>

Remove an object. Its ObjectId is never reused.

Source

pub fn iter(&self) -> impl Iterator<Item = (ObjectId, &Object)> + '_

Every live object.

Source

pub fn iter_exact( &self, class: ClassId, ) -> impl Iterator<Item = (ObjectId, &Object)> + '_

Objects of exactly class, excluding subclasses.

Source

pub fn iter_class( &self, class: ClassId, ) -> impl Iterator<Item = (ObjectId, &Object)> + '_

Objects of class or any subclass — usually what callers want.

Walks the per-class buckets of class and its descendants rather than scanning the dataset, so asking for every ACLineSegment costs their number rather than the model’s. Order is unspecified but stable for a given load.

Source

pub fn count_class(&self, class: ClassId) -> usize

Source

pub fn follow(&self, object: &Object, attr: AttrId) -> Option<&Object>

Resolve a single-valued association to the referenced object.

Source

pub fn follow_all<'a>( &'a self, object: &'a Object, attr: AttrId, ) -> impl Iterator<Item = &'a Object> + 'a

Resolve every value of a many-valued association.

References that do not resolve are skipped; use validate to report them.

Source

pub fn referrers<'a>( &'a self, target: &'a Mrid, attr: AttrId, ) -> impl Iterator<Item = (ObjectId, &'a Object)> + 'a

Objects whose association attr points at target.

This walks the inverse of a stored association. Inverse roles are deliberately not stored on both sides — IEC 61970-501 marks exactly one side of each association as serialized — so this is computed. Build an InverseIndex when querying repeatedly.

Source

pub fn content_id(&self) -> Mrid

A UUID that identifies what this model contains.

Exporting a model needs a md:FullModel rdf:about, and a model built programmatically has none. A random one would make every export of an unchanged model differ from the last, which defeats a deterministic writer; a fixed one would give two unrelated models the same identifier, which is worse. Deriving it from the content gives both properties: unchanged model, unchanged identifier; changed model, changed identifier.

The fingerprint covers the vintage and, for every object in mRID order, its identifier, its class and every stored value. What it deliberately does not cover is anything about the files — headers, per-file provenance, load order — because two ways of packaging one model are still that model.

It is not a cryptographic commitment and is not offered as one: it is derived with SHA-1, which is broken for collision resistance, and identifies a model against accident rather than against an adversary.

Source

pub fn shrink_to_fit(&mut self)

Release unused capacity after bulk loading.

Source

pub fn dangling_references(&self) -> Vec<(ObjectId, AttrId, Mrid)>

References that point at objects not present in the dataset.

Fail if the link policy is LinkPolicy::Strict and references are unresolved.

Source§

impl Dataset

Source

pub fn validate(&self) -> Report

Validate with the default checks.

Shorthand for validate::validate.

Source

pub fn validate_with(&self, options: &ValidateOptions) -> Report

Validate with explicit options.

Source§

impl Dataset

Source

pub fn difference_to( &self, target: &Dataset, options: &DiffOptions, ) -> DiffReport

The change set that turns this model into target.

See the module documentation for what the result guarantees and for the two things a statement-level difference cannot express.

Source

pub fn prune_empty(&mut self) -> usize

Remove objects that carry no values at all.

Applying a difference that retracts everything an object said leaves the identifier behind with nothing attached, because IEC 61970-552’s statement syntax has no way to say “this object is gone”. Returns how many were removed.

Deliberately separate from Dataset::apply_difference: a model legitimately contains objects described entirely by files that are not loaded, and silently deleting those would be worse than keeping a shell.

Source§

impl Dataset

Source

pub fn load<I, P>(schema: &'static Schema, paths: I) -> Result<Dataset>
where I: IntoIterator<Item = P>, P: AsRef<Path>,

Load a set of instance files into a new dataset.

Files may be given in any order: objects are merged by mRID, so an SSH file read before its EQ file produces the same result.

Source

pub fn load_files<I, P>( &mut self, paths: I, options: &ReadOptions, ) -> Result<LoadReport>
where I: IntoIterator<Item = P>, P: AsRef<Path>,

Load files into an existing dataset.

The files share one input budget (ReadOptions::max_input_bytes): a model set is one load, however many files and archive entries it arrives as.

§Errors

Error::InputTooLarge under either strictness once the budget is spent — the dataset then holds part of the model and must be discarded. Under Strictness::Strict, the first file that cannot be read.

Source

pub fn load_file( &mut self, path: &Path, options: &ReadOptions, ) -> Result<LoadReport>

Load one instance file, or every instance file inside a zip archive.

Source

pub fn load_dir( schema: &'static Schema, dir: impl AsRef<Path>, ) -> Result<Dataset>

Load every instance file under a directory, in sorted order.

A CGMES model set is a directory, not a list — that is how the conformity models, the QoCDC models and every real exchange are shipped — so this is the call most programs actually want. Naming the files individually is Dataset::load.

Source

pub fn open(path: impl AsRef<Path>) -> Result<Dataset>

Load a model set, reading its vintage out of the files themselves.

The call most programs want. path is a directory, a zip archive or a single instance file; the schema comes from the first document’s namespace declarations, so the caller does not have to know — or hard-code — whether a model is CGMES 3.0 or 2.4.15.

Use Dataset::load_dir or Dataset::load to state the vintage explicitly, which is what a program that only ever handles one of them should do.

§Errors

Error::UnknownVintage when no file under path declares a vocabulary this build has a feature for — including when path holds no CIM input at all.

let grid = cim_kit::Dataset::open("MicroGrid-BE")?;
println!("{} objects", grid.len());
Source

pub fn peek_headers<I, P>( schema: &'static Schema, paths: I, ) -> Result<Vec<(PathBuf, Option<ModelHeader>)>>
where I: IntoIterator<Item = P>, P: AsRef<Path>,

Read only the headers of a set of files, without loading their objects.

Useful for deciding what to load: headers declare profiles and dependencies.

Source

pub fn apply_difference(&mut self, diff: &DifferenceModel) -> Report

Apply a difference model (IEC 61970-552): check it applies to this model, remove reverse statements, then assert forward statements.

A change set is a statement about one model state, so it is refused — the report holds one CIM0014 error and the dataset is left unchanged — when a model its md:Model.Supersedes names is neither loaded here nor an earlier change set applied here (compared as identifiers, so spelling does not matter), or when one of its dm:preconditions does not hold. A dataset with no header identifiers, or a change set naming no base, has nothing to compare and is not checked. A caller who knows better clears diff.header.supersedes or diff.preconditions.

Past that gate, statements naming objects or properties the schema does not know are reported and skipped rather than aborting the whole application, and a retraction that does not hold is a warning: published change sets reconcile files that disagree, so it is evidence rather than grounds to refuse.

Source

pub fn save_profile( &self, path: &Path, profile: ProfileId, header: Option<ModelHeader>, ) -> Result<()>

Write one profile of this dataset to a file.

Source

pub fn save_all_profiles(&self, dir: &Path, stem: &str) -> Result<Vec<PathBuf>>

Write every profile the dataset carries data for, into dir, one file each.

Files are named <stem>_<KEYWORD>.xml. Use Dataset::save_as_loaded instead when the goal is to reproduce the file set the model was read from.

Source

pub fn save_as_loaded(&self, dir: &Path) -> Result<SaveReport>

Write the model back out as the file set it was read from.

One output file per loaded header, carrying that header, the profiles it declared and the objects that came from it. CGMES normally exchanges Equipment, Operation and ShortCircuit in a single file; splitting them apart would be legal but would not reproduce the input, so this is the faithful export.

Selecting by profile alone is not enough for a merged common grid model, where two modelling authorities each contribute an Equipment file: every object would then land in both. The dataset therefore records which file contributed each object — see Dataset::objects_from — and each header writes its own. Objects built programmatically belong to no file and go with the first header whose profiles can carry them, rather than being dropped.

Returns the paths written. A header without a resolvable profile is skipped and named in the report, and the objects that came only from it are counted in SaveReport::unwritten — this is a faithful reproduction of a file set, so where there is no file to reproduce, nothing is invented. Dataset::save_all_profiles is the export that always writes something.

Source§

impl Dataset

Source

pub fn load_zip( &mut self, path: &Path, options: &ReadOptions, ) -> Result<LoadReport>

Load every CIM/XML entry in a zip archive.

CGMES model sets are routinely distributed as archives, sometimes with one instance file per archive and sometimes with a whole model set inside one.

Source

pub fn save_zip(&self, path: &Path, stem: &str) -> Result<Vec<String>>

Write every populated profile into one zip archive.

Source§

impl Dataset

Source

pub fn view<'a, T: TypedView<'a>>(&'a self) -> impl Iterator<Item = T> + 'a

Every object of T’s class, including subclasses, as typed views.

use cim_kit::prelude::*;
use cim_kit::cgmes3::{SCHEMA, views::ACLineSegment};

let dataset = Dataset::new(SCHEMA);
for line in dataset.view::<ACLineSegment>() {
    println!("{:?} r={:?}", line.name(), line.r());
}
Source

pub fn view_by_mrid<'a, T: TypedView<'a>>(&'a self, mrid: &Mrid) -> Option<T>

Look up one object by mRID as a typed view, checking its class.

Source

pub fn count_view<'a, T: TypedView<'a>>(&'a self) -> usize

Count objects of T’s class.

Trait Implementations§

Source§

impl Debug for Dataset

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.