GLOBALGRID2050 / EXPLORE CODE

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

Diagnostics and 2 more files

A Python module in Solar Electrical Topology Analysis Engine Text Based that works with solar, using SHA-256.

639 lines of Python from solar-electrical-topology-analysis-engine-text-based, in 3 files. Topic: Solar and storage design. Section 223 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. Diagnostics transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/diagnostics.py lines 1–270
  2. DuckDB Segments storage · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/duckdb_segments.py lines 1–125
  3. Electrical Studies electrical · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/electrical_studies.py lines 1–244

Diagnostics

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

What it does
It calculates solar. Defines 22 functions or classes, including DiagnosticSeverity, DiagnosticCategory, StudyState, Diagnostic, __post_init__. 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 6 files: Solar Electrical Topology Analysis Engine Text Based — Solar Topology (solar-electrical-topology-analysis-engine-text-based); Diagnostic Adapters (solar-electrical-topology-analysis-engine-text-based); Diagnostic Bridges (solar-electrical-topology-analysis-engine-text-based); Electrical Studies (solar-electrical-topology-analysis-engine-text-based); and 2 more.
What it achieves
It builds diagnostic report (`build_diagnostic_report`) and is built from the diagnostic severity class (`DiagnosticSeverity`) and the diagnostic category class (`DiagnosticCategory`). Structured, deterministic diagnostics for V10 engineering studies.
Why it matters
Imported by 6 files, including Solar Electrical Topology Analysis Engine Text Based — Solar Topology, Diagnostic Adapters and Diagnostic Bridges.
Application
solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
Uses
__future__, dataclasses, enum, hashlib, json, typing
Used by
imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import), imported by Diagnostic Adapters (relative import), imported by Diagnostic Bridges (relative import), imported by Electrical Studies (relative import), imported by Study Applicability (relative import), imported by Study Registry (relative import)
Produces
DiagnosticSeverity, DiagnosticCategory, StudyState, Diagnostic, StudyCoverage, DiagnosticReport, build_diagnostic_report, diagnostic_payload, coverage_payload, diagnostic_report_payload, diagnostic_report_json, diagnostic_report_hash
Defines here
DiagnosticSeverity, DiagnosticCategory, StudyState, Diagnostic, __post_init__, blocking, StudyCoverage, __post_init__, DiagnosticReport, blocking, error_count, warning_count, _diagnostic_key, _coverage_key, build_diagnostic_report, diagnostic_payload, coverage_payload, diagnostic_report_payload, diagnostic_report_json, diagnostic_report_hash, require_non_blocking, diagnostic_from_exception
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/diagnostics.py:1-270 · blob 4440b55e118c1f1acfc4cf1f68d754e68f53cb4d · 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
"""Structured, deterministic diagnostics for V10 engineering studies.

Diagnostics distinguish failed checks from studies that were not performed. Public
payloads deliberately omit internal-only detail while preserving stable codes,
severity, subjects and remediation guidance.
"""

from __future__ import annotations

from dataclasses import dataclass
from enum import StrEnum
import hashlib
import json
from typing import Iterable


DIAGNOSTIC_SCHEMA_VERSION = "globalgrid2050.solar-dc.diagnostics.v10.1"


class DiagnosticSeverity(StrEnum):
    INFO = "info"
    WARNING = "warning"
    ERROR = "error"
    CRITICAL = "critical"


class DiagnosticCategory(StrEnum):
    INPUT = "input"
    TOPOLOGY = "topology"
    GEOMETRY = "geometry"
    ELECTRICAL = "electrical"
    EVIDENCE = "evidence"
    PUBLICATION = "publication"
    PERSISTENCE = "persistence"
    COVERAGE = "coverage"
    INTERNAL = "internal"


class StudyState(StrEnum):
    NOT_APPLICABLE = "not_applicable"
    NOT_CHECKED = "not_checked"
    BLOCKED = "blocked"
    CHECKED_PASS = "checked_pass"
    CHECKED_WARNING = "checked_warning"
    CHECKED_FAIL = "checked_fail"


