cimhub_gdm 2.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. cimhub_gdm/__init__.py +15 -0
  2. cimhub_gdm/exporter/__init__.py +5 -0
  3. cimhub_gdm/exporter/bus.py +68 -0
  4. cimhub_gdm/exporter/capacitor.py +174 -0
  5. cimhub_gdm/exporter/cim_to_gdm.py +98 -0
  6. cimhub_gdm/exporter/der.py +233 -0
  7. cimhub_gdm/exporter/fills.py +104 -0
  8. cimhub_gdm/exporter/geometry.py +181 -0
  9. cimhub_gdm/exporter/line.py +167 -0
  10. cimhub_gdm/exporter/load.py +99 -0
  11. cimhub_gdm/exporter/naming.py +43 -0
  12. cimhub_gdm/exporter/reactor.py +69 -0
  13. cimhub_gdm/exporter/regulator.py +203 -0
  14. cimhub_gdm/exporter/shared.py +116 -0
  15. cimhub_gdm/exporter/shell.py +32 -0
  16. cimhub_gdm/exporter/slots.py +42 -0
  17. cimhub_gdm/exporter/source.py +95 -0
  18. cimhub_gdm/exporter/switch.py +189 -0
  19. cimhub_gdm/exporter/time_series.py +91 -0
  20. cimhub_gdm/exporter/transformer.py +271 -0
  21. cimhub_gdm/gdm_reader.py +14 -0
  22. cimhub_gdm/gdm_writer.py +14 -0
  23. cimhub_gdm/importer/__init__.py +5 -0
  24. cimhub_gdm/importer/bus.py +51 -0
  25. cimhub_gdm/importer/capacitor.py +211 -0
  26. cimhub_gdm/importer/der.py +223 -0
  27. cimhub_gdm/importer/gdm_to_cim.py +242 -0
  28. cimhub_gdm/importer/line.py +297 -0
  29. cimhub_gdm/importer/load.py +176 -0
  30. cimhub_gdm/importer/network.py +90 -0
  31. cimhub_gdm/importer/reactor.py +62 -0
  32. cimhub_gdm/importer/regulator.py +258 -0
  33. cimhub_gdm/importer/shared.py +197 -0
  34. cimhub_gdm/importer/source.py +99 -0
  35. cimhub_gdm/importer/switch.py +187 -0
  36. cimhub_gdm/importer/time_series.py +157 -0
  37. cimhub_gdm/importer/transformer.py +388 -0
  38. cimhub_gdm-2.1.0a1.dist-info/METADATA +134 -0
  39. cimhub_gdm-2.1.0a1.dist-info/RECORD +42 -0
  40. cimhub_gdm-2.1.0a1.dist-info/WHEEL +5 -0
  41. cimhub_gdm-2.1.0a1.dist-info/licenses/LICENSE +28 -0
  42. cimhub_gdm-2.1.0a1.dist-info/top_level.txt +1 -0
