GraphModel Overview¶
Intro to Knowledge Graphs¶
Knowledge graphs store information as a graph: data is represented as nodes (entities) and edges (relationships) that connect these nodes. This structure makes it easier to visualize and analyze connections between different pieces of information.
For example, in a knowledge graph representing a power grid:
-
Graph nodes can represent components like transformers, substations, and generators.
-
Graph edges can represent relationships such as the connection between different components.
In this context graph nodes are not the same as electrical buses / nodes. Every bus, branch, and piece of equipment is a node in the knowledge graph.
Below is a simple graphical representation of a distribution line as a knowledge graph:
Intro to Typed Property Graphs¶
The core of CIMantic Graphs is a typed property graph in which the graph nodes and edges are strictly typed according to the classes, attributes and associations of the UML structure of the Common Information Model. Within the typed property graph, the following general rules apply:
-
Nodes and Edges:
-
Nodes represent entities (like transformers, substations, or generators).
-
Edges represent the relationships between these entities.
-
-
Properties:
-
Nodes have properties: additional pieces of information such as names, ratings, or any other relevant attributes.
-
For example, a node representing an
ACLineSegmenthas properties like name and length.
-
-
Types:
-
Each node and edge has a type that defines what kind of entity or relationship it represents.
-
Types help in organizing and validating the data. For example, a node of type
ACLineSegmenthas properties like name and length, while a node of typePhotoVoltaicUnithas properties like name and rated power.
-
In the figure above, each graph node is an object with a strict datatype, such as ACLineSegment, Feeder, and Terminal. Only classes defined in the CIM profile selected by the user are supported. The graph nodes are linked by typed edges named after each association. So, the edge ACLineSegment --[ConductingEquipment.Terminals]--> list[Terminal] can only hold Terminal objects. A different object type, such as Location, cannot be used in that edge.
GraphModel Base Class¶
Most of the interfaces for working with bus-branch, node-breaker, and distribution feeder models are provided by the GraphModel base class, the parent dataclass of the classes for each modeling need (FeederModel, NodeBreakerModel, BusBranchModel and DistributedArea). Its attributes and methods are explained below.
Input Arguments¶
The following arguments are passed when creating a model:
-
connection: An instance ofConnectionInterface, such asXMLFileorBlazegraphConnection, orNonefor a model built in memory withadd_to_graph()/create() -
container: The top-levelEquipmentContainer(such as aFeeder) from which the model will be built -
distributed: Boolean on whether a centralized or distributed graph should be built (defaultFalse) -
base_power,base_frequency: Optional system bases. By default they are read from the model'sBasePowerandBaseFrequencyobjects, else 100 MVA (orCIMG_SYSTEM_MVA_BASE) and 60 Hz
GraphModel itself does not load anything from the connection. Use one of its child classes, such as FeederModel.
The examples on this page use the IEEE 13 node feeder from the test models, read with the XMLFile parser:
import os
os.environ['CIMG_CIM_PROFILE'] = 'cimhub_2023'
import cimprofiles.cim17.cimhub_2023 as cim
from cimgraph.databases import XMLFile
from cimgraph.models import FeederModel
file = XMLFile(filename='../../tests/test_models/ieee13.xml')
network = FeederModel(container=cim.Feeder(mRID='49AD8E07-3BF9-A4E2-CB8F-C3722F837B62'), connection=file)
Graph¶
The .graph attribute of the GraphModel dataclass is the typed property graph with all data contained in the network model.
It is a dictionary keyed first by class (e.g. cim.ACLineSegment) and then by the UUID identifier of each object.
All objects within the graph (if added using the API) are forced to have a unique identifier.
Object Types in the graph¶
The classes present in the graph are the dictionary keys:
eq_types = list(network.graph.keys())
print(len(eq_types), 'classes, e.g.', [cim_class.__name__ for cim_class in eq_types[:6]])
48 classes, e.g. ['Feeder', 'IEC61970CIMVersion', 'CoordinateSystem', 'GeographicalRegion', 'SubGeographicalRegion', 'Substation']
Object IDs in the graph¶
The identifiers of all objects of one class are the keys of the inner dictionary:
line_ids = list(network.graph[cim.ACLineSegment].keys())
line_ids[:3]
[UUID('a04cdfb1-e951-4fc4-8882-0323cd70ae3c'),
UUID('abf53597-a808-422a-b7ee-552f24d83a5f'),
UUID('45395c84-f20a-4f5a-977f-b80348256421')]
Objects in the graph¶
Objects are accessed with a loop, by identifier, or with the search methods of the model.
Example 1: Access to objects via loop¶
The most direct method to access objects is a loop, which covers most use cases. .get() returns an empty dictionary if the class is not in the graph. Unit values are compared after converting them with .to():
# Find lines longer than 200 m
long_lines = []
for line in network.graph.get(cim.ACLineSegment, {}).values():
if line.length.to('m') > 200:
long_lines.append(line)
for line in long_lines:
print(line.name, round(line.length.to('ft')), 'ft')
650632 2000 ft 632670 667 ft 670671 1333 ft 671680 1000 ft 684652 800 ft
Example 2: Access to objects via UUID¶
An object can be read directly by its UUID identifier:
from uuid import UUID
line = network.graph[cim.ACLineSegment][UUID('0bbd0ea3-f665-465b-86fd-fc8b8466ad53')]
line.name
'645646'
Example 3: Search methods¶
first() and next() step through a class in a stable order, find_by_mRID() looks up an mRID, and find_by_attribute() matches an attribute value:
print(network.first(cim.ACLineSegment).name)
print(network.find_by_mRID('0BBD0EA3-F665-465B-86FD-FC8B8466AD53').name)
print([line.name for line in network.find_by_attribute(cim.ACLineSegment, 'name', '650632')])
645646 645646 ['650632']
API Reference¶
All classes based on GraphModel inherit the following methods:
-
Loading:
get_all_edges(cim.ClassName),get_all_attributes(cim.ClassName),get_object(mRID),get_from_triple(object, attribute),add_to_graph(object),add_jsonld_to_graph(json_ld) -
Reading:
list_by_class(cim.ClassName),iter_by_class(cim.ClassName),first(cim.ClassName),next(cim.ClassName),find_by_mRID(mRID),find_by_attribute(cim.ClassName, attribute, value),find_by_condition(cim.ClassName, attribute, predicate),list_identities(),pprint(cim.ClassName) -
Editing (recorded as incrementals, see Using Incrementals):
create(cim.ClassName, **kwargs),modify(object, attribute, value),delete(object),from_incremental(filename),write_all_incrementals(filename) -
Saving:
upload()writes the graph back to the connection (forXMLFile, the XML file)
get_all_edges()¶
The .get_all_edges() method is the core library method that enables the flexibility of CIM-Graph to query for CIM objects of any class and build the knowledge graph without custom queries. It reads every attribute and association of the objects of that class already in the graph, and adds the objects at the other end of each association.
The arguments of the method are
cim_class(type): The CIM class for which to retrieve edges (e.g.cim.ACLineSegment)
The method does not return any values. The file parsers (XMLFile, JSONLDFile) read the whole file when the model is created, so for them this method does nothing.
get_all_attributes()¶
The .get_all_attributes() method is similar to get_all_edges(), but does not create any new graph nodes. Instead, edges to new objects are represented as strings.
The arguments of the method are
cim_class(type): The CIM class for which to retrieve attributes (e.g.cim.ACLineSegment)
The method does not return any values.
get_object()¶
The get_object() method retrieves an object from the database by its mRID and adds it to the graph.
The arguments are
mRID(str or UUID): The mRID of the object to be retrieved.
add_to_graph()¶
The .add_to_graph() method adds a CIM object to the graph model (at both the class and identifier levels of the graph dictionary). It raises a ValueError if a different object with the same mRID is already in the graph.
The arguments are
-
obj: The CIM object to add -
graph(optional): Another graph dictionary to add the object to instead of.graph
Use create() instead to also record the new object as an incremental change.
GraphModel Class Inheritance¶
The diagram below shows the dataclass fields and methods offered by the GraphModel base class and its children classes.
%%{init: {"theme":"base"}}%%
classDiagram
class GraphModel{
<<abstract>>
+ connection: ConnectionInterface
+ container: cim.EquipmentContainer
+ graph: dict[type, uuid]
+ distributed: bool
+ add_to_graph(object)
+ add_jsonld_to_graph(str)
+ get_all_edges(cim.ClassName)
+ get_object(mRID)
+ get_from_triple(object,attribute)
+ first(cim.ClassName)
+ next(cim.ClassName)
+ pprint(cim.ClassName)
+ upload()
}
class BusBranchModel{
}
GraphModel <|-- BusBranchModel : inherits from
GraphModel <|-- NodeBreakerModel : inherits from
GraphModel <|-- FeederModel : inherits from
GraphModel <|-- DistributedArea : inherits from
get_all_edges()¶
The .get_all_edges() method invokes the method of the same name in the ConnectionInterface, which performs the database-specific query. SPARQL databases are queried in batches of 100 objects, run in parallel. The execution workflow is shown below:
%%{init: {"theme":"base"}}%%
sequenceDiagram
actor User
participant GraphModel
participant ConnectionInterface
participant Queries Module
participant Database
note right of User: Expand knowledge graph
User ->>+ GraphModel: get_all_edges(cim_class)
%% alt cim_class not in graph
%% GraphModel -->>- User: None
%% else
%% GraphModel ->> GraphModel: exit
%% %% GraphModel -->>- User: None
%% end
GraphModel ->>+ ConnectionInterface: get_all_edges(graph, cim_class)
ConnectionInterface ->>+ Queries Module: get_all_edges_query()
Queries Module -->>- ConnectionInterface: str[query text]
ConnectionInterface ->>+ Database: execute(query text)
Database -->>- ConnectionInterface: dict[query response]
loop
ConnectionInterface ->> ConnectionInterface: populate attributes
ConnectionInterface ->> ConnectionInterface: create new objects
end
ConnectionInterface -->>- GraphModel: None
GraphModel -->>- User: None
get_all_attributes()¶
The .get_all_attributes() method invokes the method of the same name in the ConnectionInterface, which performs the database-specific query. The execution workflow is shown below:
%%{init: {"theme":"base"}}%%
sequenceDiagram
actor User
participant GraphModel
participant ConnectionInterface
participant Queries Module
participant Database
note right of User: Populate knowledge graph without expanding
User ->>+ GraphModel: get_all_attributes(cim_class)
%% alt cim_class not in graph
%% GraphModel -->>- User: None
%% else
%% GraphModel ->> GraphModel: exit
%% %% GraphModel -->>- User: None
%% end
GraphModel ->>+ ConnectionInterface: get_all_attributes(graph, cim_class)
ConnectionInterface ->>+ Queries Module: get_all_edges_query()
Queries Module -->>- ConnectionInterface: str[query text]
ConnectionInterface ->>+ Database: execute(query text)
Database -->>- ConnectionInterface: dict[query response]
loop
ConnectionInterface ->> ConnectionInterface: populate attributes
ConnectionInterface ->> ConnectionInterface: populates edges as string
end
ConnectionInterface -->>- GraphModel: None
GraphModel -->>- User: None
<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>