In this section
- Adapter transform · globalgrid2050 / automation/news/grid_watch/adapter.py lines 1–146
- Government V938 transform · globalgrid2050 / automation/news/grid_watch/government_v938.py lines 1–226
- Names transform · globalgrid2050 / automation/news/names.py lines 1–214
Adapter
A Python module in the grid watch folder of GlobalGrid2050 that builds grid rows (`build_grid_rows`) (units: MW, MVA), using SHA-256.
transformglobalgrid2050 / automation/news/grid_watch/adapter.py · lines 1–146 of 146 · pattern build_grid_rows (shared by 2 files)
- What it does
- It calculates its inputs. Defines 6 functions or classes, including canonical, _timestamp, _text, _source_url, normalise. Uses libraries __future__, datetime, hashlib, json, re.
- 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: News — Grid Watch (globalgrid2050); Government V938 (globalgrid2050). Reached from 6 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- It is built from the canonical step (`canonical`) and the normalise step (`normalise`). Conservative UK electricity-grid evidence adapter for Pipeline News.
- Why it matters
- Imported by News — Grid Watch and Government V938.
- Application
- globalgrid2050 · automation/news/grid_watch · Python module
- Uses
- __future__, datetime, hashlib, json, re, urllib.parse
- Used by
- imported by News — Grid Watch (relative import), imported by Government V938 (relative import)
- Produces
- canonical, normalise, build_grid_rows
- Defines here
- canonical, _timestamp, _text, _source_url, normalise, build_grid_rows
- 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/grid_watch/adapter.py:1-146 · blob 4486009392f21655600ade88642b75417c948a4e · 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 UK electricity-grid evidence adapter for Pipeline News.
Offline, deterministic and dependency-free. Does not fetch, grant reuse rights,
certify a grid connection, or declare any scheme commissioned.
"""
from __future__ import annotations
from datetime import datetime, timezone
from hashlib import sha256
import json
import re
from urllib.parse import urlsplit
STAGES = frozenset({"unknown", "proposed", "consented", "financed", "under_construction", "commissioned"})
OPERATOR_ROLES = frozenset({"system_operator", "transmission_owner", "distribution_operator", "regulator"})
FIELDS = frozenset({"source_id", "source_url", "source_record_id", "source_sha256", "published_at",
"retrieved_at", "scheme_id", "scheme_name", "network_operator", "network_type",
"region", "stage", "reported_metric", "etys_node_code"})
METRIC_UNITS = frozenset({"kV", "km", "MW", "MVA", "GBP"})
METRIC_KINDS = frozenset({"voltage", "route_length", "reported_power", "equipment_rating", "funding_allocation"})
def canonical(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")
def _timestamp(value, *, required=False):
if value is None and not required:
return None
if not isinstance(value, str) or not value.endswith("Z"):
raise ValueError("timestamps must be explicit UTC ISO-8601 Z or null")
try:
date = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError as exc:
raise ValueError("invalid timestamp") from exc
if date.utcoffset() != timezone.utc.utcoffset(date):
raise ValueError("UTC required")
return date.isoformat().replace("+00:00", "Z")
def _text(value, label, *, optional=False):
if value is None and optional:
return None
if not isinstance(value, str) or not value.strip() or len(value) > 240:
raise ValueError(f"invalid {label}")
if any(ord(c) < 32 for c in value):
raise ValueError(f"control character in {label}")
return value.strip()
def _source_url(value, hostname):
if not isinstance(value, str):
raise ValueError("source URL required")
p = urlsplit(value)
if (p.scheme != "https" or p.hostname != hostname or p.username or p.password
or p.port or p.fragment or not p.path.startswith("/")):
raise ValueError("unapproved source URL")
return value
def normalise(record, sources):
"""Accept one explicitly attributed operator notice; do not infer matches.
sources maps registry source_id -> {publisher, operator, role, hostname}.
Returned records are REVIEW_REQUIRED; publishing and rights approval are external gates.
"""
if not isinstance(record, dict) or set(record) - FIELDS:
raise ValueError("unexpected evidence fields")
key = _text(record.get("source_id"), "source id")
source = sources.get(key)
if not isinstance(source, dict) or source.get("role") not in OPERATOR_ROLES:
raise ValueError("unknown official source")
url = _source_url(record.get("source_url"), source["hostname"])
title = _text(record.get("scheme_name"), "scheme name")
operator = _text(record.get("network_operator"), "operator")
if operator != source["operator"]:
raise ValueError("source/operator disagreement")
network_type = record.get("network_type")
if network_type not in ("transmission", "distribution", "system", "regulation"):
raise ValueError("unknown network type")
stage = record.get("stage", "unknown")
if stage not in STAGES:
raise ValueError("unrecognised project stage")
scheme_id = _text(record.get("scheme_id"), "scheme id", optional=True)
source_record_id = _text(record.get("source_record_id"), "record id", optional=True)
region = _text(record.get("region"), "region", optional=True)
source_hash = record.get("source_sha256")
if source_hash is not None and (not isinstance(source_hash, str) or not re.fullmatch(r"[a-f0-9]{64}", source_hash)):
raise ValueError("invalid source byte hash")
licence_state = _text(source.get("licence_state", "UNASSESSED"), "source licence state")
published = _timestamp(record.get("published_at"))
retrieved = _timestamp(record.get("retrieved_at"), required=True)
if published and published > retrieved:
raise ValueError("publication after retrieval")
node = record.get("etys_node_code")
if node is not None and (not isinstance(node, str) or not re.fullmatch(r"[A-Z0-9]{3,12}", node)):
raise ValueError("ETYS reference must be an exact supplied code")
metric = record.get("reported_metric")
if metric is not None:
if not isinstance(metric, dict) or set(metric) != {"value", "unit", "kind"}:
raise ValueError("invalid reported metric structure")
value = metric["value"]
if type(value) not in (int, float) or not 0 <= value < 1e12:
raise ValueError("invalid metric value")
if metric["unit"] not in METRIC_UNITS or metric["kind"] not in METRIC_KINDS:
raise ValueError("metric unit/kind not recognised")
allowed = {"voltage": "kV", "route_length": "km", "reported_power": "MW",
"equipment_rating": "MVA", "funding_allocation": "GBP"}
if allowed[metric["kind"]] != metric["unit"]:
raise ValueError("metric kind/unit mismatch")
fact = {"source_id": key, "url": url, "source_record_id": source_record_id,
"source_sha256": source_hash, "published_at": published,
"scheme_id": scheme_id, "scheme_name": title, "network_operator": operator,
"network_type": network_type, "region": region, "stage": stage,
"reported_metric": metric, "etys_node_code": node}
event_id = sha256(canonical(fact)).hexdigest()
return {
"record_id": "grid:" + event_id[:24],
"scheme": {"name": title, "scheme_id": scheme_id,
"scheme_key": f"{operator}:{scheme_id}" if scheme_id else None,
"operator": operator, "network_type": network_type, "region": region},
"evidence": {"source_id": key, "publisher": source["publisher"], "role": source["role"],
"url": url, "source_record_id": source_record_id,
"source_sha256": source_hash, "published_at": published,
"retrieved_at": retrieved, "reported_stage": stage,
"licence_state": licence_state, "review_state": "REVIEW_REQUIRED"},
"reported_metric": metric,
"links": {"repd_ref": None, "grid_connection": None, "available_capacity_mw": None,
"etys_node_code_as_reported": node, "etys_node_link_verified": False},
"publishable": False,
}
def build_grid_rows(records, sources):
"""Small immutable consumer hook: input records -> sorted one-record-per-evidence rows.
Repeated identical source observations collapse; conflicting reports do not.
The host decides review and visibility. No map coordinates, connectivity or scores.
"""
result = {}
for record in records:
row = normalise(record, sources)
rid = row["record_id"]
if rid not in result or row["evidence"]["retrieved_at"] > result[rid]["evidence"]["retrieved_at"]:
result[rid] = row
return sorted(result.values(), key=lambda r: (r["scheme"]["operator"], r["scheme"]["name"], r["record_id"]))Government V938
A Python module in the grid watch folder of GlobalGrid2050 that builds grid rows (`build_grid_rows`) (units: MW), using SHA-256.
transformglobalgrid2050 / automation/news/grid_watch/government_v938.py · lines 1–226 of 226 · pattern build_grid_rows (shared by 2 files)
- What it does
- It calculates its inputs. Defines _day, _government_receipt, normalise, build_grid_rows, reviewed_government_notice. Uses libraries __future__, datetime, hashlib, re.
- 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 1 file: Test Grid Government V938 (globalgrid2050). Reached from 3 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- It is built from the normalise step (`normalise`) and the reviewed government notice helper (`reviewed_government_notice`). V9.38 additive government-fact extension of the immutable operator adapter.
- Why it matters
- Checked by Test Grid Government V938.
- Application
- globalgrid2050 · automation/news/grid_watch · Python module
- Uses
- Adapter (relative import), __future__, datetime, hashlib, re
- Used by
- imported by Test Grid Government V938 (import)
- Produces
- normalise, build_grid_rows, reviewed_government_notice
- Defines here
- _day, _government_receipt, normalise, build_grid_rows, reviewed_government_notice
- 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/grid_watch/government_v938.py:1-226 · blob 2d74618d3054f524359cd111b649b81162ae55d0 · 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
"""V9.38 additive government-fact extension of the immutable operator adapter.
Offline, deterministic and dependency-free. Does not fetch, grant reuse rights,
certify a grid connection, or declare any scheme commissioned.
"""
from __future__ import annotations
from datetime import date
from hashlib import sha256
import re
from .adapter import (STAGES, OPERATOR_ROLES, FIELDS as OPERATOR_FIELDS,
METRIC_UNITS, METRIC_KINDS as OPERATOR_METRIC_KINDS,
canonical, _timestamp, _text, _source_url,
normalise as normalise_operator)
SOURCE_ROLES = OPERATOR_ROLES | {"government_authority"}
FIELDS = OPERATOR_FIELDS | {"published_date", "event_date", "milestones", "source_receipt"}
METRIC_KINDS = OPERATOR_METRIC_KINDS | {"planned_transmission_upper_bound"}
GOVERNMENT_URLS = frozenset({
"https://www.gov.uk/government/news/sea-link-development-consent-decision-announced",
"https://www.gov.uk/government/publications/sea-link-development-consent-order-planning-act-2008",
})
GOVERNMENT_PUBLISHERS = {
"https://www.gov.uk/government/news/sea-link-development-consent-decision-announced": "Planning Inspectorate",
"https://www.gov.uk/government/publications/sea-link-development-consent-order-planning-act-2008": "Department for Energy Security and Net Zero",
}
FACTS_RIGHTS_SCOPE = "government_html_facts_only_no_images_or_third_party_material"
def _day(value, label):
if value is None:
return None
if (not isinstance(value, dict) or set(value) != {"value", "precision"}
or value["precision"] != "DAY" or not isinstance(value["value"], str)
or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value["value"])):
raise ValueError(f"{label} must be an explicit DAY, not a fabricated midnight instant")
try:
date.fromisoformat(value["value"])
except ValueError as exc:
raise ValueError(f"invalid {label}") from exc
return dict(value)
def _government_receipt(record, source, url, retrieved):
receipt = record.get("source_receipt")
expected = source.get("document_receipt")
if (url not in GOVERNMENT_URLS or source.get("allowed_urls") != [url]
or source.get("publisher") != GOVERNMENT_PUBLISHERS.get(url)
or source.get("reported_operators") != ["NGET"]
or not isinstance(receipt, dict) or receipt != expected
or receipt.get("source_url") != url or receipt.get("http_status") != 200
or not str(receipt.get("content_type", "")).startswith("text/html")
or type(receipt.get("bytes")) is not int or not 0 < receipt["bytes"] <= 1000000
or receipt.get("sha256") != record.get("source_sha256")
or receipt.get("retrieved_at") != retrieved
or receipt.get("licence_url") != "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/"
or not isinstance(receipt.get("licence_evidence"), str)
or "images" not in receipt["licence_evidence"].lower()):
raise ValueError("government fact needs its exact pinned HTML and narrow rights receipt")
return dict(receipt)
def normalise(record, sources):
"""Accept one explicitly attributed operator notice; do not infer matches.
sources maps registry source_id -> {publisher, operator, role, hostname}.
Returned records are REVIEW_REQUIRED; publishing and rights approval are external gates.
"""
if isinstance(record, dict):
source = sources.get(record.get("source_id"))
if isinstance(source, dict) and source.get("role") != "government_authority":
return normalise_operator(record, sources)
if not isinstance(record, dict) or set(record) - FIELDS:
raise ValueError("unexpected evidence fields")
key = _text(record.get("source_id"), "source id")
source = sources.get(key)
if not isinstance(source, dict) or source.get("role") not in SOURCE_ROLES:
raise ValueError("unknown official source")
url = _source_url(record.get("source_url"), source["hostname"])
title = _text(record.get("scheme_name"), "scheme name")
operator = _text(record.get("network_operator"), "operator")
government = source["role"] == "government_authority"
if (government and (source.get("operator") is not None or operator != "NGET" or operator not in source.get("reported_operators", []))
or not government and operator != source["operator"]):
raise ValueError("source/operator disagreement")
network_type = record.get("network_type")
if network_type not in ("transmission", "distribution", "system", "regulation"):
raise ValueError("unknown network type")
stage = record.get("stage", "unknown")
if stage not in STAGES:
raise ValueError("unrecognised project stage")
scheme_id = _text(record.get("scheme_id"), "scheme id", optional=True)
source_record_id = _text(record.get("source_record_id"), "record id", optional=True)
region = _text(record.get("region"), "region", optional=True)
source_hash = record.get("source_sha256")
if source_hash is not None and (not isinstance(source_hash, str) or not re.fullmatch(r"[a-f0-9]{64}", source_hash)):
raise ValueError("invalid source byte hash")
licence_state = _text(source.get("licence_state", "UNASSESSED"), "source licence state")
published = _timestamp(record.get("published_at"))
retrieved = _timestamp(record.get("retrieved_at"), required=True)
published_date, event_date = _day(record.get("published_date"), "publication date"), _day(record.get("event_date"), "event date")
if published_date and published or government and (published or not published_date or not event_date):
raise ValueError("government publication/event clocks require separately recorded DAY precision")
for clock in (published_date, event_date):
if clock and clock["value"] > retrieved[:10]:
raise ValueError("source date after retrieval")
milestones = record.get("milestones")
if milestones is not None:
if not isinstance(milestones, dict) or set(milestones) - {"application_submitted", "accepted_for_examination", "recommendation"}:
raise ValueError("unrecognised milestone clocks")
milestones = {key: _day(value, key) for key, value in milestones.items()}
if any(value and value["value"] > retrieved[:10] for value in milestones.values()):
raise ValueError("milestone after retrieval")
receipt = _government_receipt(record, source, url, retrieved) if government else None
if not government and record.get("source_receipt") is not None:
raise ValueError("unreviewed operator notice cannot claim government fact rights")
if published and published > retrieved:
raise ValueError("publication after retrieval")
node = record.get("etys_node_code")
if node is not None and (not isinstance(node, str) or not re.fullmatch(r"[A-Z0-9]{3,12}", node)):
raise ValueError("ETYS reference must be an exact supplied code")
metric = record.get("reported_metric")
if metric is not None:
if not isinstance(metric, dict) or set(metric) != {"value", "unit", "kind"}:
raise ValueError("invalid reported metric structure")
value = metric["value"]
if type(value) not in (int, float) or not 0 <= value < 1e12:
raise ValueError("invalid metric value")
if metric["unit"] not in METRIC_UNITS or metric["kind"] not in METRIC_KINDS:
raise ValueError("metric unit/kind not recognised")
allowed = {"voltage": "kV", "route_length": "km", "reported_power": "MW",
"equipment_rating": "MVA", "funding_allocation": "GBP", "planned_transmission_upper_bound": "MW"}
if allowed[metric["kind"]] != metric["unit"]:
raise ValueError("metric kind/unit mismatch")
fact = {"source_id": key, "url": url, "source_record_id": source_record_id,
"source_sha256": source_hash, "published_at": published,
"scheme_id": scheme_id, "scheme_name": title, "network_operator": operator,
"network_type": network_type, "region": region, "stage": stage,
"reported_metric": metric, "etys_node_code": node}
if government:
fact.update(published_date=published_date, event_date=event_date, milestones=milestones)
event_id = sha256(canonical(fact)).hexdigest()
return {
"record_id": "grid:" + event_id[:24],
"scheme": {"name": title, "scheme_id": scheme_id,
"scheme_key": f"{operator}:{scheme_id}" if scheme_id and not government else None,
"operator": operator, "network_type": network_type, "region": region},
"evidence": {"source_id": key, "publisher": source["publisher"], "role": source["role"],
"url": url, "source_record_id": source_record_id,
"source_sha256": source_hash, "published_at": published,
"retrieved_at": retrieved, "reported_stage": stage,
"licence_state": licence_state, "review_state": "REVIEW_REQUIRED",
**({"published_date": published_date, "event_date": event_date,
"milestones": milestones, "source_receipt": receipt} if government else {})},
"reported_metric": metric,
"links": {"repd_ref": None, "grid_connection": None, "available_capacity_mw": None,
"etys_node_code_as_reported": node, "etys_node_link_verified": False},
"publishable": False,
}
def build_grid_rows(records, sources):
"""Small immutable consumer hook: input records -> sorted one-record-per-evidence rows.
Repeated identical source observations collapse; conflicting reports do not.
The host decides review and visibility. No map coordinates, connectivity or scores.
"""
result = {}
for record in records:
row = normalise(record, sources)
rid = row["record_id"]
if rid not in result or row["evidence"]["retrieved_at"] > result[rid]["evidence"]["retrieved_at"]:
result[rid] = row
return sorted(result.values(), key=lambda r: (r["scheme"]["operator"], r["scheme"]["name"], r["record_id"]))
def reviewed_government_notice(rows, approval=None):
"""One tightly bounded factual notice, hidden until independent rights reviews.
Review references are auditable workflow inputs, not authentication or a grant
of rights by this function. Ordinary operator rows never become publishable.
"""
if (not isinstance(rows, list) or len(rows) != 2
or {r.get("evidence", {}).get("url") for r in rows} != GOVERNMENT_URLS):
raise ValueError("Sea Link needs both exact government documents")
for row in rows:
evidence, scheme, links = row["evidence"], row["scheme"], row["links"]
if (evidence["role"] != "government_authority" or evidence["publisher"] != GOVERNMENT_PUBLISHERS[evidence["url"]]
or evidence["licence_state"] not in {"OGL_V3_FACTS_REVIEW_REQUIRED", "OGL_V3_FACTS_REVIEWED"}
or scheme["operator"] != "NGET" or scheme["scheme_id"] != "EN020026" or scheme["scheme_key"] is not None
or evidence["reported_stage"] != "consented" or evidence["event_date"] != {"value": "2026-10-30", "precision": "DAY"}
or evidence["published_date"] != {"value": "2026-10-30", "precision": "DAY"}
or evidence["published_at"] is not None or any(links[key] is not None for key in ("repd_ref", "grid_connection", "available_capacity_mw"))):
raise ValueError("unreviewed identity, clock, attribution or connection claim")
facts = {
"notice_id": "government:EN020026:consented:2026-10-30", "scheme": "Sea Link", "application_ref": "EN020026",
"reported_network_operator": "NGET", "reported_stage": "consented",
"event_date": {"value": "2026-10-30", "precision": "DAY"},
"description": "Proposed Suffolk-Kent high voltage direct current transmission link",
"planned_metric": {"value": 2000, "unit": "MW", "kind": "planned_transmission_upper_bound"},
"current_capacity_mw": None, "commissioned": None, "connection": None, "repd_ref": None, "coordinates": None,
"documents": [{"record_id": row["record_id"], **row["evidence"]} for row in sorted(rows, key=lambda r: r["evidence"]["url"])],
}
metrics = [row["reported_metric"] for row in rows if row["reported_metric"] is not None]
if metrics != [facts["planned_metric"]]:
raise ValueError("planned upper bound must remain source-qualified, not current capacity")
digest = sha256(canonical(facts)).hexdigest()
accepted = False
if approval is not None:
reviews = approval.get("reviews") if isinstance(approval, dict) else None
accepted = (isinstance(approval, dict) and set(approval) == {"state", "rights_scope", "facts_sha256", "reviews"}
and approval["state"] == "APPROVED_FACTS_ONLY" and approval["rights_scope"] == FACTS_RIGHTS_SCOPE
and approval["facts_sha256"] == digest and isinstance(reviews, list) and len(reviews) == 2
and {r.get("role") for r in reviews if isinstance(r, dict)} == {"AGENT_A", "AGENT_B"}
and all(isinstance(r, dict) and set(r) == {"role", "decision", "reference"} and r["decision"] == "PASS"
and isinstance(r["reference"], str)
and re.fullmatch(r"https://github\.com/Ventusltd/neural-link-between-agents/issues/42#issuecomment-\d+", r["reference"]) for r in reviews)
and len({r["reference"] for r in reviews}) == 2)
if not accepted:
raise ValueError("narrow two-review fact-rights approval missing or mismatched")
return {"schema": "globalgrid2050.reviewed-grid-notice.v1", "facts_sha256": digest, "facts": facts,
"approval": approval, "publishable": bool(accepted),
"review_state": "NARROW_FACTS_REVIEWED" if accepted else "REVIEW_REQUIRED",
"notice_count": 1 if accepted else None, "document_count": 2,
"limitations": "Government facts only; no images or third-party content, no current capacity/commissioning/connection, no REPD/ETYS join or coordinates, no interconnector row or VERIFIED association"}Names
A Python module in the news folder of GlobalGrid2050 that works with solar, wind, battery storage (BESS) and the Renewable Energy Planning Database (REPD) register.
transformglobalgrid2050 / automation/news/names.py · lines 1–214 of 214 · pattern descriptor_adjacent (shared by 2 files)
- What it does
- It calculates solar, wind, battery storage (BESS) and the REPD register. Defines 16 functions or classes, including clean, norm, padded, contains_phrase, phrase_spans. Uses libraries __future__, re.
- 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, wind, battery storage (BESS), the REPD register.
- Downstream impact
- Used directly by 5 files: Binder (globalgrid2050); Events (globalgrid2050); Pipeline Headlines (globalgrid2050); Relevance (globalgrid2050); and 1 more. Reached from 25 other entry points, including GlobalGrid2050 Agent7 V922 CI Workflow (globalgrid2050); GlobalGrid2050 Pipeline Headlines Workflow (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050).
- What it achieves
- It is built from the clean step (`clean`), the norm step (`norm`) and the padded step (`padded`). One shared name normalisation for events, binder and relevance.
- Why it matters
- Imported by 4 files, including Binder, Events and Pipeline Headlines. Checked by Test Names.
- Application
- globalgrid2050 · automation/news · Python module
- Uses
- __future__, re
- Used by
- imported by Binder (import), imported by Events (import), imported by Pipeline Headlines (import), imported by Relevance (import), imported by Test Names (import)
- Produces
- clean, norm, padded, contains_phrase, phrase_spans, segments, distinctive_stem, name_aliases, descriptor_adjacent, tech_context, tech_family, operator_key
- Defines here
- clean, norm, padded, contains_phrase, phrase_spans, _strip_boilerplate, _stem_of, segments, distinctive_stem, name_aliases, descriptor_adjacent, tech_context, tech_family, operator_key, operator_tokens, site_display
- 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/names.py:1-214 · blob b608b7964176a1335890dfa7a578de2c8ee6235c · 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
"""automation/news/names.py - one shared name normalisation for events, binder and relevance.
Every module in automation/news that compares a project name, an operator or a headline uses
these functions, so a REPD site name, a news headline and a previous feed entry are reduced
the same way. The rules follow the matcher already in the repository
(scripts/major_project_news_v6.py: norm, distinctive_name_stem, descriptor_adjacent) and are
restated here as a pure, importable module so that frozen file is never imported or edited.
Standard library only.
"""
from __future__ import annotations
import re
_WS = re.compile(r"\s+")
_NON_ALNUM = re.compile(r"[^a-z0-9]+")
# REPD site names append addresses and technology after commas, spaced dashes or "near".
SEGMENT_SPLIT_RE = re.compile(r"\s+-\s*|\s*-\s+|,|\bnear\b", flags=re.I)
# Words that describe a scheme rather than name it. Stripped from both ends of a stem.
NAME_BOILERPLATE = frozenset({
"solar", "farm", "farms", "park", "parks", "battery", "batteries", "storage", "energy",
"bess", "pv", "photovoltaic", "photovoltaics", "project", "projects", "scheme",
"development", "renewable", "renewables", "power", "station", "substation", "panels",
"panel", "plant", "works", "hub", "facility", "system", "systems", "ltd", "limited",
"plc", "site", "the", "and", "of", "at", "on", "in", "for", "to", "land", "extension",
"array", "units", "unit", "roof", "mounted", "ground", "wind", "windfarm", "turbine",
"turbines", "offshore", "onshore", "proposed", "phase", "1", "2", "3",
"centre", "center", "complex", "installation", "ess", "grid", "services", "mw",
})
# A stem of one of these words alone names nothing (The Grange, Manor Farm, ...).
GENERIC_SINGLE = frozenset({
"grange", "manor", "common", "lodge", "hall", "hill", "fields", "field", "wood", "woods",
"bridge", "bank", "brook", "mill", "moor", "marsh", "meadow", "meadows", "home", "house",
"court", "new", "north", "south", "east", "west", "high", "low", "old", "lane", "road",
"street", "way", "cottage", "barn", "top", "end", "great", "little", "upper", "lower",
"church", "school", "college", "university", "hospital", "business", "industrial",
"estate", "airport", "port", "dock", "quarry", "colliery", "unnamed",
})
# A multi-word stem made only of these words is an address, not a name ('Country Lane', 'New Road').
ADDRESS_ONLY = frozenset({
"lane", "road", "street", "way", "avenue", "drive", "close", "new", "north", "south", "east",
"west", "country", "park", "farm", "place", "high", "low", "old", "upper", "lower", "great",
"little", "main", "station", "the", "industrial", "estate", "business", "trading", "unit",
})
# Technology words that may sit beside a one-token stem in a headline ("Hessay Solar").
DESCRIPTORS = frozenset({
"solar", "pv", "photovoltaic", "battery", "bess", "storage", "energy", "wind", "windfarm",
"renewable", "renewables", "data", "datacentre",
})
TECH_WORDS = {
"solar": frozenset({"solar", "pv", "photovoltaic", "photovoltaics", "mwp"}),
"battery": frozenset({"battery", "batteries", "bess", "storage", "mwh"}),
"wind": frozenset({"wind", "windfarm", "turbine", "turbines"}),
}
LEGAL_SUFFIXES = frozenset({
"ltd", "limited", "plc", "llp", "lp", "inc", "llc", "gmbh", "sa", "bv", "ag", "co",
"company", "the", "and", "uk", "u", "k",
})
def clean(value) -> str:
"""Trim; treat nan/none/null/not set as blank."""
text = "" if value is None else str(value).replace("_x000D_", " ")
text = _WS.sub(" ", text).strip()
return "" if text.lower() in {"nan", "none", "null", "not set"} else text
def norm(value) -> str:
"""Lowercase, '&' to 'and', every non-alphanumeric run to one space."""
text = clean(value).lower().replace("&", " and ")
return _WS.sub(" ", _NON_ALNUM.sub(" ", text)).strip()
def padded(value) -> str:
"""norm() with a leading and trailing space, for whole-phrase containment tests."""
return f" {norm(value)} "
def contains_phrase(padded_text: str, phrase: str) -> bool:
"""True when the normalised phrase occurs on token boundaries in padded_text."""
return bool(phrase) and f" {phrase} " in padded_text
def phrase_spans(padded_text: str, phrase: str) -> list[tuple[int, int]]:
"""Character spans of every token-boundary occurrence of phrase in padded_text."""
if not phrase:
return []
needle = f" {phrase} "
spans, start = [], 0
while True:
i = padded_text.find(needle, start)
if i < 0:
return spans
spans.append((i + 1, i + 1 + len(phrase)))
start = i + 1
def _strip_boilerplate(tokens: list[str]) -> list[str]:
tokens = list(tokens)
while tokens and tokens[0] in NAME_BOILERPLATE:
tokens.pop(0)
while tokens and tokens[-1] in NAME_BOILERPLATE:
tokens.pop()
return tokens
def _stem_of(segment: str) -> str:
tokens = _strip_boilerplate(norm(segment).split())
if not tokens:
return ""
if len(tokens) == 1 and (tokens[0] in GENERIC_SINGLE or len(tokens[0]) < 4 or tokens[0].isdigit()):
return ""
if len(tokens) > 1 and all(t in ADDRESS_ONLY or t.isdigit() for t in tokens):
return ""
return " ".join(tokens)
def segments(site_name) -> list[str]:
return [s for s in (part.strip() for part in SEGMENT_SPLIT_RE.split(clean(site_name))) if s]
def distinctive_stem(site_name) -> str:
"""The leading public identity of a REPD site name, boilerplate stripped at both ends.
'Springwell, Lincoln - Springwell Solar Farm & Battery Storage' -> 'springwell'
'West Burton Power Station, North Road - Battery Storage' -> 'west burton'
'The Grange' -> '' (generic)
"""
parts = segments(site_name)
return _stem_of(parts[0]) if parts else ""
def name_aliases(site_name) -> dict:
"""Stems a headline could use for one REPD site.
primary - stem of the first segment (the usual public name)
trailing - stem of the last segment when it differs (e.g. 'Coalburn II ...' after an address)
places - stems of middle segments (usually a village or road): weak evidence only
"""
parts = segments(site_name)
primary = _stem_of(parts[0]) if parts else ""
trailing = _stem_of(parts[-1]) if len(parts) > 1 else ""
if trailing == primary:
trailing = ""
places = []
for seg in parts[1:-1]:
stem = _stem_of(seg)
if stem and stem not in (primary, trailing) and stem not in places:
places.append(stem)
return {"primary": primary, "trailing": trailing, "places": places}
def descriptor_adjacent(padded_text: str, stem: str) -> bool:
"""A one-token stem must sit right before a technology word ('hessay solar'),
optionally with one short token between ('kells 50mw solar' is not accepted; 'x ii bess' is)."""
if not stem or " " in stem:
return False
tokens = padded_text.split()
unsafe_predecessors = {"the", "on", "of", "at", "in"}
for i, tok in enumerate(tokens):
if tok != stem or (i and tokens[i - 1] in unsafe_predecessors):
continue
if i + 1 < len(tokens) and tokens[i + 1] in DESCRIPTORS:
return True
if i + 2 < len(tokens) and len(tokens[i + 1]) <= 3 and tokens[i + 2] in DESCRIPTORS:
return True
return False
def tech_context(padded_text: str) -> set[str]:
"""Technology families a text mentions: subset of {'solar', 'battery', 'wind'}."""
toks = set(padded_text.split())
return {fam for fam, words in TECH_WORDS.items() if toks & words}
def tech_family(repd_technology) -> str:
t = norm(repd_technology)
if "solar" in t:
return "solar"
if t == "battery" or "storage" in t or "flywheel" in t:
return "battery"
if "wind" in t:
return "wind"
return "other"
def operator_key(value) -> str:
"""Operator reduced for comparing two releases: case, punctuation, connectors and legal
suffixes removed, tokens sorted. 'Photovolt Development Partners / SolarFive' and
'Photovolt Development Partners & SolarFive' give the same key."""
toks = sorted({t for t in norm(value).split() if t not in LEGAL_SUFFIXES})
return " ".join(toks)
def operator_tokens(value) -> set[str]:
"""Distinctive operator tokens (length >= 4, not legal or generic words) for headline hits."""
generic = NAME_BOILERPLATE | LEGAL_SUFFIXES | {"private", "developer", "group", "holdings",
"capital", "partners", "investments", "services",
"international", "global", "europe", "british",
"national", "council", "county", "borough",
"district", "city", "farmers", "estates"}
return {t for t in norm(value).split() if len(t) >= 4 and t not in generic and not t.isdigit()}
def site_display(site_name) -> str:
"""Site name for a headline: whitespace collapsed, nothing else changed."""
return clean(site_name)