GLOBALGRID2050 / EXPLORE CODE

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

Geometry Authority and 2 more files

A Python module in the array folder of Solar Electrical Topology Analysis Engine Text Based that generates table geometry (`generate_table_geometry`), using SHA-256.

564 lines of Python from solar-electrical-topology-analysis-engine-text-based, in 3 files. Topic: Solar and storage design. Section 216 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. Geometry Authority transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/array/geometry_authority.py lines 1–293
  2. Table String Assignment transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/array/table_string_assignment.py lines 1–220
  3. Table String Hashing transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/array/table_string_hashing.py lines 1–51

Geometry Authority

A Python module in the array folder of Solar Electrical Topology Analysis Engine Text Based that generates table geometry (`generate_table_geometry`), using SHA-256.

transformsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/array/geometry_authority.py · lines 1–293 of 293 · Not reached from any entry point (candidate for review) · pattern _canonical_payload (shared by 2 files)

What it does
It calculates its inputs. Defines 17 functions or classes, including Point2D, __post_init__, ModuleDimensions, __post_init__, oriented. Uses libraries __future__, dataclasses, hashlib, json, math.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'array'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 8 files: Solar Topology — Array (solar-electrical-topology-analysis-engine-text-based); Array Engine (solar-electrical-topology-analysis-engine-text-based); Array Route Geometry (solar-electrical-topology-analysis-engine-text-based); Array Route Types (solar-electrical-topology-analysis-engine-text-based); and 4 more.
What it achieves
It is built from the point2 d class (`Point2D`), the module dimensions class (`ModuleDimensions`) and the oriented step (`oriented`). Deterministic, geometry-authoritative PV table placement.
Why it matters
Imported by 8 files, including Solar Topology — Array, Array Engine and Array Route Geometry.
Application
solar-electrical-topology-analysis-engine-text-based · src/solar_topology/array · Python module
Uses
__future__, dataclasses, hashlib, json, math, typing
Used by
imported by Solar Topology — Array (relative import), imported by Array Engine (import), imported by Array Route Geometry (import), imported by Array Route Types (import), imported by Array Routing (import), imported by Array Topology (import), imported by Table String Assignment (import), imported by Table String Validation (import)
Produces
Point2D, ModuleDimensions, TableLayoutRequest, ModulePlacement, TableBounds, TableGeometryReceipt, generate_table_geometry, receipt_as_dict, reference_24_by_30_table
Defines here
Point2D, __post_init__, ModuleDimensions, __post_init__, oriented, TableLayoutRequest, __post_init__, ModulePlacement, TableBounds, TableGeometryReceipt, _canonical_float, _rotate_translate, _corners, _canonical_payload, generate_table_geometry, receipt_as_dict, reference_24_by_30_table
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/array/geometry_authority.py:1-293 · blob acc18b4c2dcd7083565ff9e81cda309bdb6d9a90 · 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-authoritative PV table placement.

