Units and Quantities in CIM¶
In CIM, a physical quantity such as Voltage, ActivePower or Length is a datatype: a value with a unit symbol (UnitSymbol, e.g. V) and a unit multiplier (UnitMultiplier, e.g. k). The CIM-Graph profiles in the cimprofiles package define each datatype as a subclass of CIMUnit (cimprofiles.units), backed by the Pint units library.
A CIMUnit stores its value in its datatype's unit. That is the SI base unit (V, W, VAr, VA, ohm, S, m, ...) for almost every datatype; a few fix a multiplier, such as KiloActivePower (kW).
The rules in short:
- Importing data: give the source unit,
cim.ActivePower(5.5, 'MW'). - Exporting data: convert with
.to(),load.p.to('MW'), which returns a float. - Never scale by
1e3or1e6by hand. - Compare with a number through
.to()orfloat(), never theCIMUnititself.
import os
os.environ['CIMG_CIM_PROFILE'] = 'cimhub_2023'
import cimprofiles.cim17.cimhub_2023 as cim
from cimprofiles.units import CIMUnit
Creating quantities¶
The constructor takes a value and the unit it is in (input_unit, default: the datatype's unit). The unit can also be split into a CIM multiplier and symbol, and the value can be a Pint Quantity or another CIMUnit:
voltage = cim.Voltage(12.47, 'kV')
print(voltage) # stored in volts
print(cim.Voltage(12470)) # no unit: the datatype's unit
print(cim.Voltage(12.47, input_unit='V', input_multiplier='k'))
print(cim.Voltage(voltage.quantity)) # from a Pint Quantity
print(cim.Length(1, 'mi'), cim.ReactivePower(2, 'MVAr'), cim.ApparentPower(50, 'MVA'))
print(voltage.unit, voltage.multiplier, isinstance(voltage, CIMUnit))
12470.0 volt 12470.0 volt 12470.0 volt 12470.0 volt 1609.344 meter 2000000.0 VAr 50000000.0 volt_ampere UnitSymbol.V UnitMultiplier.none True
Reading values¶
.to(unit) returns the value as a float in any unit of the same dimension. float() and .value give the stored value, and .quantity is the Pint Quantity:
print(voltage.to('kV'), voltage.to('V'), voltage.to('MV'))
print(float(voltage), voltage.value)
print(repr(voltage.quantity))
12.47 12470.0 0.01247 12470.0 12470.0 <Quantity(12470.0, 'volt')>
Comparing with numbers¶
A CIMUnit equals another CIMUnit of the same value, but never compare it with a raw number. Ordering (voltage < 13000) and arithmetic (voltage + 1) raise TypeError, and so does voltage == 12470.0. Convert first:
print(voltage == cim.Voltage(12470)) # same datatype and value
print(voltage.to('kV') > 12) # compare in a stated unit
print(float(voltage) == 12470.0) # or in the stored unit
True True True
Units on CIM objects¶
CIM attributes take quantities of their datatype. When CIMG_USE_UNITS is true (the default), the file and database readers also create CIMUnit values, so attributes read from a model behave the same way.
line = cim.ACLineSegment(
name='line_1',
r=cim.Resistance(0.185, 'ohm'),
x=cim.Reactance(0.382, 'ohm'),
length=cim.Length(2.5, 'km'),
)
load = cim.EnergyConsumer(name='load_1', p=cim.ActivePower(1.5, 'MW'), q=cim.ReactivePower(500, 'kVAr'))
print(f'Line: r = {line.r.to("ohm")} ohm, length = {line.length.to("km")} km = {line.length.to("mi"):.3f} mi')
print(f'Load: p = {load.p.to("kW")} kW, q = {load.q.to("MVAr")} MVAr')
Line: r = 0.185 ohm, length = 2.5 km = 1.553 mi Load: p = 1500.0 kW, q = 0.5 MVAr
Calculations¶
CIMUnit has no arithmetic operators. Calculate with the Pint quantities (.quantity), which check dimensions, and wrap the result in the datatype it should be. A result of the wrong dimension raises Pint's DimensionalityError.
Three-phase rated current, I = S / (√3 · V):
import math
rated_s = cim.ApparentPower(50, 'MVA')
rated_u = cim.Voltage(138, 'kV')
rated_i = cim.CurrentFlow(rated_s.quantity / (math.sqrt(3) * rated_u.quantity))
print(f'Rated current: {rated_i.to("A"):.1f} A')
Rated current: 209.2 A
Per-unit impedances (as in MATPOWER or PSS/E data) convert to ohms through the base impedance, Z_base = V_base² / S_base:
base_power = cim.ApparentPower(100, 'MVA')
base_impedance = cim.Impedance(rated_u.quantity ** 2 / base_power.quantity)
r_pu = 0.01
r = cim.Resistance(r_pu * base_impedance.to('ohm'), 'ohm')
print(f'Z_base = {base_impedance.to("ohm"):.2f} ohm, r = {r_pu} pu = {r.to("ohm"):.4f} ohm')
print(f'Back to per unit: {r.to("ohm") / base_impedance.to("ohm"):.4f} pu')
Z_base = 190.44 ohm, r = 0.01 pu = 1.9044 ohm Back to per unit: 0.0100 pu
Other quantities follow the same pattern, such as per-length line constants and energy:
r_per_length = cim.ResistancePerLength(line.r.quantity / line.length.quantity)
print(f'r = {r_per_length.to("ohm/km"):.4f} ohm/km')
energy = cim.RealEnergy(load.p.quantity * cim.Hours(24, 'h').quantity)
print(f'Energy in a day: {energy.to("MWh"):.1f} MWh')
r = 0.0740 ohm/km Energy in a day: 36.0 MWh
import tempfile
from cimgraph.models import FeederModel
from cimgraph.utils import write_json_ld, write_xml
network = FeederModel(connection=None, container=cim.Feeder(name='demo'), distributed=False)
network.create(cim.EnergyConsumer, name='load_1', p=cim.ActivePower(150, 'kW'), q=cim.ReactivePower(50, 'kVAr'))
network.create(cim.OverheadWireInfo, name='wire_1', radius=cim.Length(5, 'mm'))
output_dir = tempfile.mkdtemp()
xml_file = os.path.join(output_dir, 'demo.xml')
write_xml(network, xml_file)
for row in open(xml_file):
if 'EnergyConsumer.p' in row or 'EnergyConsumer.q' in row or 'WireInfo.radius' in row:
print(row.strip())
<cim:EnergyConsumer.p>150000.0</cim:EnergyConsumer.p> <cim:EnergyConsumer.q>50000.0</cim:EnergyConsumer.q> <cim:WireInfo.radius>0.005</cim:WireInfo.radius>
JSON-LD units conventions¶
JSON-LD files are written in the units of a units convention: a publishing convention that each profile defines, per quantity kind and per property, so a file can use the units its community expects. The convention's units vocabulary is named in the file header's dct:conformsTo, and JSONLDFile converts the numbers back when it reads the file, so in Python the values are the same CIMUnits whichever convention was used.
- The default is the profile's default convention: base SI for most profiles (
si), and the CGMES units (MW, kV, km, ...) forcgmes_3_0_0. write_json_ld(..., convention='distribution')(cimhub_2023,cimhub_2026) writes kW, kVAr, kVA and kWh, line constants per km (ohm/km, uS/km), and wire and cable sizes in mm.
import json
def show_units(filename):
document = json.load(open(filename))
print('dct:conformsTo:', document['dct:conformsTo'])
for node in document['@graph']:
for key, value in node.items():
if key in ('cim:EnergyConsumer.p', 'cim:EnergyConsumer.q', 'cim:WireInfo.radius'):
print(f' {key}: {value}')
json_file = os.path.join(output_dir, 'demo.jsonld')
for convention in [None, 'distribution']:
write_json_ld(network, json_file, convention=convention)
print(f'convention={convention!r}')
show_units(json_file)
convention=None dct:conformsTo: ['https://pnnl-cim-tools.github.io/CIM-Profiles/cimhub_2023/0.2.0/units-si.jsonld'] cim:EnergyConsumer.p: 150000 cim:EnergyConsumer.q: 50000 cim:WireInfo.radius: 0.005 convention='distribution' dct:conformsTo: ['https://pnnl-cim-tools.github.io/CIM-Profiles/cimhub_2023/0.2.0/units-distribution.jsonld'] cim:EnergyConsumer.p: 150 cim:EnergyConsumer.q: 50 cim:WireInfo.radius: 5
Reading the distribution file back gives the same quantities:
from cimgraph.databases import JSONLDFile
read_back = FeederModel(connection=JSONLDFile(filename=json_file), container=cim.Feeder(), distributed=False)
load_1 = read_back.first(cim.EnergyConsumer)
wire_1 = read_back.first(cim.OverheadWireInfo)
print(f'p = {load_1.p} = {load_1.p.to("kW")} kW')
print(f'radius = {wire_1.radius} = {wire_1.radius.to("mm")} mm')
p = 150000.0 watt = 150.0 kW radius = 0.005 meter = 5.0 mm
Custom power system units¶
Pint's registry is extended with power engineering units in cimprofiles/units/cim_units/units.txt, such as VAr and VArh for reactive power and energy, VA and VAh for apparent power and energy, and ratios such as VPerV. Reactive units carry a dimensionless imaginary factor, so VAr converts like watts in calculations (e.g. S = √(P² + Q²)).
Summary¶
- CIM quantities are
CIMUnitsubclasses (cimprofiles.units) that store values in their datatype's unit, almost always base SI. - Create them with the source unit,
cim.ActivePower(5.5, 'MW'); read them with.to('MW'); compare through.to()orfloat(). - Calculate with
.quantityand wrap the result in its datatype. - CIM XML holds plain numbers in base SI units. JSON-LD uses a units convention (
write_json_ld(..., convention=...)), named in its header and converted back on read.
<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>