@dataclass(frozen=True)
class Diagnostic:
    code: str
    severity: DiagnosticSeverity
    category: DiagnosticCategory
    message: str
    subject_id: str | None = None
    field: str | None = None
    observed_value: str | int | float | bool | None = None
    expected_constraint: str | None = None
    method_reference: str | None = None
    source_reference: str | None = None
    remediation: str | None = None
    public_detail: str | None = None
    internal_detail: str | None = None
    schema_version: str = DIAGNOSTIC_SCHEMA_VERSION

    def __post_init__(self) -> None:
        if not isinstance(self.code, str) or not self.code.strip():
            raise ValueError("diagnostic code must be non-empty text")
        if self.code != self.code.upper() or any(
            char not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-" for char in self.code
        ):
            raise ValueError("diagnostic code must use uppercase stable-code syntax")
        if not isinstance(self.severity, DiagnosticSeverity):
            raise TypeError("severity must be DiagnosticSeverity")
        if not isinstance(self.category, DiagnosticCategory):
            raise TypeError("category must be DiagnosticCategory")
        if not isinstance(self.message, str) or not self.message.strip():
            raise ValueError("diagnostic message must be non-empty text")

    @property
    def blocking(self) -> bool:
        return self.severity in {
            DiagnosticSeverity.ERROR,
            DiagnosticSeverity.CRITICAL,
        }


@dataclass(frozen=True)
class StudyCoverage:
    study_id: str
    state: StudyState
    subject_id: str | None = None
    method_reference: str | None = None
    evidence_source_ids: tuple[str, ...] = ()
    reason: str | None = None

    def __post_init__(self) -> None:
        if not isinstance(self.study_id, str) or not self.study_id.strip():
            raise ValueError("study_id must be non-empty text")
        if not isinstance(self.state, StudyState):
            raise TypeError("state must be StudyState")
        if tuple(sorted(set(self.evidence_source_ids))) != self.evidence_source_ids:
            raise ValueError("evidence_source_ids must be unique and sorted")
        if self.state in {StudyState.NOT_CHECKED, StudyState.BLOCKED} and not self.reason:
            raise ValueError("not-checked and blocked studies require a reason")


@dataclass(frozen=True)
class DiagnosticReport:
    report_id: str
    diagnostics: tuple[Diagnostic, ...]
    coverage: tuple[StudyCoverage, ...]
    schema_version: str = DIAGNOSTIC_SCHEMA_VERSION

    @property
    def blocking(self) -> bool:
        return any(item.blocking for item in self.diagnostics) or any(
            item.state in {StudyState.BLOCKED, StudyState.CHECKED_FAIL}
            for item in self.coverage
        )

    @property
    def error_count(self) -> int:
        return sum(item.blocking for item in self.diagnostics)

    @property
    def warning_count(self) -> int:
        return sum(
            item.severity is DiagnosticSeverity.WARNING for item in self.diagnostics
        )


def _diagnostic_key(item: Diagnostic) -> tuple[str, str, str, str]:
    return (
        item.code,
        item.subject_id or "",
        item.field or "",
        item.message,
    )


def _coverage_key(item: StudyCoverage) -> tuple[str, str]:
    return (item.study_id, item.subject_id or "")


def build_diagnostic_report(
    diagnostics: Iterable[Diagnostic] = (),
    coverage: Iterable[StudyCoverage] = (),
    *,
    report_id: str | None = None,
) -> DiagnosticReport:
    ordered_diagnostics = tuple(sorted(diagnostics, key=_diagnostic_key))
    ordered_coverage = tuple(sorted(coverage, key=_coverage_key))
    diagnostic_keys = [_diagnostic_key(item) for item in ordered_diagnostics]
    coverage_keys = [_coverage_key(item) for item in ordered_coverage]
    if len(diagnostic_keys) != len(set(diagnostic_keys)):
        raise ValueError("duplicate diagnostics are not permitted")
    if len(coverage_keys) != len(set(coverage_keys)):
        raise ValueError("duplicate study coverage entries are not permitted")
    payload = {
        "diagnostics": [diagnostic_payload(item, public=False) for item in ordered_diagnostics],
        "coverage": [coverage_payload(item) for item in ordered_coverage],
    }
    generated = "DIAG:" + hashlib.sha256(
        json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
    ).hexdigest()
    return DiagnosticReport(
        report_id=report_id or generated,
        diagnostics=ordered_diagnostics,
        coverage=ordered_coverage,
    )