Build 025A intentionally contains no electrical physics. It establishes immutable
module placement and a canonical geometry receipt for later topology and routing.
"""

from __future__ import annotations

from dataclasses import asdict, dataclass
from hashlib import sha256
import json
import math
from typing import Literal


Orientation = Literal["portrait", "landscape"]


@dataclass(frozen=True, slots=True)
class Point2D:
    """A point in site-local metres."""

    x_m: float
    y_m: float

    def __post_init__(self) -> None:
        if not math.isfinite(self.x_m) or not math.isfinite(self.y_m):
            raise ValueError("Point coordinates must be finite")


@dataclass(frozen=True, slots=True)
class ModuleDimensions:
    """Physical module face dimensions before orientation is applied."""

    width_m: float
    height_m: float

    def __post_init__(self) -> None:
        if not math.isfinite(self.width_m) or self.width_m <= 0:
            raise ValueError("Module width must be finite and positive")
        if not math.isfinite(self.height_m) or self.height_m <= 0:
            raise ValueError("Module height must be finite and positive")

    def oriented(self, orientation: Orientation) -> tuple[float, float]:
        if orientation == "portrait":
            return self.width_m, self.height_m
        if orientation == "landscape":
            return self.height_m, self.width_m
        raise ValueError(f"Unsupported module orientation: {orientation!r}")


@dataclass(frozen=True, slots=True)
class TableLayoutRequest:
    """Canonical request for a regular rectangular PV table."""

    table_id: str
    module_count: int
    rows: int
    columns: int
    module_dimensions: ModuleDimensions
    orientation: Orientation = "portrait"
    horizontal_gap_m: float = 0.02
    vertical_gap_m: float = 0.02
    origin: Point2D = Point2D(0.0, 0.0)
    rotation_deg: float = 0.0

    def __post_init__(self) -> None:
        if not self.table_id.strip():
            raise ValueError("table_id must not be empty")
        if self.module_count <= 0:
            raise ValueError("module_count must be positive")
        if self.rows <= 0 or self.columns <= 0:
            raise ValueError("rows and columns must be positive")
        if self.module_count > self.rows * self.columns:
            raise ValueError("rows × columns cannot contain module_count")
        if self.orientation not in ("portrait", "landscape"):
            raise ValueError("orientation must be portrait or landscape")
        for name, value in (
            ("horizontal_gap_m", self.horizontal_gap_m),
            ("vertical_gap_m", self.vertical_gap_m),
        ):
            if not math.isfinite(value) or value < 0:
                raise ValueError(f"{name} must be finite and non-negative")
        if not math.isfinite(self.rotation_deg):
            raise ValueError("rotation_deg must be finite")


@dataclass(frozen=True, slots=True)
class ModulePlacement:
    """One module's authoritative centre point and oriented envelope."""

    module_id: str
    ordinal: int
    row_index: int
    column_index: int
    centre: Point2D
    width_m: float
    height_m: float
    rotation_deg: float


@dataclass(frozen=True, slots=True)
class TableBounds:
    min_x_m: float
    min_y_m: float
    max_x_m: float
    max_y_m: float


@dataclass(frozen=True, slots=True)
class TableGeometryReceipt:
    schema_version: str
    table_id: str
    module_count: int
    rows: int
    columns: int
    orientation: Orientation
    origin: Point2D
    rotation_deg: float
    bounds: TableBounds
    placements: tuple[ModulePlacement, ...]
    geometry_hash: str


def _canonical_float(value: float) -> float:
    """Normalise insignificant binary noise before hashing receipts."""

    rounded = round(value, 9)
    return 0.0 if rounded == -0.0 else rounded


def _rotate_translate(local_x: float, local_y: float, request: TableLayoutRequest) -> Point2D:
    theta = math.radians(request.rotation_deg)
    cos_theta = math.cos(theta)
    sin_theta = math.sin(theta)
    return Point2D(
        _canonical_float(request.origin.x_m + local_x * cos_theta - local_y * sin_theta),
        _canonical_float(request.origin.y_m + local_x * sin_theta + local_y * cos_theta),
    )


def _corners(placement: ModulePlacement) -> tuple[Point2D, Point2D, Point2D, Point2D]:
    half_w = placement.width_m / 2.0
    half_h = placement.height_m / 2.0
    theta = math.radians(placement.rotation_deg)
    cos_theta = math.cos(theta)
    sin_theta = math.sin(theta)
    points: list[Point2D] = []
    for dx, dy in ((-half_w, -half_h), (half_w, -half_h), (half_w, half_h), (-half_w, half_h)):
        points.append(
            Point2D(
                _canonical_float(placement.centre.x_m + dx * cos_theta - dy * sin_theta),
                _canonical_float(placement.centre.y_m + dx * sin_theta + dy * cos_theta),
            )
        )
    return tuple(points)  # type: ignore[return-value]


