File size: 11,120 Bytes
23883dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env python3
"""Validate all generated SnD Floaters cases using only the Python standard library."""

from __future__ import annotations

import json
import math
import sys
from collections import defaultdict
from datetime import datetime
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
TOLERANCE = 0.001001


class ValidationFailure(Exception):
    pass


def fail(case_id: str, message: str) -> None:
    raise ValidationFailure(f"{case_id}: {message}")


def load_json(path: Path) -> Any:
    return json.loads(path.read_text(encoding="utf-8"))


def parse_time(value: str) -> datetime:
    return datetime.fromisoformat(value.replace("Z", "+00:00"))


def close(left: float, right: float) -> bool:
    return math.isclose(left, right, abs_tol=TOLERANCE, rel_tol=0.0)


def collect_bases(value: Any) -> list[dict[str, Any]]:
    result: list[dict[str, Any]] = []
    if isinstance(value, dict):
        if {"kind", "evidence_ids", "rule_ids", "assumption_id"}.issubset(value):
            result.append(value)
        for nested in value.values():
            result.extend(collect_bases(nested))
    elif isinstance(value, list):
        for nested in value:
            result.extend(collect_bases(nested))
    return result


def profile_map(legs: list[dict[str, Any]], answer_format: bool) -> dict[str, float]:
    result: defaultdict[str, float] = defaultdict(float)
    for leg in legs:
        if not leg["included_in_scope"]:
            continue
        profile = leg["sendout_profile"]
        points = profile["points"] if answer_format else profile
        for point in points:
            result[point["gas_day"]] += float(point["gwh"])
    return dict(result)


def expected_lng_delta(case_input: dict[str, Any], answer: dict[str, Any]) -> dict[str, float]:
    prior_by_id = {cargo["cargo_id"]: cargo for cargo in case_input["prior_cargo_book"]}
    result: defaultdict[str, float] = defaultdict(float)
    matched: set[str] = set()
    for update in answer["cargo_updates"]:
        prior_id = update["matched_prior_cargo_id"]
        if prior_id is not None:
            if prior_id not in prior_by_id:
                fail(case_input["case_id"], f"unknown matched prior cargo {prior_id}")
            if prior_id in matched:
                fail(case_input["case_id"], f"prior cargo {prior_id} matched more than once")
            matched.add(prior_id)
            for day, amount in profile_map(prior_by_id[prior_id]["discharge_legs"], False).items():
                result[day] -= amount
        for day, amount in profile_map(update["discharge_legs"], True).items():
            result[day] += amount
    return dict(result)


def validate_estimate(case_id: str, estimate: dict[str, Any], label: str) -> None:
    lower = estimate["lower"]
    central = estimate["central"]
    upper = estimate["upper"]
    values = [lower, central, upper]
    if all(value is None for value in values):
        return
    if any(value is None for value in values):
        fail(case_id, f"{label} must have either three numeric values or three null values")
    if not lower <= central <= upper:
        fail(case_id, f"{label} does not satisfy lower <= central <= upper")


