cimhub-gridlabd 2.0.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 (152) hide show
  1. cimhub_gridlabd/__init__.py +3 -0
  2. cimhub_gridlabd/exporter/__init__.py +10 -0
  3. cimhub_gridlabd/exporter/base/__init__.py +1 -0
  4. cimhub_gridlabd/exporter/base/node.py +220 -0
  5. cimhub_gridlabd/exporter/cim_to_glm.py +232 -0
  6. cimhub_gridlabd/exporter/generators/__init__.py +14 -0
  7. cimhub_gridlabd/exporter/generators/battery.py +66 -0
  8. cimhub_gridlabd/exporter/generators/inverter.py +237 -0
  9. cimhub_gridlabd/exporter/generators/machine.py +180 -0
  10. cimhub_gridlabd/exporter/generators/machine_dynamics.py +100 -0
  11. cimhub_gridlabd/exporter/generators/solar.py +49 -0
  12. cimhub_gridlabd/exporter/glm_registry.py +8 -0
  13. cimhub_gridlabd/exporter/glm_text_writer.py +323 -0
  14. cimhub_gridlabd/exporter/glm_writer.py +167 -0
  15. cimhub_gridlabd/exporter/lines/__init__.py +9 -0
  16. cimhub_gridlabd/exporter/lines/line.py +205 -0
  17. cimhub_gridlabd/exporter/lines/line_configuration.py +299 -0
  18. cimhub_gridlabd/exporter/lines/line_spacing.py +245 -0
  19. cimhub_gridlabd/exporter/lines/underground_line_conductor.py +257 -0
  20. cimhub_gridlabd/exporter/loads/__init__.py +1 -0
  21. cimhub_gridlabd/exporter/loads/load.py +210 -0
  22. cimhub_gridlabd/exporter/shunts/__init__.py +2 -0
  23. cimhub_gridlabd/exporter/shunts/capacitor.py +72 -0
  24. cimhub_gridlabd/exporter/switches/__init__.py +3 -0
  25. cimhub_gridlabd/exporter/switches/_common.py +98 -0
  26. cimhub_gridlabd/exporter/switches/fuse.py +32 -0
  27. cimhub_gridlabd/exporter/switches/recloser.py +32 -0
  28. cimhub_gridlabd/exporter/switches/switch.py +35 -0
  29. cimhub_gridlabd/exporter/transformers/__init__.py +6 -0
  30. cimhub_gridlabd/exporter/transformers/regulator.py +345 -0
  31. cimhub_gridlabd/exporter/transformers/transformer.py +146 -0
  32. cimhub_gridlabd/exporter/transformers/transformer_configuration.py +520 -0
  33. cimhub_gridlabd/exporter/utils/__init__.py +4 -0
  34. cimhub_gridlabd/exporter/utils/phasing.py +163 -0
  35. cimhub_gridlabd/exporter/utils/ratings.py +36 -0
  36. cimhub_gridlabd/importer/__init__.py +15 -0
  37. cimhub_gridlabd/importer/base/__init__.py +15 -0
  38. cimhub_gridlabd/importer/base/node.py +87 -0
  39. cimhub_gridlabd/importer/base/substation.py +47 -0
  40. cimhub_gridlabd/importer/base/triplex_node.py +52 -0
  41. cimhub_gridlabd/importer/capacitors/__init__.py +2 -0
  42. cimhub_gridlabd/importer/capacitors/capacitor.py +93 -0
  43. cimhub_gridlabd/importer/common.py +105 -0
  44. cimhub_gridlabd/importer/glm_reader.py +495 -0
  45. cimhub_gridlabd/importer/glm_registry.py +7 -0
  46. cimhub_gridlabd/importer/glm_serialization.py +219 -0
  47. cimhub_gridlabd/importer/glm_text_reader.py +346 -0
  48. cimhub_gridlabd/importer/glm_to_cim.py +212 -0
  49. cimhub_gridlabd/importer/lines/__init__.py +13 -0
  50. cimhub_gridlabd/importer/lines/_wire_assembly.py +90 -0
  51. cimhub_gridlabd/importer/lines/line_configuration.py +56 -0
  52. cimhub_gridlabd/importer/lines/line_spacing.py +59 -0
  53. cimhub_gridlabd/importer/lines/overhead_line.py +47 -0
  54. cimhub_gridlabd/importer/lines/overhead_line_conductor.py +33 -0
  55. cimhub_gridlabd/importer/lines/triplex_line.py +62 -0
  56. cimhub_gridlabd/importer/lines/underground_line.py +37 -0
  57. cimhub_gridlabd/importer/lines/underground_line_conductor.py +45 -0
  58. cimhub_gridlabd/importer/loads/__init__.py +2 -0
  59. cimhub_gridlabd/importer/loads/load.py +63 -0
  60. cimhub_gridlabd/importer/switches/__init__.py +2 -0
  61. cimhub_gridlabd/importer/switches/switch.py +31 -0
  62. cimhub_gridlabd/importer/transformers/__init__.py +4 -0
  63. cimhub_gridlabd/importer/transformers/regulator.py +128 -0
  64. cimhub_gridlabd/importer/transformers/transformer.py +164 -0
  65. cimhub_gridlabd/importer/transformers/transformer_configuration.py +161 -0
  66. cimhub_gridlabd/schema/cpp_parser.py +269 -0
  67. cimhub_gridlabd/schema/gridlabd.py +27136 -0
  68. cimhub_gridlabd/schema/linkml/_directives/define.yaml +19 -0
  69. cimhub_gridlabd/schema/linkml/_directives/set.yaml +19 -0
  70. cimhub_gridlabd/schema/linkml/generators/battery.yaml +780 -0
  71. cimhub_gridlabd/schema/linkml/generators/central_dg_control.yaml +112 -0
  72. cimhub_gridlabd/schema/linkml/generators/controller_dg.yaml +262 -0
  73. cimhub_gridlabd/schema/linkml/generators/diesel_dg.yaml +2881 -0
  74. cimhub_gridlabd/schema/linkml/generators/energy_storage.yaml +244 -0
  75. cimhub_gridlabd/schema/linkml/generators/inverter.yaml +2708 -0
  76. cimhub_gridlabd/schema/linkml/generators/inverter_dyn.yaml +2087 -0
  77. cimhub_gridlabd/schema/linkml/generators/rectifier.yaml +190 -0
  78. cimhub_gridlabd/schema/linkml/generators/solar.yaml +645 -0
  79. cimhub_gridlabd/schema/linkml/generators/sync_ctrl.yaml +297 -0
  80. cimhub_gridlabd/schema/linkml/generators/windturb_dg.yaml +1075 -0
  81. cimhub_gridlabd/schema/linkml/main.yaml +115 -0
  82. cimhub_gridlabd/schema/linkml/powerflow/billdump.yaml +73 -0
  83. cimhub_gridlabd/schema/linkml/powerflow/capacitor.yaml +376 -0
  84. cimhub_gridlabd/schema/linkml/powerflow/currdump.yaml +72 -0
  85. cimhub_gridlabd/schema/linkml/powerflow/emissions.yaml +1069 -0
  86. cimhub_gridlabd/schema/linkml/powerflow/fault_check.yaml +89 -0
  87. cimhub_gridlabd/schema/linkml/powerflow/fuse.yaml +103 -0
  88. cimhub_gridlabd/schema/linkml/powerflow/impedance_dump.yaml +63 -0
  89. cimhub_gridlabd/schema/linkml/powerflow/jsondump.yaml +133 -0
  90. cimhub_gridlabd/schema/linkml/powerflow/line.yaml +111 -0
  91. cimhub_gridlabd/schema/linkml/powerflow/line_configuration.yaml +312 -0
  92. cimhub_gridlabd/schema/linkml/powerflow/line_spacing.yaml +148 -0
  93. cimhub_gridlabd/schema/linkml/powerflow/link.yaml +711 -0
  94. cimhub_gridlabd/schema/linkml/powerflow/load.yaml +1470 -0
  95. cimhub_gridlabd/schema/linkml/powerflow/load_tracker.yaml +111 -0
  96. cimhub_gridlabd/schema/linkml/powerflow/meter.yaml +1248 -0
  97. cimhub_gridlabd/schema/linkml/powerflow/motor.yaml +893 -0
  98. cimhub_gridlabd/schema/linkml/powerflow/node.yaml +1170 -0
  99. cimhub_gridlabd/schema/linkml/powerflow/overhead_line.yaml +31 -0
  100. cimhub_gridlabd/schema/linkml/powerflow/overhead_line_conductor.yaml +118 -0
  101. cimhub_gridlabd/schema/linkml/powerflow/performance_motor.yaml +407 -0
  102. cimhub_gridlabd/schema/linkml/powerflow/power_metrics.yaml +193 -0
  103. cimhub_gridlabd/schema/linkml/powerflow/powerflow_object.yaml +112 -0
  104. cimhub_gridlabd/schema/linkml/powerflow/pqload.yaml +603 -0
  105. cimhub_gridlabd/schema/linkml/powerflow/recloser.yaml +68 -0
  106. cimhub_gridlabd/schema/linkml/powerflow/regulator.yaml +168 -0
  107. cimhub_gridlabd/schema/linkml/powerflow/regulator_configuration.yaml +306 -0
  108. cimhub_gridlabd/schema/linkml/powerflow/restoration.yaml +163 -0
  109. cimhub_gridlabd/schema/linkml/powerflow/sectionalizer.yaml +31 -0
  110. cimhub_gridlabd/schema/linkml/powerflow/series_compensator.yaml +549 -0
  111. cimhub_gridlabd/schema/linkml/powerflow/series_reactor.yaml +144 -0
  112. cimhub_gridlabd/schema/linkml/powerflow/substation.yaml +297 -0
  113. cimhub_gridlabd/schema/linkml/powerflow/switch.yaml +109 -0
  114. cimhub_gridlabd/schema/linkml/powerflow/sync_check.yaml +372 -0
  115. cimhub_gridlabd/schema/linkml/powerflow/transformer.yaml +230 -0
  116. cimhub_gridlabd/schema/linkml/powerflow/transformer_configuration.yaml +512 -0
  117. cimhub_gridlabd/schema/linkml/powerflow/triplex_line.yaml +31 -0
  118. cimhub_gridlabd/schema/linkml/powerflow/triplex_line_conductor.yaml +106 -0
  119. cimhub_gridlabd/schema/linkml/powerflow/triplex_line_configuration.yaml +187 -0
  120. cimhub_gridlabd/schema/linkml/powerflow/triplex_load.yaml +729 -0
  121. cimhub_gridlabd/schema/linkml/powerflow/triplex_meter.yaml +812 -0
  122. cimhub_gridlabd/schema/linkml/powerflow/triplex_node.yaml +822 -0
  123. cimhub_gridlabd/schema/linkml/powerflow/underground_line.yaml +31 -0
  124. cimhub_gridlabd/schema/linkml/powerflow/underground_line_conductor.yaml +236 -0
  125. cimhub_gridlabd/schema/linkml/powerflow/vfd.yaml +156 -0
  126. cimhub_gridlabd/schema/linkml/powerflow/volt_var_control.yaml +217 -0
  127. cimhub_gridlabd/schema/linkml/powerflow/voltdump.yaml +82 -0
  128. cimhub_gridlabd/schema/linkml/residential/ZIPload.yaml +372 -0
  129. cimhub_gridlabd/schema/linkml/residential/appliance.yaml +83 -0
  130. cimhub_gridlabd/schema/linkml/residential/clotheswasher.yaml +596 -0
  131. cimhub_gridlabd/schema/linkml/residential/dishwasher.yaml +882 -0
  132. cimhub_gridlabd/schema/linkml/residential/dryer.yaml +601 -0
  133. cimhub_gridlabd/schema/linkml/residential/evcharger.yaml +192 -0
  134. cimhub_gridlabd/schema/linkml/residential/evcharger_det.yaml +557 -0
  135. cimhub_gridlabd/schema/linkml/residential/freezer.yaml +179 -0
  136. cimhub_gridlabd/schema/linkml/residential/house.yaml +2171 -0
  137. cimhub_gridlabd/schema/linkml/residential/house_a.yaml +480 -0
  138. cimhub_gridlabd/schema/linkml/residential/lights.yaml +122 -0
  139. cimhub_gridlabd/schema/linkml/residential/microwave.yaml +126 -0
  140. cimhub_gridlabd/schema/linkml/residential/occupantload.yaml +68 -0
  141. cimhub_gridlabd/schema/linkml/residential/plugload.yaml +82 -0
  142. cimhub_gridlabd/schema/linkml/residential/range.yaml +711 -0
  143. cimhub_gridlabd/schema/linkml/residential/refrigerator.yaml +598 -0
  144. cimhub_gridlabd/schema/linkml/residential/thermal_storage.yaml +212 -0
  145. cimhub_gridlabd/schema/linkml/residential/waterheater.yaml +640 -0
  146. cimhub_gridlabd/schema/linkml/types/common.yaml +2014 -0
  147. cimhub_gridlabd/schema/linkml_generator.py +496 -0
  148. cimhub_gridlabd/schema/property_parser.py +460 -0
  149. cimhub_gridlabd-2.0.0a1.dist-info/METADATA +110 -0
  150. cimhub_gridlabd-2.0.0a1.dist-info/RECORD +152 -0
  151. cimhub_gridlabd-2.0.0a1.dist-info/WHEEL +5 -0
  152. cimhub_gridlabd-2.0.0a1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3 @@