def _canonical_payload(
    request: TableLayoutRequest,
    placements: tuple[ModulePlacement, ...],
    bounds: TableBounds,
) -> dict[str, object]:
    return {
        "schema_version": "0.1.0",
        "table_id": request.table_id,
        "module_count": request.module_count,
        "rows": request.rows,
        "columns": request.columns,
        "orientation": request.orientation,
        "module_dimensions_m": {
            "width": _canonical_float(request.module_dimensions.width_m),
            "height": _canonical_float(request.module_dimensions.height_m),
        },
        "horizontal_gap_m": _canonical_float(request.horizontal_gap_m),
        "vertical_gap_m": _canonical_float(request.vertical_gap_m),
        "origin_m": [_canonical_float(request.origin.x_m), _canonical_float(request.origin.y_m)],
        "rotation_deg": _canonical_float(request.rotation_deg),
        "bounds_m": [
            _canonical_float(bounds.min_x_m),
            _canonical_float(bounds.min_y_m),
            _canonical_float(bounds.max_x_m),
            _canonical_float(bounds.max_y_m),
        ],
        "placements": [
            {
                "module_id": item.module_id,
                "ordinal": item.ordinal,
                "row_index": item.row_index,
                "column_index": item.column_index,
                "centre_m": [
                    _canonical_float(item.centre.x_m),
                    _canonical_float(item.centre.y_m),
                ],
                "width_m": _canonical_float(item.width_m),
                "height_m": _canonical_float(item.height_m),
                "rotation_deg": _canonical_float(item.rotation_deg),
            }
            for item in placements
        ],
    }


def generate_table_geometry(request: TableLayoutRequest) -> TableGeometryReceipt:
    """Generate deterministic row-major module placements and a content hash.

    The first module is centred at half a module width/height from the table-local
    origin. Unused cells, when capacity exceeds module_count, occur at the end of
    row-major ordering. String assignment is deliberately deferred to Build 025B.
    """

    module_width_m, module_height_m = request.module_dimensions.oriented(request.orientation)
    pitch_x = module_width_m + request.horizontal_gap_m
    pitch_y = module_height_m + request.vertical_gap_m

    placements: list[ModulePlacement] = []
    for ordinal in range(request.module_count):
        row_index, column_index = divmod(ordinal, request.columns)
        local_x = module_width_m / 2.0 + column_index * pitch_x
        local_y = module_height_m / 2.0 + row_index * pitch_y
        placements.append(
            ModulePlacement(
                module_id=f"{request.table_id}-MOD-{ordinal + 1:04d}",
                ordinal=ordinal,
                row_index=row_index,
                column_index=column_index,
                centre=_rotate_translate(local_x, local_y, request),
                width_m=module_width_m,
                height_m=module_height_m,
                rotation_deg=_canonical_float(request.rotation_deg),
            )
        )

    immutable_placements = tuple(placements)
    all_corners = [corner for placement in immutable_placements for corner in _corners(placement)]
    bounds = TableBounds(
        min_x_m=_canonical_float(min(point.x_m for point in all_corners)),
        min_y_m=_canonical_float(min(point.y_m for point in all_corners)),
        max_x_m=_canonical_float(max(point.x_m for point in all_corners)),
        max_y_m=_canonical_float(max(point.y_m for point in all_corners)),
    )

    payload = _canonical_payload(request, immutable_placements, bounds)
    encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8")
    geometry_hash = f"sha256:{sha256(encoded).hexdigest()}"

    return TableGeometryReceipt(
        schema_version="0.1.0",
        table_id=request.table_id,
        module_count=request.module_count,
        rows=request.rows,
        columns=request.columns,
        orientation=request.orientation,
        origin=request.origin,
        rotation_deg=_canonical_float(request.rotation_deg),
        bounds=bounds,
        placements=immutable_placements,
        geometry_hash=geometry_hash,
    )


def receipt_as_dict(receipt: TableGeometryReceipt) -> dict[str, object]:
    """Return a JSON-compatible representation for evidence and browser transport."""

    return asdict(receipt)


def reference_24_by_30_table(
    *,
    table_id: str = "TABLE-001",
    origin: Point2D = Point2D(0.0, 0.0),
    rotation_deg: float = 0.0,
) -> TableGeometryReceipt:
    """Build the initial 24-string × 30-module geometry fixture.

    This function establishes 24 rows of 30 modules. String membership is not yet
    asserted; Build 025B will bind each row to an ordered string explicitly.
    """

    return generate_table_geometry(
        TableLayoutRequest(
            table_id=table_id,
            module_count=720,
            rows=24,
            columns=30,
            module_dimensions=ModuleDimensions(width_m=1.134, height_m=2.278),
            orientation="portrait",
            horizontal_gap_m=0.02,
            vertical_gap_m=0.02,
            origin=origin,
            rotation_deg=rotation_deg,
        )
    )