def diagnostic_payload(item: Diagnostic, *, public: bool) -> dict[str, object]:
    payload: dict[str, object] = {
        "schema_version": item.schema_version,
        "code": item.code,
        "severity": item.severity.value,
        "category": item.category.value,
        "message": item.message,
        "subject_id": item.subject_id,
        "field": item.field,
        "observed_value": item.observed_value,
        "expected_constraint": item.expected_constraint,
        "method_reference": item.method_reference,
        "source_reference": item.source_reference,
        "remediation": item.remediation,
        "public_detail": item.public_detail,
    }
    if not public:
        payload["internal_detail"] = item.internal_detail
    return payload


def coverage_payload(item: StudyCoverage) -> dict[str, object]:
    return {
        "study_id": item.study_id,
        "state": item.state.value,
        "subject_id": item.subject_id,
        "method_reference": item.method_reference,
        "evidence_source_ids": list(item.evidence_source_ids),
        "reason": item.reason,
    }


def diagnostic_report_payload(
    report: DiagnosticReport,
    *,
    public: bool = False,
) -> dict[str, object]:
    return {
        "schema_version": report.schema_version,
        "report_id": report.report_id,
        "blocking": report.blocking,
        "error_count": report.error_count,
        "warning_count": report.warning_count,
        "diagnostics": [
            diagnostic_payload(item, public=public) for item in report.diagnostics
        ],
        "coverage": [coverage_payload(item) for item in report.coverage],
    }


def diagnostic_report_json(
    report: DiagnosticReport,
    *,
    public: bool = False,
) -> str:
    return json.dumps(
        diagnostic_report_payload(report, public=public),
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
    )


def diagnostic_report_hash(report: DiagnosticReport) -> str:
    digest = hashlib.sha256(
        diagnostic_report_json(report, public=False).encode("utf-8")
    ).hexdigest()
    return f"sha256:{digest}"


def require_non_blocking(report: DiagnosticReport) -> DiagnosticReport:
    if report.blocking:
        codes = ", ".join(item.code for item in report.diagnostics if item.blocking)
        raise ValueError(f"diagnostic report is blocking: {codes or 'study coverage failed'}")
    return report


def diagnostic_from_exception(
    error: Exception,
    *,
    code: str,
    category: DiagnosticCategory,
    subject_id: str | None = None,
    field: str | None = None,
    public_message: str | None = None,
) -> Diagnostic:
    """Convert a legacy exception without exposing its stack or internal detail."""

    return Diagnostic(
        code=code,
        severity=DiagnosticSeverity.ERROR,
        category=category,
        message=public_message or str(error) or error.__class__.__name__,
        subject_id=subject_id,
        field=field,
        public_detail=public_message,
        internal_detail=f"{error.__class__.__name__}: {error}",
    )

DuckDB Segments

A Python module in Solar Electrical Topology Analysis Engine Text Based that reads solar, using SHA-256. It creates segment table (`create_segment_table`), writes segment rows (`write_segment_rows`) and reads segment rows (`read_segment_rows`).

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

