Using CIM Objects¶
Once you have a CIM profile imported into your Python environment, you can create, manipulate, and query CIM objects. This notebook explores the fundamental operations for working with CIM dataclass objects in CIMantic Graphs.
All CIM objects inherit from the Identity base class (cimprofiles.identity.Identity), which provides object identification, UUID management, and JSON-LD serialization.
The Identity Base Class¶
Every CIM object inherits from Identity, which provides core functionality:
Key Features:¶
- UUID Management - Every object has an
identifier, a UUID (RFC 9562), either given or derived deterministically from the object's mRID or name - URI Generation -
uri()returns the identifier as text for use in RDF and graph databases - JSON-LD Serialization -
repr()gives a minimal JSON-LD form with@idand@type - Pretty Printing -
pprint()gives a human-readable display of objects - Dictionary Conversion -
to_dict()andto_json()convert objects to Python dictionaries and JSON
Identity Class Hierarchy:¶
classDiagram
class Identity{
+ identifier: UUID
+ uuid(mRID, uri, name, seed) UUID
+ uri() str
+ pprint(print_mRID)
+ to_json(show_mRID, show_empty, use_names) str
+ to_dict(show_mRID, show_empty, use_names) dict
+ expand(max_items) dict
}
class IdentifiedObject{
+ mRID: str
+ name: str
+ description: str
}
Identity <|-- IdentifiedObject
IdentifiedObject <|-- PowerSystemResource
PowerSystemResource <|-- Equipment
Equipment <|-- ConductingEquipment
ConductingEquipment <|-- Conductor
Conductor <|-- ACLineSegment
Creating CIM Objects¶
Let's start by importing a profile and creating a basic object. Without an mRID, the object's UUID is derived from its name:
import cimprofiles.cim17.cimhub_2023 as cim
from cimprofiles.identity import Identity, seeded_uuid
line1 = cim.ACLineSegment(name='Line_001')
print(f'Is an Identity: {isinstance(line1, Identity)}')
print(' -> '.join(cls.__name__ for cls in type(line1).__mro__[:-1]))
line1.pprint()
Is an Identity: True
ACLineSegment -> Conductor -> ConductingEquipment -> Equipment -> PowerSystemResource -> IdentifiedObject -> Identity
{
"@id": "3e40d3ac-fbc2-50b3-83b3-2bac9058ca05",
"@type": "ACLineSegment",
"name": "Line_001"
}
Deterministic UUIDs¶
An object built without a UUID gets a version 5 (name-based) UUID, seeded from the model authority (CIMG_MODEL_AUTHORITY), the model name (CIMG_MODEL_NAME), the class, and one key:
- Name route - with no mRID, the name is the key. The same name gives the same UUID on every run and every machine; a renamed object is a different object with a different UUID.
- mRID route - with an mRID that is not a UUID, the mRID is the key and the name is not used, so a renamed object keeps its UUID.
- An mRID that is a UUID is used directly as the identifier.
- With neither an mRID nor a name, the identifier is a random (version 4) UUID.
The default model authority is https://github.com/PNNL-CIM-Tools/CIM-Graph and the default model name is empty. Set the environment variables, or call cimgraph.core.set_model_scope(authority, model_name), before creating objects to scope the UUIDs to your own models.
same_name = cim.ACLineSegment(name='Line_001')
renamed = cim.ACLineSegment(name='Line_001a')
print(f'Name route: {line1.identifier} (UUID version {line1.identifier.version})')
print(f' same name gives the same UUID: {same_name.identifier == line1.identifier}')
print(f' renamed gives the same UUID: {renamed.identifier == line1.identifier}')
line2 = cim.ACLineSegment(mRID='LINE_002', name='Line_002')
line2_renamed = cim.ACLineSegment(mRID='LINE_002', name='Main feeder')
print(f'mRID route: {line2.identifier} (UUID version {line2.identifier.version})')
print(f' renamed gives the same UUID: {line2_renamed.identifier == line2.identifier}')
print(f' equals seeded_uuid(): {line2.identifier == seeded_uuid("ACLineSegment", mRID="LINE_002")}')
no_key = cim.ACLineSegment()
print(f'No mRID or name: random UUID version {no_key.identifier.version}')
Name route: 3e40d3ac-fbc2-50b3-83b3-2bac9058ca05 (UUID version 5) same name gives the same UUID: True renamed gives the same UUID: False mRID route: e984859c-3531-539a-9dab-a2aa04bdfdff (UUID version 5) renamed gives the same UUID: True equals seeded_uuid(): True No mRID or name: random UUID version 4
When the mRID is a UUID, it becomes the identifier. pprint(print_mRID=True) also shows the identifier and mRID:
line3 = cim.ACLineSegment(
mRID='12345678-1234-1234-1234-123456789abc',
name='Line_003',
description='Main feeder line from substation A to load center B'
)
line3.pprint(print_mRID=True)
print(f'Object URI: {line3.uri()}')
print(f'Object mRID: {line3.mRID}')
print(f'Object name: {line3.name}')
{
"@id": "12345678-1234-1234-1234-123456789abc",
"@type": "ACLineSegment",
"identifier": "12345678-1234-1234-1234-123456789abc",
"mRID": "12345678-1234-1234-1234-123456789abc",
"description": "Main feeder line from substation A to load center B",
"name": "Line_003"
}
Object URI: 12345678-1234-1234-1234-123456789abc
Object mRID: 12345678-1234-1234-1234-123456789abc
Object name: Line_003
Objects read from a file keep the UUID in their rdf:ID or rdf:about. See the XML File Parser notebook for reading models.
Working with Attributes¶
CIM dataclasses have three types of fields:
- Attributes - Simple data values (strings, numbers, booleans) and physical quantities
- Associations - References to other CIM objects
- Enumerations - Predefined sets of values
Each field includes metadata describing its UML type, cardinality, and inverse relationships (for associations).
Using Attribute Utilities¶
cimgraph.core.attribute_utils provides functions to inspect attribute metadata programmatically. These are especially useful when building generic tools that work with any CIM profile:
get_attr_field_type()- Returns the Python field type (Optional,list)get_attr_uml_type()- Returns the UML type (Attribute,Association,enumeration)get_attr_datatype()- Returns the datatype(s) of the attributeget_attr_inverse()- Returns the inverse relationship for associations
Let's see these in action:
from cimgraph.core.attribute_utils import (get_attr_datatype, get_attr_field_type,
get_attr_inverse, get_attr_uml_type)
print('Attribute inspection for ACLineSegment.name:')
print(f' Field type: {get_attr_field_type(cim_class=cim.ACLineSegment, attribute="name")}')
print(f' UML type: {get_attr_uml_type(cim_class=cim.ACLineSegment, attribute="name")}')
print(f' Datatype: {get_attr_datatype(cim_class=cim.ACLineSegment, attribute="name")}')
print('Association inspection for Terminal.Measurements:')
print(f' Field type: {get_attr_field_type(cim_class=cim.Terminal, attribute="Measurements")}')
print(f' UML type: {get_attr_uml_type(cim_class=cim.Terminal, attribute="Measurements")}')
print(f' Datatype: {get_attr_datatype(cim_class=cim.Terminal, attribute="Measurements")}')
print(f' Inverse: {get_attr_inverse(cim_class=cim.Terminal, attribute="Measurements")}')
Attribute inspection for ACLineSegment.name: Field type: Optional UML type: Attribute Datatype: ['str'] Association inspection for Terminal.Measurements: Field type: list UML type: Association Datatype: ['Measurement'] Inverse: Measurement.Terminal
Working with Associations¶
Associations represent relationships between CIM objects. In CIMantic Graphs, associations can reference objects in two ways:
- By object reference - Using the actual Python object
- By URI string - Using the referenced object's UUID text, from
uri()
Object references are more convenient for in-memory graphs, since they can be navigated directly. URI strings are useful when the referenced object has not been loaded.
# Create a line segment
line = cim.ACLineSegment(mRID='line-001', name='Feeder_Line_1')
# Create terminals for the line (one at each end)
term1 = cim.Terminal(mRID='term-001', name='Line_Terminal_1', sequenceNumber=1)
term2 = cim.Terminal(mRID='term-002', name='Line_Terminal_2', sequenceNumber=2)
# Associate terminals with the line using object references
line.Terminals = [term1, term2]
# Associate line with terminals (inverse relationship)
term1.ConductingEquipment = line
term2.ConductingEquipment = line
print('Line created with terminals:')
line.pprint()
print('Terminal 1:')
term1.pprint()
Line created with terminals:
{
"@id": "62d1fade-3703-5c1e-ba4d-638ac7adcce9",
"@type": "ACLineSegment",
"name": "Feeder_Line_1",
"Terminals": [
{
"@id": "c1b865e9-1472-57ff-b7fa-cda218b42327",
"@type": "Terminal"
},
{
"@id": "fee2e55a-f6e6-52d0-a959-2473234ed6fa",
"@type": "Terminal"
}
]
}
Terminal 1:
{
"@id": "c1b865e9-1472-57ff-b7fa-cda218b42327",
"@type": "Terminal",
"name": "Line_Terminal_1",
"sequenceNumber": "1",
"ConductingEquipment": {
"@id": "62d1fade-3703-5c1e-ba4d-638ac7adcce9",
"@type": "ACLineSegment"
}
}
# Alternative: use URI strings for associations
line4 = cim.ACLineSegment(mRID='line-004', name='Feeder_Line_4')
term3 = cim.Terminal(
mRID='term-003',
name='Line_Terminal_3',
sequenceNumber=1,
ConductingEquipment=line4.uri() # URI string instead of an object reference
)
line4.Terminals = [term3.uri()]
print('Line created with URI-based associations:')
line4.pprint()
print('Terminal 3:')
term3.pprint()
Line created with URI-based associations:
{
"@id": "5cfae17f-957e-5444-be4e-b5e2a504e112",
"@type": "ACLineSegment",
"name": "Feeder_Line_4",
"Terminals": [
"ca7244da-8ad2-55bd-ae68-a5cec793943c"
]
}
Terminal 3:
{
"@id": "ca7244da-8ad2-55bd-ae68-a5cec793943c",
"@type": "Terminal",
"name": "Line_Terminal_3",
"sequenceNumber": "1",
"ConductingEquipment": "5cfae17f-957e-5444-be4e-b5e2a504e112"
}
Object Serialization¶
CIM objects can be serialized to several formats:
repr(obj)- a minimal JSON-LD form with@idand@type, compatible with RDF and semantic web technologiesobj.pprint()- formatted JSON of the object's non-empty attributesobj.to_dict()/obj.to_json()- a dictionary or JSON string, by default including the identifier, mRID and empty attributes
To write whole models as CIM XML or JSON-LD files, see the File Writers notebook.
import json
transformer = cim.PowerTransformer(
mRID='xfmr-001',
name='Substation_Transformer_1',
description='138kV/12.47kV substation transformer'
)
print('JSON-LD representation (repr):')
print(repr(transformer))
print('Formatted JSON (pprint):')
transformer.pprint()
print('Dictionary representation (to_dict without empty attributes):')
print(json.dumps(transformer.to_dict(show_empty=False), indent=2))
JSON-LD representation (repr):
{"@id": "b9894bff-f9c2-5db3-9dcb-1075e27dc30e", "@type": "PowerTransformer"}
Formatted JSON (pprint):
{
"@id": "b9894bff-f9c2-5db3-9dcb-1075e27dc30e",
"@type": "PowerTransformer",
"description": "138kV/12.47kV substation transformer",
"name": "Substation_Transformer_1"
}
Dictionary representation (to_dict without empty attributes):
{
"@id": "b9894bff-f9c2-5db3-9dcb-1075e27dc30e",
"@type": "PowerTransformer",
"identifier": "b9894bff-f9c2-5db3-9dcb-1075e27dc30e",
"mRID": "xfmr-001",
"description": "138kV/12.47kV substation transformer",
"name": "Substation_Transformer_1"
}
Best Practices for Working with CIM Objects¶
1. Give Persistent Objects a Stable Key¶
Objects built with an mRID or a name get the same UUID on every run. For objects that will be saved to databases or exchanged between systems, prefer an explicit mRID, so that renaming an object does not change its identity:
# Good - the UUID is seeded from the mRID and survives a rename
line = cim.ACLineSegment(mRID='line-001', name='Feeder_1')
# Deterministic, but renaming the line gives it a new UUID
line = cim.ACLineSegment(name='Feeder_1')
# Avoid for persistent data - a random UUID on every run
line = cim.ACLineSegment()
2. Use Consistent mRID Formatting¶
mRIDs are free-form strings, unique within the model (CIM 18). Follow a consistent format across your organization, for example:
- UUID format: 12345678-1234-1234-1234-123456789abc
- Hierarchical: substation-A_feeder-1_line-001
Don't add a leading underscore or a urn:uuid: prefix to an mRID: these belong to the file serialization style, and the writers add them (CIMG_IEC61970_552). An mRID is used verbatim, so _line-001 and line-001 give different UUIDs.
3. Maintain Bidirectional Associations¶
When creating associations, remember to set both directions:
# Set both sides of the relationship
terminal.ConductingEquipment = line # Forward
line.Terminals.append(terminal) # Inverse
4. Choose the Right Association Format¶
- Use object references for in-memory models (easier to navigate)
- Use URI strings for objects that are not loaded
- Be consistent within a single model
5. Leverage Type Hints and IDEs¶
The generated dataclasses include full type hints. Use a modern IDE (VS Code, PyCharm) to get: - Autocomplete for attributes - Type checking warnings - Inline documentation from docstrings
6. Use Attribute Utilities for Generic Code¶
When writing tools that work with any CIM profile, use the attribute utility functions instead of hardcoding field names:
Summary¶
This notebook covered the fundamentals of working with CIM objects in CIMantic Graphs:
Key Concepts:¶
-
Identity Base Class - All CIM objects inherit from
Identity, providing UUID management, URI generation, and JSON-LD serialization -
Object Creation - Objects built with an mRID or a name get deterministic (version 5) UUIDs; an mRID that is a UUID is used directly
-
Attributes and Metadata - Each field includes metadata about its UML type, cardinality, and inverse relationships
-
Associations - Relationships between objects can use object references or URI strings
-
Serialization - Objects support JSON-LD format and dictionary conversion
-
Inspection Tools - Attribute utilities enable generic code that works with any profile
Next Steps:¶
- Using Incrementals - Track and manage model changes
- Using Units - Work with physical quantities and unit conversion
- Feeder Model - Build complete network models
<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>