GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / solar-electrical-topology-analysis-engine-text-based / src/solar_topology

Public API and 2 more files

A Python module in Solar Electrical Topology Analysis Engine Text Based that works with solar.

444 lines of Python from solar-electrical-topology-analysis-engine-text-based, in 3 files. Topic: Solar and storage design. Section 229 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Products electrical · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/products.py lines 1–158
  2. Public API transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/public_api.py lines 1–176
  3. Public Topology transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/public_topology.py lines 1–110

Products

A Python module in Solar Electrical Topology Analysis Engine Text Based that works with conductor spec (`ConductorSpec`) and envelope fill factor (`envelope_fill_factor`) (units: mm², Ω), using IEC 60228.

electricalsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/products.py · lines 1–158 of 158 · Not reached from any entry point (candidate for review) · pattern as_dict (shared by 2 files)

What it does
It calculates its inputs. Defines ConductorSpec, envelope_fill_factor, resolved_resistance, validate, as_dict. Uses libraries __future__, dataclasses, 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.
Downstream impact
Used directly by 3 files: Solar Electrical Topology Analysis Engine Text Based — Solar Topology (solar-electrical-topology-analysis-engine-text-based); Equipment Profiles (solar-electrical-topology-analysis-engine-text-based); Segments (solar-electrical-topology-analysis-engine-text-based).
What it achieves
It is built from the conductor spec class (`ConductorSpec`), the resolved resistance helper (`resolved_resistance`) and the validate step (`validate`). Generic conductor products with independently resolved resistance evidence.
Why it matters
Imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology, Equipment Profiles and Segments.
Application
solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
Uses
Resistance Evidence (relative import), __future__, dataclasses, math
Used by
imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import), imported by Equipment Profiles (relative import), imported by Segments (relative import)
Produces
ConductorSpec
Defines here
ConductorSpec, envelope_fill_factor, resolved_resistance, validate, as_dict
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/products.py:1-158 · blob 47967c27cd0ed18cce8bca43c9a013aa0f098955 · 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
"""Generic conductor products with independently resolved resistance evidence."""

from __future__ import annotations

from dataclasses import asdict, dataclass
import math

from .resistance_evidence import (
    ResistanceBasis,
    ResistanceValueKind,
    ResolvedConductorResistance,
    register_conductor_resistance,
    resolve_conductor_resistance,
)


@dataclass(frozen=True)
class ConductorSpec:
    """Finished-cable geometry kept separate from resistance authority.

    This dataclass intentionally retains its pre-refinement serialised shape so
    geometry and topology input hashes do not change when resistance evidence is
    registered, verified or revised. Resistance authority is resolved by
    ``product_id`` through the independent registry.
    """

    product_id: str
    nominal_csa_mm2: float
    conductor_diameter_mm: float
    cable_od_mm: float
    r20_ohm_per_m: float
    provenance: str = "oem_declared"

    @property
    def envelope_fill_factor(self) -> float:
        envelope_area = (
            math.pi * self.conductor_diameter_mm**2 / 4
        )
        return self.nominal_csa_mm2 / envelope_area

    @property
    def resolved_resistance(self) -> ResolvedConductorResistance:
        return resolve_conductor_resistance(
            product_id=self.product_id,
            r20_ohm_per_m=self.r20_ohm_per_m,
            legacy_provenance=self.provenance,
            legacy_source_reference="legacy_conductor_spec",
        )

    def validate(self) -> None:
        if not self.product_id:
            raise ValueError("product_id is required")
        if self.nominal_csa_mm2 <= 0:
            raise ValueError("nominal_csa_mm2 must be positive")
        if self.conductor_diameter_mm <= 0:
            raise ValueError("conductor_diameter_mm must be positive")
        if self.cable_od_mm < self.conductor_diameter_mm:
            raise ValueError(
                "cable_od_mm cannot be smaller than conductor_diameter_mm"
            )
        if self.r20_ohm_per_m <= 0:
            raise ValueError("r20_ohm_per_m must be positive")
        if not 0.70 <= self.envelope_fill_factor <= 0.95:
            raise ValueError(
                "Declared conductor envelope fill must be between 70% and 95%"
            )
        if self.provenance not in {
            "measured",
            "oem_declared",
            "assumed",
            "defaulted",
        }:
            raise ValueError("unsupported legacy conductor provenance")
        resistance = self.resolved_resistance
        if resistance.product_id != self.product_id:
            raise ValueError(
                "resistance evidence product_id must match conductor product_id"
            )
        if not math.isclose(
            resistance.r20_ohm_per_m,
            self.r20_ohm_per_m,
            rel_tol=0.0,
            abs_tol=1e-15,
        ):
            raise ValueError(
                "resistance evidence R20 must match conductor R20"
            )

    def as_dict(self) -> dict:
        self.validate()
        return asdict(self)


