JSON-LD File Parser¶
JSONLDFile reads CIM JSON-LD files into a graph, and cimgraph.utils.write_json_ld writes a graph model to one. The files follow the CGMES JSON-LD draft style: a published @context URL, "urn:uuid:..." string references, and a dcat:Dataset header that names the units the numbers are written in. Neither needs a database or an install extra.
Reading a JSON-LD file¶
Select the CIM profile, create the connection with the file name (or a list of files to load into one graph) and pass it to a graph model. A missing file raises FileNotFoundError and a malformed one json.JSONDecodeError.
import os
os.environ['CIMG_CIM_PROFILE'] = 'cimhub_2023'
import cimprofiles.cim17.cimhub_2023 as cim
from cimgraph.databases import JSONLDFile
from cimgraph.models import FeederModel
feeder = cim.Feeder(mRID='49AD8E07-3BF9-A4E2-CB8F-C3722F837B62')
network = FeederModel(container=feeder,
connection=JSONLDFile('../../tests/test_models/ieee13.jsonld'),
distributed=False)
print(f'{len(network.graph[cim.ACLineSegment])} lines, {len(network.graph[cim.EnergyConsumer])} loads')
11 lines, 16 loads
Unit values are CIMUnits stored in base SI units. Convert them with .to():
line = network.first(cim.ACLineSegment)
load = network.first(cim.EnergyConsumer)
print(f'Line {line.name}: {line.length.to("ft"):.0f} ft')
print(f'Load {load.name}: {load.p.to("kW"):.0f} kW, {load.q.to("kVAr"):.0f} kVAr')
Line 645646: 300 ft Load 646: 230 kW, 132 kVAr
Model headers¶
Each file's dcat:Dataset header is read into JSONLDFile.model_headers, one ModelHeader per file. ieee13.jsonld is an older file without a header, so its fields are empty and its numbers are read in the profile's default units (base SI for cimhub_2023).
network.connection.model_headers
[ModelHeader(full_model_uuid=None, created=None, description=None, model_name=None, authority=None, authority_uuid=None)]
Writing a JSON-LD file¶
write_json_ld(network, filename, indent=4, convention=None, header=None, contexts=None) writes the model with the header as the top-level map and the objects in its @graph.
conventionnames the units convention of the numbers.cimhub_2023has'si'(the default: W, V, m) and'distribution'(kW, kVAr, kVA, line constants per km, wire sizes in mm). The header names the convention's units vocabularies indct:conformsTo.headeradds or replaces header properties. A fixed@id,dct:identifieranddct:issuedmake repeated exports of the same model identical files; by default they are a new UUID and the export time.contextsare further JSON-LD contexts, for header prefixes that the profile's context does not define.
import json
import tempfile
from pathlib import Path
from cimgraph.utils import write_json_ld
output_dir = Path(tempfile.mkdtemp())
path = output_dir / 'ieee13.jsonld'
write_json_ld(network, str(path), convention='distribution', header={
'@id': 'urn:uuid:5a0c3a4e-0000-5000-8000-000000000001',
'dct:identifier': '5a0c3a4e-0000-5000-8000-000000000001',
'dct:issued': '2026-11-01T00:00:00Z',
'dcat:isVersionOf': 'https://example.org/models/ieee13',
})
document = json.loads(path.read_text())
header = {key: value for key, value in document.items() if key != '@graph'}
print(json.dumps(header, indent=2))
{
"@context": "https://pnnl-cim-tools.github.io/CIM-Profiles/cimhub_2023/0.2.0/context.jsonld",
"@id": "urn:uuid:5a0c3a4e-0000-5000-8000-000000000001",
"@type": [
"dcat:Dataset",
"http://www.w3.org/2004/03/trix/rdfg-1/Graph"
],
"dct:identifier": "5a0c3a4e-0000-5000-8000-000000000001",
"dct:issued": "2026-11-01T00:00:00Z",
"md:Model.modelingAuthoritySet": "https://github.com/PNNL-CIM-Tools/CIM-Graph",
"dct:conformsTo": [
"https://pnnl-cim-tools.github.io/CIM-Profiles/cimhub_2023/0.2.0/units-distribution.jsonld"
],
"dcat:distribution": {
"@type": "dcat:Distribution",
"dct:conformsTo": [
"https://pnnl-cim-tools.github.io/CIM-Profiles/cimhub_2023/0.2.0/units-distribution.jsonld"
]
},
"dcat:isVersionOf": "https://example.org/models/ieee13"
}
The load is written in kW, as the distribution convention says:
written_load = next(node for node in document['@graph'] if node['@id'] == f'urn:uuid:{load.uri()}')
print(json.dumps(written_load, indent=2))
{
"@id": "urn:uuid:0BC9183A-9067-4E06-AA5B-48DC2AB30C80",
"@type": "cim:EnergyConsumer",
"cim:EnergyConsumer.customerCount": "1",
"cim:EnergyConsumer.grounded": "false",
"cim:EnergyConsumer.p": "230",
"cim:EnergyConsumer.phaseConnection": "cim:PhaseShuntConnectionKind.D",
"cim:EnergyConsumer.q": "132",
"cim:EnergyConsumer.LoadResponse": "urn:uuid:E84837F3-04A7-414B-A72C-B429DF35BBBF",
"cim:ConductingEquipment.BaseVoltage": "urn:uuid:2A158E0C-CD01-4A50-AEBA-59D761FCF15D",
"cim:Equipment.EquipmentContainer": "urn:uuid:49AD8E07-3BF9-A4E2-CB8F-C3722F837B62",
"cim:PowerSystemResource.Location": "urn:uuid:9E735173-F2E5-408C-8279-54ED0D3BBDD1",
"cim:IdentifiedObject.mRID": "0BC9183A-9067-4E06-AA5B-48DC2AB30C80",
"cim:IdentifiedObject.name": "646"
}
Reading the file back gives the header and the same values in base SI units:
reader = JSONLDFile(str(path))
print(reader.model_headers)
copy = FeederModel(container=feeder, connection=reader, distributed=False)
print(f'{copy.graph[cim.EnergyConsumer][load.identifier].p.to("kW"):.0f} kW')
[ModelHeader(full_model_uuid='5a0c3a4e-0000-5000-8000-000000000001', created='2026-11-01T00:00:00Z', description=None, model_name=None, authority='https://github.com/PNNL-CIM-Tools/CIM-Graph', authority_uuid='bdf23f0c-0c08-525b-846a-e05b60f8af02')] 230 kW
CGMES-style files¶
JSONLDFile also reads files in the Nordic44 layout, where the header is a node in @graph and its dct:conformsTo names the CGMES vocabularies (kV, MW, km). cgmes_style_eq.jsonld is a small CGMES 3.0 Equipment file of this kind. Its @context is a URL, which is resolved from the cimprofiles offline cache.
os.environ['CIMG_CIM_PROFILE'] = 'cgmes_3_0_0'
os.environ['CIMG_AUTHORITY_FROM_IS_VERSION_OF'] = 'true' # its authority is in dcat:isVersionOf
import cimprofiles.cim17.cgmes_3_0_0 as cgmes
from cimgraph.models import NodeBreakerModel
reader = JSONLDFile('../../tests/test_models/cgmes_style_eq.jsonld')
print(reader.model_headers)
print('nominalVoltage is written in', reader.units['BaseVoltage.nominalVoltage'])
[ModelHeader(full_model_uuid='7b1e0c2a-1d3f-4b6e-9a51-000000000001', created=None, description=None, model_name=None, authority='https://github.com/PNNL-CIM-Tools/CIM-Graph/tests', authority_uuid='bdb0ee55-1d03-5def-af93-c8e742aa1619')] nominalVoltage is written in kV
eq_model = NodeBreakerModel(container=None, connection=reader, distributed=False)
line = eq_model.first(cgmes.ACLineSegment)
machine = eq_model.first(cgmes.SynchronousMachine)
print(f'{line.name}: {line.length.to("km")} km, {line.BaseVoltage.nominalVoltage.to("kV")} kV')
print(f'{machine.name}: {machine.ratedS.to("MVA")} MVA')
420NORTH-SOUTH 1: 12.5 km, 420.0 kV NORTH G1: 680.0 MVA
The header's model authority (md:Model.modelingAuthoritySet) sets the model scope used to seed UUIDs, as md:FullModel does for XMLFile. Its dct:title is the file name (description), so the model name stays as it is. dcat:isVersionOf names a model series, so it is the authority only with CIMG_AUTHORITY_FROM_IS_VERSION_OF=true, as set above for this CGMES file. Without it, a header that has no md:Model.modelingAuthoritySet leaves the model scope as it is, with a warning:
from cimgraph.core import get_model_authority
get_model_authority()
'https://github.com/PNNL-CIM-Tools/CIM-Graph/tests'
Remote contexts¶
Contexts and unit vocabularies that are not in the cimprofiles offline cache are fetched only with CIMG_ALLOW_REMOTE_CONTEXT=true. Otherwise reading such a file fails with an error that names the URL.
Files loaded together into one JSONLDFile must use the same units; files that write an attribute in different units raise ValueError.
See also: XML File Parser, Environment Variables.
<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>