Table String Assignment

A Python module in the array folder of Solar Electrical Topology Analysis Engine Text Based that assigns modules to strings (`assign_modules_to_strings`), using SHA-256.

transformsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/array/table_string_assignment.py · lines 1–220 of 220 · Not reached from any entry point (candidate for review) · pattern _canonical_payload (shared by 2 files)

What it does
It calculates its inputs. Defines 10 functions or classes, including StringFreeTerminal, __post_init__, OrderedStringMembership, __post_init__, physical_module_ids. Uses libraries __future__, dataclasses, hashlib, json, typing.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'array'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 4 files: Array Topology (solar-electrical-topology-analysis-engine-text-based); Table String Hashing (solar-electrical-topology-analysis-engine-text-based); Table String Validation (solar-electrical-topology-analysis-engine-text-based); Table String Assignment (solar-electrical-topology-analysis-engine-text-based).
What it achieves
It is built from the string free terminal class (`StringFreeTerminal`), the ordered string membership class (`OrderedStringMembership`) and the physical module ids helper (`physical_module_ids`). Deterministic module-to-string membership for Build 025B.
Why it matters
Imported by 4 files, including Array Topology, Table String Hashing and Table String Validation.
Application
solar-electrical-topology-analysis-engine-text-based · src/solar_topology/array · Python module
Uses
Geometry Authority (import), __future__, dataclasses, hashlib, json, typing
Used by
imported by Array Topology (import), imported by Table String Hashing (import), imported by Table String Validation (import), imported by Table String Assignment (import)
Produces
StringFreeTerminal, OrderedStringMembership, TableStringAssignmentReceipt, assign_modules_to_strings, assignment_as_dict
Defines here
StringFreeTerminal, __post_init__, OrderedStringMembership, __post_init__, physical_module_ids, TableStringAssignmentReceipt, assignments, _canonical_payload, assign_modules_to_strings, assignment_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/array/table_string_assignment.py:1-220 · blob a5d80ab9dde862b09b6ca0298e4b8a73fd34d40a · 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 module-to-string membership for Build 025B.

This module binds authoritative table placements into stable string membership.
It deliberately does not choose sequential or leapfrog electrical routing; those
strategies consume the same membership receipt in Build 025C.
"""

from __future__ import annotations

from dataclasses import asdict, dataclass
from hashlib import sha256
import json
from typing import Literal

from geometry_authority import TableGeometryReceipt


Polarity = Literal["positive", "negative"]
STRING_ASSIGNMENT_SCHEMA_VERSION = "0.1.0"
STRING_ORDER_BASIS = "placement_ordinal"


@dataclass(frozen=True, slots=True)
class StringFreeTerminal:
    """A logical string boundary terminal, before route geometry is generated."""

    terminal_id: str
    string_id: str
    polarity: Polarity

    def __post_init__(self) -> None:
        if not self.terminal_id.strip():
            raise ValueError("terminal_id must not be empty")
        if not self.string_id.strip():
            raise ValueError("string_id must not be empty")
        if self.polarity not in ("positive", "negative"):
            raise ValueError("polarity must be positive or negative")


@dataclass(frozen=True, slots=True)
class OrderedStringMembership:
    """One string's stable module membership in physical placement order."""

    string_id: str
    ordinal: int
    ordered_module_ids: tuple[str, ...]
    order_basis: str
    positive_free_terminal: StringFreeTerminal
    negative_free_terminal: StringFreeTerminal

    def __post_init__(self) -> None:
        if not self.string_id.strip():
            raise ValueError("string_id must not be empty")
        if self.ordinal < 0:
            raise ValueError("ordinal must be non-negative")
        if not self.ordered_module_ids:
            raise ValueError("ordered_module_ids must not be empty")
        if len(set(self.ordered_module_ids)) != len(self.ordered_module_ids):
            raise ValueError("ordered_module_ids must be unique within a string")
        if not self.order_basis.strip():
            raise ValueError("order_basis must not be empty")
        for terminal, polarity in (
            (self.positive_free_terminal, "positive"),
            (self.negative_free_terminal, "negative"),
        ):
            if terminal.string_id != self.string_id:
                raise ValueError("free terminal string_id must match membership string_id")
            if terminal.polarity != polarity:
                raise ValueError(f"expected {polarity} free terminal")

    @property
    def physical_module_ids(self) -> tuple[str, ...]:
        """Read-only compatibility name used by downstream topology layers."""

        return self.ordered_module_ids