1
+ """CIMHub GridLAB-D — bidirectional GridLAB-D ↔ CIM converter."""
2
+
3
+ __version__ = "2.0.0a0"
@@ -0,0 +1,10 @@
1
+ from cimhub_gridlabd.exporter.glm_writer import GlmJsonWriter
2
+
3
+ __all__ = ["GlmJsonWriter"]
4
+
5
+ # CIM conversion functions require cimgraph — only export when available
6
+ try:
7
+ from cimhub_gridlabd.exporter.cim_to_glm import cim_to_glm, cim_to_glm_json # noqa: F401
8
+ __all__ += ["cim_to_glm", "cim_to_glm_json"]
9
+ except ImportError:
10
+ pass
@@ -0,0 +1 @@
1
+ from cimhub_gridlabd.exporter.base.node import convert_connectivity_node
@@ -0,0 +1,220 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import logging
5
+ import math
6
+
7
+ import cimgraph.data_profile.cimhub_2026 as cim
8
+
9
+ from cimhub_core import GraphModel
10
+ from cimhub_gridlabd.schema import gridlabd as glm_schema
11
+ from cimhub_gridlabd.exporter.glm_registry import glm_exporter_registry
12
+ from cimhub_gridlabd.exporter.utils.phasing import collect_phases
13
+
14
+ _log = logging.getLogger(__name__)
15
+
16
+
17
+ def _voltage_from_transformer(terminal, xfmr, cim_mod) -> float | None:
18
+ """Return the rated voltage (V, line-to-line) for this terminal's side of xfmr.
19
+
20
+ Walks PowerTransformerEnds + TransformerTankEnds looking for an end whose
21
+ Terminal matches *terminal*. Returns ``ratedU`` (in V) if found.
22
+ """
23
+ for end in getattr(xfmr, "PowerTransformerEnd", []):
24
+ if getattr(end, "Terminal", None) is terminal:
25
+ v = getattr(end, "ratedU", None)
26
+ if v is not None:
27
+ return float(v)
28
+ for tank in getattr(xfmr, "TransformerTanks", []):
29
+ for end in getattr(tank, "TransformerTankEnds", []):
30
+ if getattr(end, "Terminal", None) is terminal:
31
+ v = getattr(end, "ratedU", None)
32
+ if v is not None:
33
+ return float(v)
34
+ return None
35
+
36
+
37
+ @glm_exporter_registry.register(cim.ConnectivityNode)
38
+ def convert_connectivity_node(node: cim.ConnectivityNode, glm_model: GraphModel) -> dict:
39
+ cim: cim = importlib.import_module(node.__module__)
40
+
41
+ phases = []
42
+ ll_voltages: list[float] = [] # line-to-line (from BaseVoltage) — divide by sqrt(3)
43
+ ln_voltages: list[float] = [] # line-to-neutral (from transformer ratedU) — use as-is
44
+ is_swing_bus = False
45
+ is_swing_pq = False
46
+ is_triplex = False
47
+ glm_node = {}
48
+ glm_node["name"] = node.name or node.uri()
49
+
50
+ # Collect phasing and nominal voltage
51
+ for terminal in node.Terminals:
52
+ equipment = terminal.ConductingEquipment
53
+ if equipment is None:
54
+ continue
55
+
56
+ # Swing bus detection: EnergySource or a regulating network injection.
57
+ # CIM17 calls it EquivalentInjection; CIM18/cimhub_2026 renamed it
58
+ # ExternalNetworkInjection. Match whichever the profile defines.
59
+ injection_cls = getattr(cim, "ExternalNetworkInjection", None) or getattr(
60
+ cim, "EquivalentInjection", None
61
+ )
62
+ if isinstance(equipment, cim.EnergySource):
63
+ is_swing_bus = True
64
+ elif injection_cls is not None and isinstance(equipment, injection_cls):
65
+ if getattr(equipment, "regulationStatus", False):
66
+ is_swing_bus = True
67
+
68
+ if equipment.BaseVoltage is not None:
69
+ # BaseVoltage.nominalVoltage is line-to-line — convert to LN later
70
+ ll_voltages.append(float(equipment.BaseVoltage.nominalVoltage))
71
+ elif isinstance(equipment, cim.PowerTransformer):
72
+ # TransformerEnd.Terminal back-ref may be empty — walk the transformer
73
+ # ends directly and match by terminal to find the rated voltage.
74
+ # TransformerEnd.ratedU is line-to-line for multi-phase ends; for single-
75
+ # phase (center-tap) ends it's line-to-neutral. Both are stored as V.
76
+ # We track these separately so we can later pick the right one.
77
+ v = _voltage_from_transformer(terminal, equipment, cim)
78
+ if v is not None:
79
+ ln_voltages.append(float(v))
80
+ else:
81
+ # For switches/lines with no BaseVoltage, look through the OTHER terminal
82
+ # of the same equipment to its connectivity node's equipment BaseVoltage.
83
+ for other_t in getattr(equipment, "Terminals", []):
84
+ if other_t is terminal:
85
+ continue
86
+ other_cn = getattr(other_t, "ConnectivityNode", None)
87
+ if other_cn is None:
88
+ continue
89
+ for other_t2 in getattr(other_cn, "Terminals", []):
90
+ eq2 = other_t2.ConductingEquipment
91
+ if eq2 is equipment:
92
+ continue
93
+ if getattr(eq2, "BaseVoltage", None) is not None:
94
+ ll_voltages.append(float(eq2.BaseVoltage.nominalVoltage))
95
+ break
96
+ if ll_voltages:
97
+ break
98
+
99
+ phases.append(collect_phases(equipment))
100
+
101
+ # Detect triplex (secondary system) nodes
102
+ if "S" in "".join(phases):
103
+ is_triplex = True
104
+
105
+ # Detect DER types connected to this node — used for sub-meter emission and
106
+ # SWING_PQ classification (matches Java GldNode.bSolarInverters / bStorageInverters
107
+ # / bSyncMachines flags).
108
+ has_pv = False
109
+ has_storage = False
110
+ has_sync = False
111
+ for terminal in node.Terminals:
112
+ eq = terminal.ConductingEquipment
113
+ if isinstance(eq, cim.PowerElectronicsConnection):
114
+ for unit in (eq.PowerElectronicsUnit or []):
115
+ if isinstance(unit, cim.PhotoVoltaicUnit):
116
+ has_pv = True
117
+ elif isinstance(unit, cim.BatteryUnit):
118
+ has_storage = True
119
+ elif isinstance(eq, cim.SynchronousMachine):
120
+ has_sync = True
121
+
122
+ # Assign phases to node. Java appends "N" for primary nodes via GetPhases(false)
123
+ # and "S" for secondary. Python replicates that here.
124
+ sorted_phases = sorted("".join(set(sorted("".join(phases)))))
125
+ if is_triplex:
126
+ # collect_phases already returns the secondary form as "<letter>S", so the
127
+ # letters here may already carry the S — appending another would emit "CSS".
128
+ # GridLAB-D needs "<letter>S" ("CS"), never a bare "S": a bare S compiles
129
+ # but leaves the triplex with no primary phase, which surfaces as wrong
130
+ # secondary voltages at run time rather than as a load-time error.
131
+ letters = "".join(p for p in sorted_phases if p != "S")
132
+ if not letters:
133
+ raise ValueError(
134
+ f"node {node.name}: triplex node has no primary phase letter "
135
+ f"(collected {phases!r}); GridLAB-D requires 'AS'/'BS'/'CS'"
136
+ )
137
+ glm_node["phases"] = letters + "S"
138
+ elif sorted_phases:
139
+ glm_node["phases"] = "".join(sorted_phases) + "N"
140
+ else:
141
+ glm_node["phases"] = "ABCN"
142
+
143
+ # Assign base voltage to node.
144
+ # BaseVoltage.nominalVoltage is line-to-line (LL); divide by sqrt(3) or 2.
145
+ # TransformerEnd.ratedU is used as-is (already LN for the relevant end).
146
+ # Prefer the LL source (more common/reliable) when available.
147
+ ll_to_ln = 2.0 if is_triplex else math.sqrt(3)
148
+ if ll_voltages:
149
+ ln_cand = [v / ll_to_ln for v in set(ll_voltages)]
150
+ elif ln_voltages:
151
+ ln_cand = list(set(ln_voltages))
152
+ else:
153
+ ln_cand = []
154
+
155
+ if len(ln_cand) == 0:
156
+ _log.warning(f"Unable to determine base voltage of Node {node.name}")
157
+ glm_node["nominal_voltage"] = None
158
+ else:
159
+ if len(ln_cand) > 1:
160
+ _log.warning(f"Node {node.name} has multiple voltages; using lowest")
161
+ glm_node["nominal_voltage"] = min(ln_cand)
162
+
163
+ node_name = glm_node["name"]
164
+
165
+ # Convert dict to appropriate GLM schema dataclass
166
+ if is_swing_bus:
167
+ glm_node["bustype"] = "SWING"
168
+ # These values were hard-coded previously, keeping the same
169
+ glm_node["base_power"] = "12MVA"
170
+ glm_node["positive_sequence_voltage"] = "${VSOURCE}"
171
+ glm_node["power_convergence_value"] = "100VA"
172
+ glm_node["outside_comments"] = [f"EnergySource Name:{node.name}"]
173
+
174
+ # Create Substation dataclass instance
175
+ substation = glm_schema.Substation()
176
+ for key, value in glm_node.items():
177
+ setattr(substation, key, value)
178
+ glm_model.add_to_graph(substation)
179
+
180
+ elif is_triplex:
181
+ glm_node["outside_comments"] = [f"Name:{node.name}"]
182
+
183
+ # Create TriplexNode dataclass instance
184
+ triplex_node = glm_schema.TriplexNode()
185
+ for key, value in glm_node.items():
186
+ setattr(triplex_node, key, value)
187
+ glm_model.add_to_graph(triplex_node)
188
+
189
+ # Sub-meters for DER at triplex (secondary) nodes — mirrors Java AppendSubMeter
190
+ for suffix, present in (("_pvmtr", has_pv), ("_stmtr", has_storage), ("_dgmtr", has_sync)):
191
+ if not present:
192
+ continue
193
+ sub = glm_schema.TriplexMeter()
194
+ sub.name = node_name + suffix
195
+ sub.parent = node_name
196
+ sub.phases = glm_node["phases"]
197
+ sub.nominal_voltage = glm_node["nominal_voltage"]
198
+ glm_model.add_to_graph(sub)
199
+
200
+ else:
201
+ if has_storage or has_sync:
202
+ glm_node["bustype"] = "SWING_PQ"
203
+ glm_node["outside_comments"] = [f"Name:{node.name}"]
204
+
205
+ # Create Node dataclass instance
206
+ node_obj = glm_schema.Node()
207
+ for key, value in glm_node.items():
208
+ setattr(node_obj, key, value)
209
+ glm_model.add_to_graph(node_obj)
210
+
211
+ # Sub-meters for DER at primary nodes — mirrors Java AppendSubMeter
212
+ for suffix, present in (("_pvmtr", has_pv), ("_stmtr", has_storage), ("_dgmtr", has_sync)):
213
+ if not present:
214
+ continue
215
+ sub = glm_schema.Meter()
216
+ sub.name = node_name + suffix
217
+ sub.parent = node_name
218
+ sub.phases = glm_node["phases"]
219
+ sub.nominal_voltage = glm_node["nominal_voltage"]
220
+ glm_model.add_to_graph(sub)
@@ -0,0 +1,232 @@
1
+ """CIM to GridLAB-D GLM converter orchestrator.
2
+
3
+ This module coordinates the conversion from CIM (cimgraph) to GridLAB-D GLM format
4
+ following the cimhub architecture pattern (mirrors ``cimhub_opendss.cim_to_dss``):
5
+
6
+ CIM FeederModel -> registered converters -> GLM schema dataclasses
7
+ -> GraphModel -> GlmJsonWriter -> GLM-JSON file
8
+
9
+ The conversion process:
10
+ 1. Iterate CIM classes in dependency order (``EXPORT_ORDER``)
11
+ 2. Dispatch each instance to its registered converter via ``glm_exporter_registry``
12
+ 3. Converters add GLM schema dataclasses to the GraphModel
13
+ 4. Return the GraphModel (serialization handled by ``GlmJsonWriter``)
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+
19
+ import cimgraph.data_profile.cimhub_2026 as cim
20
+ from cimgraph.models import FeederModel
21
+
22
+ from cimhub_core import FormatExporter, GraphModel, get_base_frequency, set_base_frequency
23
+ from cimhub_gridlabd.exporter.glm_registry import glm_exporter_registry
24
+ from cimhub_gridlabd.exporter.loads.load import flush_load_accumulators
25
+
26
+ # Trigger converter registration by importing domain packages.
27
+ import cimhub_gridlabd.exporter.base # noqa: F401
28
+ import cimhub_gridlabd.exporter.lines # noqa: F401
29
+ import cimhub_gridlabd.exporter.switches # noqa: F401
30
+ import cimhub_gridlabd.exporter.transformers # noqa: F401
31
+ import cimhub_gridlabd.exporter.shunts # noqa: F401
32
+ import cimhub_gridlabd.exporter.generators # noqa: F401
33
+ import cimhub_gridlabd.exporter.loads # noqa: F401
34
+
35
+ _log = logging.getLogger(__name__)
36
+
37
+ __all__ = ["cim_to_glm", "cim_to_glm_json", "GlmExporter"]
38
+
39
+
40
+ # Conversion order: (CIM class to iterate, registry key for its converter).
41
+ #
42
+ # Most rows use the class itself as the registry key. Switch *subclasses*
43
+ # (Breaker, ProtectedSwitch, ...) have no converter of their own, so they route
44
+ # to a registered base converter. Note Breaker routes to the Recloser converter
45
+ # (a substation breaker is modeled as a recloser in GridLAB-D), preserving the
46
+ # historical hand-written behavior.
47
+ #
48
+ # Dependency rules baked into the ordering:
49
+ # - line/cable/impedance configs before ACLineSegment
50
+ # - TransformerMeshImpedance (-> transformer_configuration) before PowerTransformer
51
+ # - RatioTapChanger (regulator) after PowerTransformer
52
+ EXPORT_ORDER: list[tuple[type, type]] = [
53
+ # Connectivity
54
+ (cim.ConnectivityNode, cim.ConnectivityNode),
55
+
56
+ # Wire info (conductors) — must precede spacing and line configs
57
+ (cim.OverheadWireInfo, cim.OverheadWireInfo),
58
+ # cim.CableInfo is the abstract base of the two cable classes below and is
59
+ # never instantiated -- Java's DistCable likewise has no GetGLM (S04).
60
+ (cim.ConcentricNeutralCableInfo, cim.ConcentricNeutralCableInfo),
61
+ (cim.TapeShieldCableInfo, cim.TapeShieldCableInfo),
62
+
63
+ # Spacing — ConductorDistanceSpacing is the current path; WireSpacingInfo deprecated
64
+ (cim.ConductorDistanceSpacing, cim.ConductorDistanceSpacing),
65
+ (cim.WireSpacingInfo, cim.WireSpacingInfo),
66
+
67
+ # Impedance-matrix path (kept for models that use it)
68
+ (cim.WireAssemblyInfo, cim.WireAssemblyInfo),
69
+ (cim.PerLengthPhaseImpedance, cim.PerLengthPhaseImpedance),
70
+ (cim.PerLengthSequenceImpedance, cim.PerLengthSequenceImpedance),
71
+
72
+ # Lines — LineConfiguration emitted inline by the ACLineSegment converter
73
+ (cim.ACLineSegment, cim.ACLineSegment),
74
+
75
+ # Switches — reclosers (and substation breakers treated as reclosers)
76
+ (cim.Recloser, cim.Recloser),
77
+ (cim.Breaker, cim.Recloser),
78
+ # Fuses
79
+ (cim.Fuse, cim.Fuse),
80
+ # Other switch types route to the generic Switch converter
81
+ (cim.Switch, cim.Switch),
82
+ (cim.ProtectedSwitch, cim.Switch),
83
+ (cim.LoadBreakSwitch, cim.Switch),
84
+ (cim.Sectionaliser, cim.Switch),
85
+ (cim.Disconnector, cim.Switch),
86
+
87
+ # Transformers (config before the transformer that references it)
88
+ (cim.TransformerMeshImpedance, cim.TransformerMeshImpedance),
89
+ (cim.TransformerTankInfo, cim.TransformerTankInfo),
90
+ (cim.PowerTransformer, cim.PowerTransformer),
91
+ (cim.RatioTapChanger, cim.RatioTapChanger),
92
+
93
+ # Shunt devices
94
+ (cim.LinearShuntCompensator, cim.LinearShuntCompensator),
95
+
96
+ # Inverter-coupled DER
97
+ (cim.PowerElectronicsConnection, cim.PowerElectronicsConnection),
98
+ (cim.PhotoVoltaicUnit, cim.PhotoVoltaicUnit),
99
+ (cim.BatteryUnit, cim.BatteryUnit),
100
+
101
+ # Loads — accumulate-only; flush_load_accumulators() emits after the loop
102
+ (cim.EnergyConsumer, cim.EnergyConsumer),
103
+
104
+ # Rotating-machine DER — steady-state (EQ + SSH).
105
+ # Dynamics (IEC 61970-457) are a separate pass below, after EQ/SSH.
106
+ (cim.SynchronousMachine, cim.SynchronousMachine),
107
+ (cim.AsynchronousMachine, cim.AsynchronousMachine),
108
+ (cim.PowerElectronicsWindUnit, cim.PowerElectronicsWindUnit),
109
+
110
+ # Machine dynamics (DY) — must run AFTER the steady-state machines above so
111
+ # the DieselDg/WindturbDg objects already exist for dynamics to augment.
112
+ (cim.SynchronousMachineDynamics, cim.SynchronousMachineDynamics),
113
+ (cim.AsynchronousMachineDynamics, cim.AsynchronousMachineDynamics),
114
+ ]
115
+
116
+ # --------------------------------------------------------------------------
117
+ # TODO: CIM classes not yet mapped to GLM converters
118
+ # --------------------------------------------------------------------------
119
+ # s223.PhysicalSpace -> house objects (ASHRAE s223 replacement for
120
+ # the legacy CIM house objects)
121
+
122
+
123
+ def _convert_class(
124
+ cim_class: type,
125
+ registry_key: type,
126
+ network: FeederModel,
127
+ glm_model: GraphModel,
128
+ ) -> int:
129
+ """Convert all instances of *cim_class* using the *registry_key* converter.
130
+
131
+ GLM converters mutate *glm_model* in place (calling ``add_to_graph``), so
132
+ there is no return value to collect. Returns the number of instances
133
+ converted, for logging.
134
+ """
135
+ converter = glm_exporter_registry.get(registry_key)
136
+ if converter is None:
137
+ _log.warning("No converter registered for %s", registry_key.__name__)
138
+ return 0
139
+
140
+ try:
141
+ instances = network.graph.get(cim_class, {}).values()
142
+ except (AttributeError, TypeError):
143
+ return 0
144
+
145
+ count = 0
146
+ for obj in instances:
147
+ try:
148
+ converter(obj, glm_model)
149
+ count += 1
150
+ except Exception as e: # noqa: BLE001 — log and continue per object
151
+ _log.error(
152
+ "Failed to convert %s '%s': %s",
153
+ cim_class.__name__,
154
+ getattr(obj, "name", "?"),
155
+ e,
156
+ exc_info=True,
157
+ )
158
+ return count
159
+
160
+
161
+ def cim_to_glm(network: FeederModel) -> GraphModel:
162
+ """Convert a CIM network to a GLM ``GraphModel``.
163
+
164
+ Iterates CIM classes in dependency order (``EXPORT_ORDER``), dispatches each
165
+ object to its registered converter, and returns the populated GraphModel of
166
+ GLM schema dataclass instances. Serialization is handled separately by
167
+ :class:`~cimhub_gridlabd.exporter.glm_writer.GlmJsonWriter`.
168
+
169
+ This is the implementation behind :meth:`GlmExporter.to_model`; both are
170
+ public and equivalent.
171
+
172
+ Args:
173
+ network: CIM network model (FeederModel).
174
+
175
+ Returns:
176
+ GraphModel containing GLM schema dataclass instances.
177
+ """
178
+ glm_model = GraphModel()
179
+
180
+ # Carry the CIM system frequency onto the output model — converters need it
181
+ # for susceptance→capacitance conversions and the GLM graph has no
182
+ # BaseFrequency of its own.
183
+ set_base_frequency(glm_model, get_base_frequency(network, cim))
184
+
185
+ for cim_class, registry_key in EXPORT_ORDER:
186
+ count = _convert_class(cim_class, registry_key, network, glm_model)
187
+ if count:
188
+ _log.info("Converted %d %s", count, cim_class.__name__)
189
+
190
+ # Flush per-node load accumulators — must run after all EnergyConsumers
191
+ n_loads = flush_load_accumulators(glm_model)
192
+ if n_loads:
193
+ _log.info("Emitted %d load objects from accumulators", n_loads)
194
+
195
+ return glm_model
196
+
197
+
198
+ class GlmExporter(FormatExporter):
199
+ """CIM → GridLAB-D exporter implementing the :class:`FormatExporter` contract.
200
+
201
+ Returns a ``GraphModel`` of GLM objects; writing is the writers' job::
202
+
203
+ glm = GlmExporter().to_model(network)
204
+ GlmJsonWriter().write(glm, "out.json") # GLM-JSON
205
+ GlmTextWriter().write(glm, "out.glm") # GLM text
206
+
207
+ :func:`cim_to_glm_json` is the convenience wrapper for the JSON form. See
208
+ ``cimhub_core/development/CONVERTER_API.md``.
209
+ """
210
+
211
+ def to_model(self, network: FeederModel, **opts) -> GraphModel:
212
+ """Convert *network* to a GraphModel of GLM schema dataclasses."""
213
+ return cim_to_glm(network)
214
+
215
+
216
+ def cim_to_glm_json(network: FeederModel, output_file: str) -> None:
217
+ """Convert a CIM FeederModel to a GLM-JSON file.
218
+
219
+ Convenience wrapper that calls :func:`cim_to_glm` to build the GraphModel
220
+ and then serializes it with
221
+ :class:`~cimhub_gridlabd.exporter.glm_writer.GlmJsonWriter`.
222
+
223
+ Args:
224
+ network: CIM network model (FeederModel).
225
+ output_file: Destination path for the GLM-JSON output file.
226
+ """
227
+ from cimhub_gridlabd.exporter.glm_writer import GlmJsonWriter # noqa: PLC0415
228
+
229
+ glm_model = cim_to_glm(network)
230
+ writer = GlmJsonWriter()
231
+ writer.write(glm_model, output_file)
232
+ _log.info("Wrote GLM-JSON to %s", output_file)
@@ -0,0 +1,14 @@
1
+ from cimhub_gridlabd.exporter.generators.battery import convert_battery_unit
2
+ from cimhub_gridlabd.exporter.generators.inverter import \
3
+ convert_power_electronics_connection
4
+ from cimhub_gridlabd.exporter.generators.solar import \
5
+ convert_photovoltaic_unit
6
+ from cimhub_gridlabd.exporter.generators.machine import (
7
+ convert_synchronous_machine,
8
+ convert_asynchronous_machine,
9
+ convert_wind_unit,
10
+ )
11
+ from cimhub_gridlabd.exporter.generators.machine_dynamics import (
12
+ convert_synchronous_machine_dynamics,
13
+ convert_asynchronous_machine_dynamics,
14
+ )
@@ -0,0 +1,66 @@
1
+ """Convert CIM BatteryUnit to a GridLAB-D battery object.
2
+
3
+ The battery object is the DC-side storage behind an inverter; its ``parent`` is
4
+ the inverter emitted from the owning :class:`PowerElectronicsConnection` (see
5
+ ``inverter.py``).
6
+
7
+ CIM carries no cell chemistry, round-trip efficiency, or DC bus voltage, so
8
+ those come from the Java reference's hardcodes (``DistStorage.java:202-206``) and
9
+ are logged as X1 in ``docs/refactor/CIM_PROFILE_GAPS.md``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+
16
+ import cimgraph.data_profile.cimhub_2026 as cim
17
+
18
+ from cimhub_core import GraphModel
19
+ from cimhub_gridlabd.schema import gridlabd as glm_schema
20
+ from cimhub_gridlabd.exporter.glm_registry import glm_exporter_registry
21
+ from cimhub_gridlabd.exporter.generators.inverter import (
22
+ der_base_name,
23
+ inverter_name_for,
24
+ )
25
+
26
+ _log = logging.getLogger(__name__)
27
+
28
+ # DC bus voltage of the battery bank. Not the connection's ratedU, which is the
29
+ # AC side (DistStorage.java:202 hardcodes 48).
30
+ _DC_NOMINAL_VOLTAGE = 48
31
+ _BATTERY_TYPE = "LI_ION"
32
+ _ROUND_TRIP_EFFICIENCY = 0.86
33
+
34
+
35
+ @glm_exporter_registry.register(cim.BatteryUnit)
36
+ def convert_battery_unit(
37
+ battery_unit: cim.BatteryUnit, glm_model: GraphModel
38
+ ) -> None:
39
+ """Emit the GLM battery object for one battery unit."""
40
+ battery = glm_schema.Battery()
41
+ battery.name = f"bat_{der_base_name(battery_unit)}"
42
+ battery.parent = inverter_name_for(battery_unit)
43
+ battery.nominal_voltage = _DC_NOMINAL_VOLTAGE
44
+
45
+ # GLM battery_capacity is in watt-hours. RealEnergy's SI base is Wh, so
46
+ # .to("Wh") is the identity here — but state it explicitly rather than
47
+ # relying on the base unit, and never .to("J") (a 3600x inflation).
48
+ rated_e = battery_unit.ratedE
49
+ stored_e = battery_unit.storedE
50
+ battery.battery_capacity = rated_e.to("Wh") if rated_e is not None else None
51
+ if rated_e is not None and stored_e is not None:
52
+ rated_wh = rated_e.to("Wh")
53
+ battery.state_of_charge = stored_e.to("Wh") / rated_wh if rated_wh else None
54
+
55
+ # rated_power is the battery's power rating, max(maxP, |minP|) in the Java
56
+ # (DistStorage.java:86 ratedP, emitted at :207).
57
+ max_p = battery_unit.maxP.to("W") if battery_unit.maxP is not None else None
58
+ min_p = battery_unit.minP.to("W") if battery_unit.minP is not None else None
59
+ if max_p is not None or min_p is not None:
60
+ battery.rated_power = max(abs(max_p or 0.0), abs(min_p or 0.0))
61
+
62
+ battery.use_internal_battery_model = True
63
+ battery.battery_type = _BATTERY_TYPE
64
+ battery.round_trip_efficiency = _ROUND_TRIP_EFFICIENCY
65
+
66
+ glm_model.add_to_graph(battery)