In this section
- Fleet Store storage · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/fleet_store.py lines 701–876
- Formulas transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/formulas.py lines 1–175
- Geometry Receipts transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/geometry_receipts.py lines 1–163
- Identifiers ingest · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/identifiers.py lines 1–105
Fleet Store
A Python module in Solar Electrical Topology Analysis Engine Text Based that reads strings, mppts, inverters and site summary, using SHA-256. It builds store (`build_store`) and builds deterministic store (`build_deterministic_store`).
storagesolar-electrical-topology-analysis-engine-text-based / src/solar_topology/fleet_store.py · lines 701–876 of 876 (continued from section 226) · Not reached from any entry point (candidate for review)
- What it does
- It loads strings, mppts, inverters and site summary. Defines 19 functions or classes, including _duckdb_module, _sql_path, _csv_record, _write_segment_csv, _scalar. Uses libraries __future__, csv, dataclasses, hashlib, json. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: Parquet file strings.parquet; Parquet file mppts.parquet; Parquet file inverters.parquet; Parquet file site.parquet; Parquet file comparison.parquet; CSV file segments.csv; DuckDB queries. Out: JSON file site-summary.json; JSON file selected-string.json; JSON file build-summary.json.
- Downstream impact
- Used directly by 1 file: Solar Electrical Topology Analysis Engine Text Based — Solar Topology (solar-electrical-topology-analysis-engine-text-based).
- What it achieves
- Authoritative deterministic DuckDB and Parquet topology fleet store.
- Why it matters
- Imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology.
- Application
- solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
- Uses
- Cartridges (relative import), Segments (relative import), __future__, csv, dataclasses, hashlib, json, pathlib, shutil, tempfile
- Used by
- imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import)
- Produces
- build_store, build_deterministic_store
- Defines here
- _load_segments, build_store, _determinism_error, build_deterministic_store
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 src/solar_topology/fleet_store.py:701-876 · blob df257c0ecd3f7acaeee7df35ce0859a59f36c187 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
parquet_digest = hashlib.sha256(
json.dumps(
topology_files,
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
).hexdigest()
manifest = {
"schema_version": "topology_segments_v1",
"cartridge_name": cartridge.name,
"cartridge_version": cartridge.version,
"method_version": "duckdb_parquet_store_v2",
"source_commit": source_commit,
"input_hash": input_hash,
"segment_row_count": statistics[0],
"distinct_string_count": statistics[1],
"first_segment_key": statistics[2],
"last_segment_key": statistics[3],
"parquet_files": topology_files,
"parquet_sha256": parquet_digest,
"feasibility_status": statistics[4],
"warning_count": statistics[5],
"data_law_result": "PASS",
"data_law_checks": data_law,
}
target = (
root
/ "manifests"
/ f"topology={cartridge.name}"
/ "manifest.json"
)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(
json.dumps(manifest, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
def _load_segments(connection, csv_path: Path) -> None:
connection.execute(SEGMENT_SCHEMA_SQL)
connection.execute(
f"""
COPY segments
FROM '{_sql_path(csv_path)}' (
FORMAT csv,
HEADER true,
DELIMITER ',',
NULLSTR '{NULL_TOKEN}'
)
"""
)
def build_store(
inputs: TopologyInputs,
output_root: Path,
source_commit: str = "unknown",
) -> dict:
"""Build one candidate segment, result, aggregate and browser store."""
inputs.validate()
output_root = Path(output_root)
if output_root.exists():
shutil.rmtree(output_root)
output_root.mkdir(parents=True, exist_ok=True)
duckdb = _duckdb_module()
with tempfile.TemporaryDirectory(
prefix="topology-segments-csv-"
) as temporary:
csv_path = Path(temporary) / "segments.csv"
generated_rows = _write_segment_csv(inputs, csv_path)
connection = duckdb.connect()
try:
connection.execute("SET threads = 1")
connection.execute("SET preserve_insertion_order = true")
_load_segments(connection, csv_path)
loaded_rows = int(
_scalar(connection, "SELECT count(*) FROM segments")
)
if generated_rows != loaded_rows:
raise ValueError(
"Generated and loaded segment row counts differ"
)
data_law = _run_data_law(connection)
_create_segment_results(connection)
_copy_query(
connection,
"""
SELECT *
FROM segments
ORDER BY
topology,
band,
inverter_id,
string_id,
segment_index
""",
output_root / "segments",
partitioned=True,
)
_write_aggregates(connection, output_root)
_write_browser_slices(connection, output_root)
_write_manifests(
connection,
output_root,
inputs,
source_commit,
data_law,
)
finally:
connection.close()
summary = {
"input_hash": canonical_input_hash(inputs),
"generated_segment_rows": generated_rows,
"string_count": inputs.total_site_string_count,
"inverter_count": inputs.inverter_count,
"file_hashes": _file_hashes(output_root),
}
(output_root / "build-summary.json").write_text(
json.dumps(summary, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
return summary
def _determinism_error(
first_hashes: dict[str, str],
second_hashes: dict[str, str],
) -> str:
missing_first = sorted(set(second_hashes) - set(first_hashes))
missing_second = sorted(set(first_hashes) - set(second_hashes))
changed = sorted(
path
for path in set(first_hashes) & set(second_hashes)
if first_hashes[path] != second_hashes[path]
)
return (
"Nondeterministic topology build: "
f"missing_first={missing_first}, "
f"missing_second={missing_second}, "
f"changed={changed}"
)
def build_deterministic_store(
inputs: TopologyInputs,
output_root: Path,
source_commit: str = "unknown",
) -> dict:
"""Build twice and publish only byte-identical relative outputs."""
output_root = Path(output_root)
with tempfile.TemporaryDirectory(
prefix="topology-determinism-"
) as temporary:
temporary_root = Path(temporary)
first = temporary_root / "first"
second = temporary_root / "second"
first_summary = build_store(inputs, first, source_commit)
build_store(inputs, second, source_commit)
first_hashes = _file_hashes(first)
second_hashes = _file_hashes(second)
if first_hashes != second_hashes:
raise ValueError(
_determinism_error(first_hashes, second_hashes)
)
if output_root.exists():
shutil.rmtree(output_root)
shutil.copytree(first, output_root)
result = dict(first_summary)
result["deterministic"] = True
result["file_hashes"] = _file_hashes(output_root)
return resultFormulas
A Python module in Solar Electrical Topology Analysis Engine Text Based that works with cables.
transformsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/formulas.py · lines 1–175 of 175 · Not reached from any entry point (candidate for review)
- What it does
- It calculates cables. Defines 8 functions or classes, including TwoWireParameters, dc_resistance, two_wire_parameters, module_frame_capacitance, cold_string_voc. Uses libraries __future__, dataclasses, math, pint.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables.
- Downstream impact
- Used directly by 3 files: Solar Electrical Topology Analysis Engine Text Based — Solar Topology (solar-electrical-topology-analysis-engine-text-based); Electrical Studies (solar-electrical-topology-analysis-engine-text-based); Topology (solar-electrical-topology-analysis-engine-text-based).
- What it achieves
- It is built from the two wire parameters class (`TwoWireParameters`), the dc resistance helper (`dc_resistance`) and the two wire parameters helper (`two_wire_parameters`). Authoritative closed-form Tier 1 formulae with explicit units and guards.
- Why it matters
- Imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology, Electrical Studies and Topology.
- Application
- solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
- Uses
- __future__, dataclasses, math, pint
- Used by
- imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import), imported by Electrical Studies (relative import), imported by Topology (relative import)
- Produces
- TwoWireParameters, dc_resistance, two_wire_parameters, module_frame_capacitance, cold_string_voc, derived_route_length, stored_magnetic_energy, stored_electric_energy
- Defines here
- TwoWireParameters, dc_resistance, two_wire_parameters, module_frame_capacitance, cold_string_voc, derived_route_length, stored_magnetic_energy, stored_electric_energy
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 src/solar_topology/formulas.py:1-175 · blob 26eaac1d7fc24bc19e99dfea3192de9b8a2011af · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Authoritative closed-form Tier 1 formulae with explicit units and guards."""
from __future__ import annotations
from dataclasses import dataclass
import math
from pint import UnitRegistry
ureg = UnitRegistry()
Q_ = ureg.Quantity
MU0 = 4 * math.pi * 1e-7 * ureg.henry / ureg.metre
EPS0 = 8.8541878128e-12 * ureg.farad / ureg.metre
ALPHA_CU_20 = 0.00393 / ureg.kelvin
@dataclass(frozen=True)
class TwoWireParameters:
"""Two-wire parameters with external and internal inductance separated."""
external_inductance_per_length: object
internal_inductance_per_length: object
inductance_per_length: object
capacitance_per_length: object
characteristic_impedance: object
propagation_velocity: object
def dc_resistance(
length,
r20_per_length,
temperature=Q_(20, ureg.degC),
):
"""Resistance from declared finished-cable R20 and conductor temperature.
Nominal cross-sectional area is an identifying size. It is not used here to
recreate a resistance from bulk material resistivity. The caller supplies the
declared or measured finished-cable resistance per unit length.
"""
length = length.to(ureg.metre)
r20_per_length = r20_per_length.to(ureg.ohm / ureg.metre)
delta_t = temperature.to(ureg.degC).magnitude - 20.0
factor = 1 + ALPHA_CU_20.magnitude * delta_t
return (length * r20_per_length * factor).to(ureg.ohm)
def two_wire_parameters(
centre_spacing,
conductor_diameter,
epsilon_r: float = 1.0,
) -> TwoWireParameters:
"""Return round two-wire transmission and low-frequency parameters.
The geometry term is ``acosh(D / d_conductor)``. The cable outside diameter
must not be substituted for the declared stranded-conductor diameter.
Characteristic impedance and propagation velocity use external inductance
only. This preserves the TEM identity ``v = c / sqrt(epsilon_r)`` because the
geometry term cancels between external inductance and capacitance.
Low-frequency internal loop inductance is retained separately as
``mu0 / (4*pi)`` H/m, representing ``mu0 / (8*pi)`` for each conductor. It is
included in the total low-frequency inductance for stored energy and lumped
``L di/dt`` studies, but not in propagation velocity or surge impedance.
"""
spacing = centre_spacing.to(ureg.metre)
diameter = conductor_diameter.to(ureg.metre)
ratio = (spacing / diameter).to_base_units().magnitude
if ratio <= 1:
raise ValueError(
"Conductor centre spacing must exceed conductor diameter"
)
if epsilon_r <= 0:
raise ValueError("Relative permittivity must be positive")
geometry = math.acosh(ratio)
external_inductance = (
MU0 / math.pi * geometry
).to(ureg.henry / ureg.metre)
internal_inductance = (
MU0 / (4 * math.pi)
).to(ureg.henry / ureg.metre)
low_frequency_inductance = external_inductance + internal_inductance
capacitance = (
math.pi * EPS0 * epsilon_r / geometry
).to(ureg.farad / ureg.metre)
characteristic_impedance = (
external_inductance / capacitance
) ** 0.5
propagation_velocity = (
1 / (external_inductance * capacitance) ** 0.5
).to(ureg.metre / ureg.second)
return TwoWireParameters(
external_inductance,
internal_inductance,
low_frequency_inductance,
capacitance,
characteristic_impedance.to(ureg.ohm),
propagation_velocity,
)
def module_frame_capacitance(
effective_area,
dielectric_thickness,
epsilon_r: float,
):
"""Parallel-plate indicative module-to-frame capacitance."""
if epsilon_r <= 0:
raise ValueError("Relative permittivity must be positive")
return (
EPS0
* epsilon_r
* effective_area.to(ureg.metre**2)
/ dielectric_thickness.to(ureg.metre)
).to(ureg.farad)
def cold_string_voc(
module_voc,
module_count: int,
beta_voc_percent_per_c: float,
cell_temperature,
):
"""Linear temperature-coefficient screen for cold string open circuit voltage."""
if module_count < 1:
raise ValueError("module_count must be at least one")
temperature_delta = (
cell_temperature.to(ureg.degC).magnitude - 25.0
)
factor = 1 + (
beta_voc_percent_per_c / 100.0
) * temperature_delta
return (module_count * module_voc * factor).to(ureg.volt)
def derived_route_length(
near_end_distance,
rank_index: int,
rank_pitch,
inverter_drop,
):
"""Geometry-only route rule with no user-supplied final length argument."""
if rank_index < 0:
raise ValueError("rank_index cannot be negative")
return (
near_end_distance
+ rank_index * rank_pitch
+ inverter_drop
).to(ureg.metre)
def stored_magnetic_energy(inductance, current):
"""Stored magnetic energy for a consistent total inductance."""
return (0.5 * inductance * current**2).to(ureg.joule)
def stored_electric_energy(capacitance, voltage):
"""Stored electric energy for a consistent total capacitance."""
return (0.5 * capacitance * voltage**2).to(ureg.joule)Geometry Receipts
A Python module in Solar Electrical Topology Analysis Engine Text Based that works with solar, using SHA-256.
transformsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/geometry_receipts.py · lines 1–163 of 163 · Not reached from any entry point (candidate for review)
- What it does
- It calculates solar. Defines 6 functions or classes, including SegmentGeometryResult, GeometryReceipt, calculate_geometry_receipt, geometry_receipt_payload, geometry_receipt_json. Uses libraries __future__, dataclasses, hashlib, json, math.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
- Downstream impact
- Used directly by 1 file: Solar Electrical Topology Analysis Engine Text Based — Solar Topology (solar-electrical-topology-analysis-engine-text-based).
- What it achieves
- It calculates geometry receipt (`calculate_geometry_receipt`) and is built from the segment geometry result class (`SegmentGeometryResult`) and the geometry receipt class (`GeometryReceipt`). Deterministic geometry screening receipts from ordered segment rows.
- Why it matters
- Imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology.
- Application
- solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
- Uses
- Segments (relative import), __future__, dataclasses, hashlib, json, math, typing
- Used by
- imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import)
- Produces
- SegmentGeometryResult, GeometryReceipt, calculate_geometry_receipt, geometry_receipt_payload, geometry_receipt_json, geometry_receipt_hash
- Defines here
- SegmentGeometryResult, GeometryReceipt, calculate_geometry_receipt, geometry_receipt_payload, geometry_receipt_json, geometry_receipt_hash
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 src/solar_topology/geometry_receipts.py:1-163 · blob e3014bc950722a78e91810e97610b05326e94531 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Deterministic geometry screening receipts from ordered segment rows.
The method is an explicit engineering approximation. It integrates local
conductor length multiplied by declared pole separation and the segment's
loop-parameter participation weight. It is not a field solution and does not
invent missing return-path geometry.
"""
from __future__ import annotations
from dataclasses import dataclass
import hashlib
import json
import math
from typing import Iterable
from .segments import SegmentRow
GEOMETRY_RECEIPT_SCHEMA_VERSION = "globalgrid2050.solar-dc.geometry-receipt.v10.1"
GEOMETRY_METHOD_VERSION = "weighted-length-times-separation.v10.1"
@dataclass(frozen=True)
class SegmentGeometryResult:
segment_id: str
conductor_length_m: float
separation_m: float
participation_weight: float
loop_area_contribution_m2: float
@dataclass(frozen=True)
class GeometryReceipt:
receipt_id: str
run_id: str
topology: str
string_id: str
segment_results: tuple[SegmentGeometryResult, ...]
loop_area_m2: float
maximum_local_separation_m: float
paired_route_length_m: float
total_route_length_m: float
paired_route_fraction: float
warnings: tuple[str, ...]
schema_version: str = GEOMETRY_RECEIPT_SCHEMA_VERSION
method_version: str = GEOMETRY_METHOD_VERSION
def calculate_geometry_receipt(rows: Iterable[SegmentRow]) -> GeometryReceipt:
ordered = tuple(sorted(rows, key=lambda row: row.segment_index))
if not ordered:
raise ValueError("at least one segment row is required")
for row in ordered:
row.validate()
identities = {(row.run_id, row.topology, row.string_id) for row in ordered}
if len(identities) != 1:
raise ValueError("geometry receipt requires one run, topology and string")
indexes = [row.segment_index for row in ordered]
if indexes != list(range(1, len(ordered) + 1)):
raise ValueError("segment indexes must be contiguous from one")
results: list[SegmentGeometryResult] = []
warnings: list[str] = []
paired_length = 0.0
total_length = math.fsum(row.conductor_length_m for row in ordered)
for row in ordered:
separation_m = row.separation_mm / 1000.0
contribution = (
row.conductor_length_m * separation_m * row.loop_parameter_weight
)
results.append(
SegmentGeometryResult(
segment_id=row.segment_id,
conductor_length_m=row.conductor_length_m,
separation_m=separation_m,
participation_weight=row.loop_parameter_weight,
loop_area_contribution_m2=contribution,
)
)
if row.loop_parameter_weight > 0:
paired_length += row.conductor_length_m
if row.separation_mm <= 0 and row.loop_parameter_weight > 0:
warnings.append(
f"segment {row.segment_id!r} participates in loop geometry but has no separation"
)
if row.provenance in {"assumed", "defaulted"}:
warnings.append(
f"segment {row.segment_id!r} geometry uses {row.provenance} evidence"
)
loop_area = math.fsum(result.loop_area_contribution_m2 for result in results)
maximum = max(result.separation_m for result in results)
fraction = paired_length / total_length if total_length else 0.0
run_id, topology, string_id = next(iter(identities))
basis = {
"method_version": GEOMETRY_METHOD_VERSION,
"run_id": run_id,
"topology": topology,
"string_id": string_id,
"segments": [
[result.segment_id, result.conductor_length_m, result.separation_m,
result.participation_weight]
for result in results
],
}
digest = hashlib.sha256(
json.dumps(basis, sort_keys=True, separators=(",", ":")).encode("utf-8")
).hexdigest()
return GeometryReceipt(
receipt_id=f"GEO:{digest}",
run_id=run_id,
topology=topology,
string_id=string_id,
segment_results=tuple(results),
loop_area_m2=loop_area,
maximum_local_separation_m=maximum,
paired_route_length_m=paired_length,
total_route_length_m=total_length,
paired_route_fraction=fraction,
warnings=tuple(sorted(set(warnings))),
)
def geometry_receipt_payload(receipt: GeometryReceipt) -> dict[str, object]:
return {
"schema_version": receipt.schema_version,
"method_version": receipt.method_version,
"receipt_id": receipt.receipt_id,
"run_id": receipt.run_id,
"topology": receipt.topology,
"string_id": receipt.string_id,
"loop_area_m2": receipt.loop_area_m2,
"maximum_local_separation_m": receipt.maximum_local_separation_m,
"paired_route_length_m": receipt.paired_route_length_m,
"total_route_length_m": receipt.total_route_length_m,
"paired_route_fraction": receipt.paired_route_fraction,
"warnings": list(receipt.warnings),
"segments": [
{
"segment_id": result.segment_id,
"conductor_length_m": result.conductor_length_m,
"separation_m": result.separation_m,
"participation_weight": result.participation_weight,
"loop_area_contribution_m2": result.loop_area_contribution_m2,
}
for result in receipt.segment_results
],
}
def geometry_receipt_json(receipt: GeometryReceipt) -> str:
return json.dumps(
geometry_receipt_payload(receipt),
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
)
def geometry_receipt_hash(receipt: GeometryReceipt) -> str:
digest = hashlib.sha256(geometry_receipt_json(receipt).encode("utf-8")).hexdigest()
return f"sha256:{digest}"Identifiers
A Python module in Solar Electrical Topology Analysis Engine Text Based that works with entity level (`EntityLevel`) and canonical identifier (`CanonicalIdentifier`), covering solar.
ingestsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/identifiers.py · lines 1–105 of 105 · Not reached from any entry point (candidate for review) · pattern __post_init__ (shared by 16 files)
- What it does
- Defines 8 functions or classes, including EntityLevel, CanonicalIdentifier, __post_init__, value, child. Uses libraries __future__, dataclasses, enum, re.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
- Downstream impact
- Used directly by 4 files: Solar Electrical Topology Analysis Engine Text Based — Solar Topology (solar-electrical-topology-analysis-engine-text-based); Contradictions (solar-electrical-topology-analysis-engine-text-based); Evidence Register (solar-electrical-topology-analysis-engine-text-based); Public Topology (solar-electrical-topology-analysis-engine-text-based).
- What it achieves
- It parses identifier (`parse_identifier`) and is built from the entity level class (`EntityLevel`) and the canonical identifier class (`CanonicalIdentifier`). Canonical hierarchical identifiers for V10 engineering records.
- Why it matters
- Imported by 4 files, including Solar Electrical Topology Analysis Engine Text Based — Solar Topology, Contradictions and Evidence Register.
- Application
- solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
- Uses
- __future__, dataclasses, enum, re
- Used by
- imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import), imported by Contradictions (relative import), imported by Evidence Register (relative import), imported by Public Topology (relative import)
- Produces
- EntityLevel, CanonicalIdentifier, project_id, parse_identifier, require_unique_identifiers
- Defines here
- EntityLevel, CanonicalIdentifier, __post_init__, value, child, project_id, parse_identifier, require_unique_identifiers
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 src/solar_topology/identifiers.py:1-105 · blob 541d4aca769d8243394f334a3e90a9cb69994155 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Canonical hierarchical identifiers for V10 engineering records.
Identifiers are deterministic, human-readable and independent of confidential
project naming. Public exports may use public aliases while restricted source
names remain outside the identifier itself.
"""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
import re
IDENTIFIER_SCHEMA_VERSION = "globalgrid2050.solar-dc.identifiers.v10.1"
_TOKEN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
class EntityLevel(StrEnum):
PROJECT = "project"
SITE = "site"
SYSTEM = "system"
EQUIPMENT = "equipment"
CIRCUIT = "circuit"
OBJECT = "object"
_LEVEL_ORDER = {
EntityLevel.PROJECT: 0,
EntityLevel.SITE: 1,
EntityLevel.SYSTEM: 2,
EntityLevel.EQUIPMENT: 3,
EntityLevel.CIRCUIT: 4,
EntityLevel.OBJECT: 5,
}
@dataclass(frozen=True)
class CanonicalIdentifier:
level: EntityLevel
local_id: str
parent: "CanonicalIdentifier | None" = None
schema_version: str = IDENTIFIER_SCHEMA_VERSION
def __post_init__(self) -> None:
if not isinstance(self.level, EntityLevel):
raise TypeError("level must be an EntityLevel")
if not isinstance(self.local_id, str) or not _TOKEN.fullmatch(self.local_id):
raise ValueError(
"local_id must be lowercase kebab-case using letters and digits"
)
if self.level is EntityLevel.PROJECT:
if self.parent is not None:
raise ValueError("project identifiers cannot have a parent")
else:
if not isinstance(self.parent, CanonicalIdentifier):
raise ValueError(f"{self.level} identifiers require a parent")
expected = _LEVEL_ORDER[self.level] - 1
actual = _LEVEL_ORDER[self.parent.level]
if actual != expected:
raise ValueError(
f"{self.level} parent must be the immediately preceding level"
)
@property
def value(self) -> str:
current: CanonicalIdentifier | None = self
parts: list[str] = []
while current is not None:
parts.append(f"{current.level.value}:{current.local_id}")
current = current.parent
return "/".join(reversed(parts))
def child(self, level: EntityLevel, local_id: str) -> "CanonicalIdentifier":
return CanonicalIdentifier(level=level, local_id=local_id, parent=self)
def project_id(local_id: str) -> CanonicalIdentifier:
return CanonicalIdentifier(EntityLevel.PROJECT, local_id)
def parse_identifier(value: str) -> CanonicalIdentifier:
if not isinstance(value, str) or not value:
raise ValueError("identifier must be non-empty text")
parent: CanonicalIdentifier | None = None
for index, component in enumerate(value.split("/")):
try:
level_text, local_id = component.split(":", 1)
level = EntityLevel(level_text)
except (ValueError, TypeError) as exc:
raise ValueError(f"invalid identifier component {component!r}") from exc
expected_level = list(EntityLevel)[index] if index < len(EntityLevel) else None
if level is not expected_level:
raise ValueError("identifier hierarchy must start at project and be contiguous")
parent = CanonicalIdentifier(level, local_id, parent)
assert parent is not None
return parent
def require_unique_identifiers(
identifiers: tuple[CanonicalIdentifier, ...] | list[CanonicalIdentifier],
) -> None:
values = [identifier.value for identifier in identifiers]
if len(values) != len(set(values)):
raise ValueError("canonical identifiers must be unique")