@dataclass(frozen=True, slots=True)
class TableStringAssignmentReceipt:
    """Content-addressed string membership bound to one geometry receipt."""

    schema_version: str
    table_id: str
    geometry_hash: str
    string_count: int
    modules_per_string: int
    strings: tuple[OrderedStringMembership, ...]
    assignment_hash: str

    @property
    def assignments(self) -> tuple[OrderedStringMembership, ...]:
        """Read-only compatibility name; ``strings`` remains canonical."""

        return self.strings


def _canonical_payload(
    *,
    geometry: TableGeometryReceipt,
    string_count: int,
    modules_per_string: int,
    strings: tuple[OrderedStringMembership, ...],
) -> dict[str, object]:
    return {
        "schema_version": STRING_ASSIGNMENT_SCHEMA_VERSION,
        "table_id": geometry.table_id,
        "geometry_hash": geometry.geometry_hash,
        "string_count": string_count,
        "modules_per_string": modules_per_string,
        "strings": [
            {
                "string_id": item.string_id,
                "ordinal": item.ordinal,
                "ordered_module_ids": list(item.ordered_module_ids),
                "order_basis": item.order_basis,
                "positive_free_terminal": {
                    "terminal_id": item.positive_free_terminal.terminal_id,
                    "string_id": item.positive_free_terminal.string_id,
                    "polarity": item.positive_free_terminal.polarity,
                },
                "negative_free_terminal": {
                    "terminal_id": item.negative_free_terminal.terminal_id,
                    "string_id": item.negative_free_terminal.string_id,
                    "polarity": item.negative_free_terminal.polarity,
                },
            }
            for item in strings
        ],
    }


def assign_modules_to_strings(
    geometry: TableGeometryReceipt,
    *,
    string_count: int,
    modules_per_string: int,
) -> TableStringAssignmentReceipt:
    """Bind placements to strings in deterministic placement-ordinal chunks.

    The order records physical membership only. Sequential and leapfrog cartridges
    may later traverse these same members in different electrical orders without
    changing the assignment hash.
    """

    if string_count <= 0:
        raise ValueError("string_count must be positive")
    if modules_per_string <= 0:
        raise ValueError("modules_per_string must be positive")
    expected_module_count = string_count * modules_per_string
    if geometry.module_count != expected_module_count:
        raise ValueError(
            "geometry module_count must equal string_count × modules_per_string"
        )
    if len(geometry.placements) != geometry.module_count:
        raise ValueError("geometry placement count must equal geometry module_count")

    placements = tuple(sorted(geometry.placements, key=lambda item: item.ordinal))
    expected_ordinals = tuple(range(geometry.module_count))
    actual_ordinals = tuple(item.ordinal for item in placements)
    if actual_ordinals != expected_ordinals:
        raise ValueError("geometry placement ordinals must be unique and contiguous")

    module_ids = tuple(item.module_id for item in placements)
    if len(set(module_ids)) != len(module_ids):
        raise ValueError("geometry module identifiers must be unique")

    memberships: list[OrderedStringMembership] = []
    for string_ordinal in range(string_count):
        string_id = f"{geometry.table_id}-STR-{string_ordinal + 1:03d}"
        start = string_ordinal * modules_per_string
        stop = start + modules_per_string
        memberships.append(
            OrderedStringMembership(
                string_id=string_id,
                ordinal=string_ordinal,
                ordered_module_ids=module_ids[start:stop],
                order_basis=STRING_ORDER_BASIS,
                positive_free_terminal=StringFreeTerminal(
                    terminal_id=f"{string_id}-TERM-POS",
                    string_id=string_id,
                    polarity="positive",
                ),
                negative_free_terminal=StringFreeTerminal(
                    terminal_id=f"{string_id}-TERM-NEG",
                    string_id=string_id,
                    polarity="negative",
                ),
            )
        )

    immutable_memberships = tuple(memberships)
    payload = _canonical_payload(
        geometry=geometry,
        string_count=string_count,
        modules_per_string=modules_per_string,
        strings=immutable_memberships,
    )
    encoded = json.dumps(
        payload,
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=True,
    ).encode("utf-8")
    assignment_hash = f"sha256:{sha256(encoded).hexdigest()}"

    return TableStringAssignmentReceipt(
        schema_version=STRING_ASSIGNMENT_SCHEMA_VERSION,
        table_id=geometry.table_id,
        geometry_hash=geometry.geometry_hash,
        string_count=string_count,
        modules_per_string=modules_per_string,
        strings=immutable_memberships,
        assignment_hash=assignment_hash,
    )


