cimhub-core 2.0.0a0__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 (36) hide show
  1. cimhub_core/__init__.py +54 -0
  2. cimhub_core/base.py +162 -0
  3. cimhub_core/connectivity/__init__.py +32 -0
  4. cimhub_core/connectivity/base_voltage.py +215 -0
  5. cimhub_core/connectivity/lookup.py +24 -0
  6. cimhub_core/connectivity/nodes.py +58 -0
  7. cimhub_core/connectivity/terminals.py +83 -0
  8. cimhub_core/domains.py +71 -0
  9. cimhub_core/get_utils/__init__.py +5 -0
  10. cimhub_core/get_utils/get_base_voltage.py +23 -0
  11. cimhub_core/get_utils/get_substation.py +21 -0
  12. cimhub_core/get_utils/get_voltage_level.py +25 -0
  13. cimhub_core/get_utils/mermaid.py +275 -0
  14. cimhub_core/graph_model.py +176 -0
  15. cimhub_core/mcp/__init__.py +37 -0
  16. cimhub_core/mcp/connection.py +249 -0
  17. cimhub_core/mcp/dual_transport_service.py +442 -0
  18. cimhub_core/mcp/jsonrpc.py +129 -0
  19. cimhub_core/mcp/topics.py +35 -0
  20. cimhub_core/registry.py +70 -0
  21. cimhub_core/scaffold.py +531 -0
  22. cimhub_core/serialization.py +513 -0
  23. cimhub_core/transformations/__init__.py +3 -0
  24. cimhub_core/transformations/lines/__init__.py +7 -0
  25. cimhub_core/transformations/lines/conductor_distance_to_wire_positions.py +291 -0
  26. cimhub_core/transformations/lines/wire_position_to_wire_spacing.py +35 -0
  27. cimhub_core/transformations/loads/__init__.py +13 -0
  28. cimhub_core/transformations/loads/load_response.py +150 -0
  29. cimhub_core/transformations/transformers/__init__.py +64 -0
  30. cimhub_core/transformations/transformers/impedance.py +333 -0
  31. cimhub_core/transformations/transformers/per_unit.py +280 -0
  32. cimhub_core/transformations/transformers/test_data.py +391 -0
  33. cimhub_core-2.0.0a0.dist-info/METADATA +104 -0
  34. cimhub_core-2.0.0a0.dist-info/RECORD +36 -0
  35. cimhub_core-2.0.0a0.dist-info/WHEEL +5 -0
  36. cimhub_core-2.0.0a0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,54 @@