What it does
It loads solar. Defines 8 functions or classes, including _sql_type, create_segment_table, write_segment_rows, read_segment_rows, segment_rows_payload. Uses libraries __future__, dataclasses, hashlib, json, pathlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
Inputs & outputs
In: DuckDB queries.
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
Deterministic DuckDB persistence for canonical segment rows.
Why it matters
Imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology.
Application
solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
Uses
Segments (relative import), __future__, dataclasses, hashlib, json, pathlib, typing, duckdb
Used by
imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import)
Produces
create_segment_table, write_segment_rows, read_segment_rows, segment_rows_payload, segment_rows_hash, export_segment_parquet, read_segment_parquet
Defines here
_sql_type, create_segment_table, write_segment_rows, read_segment_rows, segment_rows_payload, segment_rows_hash, export_segment_parquet, read_segment_parquet
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/duckdb_segments.py:1-125 · blob 60776d593a49e54f069cf5ff6d3eba08066ed041 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Deterministic DuckDB persistence for canonical segment rows."""

from __future__ import annotations

from dataclasses import fields
import hashlib
import json
from pathlib import Path
from typing import Iterable

import duckdb

from .segments import SegmentRow


DUCKDB_SEGMENT_SCHEMA_VERSION = "globalgrid2050.solar-dc.duckdb-segments.v10.1"
_TABLE = "segment_rows"
_PRIMARY_KEY = ("run_id", "topology", "string_id", "segment_index")


def _sql_type(name: str) -> str:
    if name in {
        "band", "inverter_id", "mppt_id", "segment_index", "connector_count"
    }:
        return "BIGINT"
    if name in {"user_override", "saving_available"}:
        return "BOOLEAN"
    if name in {
        "from_x", "from_y", "from_z", "to_x", "to_y", "to_z",
        "displacement_m", "conductor_length_m", "separation_mm",
        "conductor_csa_mm2", "conductor_diameter_mm", "cable_od_mm",
        "r20_ohm_per_m", "temperature_c", "effective_epsilon_r",
        "loop_parameter_weight", "coil_turns", "coil_diameter_mm",
        "connector_resistance_ohm_each",
    }:
        return "DOUBLE"
    return "VARCHAR"


def create_segment_table(connection: duckdb.DuckDBPyConnection) -> None:
    columns = [f'"{field.name}" {_sql_type(field.name)}' for field in fields(SegmentRow)]
    primary = ", ".join(f'"{name}"' for name in _PRIMARY_KEY)
    connection.execute(
        f'CREATE TABLE IF NOT EXISTS {_TABLE} ({", ".join(columns)}, '
        f'PRIMARY KEY ({primary}))'
    )


def write_segment_rows(
    connection: duckdb.DuckDBPyConnection,
    rows: Iterable[SegmentRow],
) -> int:
    ordered = sorted(
        rows,
        key=lambda row: (row.run_id, row.topology, row.string_id, row.segment_index),
    )
    for row in ordered:
        row.validate()
    create_segment_table(connection)
    names = [field.name for field in fields(SegmentRow)]
    placeholders = ", ".join("?" for _ in names)
    quoted = ", ".join(f'"{name}"' for name in names)
    statement = f'INSERT INTO {_TABLE} ({quoted}) VALUES ({placeholders})'
    connection.executemany(
        statement,
        [[getattr(row, name) for name in names] for row in ordered],
    )
    return len(ordered)


def read_segment_rows(connection: duckdb.DuckDBPyConnection) -> tuple[SegmentRow, ...]:
    names = [field.name for field in fields(SegmentRow)]
    quoted = ", ".join(f'"{name}"' for name in names)
    result = connection.execute(
        f'SELECT {quoted} FROM {_TABLE} '
        'ORDER BY run_id, topology, string_id, segment_index'
    ).fetchall()
    rows = tuple(SegmentRow(**dict(zip(names, values, strict=True))) for values in result)
    for row in rows:
        row.validate()
    return rows


def segment_rows_payload(rows: Iterable[SegmentRow]) -> dict[str, object]:
    ordered = sorted(
        rows,
        key=lambda row: (row.run_id, row.topology, row.string_id, row.segment_index),
    )
    return {
        "schema_version": DUCKDB_SEGMENT_SCHEMA_VERSION,
        "rows": [row.as_dict() for row in ordered],
    }


def segment_rows_hash(rows: Iterable[SegmentRow]) -> str:
    encoded = json.dumps(
        segment_rows_payload(rows), sort_keys=True, separators=(",", ":")
    ).encode("utf-8")
    return f"sha256:{hashlib.sha256(encoded).hexdigest()}"


def export_segment_parquet(
    connection: duckdb.DuckDBPyConnection,
    destination: str | Path,
) -> Path:
    path = Path(destination)
    path.parent.mkdir(parents=True, exist_ok=True)
    escaped = str(path).replace("'", "''")
    connection.execute(
        f"COPY (SELECT * FROM {_TABLE} ORDER BY run_id, topology, string_id, "
        f"segment_index) TO '{escaped}' (FORMAT PARQUET, COMPRESSION ZSTD)"
    )
    return path


def read_segment_parquet(path: str | Path) -> tuple[SegmentRow, ...]:
    connection = duckdb.connect(":memory:")
    try:
        escaped = str(Path(path)).replace("'", "''")
        connection.execute(
            f"CREATE TABLE {_TABLE} AS SELECT * FROM read_parquet('{escaped}')"
        )
        return read_segment_rows(connection)
    finally:
        connection.close()

Electrical Studies

A Python module in Solar Electrical Topology Analysis Engine Text Based that works with solar, using SHA-256.

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

What it does
It calculates solar. Defines 8 functions or classes, including ElectricalStudyReceipt, __post_init__, _criterion_diagnostics, calculate_cold_voc_study, evaluate_numeric_study. Uses libraries __future__, dataclasses, hashlib, json, math.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
What it achieves
It calculates cold voc study (`calculate_cold_voc_study`) and is built from the electrical study receipt class (`ElectricalStudyReceipt`) and the evaluate numeric study helper (`evaluate_numeric_study`). Evidence-controlled electrical study receipts for V10.
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
Diagnostics (relative import), Formulas (relative import), Study Applicability (relative import), __future__, dataclasses, hashlib, json, math
Used by
none found
Produces
ElectricalStudyReceipt, calculate_cold_voc_study, evaluate_numeric_study, electrical_study_payload, electrical_study_json, electrical_study_hash
Defines here
ElectricalStudyReceipt, __post_init__, _criterion_diagnostics, calculate_cold_voc_study, evaluate_numeric_study, electrical_study_payload, electrical_study_json, electrical_study_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/electrical_studies.py:1-244 · blob fb1f4c850a39a16d6053910022472c7d1927b0c8 · 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-controlled electrical study receipts for V10.

The module calculates quantities from declared inputs and only creates an acceptance
verdict when an explicit, unit-matched criterion is supplied.
"""