cimhub_gdm/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """CIMHub GDM: grid-data-models DistributionSystem <-> cim18v17 (importer builder-native, exporter on the core
2
+ getters)."""
3
+
4
+ import importlib.metadata
5
+
6
+ __version__ = importlib.metadata.version("cimhub_gdm")
7
+
8
+ from cimhub_core.time_points import read_time_points, write_time_points
9
+ from cimhub_gdm.exporter import GdmExporter, cim_to_gdm
10
+ from cimhub_gdm.gdm_reader import read_gdm
11
+ from cimhub_gdm.gdm_writer import write_gdm
12
+ from cimhub_gdm.importer import GdmImporter, gdm_to_cim
13
+
14
+ __all__ = ["GdmExporter", "GdmImporter", "cim_to_gdm", "gdm_to_cim", "read_gdm", "read_time_points", "write_gdm",
15
+ "write_time_points"]
@@ -0,0 +1,5 @@
1
+ """cim18v17 → GDM DistributionSystem, through the core getters (``docs/EXPORT_PLAN.md``)."""
2
+
3
+ from cimhub_gdm.exporter.cim_to_gdm import EXPORT_ORDER, GdmExporter, cim_to_gdm
4
+
5
+ __all__ = ["EXPORT_ORDER", "GdmExporter", "cim_to_gdm"]
@@ -0,0 +1,68 @@
1
+ """ConnectivityNode → DistributionBus (``EXPORT_MAPPING.md#buses``, decision X6).
2
+
3
+ Buses are rated line to ground, as ditto's DSS reader writes them: ditto's capacitor and solar writers read a bus
4
+ rating as line to ground whatever its ``voltage_type``, so a line-to-line bus would put a 3-phase capacitor at √3 times
5
+ its voltage.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import cimprofiles.cim18.cim18v17 as cim
11
+ from cimhub_core.getters.base_voltage import get_base_voltage
12
+ from cimhub_core.getters.terminals import get_terminal_phases
13
+ from gdm.quantities import Voltage
14
+ from gdm.systems.distribution.components import DistributionBus
15
+ from gdm.systems.distribution.enums import Phase, VoltageTypes
16
+
17
+ from cimhub_gdm.exporter.shared import BUS_PHASE_ORDER, ExportContext, containers, gdm_phases
18
+ from cimhub_gdm.exporter.slots import UUID, Slot
19
+
20
+ CIM_CLASSES = (cim.ConnectivityNode,)
21
+
22
+ SPLIT_PHASES = {Phase.S1, Phase.S2}
23
+
24
+ SLOTS = {
25
+ DistributionBus: {
26
+ "uuid": UUID,
27
+ "name": Slot("written", "Names (X2)"),
28
+ "substation": Slot("written", "the ConnectivityNodeContainer when it is a Substation or VoltageLevel "
29
+ "(containers)"),
30
+ "feeder": Slot("written", "the ConnectivityNodeContainer when it is a Feeder (containers)"),
31
+ "in_service": Slot("unset", "a ConnectivityNode has no service state; GDM's default, True"),
32
+ "voltage_type": Slot("rule", "always line-to-ground, as ditto writes buses: its capacitor and solar writers "
33
+ "read every bus rating as line to ground (X6)"),
34
+ "phases": Slot("rule", "the union of the conductors on the node's terminals, in A B C S1 S2 N order; [] when "
35
+ "no terminal is on it (X6)"),
36
+ "voltagelimits": Slot("unset", "untranscribed on import: no OperationalLimitSet on a ConnectivityNode"),
37
+ "rated_voltage": Slot("rule", "get_base_voltage(form='LN') (kV); on a split-phase bus (S1 or S2) the 120 V "
38
+ "leg, get_base_voltage(form='LL') / 2 (the importer's system_voltage inverse)"),
39
+ "coordinate": Slot("unset", "untranscribed on import: a ConnectivityNode is not a PowerSystemResource (X10)"),
40
+ },
41
+ }
42
+
43
+
44
+ def export(node: cim.ConnectivityNode, context: ExportContext) -> DistributionBus:
45
+ phases = bus_phases(node)
46
+ return DistributionBus(
47
+ **context.names.own(node),
48
+ rated_voltage=Voltage(line_to_ground(node, phases), "kilovolt"),
49
+ voltage_type=VoltageTypes.LINE_TO_GROUND,
50
+ phases=phases,
51
+ **containers(node.ConnectivityNodeContainer, context),
52
+ )
53
+
54
+
55
+ def line_to_ground(node: cim.ConnectivityNode, phases: list) -> float:
56
+ """The bus's line-to-ground rating in kV: half the line-to-line voltage on a split-phase bus (240 V → 120 V),
57
+ else line to line / sqrt(3) (4.16 kV → 2.4018 kV)."""
58
+ if SPLIT_PHASES & set(phases):
59
+ return get_base_voltage(node, "kV", form="LL") / 2
60
+ return get_base_voltage(node, "kV", form="LN")
61
+
62
+
63
+ def bus_phases(node: cim.ConnectivityNode) -> list:
64
+ """Every conductor on the node's terminals, once, in ``BUS_PHASE_ORDER``."""
65
+ found = set()
66
+ for terminal in node.Terminals:
67
+ found.update(gdm_phases(get_terminal_phases(terminal), terminal))
68
+ return [phase for phase in BUS_PHASE_ORDER if phase in found]
@@ -0,0 +1,174 @@
1
+ """LinearShuntCompensator → DistributionCapacitor, its RegulatingControl → a capacitor controller
2
+ (``EXPORT_MAPPING.md#capacitors``, decisions X7, X8).
3
+
4
+ Each phase gets an equal share of the rated Q (all sections in, on ``nomU``: ``get_shunt_reactive_power``). The
5
+ state is one entry, as ditto writes it: on when any section is in. The controller is the importer's inverse: on and
6
+ off = (target ∓ deadband / 2) / ratio. GDM names no monitored element, so a control on another terminal raises.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import cimprofiles.cim18.cim18v17 as cim
12
+ from cimhub_core.cimtbl import lookup
13
+ from cimhub_core.getters import describe
14
+ from cimhub_core.getters.control import get_equipment_control
15
+ from cimhub_core.getters.shunt import get_shunt_reactive_power
16
+ from cimhub_core.getters.terminals import get_terminal_nodes
17
+ from gdm.quantities import ReactivePower
18
+ from gdm.systems.distribution.components import DistributionCapacitor
19
+ from gdm.systems.distribution.controllers import (
20
+ ActivePowerCapacitorController,
21
+ CurrentCapacitorController,
22
+ ReactivePowerCapacitorController,
23
+ VoltageCapacitorController,
24
+ )
25
+ from gdm.systems.distribution.enums import ConnectionType, VoltageTypes
26
+ from gdm.systems.distribution.equipment import CapacitorEquipment, PhaseCapacitorEquipment
27
+ from infrasys.quantities import ActivePower, Current, Time, Voltage
28
+
29
+ from cimhub_gdm.exporter.shared import ExportContext, connection_type, containers, gdm_phases, in_service
30
+ from cimhub_gdm.exporter.slots import UUID, Slot
31
+
32
+ CIM_CLASSES = (cim.LinearShuntCompensator,)
33
+
34
+ MODE = cim.RegulatingControlModeKind
35
+ #: Control mode → (controller class, on slot, off slot, quantity class, GDM unit of the mode's SI unit, ratio slot).
36
+ CONTROLLERS = {
37
+ MODE.voltage: (VoltageCapacitorController, "on_voltage", "off_voltage", Voltage, "volt", "pt_ratio"),
38
+ MODE.currentFlow: (CurrentCapacitorController, "on_current", "off_current", Current, "ampere", "ct_ratio"),
39
+ MODE.activePower: (ActivePowerCapacitorController, "on_power", "off_power", ActivePower, "watt", None),
40
+ MODE.reactivePower: (ReactivePowerCapacitorController, "on_power", "off_power", ReactivePower, "var", None),
41
+ }
42
+
43
+ BALANCED = (cim.SinglePhaseKind.A, cim.SinglePhaseKind.B, cim.SinglePhaseKind.C)
44
+
45
+ _UNTRANSCRIBED = "untranscribed on import: no CIM home"
46
+ _CONTROLLER_SLOTS = {
47
+ "uuid": UUID,
48
+ "name": Slot("written", "the capacitor's name (X2)"),
49
+ "delay_on": Slot("written", "get_equipment_control.delay (aVRDelay, s); unset is None"),
50
+ "delay_off": Slot("unset", "untranscribed on import: CIM has one delay, aVRDelay"),
51
+ "dead_time": Slot("unset", _UNTRANSCRIBED),
52
+ }
53
+ _ON = "(target − deadband / 2)"
54
+ _OFF = "(target + deadband / 2)"
55
+
56
+ SLOTS = {
57
+ DistributionCapacitor: {
58
+ "uuid": UUID,
59
+ "name": Slot("written", "Names (X2)"),
60
+ "substation": Slot("written", "the EquipmentContainer when it is a Substation or VoltageLevel (containers)"),
61
+ "feeder": Slot("written", "the EquipmentContainer when it is a Feeder (containers)"),
62
+ "in_service": Slot("rule", "get_in_service(which='actual'); unset is in service, GDM's default"),
63
+ "bus": Slot("written", "the bus of get_terminal_nodes"),
64
+ "phases": Slot("written", "get_shunt_reactive_power.phases: the phase conductors, no neutral"),
65
+ "controllers": Slot("rule", "one controller from get_equipment_control, by mode (CONTROLLERS); none when "
66
+ "there is no control or it is disabled (enabled or controlEnabled false)"),
67
+ "equipment": Slot("written", "a CapacitorEquipment made for this capacitor"),
68
+ "state": Slot("rule", "one entry, as ditto writes it: sections (actual) > 0"),
69
+ },
70
+ CapacitorEquipment: {
71
+ "uuid": UUID,
72
+ "name": Slot("written", "the capacitor's name (X2)"),
73
+ "phase_capacitors": Slot("written", "one PhaseCapacitorEquipment per phase conductor"),
74
+ "connection_type": Slot("written", "phaseConnection: Y and Yn → STAR, D → DELTA; others raise"),
75
+ "rated_voltage": Slot("written", "get_shunt_reactive_power(voltage='nominal').voltage: nomU (kV)"),
76
+ "voltage_type": Slot("rule", "line-to-line on balanced ABC and for delta (nomU across a branch), else "
77
+ "line-to-ground: the importer's nominal_voltage inverse"),
78
+ },
79
+ PhaseCapacitorEquipment: {
80
+ "uuid": UUID,
81
+ "name": Slot("written", "<capacitor>_<phase> (X2)"),
82
+ "resistance": Slot("unset", "untranscribed on import: no home on LinearShuntCompensator; GDM's default 0"),
83
+ "reactance": Slot("unset", "untranscribed on import: no home on LinearShuntCompensator; GDM's default 0"),
84
+ "rated_reactive_power": Slot("written", "get_shunt_reactive_power(sections='maximum', voltage='nominal')"
85
+ ".per_phase (kVAr)"),
86
+ "num_banks_on": Slot("written", "get_shunt_reactive_power(sections='actual').sections; a fraction raises"),
87
+ "num_banks": Slot("written", "get_shunt_reactive_power(sections='maximum').sections"),
88
+ },
89
+ VoltageCapacitorController: _CONTROLLER_SLOTS | {
90
+ "on_voltage": Slot("rule", f"{_ON} / pt_ratio (V)"),
91
+ "off_voltage": Slot("rule", f"{_OFF} / pt_ratio (V)"),
92
+ "pt_ratio": Slot("rule", "ptRatio; unset is 1, the targets as stored"),
93
+ },
94
+ CurrentCapacitorController: _CONTROLLER_SLOTS | {
95
+ "on_current": Slot("rule", f"{_ON} / ct_ratio (A)"),
96
+ "off_current": Slot("rule", f"{_OFF} / ct_ratio (A)"),
97
+ "ct_ratio": Slot("rule", "ctRatio; unset is 1, the targets as stored"),
98
+ },
99
+ ActivePowerCapacitorController: _CONTROLLER_SLOTS | {
100
+ "on_power": Slot("rule", f"{_ON} (W)"),
101
+ "off_power": Slot("rule", f"{_OFF} (W)"),
102
+ },
103
+ ReactivePowerCapacitorController: _CONTROLLER_SLOTS | {
104
+ "on_power": Slot("rule", f"{_ON} (VAr)"),
105
+ "off_power": Slot("rule", f"{_OFF} (VAr)"),
106
+ },
107
+ }
108
+
109
+
110
+ def export(shunt: cim.LinearShuntCompensator, context: ExportContext) -> DistributionCapacitor:
111
+ rated = get_shunt_reactive_power(shunt, "kVAr", sections="maximum", voltage="nominal", voltage_unit="kV")
112
+ actual = get_shunt_reactive_power(shunt, "kVAr", sections="actual", voltage="nominal", voltage_unit="kV")
113
+ names = context.names
114
+ phases = gdm_phases(rated.phases, shunt)
115
+ banks_on = whole_sections(actual.sections, shunt)
116
+ phase_capacitors = [
117
+ PhaseCapacitorEquipment(**names.part(shunt, PhaseCapacitorEquipment, suffix=f"_{phase.value}"),
118
+ rated_reactive_power=ReactivePower(rated.per_phase[conductor], "kilovar"),
119
+ num_banks_on=banks_on, num_banks=whole_sections(rated.sections, shunt))
120
+ for conductor, phase in zip(rated.phases, phases)
121
+ ]
122
+ connection = connection_type(rated.connection, shunt)
123
+ equipment = CapacitorEquipment(**names.part(shunt, CapacitorEquipment), phase_capacitors=phase_capacitors,
124
+ connection_type=connection, rated_voltage=Voltage(rated.voltage, "kilovolt"),
125
+ voltage_type=voltage_type(rated.phases, connection))
126
+ [node] = get_terminal_nodes(shunt)
127
+ return DistributionCapacitor(
128
+ **names.own(shunt),
129
+ bus=context.gdm(node),
130
+ phases=phases,
131
+ equipment=equipment,
132
+ state=[banks_on > 0],
133
+ controllers=controllers(shunt, context),
134
+ in_service=in_service(shunt),
135
+ **containers(shunt.EquipmentContainer, context),
136
+ )
137
+
138
+
139
+ def whole_sections(sections: float, shunt: cim.LinearShuntCompensator) -> int:
140
+ """A section count as GDM's bank count; a fraction of a section raises."""
141
+ if sections != int(sections):
142
+ raise ValueError(f"{describe(shunt)}: {sections} sections; GDM counts whole banks")
143
+ return int(sections)
144
+
145
+
146
+ def voltage_type(phases, connection: ConnectionType) -> VoltageTypes:
147
+ """nomU's form: line to line on balanced ABC and across a delta branch, line to ground for a wye off ABC."""
148
+ if tuple(phases) == BALANCED or connection is ConnectionType.DELTA:
149
+ return VoltageTypes.LINE_TO_LINE
150
+ return VoltageTypes.LINE_TO_GROUND
151
+
152
+
153
+ def controllers(shunt: cim.LinearShuntCompensator, context: ExportContext) -> list:
154
+ """The capacitor's one controller, or none when it has no control or the control is disabled."""
155
+ control = get_equipment_control(shunt, time_unit="s")
156
+ if control is None or control.control_enabled is False or control.control.enabled is False:
157
+ return []
158
+ settings = control.control
159
+ if settings.terminal not in shunt.Terminals:
160
+ raise ValueError(f"{describe(shunt)}: its RegulatingControl monitors {describe(settings.terminal)}, not "
161
+ "its own terminal; a GDM capacitor controller names no monitored element")
162
+ controller_class, on_slot, off_slot, quantity, unit, ratio_slot = lookup(
163
+ CONTROLLERS, settings.mode, slot="mode", record_id=shunt.mRID)
164
+ values = {}
165
+ scale = 1.0
166
+ if ratio_slot is not None:
167
+ ratio = settings.pt_ratio if ratio_slot == "pt_ratio" else settings.ct_ratio
168
+ scale = 1.0 if ratio is None else ratio # unset: the targets as stored
169
+ values[ratio_slot] = scale
170
+ half_band = (settings.deadband or 0.0) / 2
171
+ values[on_slot] = quantity((settings.target - half_band) / scale, unit)
172
+ values[off_slot] = quantity((settings.target + half_band) / scale, unit)
173
+ delay = None if control.delay is None else Time(control.delay, "second")
174
+ return [controller_class(**context.names.part(shunt, controller_class), delay_on=delay, **values)]
@@ -0,0 +1,98 @@
1
+ """cim18v17 network -> GDM ``DistributionSystem`` (``EXPORT_PLAN.md``, spec ``EXPORT_MAPPING.md``).
2
+
3
+ Each module in ``EXPORT_ORDER`` exports its CIM classes through the core getters, in GDM reference order: a
4
+ component exists before anything that names it. ``write_gdm`` writes the result as GDM JSON, which ``read_gdm`` and
5
+ the importer read back.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections import Counter
11
+
12
+ import cimprofiles.cim18.cim18v17 as cim
13
+ from cimhub_core.base import FormatExporter
14
+ from cimhub_core.names import export_name
15
+ from gdm.systems.distribution import DistributionSystem
16
+
17
+ from cimhub_gdm.exporter import (
18
+ bus,
19
+ capacitor,
20
+ der,
21
+ fills,
22
+ line,
23
+ load,
24
+ reactor,
25
+ regulator,
26
+ shell,
27
+ source,
28
+ switch,
29
+ time_series,
30
+ transformer,
31
+ )
32
+ from cimhub_gdm.exporter.naming import Names
33
+ from cimhub_gdm.exporter.shared import ExportContext
34
+ from cimhub_gdm.gdm_writer import write_gdm
35
+
36
+ #: Modules in export order; each has ``CIM_CLASSES``, ``SLOTS`` and ``export(obj, context)`` -> one GDM component,
37
+ #: or a tuple of them (a connection's DER, one per unit).
38
+ EXPORT_ORDER = (shell, bus, source, switch, line, reactor, transformer, regulator, load, capacitor, der)
39
+
40
+ __all__ = ["EXPORT_ORDER", "GdmExporter", "cim_to_gdm"]
41
+
42
+
43
+ class GdmExporter(FormatExporter):
44
+ """``to_model(network, *, name_source=None, system_name=None) -> DistributionSystem``.
45
+
46
+ ``name_source`` is the shared naming switch (``cimhub_core.names``: ``'name'``, ``'mrid'``, ``'uri'``; else
47
+ ``$CIMHUB_NAME_SOURCE``, else ``'mrid'``). ``system_name`` names the system; without it, the one Feeder's
48
+ exported name does, and several Feeders raise (X1). Conducting equipment of a class no module exports raises.
49
+ Required GDM fields CIM cannot hold get the neutral values of ``fills.py``, with one WARNING (X4).
50
+
51
+ ``time_points``: the TimePoint tables of the network's schedules (``read_time_points``, or the dict the importer
52
+ filled); each EnergyConnectionSchedule becomes its load's series (``time_series.py``). Without them, schedules
53
+ are exported with no series and one WARNING.
54
+ """
55
+
56
+ def __init__(self, time_points: dict | None = None):
57
+ self.time_points = time_points
58
+
59
+ def to_model(self, network, *, name_source: str | None = None,
60
+ system_name: str | None = None) -> DistributionSystem:
61
+ _check_exported(network)
62
+ context = ExportContext(network, Names(name_source), {}, {}, Counter())
63
+ system = DistributionSystem(name=system_name or _system_name(network, context.names.source),
64
+ auto_add_composed_components=True)
65
+ for module in EXPORT_ORDER:
66
+ for cim_class in module.CIM_CLASSES:
67
+ for obj in network.graph.get(cim_class, {}).values():
68
+ made = module.export(obj, context)
69
+ context.made[obj.uri()] = made
70
+ for component in made if isinstance(made, tuple) else (made,):
71
+ system.add_component(component)
72
+ time_series.add_time_series(system, context, self.time_points)
73
+ fills.warn(context.filled)
74
+ return system
75
+
76
+
77
+ def cim_to_gdm(network, destination, *, time_points: dict | None = None, **opts) -> None:
78
+ """Export ``network`` and write the GDM JSON file ``destination``; ``time_points`` as ``GdmExporter``, ``opts``
79
+ go to ``to_model``."""
80
+ write_gdm(GdmExporter(time_points).to_model(network, **opts), destination)
81
+
82
+
83
+ def _system_name(network, name_source: str) -> str:
84
+ """The one Feeder's exported name (X1)."""
85
+ feeders = list(network.graph.get(cim.Feeder, {}).values())
86
+ if len(feeders) != 1:
87
+ raise ValueError(f"{len(feeders)} Feeders {sorted(feeder.mRID for feeder in feeders)}; pass system_name= "
88
+ "to name the GDM system")
89
+ return export_name(feeders[0], name_source)
90
+
91
+
92
+ def _check_exported(network) -> None:
93
+ """Raise on conducting equipment no module exports, so nothing is dropped silently."""
94
+ exported = {cim_class for module in EXPORT_ORDER for cim_class in module.CIM_CLASSES}
95
+ missing = {cls.__name__: len(objects) for cls, objects in network.graph.items()
96
+ if objects and issubclass(cls, cim.ConductingEquipment) and cls not in exported}
97
+ if missing:
98
+ raise ValueError(f"no GDM export yet for {dict(sorted(missing.items()))}")
@@ -0,0 +1,233 @@
1
+ """PowerElectronicsConnection → DistributionSolar or DistributionBattery (``EXPORT_MAPPING.md#der``, X4, X7, X8).
2
+
3
+ Each PowerElectronicsUnit is one GDM DER, its class picking the GDM class: a PhotoVoltaicUnit gives a
4
+ DistributionSolar, a BatteryUnit a DistributionBattery; another unit raises. GDM holds one DC device per inverter, so
5
+ a connection of several units (a PV array and a battery behind one inverter) is chopped by ``get_inverter_units``, the
6
+ DSS exporter's rule: each unit's share is its maxP over the units' total, and it takes that share of the connection's
7
+ q and inverter rating, and its own p (else that share of the connection's p), in the generation sign. One unit is the
8
+ whole connection, and its DER is the connection's (name and uuid); several each take their unit's. The inverter is
9
+ the connection's InverterInfo, shared (X3) per share, else the DER's own. A battery's equipment is its unit's
10
+ BatteryInfo, shared, else its own. The equipment's rating is ``ratedU`` in the importer's ``system_voltage`` form,
11
+ inverted: line to line on three phases, else line to ground (a split-phase leg is half, any other phase ratedU / √3).
12
+ Inverter controllers are not in CIM, so ``controller`` is None (X8).
13
+
14
+ A PV's irradiance is ``PhotoVoltaicUnit.irradiance`` when set (B16b). When it is not, it is not neutral: ditto 0.1.8
15
+ writes no ``active_power``, and OpenDSS makes ``Pmpp × Irradiance``. So irradiance is then the output's share of the
16
+ panel's rating at standard test conditions (p / maxP × 1 kW/m²), and the PV makes CIM's p.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import math
22
+
23
+ import cimprofiles.cim18.cim18v17 as cim
24
+ from cimtables.graph_write import get_qty
25
+ from cimhub_core.getters import describe
26
+ from cimhub_core.getters.der import (
27
+ get_battery_unit,
28
+ InverterUnitShare,
29
+ get_der_output,
30
+ get_inverter_rating,
31
+ get_inverter_units,
32
+ get_photovoltaic_unit,
33
+ )
34
+ from cimhub_core.getters.terminals import get_terminal_nodes
35
+ from gdm.quantities import ApparentPower, EnergyDC, Irradiance, ReactivePower
36
+ from gdm.systems.distribution.components import DistributionBattery, DistributionSolar
37
+ from gdm.systems.distribution.enums import VoltageTypes
38
+ from gdm.systems.distribution.equipment import BatteryEquipment, InverterEquipment, SolarEquipment
39
+ from infrasys.quantities import ActivePower, Voltage
40
+
41
+ from cimhub_gdm.exporter import fills
42
+ from cimhub_gdm.exporter.shared import (
43
+ ExportContext,
44
+ containers,
45
+ gdm_phases,
46
+ in_service,
47
+ shared_equipment,
48
+ )
49
+ from cimhub_gdm.exporter.slots import UUID, Slot
50
+
51
+ CIM_CLASSES = (cim.PowerElectronicsConnection,)
52
+
53
+ #: The sign every DER value is read in: positive output, GDM's.
54
+ SIGN = "generation"
55
+ THREE_PHASE = {cim.SinglePhaseKind.A, cim.SinglePhaseKind.B, cim.SinglePhaseKind.C}
56
+ SPLIT_PHASES = {cim.SinglePhaseKind.s1, cim.SinglePhaseKind.s2}
57
+
58
+ _RATING = ("the connection's ratedU (get_inverter_rating), line to line on three phases, else line to ground: / 2 "
59
+ "on a split-phase leg, / √3 otherwise (the importer's system_voltage inverted)")
60
+ _VOLTAGE_TYPE = "line-to-line on A, B and C, else line-to-ground"
61
+ _DER_SLOTS = {
62
+ "uuid": UUID,
63
+ "name": Slot("written", "Names (X2): the connection's for one unit, else the unit's"),
64
+ "substation": Slot("written", "the EquipmentContainer when it is a Substation or VoltageLevel (containers)"),
65
+ "feeder": Slot("written", "the EquipmentContainer when it is a Feeder (containers)"),
66
+ "in_service": Slot("rule", "get_in_service(which='actual'); unset is in service, GDM's default"),
67
+ "bus": Slot("written", "the bus of get_terminal_nodes"),
68
+ "phases": Slot("written", "get_der_output.phases: the phase conductors, no neutral (balanced ABC on none, G3)"),
69
+ "active_power": Slot("written", "get_inverter_units(sign='generation') p (kW): the unit's own, else its share "
70
+ "of the connection's"),
71
+ "reactive_power": Slot("written", "get_inverter_units(sign='generation') q (kVAr): its share of the "
72
+ "connection's"),
73
+ "controller": Slot("unset", "inverter controllers are not in CIM (PENDING on import, X8)"),
74
+ "inverter": Slot("written", "the InverterEquipment of the connection's InverterInfo (shared, X3), else the "
75
+ "DER's own"),
76
+ }
77
+
78
+ SLOTS = {
79
+ DistributionSolar: _DER_SLOTS | {
80
+ "irradiance": Slot("rule", "PhotoVoltaicUnit.irradiance; unset, p / the panel's maxP × 1 kW/m² (standard "
81
+ "test conditions): what OpenDSS makes of it (Pmpp × Irradiance) is CIM's p"),
82
+ "equipment": Slot("written", "a SolarEquipment made for this DER"),
83
+ },
84
+ DistributionBattery: _DER_SLOTS | {
85
+ "equipment": Slot("written", "the BatteryEquipment of the unit's BatteryInfo (shared, X3), else the DER's "
86
+ "own"),
87
+ },
88
+ SolarEquipment: {
89
+ "uuid": UUID,
90
+ "name": Slot("written", "the DER's name (X2)"),
91
+ "rated_power": Slot("written", "get_photovoltaic_unit(sign='generation').max_p (kW); unset raises"),
92
+ "power_temp_curve": Slot("unset", "untranscribed on import: until the Curve builder (B12)"),
93
+ "resistance": Slot("fill", "fills.SOLAR_RESISTANCE, 0 % (§3.1)"),
94
+ "reactance": Slot("fill", "fills.SOLAR_REACTANCE, 0 % (§3.1)"),
95
+ "rated_voltage": Slot("rule", _RATING),
96
+ "voltage_type": Slot("rule", _VOLTAGE_TYPE),
97
+ },
98
+ BatteryEquipment: {
99
+ "uuid": UUID,
100
+ "name": Slot("written", "the BatteryInfo's name (X2); else the DER's"),
101
+ "rated_energy": Slot("written", "get_battery_unit.rated_e (kWh); unset raises"),
102
+ "rated_power": Slot("rule", "get_battery_unit(sign='generation').max_p (kW), with min_p unset or -max_p "
103
+ "(GDM has one rating both ways); else raises"),
104
+ "charging_efficiency": Slot("written", "get_battery_unit.charging_efficiency (%); unset raises"),
105
+ "discharging_efficiency": Slot("written", "get_battery_unit.discharging_efficiency (%); unset raises"),
106
+ "idling_efficiency": Slot("fill", "fills.BATTERY_IDLING_EFFICIENCY, 100 % (§3.1)"),
107
+ "rated_voltage": Slot("rule", _RATING),
108
+ "voltage_type": Slot("rule", _VOLTAGE_TYPE),
109
+ },
110
+ InverterEquipment: {
111
+ "uuid": UUID,
112
+ "name": Slot("written", "the InverterInfo's name (X2), '' when it has none under name source 'name' (GDM's "
113
+ "default, which the importer reads as unnamed); else the DER's"),
114
+ "rated_apparent_power": Slot("written", "get_inverter_rating.rated_s × the unit's share (kVA)"),
115
+ "rise_limit": Slot("fill", "fills.INVERTER_RAMP_LIMIT, None (§3.1)"),
116
+ "fall_limit": Slot("fill", "fills.INVERTER_RAMP_LIMIT, None (§3.1)"),
117
+ "cutout_percent": Slot("fill", "fills.INVERTER_CUTOUT_PERCENT, 0 % (§3.1)"),
118
+ "cutin_percent": Slot("fill", "fills.INVERTER_CUTIN_PERCENT, 0 % (§3.1)"),
119
+ "dc_to_ac_efficiency": Slot("fill", "fills.INVERTER_EFFICIENCY, 100 % (§3.1)"),
120
+ "eff_curve": Slot("unset", "untranscribed on import: until the Curve builder (B12)"),
121
+ },
122
+ }
123
+
124
+
125
+ def export(connection: cim.PowerElectronicsConnection, context: ExportContext) -> tuple:
126
+ """One GDM DER per unit of the connection."""
127
+ units = get_inverter_units(connection, "kW", "kVAr", sign=SIGN)
128
+ output = get_der_output(connection, "kW", "kVAr", sign=SIGN)
129
+ rating = get_inverter_rating(connection, "kVA", "kVAr", sign=SIGN, voltage_unit="kV")
130
+ voltage = equipment_voltage(rating.rated_u, output.phases)
131
+ [node] = get_terminal_nodes(connection)
132
+ common = {
133
+ "bus": context.gdm(node),
134
+ "phases": gdm_phases(output.phases, connection),
135
+ "in_service": in_service(connection),
136
+ **containers(connection.EquipmentContainer, context),
137
+ }
138
+ return tuple(der(connection, share, connection if len(units) == 1 else share.unit, rating, voltage, common,
139
+ context) for share in units)
140
+
141
+
142
+ def der(connection, share: InverterUnitShare, owner, rating, voltage: dict, common: dict, context: ExportContext):
143
+ """The DER of one unit's ``share``, named and identified as ``owner`` (the connection, or the unit)."""
144
+ unit = share.unit
145
+ common = common | {
146
+ **context.names.own(owner),
147
+ "active_power": ActivePower(share.p, "kilowatt"),
148
+ "reactive_power": ReactivePower(share.q, "kilovar"),
149
+ "inverter": inverter(connection, owner, share.share * rating.rated_s, context),
150
+ }
151
+ if isinstance(unit, cim.PhotoVoltaicUnit):
152
+ panel = solar_equipment(owner, unit, voltage, context)
153
+ return DistributionSolar(irradiance=irradiance(share.p, panel, unit), equipment=panel, **common)
154
+ if isinstance(unit, cim.BatteryUnit):
155
+ return DistributionBattery(equipment=battery_equipment(owner, unit, voltage, context), **common)
156
+ raise ValueError(f"no GDM export yet for a {type(unit).__name__}: {describe(connection)}")
157
+
158
+
159
+ def equipment_voltage(rated_u: float, phases) -> dict:
160
+ """``rated_voltage`` (kV) and ``voltage_type`` from ratedU, line to line as CIM stores it (the importer's
161
+ ``system_voltage`` inverted)."""
162
+ conductors = set(phases)
163
+ if THREE_PHASE <= conductors:
164
+ return {"rated_voltage": Voltage(rated_u, "kilovolt"), "voltage_type": VoltageTypes.LINE_TO_LINE}
165
+ leg = rated_u / 2 if SPLIT_PHASES & conductors else rated_u / math.sqrt(3)
166
+ return {"rated_voltage": Voltage(leg, "kilovolt"), "voltage_type": VoltageTypes.LINE_TO_GROUND}
167
+
168
+
169
+ def inverter(connection, owner, rated_s: float, context: ExportContext) -> InverterEquipment:
170
+ """The DER's inverter of ``rated_s`` kVA: its connection's InverterInfo's, shared, else ``owner``'s own."""
171
+ equipment = InverterEquipment(
172
+ name="",
173
+ rated_apparent_power=ApparentPower(rated_s, "kilova"),
174
+ rise_limit=context.fill("InverterEquipment.rise_limit", fills.INVERTER_RAMP_LIMIT),
175
+ fall_limit=context.fill("InverterEquipment.fall_limit", fills.INVERTER_RAMP_LIMIT),
176
+ cutin_percent=context.fill("InverterEquipment.cutin_percent", fills.INVERTER_CUTIN_PERCENT),
177
+ cutout_percent=context.fill("InverterEquipment.cutout_percent", fills.INVERTER_CUTOUT_PERCENT),
178
+ dc_to_ac_efficiency=context.fill("InverterEquipment.dc_to_ac_efficiency", fills.INVERTER_EFFICIENCY),
179
+ )
180
+ info = connection.AssetDatasheet
181
+ if not isinstance(info, cim.InverterInfo):
182
+ return equipment.model_copy(update=context.names.part(owner, InverterEquipment))
183
+ return shared_equipment(context, info, equipment, unnamed="") # GDM's default; the importer reads it as unnamed
184
+
185
+
186
+ def irradiance(output_kw: float, panel: SolarEquipment, unit: cim.PhotoVoltaicUnit) -> Irradiance:
187
+ """The unit's irradiance; unset, the irradiance at which the panel makes ``output_kw``: its share of the rating,
188
+ at 1 kW/m² for the rating."""
189
+ stored = get_qty(unit, "irradiance", "kW/m^2")
190
+ if stored is not None:
191
+ return Irradiance(stored, "kilowatt / meter ** 2")
192
+ rated_kw = panel.rated_power.to("kilowatt").magnitude
193
+ if rated_kw <= 0:
194
+ raise ValueError(f"{describe(unit)}: maxP is {rated_kw} kW; GDM's irradiance is the output's share of it")
195
+ return Irradiance(output_kw / rated_kw, "kilowatt / meter ** 2")
196
+
197
+
198
+ def solar_equipment(owner, unit: cim.PhotoVoltaicUnit, voltage: dict, context: ExportContext) -> SolarEquipment:
199
+ rated_power = get_photovoltaic_unit(unit, "kW", sign=SIGN).max_p
200
+ if rated_power is None:
201
+ raise ValueError(f"{describe(unit)}: maxP is unset; GDM needs the panel's rated_power")
202
+ return SolarEquipment(
203
+ **context.names.part(owner, SolarEquipment),
204
+ rated_power=ActivePower(rated_power, "kilowatt"),
205
+ resistance=context.fill("SolarEquipment.resistance", fills.SOLAR_RESISTANCE),
206
+ reactance=context.fill("SolarEquipment.reactance", fills.SOLAR_REACTANCE),
207
+ **voltage,
208
+ )
209
+
210
+
211
+ def battery_equipment(owner, unit: cim.BatteryUnit, voltage: dict, context: ExportContext) -> BatteryEquipment:
212
+ """The battery's equipment: its BatteryInfo's, shared, else ``owner``'s own."""
213
+ battery = get_battery_unit(unit, "kW", "kWh", sign=SIGN)
214
+ unset = [name for name in ("max_p", "rated_e", "charging_efficiency", "discharging_efficiency")
215
+ if getattr(battery, name) is None]
216
+ if unset:
217
+ raise ValueError(f"{describe(unit)}: {', '.join(unset)} unset; GDM's BatteryEquipment requires them")
218
+ if battery.min_p is not None and not math.isclose(battery.min_p, -battery.max_p):
219
+ raise ValueError(f"{describe(unit)}: minP {battery.min_p} kW is not the negative of maxP {battery.max_p} kW; "
220
+ "GDM's BatteryEquipment has one rated_power both ways")
221
+ equipment = BatteryEquipment(
222
+ name="",
223
+ rated_energy=EnergyDC(battery.rated_e, "kilowatthour"),
224
+ rated_power=ActivePower(battery.max_p, "kilowatt"),
225
+ charging_efficiency=battery.charging_efficiency,
226
+ discharging_efficiency=battery.discharging_efficiency,
227
+ idling_efficiency=context.fill("BatteryEquipment.idling_efficiency", fills.BATTERY_IDLING_EFFICIENCY),
228
+ **voltage,
229
+ )
230
+ info = unit.AssetDatasheet
231
+ if isinstance(info, cim.BatteryInfo):
232
+ return shared_equipment(context, info, equipment)
233
+ return equipment.model_copy(update=context.names.part(owner, BatteryEquipment))