1
+ """CIMHub core — shared foundation for all CIMHub sub-packages.
2
+
3
+ Public API:
4
+ GraphModel — sorted-dictionary data store for LinkML dataclasses
5
+ ConverterRegistry — decorator-based schema-to-function dispatcher
6
+ FormatReader — ABC for parsing native files into dataclasses
7
+ FormatWriter — ABC for writing dataclasses to native files
8
+ FormatImporter — ABC for native format → CIM conversion (to_cim)
9
+ FormatExporter — ABC for CIM → native format conversion (to_format)
10
+ See development/CONVERTER_API.md for the contract.
11
+ scaffold_package — generate directory tree for a new sub-package
12
+ get_mermaid — render a LinkML dataclass instance/class as a mermaid diagram
13
+ download_mermaid — render a mermaid diagram to an image via mermaid.ink
14
+
15
+ Serialization utilities (for FormatWriter implementations):
16
+ AnnotationSerializer — automatic serialization driven by LinkML annotations
17
+ get_schema_annotations — load annotations from YAML schema at runtime
18
+ get_field_order — get field names in annotated order
19
+ get_native_name — resolve native format name for a field
20
+ format_by_spec — format a value using a format specification
21
+ """
22
+
23
+ __version__ = "2.0.0a0"
24
+
25
+ from cimhub_core.base import FormatExporter, FormatImporter, FormatReader, FormatWriter
26
+ from cimhub_core.get_utils import download_mermaid, get_mermaid
27
+ from cimhub_core.graph_model import GraphModel
28
+ from cimhub_core.registry import ConverterRegistry
29
+ from cimhub_core.scaffold import scaffold_package
30
+ from cimhub_core.serialization import (
31
+ AnnotationSerializer,
32
+ format_by_spec,
33
+ get_field_order,
34
+ get_native_name,
35
+ get_schema_annotations,
36
+ )
37
+
38
+ __all__ = [
39
+ "GraphModel",
40
+ "ConverterRegistry",
41
+ "FormatReader",
42
+ "FormatWriter",
43
+ "FormatImporter",
44
+ "FormatExporter",
45
+ "scaffold_package",
46
+ "get_mermaid",
47
+ "download_mermaid",
48
+ # Serialization utilities
49
+ "AnnotationSerializer",
50
+ "get_schema_annotations",
51
+ "get_field_order",
52
+ "get_native_name",
53
+ "format_by_spec",
54
+ ]
cimhub_core/base.py ADDED
@@ -0,0 +1,162 @@
1
+ """Abstract base classes for format-specific I/O and conversion.
2
+
3
+ Every CIMHub sub-package implements one or more of these interfaces to
4
+ bridge its native file format with LinkML-generated dataclasses and the
5
+ CIM graph model.
6
+
7
+ Serialization layer (file ↔ LinkML objects):
8
+ FormatReader — parse native files into dataclass instances
9
+ FormatWriter — write dataclass instances back to native files
10
+
11
+ Conversion layer (LinkML objects ↔ CIM graph):
12
+ FormatImporter — native format → CIM graph
13
+ FormatExporter — CIM graph → native format
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from abc import ABC, abstractmethod
19
+ from typing import Any, Optional, Type
20
+
21
+ __all__ = ["FormatReader", "FormatWriter", "FormatImporter", "FormatExporter"]
22
+
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Serialization
26
+ # ---------------------------------------------------------------------------
27
+
28
+ class FormatReader(ABC):
29
+ """Parse native format files into LinkML dataclass instances."""
30
+
31
+ @abstractmethod
32
+ def read(self, source: str, schema_class: Type) -> list:
33
+ """Read *source* and return a list of *schema_class* instances.
34
+
35
+ Args:
36
+ source: Path to file or directory containing format-specific data.
37
+ schema_class: The LinkML-generated dataclass type to instantiate.
38
+
39
+ Returns:
40
+ List of populated dataclass instances.
41
+ """
42
+ ...
43
+
44
+
45
+ class FormatWriter(ABC):
46
+ """Write LinkML dataclass instances to native format files."""
47
+
48
+ @abstractmethod
49
+ def write(self, objects: list, destination: str) -> None:
50
+ """Write *objects* to *destination* in the native format.
51
+
52
+ Args:
53
+ objects: List of LinkML-generated dataclass instances.
54
+ destination: Path to output file or directory.
55
+ """
56
+ ...
57
+
58
+ @abstractmethod
59
+ def serialize(self, obj) -> str:
60
+ """Convert a single dataclass instance to its native format string.
61
+
62
+ Returns:
63
+ The native representation (DSS command, RAW record, GLM block, etc.).
64
+ """
65
+ ...
66
+
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # Conversion
70
+ # ---------------------------------------------------------------------------
71
+
72
+ class FormatImporter(ABC):
73
+ """Read a native format, convert to CIM, and return a populated graph model.
74
+
75
+ This is the canonical contract for every CIMHub importer. Subclasses declare
76
+ the concrete cimgraph model type they produce (``model_cls``) and the
77
+ ``FormatReader`` they parse with (``reader_cls``), then implement
78
+ :meth:`to_cim` to drive the per-record conversion loop. The base class
79
+ provides :meth:`make_network` and :meth:`make_reader` so subclasses never
80
+ repeat the create-or-reuse boilerplate.
81
+
82
+ Each format also exposes a thin convenience function — ``<fmt>_to_cim`` —
83
+ that delegates to ``to_cim`` so users get a one-liner::
84
+
85
+ feeder = dss_to_cim("Master.dss") # convenience
86
+ feeder = DssImporter().to_cim("Master.dss") # equivalent
87
+
88
+ See ``cimhub_core/development/CONVERTER_API.md`` for the full spec.
89
+ """
90
+
91
+ #: Concrete cimgraph GraphModel subclass this importer populates
92
+ #: (e.g. ``FeederModel``, ``NodeBreakerModel``, ``BusBranchModel``).
93
+ model_cls: type
94
+
95
+ #: ``FormatReader`` subclass used to parse the native source. May be ``None``
96
+ #: for formats whose ``source`` is an in-memory object (e.g. GDM).
97
+ reader_cls: Optional[type] = None
98
+
99
+ @abstractmethod
100
+ def to_cim(self, source: Any, *, network=None, reader=None):
101
+ """Convert *source* to CIM and return the populated graph model.
102
+
103
+ Args:
104
+ source: Path to a file/directory (``str`` or ``Path``), or an
105
+ in-memory native object for formats without a file representation.
106
+ network: Existing graph model to populate. If ``None``, a new
107
+ ``model_cls`` is created via :meth:`make_network`.
108
+ reader: Existing ``FormatReader`` to parse with. If ``None``, a new
109
+ ``reader_cls`` is created via :meth:`make_reader`. Ignored by
110
+ formats whose ``source`` is already in memory.
111
+
112
+ Returns:
113
+ A populated cimgraph ``GraphModel`` subclass (never raw records).
114
+ """
115
+ ...
116
+
117
+ def make_network(self, network=None):
118
+ """Return *network* if given, else a fresh empty ``self.model_cls``."""
119
+ if network is not None:
120
+ return network
121
+ from cimgraph.databases import XMLFile
122
+ return self.model_cls(connection=XMLFile(""), container=None)
123
+
124
+ def make_reader(self, reader=None):
125
+ """Return *reader* if given, else a fresh ``self.reader_cls`` instance."""
126
+ if reader is not None:
127
+ return reader
128
+ if self.reader_cls is None:
129
+ raise TypeError(
130
+ f"{type(self).__name__} has no reader_cls; "
131
+ f"its source is consumed in memory"
132
+ )
133
+ return self.reader_cls()
134
+
135
+
136
+ class FormatExporter(ABC):
137
+ """Traverse a CIM graph model and emit a native format.
138
+
139
+ Mirror of :class:`FormatImporter`. The first argument is always the CIM
140
+ ``network`` (never a file path); the second is the ``destination`` (output
141
+ path, or an in-memory sink for formats like GDM). The return value is the
142
+ native artifact (a commands dict, an in-memory model, DataFrames) or
143
+ ``None`` when the exporter only writes files — documented per format.
144
+
145
+ Each format exposes a thin ``cim_to_<fmt>`` convenience function delegating
146
+ to :meth:`to_format`. See ``CONVERTER_API.md`` for the full spec.
147
+ """
148
+
149
+ @abstractmethod
150
+ def to_format(self, network, destination: Any, **opts):
151
+ """Convert CIM objects in *network* and write/return the native format.
152
+
153
+ Args:
154
+ network: A cimgraph ``GraphModel`` containing CIM objects.
155
+ destination: Output file/directory path, or an in-memory target for
156
+ formats without a file representation.
157
+ **opts: Format-specific options (e.g. ``system_base_mva``).
158
+
159
+ Returns:
160
+ The native artifact, or ``None`` if the exporter only writes files.
161
+ """
162
+ ...
@@ -0,0 +1,32 @@
1
+ """Shared connectivity helpers for CIM converters.
2
+
3
+ Terminal/ConnectivityNode wiring is identical across every cimhub importer:
4
+ a Terminal links a piece of ConductingEquipment to a ConnectivityNode, and CIM
5
+ requires *both* directions of every association to be populated
6
+ (``terminal.ConductingEquipment``/``equipment.Terminals`` and
7
+ ``terminal.ConnectivityNode``/``connectivity_node.Terminals``). Exporters read the
8
+ back-references, so a converter that sets only the forward ref produces a graph that
9
+ looks wired but breaks downstream.
10
+
11
+ These helpers centralize that wiring. They are profile-agnostic: the CIM classes are
12
+ resolved at runtime from ``network.cim`` (the active data profile on the GraphModel),
13
+ so the same helper works for any profile (cim17v40, cimhub_2026, ...). The top-level
14
+ ``import ... as cim`` is for typing/IDE only and is never used at runtime.
15
+ """
16
+
17
+ from cimhub_core.connectivity.base_voltage import (
18
+ get_or_create_base_voltage,
19
+ propagate_base_voltages,
20
+ )
21
+ from cimhub_core.connectivity.lookup import find_by_name
22
+ from cimhub_core.connectivity.nodes import get_or_create_connectivity_node
23
+ from cimhub_core.connectivity.terminals import attach_terminal_to_node, link_terminal
24
+
25
+ __all__ = [
26
+ "link_terminal",
27
+ "attach_terminal_to_node",
28
+ "get_or_create_connectivity_node",
29
+ "find_by_name",
30
+ "propagate_base_voltages",
31
+ "get_or_create_base_voltage",
32
+ ]
@@ -0,0 +1,215 @@
1
+ """BFS base-voltage propagation across a CIM feeder.
2
+
3
+ A converted feeder often has BaseVoltage set only on the source and the
4
+ transformer windings (the equipment that actually *defines* a voltage level).
5
+ Lines, switches, loads, and shunts inherit their level from whatever they are
6
+ connected to. This pass walks the connectivity graph outward from each
7
+ ``EnergySource`` and assigns ``BaseVoltage`` to every ``ConductingEquipment`` it
8
+ reaches, stepping the voltage at each transformer via the winding ``ratedU``.
9
+
10
+ Only ``BaseVoltage`` is assigned — ``EquipmentContainer`` is deliberately left
11
+ untouched. Equipment keeps the container its importer gave it (a Feeder for
12
+ ordinary distribution equipment); moving equipment into a VoltageLevel for CGMES
13
+ "better containment" applies only to substation equipment and is a separate
14
+ concern handled elsewhere.
15
+
16
+ CIM classes are resolved from ``feeder.cim`` at runtime, so this works for any
17
+ data profile. The top-level import is for typing/IDE only.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import logging
23
+ from collections import deque
24
+
25
+ import cimgraph.data_profile.cimhub_2026 as cim # typing/IDE only; runtime uses feeder.cim
26
+ from cimgraph.models import FeederModel
27
+
28
+ __all__ = ["propagate_base_voltages", "get_or_create_base_voltage"]
29
+
30
+ _log = logging.getLogger(__name__)
31
+
32
+
33
+ def get_or_create_base_voltage(feeder: FeederModel, nominal_kv: float):
34
+ """Return a BaseVoltage at *nominal_kv* (within 1%), creating it if absent.
35
+
36
+ Uses an exact class scan with a kV tolerance compare rather than
37
+ ``find_by_attribute`` (which does a substring match on the raw value and
38
+ cannot compare against a CIMUnit-typed ``nominalVoltage``).
39
+ """
40
+ cim_ = feeder.cim
41
+ tolerance_kv = nominal_kv * 0.01
42
+
43
+ for base_v in feeder.list_by_class(cim_.BaseVoltage):
44
+ nv = base_v.nominalVoltage
45
+ existing_kv = float(nv.to("kV")) if hasattr(nv, "to") else float(nv) / 1000.0
46
+ if abs(existing_kv - nominal_kv) < tolerance_kv:
47
+ return base_v
48
+
49
+ base_voltage = cim_.BaseVoltage(name=f"BaseV_{nominal_kv:.3f}kV")
50
+ base_voltage.nominalVoltage = cim_.Voltage(nominal_kv, "kV")
51
+ feeder.add_to_graph(base_voltage)
52
+ return base_voltage
53
+
54
+
55
+ def propagate_base_voltages(feeder: FeederModel, *, overwrite: bool = False) -> int:
56
+ """BFS from every EnergySource, assigning BaseVoltage to all reachable equipment.
57
+
58
+ Args:
59
+ feeder: CIM feeder model. Requires populated terminal/node back-references
60
+ (``cn.Terminals``, ``equipment.Terminals``, ``end.Terminal``,
61
+ ``PowerTransformer.PowerTransformerEnd``).
62
+ overwrite: If True, reassign even equipment that already has a BaseVoltage.
63
+ If False (default), only fill in equipment whose BaseVoltage is None.
64
+
65
+ Returns:
66
+ Number of ConductingEquipment elements assigned a BaseVoltage.
67
+ """
68
+ cim_ = feeder.cim
69
+
70
+ queue: deque[tuple[object, float]] = deque()
71
+ visited: set[str] = set()
72
+ count = 0
73
+
74
+ for src in feeder.graph.get(cim_.EnergySource, {}).values():
75
+ if src.nominalVoltage is None:
76
+ _log.warning("EnergySource %s has no nominalVoltage — skipping", src.name)
77
+ continue
78
+ if not src.Terminals:
79
+ _log.warning("EnergySource %s has no Terminals — skipping", src.name)
80
+ continue
81
+ kv = float(src.nominalVoltage.to("kV"))
82
+ for t in src.Terminals:
83
+ cn = t.ConnectivityNode
84
+ if cn is not None:
85
+ queue.append((cn, kv))
86
+
87
+ if not queue:
88
+ _log.warning("No EnergySource seeds found — base voltage propagation skipped")
89
+ return 0
90
+
91
+ while queue:
92
+ cn, voltage_kv = queue.popleft()
93
+ if cn is None or cn.mRID in visited:
94
+ continue
95
+ visited.add(cn.mRID)
96
+
97
+ for terminal in cn.Terminals:
98
+ equipment = terminal.ConductingEquipment
99
+ # A TransformerTankEnd terminal carries no ConductingEquipment; resolve
100
+ # its bank PowerTransformer through the tank end instead.
101
+ if equipment is None:
102
+ equipment = _bank_from_tank_terminal(terminal)
103
+ if equipment is None:
104
+ continue
105
+
106
+ if isinstance(equipment, cim_.PowerTransformer):
107
+ count += _step_through_transformer(
108
+ equipment, cn, voltage_kv, feeder, visited, queue, overwrite, cim_
109
+ )
110
+ else:
111
+ if overwrite or getattr(equipment, "BaseVoltage", None) is None:
112
+ equipment.BaseVoltage = get_or_create_base_voltage(feeder, voltage_kv)
113
+ count += 1
114
+ for other in equipment.Terminals:
115
+ if other is terminal:
116
+ continue
117
+ other_cn = other.ConnectivityNode
118
+ if other_cn is not None and other_cn.mRID not in visited:
119
+ queue.append((other_cn, voltage_kv))
120
+
121
+ _log.info("propagate_base_voltages: assigned %d elements", count)
122
+ return count
123
+
124
+
125
+ def _tank_end_voltage_kv(tank_end) -> float | None:
126
+ """Return a tank end's winding voltage in kV, or None if unavailable.
127
+
128
+ The DSS importer already assigns the correct per-winding ``BaseVoltage`` to
129
+ each ``TransformerTankEnd`` (e.g. 12.47 kV primary, 0.208 kV secondary for a
130
+ split-phase service transformer), so that is the source of truth. Fall back
131
+ to the winding rating on ``TransformerTankInfo.TransformerEndInfos`` when a
132
+ tank end has no BaseVoltage.
133
+ """
134
+ bv = getattr(tank_end, "BaseVoltage", None)
135
+ if bv is not None and bv.nominalVoltage is not None:
136
+ nv = bv.nominalVoltage
137
+ return float(nv.to("kV")) if hasattr(nv, "to") else float(nv) / 1000.0
138
+
139
+ tank = getattr(tank_end, "TransformerTank", None)
140
+ info = getattr(tank, "TransformerTankInfo", None) if tank is not None else None
141
+ if info is not None:
142
+ for ei in getattr(info, "TransformerEndInfos", []) or []:
143
+ if ei.endNumber == tank_end.endNumber:
144
+ rated = getattr(ei, "ratedVoltage", None)
145
+ if rated is not None:
146
+ return float(rated.to("kV")) if hasattr(rated, "to") else float(rated) / 1000.0
147
+ return None
148
+
149
+
150
+ def _bank_from_tank_terminal(terminal):
151
+ """Resolve the bank PowerTransformer behind a TransformerTankEnd terminal.
152
+
153
+ Tank-end terminals are wired via ``terminal.TransformerEnd`` (a
154
+ TransformerTankEnd), not ``ConductingEquipment``, since a TransformerTank is
155
+ Equipment rather than ConductingEquipment. Return the tank's bank
156
+ PowerTransformer, or None if this is not a tank terminal.
157
+ """
158
+ for end in getattr(terminal, "TransformerEnd", []) or []:
159
+ tank = getattr(end, "TransformerTank", None)
160
+ if tank is not None:
161
+ return getattr(tank, "PowerTransformer", None)
162
+ return None
163
+
164
+
165
+ def _step_through_transformer(
166
+ xformer,
167
+ arriving_cn,
168
+ upstream_kv: float,
169
+ feeder: FeederModel,
170
+ visited: set[str],
171
+ queue: deque[tuple[object, float]],
172
+ overwrite: bool,
173
+ cim_,
174
+ ) -> int:
175
+ """Enqueue each winding node not on the arriving CN at its ratedU voltage.
176
+ Returns 1 if the transformer was assigned a BaseVoltage, else 0."""
177
+ count = 0
178
+ arriving_cn_mrid = arriving_cn.mRID
179
+
180
+ # Transformers modeled as TransformerTanks carry no PowerTransformerEnd; each
181
+ # winding's voltage lives on its TransformerTankEnd.BaseVoltage (importer-
182
+ # assigned). Step each downstream node to that winding voltage. This covers
183
+ # both service transformers (12.47 → 0.208 kV) and banked regulators
184
+ # (7.2 → 7.2 kV, i.e. effectively 1:1) with the same logic. When a winding
185
+ # voltage is unavailable, fall back to the arriving voltage (1:1).
186
+ if not xformer.PowerTransformerEnd and xformer.TransformerTanks:
187
+ for tank in xformer.TransformerTanks:
188
+ for tte in tank.TransformerTankEnds:
189
+ if tte.Terminal is None:
190
+ continue
191
+ cn = tte.Terminal.ConnectivityNode
192
+ if cn is None or cn.mRID == arriving_cn_mrid:
193
+ continue
194
+ downstream_kv = _tank_end_voltage_kv(tte) or upstream_kv
195
+ if cn.mRID not in visited:
196
+ queue.append((cn, downstream_kv))
197
+ return count
198
+
199
+ for end in xformer.PowerTransformerEnd:
200
+ if end.Terminal is None:
201
+ continue
202
+ cn = end.Terminal.ConnectivityNode
203
+ if cn is None or cn.mRID == arriving_cn_mrid:
204
+ continue
205
+ if end.ratedU is None:
206
+ _log.warning(
207
+ "PowerTransformerEnd on %s has no ratedU — cannot propagate downstream",
208
+ xformer.name,
209
+ )
210
+ continue
211
+ downstream_kv = float(end.ratedU.to("kV"))
212
+ if cn.mRID not in visited:
213
+ queue.append((cn, downstream_kv))
214
+
215
+ return count
@@ -0,0 +1,24 @@
1
+ """Exact-name lookup over a UUID-keyed cimgraph graph.
2
+
3
+ ``cimgraph`` GraphModels (FeederModel, ...) key ``graph[cls]`` by object UUID, and
4
+ ``find_by_attribute`` does a *substring* match — unsafe when names are numeric
5
+ substrings of each other (``'6'`` matches ``'632'``). Converters that resolve CIM
6
+ objects by their catalog name/ID (wire info, per-length impedance, base voltage, ...)
7
+ need an exact match instead.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Optional
13
+
14
+
15
+ def find_by_name(network, cim_class: type, name: str) -> Optional[object]:
16
+ """Return the single object of *cim_class* whose ``name`` equals *name* exactly.
17
+
18
+ Returns ``None`` if no object matches. Resolves against ``network.graph`` so it
19
+ works on any cimgraph GraphModel regardless of key type.
20
+ """
21
+ for obj in network.graph.get(cim_class, {}).values():
22
+ if obj.name == name:
23
+ return obj
24
+ return None
@@ -0,0 +1,58 @@
1
+ """ConnectivityNode helpers shared across CIM converters.
2
+
3
+ ConnectivityNodes represent buses. A converter must ensure exactly one node exists
4
+ per unique bus name. The CIM classes are resolved from ``network.cim`` at runtime so
5
+ this works with any data profile; the top-level import is for typing only.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Optional
11
+
12
+ import cimgraph.data_profile.cimhub_2026 as cim # typing/IDE only; runtime uses network.cim
13
+
14
+ from cimhub_core.connectivity.lookup import find_by_name
15
+
16
+
17
+ def get_or_create_connectivity_node(
18
+ network,
19
+ name: str,
20
+ *,
21
+ base_voltage: Optional[cim.BaseVoltage] = None,
22
+ container: Optional[object] = None,
23
+ ) -> cim.ConnectivityNode:
24
+ """Find (by exact name) or create a ConnectivityNode.
25
+
26
+ Bus names are normalized to lowercase so that case-insensitive DSS bus
27
+ references (e.g. ``SourceBus`` vs ``sourcebus``) resolve to the same node.
28
+
29
+ Uses an exact-name scan over the graph rather than ``find_by_attribute``, which
30
+ does a substring match — unsafe when node names are numeric substrings of each
31
+ other (e.g. ``'6'`` would match ``'632'``).
32
+
33
+ Args:
34
+ network: GraphModel (its ``.cim`` selects the data profile).
35
+ name: Unique bus name (normalized to lowercase on lookup and creation).
36
+ base_voltage: Optional BaseVoltage to set on a newly created node.
37
+ container: Optional ConnectivityNodeContainer (e.g. VoltageLevel). When set,
38
+ the reverse ``container.ConnectivityNodes`` list is populated too.
39
+
40
+ Returns:
41
+ The existing or newly created ConnectivityNode.
42
+ """
43
+ cim_ = network.cim
44
+ name = name.lower()
45
+ existing = find_by_name(network, cim_.ConnectivityNode, name)
46
+ if existing is not None:
47
+ return existing
48
+
49
+ node = cim_.ConnectivityNode(name=name)
50
+ if base_voltage is not None:
51
+ node.BaseVoltage = base_voltage
52
+ if container is not None:
53
+ node.ConnectivityNodeContainer = container
54
+ if node not in container.ConnectivityNodes:
55
+ container.ConnectivityNodes.append(node)
56
+
57
+ network.add_to_graph(node)
58
+ return node
@@ -0,0 +1,83 @@
1
+ """Terminal wiring helpers shared across CIM converters.
2
+
3
+ A CIM ``Terminal`` is the connection point between a piece of
4
+ ``ConductingEquipment`` and a ``ConnectivityNode``. Both ends of each association
5
+ must be populated for the graph to be traversable by exporters:
6
+
7
+ terminal.ConductingEquipment = equipment equipment.Terminals.append(terminal)
8
+ terminal.ConnectivityNode = node node.Terminals.append(terminal)
9
+
10
+ The CIM classes are resolved from ``network.cim`` at runtime so these functions work
11
+ with any data profile. The top-level import is for typing only.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Optional
17
+
18
+ import cimgraph.data_profile.cimhub_2026 as cim # typing/IDE only; runtime uses network.cim
19
+
20
+
21
+ def link_terminal(
22
+ network,
23
+ equipment: cim.ConductingEquipment,
24
+ connectivity_node: Optional[cim.ConnectivityNode] = None,
25
+ *,
26
+ sequence_number: int = 1,
27
+ phases: Optional[cim.PhaseCode] = None,
28
+ name: Optional[str] = None,
29
+ ) -> cim.Terminal:
30
+ """Create a Terminal and wire both directions of its associations.
31
+
32
+ Args:
33
+ network: GraphModel (its ``.cim`` selects the data profile).
34
+ equipment: ConductingEquipment the terminal belongs to.
35
+ connectivity_node: ConnectivityNode to attach to. May be ``None`` when the
36
+ node is wired later by a topology pass (the equipment back-reference is
37
+ still set so ``equipment.Terminals`` is populated immediately).
38
+ sequence_number: Terminal sequence number (1, 2, ...).
39
+ phases: Already-resolved ``cim.PhaseCode`` (format-specific phase parsing
40
+ belongs in the calling converter, not here).
41
+ name: Terminal name. Defaults to ``f"{equipment.name}_T{sequence_number}"``.
42
+
43
+ Returns:
44
+ The created Terminal (already added to the graph).
45
+ """
46
+ cim_ = network.cim
47
+ term_name = name or f"{equipment.name}_T{sequence_number}"
48
+
49
+ terminal = cim_.Terminal(name=term_name)
50
+ terminal.sequenceNumber = sequence_number
51
+ terminal.ConductingEquipment = equipment
52
+ if terminal not in equipment.Terminals:
53
+ equipment.Terminals.append(terminal)
54
+
55
+ if phases is not None:
56
+ terminal.phases = phases
57
+
58
+ if connectivity_node is not None:
59
+ attach_terminal_to_node(terminal, connectivity_node)
60
+
61
+ network.add_to_graph(terminal)
62
+ return terminal
63
+
64
+
65
+ def attach_terminal_to_node(
66
+ terminal: cim.Terminal,
67
+ connectivity_node: cim.ConnectivityNode,
68
+ ) -> None:
69
+ """Wire an existing Terminal to a ConnectivityNode in both directions.
70
+
71
+ Idempotent: re-attaching the same terminal to the same node is a no-op, and
72
+ re-pointing a terminal to a different node removes it from the old node's
73
+ back-reference list first.
74
+ """
75
+ old_node = terminal.ConnectivityNode
76
+ if old_node is connectivity_node:
77
+ return
78
+ if old_node is not None and terminal in old_node.Terminals:
79
+ old_node.Terminals.remove(terminal)
80
+
81
+ terminal.ConnectivityNode = connectivity_node
82
+ if terminal not in connectivity_node.Terminals:
83
+ connectivity_node.Terminals.append(terminal)