In this section
- Study Registry transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/study_registry.py lines 1–253
- Topology transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/topology.py lines 1–295
- Topology Authority transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/topology_authority.py lines 1–88
Study Registry
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/study_registry.py · lines 1–253 of 253 · Not reached from any entry point (candidate for review) · pattern __post_init__ (shared by 16 files)
- What it does
- It calculates solar. Defines 11 functions or classes, including StudyCategory, _validate_sorted_unique, StudyDefinition, __post_init__, StudyAssessment. Uses libraries __future__, dataclasses, enum, hashlib, json.
- 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 is built from the study category class (`StudyCategory`), the study definition class (`StudyDefinition`) and the study assessment class (`StudyAssessment`). Applicability and coverage registry for V10 engineering studies.
- 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
- Diagnostics (relative import), __future__, dataclasses, enum, hashlib, json, typing
- Used by
- imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import)
- Produces
- StudyCategory, StudyDefinition, StudyAssessment, StudyRegistry, assess_study, build_study_registry, study_registry_payload, study_registry_json, study_registry_hash
- Defines here
- StudyCategory, _validate_sorted_unique, StudyDefinition, __post_init__, StudyAssessment, StudyRegistry, assess_study, build_study_registry, study_registry_payload, study_registry_json, study_registry_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/study_registry.py:1-253 · blob 025eaee058e03235a03ae040ead5a8e070adf0b9 · 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
"""Applicability and coverage registry for V10 engineering studies.
The registry prevents absence of a diagnostic from being misread as a passed study.
Acceptance criteria remain evidence-bearing inputs rather than invented constants.
"""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
import hashlib
import json
from typing import Iterable
from .diagnostics import StudyCoverage, StudyState
STUDY_REGISTRY_SCHEMA_VERSION = "globalgrid2050.solar-dc.study-registry.v10.1"
class StudyCategory(StrEnum):
TOPOLOGY = "topology"
STEADY_STATE = "steady_state"
THERMAL = "thermal"
INSULATION = "insulation"
TRANSIENT = "transient"
LIGHTNING = "lightning"
EVIDENCE = "evidence"
PUBLICATION = "publication"
def _validate_sorted_unique(
values: tuple[str, ...], *, study_id: str, field_name: str
) -> None:
"""Fail fast with the exact registry declaration that is malformed."""
expected = tuple(sorted(set(values)))
if values != expected:
raise ValueError(
f"study_id={study_id!r} field={field_name!r} must be unique and sorted; "
f"received={values!r}; expected={expected!r}"
)
@dataclass(frozen=True)
class StudyDefinition:
study_id: str
category: StudyCategory
title: str
method_reference: str
required_input_ids: tuple[str, ...] = ()
required_evidence_roles: tuple[str, ...] = ()
acceptance_criterion_required: bool = False
public_description: str | None = None
def __post_init__(self) -> None:
if not self.study_id or not self.title or not self.method_reference:
raise ValueError("study_id, title and method_reference are required")
if not isinstance(self.category, StudyCategory):
raise TypeError("category must be StudyCategory")
_validate_sorted_unique(
self.required_input_ids,
study_id=self.study_id,
field_name="required_input_ids",
)
_validate_sorted_unique(
self.required_evidence_roles,
study_id=self.study_id,
field_name="required_evidence_roles",
)
@dataclass(frozen=True)
class StudyAssessment:
definition: StudyDefinition
coverage: StudyCoverage
missing_input_ids: tuple[str, ...] = ()
missing_evidence_roles: tuple[str, ...] = ()
acceptance_criterion_source: str | None = None
@dataclass(frozen=True)
class StudyRegistry:
definitions: tuple[StudyDefinition, ...]
assessments: tuple[StudyAssessment, ...]
schema_version: str = STUDY_REGISTRY_SCHEMA_VERSION
def assess_study(
definition: StudyDefinition,
*,
subject_id: str | None,
available_input_ids: Iterable[str],
available_evidence_roles: Iterable[str],
applicable: bool = True,
performed: bool = False,
passed: bool | None = None,
warning: bool = False,
acceptance_criterion_source: str | None = None,
) -> StudyAssessment:
inputs = set(available_input_ids)
evidence = set(available_evidence_roles)
missing_inputs = tuple(sorted(set(definition.required_input_ids) - inputs))
missing_evidence = tuple(
sorted(set(definition.required_evidence_roles) - evidence)
)
if not applicable:
state = StudyState.NOT_APPLICABLE
reason = "study is not applicable to the declared system boundary"
elif missing_inputs or missing_evidence:
state = StudyState.BLOCKED
reason = "missing required inputs or evidence"
elif definition.acceptance_criterion_required and not acceptance_criterion_source:
state = StudyState.BLOCKED
reason = "acceptance criterion source is not declared"
elif not performed:
state = StudyState.NOT_CHECKED
reason = "study inputs are available but the study was not performed"
elif passed is False:
state = StudyState.CHECKED_FAIL
reason = None
elif warning:
state = StudyState.CHECKED_WARNING
reason = None
else:
state = StudyState.CHECKED_PASS
reason = None
coverage = StudyCoverage(
study_id=definition.study_id,
state=state,
subject_id=subject_id,
method_reference=definition.method_reference,
reason=reason,
)
return StudyAssessment(
definition=definition,
coverage=coverage,
missing_input_ids=missing_inputs,
missing_evidence_roles=missing_evidence,
acceptance_criterion_source=acceptance_criterion_source,
)
def build_study_registry(
assessments: Iterable[StudyAssessment],
) -> StudyRegistry:
ordered = tuple(
sorted(assessments, key=lambda item: item.definition.study_id)
)
ids = [item.definition.study_id for item in ordered]
if len(ids) != len(set(ids)):
raise ValueError("study definitions must be unique")
return StudyRegistry(
definitions=tuple(item.definition for item in ordered),
assessments=ordered,
)
def study_registry_payload(registry: StudyRegistry) -> dict[str, object]:
return {
"schema_version": registry.schema_version,
"studies": [
{
"study_id": item.definition.study_id,
"category": item.definition.category.value,
"title": item.definition.title,
"method_reference": item.definition.method_reference,
"required_input_ids": list(item.definition.required_input_ids),
"required_evidence_roles": list(
item.definition.required_evidence_roles
),
"acceptance_criterion_required": (
item.definition.acceptance_criterion_required
),
"public_description": item.definition.public_description,
"state": item.coverage.state.value,
"subject_id": item.coverage.subject_id,
"reason": item.coverage.reason,
"missing_input_ids": list(item.missing_input_ids),
"missing_evidence_roles": list(item.missing_evidence_roles),
"acceptance_criterion_source": (
item.acceptance_criterion_source
),
}
for item in registry.assessments
],
}
def study_registry_json(registry: StudyRegistry) -> str:
return json.dumps(
study_registry_payload(registry),
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
)
def study_registry_hash(registry: StudyRegistry) -> str:
digest = hashlib.sha256(
study_registry_json(registry).encode("utf-8")
).hexdigest()
return f"sha256:{digest}"
INITIAL_STUDIES = (
StudyDefinition(
study_id="complete-circuit-resistance",
category=StudyCategory.STEADY_STATE,
title="Complete series-circuit resistance",
method_reference="globalgrid2050.solar-dc.complete-circuit.v10.1",
required_input_ids=("current-a", "ordered-segments"),
required_evidence_roles=("conductor-data", "route-geometry"),
),
StudyDefinition(
study_id="voltage-drop-acceptance",
category=StudyCategory.STEADY_STATE,
title="Voltage-drop acceptance",
method_reference="globalgrid2050.solar-dc.voltage-drop.v10.1",
required_input_ids=("current-a", "string-vmp-v"),
required_evidence_roles=("complete-circuit-resistance",),
acceptance_criterion_required=True,
),
StudyDefinition(
study_id="cold-voc-limit",
category=StudyCategory.STEADY_STATE,
title="Cold string open-circuit voltage limit",
method_reference="globalgrid2050.solar-dc.cold-voc.v10.1",
required_input_ids=(
"beta-voc-percent-per-k",
"cold-cell-temperature-c",
"module-voc-v",
"modules-per-string",
"system-maximum-voltage-v",
),
required_evidence_roles=("module-datasheet", "system-voltage-basis"),
),
StudyDefinition(
study_id="loop-geometry",
category=StudyCategory.TRANSIENT,
title="Differential loop geometry",
method_reference="globalgrid2050.solar-dc.geometry-receipt.v10.1",
required_input_ids=("ordered-segments",),
required_evidence_roles=("pole-separation", "route-geometry"),
),
StudyDefinition(
study_id="ampacity-acceptance",
category=StudyCategory.THERMAL,
title="Conductor ampacity acceptance",
method_reference="globalgrid2050.solar-dc.ampacity.v10.1",
required_input_ids=("design-current-a", "installation-class"),
required_evidence_roles=("cable-rating-basis",),
acceptance_criterion_required=True,
),
)Topology
A Python module in Solar Electrical Topology Analysis Engine Text Based that builds segments (`build_string_segments`) and site model (`build_site_model`) and builds export (`build_export`).
transformsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/topology.py · lines 1–295 of 295 · Not reached from any entry point (candidate for review) · pattern StringTopology (shared by 2 files)
- What it does
- It calculates its inputs. Defines 12 functions or classes, including Point3D, Segment, StringTopology, installed_conductor_length_m, GeometryConfig. Uses libraries __future__, dataclasses, math, typing.
- 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.
- 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 is built from the point3 d class (`Point3D`), the segment class (`Segment`) and the string topology class (`StringTopology`). Headless geometry-to-segment topology generation.
- 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
- Formulas (relative import), __future__, dataclasses, math, typing
- Used by
- imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import)
- Produces
- Point3D, Segment, StringTopology, GeometryConfig, FormationConfig, build_string_segments, build_site_model, build_export, validate_no_user_route_lengths
- Defines here
- Point3D, Segment, StringTopology, installed_conductor_length_m, GeometryConfig, FormationConfig, _polyline_length, _segment, build_string_segments, build_site_model, build_export, validate_no_user_route_lengths
- 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/topology.py:1-295 · blob 0c76e2bc7240c359fc33b2c2a5a31acc987c6351 · 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
"""Headless geometry-to-segment topology generation.
The renderer is deliberately absent. Geometry produces strings and typed conductor
segments; studies and exports can therefore run without any browser dependency.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass
import math
from typing import Iterable, Sequence
from .formulas import Q_, ureg
@dataclass(frozen=True)
class Point3D:
x_m: float
y_m: float
z_m: float
@dataclass(frozen=True)
class Segment:
segment_id: str
string_id: str
sequence_index: int
segment_type: str
points_3d: tuple[Point3D, ...]
geometric_displacement_m: float
installed_conductor_length_m: float
formation_type: str
conductor_separation_mm: float
provenance: str
route_length_source: str = "derived_from_segment_geometry"
@dataclass(frozen=True)
class StringTopology:
string_id: str
face: str
band_index: int
rank_index: int
module_count: int
segments: tuple[Segment, ...]
@property
def installed_conductor_length_m(self) -> float:
return sum(segment.installed_conductor_length_m for segment in self.segments)
@dataclass(frozen=True)
class GeometryConfig:
modules_along_row: int = 30
modules_per_string: int = 30
ranks_per_face: int = 5
faces_per_table: int = 2
module_width_m: float = 1.303
module_length_m: float = 2.384
clamp_gap_m: float = 0.020
along_gap_m: float = 0.020
tilt_deg: float = 10.0
structure_drop_m: float = 2.0
east_bands: tuple[int, ...] = (5, 5, 2)
west_bands: tuple[int, ...] = (5, 5, 2)
inverter_x_m: float = -4.0
inverter_y_m: float = 0.0
@dataclass(frozen=True)
class FormationConfig:
module_interconnect_spacing_mm: float = 8.0
return_spacing_mm: float = 20.0
coil_surplus_length_m: float = 0.20
coil_diameter_mm: float = 80.0
trench_spacing_mm: float = 40.0
def _polyline_length(points: Sequence[Point3D]) -> float:
return sum(
math.dist((a.x_m, a.y_m, a.z_m), (b.x_m, b.y_m, b.z_m))
for a, b in zip(points, points[1:])
)
def _segment(
*, string_id: str, sequence_index: int, segment_type: str,
points: Sequence[Point3D], installed_length_m: float | None,
formation_type: str, separation_mm: float, provenance: str,
) -> Segment:
displacement = _polyline_length(points)
length = displacement if installed_length_m is None else installed_length_m
if length < 0:
raise ValueError("Segment installed length cannot be negative")
return Segment(
segment_id=f"{string_id}-S{sequence_index:03d}",
string_id=string_id,
sequence_index=sequence_index,
segment_type=segment_type,
points_3d=tuple(points),
geometric_displacement_m=displacement,
installed_conductor_length_m=length,
formation_type=formation_type,
conductor_separation_mm=separation_mm,
provenance=provenance,
)
def build_string_segments(
string_id: str,
face: str,
band_index: int,
rank_index: int,
band_x0_m: float,
geometry: GeometryConfig,
formations: FormationConfig,
) -> StringTopology:
"""Build one complete segment chain from physical geometry only."""
if face not in {"E", "W"}:
raise ValueError("face must be E or W")
if geometry.modules_along_row < 1 or geometry.modules_per_string < 1:
raise ValueError("module counts must be positive")
if rank_index < 0:
raise ValueError("rank_index cannot be negative")
sign = -1 if face == "E" else 1
theta = math.radians(geometry.tilt_deg)
rank_pitch_slope = geometry.module_length_m + geometry.clamp_gap_m
rank_pitch_plan = rank_pitch_slope * math.cos(theta)
rank_rise = rank_pitch_slope * math.sin(theta)
module_pitch = geometry.module_width_m + geometry.along_gap_m
band_length = geometry.modules_along_row * module_pitch - geometry.along_gap_m
x1 = band_x0_m + band_length
y = sign * (rank_index + 0.5) * rank_pitch_plan
z = (rank_index + 0.5) * rank_rise
sequence = 1
segments: list[Segment] = []
for module_index in range(geometry.modules_per_string - 1):
xa = band_x0_m + (module_index + 0.5) * module_pitch
xb = band_x0_m + (module_index + 1.5) * module_pitch
segments.append(_segment(
string_id=string_id, sequence_index=sequence,
segment_type="module_interconnect",
points=(Point3D(xa, y, z), Point3D(xb, y, z)),
installed_length_m=None, formation_type="rail_mounted_pair",
separation_mm=formations.module_interconnect_spacing_mm,
provenance="manufacturer_and_geometry",
))
sequence += 1
for module_index in range(geometry.modules_per_string):
x = band_x0_m + (module_index + 0.5) * module_pitch
for _lead in ("positive", "negative"):
point = Point3D(x, y, z)
segments.append(_segment(
string_id=string_id, sequence_index=sequence,
segment_type="coiled_surplus", points=(point, point),
installed_length_m=formations.coil_surplus_length_m,
formation_type="coiled_pair",
separation_mm=formations.coil_diameter_mm,
provenance="defaulted",
))
sequence += 1
return_y = y + sign * formations.return_spacing_mm / 1000
segments.append(_segment(
string_id=string_id, sequence_index=sequence,
segment_type="along_rank_return",
points=(Point3D(x1, y, z), Point3D(x1, return_y, z), Point3D(band_x0_m, return_y, z)),
installed_length_m=None, formation_type="rail_mounted_return",
separation_mm=formations.return_spacing_mm, provenance="assumed",
))
sequence += 1
transfer_slope = rank_index * rank_pitch_slope
transfer_plan = rank_index * rank_pitch_plan
transfer_rise = rank_index * rank_rise
transfer_end = Point3D(band_x0_m, sign * 0.08, max(0.0, z - transfer_rise))
segments.append(_segment(
string_id=string_id, sequence_index=sequence,
segment_type="across_table_transfer",
points=(Point3D(band_x0_m, return_y, z), transfer_end),
installed_length_m=transfer_slope,
formation_type="structure_mounted_pair",
separation_mm=formations.return_spacing_mm,
provenance="derived",
))
sequence += 1
drop_end = Point3D(band_x0_m, sign * 0.08, max(0.0, transfer_end.z_m - geometry.structure_drop_m))
segments.append(_segment(
string_id=string_id, sequence_index=sequence,
segment_type="structure_drop",
points=(transfer_end, drop_end), installed_length_m=geometry.structure_drop_m,
formation_type="free_air_drop", separation_mm=formations.return_spacing_mm,
provenance="assumed",
))
sequence += 1
ground_start = Point3D(band_x0_m, sign * 0.08, 0.0)
inverter = Point3D(geometry.inverter_x_m, geometry.inverter_y_m, 0.0)
segments.append(_segment(
string_id=string_id, sequence_index=sequence,
segment_type="surface_or_trench_run",
points=(ground_start, inverter), installed_length_m=None,
formation_type="buried_or_surface_pair",
separation_mm=formations.trench_spacing_mm,
provenance="geometry_and_assumed_formation",
))
return StringTopology(
string_id=string_id, face=face, band_index=band_index,
rank_index=rank_index, module_count=geometry.modules_per_string,
segments=tuple(segments),
)
def build_site_model(
geometry: GeometryConfig = GeometryConfig(),
formations: FormationConfig = FormationConfig(),
) -> tuple[StringTopology, ...]:
"""Build the full site topology headlessly, with arbitrary band lists."""
result: list[StringTopology] = []
module_pitch = geometry.module_width_m + geometry.along_gap_m
band_length = geometry.modules_along_row * module_pitch - geometry.along_gap_m
band_gap = max(0.5, geometry.along_gap_m * 5)
definitions: Iterable[tuple[str, tuple[int, ...]]] = (
("E", geometry.east_bands),
("W", geometry.west_bands if geometry.faces_per_table == 2 else ()),
)
for face, bands in definitions:
x0 = 0.0
for band_index, rank_count in enumerate(bands):
for rank_index in range(rank_count):
string_id = f"{face}-B{band_index+1}-R{rank_index+1}"
result.append(build_string_segments(
string_id, face, band_index, rank_index, x0, geometry, formations,
))
x0 += band_length + band_gap
return tuple(result)
def build_export(
strings: Sequence[StringTopology],
geometry: GeometryConfig,
formations: FormationConfig,
) -> dict:
"""Return a complete headless export with no user-supplied route length field."""
string_rows = []
for string in strings:
route_length = string.installed_conductor_length_m
string_rows.append({
"string_id": string.string_id,
"face": string.face,
"band_index": string.band_index,
"rank_index": string.rank_index,
"module_count": string.module_count,
"route_length": {
"value_m": route_length,
"source": "segment_list",
"provenance": "derived",
},
"segments": [asdict(segment) for segment in string.segments],
})
return {
"schema_version": "2.0.0-segment-chain",
"geometry": asdict(geometry),
"formations": asdict(formations),
"strings": string_rows,
"aggregates": {
"string_count": len(strings),
"site_installed_conductor_m": sum(s.installed_conductor_length_m for s in strings),
},
}
def validate_no_user_route_lengths(export: dict) -> None:
"""Fail if any final route length is not derived from its exported segment list."""
forbidden_input_keys = {
"string_length", "route_length", "home_run_length",
"positive_total_length", "negative_total_length",
}
geometry_keys = set(export.get("geometry", {}))
formation_keys = set(export.get("formations", {}))
overlap = forbidden_input_keys & (geometry_keys | formation_keys)
if overlap:
raise ValueError(f"Forbidden final length input(s): {sorted(overlap)}")
for string in export.get("strings", []):
route = string["route_length"]
segment_sum = sum(s["installed_conductor_length_m"] for s in string["segments"])
if route.get("source") != "segment_list" or route.get("provenance") != "derived":
raise ValueError(f"{string['string_id']} route length was not derived")
if not math.isclose(route["value_m"], segment_sum, rel_tol=1e-12, abs_tol=1e-12):
raise ValueError(f"{string['string_id']} route length differs from segment sum")Topology Authority
A Python module in Solar Electrical Topology Analysis Engine Text Based that works with solar.
transformsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/topology_authority.py · lines 1–88 of 88 · Not reached from any entry point (candidate for review)
- What it does
- It calculates solar. Defines AuthoritativeTopologyReceipt, issue_topology_receipt, require_topology_receipt. Uses libraries __future__, dataclasses.
- 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.
- What it achieves
- It is built from the authoritative topology receipt class (`AuthoritativeTopologyReceipt`), the issue topology receipt helper (`issue_topology_receipt`) and the require topology receipt helper (`require_topology_receipt`). Authoritative topology receipts for calculation entry-point gating.
- Why it matters
- No other file in the estate was found to import it.
- Application
- solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
- Uses
- Circuit (relative import), Circuit Traversal (relative import), Circuit Validation (relative import), __future__, dataclasses
- Used by
- none found
- Produces
- AuthoritativeTopologyReceipt, issue_topology_receipt, require_topology_receipt
- Defines here
- AuthoritativeTopologyReceipt, issue_topology_receipt, require_topology_receipt
- 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/topology_authority.py:1-88 · blob 00c5bed21dc5db6e5e34e94b478d6c01b603d31c · 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 topology receipts for calculation entry-point gating."""
from __future__ import annotations
from dataclasses import dataclass
from .circuit import CircuitModel
from .circuit_traversal import OrderedCircuitTraversal, verify_ordered_circuit
from .circuit_validation import (
CircuitValidationResult,
validate_circuit_model,
validated_circuit_hash,
)
TOPOLOGY_RECEIPT_SCHEMA_VERSION = "globalgrid2050.solar-dc.topology-receipt.v10.1"
@dataclass(frozen=True)
class AuthoritativeTopologyReceipt:
model_id: str
circuit_hash: str
start_terminal_id: str
end_terminal_id: str
ordered_terminal_ids: tuple[str, ...]
ordered_connection_ids: tuple[str, ...]
ordered_segment_ids: tuple[str, ...]
schema_version: str = TOPOLOGY_RECEIPT_SCHEMA_VERSION
def issue_topology_receipt(
model: CircuitModel,
start_terminal_id: str,
end_terminal_id: str,
*,
expected_segment_ids: tuple[str, ...] | None = None,
) -> AuthoritativeTopologyReceipt:
"""Issue a receipt only after independent validation and complete traversal."""
validation: CircuitValidationResult = validate_circuit_model(model)
validation.raise_for_errors()
traversal: OrderedCircuitTraversal = verify_ordered_circuit(
model,
start_terminal_id,
end_terminal_id,
expected_segment_ids=expected_segment_ids,
)
traversal.raise_for_errors()
return AuthoritativeTopologyReceipt(
model_id=model.model_id,
circuit_hash=validated_circuit_hash(model),
start_terminal_id=start_terminal_id,
end_terminal_id=end_terminal_id,
ordered_terminal_ids=traversal.ordered_terminal_ids,
ordered_connection_ids=traversal.ordered_connection_ids,
ordered_segment_ids=traversal.ordered_segment_ids,
)
def require_topology_receipt(
model: CircuitModel,
receipt: AuthoritativeTopologyReceipt,
) -> None:
"""Reject stale, foreign or structurally invalid receipts before calculation."""
if not isinstance(receipt, AuthoritativeTopologyReceipt):
raise TypeError("receipt must be an AuthoritativeTopologyReceipt")
if receipt.schema_version != TOPOLOGY_RECEIPT_SCHEMA_VERSION:
raise ValueError("unsupported topology receipt schema")
if receipt.model_id != model.model_id:
raise ValueError("topology receipt model_id does not match model")
current_hash = validated_circuit_hash(model)
if receipt.circuit_hash != current_hash:
raise ValueError("topology receipt is stale for the supplied circuit model")
traversal = verify_ordered_circuit(
model,
receipt.start_terminal_id,
receipt.end_terminal_id,
expected_segment_ids=receipt.ordered_segment_ids,
)
traversal.raise_for_errors()
if traversal.ordered_terminal_ids != receipt.ordered_terminal_ids:
raise ValueError("topology receipt terminal order does not match model")
if traversal.ordered_connection_ids != receipt.ordered_connection_ids:
raise ValueError("topology receipt connection order does not match model")