Overview & Quick Start¶
This tutorial introduces the CIMantic Graphs library (CIM-Graph, published on PyPI as cim-graph).
CIMantic Graphs builds typed, in-memory knowledge graphs of IEC Common Information Model (CIM) power system models, so they can be parsed, created and edited without writing database queries. Every CIM class is a Python dataclass from a CIM profile (e.g. IEC 61970 CIM17v40, CIMHub 2023 or GridAPPS-D RC4 2021), provided by the companion cimprofiles package.
Install with pip install cim-graph. Database drivers are optional extras, described in Installation. This quick start reads the IEEE 13 node test feeder from a CIM XML file, so it needs no database.
Library Structure¶
CIMantic Graphs uses the layered architecture shown below:

- Database layer: connections to CIM XML and JSON-LD files and to databases (Blazegraph, GraphDB, Neo4j, MySQL, RDFLib, GridAPPS-D). Changing the database changes only the connection, not the rest of the code.
- Data profile layer: the CIM profile, with every UML class and attribute as a Python dataclass.
- API layer:
network.graph[cim.ClassName]to access objects andnetwork.get_all_edges(cim.ClassName)to load them, for every class, profile and database. - Knowledge graph layer:
FeederModel,NodeBreakerModelandBusBranchModel, centralized or split intoDistributedAreas.
See Structure for each layer and the package layout.
Importing a CIM Profile¶
The first step is to import the CIM profile that matches your data. The profile defines every CIM class as a Python dataclass, so classes can be used directly by name.
Method 1: Directly import the desired CIM profile:
import cimprofiles.cim17.cimhub_2023 as cim
Method 2: Import a profile by its short name with importlib:
import importlib
from cimprofiles import profile_module
cim = importlib.import_module(profile_module('cimhub_2023'))
Profiles are grouped by CIM version (cimprofiles.cim16, cimprofiles.cim17, cimprofiles.cim18). cimprofiles.PROFILE_PACKAGES maps each short name to its module:
import cimprofiles
cimprofiles.PROFILE_PACKAGES
{'cim16v33': 'cimprofiles.cim16.cim16v33',
'cgmes_2_4_0': 'cimprofiles.cim16.cgmes_2_4_0',
'cgmes_3_0_0': 'cimprofiles.cim17.cgmes_3_0_0',
'cim17v40': 'cimprofiles.cim17.cim17v40',
'cimhub_2023': 'cimprofiles.cim17.cimhub_2023',
'rc4_2021': 'cimprofiles.cim17.gridappsd_rc4_2021',
'cim18gad': 'cimprofiles.cim18.cim18gad',
'cim18gmdm': 'cimprofiles.cim18.cim18gmdm',
'cim18v17': 'cimprofiles.cim18.cim18v17',
'cimhub_2026': 'cimprofiles.cim18.cimhub_2026'}
The pre-0.6 imports (cimgraph.data_profile.cimhub_2023) still work, with a DeprecationWarning.
Creating CIM Objects¶
After importing the profile, you can create an instance of any class or view its documentation.
Example 1: Create a new breaker with a name and set its attributes. If no mRID is given, the UUID is derived from the class and name, so the same object gets the same UUID on every run.
breaker = cim.Breaker(name='breaker_01', open=True)
breaker.normalOpen = False
breaker.pprint()
{
"@id": "9ad6320a-59e3-571b-bbc9-badc2cf2a449",
"@type": "Breaker",
"name": "breaker_01",
"normalOpen": "False",
"open": "True"
}
Example 2: Associate two CIM objects. Set both ends of the association; GraphModel.create and GraphModel.modify do this for you.
substation = cim.Substation(name='sub_1')
breaker.EquipmentContainer = substation
substation.Equipments.append(breaker)
breaker.pprint()
substation.pprint()
{
"@id": "9ad6320a-59e3-571b-bbc9-badc2cf2a449",
"@type": "Breaker",
"name": "breaker_01",
"EquipmentContainer": {
"@id": "3e24fe79-f1fc-5773-aef0-e5a038d9c3a9",
"@type": "Substation"
},
"normalOpen": "False",
"open": "True"
}
{
"@id": "3e24fe79-f1fc-5773-aef0-e5a038d9c3a9",
"@type": "Substation",
"name": "sub_1",
"Equipments": [
{
"@id": "9ad6320a-59e3-571b-bbc9-badc2cf2a449",
"@type": "Breaker"
}
]
}
Example 3: Physical quantities are unit objects. Give the unit when creating one, and convert with .to(). See Using Units.
line = cim.ACLineSegment(name='line_01', length=cim.Length(1.2, 'km'))
print(line.length.to('m'), 'm')
print(line.length.to('ft'), 'ft')
1200.0 m 3937.0078740157483 ft
Example 4: View the documentation of the ACLineSegment class:
print(cim.ACLineSegment.__doc__)
A wire or combination of wires, with consistent electrical characteristics, building a single electrical system, used to carry alternating current between points in the power system. For symmetrical, transposed 3ph lines, it is sufficient to use attributes of the line segment, which describe impedances and admittances for the entire length of the segment. Additionally impedances can be computed by using length and associated per length impedances. The BaseVoltage at the two ends of ACLineSegments in a Line shall have the same BaseVoltage.nominalVoltage. However, boundary lines may have slightly different BaseVoltage.nominalVoltages and variation is allowed. Larger voltage difference in general requires use of an equivalent branch.
Specifying Environment Variables¶
Every connection reads its settings from CIMG_* environment variables when it is created. A file connection needs only the CIM profile:
import os
os.environ['CIMG_CIM_PROFILE'] = 'cimhub_2023'
A database connection also needs its address and, for some databases, credentials. For example, for Blazegraph:
All variables are described in Environment Variables.
Connecting to the Data Source¶
The next step is to connect to the file or database that holds the CIM model. Here it is the IEEE 13 node model from the tests/test_models folder of the CIM-Graph repository:
from cimgraph.databases import XMLFile
file = XMLFile(filename='../../tests/test_models/ieee13.xml')
Any other connection can be used in its place, for example BlazegraphConnection() from cimgraph.databases (after pip install "cim-graph[sparql]"); the rest of the code is unchanged. All connection types are described in Supported Databases.
Creating a Graph Model¶
A graph model is built from a connection and an EquipmentContainer as its starting point. The graph model classes are FeederModel, NodeBreakerModel and BusBranchModel.
from cimgraph.models import FeederModel
Pass the connection, the container object, and whether to build a centralized (distributed=False) or distributed model:
feeder = cim.Feeder(mRID='49AD8E07-3BF9-A4E2-CB8F-C3722F837B62') # IEEE 13 bus
network = FeederModel(connection=file, container=feeder, distributed=False)
The knowledge graph is indexed by class and then by object identifier (a UUID). To view all objects of a class, use network.pprint(cim.ClassName). Individual objects can also be printed with print() or .pprint().
A file connection reads the whole file when the model is created. A database connection first loads only the ConductingEquipment, Terminals and ConnectivityNodes, with just their identifiers, to save memory and query time.
network.pprint(cim.Breaker) # View all objects of type 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 as a diagram, generated with utils.get_mermaid(breaker) (see Utils Shortcuts):
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))
Automated Database Queries¶
CIMantic Graphs generates the queries for every class and every supported database through the .get_all_edges(cim.ClassName) method. It loads all attributes of all objects of that class and expands the knowledge graph by one edge, adding objects for all associated objects that are not in the graph yet.
network.get_all_edges(cim.Breaker)
network.get_all_edges(cim.Terminal)
network.get_all_edges(cim.ConnectivityNode)
With a file connection the data is already loaded, so these calls return immediately. The same code works unchanged against a database.
Traversing the Knowledge Graph¶
CIMantic Graphs links CIM objects by direct references between the in-memory objects, following the names and hierarchy of the CIM UML.
To view an attribute of an object, use its name from the UML class diagram:
from uuid import UUID
breaker = network.graph[cim.Breaker][UUID('52de9189-20dc-4c73-bdee-e960fe1f9493')]
print(breaker.normalOpen)
print(breaker.ratedCurrent.to('A'), 'A')
False 400.0 A
To traverse the knowledge graph, no custom queries are required. Use the UML association names that link the objects:
bus1_name = breaker.Terminals[0].ConnectivityNode.name
bus2_name = breaker.Terminals[1].ConnectivityNode.name
print(breaker.name, 'connects nodes', bus1_name, bus2_name)
brkr1 connects nodes 650 brkr
%%{init: {"theme":"neutral"}}%%
flowchart LR
52DE9189("`**Breaker**
name: brkr1`")
52DE9189 -- "Terminals[0]" --> 1D81C7FE
1D81C7FE("`**Terminal**
name: brkr1_T1`")
1D81C7FE -- "ConnectivityNode" --> 7BEDDADD
7BEDDADD("`**ConnectivityNode**
name: 650`")
52DE9189 -- "Terminals[1]" --> 2847E06B
2847E06B("`**Terminal**
name: brkr1_T2`")
2847E06B -- "ConnectivityNode" --> 94F822E0
94F822E0("`**ConnectivityNode**
name: brkr`")
Measurements need no separate queries or mapping either. In a model with measurements (e.g. from GridAPPS-D), load each measurement class and read the measurements from the equipment:
Utils Shortcuts¶
The utils module provides shortcut methods for bulk queries, file writing and diagrams. Import it with:
from cimgraph import utils
Shortcuts for Bulk Queries¶
The utils module has shortcut methods that query all classes related to lines, transformers, loads, switches, measurements, or everything in the model. They are documented in Get All Data. On large models, which have tens of thousands of objects, they can take from a few seconds to a minute.
For example, to get all line data (phases, asset info, impedance matrices, etc.):
utils.get_all_line_data(network)
print(len(network.graph[cim.ACLineSegment]), 'lines')
11 lines
Shortcuts for File Writers¶
The utils module writes CIM XML and JSON-LD files of new and existing models. The arguments are the graph model and the file name:
utils.write_xml(network, 'ieee13_copy.xml')
utils.write_json_ld(network, 'ieee13.jsonld')
See File Writers for the options.
Shortcuts for Visualization¶
CIM-Graph creates Mermaid diagrams of classes, objects and paths through the graph. The diagrams are plain text, so they can be tracked in git and rendered in Markdown and most web tools. See Mermaid Diagrams for details; the diagrams above were generated this way.
For example, a UML class diagram of a list of CIM classes:
diagram_text = utils.get_mermaid([cim.ACLineSegment,
cim.ACLineSegmentPhase,
cim.PerLengthImpedance,
cim.PerLengthPhaseImpedance,
cim.PhaseImpedanceData,
cim.WireSpacingInfo])
print(diagram_text)
%%{init: {"theme":"neutral", "layout":"dagre"}}%%
classDiagram
class ACLineSegment{
+ b0ch: float | Susceptance
+ bch: float | Susceptance
+ g0ch: float | Conductance
+ gch: float | Conductance
+ r: float | Resistance
+ r0: float | Resistance
+ shortCircuitEndTemperature: float | Temperature
+ x: float | Reactance
+ x0: float | Reactance
}
ACLineSegment --> "0..1" PerLengthImpedance : PerLengthImpedance
ACLineSegment --> "0..1" WireSpacingInfo : WireSpacingInfo
ACLineSegment --> "0..*" ACLineSegmentPhase : ACLineSegmentPhases
class ACLineSegmentPhase{
+ sequenceNumber: int
+ phase: enum:SinglePhaseKind
}
ACLineSegmentPhase --> "0..1" ACLineSegment : ACLineSegment
class PerLengthImpedance{
}
PerLengthImpedance --> "0..*" ACLineSegment : ACLineSegments
class PerLengthPhaseImpedance{
+ conductorCount: int
}
PerLengthPhaseImpedance --> "0..*" PhaseImpedanceData : PhaseImpedanceData
PerLengthImpedance <|-- PerLengthPhaseImpedance : inherits from
class PhaseImpedanceData{
+ column: int
+ row: int
+ b: float | SusceptancePerLength
+ g: float | ConductancePerLength
+ r: float | ResistancePerLength
+ x: float | ReactancePerLength
}
PhaseImpedanceData --> "0..1" PerLengthPhaseImpedance : PhaseImpedance
class WireSpacingInfo{
+ isCable: bool
+ phaseWireCount: int
+ phaseWireSpacing: float | Length
+ usage: enum:WireUsageKind
}
WireSpacingInfo --> "0..*" ACLineSegment : ACLineSegments
Rendered in a Markdown mermaid block, it looks like this:
%%{init: {"theme":"neutral"}}%%
classDiagram
class ACLineSegment{
+ b0ch: float | Susceptance
+ bch: float | Susceptance
+ g0ch: float | Conductance
+ gch: float | Conductance
+ r: float | Resistance
+ r0: float | Resistance
+ shortCircuitEndTemperature: float | Temperature
+ x: float | Reactance
+ x0: float | Reactance
}
ACLineSegment --> "0..1" PerLengthImpedance : PerLengthImpedance
ACLineSegment --> "0..1" WireSpacingInfo : WireSpacingInfo
ACLineSegment --> "0..*" ACLineSegmentPhase : ACLineSegmentPhases
class ACLineSegmentPhase{
+ sequenceNumber: int
+ phase: enum:SinglePhaseKind
}
ACLineSegmentPhase --> "0..1" ACLineSegment : ACLineSegment
class PerLengthImpedance{
}
PerLengthImpedance --> "0..*" ACLineSegment : ACLineSegments
class PerLengthPhaseImpedance{
+ conductorCount: int
}
PerLengthPhaseImpedance --> "0..*" PhaseImpedanceData : PhaseImpedanceData
PerLengthImpedance <|-- PerLengthPhaseImpedance : inherits from
class PhaseImpedanceData{
+ column: int
+ row: int
+ b: float | SusceptancePerLength
+ g: float | ConductancePerLength
+ r: float | ResistancePerLength
+ x: float | ReactancePerLength
}
PhaseImpedanceData --> "0..1" PerLengthPhaseImpedance : PhaseImpedance
class WireSpacingInfo{
+ isCable: bool
+ phaseWireCount: int
+ phaseWireSpacing: float | Length
+ usage: enum:WireUsageKind
}
WireSpacingInfo --> "0..*" ACLineSegment : ACLineSegments
<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>