def assignment_as_dict(receipt: TableStringAssignmentReceipt) -> dict[str, object]:
    """Return a JSON-compatible representation for evidence transport."""

    return asdict(receipt)

Table String Hashing

A Python module in the array folder of Solar Electrical Topology Analysis Engine Text Based that calculates assignment hash (`calculate_assignment_hash`), using SHA-256.

transformsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/array/table_string_hashing.py · lines 1–51 of 51 · Not reached from any entry point (candidate for review)

What it does
It calculates its inputs. Defines assignment_payload, calculate_assignment_hash. Uses libraries __future__, hashlib, json.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'array'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 2 files: Table String Validation (solar-electrical-topology-analysis-engine-text-based); Table String Hashing (solar-electrical-topology-analysis-engine-text-based).
What it achieves
It is built from the assignment payload helper (`assignment_payload`). Independent canonical hashing for Build 025B assignment receipts.
Why it matters
Imported by Table String Validation and a file of the same name.
Application
solar-electrical-topology-analysis-engine-text-based · src/solar_topology/array · Python module
Uses
Table String Assignment (import), __future__, hashlib, json
Used by
imported by Table String Validation (import), imported by Table String Hashing (import)
Produces
assignment_payload, calculate_assignment_hash
Defines here
assignment_payload, calculate_assignment_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/array/table_string_hashing.py:1-51 · blob d5948a18277124d875df0fe907007df90adb804e · 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
"""Independent canonical hashing for Build 025B assignment receipts."""

from __future__ import annotations

from hashlib import sha256
import json

from table_string_assignment import TableStringAssignmentReceipt


def assignment_payload(receipt: TableStringAssignmentReceipt) -> dict[str, object]:
    """Return the canonical receipt payload excluding its asserted hash."""

    return {
        "schema_version": receipt.schema_version,
        "table_id": receipt.table_id,
        "geometry_hash": receipt.geometry_hash,
        "string_count": receipt.string_count,
        "modules_per_string": receipt.modules_per_string,
        "strings": [
            {
                "string_id": item.string_id,
                "ordinal": item.ordinal,
                "ordered_module_ids": list(item.ordered_module_ids),
                "order_basis": item.order_basis,
                "positive_free_terminal": {
                    "terminal_id": item.positive_free_terminal.terminal_id,
                    "string_id": item.positive_free_terminal.string_id,
                    "polarity": item.positive_free_terminal.polarity,
                },
                "negative_free_terminal": {
                    "terminal_id": item.negative_free_terminal.terminal_id,
                    "string_id": item.negative_free_terminal.string_id,
                    "polarity": item.negative_free_terminal.polarity,
                },
            }
            for item in receipt.strings
        ],
    }


def calculate_assignment_hash(receipt: TableStringAssignmentReceipt) -> str:
    """Recalculate the deterministic SHA-256 content hash independently."""

    encoded = json.dumps(
        assignment_payload(receipt),
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=True,
    ).encode("utf-8")
    return f"sha256:{sha256(encoded).hexdigest()}"