Databases Overview¶
CIMantic Graphs reads CIM power system models from files and from several databases through one interface. You can choose the storage that fits your use case, from XML files for small test cases to graph databases for utility-scale networks, without changing the rest of your code.
Available Connections¶
| Connection | Reads from | Install extra | Documentation |
|---|---|---|---|
XMLFile |
CIM XML (RDF/XML) files | none | XML File Parser |
JSONLDFile |
CIM JSON-LD files | none | JSON-LD File Parser |
SPARQLEndpointConnection |
base class of the SPARQL connections | none | this page |
BlazegraphConnection |
Blazegraph (SPARQL) | sparql |
Blazegraph |
GraphDBConnection |
Ontotext GraphDB (SPARQL) | sparql |
GraphDB |
RDFlibConnection |
a local RDF/XML file in an in-memory rdflib graph (SPARQL) | rdflib |
RDFLib Parser |
Neo4jConnection |
Neo4j (Cypher) | neo4j |
Neo4j |
MySQLConnection |
MySQL | mysql |
MySQL |
GridappsdConnection |
the GridAPPS-D platform | gridappsd |
GridAPPS-D |
pip install cim-graph installs no database driver. Install the extra of each connection you use, or all for every driver:
All connections are imported from cimgraph.databases. Using a connection without its driver raises an ImportError that names the extra to install.
Architecture¶
All connections implement the ConnectionInterface abstract base class, which defines one API for:
- Connection management:
connect(),disconnect() - Query execution:
execute() - Object retrieval:
get_object(),get_from_triple() - Graph creation:
create_new_graph(),create_distributed_graph() - Graph expansion:
get_all_edges(),get_all_attributes() - Data upload:
upload()
Graph models call these methods, so the same application code works with any connection. Every connection reads its CIMG_* settings (profile, namespace, identifier style, units, URL, credentials, ...) as they are when it is created.
ConnectionInterface Class Diagram¶
classDiagram
class ConnectionInterface {
<<abstract>>
+cim_profile: str
+cim: module
+namespace: str
+iec61970_552: str
+log_level: int
+use_units: bool
+connect()*
+disconnect()*
+execute(query)* QueryResponse
+get_object(mRID, graph)* object
+get_from_triple(subject, predicate, graph)* list
+create_new_graph(container, graph)* Graph
+create_distributed_graph(area, graph)* Graph
+get_all_edges(graph, cim_class)*
+get_all_attributes(graph, cim_class)*
+upload(graph)*
+check_attribute(cim_class, attribute) str
+create_object(graph, class_type, uri) object
+create_edge(graph, cim_class, identifier, attribute, edge_class, edge_mRID) object
+create_reference(graph, cim_class, identifier, attribute, edge_class, edge_id) object
+create_value(graph, cim_class, identifier, attribute, value) value
+add_to_graph(obj, graph)
}
class SPARQLEndpointConnection {
<<abstract>>
+connection_obj: object
#_setup_connection()*
#_execute_raw_query(query)* QueryResponse
#_parse_result_field(result, field)* str
#_update_raw(update)* str
+update(update) str
+parse_node_query(graph, output) Graph
+edge_query_parser(output, graph, cim_class, expand_graph) list
+build_graph_from_list(graph, mrid_list) Graph
+run_batch_queries(queries) list
}
class XMLFile {
+filename: str or list
+namespaces: dict
+model_headers: list
+parse_nodes(element) Identity
+parse_edges(element)
+parse_value(sub_element, cim_class, identifier)
+extract_namespaces_from_header(filename) dict
}
class JSONLDFile {
+filename: str or list
+model_headers: list
+units: dict
}
class BlazegraphConnection {
+url: str
}
class GraphDBConnection {
+url: str
}
class RDFlibConnection {
+filename: str
+use_oxigraph: bool
}
class Neo4jConnection {
+url: str
+database: str
}
class MySQLConnection {
+host: str
+port: int
+database: str
}
class GridappsdConnection {
+url: str
+database: str
}
ConnectionInterface <|-- SPARQLEndpointConnection
ConnectionInterface <|-- XMLFile
ConnectionInterface <|-- JSONLDFile
SPARQLEndpointConnection <|-- BlazegraphConnection
SPARQLEndpointConnection <|-- GraphDBConnection
SPARQLEndpointConnection <|-- RDFlibConnection
ConnectionInterface <|-- Neo4jConnection
ConnectionInterface <|-- MySQLConnection
ConnectionInterface <|-- GridappsdConnection
SPARQL Endpoint Architecture¶
The SPARQL connections (Blazegraph, GraphDB, RDFlib) share one implementation, the SPARQLEndpointConnection abstract class in cimgraph.databases.sparql_endpoint. It provides:
- Common query generation with the
cimgraph.queries.sparqlmodule - Shared parsing of SPARQL query results
- Batched queries, run in parallel
- Template methods: subclasses implement only the database-specific connection details
Database-Specific Implementation Requirements¶
Each SPARQL connection implements four abstract methods:
_setup_connection(): create the database-specific connection object_execute_raw_query(query_message): run a SPARQL query and return the raw results_parse_result_field(result, field_name): read a field value from a query result_update_raw(update_message): run a SPARQL update
get_all_edges and get_all_attributes run their batch queries in parallel threads, so _execute_raw_query must be safe to call from several threads at once (e.g. give each call its own client object), or the subclass overrides run_batch_queries.
Common SPARQL Endpoint Methods¶
These methods are implemented in SPARQLEndpointConnection and shared by the Blazegraph, GraphDB and RDFlib connections. The database pages refer to this section rather than repeating it.
Connection Management¶
connect()¶
Creates the connection object with _setup_connection() if there is none yet. The constructors and the query methods call it, so it rarely needs to be called directly.
Query Execution¶
execute(query_message)¶
Runs a SPARQL SELECT query and returns the results in the SPARQL JSON layout ({'results': {'bindings': [...]}}).
update(update_message)¶
Runs a SPARQL UPDATE (INSERT, DELETE, ...) and returns the database's response. upload() uses it.
Object Retrieval¶
get_object(mRID, graph=None)¶
Returns the object with this mRID, of the class the database gives it, or None if it is not found. The query is built by sparql.get_object_sparql(mRID).
get_from_triple(subject, predicate, graph=None)¶
Returns the values of one attribute of an object: text for primitive values, objects for associations. The query is built by sparql.get_triple_sparql(subject, predicate).
Graph Creation¶
create_new_graph(container, graph=None)¶
Builds the base graph of an EquipmentContainer (typically a Feeder): its equipment, their terminals and connectivity nodes, and optionally measurements, with identifiers but no other attributes. The query is built by sparql.get_all_nodes_from_container(container) and parsed by parse_node_query(). Graph models call it when they are created.
create_distributed_graph(area, graph=None)¶
Builds the graph of a SubSchedulingArea (distributed models). The query is built by sparql.get_all_nodes_from_area(area).
build_graph_from_list(graph, mrid_list)¶
Adds the equipment with the given mRIDs, with their terminals and connectivity nodes, to the graph, 100 mRIDs per query (sparql.get_all_nodes_from_list). It was written for the GridAPPS-D topology processor.
Graph Expansion¶
get_all_edges(graph, cim_class)¶
Reads every attribute and association of all objects of cim_class in the graph, and adds the associated objects to the graph.
- The objects are queried 100 per query (
sparql.get_all_edges_sparql). - Up to
MAX_PARALLEL_QUERIES(8) queries run at once; the results are parsed on the calling thread withedge_query_parser().
get_all_attributes(graph, cim_class)¶
Like get_all_edges, but adds no objects to the graph: an association is set to the referenced object if it is already in the graph, else to its identifier text. Writers serialize that text as a reference. The query is built by sparql.get_all_attributes_sparql.
get_edges_query(graph, cim_class)¶
Returns the edge query for the first 100 objects of cim_class, without running it, for debugging.
Query Parsing¶
parse_node_query(graph, query_output)¶
Parses the results of a node query into the graph: creates the equipment, terminal and connectivity node objects (and measurements, if queried) and links equipment to terminals and terminals to connectivity nodes, in both directions. Classes that are not in the CIM profile are skipped with a validation log message.
edge_query_parser(query_output, graph, cim_class, expand_graph=True)¶
Parses the results of an edge or attribute query. For each result:
- Association: with
expand_graph=True, links the referenced object withcreate_edge(), creating it if needed; withFalse, sets the reference withcreate_reference(). - Enumeration: a value IRI in the enumeration's namespace (or
CIMG_NAMESPACE), e.g.cim:PhaseCode.ABC, is set as the profile's enumeration member. - Primitive value: converted with
create_value().
Returns the created edges.
Data Upload¶
upload(graph)¶
Inserts every object of the graph, with its attributes and associations, as RDF triples: one SPARQL INSERT per object (sparql.upload_triples_sparql(obj)), run with update().
breaker = network.first(cim.Breaker)
network.modify(breaker, 'name', 'Modified Breaker')
database.upload(network.graph)
Large graphs take a long time to upload this way.
Common SPARQL Query Generation¶
The SPARQL connections share the query builders of cimgraph.queries.sparql:
get_object_sparql(mRID): one object by mRIDget_triple_sparql(obj, attribute): one attribute of an objectget_all_nodes_from_container(container): the base graph of a containerget_all_nodes_from_area(area): the base graph of a distributed areaget_all_nodes_from_list(mrid_list, namespace): the base graph of a list of equipmentget_all_edges_sparql(graph, cim_class, uuid_list): attributes and associationsget_all_attributes_sparql(graph, cim_class, uuid_list): attributes, with associations as referencesupload_triples_sparql(obj): the INSERT statement of an object
RDFlibConnection uses its own edge query (cimgraph.queries.rdflib).
UML Sequence Diagrams¶
These diagrams show how the SPARQL connections handle common operations.
Creating a New Graph from Database¶
sequenceDiagram
actor User
participant FeederModel
participant SPARQLEndpoint
participant QueryModule
participant Database
note right of User: Load feeder from database
User ->>+ FeederModel: FeederModel(container, connection)
FeederModel ->>+ SPARQLEndpoint: create_new_graph(container)
SPARQLEndpoint ->> SPARQLEndpoint: add_to_graph(container)
SPARQLEndpoint ->>+ QueryModule: get_all_nodes_from_container(container)
QueryModule -->>- SPARQLEndpoint: SPARQL query string
SPARQLEndpoint ->>+ SPARQLEndpoint: execute(query)
SPARQLEndpoint ->>+ Database: _execute_raw_query(query)
Database -->>- SPARQLEndpoint: query results (JSON)
SPARQLEndpoint -->>- SPARQLEndpoint: QueryResponse
SPARQLEndpoint ->>+ SPARQLEndpoint: parse_node_query(graph, results)
loop for each result
SPARQLEndpoint ->> SPARQLEndpoint: create_object(Equipment)
SPARQLEndpoint ->> SPARQLEndpoint: create_object(Terminal)
SPARQLEndpoint ->> SPARQLEndpoint: create_object(ConnectivityNode)
SPARQLEndpoint ->> SPARQLEndpoint: link Equipment, Terminal and Node
end
SPARQLEndpoint -->>- SPARQLEndpoint: updated graph
SPARQLEndpoint -->>- FeederModel: Graph with base topology
FeederModel -->>- User: FeederModel instance
Expanding the Graph with get_all_edges()¶
sequenceDiagram
actor User
participant FeederModel
participant SPARQLEndpoint
participant QueryModule
participant Database
note right of User: Expand breaker attributes
User ->>+ FeederModel: get_all_edges(cim.Breaker)
FeederModel ->>+ SPARQLEndpoint: get_all_edges(graph, cim.Breaker)
SPARQLEndpoint ->> SPARQLEndpoint: UUIDs of graph[cim.Breaker], in batches of 100
loop for each batch
SPARQLEndpoint ->>+ QueryModule: get_all_edges_sparql(graph, cim.Breaker, batch)
QueryModule -->>- SPARQLEndpoint: SPARQL query
end
par up to 8 queries at once
SPARQLEndpoint ->>+ Database: _execute_raw_query(query)
Database -->>- SPARQLEndpoint: query results
end
loop for each result, on the calling thread
SPARQLEndpoint ->>+ SPARQLEndpoint: edge_query_parser(results)
alt Association
SPARQLEndpoint ->> SPARQLEndpoint: create_edge() to linked object
else Enumeration
SPARQLEndpoint ->> SPARQLEndpoint: set enumeration member
else Primitive value
SPARQLEndpoint ->> SPARQLEndpoint: create_value() with type conversion
end
SPARQLEndpoint -->>- SPARQLEndpoint: batch parsed
end
SPARQLEndpoint -->>- FeederModel: None (graph updated)
FeederModel -->>- User: None
Database Comparison¶
| Feature | XMLFile / JSONLDFile | Blazegraph | GraphDB | RDFlib | Neo4j |
|---|---|---|---|---|---|
| Query language | none (file parser) | SPARQL | SPARQL | SPARQL | Cypher |
| Storage | File | Triple store | Triple store | In-memory triple store | Property graph |
| Server needed | No | Yes (Java) | Yes (Java/Docker) | No | Yes (Java/Docker) |
| Loads | the whole file | queried containers and classes | queried containers and classes | the whole file | queried containers and classes |
| Install extra | none | sparql |
sparql |
rdflib |
neo4j |
Recommended Use Cases¶
- XMLFile / JSONLDFile: quick work with IEEE 13 and 123 bus models, no database setup
- Blazegraph, GraphDB: large models shared through a SPARQL endpoint
- RDFlib: testing SPARQL-based code against a local file
- Neo4j: graph analytics, path finding, community detection
- GridAPPS-D: models served by a GridAPPS-D platform
Environment Variables¶
All connections are configured with environment variables. See Environment Variables for the complete list and defaults.
Common Variables¶
import os
# CIM profile (required)
os.environ['CIMG_CIM_PROFILE'] = 'cimhub_2023'
# Namespace of the cim: prefix (default: http://iec.ch/TC57/CIM100#)
os.environ['CIMG_NAMESPACE'] = 'http://iec.ch/TC57/CIM100#'
# Identifier style: '552-NEW' (default), '552-LEGACY' or 'CGMES'
os.environ['CIMG_IEC61970_552'] = '552-NEW'
# Log level of validation messages (default: WARNING)
os.environ['CIMG_VALIDATION_LOG_LEVEL'] = 'INFO'
Connection Variables¶
| Connection | Variables |
|---|---|
BlazegraphConnection, GraphDBConnection |
CIMG_URL |
Neo4jConnection |
CIMG_URL, CIMG_DATABASE, CIMG_USERNAME, CIMG_PASSWORD |
MySQLConnection |
CIMG_HOST, CIMG_PORT, CIMG_DATABASE, CIMG_USERNAME, CIMG_PASSWORD |
GridappsdConnection |
CIMG_URL, CIMG_HOST, CIMG_PORT, CIMG_DATABASE, CIMG_USERNAME, CIMG_PASSWORD |
XMLFile, JSONLDFile, RDFlibConnection |
none: they take a file name |
For example, for Blazegraph:
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
# Load from XML
file = XMLFile(filename='../../tests/test_models/ieee13.xml')
feeder = cim.Feeder(mRID='49AD8E07-3BF9-A4E2-CB8F-C3722F837B62')
network = FeederModel(container=feeder, connection=file, distributed=False)
print(f"Loaded {len(network.graph[cim.ACLineSegment])} lines")
Loaded 11 lines
Example 2: Blazegraph (SPARQL Endpoint)¶
This example needs a running Blazegraph with the IEEE 13 model loaded (see Blazegraph) and the sparql extra:
import os
os.environ['CIMG_CIM_PROFILE'] = 'cimhub_2023'
os.environ['CIMG_URL'] = 'http://localhost:8889/bigdata/namespace/kb/sparql'
import cimprofiles.cim17.cimhub_2023 as cim
from cimgraph.databases import BlazegraphConnection
from cimgraph.models import FeederModel
database = BlazegraphConnection()
feeder = cim.Feeder(mRID='49AD8E07-3BF9-A4E2-CB8F-C3722F837B62')
network = FeederModel(container=feeder, connection=database)
# Read every attribute and association of the breakers
network.get_all_edges(cim.Breaker)
print(f"Loaded {len(network.graph[cim.Breaker])} breakers")
Example 3: Switching Databases¶
Only the connection changes; the rest of the code stays the same:
from cimgraph.databases import BlazegraphConnection, GraphDBConnection, RDFlibConnection
database = BlazegraphConnection()
# database = GraphDBConnection()
# database = RDFlibConnection(filename='ieee13.xml')
feeder = cim.Feeder(mRID='49AD8E07-3BF9-A4E2-CB8F-C3722F837B62')
network = FeederModel(container=feeder, connection=database)
Additional Documentation¶
For each connection:
- Environment Variables Configuration
- Blazegraph Database
- Neo4j Database
- GraphDB Database
- MySQL Database
- GridAPPS-D Integration
- XML File Parser
- JSON-LD File Parser
- RDFLib Parser
For usage examples:
<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>