def validate_case(case_path: Path, answer_path: Path) -> None:
    case_input = load_json(case_path)
    answer = load_json(answer_path)
    case_id = case_input["case_id"]

    if answer["case_id"] != case_id:
        fail(case_id, "answer case_id does not match input")
    if answer["as_of"] != case_input["as_of"]:
        fail(case_id, "answer as_of does not match input")
    if answer["unit"] != "GWh":
        fail(case_id, "answer unit must be GWh")

    as_of = parse_time(case_input["as_of"])
    observations = {item["observation_id"]: item for item in case_input["observations"]}
    rule_ids = {item["rule_id"] for item in case_input["rules"]}
    known_evidence = set(observations)
    known_evidence.update(item["cargo_id"] for item in case_input["prior_cargo_book"])
    known_evidence.update(item["record_id"] for item in case_input["prior_balance"])
    for section in ("capacity_schedule", "unit_conversions"):
        for item in case_input["reference_data"].get(section, []):
            if "record_id" in item:
                known_evidence.add(item["record_id"])

    for update in answer["cargo_updates"]:
        for observation_id in update["source_observation_ids"]:
            if observation_id not in observations:
                fail(case_id, f"unknown source observation {observation_id}")
            observation = observations[observation_id]
            if parse_time(observation["received_at"]) > as_of:
                fail(case_id, f"post-cutoff observation {observation_id} used in cargo update")
            if observation["retracted"]:
                fail(case_id, f"retracted observation {observation_id} used in cargo update")

        validate_estimate(case_id, update["quantity_gwh"], f"{update['update_id']} quantity")
        quantity = update["quantity_gwh"]["central"]
        fraction_sum = 0.0
        for leg in update["discharge_legs"]:
            validate_estimate(case_id, leg["discharge_fraction"], f"{leg['leg_id']} fraction")
            fraction = leg["discharge_fraction"]["central"]
            if fraction is None:
                continue
            fraction_sum += fraction
            if quantity is not None:
                allocated = sum(float(point["gwh"]) for point in leg["sendout_profile"]["points"])
                allocated += float(leg["sendout_profile"]["unallocated_gwh"])
                expected = quantity * fraction
                if not close(allocated, expected):
                    fail(
                        case_id,
                        f"{leg['leg_id']} allocates {allocated} GWh but should allocate {expected} GWh",
                    )
        if quantity is not None and update["action"]["value"] != "unresolved":
            if not close(fraction_sum, 1.0):
                fail(case_id, f"{update['update_id']} discharge fractions sum to {fraction_sum}")

    for item_basis in collect_bases(answer):
        kind = item_basis["kind"]
        evidence_ids = item_basis["evidence_ids"]
        unknown_ids = set(evidence_ids) - known_evidence
        if unknown_ids:
            fail(case_id, f"basis cites unknown evidence IDs {sorted(unknown_ids)}")
        if kind == "observed":
            if not evidence_ids or item_basis["rule_ids"]:
                fail(case_id, "observed basis must cite evidence and must not cite a rule")
        elif kind in {"inferred", "calculated", "unknown"}:
            if not evidence_ids:
                fail(case_id, f"{kind} basis must cite evidence")
            if not item_basis["rule_ids"]:
                fail(case_id, f"{kind} basis must cite at least one rule")
            missing_rules = set(item_basis["rule_ids"]) - rule_ids
            if missing_rules:
                fail(case_id, f"{kind} basis cites missing rules {sorted(missing_rules)}")
        elif kind == "assumed":
            if not item_basis["assumption_id"]:
                fail(case_id, "assumed basis must cite an assumption_id")
        else:
            fail(case_id, f"invalid basis kind {kind}")

    prior_rows = {
        (row["gas_day"], row["component_id"]): row for row in case_input["prior_balance"]
    }
    input_days = case_input["scope"]["balance_gas_days"]
    for day in input_days:
        prior_residual = sum(
            row["contribution_gwh"] for row in case_input["prior_balance"] if row["gas_day"] == day
        )
        if not close(prior_residual, 0.0):
            fail(case_id, f"prior balance on {day} has residual {prior_residual}")

    derived_lng_delta = expected_lng_delta(case_input, answer)
    answer_days = [row["gas_day"] for row in answer["daily_balance"]]
    if answer_days != input_days:
        fail(case_id, f"answer gas days {answer_days} do not match input {input_days}")

    for day in answer["daily_balance"]:
        gas_day = day["gas_day"]
        components = {row["component_id"]: row for row in day["components"]}
        if len(components) != len(day["components"]):
            fail(case_id, f"duplicate component on {gas_day}")
        if set(components) != {
            "domestic_production",
            "pipeline_imports",
            "lng_sendout",
            "demand",
            "exports",
            "storage_net",
        }:
            fail(case_id, f"wrong component set on {gas_day}")

        expected_delta = round(derived_lng_delta.get(gas_day, 0.0), 3)
        if not close(components["lng_sendout"]["delta_contribution_gwh"], expected_delta):
            fail(case_id, f"LNG delta on {gas_day} is not the cargo-profile difference")
        if not close(components["storage_net"]["delta_contribution_gwh"], -expected_delta):
            fail(case_id, f"storage delta on {gas_day} does not offset LNG")

        for component_id, row in components.items():
            prior = prior_rows[(gas_day, component_id)]["contribution_gwh"]
            if not close(row["prior_contribution_gwh"], prior):
                fail(case_id, f"wrong prior {component_id} value on {gas_day}")
            if not close(
                row["prior_contribution_gwh"] + row["delta_contribution_gwh"],
                row["updated_contribution_gwh"],
            ):
                fail(case_id, f"component arithmetic fails for {component_id} on {gas_day}")
            if component_id not in {"lng_sendout", "storage_net"} and not close(
                row["delta_contribution_gwh"], 0.0
            ):
                fail(case_id, f"unexpected non-LNG change to {component_id} on {gas_day}")

        residual = sum(row["updated_contribution_gwh"] for row in components.values())
        if not close(residual, day["residual_gwh"]):
            fail(case_id, f"reported residual is wrong on {gas_day}")
        if not close(residual, 0.0):
            fail(case_id, f"updated balance on {gas_day} has residual {residual}")

    allowed_check_values = {"pass", "fail", "not_applicable"}
    if set(answer["quality_checks"].values()) - allowed_check_values:
        fail(case_id, "quality_checks contains an invalid status")
    if answer["assumptions"]:
        fail(case_id, "starter answer keys should contain no unsupported assumptions")


def main() -> int:
    manifest = load_json(ROOT / "manifest.json")
    failures: list[str] = []
    for entry in manifest["cases"]:
        try:
            validate_case(ROOT / entry["input_path"], ROOT / entry["answer_path"])
            print(f"PASS {entry['case_id']}: {entry['title']}")
        except (ValidationFailure, KeyError, TypeError, ValueError) as error:
            failures.append(str(error))
            print(f"FAIL {entry['case_id']}: {error}")
    print()
    if failures:
        print(f"{len(failures)} of {manifest['case_count']} cases failed validation")
        return 1
    print(f"All {manifest['case_count']} cases passed deterministic validation")
    return 0


if __name__ == "__main__":
    sys.exit(main())