XML File Parser¶
The XMLFile class reads CIM power system models from CIM XML (RDF/XML) files into a graph. It is the simplest way to work with small and medium test cases, as it needs no database.
Overview¶
XMLFile implements the ConnectionInterface and:
- reads CIM RDF/XML files (IEC 61970-552), one file or several part files into one graph;
- resolves the part files named by an IEC 61970-552 metadata graph (
.cimx); - reads the namespace declarations of each file's header;
- reads every identifier style (
rdf:about="urn:uuid:...",rdf:ID="_...",rdf:about="#_..."); - reads each file's
md:FullModelheader intomodel_headers, which sets the model scope of seeded UUIDs.
Models are written with cimgraph.utils.write_xml (see Writing XML Files below).
User Guide¶
Installation and Setup¶
The XML parser needs no install extra or database software. It parses with the defusedxml library.
First, set the CIM profile environment variable and import the profile:
import os
os.environ['CIMG_CIM_PROFILE'] = 'cimhub_2023'
import cimprofiles.cim17.cimhub_2023 as cim
Creating an XMLFile Connection¶
Import and instantiate the XMLFile class. The file is parsed when the connection is created:
from cimgraph.databases import XMLFile
file = XMLFile(filename='../../tests/test_models/ieee13.xml')
print(file.cim_profile, file.iec61970_552, file.namespaces['cim'])
cimhub_2023 552-NEW http://iec.ch/TC57/CIM100#
Constructor Parameters¶
XMLFile(filename=None, namespaces=None, metadata=None):
filename(str | list[str]): the XML file, or a list of part files to load into one graph.namespaces(dict): namespace mappings{'prefix': 'uri'}added to, or replacing, those read from the file headers.metadata(str): an IEC 61970-552 metadata graph (.cimx) whosedcat:Distributionpart files are loaded, in place offilename.
Behavior:
- Reads the
CIMG_*settings (profile, namespace, identifier style, units, log level) as they are at creation. - Parses each file and reads the namespaces declared in its header.
- A missing file raises
FileNotFoundErrorand a malformed oneParseError. For an empty in-memory model, passconnection=Noneto the model instead.
A metadata graph loads all of its parts:
from pathlib import Path
parts = XMLFile(metadata='../../tests/test_models/ieee13_metadata.cimx')
print([Path(name).name for name in parts.filename])
['ieee13.xml', 'ieee13_assets.xml']
Loading a FeederModel from XML¶
Once the XMLFile connection is created, create a FeederModel to build the network graph:
from cimgraph.models import FeederModel
feeder = cim.Feeder(mRID='49AD8E07-3BF9-A4E2-CB8F-C3722F837B62')
network = FeederModel(container=feeder, connection=file, distributed=False)
print(f'{len(network.graph)} classes, {len(network.graph[cim.ACLineSegment])} lines')
48 classes, 11 lines
The complete model, with both ends of every association, is now in the graph. Unit values are CIMUnits in base SI units; convert them with .to():
line = network.first(cim.ACLineSegment)
print(f'{line.name}: {line.length.to("ft"):.0f} ft')
645646: 300 ft
To show the structure, here is the breaker:
network.pprint(cim.Breaker)
[
{
"@id": "52de9189-20dc-4c73-bdee-e960fe1f9493",
"@type": "Breaker",
"name": "brkr1",
"Location": {
"@id": "085bbe1f-ff95-4260-a9d2-8d2f1a8ea9a3",
"@type": "Location"
},
"EquipmentContainer": {
"@id": "49ad8e07-3bf9-a4e2-cb8f-c3722f837b62",
"@type": "Feeder"
},
"BaseVoltage": {
"@id": "2a158e0c-cd01-4a50-aeba-59d761fcf15d",
"@type": "BaseVoltage"
},
"Terminals": [
{
"@id": "1d81c7fe-e88f-41e3-a900-476ca6476ccd",
"@type": "Terminal"
},
{
"@id": "2847e06b-c8ed-41e6-b515-c61c9e8eb4b4",
"@type": "Terminal"
}
],
"normalOpen": "False",
"open": "False",
"retained": "True",
"ratedCurrent": "400.0",
"breakingCapacity": "400.0"
}
]
The same breaker drawn with cimgraph.utils.get_mermaid(breaker) (see Mermaid Diagrams):
mindmap
52DE9189((**Breaker**
name: brkr1
normalOpen: False
open: False
retained: True
ratedCurrent: 400 ampere
breakingCapacity: 400 ampere))
[Location]
085BBE1F((**Location**
name: brkr1_Loc))
[EquipmentContainer]
49AD8E07((**Feeder**
name: ieee13nodeckt))
[BaseVoltage]
2A158E0C((**BaseVoltage**
name: BaseV_4.1600))
["Terminals"]
1D81C7FE((**Terminal**
name: brkr1_T1))
2847E06B((**Terminal**
name: brkr1_T2))
Writing XML Files¶
cimgraph.utils.write_xml(network, filename) writes a model to a new CIM XML file:
- Identifiers are written in the
CIMG_IEC61970_552style. - Unit values are plain numbers in base SI units, as CIM XML requires (no
rdf:datatype). - An
md:FullModelheader is written first, with the model authority (CIMG_MODEL_AUTHORITY).header={...}writes adcat:Datasetheader instead, aswrite_json_lddoes.
Classes are written in alphabetical order and objects sorted by identifier, so the output is stable between runs. The complete workflow example below writes and reads back a modified model.
User API Methods¶
XMLFile implements the ConnectionInterface abstract base class with the following methods.
connect()¶
Parses the files. Called by the constructor.
- Parses each file with
defusedxml.ElementTree.parse(). - Reads the namespace declarations from each file's header and adds them to
namespaces. - Creates an empty graph.
- A missing or malformed file raises (
FileNotFoundError,ParseError);filename=NonewithoutmetadataraisesValueError.
disconnect()¶
Deletes the parsed tree (tree, root) and the graph.
get_object(mRID, graph=None)¶
Returns the object whose rdf:about or rdf:ID text contains mRID, from the first file, or None. The match is case-sensitive, so give the ID as the file writes it.
get_from_triple(subject, predicate, graph=None)¶
Returns the values of the attribute predicate (e.g. 'IdentifiedObject.name') of the object subject.
create_new_graph(container, graph=None)¶
Builds the graph of every object in the files. Graph models call it when they are created.
- First pass: reads each file's header (
model_headers), sets the model scope from it, and creates every object withparse_nodes(). - Second pass: sets the attributes and associations of every object with
parse_edges(), including the inverse end of each association. - Classes that are not in the CIM profile are skipped, with a validation log message.
The whole file is read whatever container is given.
upload(graph)¶
Writes the graph to self.filename, replacing the file that was read. GraphModel.upload() calls it. To write to a new file, use cimgraph.utils.write_xml(network, filename).
execute(), create_distributed_graph()¶
XMLFile has no query language: execute() does nothing and returns None. Distributed models are not supported: create_distributed_graph() logs an error.
UML Sequence Diagrams¶
These diagrams show the internal workflow of the main XMLFile methods.
XMLFile Initialization and Connection¶
sequenceDiagram
actor User
participant XMLFile
participant ElementTree
participant FileSystem
note right of User: Initialize XML connection
User ->>+ XMLFile: XMLFile(filename, namespaces)
XMLFile ->> XMLFile: read CIMG_* settings
XMLFile ->>+ XMLFile: connect()
loop for each file
XMLFile ->>+ ElementTree: parse(filename)
ElementTree ->>+ FileSystem: read XML file
FileSystem -->>- ElementTree: file contents
ElementTree -->>- XMLFile: tree & root element
XMLFile ->> XMLFile: extract_namespaces_from_header(filename)
XMLFile ->> XMLFile: update namespace mappings
end
XMLFile ->> XMLFile: initialize empty graph and object_index
XMLFile -->>- XMLFile: connection ready
XMLFile -->>- User: XMLFile instance
create_new_graph() - Building the Typed Property Graph¶
sequenceDiagram
actor GraphModel
participant XMLFile
participant root as root elements
note right of GraphModel: Build network graph from XML
GraphModel ->>+ XMLFile: create_new_graph(container, graph)
note over XMLFile,root: First Pass - Create Nodes
loop for each file
XMLFile ->> XMLFile: parse_model_header(root), set model scope
loop for each element in root
XMLFile ->>+ XMLFile: parse_nodes(element)
XMLFile ->> XMLFile: extract class name from tag
XMLFile ->> XMLFile: extract rdf:about or rdf:ID
XMLFile ->> XMLFile: create_object(graph, cim_class, uri)
XMLFile ->> XMLFile: update object_index
XMLFile -->>- XMLFile: object created
end
end
note over XMLFile,root: Second Pass - Create Edges
loop for each element in every root
XMLFile ->>+ XMLFile: parse_edges(element)
loop for each sub_element
XMLFile ->> XMLFile: parse_value(sub_element)
alt rdf:resource to an object
XMLFile ->> XMLFile: create_edge() to linked object
XMLFile ->> XMLFile: create reverse edge
else rdf:resource to an enumeration
XMLFile ->> XMLFile: set enum value
else text value
XMLFile ->> XMLFile: create_value() attribute
end
end
XMLFile -->>- XMLFile: edges created
end
XMLFile -->>- GraphModel: Graph
write_xml() - Writing a Graph to XML¶
sequenceDiagram
actor User
participant write_xml
participant FileSystem
note right of User: Write the graph to a new XML file
User ->>+ write_xml: write_xml(network, filename)
write_xml ->> write_xml: collect namespaces of the graph's classes
write_xml ->>+ FileSystem: open(filename, 'w')
write_xml ->> FileSystem: rdf:RDF tag and model header
loop for each class, alphabetically
loop for each object, sorted by identifier
write_xml ->> FileSystem: object_to_xml(obj)
note right of FileSystem: references as rdf:resource,<br/>enumerations as rdf:resource,<br/>numbers in base SI units
end
end
write_xml ->> FileSystem: closing rdf:RDF tag
FileSystem -->>- write_xml: file closed
write_xml -->>- User: None
Developer Documentation¶
This section documents the internal methods of the XML parser. They are not usually called directly.
extract_namespaces_from_header(filename=None)¶
Returns the namespace declarations of a file (default: self.filename) as {prefix: uri}.
- Reads the first 8 KB of the file, which hold the root element.
- Matches
xmlns:prefix="..."andxmlns="..."declarations; the default namespace gets the key'default'. - The URIs have no curly braces, as ElementTree
find()expects.
parse_nodes(element)¶
Creates the CIM object of an XML element, without its attributes or associations, and returns it (or None).
- Skips file header elements (
md:FullModeland the like), whichparse_model_headerreads. - Takes the class name from the element tag, trying
CIMG_NAMESPACEfirst and then the other declared namespaces. - Logs a validation message for a class that is not in the CIM profile.
- Takes the identifier from
rdf:aboutorrdf:ID(an element with neither raisesValueError), creates the object withcreate_object()and records it inobject_index.
parse_edges(element)¶
Sets the attributes and associations of an element's object, after parse_nodes() has created every object. It calls parse_value() for each child element except Identity.identifier.
parse_value(sub_element, cim_class, identifier)¶
Sets one attribute or association of an object and returns the value.
- Reference to an object (
rdf:resource, not in a declared namespace): looks up the target inobject_index, links it withcreate_edge()and sets the inverse association. A target that is not in the files is logged and skipped. - Enumeration (
rdf:resourcein a declared namespace, e.g.cim:PhaseCode.ABC): sets the profile's enumeration member. - Text value: converts it with
create_value(). Anrdf:datatypeon a unit value (written by older releases) is read whenCIMG_USE_UNITSis true.
Query methods¶
parse_node_query, get_edges_query, get_all_edges, get_all_attributes and edge_query_parser do nothing for XMLFile: the whole file is read in create_new_graph(), so there is nothing more to query.
Common Inherited Methods¶
XMLFile uses these ConnectionInterface methods, which every reader shares.
check_attribute(cim_class, attribute)¶
Resolves an attribute name of the form ClassName.attributeName to the field of cim_class it sets, including the inverse end of an association written on the other class. Returns None (with a validation log message) if the profile has no such field. Results are cached per class and attribute.
create_object(graph, class_type, uri)¶
Returns the object of class_type with this RDF ID, mRID or identifier from the graph, or creates it and adds it to the graph. A non-UUID ID is replaced by the UUID seeded from it in the current model scope.
create_edge(graph, cim_class, identifier, attribute, edge_class, edge_mRID)¶
Sets an association of the object identifier to the object edge_mRID of edge_class, creating that object if needed. For a list-valued association, it appends the object if it is not already there. Returns the linked object, or None if the attribute is not in the profile.
create_value(graph, cim_class, identifier, attribute, value, datatype_uri=None, input_unit=None)¶
Sets an attribute from its text and returns the converted value:
bool:true/1andfalse/0;int: throughfloat, so'123.0'reads as123;floatand unit values: a unit value is aCIMUnitwhenCIMG_USE_UNITSis true, else a float in its base SI unit.input_unitis the unit the number is written in (JSON-LD unit vocabularies);Nonemeans base SI, as in CIM XML;- other types are kept as text.
A value that does not convert is logged at the validation log level.
add_to_graph(obj, graph)¶
Adds an existing object to the graph under its identifier. Adding the same object again does nothing; a different object with the same identifier raises ValueError.
Performance Considerations¶
The XML parser parses the whole file and builds every object in memory. That is quick for IEEE 13 and 123 bus models; for models with tens of thousands of objects (the IEEE 9500-node model), loading takes longer and the graph uses a lot of memory. A database backend can load only the containers and classes you query.
Example: Complete Workflow¶
This example loads a model, makes every line 10% longer, writes the model to a new file and reads it back.
import tempfile
from cimgraph.utils import write_xml
# 1. Load the model
network = FeederModel(container=feeder,
connection=XMLFile('../../tests/test_models/ieee13.xml'),
distributed=False)
# 2. Make every line 10% longer
for line in network.list_by_class(cim.ACLineSegment):
network.modify(line, 'length', cim.Length(line.length.to('ft') * 1.1, 'ft'))
# 3. Write the model to a new file
output_file = Path(tempfile.mkdtemp()) / 'ieee13_modified.xml'
write_xml(network, str(output_file))
# 4. Read it back
copy = FeederModel(container=feeder, connection=XMLFile(str(output_file)), distributed=False)
line = network.first(cim.ACLineSegment)
print(f'{line.name}: {copy.graph[cim.ACLineSegment][line.identifier].length.to("ft"):.0f} ft')
645646: 330 ft
Troubleshooting¶
Common Issues¶
1. File not found
- Check the path. Relative paths are relative to the working directory.2. Namespace errors
- Check that the file declares its namespaces in therdf:RDF element.
- Check that CIMG_NAMESPACE and the CIM profile match the file's CIM version.
- Use the namespaces parameter to add or override a namespace.
3. Class not in profile
- Check that the right CIM profile is selected (CIMG_CIM_PROFILE).
- Check whether the file uses a newer or older CIM version than the profile.
- Set CIMG_VALIDATION_LOG_LEVEL to hide or show these messages.
4. Missing references
- The referenced object is in another part file. Load all the parts together (a list of files ormetadata=).
<style>
['pre { line-height: 125%; }\ntd.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\nspan.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\ntd.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\nspan.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\n.highlight-ipynb .hll { background-color: var(--jp-cell-editor-active-background) }\n.highlight-ipynb { background: var(--jp-cell-editor-background); color: var(--jp-mirror-editor-variable-color) }\n.highlight-ipynb .c { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment */\n.highlight-ipynb .err { color: var(--jp-mirror-editor-error-color) } /* Error */\n.highlight-ipynb .k { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword */\n.highlight-ipynb .o { color: var(--jp-mirror-editor-operator-color); font-weight: bold } /* Operator */\n.highlight-ipynb .p { color: var(--jp-mirror-editor-punctuation-color) } /* Punctuation */\n.highlight-ipynb .ch { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Hashbang */\n.highlight-ipynb .cm { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Multiline */\n.highlight-ipynb .cp { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Preproc */\n.highlight-ipynb .cpf { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.PreprocFile */\n.highlight-ipynb .c1 { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Single */\n.highlight-ipynb .cs { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Special */\n.highlight-ipynb .kc { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Constant */\n.highlight-ipynb .kd { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Declaration */\n.highlight-ipynb .kn { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Namespace */\n.highlight-ipynb .kp { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Pseudo */\n.highlight-ipynb .kr { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Reserved */\n.highlight-ipynb .kt { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Type */\n.highlight-ipynb .m { color: var(--jp-mirror-editor-number-color) } /* Literal.Number */\n.highlight-ipynb .s { color: var(--jp-mirror-editor-string-color) } /* Literal.String */\n.highlight-ipynb .ow { color: var(--jp-mirror-editor-operator-color); font-weight: bold } /* Operator.Word */\n.highlight-ipynb .pm { color: var(--jp-mirror-editor-punctuation-color) } /* Punctuation.Marker */\n.highlight-ipynb .w { color: var(--jp-mirror-editor-variable-color) } /* Text.Whitespace */\n.highlight-ipynb .mb { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Bin */\n.highlight-ipynb .mf { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Float */\n.highlight-ipynb .mh { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Hex */\n.highlight-ipynb .mi { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Integer */\n.highlight-ipynb .mo { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Oct */\n.highlight-ipynb .sa { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Affix */\n.highlight-ipynb .sb { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Backtick */\n.highlight-ipynb .sc { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Char */\n.highlight-ipynb .dl { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Delimiter */\n.highlight-ipynb .sd { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Doc */\n.highlight-ipynb .s2 { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Double */\n.highlight-ipynb .se { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Escape */\n.highlight-ipynb .sh { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Heredoc */\n.highlight-ipynb .si { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Interpol */\n.highlight-ipynb .sx { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Other */\n.highlight-ipynb .sr { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Regex */\n.highlight-ipynb .s1 { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Single */\n.highlight-ipynb .ss { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Symbol */\n.highlight-ipynb .il { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Integer.Long */']
</style>