register_conductor_resistance(
    ResolvedConductorResistance(
        product_id="factory_module_lead_4mm2_metal_coated_class5",
        r20_ohm_per_m=5.09e-3,
        basis=ResistanceBasis.STANDARD_MAXIMUM,
        value_kind=ResistanceValueKind.STANDARD_MAXIMUM,
        source_reference=(
            "IEC 60228 Class 5 metal-coated copper maximum-resistance table"
        ),
        source_revision="edition-not-yet-encoded",
        verification_state="standards_review_required",
        temperature_coefficient_per_c=0.00393,
        temperature_coefficient_basis=(
            "copper linear temperature correction from 20 C"
        ),
        warnings=(
            "Numeric standard source requires edition and table verification before certification use.",
        ),
    )
)

register_conductor_resistance(
    ResolvedConductorResistance(
        product_id="external_string_6mm2_metal_coated_class5",
        r20_ohm_per_m=3.39e-3,
        basis=ResistanceBasis.STANDARD_MAXIMUM,
        value_kind=ResistanceValueKind.STANDARD_MAXIMUM,
        source_reference=(
            "IEC 60228 Class 5 metal-coated copper maximum-resistance table"
        ),
        source_revision="edition-not-yet-encoded",
        verification_state="standards_review_required",
        temperature_coefficient_per_c=0.00393,
        temperature_coefficient_basis=(
            "copper linear temperature correction from 20 C"
        ),
        warnings=(
            "Numeric standard source requires edition and table verification before certification use.",
        ),
    )
)


FACTORY_LEAD_4MM2 = ConductorSpec(
    product_id="factory_module_lead_4mm2_metal_coated_class5",
    nominal_csa_mm2=4.0,
    conductor_diameter_mm=2.45,
    cable_od_mm=5.5,
    r20_ohm_per_m=5.09e-3,
    provenance="oem_declared",
)


EXTERNAL_STRING_6MM2 = ConductorSpec(
    product_id="external_string_6mm2_metal_coated_class5",
    nominal_csa_mm2=6.0,
    conductor_diameter_mm=3.00,
    cable_od_mm=6.1,
    r20_ohm_per_m=3.39e-3,
    provenance="oem_declared",
)


for _specification in (FACTORY_LEAD_4MM2, EXTERNAL_STRING_6MM2):
    _specification.validate()

Public API

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/public_api.py · lines 1–176 of 176 · Not reached from any entry point (candidate for review)

What it does
It calculates solar. Defines ApiStatus, explicitly_classified_public_names, public_api_status, build_public_api_inventory. Uses libraries __future__, enum.
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 builds public API inventory (`build_public_api_inventory`) and is built from the API status class (`ApiStatus`) and the explicitly classified public names helper (`explicitly_classified_public_names`). Canonical classification manifest for the package-level public API.
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
__future__, enum
Used by
imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import)
Produces
ApiStatus, explicitly_classified_public_names, public_api_status, build_public_api_inventory
Defines here
ApiStatus, explicitly_classified_public_names, public_api_status, build_public_api_inventory
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/public_api.py:1-176 · blob 2088144c9e0b45bd49764ec17b973069440707b4 · 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 classification manifest for the package-level public API.