from __future__ import annotations

from dataclasses import dataclass
import hashlib
import json
import math

from .diagnostics import (
    Diagnostic,
    DiagnosticCategory,
    DiagnosticReport,
    DiagnosticSeverity,
    StudyCoverage,
    StudyState,
    build_diagnostic_report,
)
from .formulas import cold_string_voc
from .study_applicability import AcceptanceCriterion, StudyKind, evaluate_criterion

ELECTRICAL_STUDY_SCHEMA_VERSION = "globalgrid2050.solar-dc.electrical-study.v10.1"


@dataclass(frozen=True)
class ElectricalStudyReceipt:
    study_id: str
    subject_id: str
    value: float
    unit: str
    input_values: tuple[tuple[str, float], ...]
    input_source_ids: tuple[str, ...]
    method_reference: str
    criterion: AcceptanceCriterion | None
    passed: bool | None
    diagnostic_report: DiagnosticReport
    schema_version: str = ELECTRICAL_STUDY_SCHEMA_VERSION

    def __post_init__(self) -> None:
        if not self.study_id or not self.subject_id or not self.unit:
            raise ValueError("study_id, subject_id and unit are required")
        if not math.isfinite(self.value):
            raise ValueError("study value must be finite")
        keys = [key for key, _ in self.input_values]
        if keys != sorted(keys) or len(keys) != len(set(keys)):
            raise ValueError("input_values must use unique sorted keys")
        if tuple(sorted(set(self.input_source_ids))) != self.input_source_ids:
            raise ValueError("input_source_ids must be unique and sorted")
        if self.criterion is None and self.passed is not None:
            raise ValueError("passed must be null when no criterion is supplied")


def _criterion_diagnostics(
    *,
    study_id: str,
    subject_id: str,
    value: float,
    unit: str,
    criterion: AcceptanceCriterion | None,
) -> tuple[bool | None, DiagnosticReport]:
    if criterion is None:
        return None, build_diagnostic_report(
            (),
            (
                StudyCoverage(
                    study_id=study_id,
                    state=StudyState.CHECKED_WARNING,
                    subject_id=subject_id,
                    reason=(
                        "quantity calculated but no acceptance criterion was supplied; "
                        "no compliance verdict is made"
                    ),
                ),
            ),
        )
    passed = evaluate_criterion(value, unit, criterion)
    if passed:
        diagnostics = ()
        state = StudyState.CHECKED_PASS
    else:
        diagnostics = (
            Diagnostic(
                code=f"ELECTRICAL.{study_id.upper().replace('-', '_')}.LIMIT",
                severity=DiagnosticSeverity.ERROR,
                category=DiagnosticCategory.ELECTRICAL,
                message=f"{study_id} result does not satisfy the declared criterion",
                subject_id=subject_id,
                observed_value=value,
                expected_constraint=(
                    f"{criterion.operator.value} {criterion.threshold} {criterion.unit}"
                ),
                method_reference=criterion.method_reference,
                source_reference=criterion.source_id,
                remediation="review design inputs, topology and the sourced acceptance basis",
            ),
        )
        state = StudyState.CHECKED_FAIL
    return passed, build_diagnostic_report(
        diagnostics,
        (
            StudyCoverage(
                study_id=study_id,
                state=state,
                subject_id=subject_id,
                method_reference=criterion.method_reference,
                evidence_source_ids=(criterion.source_id,),
            ),
        ),
    )


