In this section
- GlobalGrid2050 Test News Binder Refaware test · globalgrid2050 / scripts/test_news_binder_refaware.py lines 1–226
- GlobalGrid2050 Test News Binder V9 5 test · globalgrid2050 / scripts/test_news_binder_v9_5.py lines 1–116
- GlobalGrid2050 Test News Feed V9 5 1 test · globalgrid2050 / scripts/test_news_feed_v9_5_1.py lines 1–65
- GlobalGrid2050 Test V6 Price History Accuracy test · globalgrid2050 / scripts/test_v6_price_history_accuracy.py lines 1–177
GlobalGrid2050 Test News Binder Refaware
A test in the scripts folder that checks GlobalGrid2050 Major Project News V6 and GlobalGrid2050 News Binder Refaware, using SHA-256.
testglobalgrid2050 / scripts/test_news_binder_refaware.py · lines 1–226 of 226 · Entry point · pattern story (shared by 6 files)
- What it does
- It tests solar and battery storage (BESS). Defines 18 functions or classes, including story, sha, resolve, test_operator_parties, test_capacity_extraction. Uses libraries __future__, hashlib, json, re, sys. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, battery storage (BESS).
- Inputs & outputs
- In: JSON file news_binding_labels_2026q3.json; JSON file major_projects_v6.json; JSON file major_projects_2026q3.json; JSON file major_project_news_v9_5_1.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- It is built from the story step (`story`), the sha step (`sha`) and the resolve step (`resolve`). Offline tests for `scripts/news_binder_refaware.py` and `scripts/build_news_feed_2026q3.py`. Its code works with 1 GWh, 100 MWh and 107 MW.
- Why it matters
- Run by GlobalGrid2050 Project Signals Acid Workflow.
- Application
- globalgrid2050 · scripts · test
- Uses
- GlobalGrid2050 Major Project News V6 (import), GlobalGrid2050 News Binder Refaware (import), GlobalGrid2050 Build News Feed 2026q3 (import), __future__, hashlib, json, re, sys, tempfile, datetime, pathlib
- Used by
- run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
- Produces
- story, sha, resolve, test_operator_parties, test_capacity_extraction, test_c1_capacity_contradiction_blocks_camblesforth, test_c2_qualifier_coalburn_ii, test_c3_full_exact_name_not_downgraded_by_shared_stem, test_c4_multi_token_stem_adjacent_descriptor, test_c6_operator_route_and_vetoes, test_c7_stale_records, test_c8_ref_aware
- Defines here
- story, sha, resolve, test_operator_parties, test_capacity_extraction, test_c1_capacity_contradiction_blocks_camblesforth, test_c2_qualifier_coalburn_ii, test_c3_full_exact_name_not_downgraded_by_shared_stem, test_c4_multi_token_stem_adjacent_descriptor, test_c6_operator_route_and_vetoes, test_c7_stale_records, test_c8_ref_aware, test_west_burton_c_is_fidra_11928, test_v9_5_fixtures_on_both_universes, test_status_change_candidates_synthetic, evaluate, test_labelled_precision_recall, test_feed_builder_is_additive_and_deterministic
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/test_news_binder_refaware.py:1-226 · blob 2c196507132b864fcb7523f53ab550e6490a099e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Offline tests for scripts/news_binder_refaware.py and scripts/build_news_feed_2026q3.py.
Run: python3 scripts/test_news_binder_refaware.py (or pytest scripts/test_news_binder_refaware.py)
Needs only committed files: dist/major_projects_v6.json, dist/major_projects_2026q3.json,
dist/major_project_news_v4/v5/v6/v9_5_1.json, docs/repd/2026q3/changes-jul-to-oct/diff.json and
scripts/fixtures/news_binding_labels_2026q3.json. No network. Writes nothing in the repository.
"""
from __future__ import annotations
import hashlib
import json
import re
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import major_project_news_v6 as base # noqa: E402
import news_binder_refaware as nb # noqa: E402
import build_news_feed_2026q3 as feed # noqa: E402
LABELS = ROOT / "scripts" / "fixtures" / "news_binding_labels_2026q3.json"
Q2 = ROOT / "dist" / "major_projects_v6.json"
Q3 = ROOT / "dist" / "major_projects_2026q3.json"
CRAWL_INSTANT = "2026-08-22T20:45:25.507638+00:00"
def story(title, source="Example News", url="https://example.com", published=None):
return {"title": title, "description": "", "source": source, "source_url": url, "link": "https://example.test/x",
"published": published or datetime(2026, 8, 1, tzinfo=timezone.utc)}
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
base.pin_scoring_reference(CRAWL_INSTANT)
_, Q3P = nb.load_universe(Q3)
Q3BY = {p["repd_ref"]: p for p in Q3P}
def resolve(title, **kw):
item, reason, _ = nb.resolve_story(story(title, **kw), Q3P, Q3BY)
return (item["repd_ref"] if item else None), reason
# ---- unit rules -----------------------------------------------------------
def test_operator_parties():
assert nb.normalise_operator_parties("Fidra Energy & Drax") == ["fidra", "drax"]
assert nb.normalise_operator_parties("JBM Solar & RWE") == ["jbm", "rwe"]
assert nb.normalise_operator_parties("Innagreen Investments & RES") == ["innagreen", "res"]
assert nb.normalise_operator_parties("Photovolt Development Partners / SolarFive") == \
nb.normalise_operator_parties("Photovolt Development Partners & SolarFive")
assert nb.operator_party_key("Low Carbon Limited") == nb.operator_party_key("Low Carbon Ltd")
def test_capacity_extraction():
assert nb.extract_capacities("Government approves new 1,900MW Camblesforth solar farm") == [1900.0]
assert nb.extract_capacities("46.5MW Brecks") == [46.5]
assert nb.extract_capacities("49.9MWp Staffordshire") == [49.9]
assert nb.extract_capacities("1GWh Coalburn 1 battery") == []
def test_c1_capacity_contradiction_blocks_camblesforth():
assert resolve("Government approves new 1,900MW Camblesforth solar farm")[0] is None
assert resolve("Government approves new 49.9MW Camblesforth solar farm")[0] == "8100"
def test_c2_qualifier_coalburn_ii():
ref, _ = resolve("Meadow Partners Acquires Ground Lease for Coalburn II Battery Storage Project in Scotland")
assert ref == "12206", ref
assert resolve("1GWh Coalburn 1 battery energy storage enters operations in Scotland")[0] == "11034"
def test_c3_full_exact_name_not_downgraded_by_shared_stem():
assert resolve("Greencells signs 71 MW Carlton solar farm EPC deal",
source="Solar Power Portal", url="https://www.solarpowerportal.co.uk")[0] == "12017"
def test_c4_multi_token_stem_adjacent_descriptor():
assert resolve("Monk Fryston BESS Set to Become One of the UK's Largest Battery Storage Assets")[0] == "15164"
assert resolve("More than 1,000 people have say on Green Hill Solar Farm", source="BBC",
url="https://www.bbc.co.uk")[0] == "15793"
def test_c6_operator_route_and_vetoes():
assert resolve("Lightsource bp secures planning approval at 57MW solar-plus-storage project in Wales",
source="Solar Power Portal", url="https://www.solarpowerportal.co.uk")[0] == "7858"
# portfolio wording and capacity contradiction keep unnamed stories unbound
assert resolve("NextEnergy UK I Acquires 107 MW Battery Storage Portfolio in the UK")[0] is None
assert resolve("Harmony Energy energises new 35MW/70MWh BESS in North Yorkshire")[0] is None
assert resolve("Eelpower Energy acquires 50MW/100MWh BESS project in Devon")[0] is None
def test_c7_stale_records():
assert resolve("Solar farm plan for North Tawton field", published=datetime(2026, 8, 21, tzinfo=timezone.utc))[1] \
in {"stale_record_candidate", "no_canonical_identity"}
assert resolve("Solar farm plan for North Tawton field")[0] is None
# full exact name still binds a stale-status site, flagged in evidence
item, _, _ = nb.resolve_story(story("Work on solar farm at former Williamthorpe Colliery site starts"), Q3P, Q3BY)
assert item and item["repd_ref"] == "5533" and item["match_evidence"]["stale_record"] is True
def test_c8_ref_aware():
assert resolve("Update on REPD ref 13599 solar scheme")[0] == "13599"
item, _, _ = nb.resolve_story(story("Kells solar farm refusal of planning appealed", source="BBC",
url="https://www.bbc.co.uk"), Q3P, Q3BY)
assert item["repd_ref"] == "6012" and item["match_evidence"]["superseded_repd_ref"] == "5967"
def test_west_burton_c_is_fidra_11928():
assert resolve("Fidra Energy reaches financial close on 500 MW West Burton C BESS project")[0] == "11928"
# the V9.5 hostile fixture (no operator, no corroboration) still does not bind
assert resolve("West Burton C BESS project reaches financial close", source="Energy-Storage.News",
url="https://energy-storage.news")[0] is None
def test_v9_5_fixtures_on_both_universes():
src = (ROOT / "scripts" / "test_news_binder_v9_5.py").read_text(encoding="utf-8")
positives = eval(re.search(r"positives = (\(.*?\n\))\n", src, re.S).group(1)) # noqa: S307 (own repo file)
negatives = eval(re.search(r"negatives = (\(.*?\n\))\n", src, re.S).group(1)) # noqa: S307
for path in (Q2, Q3):
_, projects = nb.load_universe(path)
by_ref = {p["repd_ref"]: p for p in projects}
hits = 0
for title, source, url, expected in positives:
item, _, _ = nb.resolve_story(story(title, source, url), projects, by_ref)
hits += bool(item and item["repd_ref"] == expected)
assert hits == len(positives), (path.name, hits)
for title in negatives:
item, _, _ = nb.resolve_story(story(title, "Energy-Storage.News", "https://energy-storage.news"),
projects, by_ref)
assert item is None, (path.name, title, item and item["repd_ref"])
def test_status_change_candidates_synthetic():
diff = {"previous": {"label": "P"}, "new": {"label": "N"},
"status_transitions": {"transitions": [{"from": "Application Submitted", "to": "Awaiting Construction",
"refs": ["13599"]}]},
"milestones": {"categories": {"consented": {"label": "Newly consented", "refs": ["13599", "99999999"]},
"refused": {"label": "Newly refused", "refs": []}}}}
changes = nb.repd_status_change_candidates(diff, Q3P)
assert [c["repd_ref"] for c in changes] == ["13599"]
change = changes[0]
assert change["role"] == "REPD_STATUS_CHANGE" and change["eligible_for_news_signal"] is False
assert change["event"] == "CONSENT" and change["basis"] == "transition"
article = {"gg_article_id": "A1", "repd_ref": "13599", "event": "CONSENT"}
assert nb.corroborate(changes, [article]) == 1 and change["corroborating_articles"] == ["A1"]
# ---- measured precision / recall on the labelled set ----------------------
def evaluate(resolver) -> dict:
labels = json.loads(LABELS.read_text(encoding="utf-8"))["pairs"]
tp = fp = fn = tn = 0
n_true = sum(p["label"] == "TRUE" for p in labels)
for pair in labels:
if pair["label"] == "UNCERTAIN":
continue
got = resolver(story(pair["headline"], pair["source"] or "", pair["source_url"] or "",
datetime.fromisoformat(pair["published"]).replace(tzinfo=timezone.utc)))
truth = pair["true_repd_refs"]
if got is None:
fn += bool(truth)
tn += not truth
elif got in truth:
tp += 1
else:
fp += 1
return {"tp": tp, "fp": fp, "fn": fn, "tn": tn, "precision": round(tp / (tp + fp), 3),
"recall": round(tp / n_true, 3)}
def test_labelled_precision_recall():
legacy = evaluate(lambda s: (lambda r: r[0] and r[0]["repd_ref"])(base._resolve_story(s, Q3P)))
refaware = evaluate(lambda s: (lambda r: r[0] and r[0]["repd_ref"])(nb.resolve_story(s, Q3P, Q3BY)))
print("legacy ", legacy)
print("refaware", refaware)
assert legacy["fp"] == 4 and legacy["tp"] == 40, legacy # recorded baseline
assert refaware["precision"] >= 0.98 and refaware["recall"] >= 0.85, refaware
assert refaware["tp"] > legacy["tp"] and refaware["fp"] < legacy["fp"]
# ---- the October feed builder ---------------------------------------------
def test_feed_builder_is_additive_and_deterministic():
protected = {p: sha(ROOT / p) for p in feed.PROTECTED}
with tempfile.TemporaryDirectory() as tmp:
outs = {}
for binder in ("legacy", "refaware"):
for run in (1, 2):
out = Path(tmp) / f"{binder}{run}.json"
feed.main(["--binder", binder, "--out", str(out)])
outs[(binder, run)] = out.read_bytes()
assert outs[("legacy", 1)] == outs[("legacy", 2)]
assert outs[("refaware", 1)] == outs[("refaware", 2)]
legacy = json.loads(outs[("legacy", 1)])
refaware = json.loads(outs[("refaware", 1)])
assert {p: sha(ROOT / p) for p in feed.PROTECTED} == protected
q2 = json.loads((ROOT / "dist" / "major_project_news_v9_5_1.json").read_text(encoding="utf-8"))
key = lambda i: (i["headline"], i["repd_ref"]) # noqa: E731
assert sorted(map(key, legacy["canonical_items"])) == sorted(map(key, q2["canonical_items"]))
assert legacy["project_snapshot"]["project_count"] == len(Q3P)
refs = {i["repd_ref"] for i in refaware["canonical_items"]}
assert {"1044", "2377", "5452", "8100"}.isdisjoint(refs) # known false/stale bindings removed
assert {"12206", "11928", "6502", "15164"} <= refs # known misses recovered
assert all("project" not in i for i in refaware["all_items"] if i["role"] == "DISCOVERY_ONLY"
and i["discovery_origin"] in {"V4_BASELINE", "V5_BASELINE"}) # no unverified V5 labels shown
assert refaware["repd_status_changes"]["count"] > 0
assert all(c["eligible_for_news_signal"] is False for c in refaware["repd_status_changes"]["items"])
try:
feed.main(["--out", str(ROOT / "dist" / "major_project_news_v9_5_1.json")])
except SystemExit:
pass
else:
raise AssertionError("builder must refuse to overwrite the pinned V9.5.1 feed")
if __name__ == "__main__":
tests = [(name, fn) for name, fn in sorted(globals().items()) if name.startswith("test_") and callable(fn)]
for name, fn in tests:
fn()
print("PASS", name)
print(f"news_binder_refaware: {len(tests)} tests PASS")GlobalGrid2050 Test News Binder V9 5
A test in the scripts folder that checks GlobalGrid2050 Major Project News V6. It is built from the story step (`story`).
testglobalgrid2050 / scripts/test_news_binder_v9_5.py · lines 1–116 of 116 · Entry point · pattern story (shared by 6 files)
- What it does
- It tests solar and battery storage (BESS). Defines story. Uses libraries __future__, json, sys, datetime, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, battery storage (BESS).
- Inputs & outputs
- In: JSON file major_project_news_v6.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- Offline V9.5 news-binder recall and adversarial regression gate. Its code works with 150 MW, 1 GWh and 123 MW.
- Why it matters
- Run by GlobalGrid2050 Project Signals Acid Workflow.
- Application
- globalgrid2050 · scripts · test
- Uses
- GlobalGrid2050 Major Project News V6 (import), __future__, json, sys, datetime, pathlib
- Used by
- run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
- Produces
- story
- Defines here
- story
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/test_news_binder_v9_5.py:1-116 · blob ff9b84e6dc75295cba199c9697ba0ca55126786d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Offline V9.5 news-binder recall and adversarial regression gate."""
from __future__ import annotations
import json
import sys
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import major_project_news_v6 as matcher # noqa: E402
def story(title: str, source: str = "Example News", source_url: str = "https://example.com") -> dict:
return {
"title": title,
"description": "",
"source": source,
"source_url": source_url,
"link": "https://example.test/v9-5-news-binder",
"published": datetime.now(timezone.utc),
}
snapshot, projects = matcher.load_project_snapshot()
by_ref = {project["repd_ref"]: project for project in projects}
expected_stems = {
"West Burton Power Station, North Road - Battery Storage": "west burton",
"Clifton Marsh Farm, Preston New Road - Solar Farm": "clifton marsh",
"The Tween Bridge Solar Farm": "tween bridge",
"Helios Renewable Energy Project": "helios",
"Coalburn Energy - Battery Storage": "coalburn",
"Dean Moor Solar Farm & Battery Storage": "dean moor",
"Stonestreet Green - Solar Farm & Battery Storage": "stonestreet green",
}
for official_name, expected in expected_stems.items():
actual = matcher.distinctive_name_stem(official_name)
assert actual == expected, f"stem {official_name!r}: {actual!r} != {expected!r}"
assert by_ref["13599"]["_name_duplicate_count"] == 1
assert by_ref["13600"]["_name_duplicate_count"] == 1
assert by_ref["12926"]["_name_stem_duplicate_count"] == 1
assert by_ref["19574"]["_name_stem_duplicate_count"] == 1
positives = (
("DESNZ grants DCO for 150MW Dean Moor solar project in Cumbria", "Solar Power Portal", "https://solarpowerportal.co.uk", "14550"),
("Longhedge solar project begins construction in Nottinghamshire", "reNEWS", "https://renews.biz", "11063"),
("Beacon Fen Energy Park development consent decision announced", "GOV.UK", "https://www.gov.uk", "13599"),
("Helios Renewable Energy Project development consent decision announced", "GOV.UK", "https://www.gov.uk", "11476"),
("1GWh Coalburn 1 battery energy storage enters operations in Scotland", "Solar Power Portal", "https://solarpowerportal.co.uk", "11034"),
("Elements Green acquires 300 MW Newarthill BESS project", "Energy Global", "https://energyglobal.com", "14763"),
("Eccles battery storage system plan secures £245m finance deal", "BBC", "https://www.bbc.co.uk", "11867"),
("Miliband grants DCO for Stonestreet Green solar-plus-storage NSIP", "Solar Power Portal", "https://solarpowerportal.co.uk", "10085"),
("Consent awarded for Clifton Marsh Solar Farm", "Vattenfall", "https://group.vattenfall.com", "13763"),
("Proposed Sutton-on-the-Forest solar farm attracts local criticism", "BBC", "https://www.bbc.co.uk", "19658"),
("EDF to optimise BW ESS’s 350MW Hams Hall BESS project", "Solar Power Portal", "https://solarpowerportal.co.uk", "9427"),
("RWE submits planning application for £125m Tween Bridge Solar development project", "Doncaster Free Press", "https://doncasterfreepress.co.uk", "12926"),
("RES secures three-year O&M contract for Cleve Hill solar project", "Solar Power Portal", "https://solarpowerportal.co.uk", "6502"),
)
positive_results = []
for title, source_name, source_url, expected_ref in positives:
item, resolution, detail = matcher._resolve_story(story(title, source_name, source_url), projects)
actual_ref = item and item.get("repd_ref")
positive_results.append({"title": title, "expected": expected_ref, "actual": actual_ref, "resolution": resolution})
positive_passes = sum(result["expected"] == result["actual"] for result in positive_results)
recall = positive_passes / len(positive_results)
assert recall >= 0.80, json.dumps(positive_results, indent=2)
brecks, brecks_resolution, _ = matcher._resolve_story(
story(
"Qair contracts INTEC to provide EPC and O&M services at 46.5MW Brecks solar farm",
"Solar Power Portal",
"https://solarpowerportal.co.uk",
),
projects,
)
assert brecks is not None and brecks_resolution == "accepted"
assert brecks["repd_ref"] == "10087"
assert brecks["capacity_mw"] == 45.4
assert brecks["news_capacities_mw"] == [46.5]
negatives = (
"New Jersey Board of Public Utilities releases 150MW BTM energy storage proposal",
"Sol Systems reaches financial close on 123MW Illinois solar portfolio",
"Fields record demand as 150MW solar output reaches a new high",
"150MW battery project approved in the UK",
"Stonestreet Green solar project approved in Australia",
"California Farm solar project secures approval in California",
"Canada Farm solar project expands into Ontario",
"Cleve Hill offshore wind farm begins construction",
"West Burton C BESS project reaches financial close",
)
negative_leaks = []
for title in negatives:
item, resolution, _detail = matcher._resolve_story(
story(title, "Energy-Storage.News", "https://energy-storage.news"), projects
)
if item is not None:
negative_leaks.append({"title": title, "repd_ref": item.get("repd_ref"), "resolution": resolution})
assert not negative_leaks, json.dumps(negative_leaks, indent=2)
telemetry = (json.loads((ROOT / "dist" / "major_project_news_v6.json").read_text()).get("telemetry") or {})
assert isinstance(telemetry.get("pair_rejection_reasons"), dict)
assert isinstance(telemetry.get("rejected_article_samples"), list)
assert len(telemetry["rejected_article_samples"]) <= matcher.MAX_REJECTED_ARTICLE_SAMPLES
print(
"V9.5 news binder: PASS "
f"({positive_passes}/{len(positive_results)} focused positives, "
f"{len(negatives)}/{len(negatives)} hostile negatives rejected, telemetry present)"
)GlobalGrid2050 Test News Feed V9 5 1
A test in the scripts folder covering the Renewable Energy Planning Database (REPD) register.
testglobalgrid2050 / scripts/test_news_feed_v9_5_1.py · lines 1–65 of 65 · Entry point
- What it does
- It tests the REPD register. Defines load, key. Uses libraries __future__, json, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file major_project_news_v9_5_1.json; JSON file major_project_news_v5.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- Defines `load` and `key`.
- Why it matters
- Run by GlobalGrid2050 Project Signals Acid Workflow.
- Application
- globalgrid2050 · scripts · test
- Uses
- __future__, json, pathlib
- Used by
- run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
- Produces
- load, key
- Defines here
- load, key
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/test_news_feed_v9_5_1.py:1-65 · blob df029fdcbf2996a3f98f0c05fd70cb18d2a130d9 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
FEED = ROOT / "dist" / "major_project_news_v9_5_1.json"
V5 = ROOT / "dist" / "major_project_news_v5.json"
def load(path: Path) -> dict:
return json.loads(path.read_text(encoding="utf-8"))
def key(item: dict) -> tuple[str, str, str]:
return (
str(item.get("headline") or "").casefold().strip(),
str(item.get("source_url") or item.get("source") or "").casefold().strip(),
str(item.get("published") or "")[:10],
)
feed, v5 = load(FEED), load(V5)
assert feed["schema"] == "globalgrid2050.major-project-news.v9.5.1"
assert feed["release"] == "9.5.1"
assert feed["all_headline_count"] == len(feed["all_items"]) == 133
assert feed["relevant_headline_count"] == len(feed["canonical_items"]) == 45
assert feed["v9_4_baseline_headline_count"] == len(v5["items"]) == 125
assert feed["v5_revalidated_primary_count"] == 37
assert feed["v6_canonical_headline_count"] == 8
all_keys = {key(item) for item in feed["all_items"]}
assert {key(item) for item in v5["items"]} <= all_keys, "V9.4 newspaper was truncated"
assert sum(item["canonical_relevant"] for item in feed["all_items"]) == 45
for item in feed["canonical_items"]:
assert item["role"] == "PRIMARY_MATCH"
assert item["eligible_for_news_signal"] is True
assert item["gg_project_id"] == f"GG2050-REPD-{item['repd_ref']}"
for item in feed["all_items"]:
if not item["canonical_relevant"]:
assert item["role"] == "DISCOVERY_ONLY"
assert item["eligible_for_news_signal"] is False
beacon = [
item for item in feed["canonical_items"]
if item["headline"] == "Beacon Fen Energy Park development consent decision announced"
]
assert len(beacon) == 1
assert beacon[0]["repd_ref"] == "13599"
assert beacon[0]["gg_project_id"] == "GG2050-REPD-13599"
assert beacon[0]["operator"] == "Low Carbon Limited"
assert beacon[0]["capacity_mw"] == 400.0
assert beacon[0]["technology"] == "solar"
assert beacon[0]["confidence"] == 91
assert "13600" in beacon[0]["development_related_repd_refs"]
hostile_patterns = ("New Jersey Board", "South Australia", "Evolution Mining", "Forest Healthcare")
for pattern in hostile_patterns:
matches = [item for item in feed["all_items"] if pattern.casefold() in item["headline"].casefold()]
assert matches, f"hostile discovery fixture missing: {pattern}"
assert all(item["canonical_relevant"] is False for item in matches), pattern
print("V9.5.1 feed: PASS (133 ALL, 45 RELEVANT, Beacon Fen -> REPD 13599, discovery-only blocked from signals)")GlobalGrid2050 Test V6 Price History Accuracy
A test in the scripts folder. It parses time (`parse_time`), reads annual CSV (`read_annual_csv`) and reads daily JSON (`read_daily_json`).
testglobalgrid2050 / scripts/test_v6_price_history_accuracy.py · lines 1–177 of 177 · Entry point · pattern parse_time (shared by 19 files)
- What it does
- It tests its inputs. Defines 9 functions or classes, including parse_time, read_annual_csv, daily_from_csv, read_daily_json, assert_close. Uses libraries __future__, csv, json, collections, datetime. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: CSV file elexon_system_prices_2021.csv; CSV file elexon_system_prices_2026.csv; JSON file electricity_price_history_daily_decade.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- Validate the V6 UK energy tracking price history chart inputs against source CSV data.
- Why it matters
- Run by GlobalGrid2050 Project Signals Acid Workflow.
- Application
- globalgrid2050 · scripts · test
- Uses
- __future__, csv, json, collections, datetime, pathlib
- Used by
- run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
- Produces
- parse_time, read_annual_csv, daily_from_csv, read_daily_json, assert_close, validate_day, count_csv_window, write_report, main
- Defines here
- parse_time, read_annual_csv, daily_from_csv, read_daily_json, assert_close, validate_day, count_csv_window, write_report, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/test_v6_price_history_accuracy.py:1-177 · blob 620051e6577bce1d5dc154dffb988b0e14794c7f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
#!/usr/bin/env python3
"""
Validate the V6 UK energy tracking price history chart inputs against source CSV data.
This test protects the fixed chart contract:
- Short periods use half hourly settlement records.
- Six months and longer use the daily aggregate JSON.
- Daily aggregate mode must preserve true daily high, average and low values.
- Extreme price events must not disappear from the long range chart.
"""
from __future__ import annotations
import csv
import json
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ANNUAL_FILES = {
2021: ROOT / "data" / "electricity" / "elexon_system_prices_2021.csv",
2026: ROOT / "data" / "electricity" / "elexon_system_prices_2026.csv",
}
DAILY_JSON = ROOT / "uk_energy_tracking_v6" / "electricity_price_history_daily_decade.json"
REPORT = ROOT / "V6_PRICE_HISTORY_ACCURACY_REPORT.md"
def parse_time(value: str) -> datetime:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
def read_annual_csv(path: Path) -> list[dict[str, object]]:
rows: list[dict[str, object]] = []
with path.open("r", encoding="utf-8", newline="") as handle:
reader = csv.DictReader(handle)
for row in reader:
price = row.get("systemBuyPriceGBPperMWh") or row.get("systemSellPriceGBPperMWh") or row.get("priceGBPperMWh")
if not price:
continue
rows.append(
{
"settlementDate": row["settlementDate"],
"settlementPeriod": int(row["settlementPeriod"]),
"periodStartUTC": parse_time(row["periodStartUTC"]),
"price": float(price),
}
)
return rows
def daily_from_csv(rows: list[dict[str, object]]) -> dict[str, dict[str, object]]:
grouped: dict[str, list[dict[str, object]]] = defaultdict(list)
for row in rows:
grouped[str(row["settlementDate"])].append(row)
out: dict[str, dict[str, object]] = {}
for day, items in grouped.items():
prices = [float(item["price"]) for item in items]
high_row = max(items, key=lambda item: float(item["price"]))
low_row = min(items, key=lambda item: float(item["price"]))
out[day] = {
"average": round(sum(prices) / len(prices), 2),
"high": round(float(high_row["price"]), 2),
"highAt": high_row["periodStartUTC"].strftime("%H:%M"),
"low": round(float(low_row["price"]), 2),
"lowAt": low_row["periodStartUTC"].strftime("%H:%M"),
"observations": len(items),
}
return out
def read_daily_json(path: Path) -> dict[str, dict[str, object]]:
payload = json.loads(path.read_text(encoding="utf-8"))
return {row["date"]: row for row in payload.get("rows", [])}
def assert_close(label: str, actual: float, expected: float, tolerance: float = 0.01) -> None:
if abs(actual - expected) > tolerance:
raise AssertionError(f"{label}: expected {expected}, got {actual}")
def validate_day(day: str, csv_daily: dict[str, dict[str, object]], json_daily: dict[str, dict[str, object]]) -> list[str]:
if day not in csv_daily:
raise AssertionError(f"Missing {day} in annual CSV aggregation")
if day not in json_daily:
raise AssertionError(f"Missing {day} in daily JSON")
c = csv_daily[day]
j = json_daily[day]
assert_close(f"{day} average", float(j["average"]), float(c["average"]))
assert_close(f"{day} high", float(j["high"]), float(c["high"]))
assert_close(f"{day} low", float(j["low"]), float(c["low"]))
if int(j["observations"]) != int(c["observations"]):
raise AssertionError(f"{day} observations: expected {c['observations']}, got {j['observations']}")
if str(j["highAt"]) != str(c["highAt"]):
raise AssertionError(f"{day} highAt: expected {c['highAt']}, got {j['highAt']}")
if str(j["lowAt"]) != str(c["lowAt"]):
raise AssertionError(f"{day} lowAt: expected {c['lowAt']}, got {j['lowAt']}")
return [
day,
f"average £{j['average']}/MWh",
f"high £{j['high']}/MWh at {j['highAt']}",
f"low £{j['low']}/MWh at {j['lowAt']}",
f"{j['observations']} settlement periods",
]
def count_csv_window(rows: list[dict[str, object]], start: datetime, days: int) -> int:
end = start + timedelta(days=days) - timedelta(seconds=1)
return sum(1 for row in rows if start <= row["periodStartUTC"] <= end)
def write_report(results: list[list[str]], window_count: int) -> None:
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
lines = [
"# V6 Price History Accuracy Report",
"",
f"Generated UTC: `{now}`",
"",
"This report validates V6 chart source values against the Elexon annual CSV and daily aggregate JSON used by the UK Energy Tracking V6 chart.",
"",
"## Result",
"",
"PASS: sampled daily aggregates match the underlying Elexon CSV files, including the September 2021 extreme price event.",
"",
"## Sample day checks",
"",
"| Date | Average | High | Low | Observations |",
"|---|---:|---:|---:|---:|",
]
for row in results:
lines.append(f"| {row[0]} | {row[1]} | {row[2]} | {row[3]} | {row[4]} |")
lines.extend(
[
"",
"## Seven day half hourly window check",
"",
f"2026-01-01 for 7 days contains `{window_count}` half hourly settlement records. Expected `336`.",
"",
"## Interpretation",
"",
"The chart must preserve true daily high, average and low values for periods of six months and longer. The 2021-09-09 high of £4,037.80/MWh is a required truth marker for the ten year chart and must not be hidden by average only rendering.",
"",
]
)
REPORT.write_text("\n".join(lines), encoding="utf-8")
def main() -> None:
daily_json = read_daily_json(DAILY_JSON)
rows_2026 = read_annual_csv(ANNUAL_FILES[2026])
daily_2026 = daily_from_csv(rows_2026)
rows_2021 = read_annual_csv(ANNUAL_FILES[2021])
daily_2021 = daily_from_csv(rows_2021)
results = [
validate_day("2026-01-01", daily_2026, daily_json),
validate_day("2026-01-02", daily_2026, daily_json),
validate_day("2026-01-05", daily_2026, daily_json),
validate_day("2021-09-09", daily_2021, daily_json),
]
window_count = count_csv_window(rows_2026, datetime(2026, 1, 1, tzinfo=timezone.utc), 7)
if window_count != 336:
raise AssertionError(f"2026-01-01 7 day window expected 336 rows, got {window_count}")
write_report(results, window_count)
print("PASS: V6 price history CSV checks completed")
print(f"Report written: {REPORT}")
if __name__ == "__main__":
main()