The manifest makes package exports reviewable and gives tests a stable contract
against accidental export drift. Symbols not yet explicitly adjudicated remain
PROVISIONAL rather than silently becoming canonical.
"""

from __future__ import annotations

from enum import StrEnum


PUBLIC_API_SCHEMA_VERSION = "globalgrid2050.solar-dc.public-api.v10.1"


class ApiStatus(StrEnum):
    CANONICAL = "canonical"
    PROVISIONAL = "provisional"
    COMPATIBILITY = "compatibility"


PUBLIC_API_CLASSIFICATION: dict[ApiStatus, tuple[str, ...]] = {
    ApiStatus.CANONICAL: (
        "ALPHA_CU_20_PER_C",
        "CIRCUIT_SCHEMA_VERSION",
        "CALCULATION_RECEIPT_SCHEMA_VERSION",
        "COMPLETE_CIRCUIT_METHOD_VERSION",
        "TOPOLOGY_RECEIPT_SCHEMA_VERSION",
        "AuthoritativeTopologyReceipt",
        "CircuitModel",
        "CircuitValidationResult",
        "Connection",
        "ConnectionKind",
        "ConductorSpec",
        "EvidenceClass",
        "EvidenceDescriptor",
        "FormationConfig",
        "GeometryConfig",
        "GeometryReceipt",
        "Interval",
        "IssueSeverity",
        "ObjectKind",
        "OperatingState",
        "OrderedCircuitCalculationReceipt",
        "OrderedCircuitTraversal",
        "PhysicalObject",
        "Point3D",
        "Segment",
        "SegmentCalculationResult",
        "SegmentGeometryResult",
        "SegmentInputIntervals",
        "SegmentRow",
        "StringDefinition",
        "StringTopology",
        "Terminal",
        "TerminalPolarity",
        "TopologyInputs",
        "UncertainCircuitCalculationReceipt",
        "ValidationIssue",
        "VerificationState",
        "adapt_segment_chain_to_circuit",
        "build_export",
        "build_leapfrog_circuit",
        "build_sequential_circuit",
        "build_site_model",
        "build_string_segments",
        "calculate_complete_circuit",
        "calculate_complete_circuit_with_uncertainty",
        "calculate_geometry_receipt",
        "canonical_circuit_json",
        "canonical_circuit_payload",
        "canonical_evidence_descriptor",
        "cold_string_voc",
        "dc_resistance",
        "geometry_receipt_hash",
        "geometry_receipt_json",
        "geometry_receipt_payload",
        "issue_topology_receipt",
        "require_topology_receipt",
        "stored_electric_energy",
        "stored_magnetic_energy",
        "two_wire_parameters",
        "uncertainty_receipt_hash",
        "uncertainty_receipt_json",
        "uncertainty_receipt_payload",
        "validate_circuit_model",
        "validate_no_user_route_lengths",
        "validated_circuit_hash",
        "verify_ordered_circuit",
    ),
    ApiStatus.PROVISIONAL: (
        "INVERTER_BLOCK_SCHEMA_VERSION",
        "REFERENCE_INVERTER_BLOCK_ID",
        "InverterBlockEvidenceState",
        "InverterBlockReceipt",
        "build_inverter_block",
        "build_reference_inverter_block",
        "inverter_block_hash",
        "inverter_block_json",
        "inverter_block_payload",
        "validate_inverter_block_receipt",
        "EQUIPMENT_PROFILE_SCHEMA_VERSION",
        "GENERIC_REFERENCE_CONTRACT_REVISION",
        "GENERIC_REFERENCE_EQUIPMENT_CONTRACT",
        "ConnectorCompatibilityState",
        "ConnectorEquipmentProfile",
        "DcInputProfile",
        "FactoryLeadSetProfile",
        "FieldConductorProfile",
        "InternalDcTopology",
        "InverterEquipmentProfile",
        "ModuleEquipmentProfile",
        "ModuleTechnology",
        "QualifiedValue",
        "ReferenceEquipmentContract",
        "ReverseCurrentBlockingState",
        "build_generic_reference_equipment_contract",
        "reference_equipment_contract_hash",
        "reference_equipment_contract_json",
        "reference_equipment_contract_payload",
        "reference_equipment_missing_evidence",
        "validate_reference_equipment_contract",
        "RESISTANCE_QUALIFICATION_SCHEMA_VERSION",
        "ResistanceSourceAssessment",
        "ResistanceSourceStatus",
        "assess_resistance_source",
        "resistance_source_assessment_hash",
        "resistance_source_assessment_json",
        "resistance_source_assessment_payload",
    ),
    ApiStatus.COMPATIBILITY: (
        "EXTERNAL_STRING_6MM2",
        "FACTORY_LEAD_4MM2",
        "INITIAL_CARTRIDGES",
        "INITIAL_STUDIES",
        "LeapfrogCartridge",
        "SequentialCartridge",
        "TopologyCartridge",
        "build_deterministic_store",
        "build_fleet_segments",
        "build_store",
        "javascript_provenance_descriptor",
        "segment_provenance_descriptor",
        "validate_cross_cartridge_invariants",
        "validate_segment_chains",
    ),
}


def explicitly_classified_public_names() -> tuple[str, ...]:
    """Return explicitly adjudicated names in deterministic order."""

    names = [name for group in PUBLIC_API_CLASSIFICATION.values() for name in group]
    if len(names) != len(set(names)):
        raise ValueError("public API classification contains duplicate symbols")
    return tuple(sorted(names))


def public_api_status(name: str) -> ApiStatus:
    """Return status for a package symbol; unknown names remain provisional."""

    for status, names in PUBLIC_API_CLASSIFICATION.items():
        if name in names:
            return status
    return ApiStatus.PROVISIONAL


def build_public_api_inventory(
    exported_names: tuple[str, ...] | list[str],
) -> tuple[tuple[str, ApiStatus], ...]:
    """Build a deterministic total inventory for supplied package exports."""

    names = tuple(exported_names)
    if len(names) != len(set(names)):
        raise ValueError("package exports contain duplicate symbols")
    return tuple((name, public_api_status(name)) for name in sorted(names))

Public Topology

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/public_topology.py · lines 1–110 of 110 · Not reached from any entry point (candidate for review) · pattern __post_init__ (shared by 16 files)

What it does
It calculates solar. Defines 7 functions or classes, including PublicTopologyRecord, __post_init__, PublicTopologyManifest, build_public_topology_manifest, public_topology_payload. Uses libraries __future__, dataclasses, hashlib, json, 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. 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 builds public topology manifest (`build_public_topology_manifest`) and is built from the public topology record class (`PublicTopologyRecord`) and the public topology manifest class (`PublicTopologyManifest`). Evidence-bearing public topology manifests for V10.
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
Evidence Boundary (relative import), Identifiers (relative import), __future__, dataclasses, hashlib, json, typing
Used by
imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import)
Produces
PublicTopologyRecord, PublicTopologyManifest, build_public_topology_manifest, public_topology_payload, public_topology_json, public_topology_hash
Defines here
PublicTopologyRecord, __post_init__, PublicTopologyManifest, build_public_topology_manifest, public_topology_payload, public_topology_json, public_topology_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/public_topology.py:1-110 · blob 737dc8f8100fafb5fd76cba27b9f16a3ec043d63 · 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
"""Evidence-bearing public topology manifests for V10.