def calculate_cold_voc_study(
    *,
    subject_id: str,
    module_voc_v: float,
    modules_per_string: int,
    beta_voc_percent_per_k: float,
    cold_cell_temperature_c: float,
    input_source_ids: tuple[str, ...],
    criterion: AcceptanceCriterion | None = None,
) -> ElectricalStudyReceipt:
    if criterion is not None and criterion.study_kind is not StudyKind.COLD_VOC:
        raise ValueError("criterion must be for cold Voc")
    value = cold_string_voc(
        module_voc_v,
        modules_per_string,
        beta_voc_percent_per_k,
        cold_cell_temperature_c,
    )
    passed, report = _criterion_diagnostics(
        study_id="cold-voc-limit",
        subject_id=subject_id,
        value=value,
        unit="V",
        criterion=criterion,
    )
    return ElectricalStudyReceipt(
        study_id="cold-voc-limit",
        subject_id=subject_id,
        value=value,
        unit="V",
        input_values=tuple(
            sorted(
                (
                    ("beta_voc_percent_per_k", float(beta_voc_percent_per_k)),
                    ("cold_cell_temperature_c", float(cold_cell_temperature_c)),
                    ("module_voc_v", float(module_voc_v)),
                    ("modules_per_string", float(modules_per_string)),
                )
            )
        ),
        input_source_ids=tuple(sorted(set(input_source_ids))),
        method_reference="globalgrid2050.solar-dc.cold-voc.v10.1",
        criterion=criterion,
        passed=passed,
        diagnostic_report=report,
    )


def evaluate_numeric_study(
    *,
    study_id: str,
    study_kind: StudyKind,
    subject_id: str,
    value: float,
    unit: str,
    input_values: tuple[tuple[str, float], ...],
    input_source_ids: tuple[str, ...],
    method_reference: str,
    criterion: AcceptanceCriterion | None = None,
) -> ElectricalStudyReceipt:
    if criterion is not None and criterion.study_kind is not study_kind:
        raise ValueError("criterion study kind does not match study")
    if not math.isfinite(value):
        raise ValueError("study value must be finite")
    passed, report = _criterion_diagnostics(
        study_id=study_id,
        subject_id=subject_id,
        value=float(value),
        unit=unit,
        criterion=criterion,
    )
    return ElectricalStudyReceipt(
        study_id=study_id,
        subject_id=subject_id,
        value=float(value),
        unit=unit,
        input_values=input_values,
        input_source_ids=tuple(sorted(set(input_source_ids))),
        method_reference=method_reference,
        criterion=criterion,
        passed=passed,
        diagnostic_report=report,
    )


def electrical_study_payload(receipt: ElectricalStudyReceipt) -> dict[str, object]:
    criterion = receipt.criterion
    return {
        "schema_version": receipt.schema_version,
        "study_id": receipt.study_id,
        "subject_id": receipt.subject_id,
        "value": receipt.value,
        "unit": receipt.unit,
        "input_values": {key: value for key, value in receipt.input_values},
        "input_source_ids": list(receipt.input_source_ids),
        "method_reference": receipt.method_reference,
        "criterion": (
            None
            if criterion is None
            else {
                "criterion_id": criterion.criterion_id,
                "study_kind": criterion.study_kind.value,
                "operator": criterion.operator.value,
                "threshold": criterion.threshold,
                "unit": criterion.unit,
                "source_id": criterion.source_id,
                "method_reference": criterion.method_reference,
                "public_support": criterion.public_support,
            }
        ),
        "passed": receipt.passed,
        "diagnostic_report_id": receipt.diagnostic_report.report_id,
    }


def electrical_study_json(receipt: ElectricalStudyReceipt) -> str:
    return json.dumps(
        electrical_study_payload(receipt),
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
    )


def electrical_study_hash(receipt: ElectricalStudyReceipt) -> str:
    digest = hashlib.sha256(
        electrical_study_json(receipt).encode("utf-8")
    ).hexdigest()
    return f"sha256:{digest}"