In this section
- Match transform · globalgrid2050 / automation/news/acquisition/match.py lines 1–37
- Normalise transform · globalgrid2050 / automation/news/acquisition/normalise.py lines 1–69
- Publish other · globalgrid2050 / automation/news/acquisition/publish.py lines 1–30
- Research Queue ingest · globalgrid2050 / automation/news/acquisition/research_queue.py lines 1–53
- News — Acquisition storage · globalgrid2050 / automation/news/acquisition/run.py lines 1–94
- Sources docs-config · globalgrid2050 / automation/news/acquisition/sources.yaml lines 1–10
- Binder energy-data · globalgrid2050 / automation/news/binder.py lines 1–405
Match
A Python module in the acquisition folder of GlobalGrid2050 that works with the Renewable Energy Planning Database (REPD) register. It normalises name (`normalise_name`) and matches articles (`match_articles`).
transformglobalgrid2050 / automation/news/acquisition/match.py · lines 1–37 of 37
- What it does
- It calculates the REPD register. Defines normalise_name, match_articles. Uses libraries __future__, collections, re, unicodedata.
- 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.
- Downstream impact
- Used directly by 5 files: Research Queue (globalgrid2050); News — Acquisition (globalgrid2050); Engine (globalgrid2050); Test Acquisition (globalgrid2050); and 1 more. Reached from 10 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Build Prospecting Priority (globalgrid2050).
- What it achieves
- Conservative exact project matching, with no verification or event inference.
- Why it matters
- Imported by Research Queue, News — Acquisition and Engine. Checked by 2 tests, including Test Acquisition.
- Application
- globalgrid2050 · automation/news/acquisition · Python module
- Uses
- __future__, collections, re, unicodedata
- Used by
- imported by Research Queue (relative import), imported by News — Acquisition (relative import), imported by Engine (relative import), imported by Test Acquisition (import), imported by Test Evidence Store (import)
- Produces
- normalise_name, match_articles
- Defines here
- normalise_name, match_articles
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/acquisition/match.py:1-37 · blob d1142e947ce2fc5013cf59dd02c3ce97d82768fe · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Conservative exact project matching, with no verification or event inference."""
from __future__ import annotations
from collections import Counter
import re
import unicodedata
def normalise_name(value):
return " ".join(re.findall(r"[^\W_]+", unicodedata.normalize("NFKC", value).casefold(), re.UNICODE))
def match_articles(articles, projects):
"""Match explicit REPD identifiers or a complete, unambiguous project name.
Bare digits are not IDs (they can be years or capacities). Short one-word
names and names duplicated in the queue require an explicit REPD ID.
"""
names = Counter(normalise_name(p["name"]) for p in projects)
matches = {}
for article in articles:
raw = article["title"] + "\n" + article.get("content", "")
text = " " + normalise_name(raw) + " "
explicit = set(re.findall(r"\brepd\s*(?:(?:ref(?:erence)?\s*)?(?:id\s*)?)[:#-]?\s*(\d+)\b", raw, flags=re.I))
for project in projects:
ref = str(project["id"])
name = normalise_name(project["name"])
method = None
if ref in explicit:
method = "repd_id"
elif (not project.get("name_ambiguous", False) and len(name.split()) >= 2
and len(name) >= 8 and names[name] == 1 and " " + name + " " in text):
method = "exact_name"
if method:
matches[(ref, article["url"])] = {"project_id": ref, "article_url": article["url"],
"status": "PROVISIONAL", "match_method": method}
return list(matches.values())Normalise
A Python module in the acquisition folder of GlobalGrid2050 that uses SHA-256. It cleans text (`clean_text`) and normalises article (`normalise_article`).
transformglobalgrid2050 / automation/news/acquisition/normalise.py · lines 1–69 of 69 · pattern clean_text (shared by 6 files)
- What it does
- It calculates its inputs. Defines 8 functions or classes, including _Text, __init__, handle_starttag, handle_endtag, handle_data. Uses libraries __future__, datetime, email.utils, hashlib, html.
- 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.
- Downstream impact
- Used directly by 2 files: Fetch (globalgrid2050); Test Acquisition (globalgrid2050). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); News — Acquisition (globalgrid2050).
- What it achieves
- Normalize RSS metadata without persisting publisher article bodies.
- Why it matters
- Imported by Fetch. Checked by Test Acquisition.
- Application
- globalgrid2050 · automation/news/acquisition · Python module
- Uses
- __future__, datetime, email.utils, hashlib, html, html.parser, urllib.parse
- Used by
- imported by Fetch (relative import), imported by Test Acquisition (import)
- Produces
- clean_text, safe_publisher_url, normalise_article
- Defines here
- _Text, __init__, handle_starttag, handle_endtag, handle_data, clean_text, safe_publisher_url, normalise_article
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/acquisition/normalise.py:1-69 · blob 1a715bde2204f017d8dbe14b46195c184d65d888 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Normalize RSS metadata without persisting publisher article bodies."""
from __future__ import annotations
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import hashlib
import html
from html.parser import HTMLParser
from urllib.parse import urlsplit, urlunsplit
class _Text(HTMLParser):
def __init__(self):
super().__init__()
self.parts = []
self.hidden = 0
def handle_starttag(self, tag, attrs):
if tag in {"script", "style"}:
self.hidden += 1
def handle_endtag(self, tag):
if tag in {"script", "style"}:
self.hidden = max(0, self.hidden - 1)
def handle_data(self, data):
if not self.hidden:
self.parts.append(data)
def clean_text(value):
parser = _Text()
parser.feed(html.unescape(str(value or "")))
return " ".join(" ".join(parser.parts).split())
def safe_publisher_url(value):
"""Only the explicitly approved HTTPS publisher host is accepted."""
try:
p = urlsplit(value)
return (p.scheme == "https" and p.hostname in {"www.pv-magazine.com", "pv-magazine.com"}
and p.port in {None, 443} and not p.username and not p.password)
except (TypeError, ValueError):
return False
def normalise_article(entry, source):
url = str(entry.get("url") or entry.get("link") or "").strip()
if not safe_publisher_url(url):
raise ValueError("Article URL must use the approved HTTPS publisher")
p = urlsplit(url)
url = urlunsplit((p.scheme, p.netloc.lower(), p.path, p.query, ""))
title = clean_text(entry.get("title"))
raw_date = entry.get("pub_date") or entry.get("date") or entry.get("published")
if not title or not isinstance(raw_date, str):
raise ValueError("Article title and publisher date are required")
try:
date = parsedate_to_datetime(raw_date)
except (TypeError, ValueError):
date = datetime.fromisoformat(raw_date.replace("Z", "+00:00"))
if date.tzinfo is None:
raise ValueError("Publisher date must have a timezone")
return {
"id": hashlib.sha256(url.encode()).hexdigest(), "url": url, "title": title,
"pub_date": date.astimezone(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
"source_id": source["id"], "publisher": source["publisher"],
# Transient matching input: deliberately excluded from database/export.
"content": clean_text(entry.get("content") or entry.get("description"))[:20000],
}Publish
A Python command-line tool in the acquisition folder of GlobalGrid2050 that publishes one evidence commit with an exact-ref lease and no history rewrite.
otherglobalgrid2050 / automation/news/acquisition/publish.py · lines 1–30 of 30 · Entry point · pattern publish (shared by 21 files)
- What it does
- Defines publish, git. Uses libraries argparse, re, subprocess. Side effects: starts processes.
- 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.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 2 files: Test Evidence Publish (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- Defines `publish` and `git`.
- Why it matters
- Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow. Checked by Test Evidence Publish.
- Application
- globalgrid2050 · automation/news/acquisition · Python CLI
- Uses
- argparse, re, subprocess
- Used by
- imported by Test Evidence Publish (import), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run)
- Produces
- publish
- Defines here
- publish, git
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/acquisition/publish.py:1-30 · blob 0030206dc5bbe734fa81e24a6d6298049c7fd77e · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Publish one evidence commit with an exact-ref lease and no history rewrite."""
import argparse
import re
import subprocess
REF = "refs/heads/pipeline-evidence-data"
def publish(repository, expected_head, remote="origin"):
if expected_head and not re.fullmatch(r"[0-9a-f]{40}", expected_head):
raise ValueError("Expected a full restored commit SHA or empty new-branch lease")
def git(*args):
return subprocess.run(["git", "-C", str(repository), *args], check=True,
capture_output=True, text=True).stdout.strip()
ancestry = git("rev-list", "--parents", "-n", "1", "HEAD").split()
# Only a direct successor of the restored state (or a root initial commit)
# may be published. The lease flag is a CAS, never permission to rewrite.
if ancestry[1:] != ([expected_head] if expected_head else []):
raise ValueError("Publication must be one direct successor of restored state")
return git("push", f"--force-with-lease={REF}:{expected_head}", remote, f"HEAD:{REF}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("repository")
parser.add_argument("expected_head")
args = parser.parse_args()
publish(args.repository, args.expected_head)Research Queue
A Python command-line tool in the acquisition folder of GlobalGrid2050 that loads seed projects (`load_seed_projects`), covering solar and the Renewable Energy Planning Database (REPD) register, using SHA-256.
ingestglobalgrid2050 / automation/news/acquisition/research_queue.py · lines 1–53 of 53 · Entry point
- What it does
- Defines _read_pinned, load_seed_projects. Uses libraries __future__, hashlib, json, collections, 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, the REPD register. README: "`research_queue.py` verifies the original manifest, build manifest and every partition hash before returning projects."
- Inputs & outputs
- In: JSON file build_manifest.json.
- Downstream impact
- Used directly by 6 files: News — Acquisition (globalgrid2050); Prospecting (globalgrid2050); Test Acquisition (globalgrid2050); Test Acquisition Analytics (globalgrid2050); and 2 more. Reached from 4 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Build Prospecting Priority (globalgrid2050); Test Prospecting (globalgrid2050).
- What it achieves
- Load exactly the immutable V9.24 Solar-1000, validating all official rows. It reads `solar1000/manifest.json`.
- Why it matters
- Imported by News — Acquisition and Prospecting. Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow. Checked by 3 tests, including Test Acquisition.
- Application
- globalgrid2050 · automation/news/acquisition · Python CLI
- Uses
- Match (relative import), __future__, hashlib, json, collections, pathlib
- Used by
- imported by News — Acquisition (relative import), imported by Prospecting (import), imported by Test Acquisition (import), imported by Test Acquisition Analytics (import), imported by Test Acquisition Run (import), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run)
- Produces
- load_seed_projects
- Defines here
- _read_pinned, load_seed_projects
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/acquisition/research_queue.py:1-53 · blob 5a24ac8f953ddf2f7bd93c22817d06cb6236ac53 · 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
"""Load exactly the immutable V9.24 Solar-1000, validating all official rows."""
from __future__ import annotations
import hashlib
import json
from collections import Counter
from pathlib import Path
from .match import normalise_name
RELEASE_ID = "202611161244"
MANIFEST_SHA256 = "c625edbb9c471a1e9a9034a1afe99881fbfabb1fcadcf0623355931f5b6aed1f"
BUILD_MANIFEST_SHA256 = "eb59fee0ab9bd4bf304cf7957755e69647038ad2360eabe680848d14e636c304"
ROOT = Path(__file__).resolve().parents[3]
def _read_pinned(path, digest):
try:
data = path.read_bytes()
except OSError as exc:
raise ValueError("Required immutable V9.24 input unavailable") from exc
if hashlib.sha256(data).hexdigest() != digest:
raise ValueError("Immutable V9.24 input changed")
return json.loads(data)
def load_seed_projects(repo_root=None):
"""Return 1,000 original project dicts plus an `id` alias, never reselection."""
release = Path(repo_root or ROOT) / "uk_renewables_pipeline" / RELEASE_ID
seed = _read_pinned(release / "solar1000/manifest.json", MANIFEST_SHA256)
manifest = _read_pinned(release / "data/v9.1/build_manifest.json", BUILD_MANIFEST_SHA256)
ids = seed["ids"]
if len(ids) != 1000 or len(set(ids)) != 1000 or seed["selection_count"] != 1000:
raise ValueError("Solar-1000 selection count changed")
projects = []
for part in manifest["project_partitions"]:
data = _read_pinned(release / part["path"], part["sha256"])
if len(data["projects"]) != part["record_count"]:
raise ValueError("REPD partition count changed")
projects.extend(data["projects"])
index = {p["repd_ref"]: p for p in projects}
solar_ids = sorted((p["repd_ref"] for p in projects if p["technology"] == "solar"), key=int)
if len(projects) != 7775 or len(index) != 7775 or len(solar_ids) != 3604:
raise ValueError("Official REPD population changed")
if ids != solar_ids[:1000]:
raise ValueError("Solar-1000 differs from V9.24 selection")
name_counts = Counter(normalise_name(p["name"]) for p in projects if p["technology"] == "solar")
return [dict(index[ref], id=ref, name_ambiguous=name_counts[normalise_name(index[ref]["name"])] > 1)
for ref in ids]
if __name__ == "__main__":
print(f"V9.24 REPD: 7775; immutable Solar-1000: {len(load_seed_projects())}")News — Acquisition
A Python command-line tool in the automation folder of GlobalGrid2050. It is built from the collect step (`collect`).
storageglobalgrid2050 / automation/news/acquisition/run.py · lines 1–94 of 94 · Entry point · pattern collect (shared by 23 files)
- What it does
- It loads data. Defines collect, main. Uses libraries __future__, argparse, datetime, 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.
- Inputs & outputs
- In: JSON file latest.json; command-line arguments. Out: JSON file latest.json.
- Downstream impact
- Used directly by 2 files: Test Acquisition Run (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- Weekly evidence candidate builder; probes never write evidence or state. It writes `latest.json`. It accepts `--out`, `--sources` and `--probe`.
- Why it matters
- Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow. Checked by Test Acquisition Run.
- Application
- globalgrid2050 · automation/news/acquisition · Python CLI
- Uses
- Evidence Store (relative import), Fetch (relative import), Match (relative import), Research Queue (relative import), Analytics (relative import), __future__, argparse, datetime, json, pathlib, shutil, tempfile
- Used by
- imported by Test Acquisition Run (import), run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run)
- Produces
- collect, main
- Defines here
- collect, 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 automation/news/acquisition/run.py:1-94 · blob 38eea3eb4075eab724f62ea5ad21601ed301a4a3 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Weekly evidence candidate builder; probes never write evidence or state."""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import shutil
import tempfile
from .evidence_store import EvidenceStore, export_snapshot
from .fetch import FetchError, fetch_source, load_sources
from .match import match_articles
from .research_queue import MANIFEST_SHA256, load_seed_projects
def collect(out, *, sources_path=None, probe=False, fetcher=fetch_source):
projects = load_seed_projects()
sources = load_sources(sources_path, include_disabled=probe)
if not sources:
raise FetchError("No enabled source with accepted rights; manual review required")
# Complete every critical fetch and match before opening or changing state.
results = [fetcher(source, probe=probe) for source in sources]
articles = [a for result in results for a in result["articles"]]
receipts = [result["source"] for result in results]
matches = match_articles(articles, projects)
report = {"probe_only": probe, "selected": len(projects), "articles": len(articles),
"provisional_matches": len(matches), "verified": 0,
"seed_sha256": MANIFEST_SHA256, "sources": receipts}
if probe:
return report
out = Path(out)
out.mkdir(parents=True, exist_ok=True)
database = out / "evidence.sqlite"
# A failed schema/export cannot corrupt the previous accepted SQLite state.
# This is staging, not a claim of filesystem-atomic multi-file publication.
# Workflow publishes the entire validated output in one Git ref update.
with tempfile.TemporaryDirectory(prefix="evidence-build-") as temporary:
staged = Path(temporary)
staged_db = staged / "evidence.sqlite"
if database.exists():
shutil.copyfile(database, staged_db)
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
with EvidenceStore(staged_db) as store:
store.record_run(projects, articles, matches, now, receipts)
pointer = export_snapshot(store, staged, expected_project_ids=[p["id"] for p in projects])
# Analytical artifacts belong to the same candidate transaction. Import
# only on this path: health probes never load or create analytical data.
from .analytics import export_analytics
payload = json.loads((staged / pointer["json"]).read_text(encoding="utf-8"))
analytics = export_analytics(payload, staged, expected_project_ids=[p["id"] for p in projects])
# Check immutable conflicts before copying any candidate file.
for path in staged.rglob("*"):
if not path.is_file() or path.name in {"evidence.sqlite", "latest.json"}:
continue
destination = out / path.relative_to(staged)
if destination.exists() and destination.read_bytes() != path.read_bytes():
raise ValueError("Immutable snapshot conflict; manual review required")
for path in staged.rglob("*"):
if path.is_file() and path.name != "latest.json":
destination = out / path.relative_to(staged)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(path, destination)
(out / "latest.json").write_bytes((staged / "latest.json").read_bytes())
report["pointer"] = pointer
report["analytics"] = analytics
return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--out", type=Path, default=Path("dist/news/evidence"))
parser.add_argument("--sources", type=Path)
parser.add_argument("--probe", action="store_true", help="Health metadata only, including disabled sources")
parser.add_argument("--report", type=Path, required=True)
args = parser.parse_args()
try:
report = collect(args.out, sources_path=args.sources, probe=args.probe)
report["result"] = "probe_complete" if args.probe else "candidate_built"
code = 0
except Exception as exc:
# Never dump paths, raw responses, credentials or articles into receipts.
report = {"result": "blocked", "error_type": type(exc).__name__,
"manual_review_required": True, "probe_only": args.probe}
print(f"BLOCKED ({type(exc).__name__}); manual review required; no publication")
code = 1
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8", newline="\n")
print(json.dumps(report))
return code
if __name__ == "__main__":
raise SystemExit(main())Sources
A configuration file in the acquisition folder of GlobalGrid2050.
docs-configglobalgrid2050 / automation/news/acquisition/sources.yaml · lines 1–10 of 10 · Not reached from any entry point (candidate for review)
- 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.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · automation/news/acquisition · configuration
- Uses
- none found
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/acquisition/sources.yaml:1-10 · blob 3e51615a6a0848989b8b3f81817b01d0ee065d81 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
- id: pv_magazine_global
publisher: PV Magazine
kind: rss
url: https://www.pv-magazine.com/feed/
technology: [solar]
interval_hours: 168
enabled: false
rights_status: unknown
rights_review_url: null
output_policy: headline_link_onlyBinder
A Python command-line tool in the news folder of GlobalGrid2050 that reads the Renewable Energy Planning Database (REPD) register, solar and wind.
energy-dataglobalgrid2050 / automation/news/binder.py · lines 1–405 of 405 · Entry point · pattern tally (shared by 2 files)
- What it does
- It loads the REPD register, solar and wind. Defines 17 functions or classes, including news_capacities, capacity_corroborates, ProjectIndex, __init__, name_hits. Uses libraries __future__, argparse, json, re, sys. Side effects: reads or writes files; starts processes.
- 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, solar, wind.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Test Binder (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- It is built from the news capacities helper (`news_capacities`), the capacity corroborates helper (`capacity_corroborates`) and the project index class (`ProjectIndex`). Bind a news article to a REPD project (and, separately, to a data-centre site) with an explicit confidence class and a full evidence trail. Its code works with 1.2 GW and 2 MW. It accepts `--repd`, `--labels` and `--out`.
- Why it matters
- Checked by Test Binder.
- Application
- globalgrid2050 · automation/news · Python CLI
- Uses
- Renewable Energy Planning Database (REPD) Diff (import), Names (import), Events (import), Relevance (import), __future__, argparse, json, re, sys, pathlib
- Used by
- imported by Test Binder (import)
- Produces
- news_capacities, capacity_corroborates, ProjectIndex, bind, DatacentreIndex, evaluate, main
- Defines here
- news_capacities, capacity_corroborates, ProjectIndex, __init__, name_hits, _foreign, bind, devs, narrow, primary_key, DatacentreIndex, __init__, bind, evaluate, tally, metrics, 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 automation/news/binder.py:1-405 · blob b2f5fa5b9a7cc630f9870280bfc221c448850837 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""automation/news/binder.py - bind a news article to a REPD project (and, separately, to a
data-centre site) with an explicit confidence class and a full evidence trail.
python -m automation.news.binder --repd repd-2026q3.csv --labels LABELS.json --out EVAL.json \
[--datacentres uk_datacentre_pipeline_202610312133.geojson]
Classes (only EXACT and STRONG may drive a project's news signal; the rest are context):
EXACT a planning application reference from REPD appears in the text; or one development
matched by its distinctive name AND corroborated by stated capacity (within
max(2 MW, 15%)), operator or county / planning authority
STRONG one development matched by its distinctive name (a one-word name only when it
sits beside a technology word, e.g. 'Hessay Solar'); or several matched and
narrowed to one by capacity, location or operator corroboration
PROBABLE narrowed to one only by status preference (live over revised/expired, refused for
a refusal story), or matched only by a place segment of the REPD name
CANDIDATE name matched but still ambiguous, foreign location named without UK context, or
the story's technology contradicts the project's
UNBOUND no REPD name matched
Name matching uses automation/news/names.py (shared with events and relevance). A name that
is wholly inside a longer matched name is ignored ('Coalburn' inside 'Coalburn II'). Co-located
REPD siblings (same development group) count as one development; the primary row is chosen by
the story's technology words, else solar > wind > battery > other, then capacity, then Ref ID.
Data centres are a distinct category: an article mentioning data-centre wording is tagged
topic DATA_CENTRES, and a named site from the GridAtlas data-centre register is bound by its
dcuk id, never by an invented REPD Ref ID.
Standard library only. No network.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
from automation.repd import diff as repd
from automation.news import names
from automation.news.events import development_groups
from automation.news.relevance import classify_article_event
SCHEMA_EVAL = "globalgrid2050.news-binder-evaluation.v1"
SIGNAL_CLASSES = ("EXACT", "STRONG")
CLASS_ORDER = ("EXACT", "STRONG", "PROBABLE", "CANDIDATE", "UNBOUND")
LIVE = {"Application Submitted", "Appeal Lodged", "Awaiting Construction", "Under Construction",
"Operational", "No Application Required"}
REFUSAL_STATUSES = {"Application Refused", "Appeal Refused", "Appeal Lodged"}
FAMILY_ORDER = {"solar": 0, "wind": 1, "battery": 2, "other": 3}
# Foreign places (restated from scripts/major_project_news_v6.py FOREIGN_RULES, plus Republic of
# Ireland counties that do not double as UK place names). Bare "ireland" is not foreign:
# Northern Ireland is UK.
FOREIGN = (
"new jersey", "california", "texas", "australia", "new south wales", "queensland", "canada",
"alberta", "ontario", "germany", "german", "italy", "spain", "india", "china", "chinese",
"south africa", "new zealand", "republic of ireland", "irish republic", "united states",
"us roundup", "new york", "arizona", "nevada", "florida", "ohio", "virginia", "massachusetts",
"pennsylvania", "colorado", "illinois", "chile", "japan", "greece", "romania", "uzbek",
"uzbekistan", "france", "sweden", "netherlands", "poland", "county kerry", "kerry", "meath",
"wexford", "wicklow", "kildare", "offaly", "laois", "westmeath", "tipperary", "kilkenny",
"donegal", "galway", "co cork", "county cork", "co clare", "county clare", "nem", "eu roundup",
)
UK_CONTEXT = ("uk", "u k", "britain", "british", "england", "english", "scotland", "scottish", "wales",
"welsh", "northern ireland", "gb")
DC_CONTEXT = ("data centre", "data centres", "data center", "data centers", "datacentre", "datacentres",
"datacenter", "ai growth zone", "supercomputer", "hyperscale", "colocation campus")
DC_BOILERPLATE = frozenset({"data", "centre", "centres", "center", "centers", "datacentre", "datacentres",
"campus", "dc", "uk", "the", "ltd", "limited", "plc", "and", "of", "site"})
_MW_RE = re.compile(r"\b(\d{1,2}(?:,\d{3})+|\d{1,5}(?:\.\d+)?)\s*(gw|mw)(?:p|e|ac|dc)?\b", re.I)
def news_capacities(text: str) -> list[float]:
"""MW figures stated in a text ('49.9MWp', '1,000 MW', '1.2GW'). MWh and GWh are energy, not power,
and are ignored."""
out = []
for num, unit in _MW_RE.findall(text):
try:
v = float(num.replace(",", ""))
except ValueError:
continue
v = v * 1000 if unit.lower() == "gw" else v
if v not in out:
out.append(v)
return out
def capacity_corroborates(project_mw, stated: list[float]) -> bool:
return project_mw is not None and any(abs(v - project_mw) <= max(2.0, 0.15 * project_mw) for v in stated)
class ProjectIndex:
"""Distinctive-name index over every REPD record of one release."""
def __init__(self, snapshot: dict):
self.records = {}
self.by_first = {}
groups = development_groups(snapshot)
self.planning_refs = {}
for ref, rec in snapshot["by_ref"].items():
t = lambda c: repd.collapse(rec.get(c, "")) # noqa: E731
r = {
"ref": ref, "site_name": names.site_display(t(repd.SITE)), "technology": t(repd.TECH) or None,
"family": names.tech_family(t(repd.TECH)), "capacity_mw": repd.r3(repd.cap_of(rec)),
"status": t(repd.STATUS) or None, "operator": t(repd.OPER) or None,
"county": t(repd.COUNTY) or None, "region": t(repd.REGION) or None,
"country": t(repd.COUNTRY) or None, "planning_authority": t("Planning Authority") or None,
"planning_application_reference": t("Planning Application Reference") or None,
"storage_colocation_ref": t("Storage Co-location REPD Ref ID") or None,
"group": groups.get(ref, f"DEV-{ref}"),
}
r["aliases"] = names.name_aliases(r["site_name"])
r["full_name"] = names.norm(r["site_name"])
r["operator_tokens"] = names.operator_tokens(r["operator"])
r["location_phrases"] = sorted({names.norm(x) for x in (r["county"], r["planning_authority"])
if x and len(names.norm(x)) >= 4} - {"offshore"})
self.records[ref] = r
for kind in ("primary", "trailing"):
stem = r["aliases"][kind]
if stem:
self.by_first.setdefault(stem.split()[0], []).append((stem, ref, kind))
for stem in r["aliases"]["places"]:
self.by_first.setdefault(stem.split()[0], []).append((stem, ref, "place"))
pref = names.norm(r["planning_application_reference"])
if len(pref.replace(" ", "")) >= 7 and any(ch.isdigit() for ch in pref) and any(ch.isalpha() for ch in pref):
self.planning_refs.setdefault(pref, set()).add(ref)
def name_hits(self, pt: str) -> list[dict]:
hits = {}
for tok in set(pt.split()):
for stem, ref, kind in self.by_first.get(tok, ()):
if not names.contains_phrase(pt, stem):
continue
if " " not in stem and not names.descriptor_adjacent(pt, stem) and \
not names.contains_phrase(pt, self.records[ref]["full_name"]):
continue
key = (ref, stem)
if key not in hits or kind == "primary":
hits[key] = {"ref": ref, "stem": stem, "kind": kind, "spans": names.phrase_spans(pt, stem)}
# drop a name wholly inside a longer matched name of another record
out = []
allh = list(hits.values())
for h in allh:
inside = all(any(o["stem"] != h["stem"] and len(o["stem"]) > len(h["stem"]) and
os <= s and e <= oe for o in allh for os, oe in o["spans"])
for s, e in h["spans"])
if not inside:
out.append(h)
return out
def _foreign(pt: str, source: str) -> list[str]:
ps = names.padded(source)
return sorted({f for f in FOREIGN if names.contains_phrase(pt, f) or names.contains_phrase(ps, f)})
def bind(article: dict, index: ProjectIndex) -> dict:
text = " ".join(filter(None, [article.get("headline"), article.get("description")]))
pt = names.padded(text)
trace = []
stated = news_capacities(text)
ctx = names.tech_context(pt)
event = classify_article_event(text)
foreign = _foreign(pt, article.get("source", ""))
result = {"class": "UNBOUND", "ref": None, "gg_project_id": None, "related_refs": [], "candidates": [],
"evidence": {"stated_mw": stated, "technology_words": sorted(ctx), "foreign_places": foreign,
"article_event": event}, "trace": trace}
# 1. planning application reference
pref_hits = sorted({ref for pref, refs in index.planning_refs.items() if names.contains_phrase(pt, pref) for ref in refs},
key=repd.ref_key)
hits = index.name_hits(pt)
if pref_hits:
trace.append(f"planning reference hit: {pref_hits}")
if not hits and not pref_hits:
trace.append("no REPD distinctive name in text")
return result
cands = {}
for h in hits:
cands.setdefault(h["ref"], []).append(h)
for ref in pref_hits:
cands.setdefault(ref, []).append({"ref": ref, "stem": None, "kind": "planning_reference", "spans": []})
recs = {ref: index.records[ref] for ref in cands}
trace.append(f"name hits: {sorted({(h['stem'], h['kind']) for h in hits})} -> {len(recs)} records")
def devs(rs):
return sorted({r["group"] for r in rs.values()})
initial_devs = devs(recs)
resolved_by = []
if len(pref_hits) == 1 and len(devs({r: recs[r] for r in pref_hits})) == 1:
recs = {pref_hits[0]: recs[pref_hits[0]]}
resolved_by.append("planning_reference")
def narrow(label, keep):
nonlocal recs
kept = {r: v for r, v in recs.items() if keep(v)}
if kept and len(kept) < len(recs):
trace.append(f"{label}: {len(recs)} -> {len(kept)} records")
if len(devs(kept)) < len(devs(recs)):
resolved_by.append(label)
recs = kept
strong_kinds = ("primary", "trailing", "planning_reference")
narrow("name_kind", lambda v: any(h["kind"] in strong_kinds for h in cands[v["ref"]]))
if ctx:
narrow("technology", lambda v: v["family"] in ctx)
cap_ok = {r for r, v in recs.items() if capacity_corroborates(v["capacity_mw"], stated)}
narrow("capacity", lambda v: v["ref"] in cap_ok)
loc_ok = {r for r, v in recs.items() if any(names.contains_phrase(pt, ph) for ph in v["location_phrases"])}
narrow("location", lambda v: v["ref"] in loc_ok)
# operator words that are also part of the site name prove nothing ('Eccles Grid Stability Ltd')
op_ok = {r for r, v in recs.items() if (v["operator_tokens"] - set(v["full_name"].split())) & set(pt.split())}
narrow("operator", lambda v: v["ref"] in op_ok)
before_status = len(devs(recs))
if event == "REFUSED":
narrow("status_preference", lambda v: v["status"] in REFUSAL_STATUSES)
elif event == "NEW_APPLICATION":
narrow("status_preference", lambda v: v["status"] in ("Application Submitted", "Appeal Lodged"))
else:
narrow("status_preference", lambda v: v["status"] in LIVE)
status_resolved = before_status > 1 and len(devs(recs)) == 1
remaining = devs(recs)
result["candidates"] = [{"ref": r, "site_name": v["site_name"], "technology": v["technology"],
"capacity_mw": v["capacity_mw"], "status": v["status"], "county": v["county"]}
for r, v in sorted(recs.items(), key=lambda kv: repd.ref_key(kv[0]))][:12]
if len(remaining) > 1:
result["class"] = "CANDIDATE"
trace.append(f"ambiguous: {len(remaining)} developments remain")
return result
# one development: choose its primary row
def primary_key(v):
fam_pref = 0 if (len(ctx) == 1 and v["family"] in ctx) else 1
return (fam_pref, FAMILY_ORDER.get(v["family"], 9),
-(v["capacity_mw"] if v["capacity_mw"] is not None else -1), repd.ref_key(v["ref"]))
chosen = sorted(recs.values(), key=primary_key)[0]
result["ref"] = chosen["ref"]
result["gg_project_id"] = f"GG2050-REPD-{chosen['ref']}"
result["related_refs"] = sorted((r for r in recs if r != chosen["ref"]), key=repd.ref_key)
kinds = {h["kind"] for h in cands[chosen["ref"]]}
stem = next((h["stem"] for h in cands[chosen["ref"]] if h["stem"]), None)
corroborated = [k for k, ok in (("capacity", chosen["ref"] in cap_ok), ("location", chosen["ref"] in loc_ok),
("operator", chosen["ref"] in op_ok)) if ok]
result["evidence"].update({"matched_name": stem, "name_kinds": sorted(kinds), "corroborated_by": corroborated,
"resolved_by": resolved_by, "initial_developments": len(initial_devs)})
uk_context = any(names.contains_phrase(pt, u) for u in UK_CONTEXT) or \
any(names.contains_phrase(pt, ph) for ph in chosen["location_phrases"])
if foreign and not uk_context:
result["class"] = "CANDIDATE"
trace.append(f"foreign place named without UK context: {foreign}")
elif ctx and chosen["family"] not in ctx and chosen["family"] != "other":
result["class"] = "CANDIDATE"
trace.append(f"technology words {sorted(ctx)} contradict project family {chosen['family']}")
elif "planning_reference" in kinds:
result["class"] = "EXACT"
elif not kinds & {"primary", "trailing"}:
result["class"] = "PROBABLE" if corroborated else "CANDIDATE"
trace.append("matched by a place segment only")
elif len(initial_devs) == 1:
result["class"] = "EXACT" if corroborated and stem and " " in stem else "STRONG"
elif status_resolved and not ({"capacity", "location", "operator", "technology"} & set(resolved_by)):
result["class"] = "PROBABLE"
else:
result["class"] = "STRONG"
trace.append(f"class {result['class']}")
return result
# --------------------------------------------------------------------------- data centres
class DatacentreIndex:
def __init__(self, geojson_path):
doc = json.loads(Path(geojson_path).read_text(encoding="utf-8"))
self.sites, self.by_first = {}, {}
for f in doc["features"]:
p = f.get("properties") or {}
name = names.clean(p.get("name"))
if not name or names.norm(name).startswith("unnamed"):
continue
stems = set()
for n in [name, *(p.get("aliases") or [])]:
toks = names.norm(n).split()
while toks and toks[0] in DC_BOILERPLATE:
toks.pop(0)
while toks and toks[-1] in DC_BOILERPLATE:
toks.pop()
stem = " ".join(toks)
if stem and (len(toks) >= 2 or (len(stem) >= 6 and stem not in names.GENERIC_SINGLE)):
stems.add(stem)
if not stems:
continue
sid = p.get("id")
self.sites[sid] = {"id": sid, "name": name, "status": p.get("status"),
"precision": (p.get("location") or {}).get("precision"), "stems": sorted(stems)}
for s in stems:
self.by_first.setdefault(s.split()[0], []).append((s, sid))
def bind(self, article: dict) -> dict:
text = " ".join(filter(None, [article.get("headline"), article.get("description")]))
pt = names.padded(text)
topic = any(names.contains_phrase(pt, w) for w in DC_CONTEXT)
out = {"topic_datacentres": topic, "bindings": []}
if not topic:
return out # a site name alone (often a place: 'Hertfordshire') is not a data-centre story
hits = sorted({sid for tok in set(pt.split()) for s, sid in self.by_first.get(tok, ())
if names.contains_phrase(pt, s) and (" " in s or names.descriptor_adjacent(pt, s))})
for sid in hits:
site = self.sites[sid]
cls = "STRONG" if topic and len(hits) == 1 else "CANDIDATE"
out["bindings"].append({"entity_type": "DATA_CENTRE", "id": sid, "name": site["name"],
"status": site["status"], "class": cls})
return out
# --------------------------------------------------------------------------- evaluation
def evaluate(labels: list, index: ProjectIndex) -> dict:
"""Score bind() against a labelled set. gold_ref null = should bind to no project;
label 'unsure' rows are reported but excluded from the metrics."""
rows, per_class = [], {c: {"n": 0, "correct": 0, "wrong_ref": 0, "false_positive": 0} for c in CLASS_ORDER}
sig = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
anyc = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
base = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
def tally(t, predicted, gold):
if predicted and gold and predicted == gold:
t["tp"] += 1
elif predicted:
t["fp"] += 1
if gold:
t["fn"] += 1
elif gold:
t["fn"] += 1
else:
t["tn"] += 1
for lab in labels:
b = bind({"headline": lab["headline"], "source": lab.get("source", ""), "description": lab.get("description")}, index)
row = {"id": lab["id"], "headline": lab["headline"], "gold_ref": lab["gold_ref"], "label": lab["label"],
"class": b["class"], "ref": b["ref"], "baseline_ref": lab.get("baseline_ref"), "trace": b["trace"]}
rows.append(row)
if lab["label"] in ("unsure", "implicit"):
continue
gold = lab["gold_ref"]
pc = per_class[b["class"]]
pc["n"] += 1
if b["ref"]:
if b["ref"] == gold:
pc["correct"] += 1
elif gold:
pc["wrong_ref"] += 1
else:
pc["false_positive"] += 1
tally(sig, b["ref"] if b["class"] in SIGNAL_CLASSES else None, gold)
tally(anyc, b["ref"] if b["class"] != "UNBOUND" else None, gold)
tally(base, lab.get("baseline_ref"), gold)
def metrics(t):
p = t["tp"] / (t["tp"] + t["fp"]) if t["tp"] + t["fp"] else None
r = t["tp"] / (t["tp"] + t["fn"]) if t["tp"] + t["fn"] else None
return {**t, "precision": round(p, 4) if p is not None else None, "recall": round(r, 4) if r is not None else None}
scored = [r for r in rows if r["label"] not in ("unsure", "implicit")]
errors = [r for r in scored if (r["class"] in SIGNAL_CLASSES and r["ref"] != r["gold_ref"]) or
(r["gold_ref"] and r["ref"] != r["gold_ref"])]
return {
"schema": SCHEMA_EVAL,
"n_labels": len(labels), "n_scored": len(scored),
"n_unsure": sum(1 for r in rows if r["label"] == "unsure"),
"n_implicit": sum(1 for r in rows if r["label"] == "implicit"),
"n_positive": sum(1 for r in scored if r["gold_ref"]), "n_negative": sum(1 for r in scored if not r["gold_ref"]),
"signal_classes": list(SIGNAL_CLASSES),
"signal_metrics": metrics(sig),
"any_class_metrics": metrics(anyc),
"baseline_v9_5_1_primary_match_metrics": metrics(base),
"per_class": per_class,
"errors": errors,
"rows": rows,
}
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--repd", required=True)
ap.add_argument("--labels", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args(argv)
index = ProjectIndex(repd.load_csv(a.repd))
labels = json.loads(Path(a.labels).read_text(encoding="utf-8"))["labels"]
ev = evaluate(labels, index)
Path(a.out).write_text(json.dumps(ev, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(json.dumps({k: ev[k] for k in ("signal_metrics", "any_class_metrics", "baseline_v9_5_1_primary_match_metrics")}))
return 0
if __name__ == "__main__":
sys.exit(main())