This layer records only publicly supportable topology facts. It does not ingest,
encode or reproduce Employer's Requirements, SLDs or other NDA material.
"""

from __future__ import annotations

from dataclasses import dataclass
import hashlib
import json
from typing import Mapping

from .evidence_boundary import EvidenceSource, assess_publication_boundary
from .identifiers import CanonicalIdentifier, EntityLevel, require_unique_identifiers


PUBLIC_TOPOLOGY_SCHEMA_VERSION = "globalgrid2050.solar-dc.public-topology.v10.1"


@dataclass(frozen=True)
class PublicTopologyRecord:
    identifier: CanonicalIdentifier
    record_type: str
    source_ids: tuple[str, ...]
    attributes: tuple[tuple[str, str | int | float | bool | None], ...] = ()

    def __post_init__(self) -> None:
        if self.identifier.level is EntityLevel.PROJECT:
            raise ValueError("topology records must sit below project level")
        if not isinstance(self.record_type, str) or not self.record_type.strip():
            raise ValueError("record_type must be non-empty text")
        if not self.source_ids or any(
            not isinstance(source_id, str) or not source_id.strip()
            for source_id in self.source_ids
        ):
            raise ValueError("source_ids must contain non-empty text")
        if tuple(sorted(set(self.source_ids))) != self.source_ids:
            raise ValueError("source_ids must be unique and sorted")
        keys = [key for key, _ in self.attributes]
        if keys != sorted(keys) or len(keys) != len(set(keys)):
            raise ValueError("attribute keys must be unique and sorted")


@dataclass(frozen=True)
class PublicTopologyManifest:
    project_identifier: CanonicalIdentifier
    records: tuple[PublicTopologyRecord, ...]
    public_source_ids: tuple[str, ...]
    schema_version: str = PUBLIC_TOPOLOGY_SCHEMA_VERSION


def build_public_topology_manifest(
    project_identifier: CanonicalIdentifier,
    records: tuple[PublicTopologyRecord, ...] | list[PublicTopologyRecord],
    sources: Mapping[str, EvidenceSource],
) -> PublicTopologyManifest:
    if project_identifier.level is not EntityLevel.PROJECT:
        raise ValueError("project_identifier must be project level")
    ordered_records = tuple(sorted(records, key=lambda record: record.identifier.value))
    require_unique_identifiers([record.identifier for record in ordered_records])
    source_ids = sorted({source_id for record in ordered_records for source_id in record.source_ids})
    missing = [source_id for source_id in source_ids if source_id not in sources]
    if missing:
        raise ValueError(f"manifest references unknown evidence sources: {missing}")
    for record in ordered_records:
        if not record.identifier.value.startswith(project_identifier.value + "/"):
            raise ValueError("all topology records must belong to the manifest project")
        decision = assess_publication_boundary([sources[source_id] for source_id in record.source_ids])
        if not decision.publishable or decision.restricted_source_ids:
            detail = "; ".join(decision.reasons) or "restricted evidence present"
            raise PermissionError(
                f"public topology record {record.identifier.value!r} blocked: {detail}"
            )
    return PublicTopologyManifest(
        project_identifier=project_identifier,
        records=ordered_records,
        public_source_ids=tuple(source_ids),
    )


def public_topology_payload(manifest: PublicTopologyManifest) -> dict[str, object]:
    return {
        "schema_version": manifest.schema_version,
        "project_identifier": manifest.project_identifier.value,
        "public_source_ids": list(manifest.public_source_ids),
        "records": [
            {
                "identifier": record.identifier.value,
                "record_type": record.record_type,
                "source_ids": list(record.source_ids),
                "attributes": {key: value for key, value in record.attributes},
            }
            for record in manifest.records
        ],
    }


def public_topology_json(manifest: PublicTopologyManifest) -> str:
    return json.dumps(
        public_topology_payload(manifest),
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
    )


def public_topology_hash(manifest: PublicTopologyManifest) -> str:
    digest = hashlib.sha256(public_topology_json(manifest).encode("utf-8")).hexdigest()
    return f"sha256:{digest}"