GLOBALGRID2050 / EXPLORE CODE

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

Cartridges and 2 more files

A Python module in Solar Electrical Topology Analysis Engine Text Based that builds segments (`build_segments`) and fleet segments (`build_fleet_segments`) and validates segment chains (`validate_segment_chains`) (units: Ω), using SHA-256.

700 lines of Python from solar-electrical-topology-analysis-engine-text-based, in 3 files. Topic: Solar and storage design. Section 217 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. Table String Validation transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/array/table_string_validation.py lines 1–144
  2. Calculation Receipts transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/calculation_receipts.py lines 1–179
  3. Cartridges transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/cartridges.py lines 1–377

Table String Validation

A Python module in the array folder of Solar Electrical Topology Analysis Engine Text Based that validates table assignment (`validate_table_string_assignment`).

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

What it does
It calculates its inputs. Defines StringAssignmentValidationIssue, StringAssignmentValidationResult, validate_table_string_assignment, add. Uses libraries __future__, dataclasses.
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: Array Topology (solar-electrical-topology-analysis-engine-text-based); Table String Validation (solar-electrical-topology-analysis-engine-text-based).
What it achieves
It is built from the string assignment validation issue class (`StringAssignmentValidationIssue`), the string assignment validation result class (`StringAssignmentValidationResult`) and the add step (`add`). Independent structural validation for Build 025B string membership.
Why it matters
Imported by Array Topology and a file of the same name.
Application
solar-electrical-topology-analysis-engine-text-based · src/solar_topology/array · Python module
Uses
Geometry Authority (import), Table String Assignment (import), Table String Hashing (import), __future__, dataclasses
Used by
imported by Array Topology (import), imported by Table String Validation (import)
Produces
StringAssignmentValidationIssue, StringAssignmentValidationResult, validate_table_string_assignment
Defines here
StringAssignmentValidationIssue, StringAssignmentValidationResult, validate_table_string_assignment, add
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_validation.py:1-144 · blob 561d457092075d9f404d0f24f2797b9963a54a45 · 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 structural validation for Build 025B string membership."""

from __future__ import annotations

from dataclasses import dataclass

from geometry_authority import TableGeometryReceipt
from table_string_assignment import (
    STRING_ORDER_BASIS,
    TableStringAssignmentReceipt,
)
from table_string_hashing import calculate_assignment_hash


@dataclass(frozen=True, slots=True)
class StringAssignmentValidationIssue:
    code: str
    message: str


@dataclass(frozen=True, slots=True)
class StringAssignmentValidationResult:
    table_id: str
    valid: bool
    checked_string_count: int
    checked_module_count: int
    issues: tuple[StringAssignmentValidationIssue, ...]


def validate_table_string_assignment(
    geometry: TableGeometryReceipt,
    assignment: TableStringAssignmentReceipt,
) -> StringAssignmentValidationResult:
    """Validate membership without trusting the assignment builder."""

    issues: list[StringAssignmentValidationIssue] = []

    def add(code: str, message: str) -> None:
        issues.append(StringAssignmentValidationIssue(code=code, message=message))

    if assignment.assignment_hash != calculate_assignment_hash(assignment):
        add("ASSIGNMENT_HASH_MISMATCH", "assignment content does not match its asserted hash")
    if assignment.table_id != geometry.table_id:
        add("TABLE_ID_MISMATCH", "assignment table_id does not match geometry")
    if assignment.geometry_hash != geometry.geometry_hash:
        add("GEOMETRY_HASH_MISMATCH", "assignment is not bound to this geometry receipt")
    if assignment.string_count != len(assignment.strings):
        add("STRING_COUNT_MISMATCH", "declared string_count does not match string records")
    if assignment.string_count <= 0:
        add("INVALID_STRING_COUNT", "string_count must be positive")
    if assignment.modules_per_string <= 0:
        add("INVALID_MODULES_PER_STRING", "modules_per_string must be positive")

    string_ids = tuple(item.string_id for item in assignment.strings)
    if len(set(string_ids)) != len(string_ids):
        add("DUPLICATE_STRING_ID", "string identifiers must be unique")

    ordinals = tuple(item.ordinal for item in assignment.strings)
    if ordinals != tuple(range(len(assignment.strings))):
        add("NON_CONTIGUOUS_STRING_ORDINALS", "string ordinals must be contiguous and ordered")

    terminal_ids: list[str] = []
    assigned_module_ids: list[str] = []
    for string in assignment.strings:
        if len(string.ordered_module_ids) != assignment.modules_per_string:
            add(
                "STRING_MODULE_COUNT_MISMATCH",
                f"{string.string_id} does not contain modules_per_string members",
            )
        if string.order_basis != STRING_ORDER_BASIS:
            add(
                "UNSUPPORTED_ORDER_BASIS",
                f"{string.string_id} uses unsupported order basis {string.order_basis!r}",
            )

        positive = string.positive_free_terminal
        negative = string.negative_free_terminal
        if positive.string_id != string.string_id or positive.polarity != "positive":
            add(
                "INVALID_POSITIVE_FREE_TERMINAL",
                f"{string.string_id} positive free terminal is inconsistent",
            )
        if negative.string_id != string.string_id or negative.polarity != "negative":
            add(
                "INVALID_NEGATIVE_FREE_TERMINAL",
                f"{string.string_id} negative free terminal is inconsistent",
            )
        if positive.terminal_id == negative.terminal_id:
            add(
                "COLLAPSED_FREE_TERMINALS",
                f"{string.string_id} positive and negative free terminals share one identifier",
            )

        terminal_ids.extend((positive.terminal_id, negative.terminal_id))
        assigned_module_ids.extend(string.ordered_module_ids)

    if len(set(terminal_ids)) != len(terminal_ids):
        add("DUPLICATE_FREE_TERMINAL_ID", "free terminal identifiers must be globally unique")

    geometry_placements = tuple(sorted(geometry.placements, key=lambda item: item.ordinal))
    geometry_module_ids = tuple(item.module_id for item in geometry_placements)
    if len(geometry_module_ids) != geometry.module_count:
        add("GEOMETRY_PLACEMENT_COUNT_MISMATCH", "geometry placement count is inconsistent")
    if len(set(geometry_module_ids)) != len(geometry_module_ids):
        add("DUPLICATE_GEOMETRY_MODULE_ID", "geometry module identifiers must be unique")

    if len(assigned_module_ids) != geometry.module_count:
        add("ASSIGNED_MODULE_COUNT_MISMATCH", "assigned module count does not match geometry")
    if len(set(assigned_module_ids)) != len(assigned_module_ids):
        add("DUPLICATE_MODULE_ASSIGNMENT", "a module is assigned to more than one string position")

    assigned_set = set(assigned_module_ids)
    geometry_set = set(geometry_module_ids)
    missing = sorted(geometry_set - assigned_set)
    unexpected = sorted(assigned_set - geometry_set)
    if missing:
        add("OMITTED_MODULES", f"assignment omits {len(missing)} geometry modules")
    if unexpected:
        add("UNKNOWN_MODULES", f"assignment contains {len(unexpected)} unknown modules")

    if (
        all(string.order_basis == STRING_ORDER_BASIS for string in assignment.strings)
        and tuple(assigned_module_ids) != geometry_module_ids
    ):
        add(
            "PHYSICAL_ORDER_MISMATCH",
            "placement_ordinal membership does not preserve authoritative geometry order",
        )

    expected_total = assignment.string_count * assignment.modules_per_string
    if expected_total != geometry.module_count:
        add(
            "ASSIGNMENT_CAPACITY_MISMATCH",
            "string_count × modules_per_string does not equal geometry module_count",
        )

    immutable_issues = tuple(issues)
    return StringAssignmentValidationResult(
        table_id=assignment.table_id,
        valid=not immutable_issues,
        checked_string_count=len(assignment.strings),
        checked_module_count=len(assigned_module_ids),
        issues=immutable_issues,
    )

Calculation 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/calculation_receipts.py · lines 1–179 of 179 · Not reached from any entry point (candidate for review) · pattern resistance_registry_hash (shared by 2 files)

What it does
It calculates solar. Defines 8 functions or classes, including SegmentCalculationResult, OrderedCircuitCalculationReceipt, resistance_registry_hash, _evidence_payload, _segment_payload. Uses libraries __future__, dataclasses, 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 4 files: Solar Electrical Topology Analysis Engine Text Based — Solar Topology (solar-electrical-topology-analysis-engine-text-based); Circuit Calculations (solar-electrical-topology-analysis-engine-text-based); Kernel Authority (solar-electrical-topology-analysis-engine-text-based); Uncertainty (solar-electrical-topology-analysis-engine-text-based).
What it achieves
It is built from the segment calculation result class (`SegmentCalculationResult`), the ordered circuit calculation receipt class (`OrderedCircuitCalculationReceipt`) and the resistance registry hash helper (`resistance_registry_hash`). Immutable deterministic calculation receipts for validated V10 circuits.
Why it matters
Imported by 4 files, including Solar Electrical Topology Analysis Engine Text Based — Solar Topology, Circuit Calculations and Kernel Authority.
Application
solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
Uses
Circuit (relative import), Evidence (relative import), Resistance Evidence (relative import), __future__, dataclasses, hashlib, json
Used by
imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import), imported by Circuit Calculations (relative import), imported by Kernel Authority (relative import), imported by Uncertainty (relative import)
Produces
SegmentCalculationResult, OrderedCircuitCalculationReceipt, calculation_receipt_payload, calculation_receipt_json, calculation_receipt_hash
Defines here
SegmentCalculationResult, OrderedCircuitCalculationReceipt, resistance_registry_hash, _evidence_payload, _segment_payload, calculation_receipt_payload, calculation_receipt_json, calculation_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/calculation_receipts.py:1-179 · blob b92f9bbf8066ec4780c035bc49f907b07ae6e7fa · 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
"""Immutable deterministic calculation receipts for validated V10 circuits."""

from __future__ import annotations

from dataclasses import dataclass
import hashlib
import json

from .circuit import EvidenceClass
from .evidence import EvidenceDescriptor
from .resistance_evidence import (
    ResolvedConductorResistance,
    resistance_evidence_payload,
)


CALCULATION_RECEIPT_SCHEMA_VERSION = (
    "globalgrid2050.solar-dc.calculation-receipt.v10.2"
)
COMPLETE_CIRCUIT_METHOD_VERSION = (
    "globalgrid2050.solar-dc.complete-circuit-r-vdrop-loss.v10.3"
)


@dataclass(frozen=True)
class SegmentCalculationResult:
    segment_id: str
    segment_type: str
    conductor_product_id: str
    conductor_length_m: float
    r20_ohm_per_m: float
    resistance_evidence: ResolvedConductorResistance
    temperature_c: float
    conductor_resistance_ohm: float
    connector_count: int
    connector_resistance_ohm_each: float
    connector_resistance_ohm: float
    total_resistance_ohm: float
    voltage_drop_v: float
    resistive_loss_w: float
    source_evidence: EvidenceDescriptor
    result_evidence_class: EvidenceClass = EvidenceClass.DERIVED


@dataclass(frozen=True)
class OrderedCircuitCalculationReceipt:
    receipt_id: str
    circuit_model_id: str
    validated_circuit_hash: str
    traversal_schema_version: str
    ordered_terminal_ids: tuple[str, ...]
    ordered_connection_ids: tuple[str, ...]
    ordered_segment_ids: tuple[str, ...]
    current_a: float
    current_evidence: EvidenceDescriptor
    segment_results: tuple[SegmentCalculationResult, ...]
    total_conductor_length_m: float
    total_conductor_resistance_ohm: float
    total_connector_resistance_ohm: float
    total_resistance_ohm: float
    voltage_drop_v: float
    resistive_loss_w: float
    resistance_evidence_set_hash: str
    input_evidence_floor: EvidenceClass
    warnings: tuple[str, ...] = ()
    schema_version: str = CALCULATION_RECEIPT_SCHEMA_VERSION
    method_version: str = COMPLETE_CIRCUIT_METHOD_VERSION
    formula_ids: tuple[str, ...] = (
        "V10-R-000:R20=resolved_evidence_bound_product_property",
        "V10-R-001:Rconductor=R20*L*(1+alpha20*(T-20C))",
        "V10-R-002:Rcontacts=N*R20contact*(1+alpha20*(T-20C))",
        "V10-V-001:dV=I*R",
        "V10-P-001:Ploss=I^2*R",
    )

    @property
    def resistance_registry_hash(self) -> str:
        """Deprecated compatibility alias for pre-v10.3 callers."""

        return self.resistance_evidence_set_hash


def _evidence_payload(descriptor: EvidenceDescriptor) -> dict[str, object]:
    return {
        "schema_version": descriptor.schema_version,
        "evidence_class": str(descriptor.evidence_class),
        "verification_state": str(descriptor.verification_state),
        "source_reference": descriptor.source_reference,
        "source_vocabulary": descriptor.source_vocabulary,
        "source_value": descriptor.source_value,
    }


def _segment_payload(result: SegmentCalculationResult) -> dict[str, object]:
    return {
        "segment_id": result.segment_id,
        "segment_type": result.segment_type,
        "conductor_product_id": result.conductor_product_id,
        "conductor_length_m": result.conductor_length_m,
        "r20_ohm_per_m": result.r20_ohm_per_m,
        "resistance_evidence": resistance_evidence_payload(
            result.resistance_evidence
        ),
        "temperature_c": result.temperature_c,
        "conductor_resistance_ohm": result.conductor_resistance_ohm,
        "connector_count": result.connector_count,
        "connector_resistance_ohm_each": (
            result.connector_resistance_ohm_each
        ),
        "connector_resistance_ohm": result.connector_resistance_ohm,
        "total_resistance_ohm": result.total_resistance_ohm,
        "voltage_drop_v": result.voltage_drop_v,
        "resistive_loss_w": result.resistive_loss_w,
        "source_evidence": _evidence_payload(result.source_evidence),
        "result_evidence_class": str(result.result_evidence_class),
    }


def calculation_receipt_payload(
    receipt: OrderedCircuitCalculationReceipt,
) -> dict[str, object]:
    """Return deterministic machine-readable evidence without a timestamp."""

    return {
        "schema_version": receipt.schema_version,
        "method_version": receipt.method_version,
        "receipt_id": receipt.receipt_id,
        "circuit_model_id": receipt.circuit_model_id,
        "validated_circuit_hash": receipt.validated_circuit_hash,
        "traversal_schema_version": receipt.traversal_schema_version,
        "ordered_terminal_ids": list(receipt.ordered_terminal_ids),
        "ordered_connection_ids": list(receipt.ordered_connection_ids),
        "ordered_segment_ids": list(receipt.ordered_segment_ids),
        "current_a": receipt.current_a,
        "current_evidence": _evidence_payload(receipt.current_evidence),
        "resistance_evidence_set_hash": (
            receipt.resistance_evidence_set_hash
        ),
        "segment_results": [
            _segment_payload(result)
            for result in receipt.segment_results
        ],
        "totals": {
            "conductor_length_m": receipt.total_conductor_length_m,
            "conductor_resistance_ohm": (
                receipt.total_conductor_resistance_ohm
            ),
            "connector_resistance_ohm": (
                receipt.total_connector_resistance_ohm
            ),
            "resistance_ohm": receipt.total_resistance_ohm,
            "voltage_drop_v": receipt.voltage_drop_v,
            "resistive_loss_w": receipt.resistive_loss_w,
        },
        "input_evidence_floor": str(receipt.input_evidence_floor),
        "result_evidence_class": str(EvidenceClass.DERIVED),
        "formula_ids": list(receipt.formula_ids),
        "warnings": list(receipt.warnings),
    }


def calculation_receipt_json(
    receipt: OrderedCircuitCalculationReceipt,
) -> str:
    return json.dumps(
        calculation_receipt_payload(receipt),
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
    )


def calculation_receipt_hash(
    receipt: OrderedCircuitCalculationReceipt,
) -> str:
    digest = hashlib.sha256(
        calculation_receipt_json(receipt).encode("utf-8")
    ).hexdigest()
    return f"sha256:{digest}"

Cartridges

A Python module in Solar Electrical Topology Analysis Engine Text Based that builds segments (`build_segments`) and fleet segments (`build_fleet_segments`) and validates segment chains (`validate_segment_chains`) (units: Ω), using SHA-256.

transformsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/cartridges.py · lines 1–377 of 643 · Not reached from any entry point (candidate for review) · pattern manifest (shared by 9 files)

What it does
It calculates its inputs. Defines 28 functions or classes, including TopologyCartridge, feasibility, module_order, build_segments, manifest. Uses libraries __future__, abc, collections, 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.
Downstream impact
Used directly by 3 files: Solar Electrical Topology Analysis Engine Text Based — Solar Topology (solar-electrical-topology-analysis-engine-text-based); Circuit Adapters (solar-electrical-topology-analysis-engine-text-based); Fleet Store (solar-electrical-topology-analysis-engine-text-based).
What it achieves
It is built from the topology cartridge class (`TopologyCartridge`), the feasibility step (`feasibility`) and the module order helper (`module_order`). Topology cartridges that emit one shared ordered segment schema.
Why it matters
Imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology, Circuit Adapters and Fleet Store.
Application
solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
Uses
Segments (relative import), __future__, abc, collections, hashlib, json, typing
Used by
imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import), imported by Circuit Adapters (relative import), imported by Fleet Store (relative import)
Produces
TopologyCartridge, SequentialCartridge, LeapfrogCartridge, build_fleet_segments, validate_segment_chains, validate_cross_cartridge_invariants, math_isclose, segments_as_json
Defines here
TopologyCartridge, feasibility, module_order, build_segments, manifest, _point_at_module, _midpoint, _near_terminal, _far_terminal, _inverter_terminal, _build_module_chain, _append_positive_home_run, _append_negative_home_run, SequentialCartridge, feasibility, module_order, build_segments
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/cartridges.py:1-377 · blob 95c65d48be7b3b92361f537e839c8a60dc11f84c · 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
"""Topology cartridges that emit one shared ordered segment schema."""

from __future__ import annotations

from abc import ABC, abstractmethod
from collections import defaultdict
import hashlib
import json
from typing import Iterable, Iterator, Sequence

from .segments import (
    FeasibilityResult,
    Point3D,
    SegmentBuilder,
    SegmentRow,
    StringDefinition,
    TopologyInputs,
    canonical_input_hash,
    fleet_string_definitions,
)


FACTORY_GEOMETRY_WARNING = "FACTORY_LEAD_GEOMETRY_UNRESOLVED"
SEQUENTIAL_RETURN_WARNING = "SEQUENTIAL_RETURN_REQUIRES_LOOP_MODEL"


class TopologyCartridge(ABC):
    """A cartridge generates physical segments and no electrical totals."""

    name: str
    version: str

    @abstractmethod
    def feasibility(
        self,
        inputs: TopologyInputs,
    ) -> FeasibilityResult:
        """Return whether the physical topology passes its build screen."""

    @abstractmethod
    def module_order(
        self,
        module_count: int,
    ) -> tuple[int, ...]:
        """Return the electrical module order for one physical row."""

    @abstractmethod
    def build_segments(
        self,
        inputs: TopologyInputs,
        definition: StringDefinition,
    ) -> tuple[SegmentRow, ...]:
        """Build one complete positive-to-negative ordered segment chain."""

    def manifest(
        self,
        inputs: TopologyInputs,
        segments: Sequence[SegmentRow],
        source_commit: str = "unknown",
    ) -> dict:
        ordered = sorted(
            segments,
            key=lambda row: (
                row.inverter_id,
                row.string_id,
                row.segment_index,
            ),
        )
        warnings = sorted(
            {
                warning
                for row in ordered
                for warning in row.warnings.split(";")
                if warning
            }
        )
        cartridge_hash = hashlib.sha256(
            f"{self.name}:{self.version}".encode("utf-8")
        ).hexdigest()
        feasibility = self.feasibility(inputs)

        return {
            "schema_version": "topology_segments_v1",
            "cartridge_name": self.name,
            "cartridge_version": self.version,
            "method_version": "cartridge_segments_v1",
            "source_commit": source_commit,
            "input_hash": canonical_input_hash(inputs),
            "cartridge_hash": cartridge_hash,
            "segment_row_count": len(ordered),
            "distinct_string_count": len(
                {row.string_id for row in ordered}
            ),
            "first_segment_key": (
                ordered[0].segment_id if ordered else None
            ),
            "last_segment_key": (
                ordered[-1].segment_id if ordered else None
            ),
            "feasibility_status": feasibility.status,
            "saving_available": feasibility.feasible,
            "warning_count": len(warnings),
            "warnings": warnings,
            "data_law_result": "PENDING_PARQUET_AUDIT",
        }


def _point_at_module(
    definition: StringDefinition,
    inputs: TopologyInputs,
    module_index: int,
) -> Point3D:
    return Point3D(
        x=(
            definition.row_start_x_m
            + (module_index - 0.5) * inputs.module_pitch_m
        ),
        y=definition.row_y_m,
        z=0.0,
    )


def _midpoint(first: Point3D, second: Point3D) -> Point3D:
    return Point3D(
        x=(first.x + second.x) / 2,
        y=(first.y + second.y) / 2,
        z=(first.z + second.z) / 2,
    )


def _near_terminal(definition: StringDefinition) -> Point3D:
    return Point3D(
        definition.row_start_x_m,
        definition.row_y_m,
        0.0,
    )


def _far_terminal(definition: StringDefinition) -> Point3D:
    return Point3D(
        definition.row_end_x_m,
        definition.row_y_m,
        0.0,
    )


def _inverter_terminal(definition: StringDefinition) -> Point3D:
    return Point3D(
        definition.inverter_x_m,
        definition.inverter_y_m,
        0.0,
    )


def _build_module_chain(
    *,
    builder: SegmentBuilder,
    inputs: TopologyInputs,
    definition: StringDefinition,
    order: Sequence[int],
    first_terminal: Point3D,
    last_terminal: Point3D,
    turnaround_after_position: int | None = None,
) -> None:
    centres = {
        module_index: _point_at_module(
            definition,
            inputs,
            module_index,
        )
        for module_index in order
    }
    factory_warnings = (
        *builder.feasibility.warnings,
        FACTORY_GEOMETRY_WARNING,
    )
    previous_connector_node = "string:terminal:positive"
    previous_connector_point = first_terminal

    for position, module_index in enumerate(order, start=1):
        module_id = f"{definition.string_id}-M{module_index:02d}"
        centre = centres[module_index]

        if position == len(order):
            outgoing_point = last_terminal
        else:
            next_module = order[position]
            outgoing_point = _midpoint(
                centre,
                centres[next_module],
            )

        internal_node = f"{module_id}:internal"
        outgoing_node = (
            "string:terminal:negative"
            if position == len(order)
            else f"string:connector:{position}:a"
        )

        builder.append(
            segment_type="module_factory_positive_lead",
            polarity="series",
            from_node_id=previous_connector_node,
            to_node_id=internal_node,
            start=previous_connector_point,
            end=centre,
            conductor_length_m=inputs.positive_factory_lead_m,
            separation_mm=inputs.factory_pair_separation_mm,
            formation="single_pole",
            installation_class="under_module",
            conductor=inputs.factory_lead_conductor,
            temperature_c=inputs.factory_lead_temperature_c,
            effective_epsilon_r=inputs.effective_epsilon_r,
            loop_parameter_weight=0.0,
            module_id=module_id,
            provenance="oem_declared",
            source_reference="factory_lead_length_input",
            warnings=factory_warnings,
        )
        builder.append(
            segment_type="module_factory_negative_lead",
            polarity="series",
            from_node_id=internal_node,
            to_node_id=outgoing_node,
            start=centre,
            end=outgoing_point,
            conductor_length_m=inputs.negative_factory_lead_m,
            separation_mm=inputs.factory_pair_separation_mm,
            formation="single_pole",
            installation_class="under_module",
            conductor=inputs.factory_lead_conductor,
            temperature_c=inputs.factory_lead_temperature_c,
            effective_epsilon_r=inputs.effective_epsilon_r,
            loop_parameter_weight=0.0,
            module_id=module_id,
            provenance="oem_declared",
            source_reference="factory_lead_length_input",
            warnings=factory_warnings,
        )

        if position < len(order):
            next_connector_node = f"string:connector:{position}:b"
            segment_type = (
                "string_turnaround"
                if position == turnaround_after_position
                else "module_interconnect"
            )
            builder.append(
                segment_type=segment_type,
                polarity="series",
                from_node_id=outgoing_node,
                to_node_id=next_connector_node,
                start=outgoing_point,
                end=outgoing_point,
                conductor_length_m=0.0,
                separation_mm=inputs.factory_pair_separation_mm,
                formation="touching_pair",
                installation_class="under_module",
                conductor=inputs.factory_lead_conductor,
                temperature_c=inputs.factory_lead_temperature_c,
                effective_epsilon_r=inputs.effective_epsilon_r,
                loop_parameter_weight=0.0,
                connector_count=2,
                connector_resistance_ohm_each=(
                    inputs.connector_contact_ohm
                ),
                provenance="assumed",
                source_reference="module_connector_contact_model",
                warnings=factory_warnings,
            )
            previous_connector_node = next_connector_node
            previous_connector_point = outgoing_point


def _append_positive_home_run(
    builder: SegmentBuilder,
    inputs: TopologyInputs,
    definition: StringDefinition,
) -> None:
    builder.append(
        segment_type="external_positive_home_run",
        polarity="positive",
        from_node_id="inverter:positive",
        to_node_id="string:terminal:positive",
        start=_inverter_terminal(definition),
        end=_near_terminal(definition),
        conductor_length_m=definition.near_route_m,
        separation_mm=inputs.external_pair_separation_mm,
        formation="spaced_pair",
        installation_class="open_air",
        conductor=inputs.external_conductor,
        temperature_c=inputs.external_temperature_c,
        effective_epsilon_r=inputs.effective_epsilon_r,
        loop_parameter_weight=0.5,
        connector_count=2,
        connector_resistance_ohm_each=inputs.connector_contact_ohm,
        provenance="assumed",
        source_reference="geometry_derived_external_route",
        warnings=builder.feasibility.warnings,
    )


def _append_negative_home_run(
    builder: SegmentBuilder,
    inputs: TopologyInputs,
    definition: StringDefinition,
    from_node_id: str,
    start: Point3D,
) -> None:
    builder.append(
        segment_type="external_negative_home_run",
        polarity="negative",
        from_node_id=from_node_id,
        to_node_id="inverter:negative",
        start=start,
        end=_inverter_terminal(definition),
        conductor_length_m=definition.near_route_m,
        separation_mm=inputs.external_pair_separation_mm,
        formation="spaced_pair",
        installation_class="open_air",
        conductor=inputs.external_conductor,
        temperature_c=inputs.external_temperature_c,
        effective_epsilon_r=inputs.effective_epsilon_r,
        loop_parameter_weight=0.5,
        connector_count=2,
        connector_resistance_ohm_each=inputs.connector_contact_ohm,
        provenance="assumed",
        source_reference="geometry_derived_external_route",
        warnings=builder.feasibility.warnings,
    )


class SequentialCartridge(TopologyCartridge):
    name = "sequential"
    version = "1.1.0"

    def feasibility(
        self,
        inputs: TopologyInputs,
    ) -> FeasibilityResult:
        inputs.validate()
        return FeasibilityResult(
            status="FEASIBLE_BASE_TOPOLOGY",
            feasible=True,
            required_reach_m=0.0,
            available_reach_m=(
                inputs.positive_factory_lead_m
                + inputs.negative_factory_lead_m
            ),
            margin_m=0.0,
            extension_required_m=0.0,
            basis="SEQUENTIAL_BASELINE",
        )

    def module_order(
        self,
        module_count: int,
    ) -> tuple[int, ...]:
        if module_count < 1:
            raise ValueError("module_count must be positive")
        return tuple(range(1, module_count + 1))

    def build_segments(
        self,
        inputs: TopologyInputs,
        definition: StringDefinition,
    ) -> tuple[SegmentRow, ...]:
        feasibility = self.feasibility(inputs)
        builder = SegmentBuilder(
            run_id=canonical_input_hash(inputs),
            topology=self.name,
            cartridge_version=self.version,
            definition=definition,
            feasibility=feasibility,
        )
        near = _near_terminal(definition)
        far = _far_terminal(definition)