In this section
- Monthly Update Interconnectors energy-data · data-interconnectors / pipelines/monthly_update_interconnectors.py lines 1–129
- Data UK Distribution Network Operator (DNO) and Transmission System Operator (TSO) — Index Page render · data_uk_dno_and_tso / index.html lines 1–320
- Build Declared storage · data_uk_dno_and_tso / scripts/build_declared.py lines 1–38
- Fetch CKAN Catalogue storage · data_uk_dno_and_tso / scripts/fetch_ckan_catalogue.py lines 1–71
- Fetch NESO Distribution Network Operator (DNO) Boundaries energy-data · data_uk_dno_and_tso / scripts/fetch_neso_dno_boundaries.py lines 1–14
- Fetch Ods Catalogue storage · data_uk_dno_and_tso / scripts/fetch_ods_catalogue.py lines 1–69
- Audit storage · data_uk_dno_and_tso / scripts/lib/audit.py lines 1–26
Monthly Update Interconnectors
A Python command-line tool in the pipelines folder of Data Interconnectors that reads interconnectors. It resolves month range (`resolve_month_range`).
energy-datadata-interconnectors / pipelines/monthly_update_interconnectors.py · lines 1–129 of 129 · Entry point · pattern shift_month (shared by 2 files)
- What it does
- It loads interconnectors. Defines month_text, shift_month, existing_flow_files, resolve_month_range, main. Uses libraries __future__, argparse, json, pathlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'interconnectors'): 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: interconnectors.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Gridbot UK Interconnector Build Workflow (data-interconnectors).
- What it achieves
- Defines `month_text`, `shift_month`, `existing_flow_files` and 1 more. It accepts `--start`, `--end` and `--refetch-months`.
- Why it matters
- Run by Gridbot UK Interconnector Build Workflow.
- Application
- data-interconnectors · pipelines · Python CLI
- Uses
- Build Interconnectors (import), __future__, argparse, json, pathlib
- Used by
- run by Gridbot UK Interconnector Build Workflow (workflow run)
- Produces
- month_text, shift_month, existing_flow_files, resolve_month_range, main
- Defines here
- month_text, shift_month, existing_flow_files, resolve_month_range, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-interconnectors@2bd00d9610f24d02ba00e341216cab162b3e821b pipelines/monthly_update_interconnectors.py:1-129 · blob 5a6f2dadbbfeb6140f912c2a627b3436ea349f5d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
from pathlib import Path
from build_interconnectors import (
API_URL,
CODES,
DEFAULT_INTERVAL_HOURS,
MAX_INFERRED_INTERVAL_HOURS,
METHOD_VERSION,
ROOT,
SOURCE,
build_rollups,
fetch_month,
latest_complete_month,
month_iter,
next_month,
normalise_month,
parse_month,
reconcile,
update_changelog,
utcnow,
verify_output,
write_month,
write_reports,
)
BOOTSTRAP_START_MONTH = "2020-12"
def month_text(year: int, month: int) -> str:
return f"{year:04d}-{month:02d}"
def shift_month(year: int, month: int, offset: int) -> tuple[int, int]:
idx = year * 12 + (month - 1) + offset
return idx // 12, idx % 12 + 1
def existing_flow_files() -> list[Path]:
return list((ROOT / "flows" / "dataset=fuelinst_interconnector").glob("year=*/month=*/*.parquet"))
def resolve_month_range(start: str, end: str, refetch_months: int, bootstrap_start: str) -> tuple[str, str, str]:
end_month = latest_complete_month() if not end or end == "latest-complete" else end
if refetch_months < 1:
raise SystemExit("refetch-months must be >= 1")
if start and start not in {"auto", "latest-complete"}:
return start, end_month, "explicit_month_range"
if not existing_flow_files():
return bootstrap_start, end_month, "bootstrap_full_history_no_existing_parquet"
ey, em = parse_month(end_month)
sy, sm = shift_month(ey, em, -(refetch_months - 1))
return month_text(sy, sm), end_month, f"monthly_refetch_last_{refetch_months}_complete_months"
def main() -> int:
ap = argparse.ArgumentParser(description="Monthly interconnector updater for data-interconnectors")
ap.add_argument("--start", default="auto", help="YYYY-MM or auto. Auto means trailing refetch, or bootstrap if no Parquet exists.")
ap.add_argument("--end", default="latest-complete", help="YYYY-MM or latest-complete")
ap.add_argument("--refetch-months", type=int, default=3, help="Recent complete months to rewrite when start is auto.")
ap.add_argument("--bootstrap-start", default=BOOTSTRAP_START_MONTH)
ap.add_argument("--timeout", type=int, default=120)
ap.add_argument("--monolith-dir", default="_monolith/uk_energy_tracking_v6/generation_history/interconnectors")
ap.add_argument("--fail-on-reconciliation-mismatch", dest="fail_on_reconciliation_mismatch", action="store_true", default=True)
ap.add_argument("--allow-reconciliation-mismatch", dest="fail_on_reconciliation_mismatch", action="store_false")
args = ap.parse_args()
start_month, end_month, selection_mode = resolve_month_range(args.start, args.end, args.refetch_months, args.bootstrap_start)
months = list(month_iter(start_month, end_month))
if not months:
raise RuntimeError("no months selected")
month_reports = []
removed_partitions = []
for year, month in months:
raw = fetch_month(year, month, args.timeout)
rows, meta = normalise_month(year, month, raw)
partition_dir = ROOT / "flows" / "dataset=fuelinst_interconnector" / f"year={year}" / f"month={month}"
if partition_dir.exists():
removed_partitions.append(str(partition_dir))
write_month(rows, year, month)
month_reports.append(meta)
print(f"{year:04d}-{month:02d}: api={meta['apiRows']} interconnector={meta['interconnectorRows']} codes={','.join(meta['codesPresent'])} intervals={meta['intervalSourceCounts']}")
rollups = build_rollups()
verification = verify_output(end_month)
reconciliation = reconcile(ROOT / args.monolith_dir)
report = {
"generatedUTC": utcnow(),
"mode": "monthly_update",
"selectionMode": selection_mode,
"startMonth": start_month,
"endMonth": end_month,
"targetMonths": [month_text(y, m) for y, m in months],
"removedPartitionsBeforeRewrite": removed_partitions,
"methodVersion": METHOD_VERSION,
"source": SOURCE,
"apiUrl": API_URL,
"signConvention": "positive signed MW is import to GB; negative signed MW is export from GB",
"intervalMethod": "inferred per BMRS code from neighbouring readings; max one hour; default five minutes",
"defaultIntervalHours": DEFAULT_INTERVAL_HOURS,
"maxInferredIntervalHours": MAX_INFERRED_INTERVAL_HOURS,
"operationalCodes": sorted(CODES),
"months": month_reports,
"verification": verification,
"rollups": rollups,
"reconciliation": reconciliation,
}
write_reports(report)
if args.fail_on_reconciliation_mismatch and not reconciliation.get("accuracyProven"):
raise RuntimeError("monolith reconciliation did not prove accuracy; see reports/INTERCONNECTOR_BUILD_LATEST.md")
update_changelog(report)
print(json.dumps(report["verification"], indent=2))
print(json.dumps(report["reconciliation"], indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())Data UK Distribution Network Operator (DNO) and Transmission System Operator (TSO) — Index Page
A web page in Data UK DNO And TSO that draws MPAN distributor, sources, operators schema and transmission ownership.
renderdata_uk_dno_and_tso / index.html · lines 1–320 of 320 · Entry point
- What it does
- It draws mpan distributor, sources, operators schema and transmission ownership. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'dno'): 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: CSV file mpan_distributor.csv; JSON file sources.json; CSV file operators.csv; CSV file transmission_ownership.csv; CSV file department_lineage.csv; JSON file operators.schema.json; DuckDB queries. Out: web page.
- Downstream impact
- It is itself an entry point (page); no other file was found loading it.
- What it achieves
- Canonical public-data spine for UK and Ireland electricity network operators, DNO licence areas, transmission owners, National Energy System Operator (NESO), regulators and government public energy datasets.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- data_uk_dno_and_tso · / · page
- 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
- data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b index.html:1-320 · blob 50bbcaeced644b39038b1a1d17f16245ee9857d2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
<!doctype html>
<html lang="en" data-globalgrid-repo="data_uk_dno_and_tso">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GlobalGrid2050 | UK DNO and TSO Data Spine</title>
<meta name="description" content="Canonical public-data spine for UK and Ireland electricity network operators, DNO licence areas, transmission owners, NESO, regulators and government public energy datasets.">
<meta name="robots" content="index,follow">
<meta name="globalgrid:repo" content="Ventusltd/data_uk_dno_and_tso">
<meta name="globalgrid:repo-role" content="data-spine">
<meta name="globalgrid:domain" content="uk-dno-tso-ireland-network-authorities">
<meta name="globalgrid:schema-version" content="0.1.0">
<meta name="globalgrid:method-state" content="screening">
<meta name="globalgrid:provenance" content="declared-first">
<meta name="globalgrid:spider-node-id" content="Ventusltd/data_uk_dno_and_tso">
<meta name="globalgrid:spider-node-type" content="data_repository">
<meta name="globalgrid:spider-ingest" content="config/sources.json;docs/ARCHITECTURE.md;data/declared/operators.csv;data/declared/mpan_distributor.csv">
<meta name="globalgrid:spider-outgoing" content="atlas-v8;sld-financial-sandbox;uk-energy-generation-history;battery-storage-repos;idno-repos;behind-the-meter;data-federation-spiders">
<meta name="globalgrid:spider-incoming" content="NESO;Ofgem;UK government public data;DNO open data portals;NIUR;CRU;EirGrid;SONI;ESB Networks;NIE Networks">
<style>
:root {
color-scheme: light;
--bg: #ffffff;
--ink: #101418;
--muted: #5f6b76;
--line: #d9e0e7;
--soft: #f5f8fa;
--accent: #0b5cad;
--accent-soft: #eef6ff;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--ink);
font-family: Arial, Helvetica, sans-serif;
line-height: 1.55;
}
main {
max-width: 1040px;
margin: 0 auto;
padding: 56px 24px 80px;
}
header {
border-bottom: 1px solid var(--line);
padding-bottom: 28px;
margin-bottom: 30px;
}
.eyebrow {
color: var(--accent);
font-size: 0.82rem;
letter-spacing: 0.08em;
text-transform: uppercase;
margin-bottom: 12px;
}
h1 {
font-size: clamp(2.1rem, 5vw, 4rem);
line-height: 1.05;
margin: 0 0 18px;
font-weight: 700;
letter-spacing: -0.04em;
}
h2 {
font-size: 1rem;
margin: 34px 0 12px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
p { max-width: 820px; }
.lede {
font-size: 1.08rem;
color: #24303a;
margin-bottom: 0;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
margin: 18px 0 8px;
}
a.card, .card {
display: block;
border: 1px solid var(--line);
border-radius: 14px;
padding: 16px;
text-decoration: none;
color: inherit;
background: #fff;
}
a.card:hover {
border-color: var(--accent);
background: var(--accent-soft);
}
.card strong { display: block; margin-bottom: 5px; }
.card span { color: var(--muted); font-size: 0.92rem; }
.pill-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 20px 0 0;
}
.pill {
border: 1px solid var(--line);
border-radius: 999px;
padding: 7px 10px;
font-size: 0.86rem;
color: #2a3640;
background: var(--soft);
}
code, pre {
font-family: Consolas, Monaco, 'Courier New', monospace;
font-size: 0.92rem;
}
pre {
overflow: auto;
background: var(--soft);
border: 1px solid var(--line);
border-radius: 14px;
padding: 16px;
}
footer {
border-top: 1px solid var(--line);
margin-top: 42px;
padding-top: 18px;
color: var(--muted);
font-size: 0.92rem;
}
</style>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Dataset",
"name": "UK DNO and TSO Data Spine",
"alternateName": "data_uk_dno_and_tso",
"description": "Canonical public-data spine for UK and Ireland electricity network operators, DNO licence areas, transmission owners, NESO, regulators and government public energy datasets.",
"creator": {
"@type": "Organization",
"name": "Ventus Ltd"
},
"isPartOf": {
"@type": "CreativeWork",
"name": "GlobalGrid2050"
},
"codeRepository": "https://github.com/Ventusltd/data_uk_dno_and_tso",
"keywords": [
"GlobalGrid2050",
"DNO",
"TSO",
"NESO",
"Ofgem",
"MPAN",
"electricity distribution",
"transmission owners",
"Ireland electricity networks",
"data federation"
],
"variableMeasured": [
"operator_id",
"mpan_id",
"licence_area",
"jurisdiction",
"regulator_id",
"network_stats",
"source",
"provenance"
],
"distribution": [
{
"@type": "DataDownload",
"name": "Source registry",
"encodingFormat": "application/json",
"contentUrl": "config/sources.json"
},
{
"@type": "DataDownload",
"name": "Declared operators",
"encodingFormat": "text/csv",
"contentUrl": "data/declared/operators.csv"
},
{
"@type": "DataDownload",
"name": "MPAN distributor lookup",
"encodingFormat": "text/csv",
"contentUrl": "data/declared/mpan_distributor.csv"
}
],
"additionalProperty": [
{"@type": "PropertyValue", "name": "globalgrid:spider-node-id", "value": "Ventusltd/data_uk_dno_and_tso"},
{"@type": "PropertyValue", "name": "globalgrid:spider-node-type", "value": "data_repository"},
{"@type": "PropertyValue", "name": "globalgrid:method-state", "value": "screening"},
{"@type": "PropertyValue", "name": "globalgrid:backend-hint", "value": "Read config/sources.json first; use docs/ARCHITECTURE.md for table intent; use data/declared/*.csv for phase-one seed entities; do not treat network_stats_seed.csv as verified published stats."}
]
}
</script>
</head>
<body>
<main>
<header>
<div class="eyebrow">GlobalGrid2050 data spine</div>
<h1>UK DNO and TSO Data Spine</h1>
<p class="lede">A public, declared-first repository for electricity network authorities across Great Britain, Northern Ireland and the Republic of Ireland. It separates operators, owners, licence areas, regulators, public government datasets and future operational network layers.</p>
<div class="pill-row" aria-label="Repository tags">
<span class="pill">DNO</span>
<span class="pill">IDNO</span>
<span class="pill">NESO</span>
<span class="pill">Transmission owners</span>
<span class="pill">MPAN areas</span>
<span class="pill">Ireland networks</span>
<span class="pill">Ofgem</span>
<span class="pill">UK government public data</span>
</div>
</header>
<section>
<h2>Repository purpose</h2>
<p>This repo is designed as a backend data authority for GlobalGrid2050. Heavy analytical truth is intended to live as Parquet, DuckDB is the local query engine, and web applications consume only compact derived JSON or GeoJSON.</p>
</section>
<section>
<h2>Human entry points</h2>
<div class="grid">
<a class="card" href="README.md"><strong>README</strong><span>Repository purpose, folder map and audit gate.</span></a>
<a class="card" href="docs/ARCHITECTURE.md"><strong>Architecture</strong><span>Data layers, core tables, DuckDB and Parquet rules.</span></a>
<a class="card" href="docs/DEFINITIONS.md"><strong>Definitions</strong><span>DNO, IDNO, TO, SO, NESO and provenance terms.</span></a>
<a class="card" href="docs/DATA_SOURCES.md"><strong>Data sources</strong><span>Source classes, licensing rule and attribution approach.</span></a>
<a class="card" href="docs/PHASE_2_DEEP_STUDY_SCOPE.md"><strong>Phase 2 scope</strong><span>Portal mechanics, DFES, LTDS, ECR, headroom and Ireland pass.</span></a>
<a class="card" href="docs/CHANGELOG.md"><strong>Changelog</strong><span>Visible record of repo evolution.</span></a>
</div>
</section>
<section>
<h2>Machine entry points</h2>
<div class="grid" data-globalgrid-spider-entrypoints="true">
<a class="card" href="config/sources.json" data-spider-role="source-registry"><strong>config/sources.json</strong><span>First file for spiders and fetcher orchestration.</span></a>
<a class="card" href="data/declared/operators.csv" data-spider-role="operator-entities"><strong>operators.csv</strong><span>Canonical phase-one operator IDs and roles.</span></a>
<a class="card" href="data/declared/mpan_distributor.csv" data-spider-role="mpan-join-key"><strong>mpan_distributor.csv</strong><span>GB licence-area join key for MPAN IDs 10 to 23.</span></a>
<a class="card" href="data/declared/transmission_ownership.csv" data-spider-role="owner-operator-bridge"><strong>transmission_ownership.csv</strong><span>Bridge between system operators and transmission owners.</span></a>
<a class="card" href="data/declared/department_lineage.csv" data-spider-role="government-lineage"><strong>department_lineage.csv</strong><span>DECC, BEIS and DESNZ naming lineage under stable public-data folder logic.</span></a>
<a class="card" href="schemas/operators.schema.json" data-spider-role="schema"><strong>operators.schema.json</strong><span>Machine-readable table contract for operator entities.</span></a>
</div>
</section>
<section id="spider-backend-hints" data-globalgrid-spider-hints="true">
<h2>Backend hints for federation spiders</h2>
<pre>{
"node_id": "Ventusltd/data_uk_dno_and_tso",
"node_type": "data_repository",
"domain": "uk_dno_tso_ireland_network_authorities",
"read_order": [
"config/sources.json",
"docs/ARCHITECTURE.md",
"data/declared/operators.csv",
"data/declared/mpan_distributor.csv",
"data/declared/transmission_ownership.csv",
"data/declared/department_lineage.csv"
],
"truth_layers": {
"declared_seed": "data/declared/",
"generated_json": "build/json/",
"generated_parquet": "build/parquet/",
"audit_receipts": "audit/"
},
"incoming_source_classes": [
"NESO",
"Ofgem",
"UK government public data",
"DNO open data portals",
"NIUR",
"CRU",
"EirGrid",
"SONI",
"ESB Networks",
"NIE Networks"
],
"outgoing_consumers": [
"atlas_v8",
"sld_financial_sandbox",
"uk_energy_generation_history",
"battery_storage_repos",
"idno_repos",
"behind_the_meter",
"data_federation_spiders"
],
"do_not_assume": [
"network_stats_seed.csv contains verified headline stats",
"Ireland data is redistributable before licence clearance",
"NESO is a transmission owner"
]
}</pre>
</section>
<section>
<h2>Current method state</h2>
<p>The current state is <strong>screening</strong>. The repository contains declared seed structure and source registry intent. It should be treated as a clean scaffold until public-source fetchers, licences, hashes and audit receipts promote datasets into verified generated outputs.</p>
</section>
<footer>
<p>The information published here is provided for technical documentation, research and educational purposes. It does not constitute engineering advice, regulatory advice or project-specific design guidance. Electrical infrastructure decisions must be made by appropriately qualified professionals using authoritative project data and applicable standards.</p>
</footer>
</main>
</body>
</html>Build Declared
A Python command-line tool in the scripts folder of Data UK DNO And TSO that reads CSV (`read_csv`).
storagedata_uk_dno_and_tso / scripts/build_declared.py · lines 1–38 of 38 · Entry point · pattern read_csv (shared by 5 files)
- What it does
- It loads data. Defines read_csv, write_json, main. Uses libraries __future__, csv, json, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'dno'): 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: Audit Workflow (data_uk_dno_and_tso).
- What it achieves
- Its name says it builds declared. Defines `read_csv` and `write_json`.
- Why it matters
- Run by Audit Workflow.
- Application
- data_uk_dno_and_tso · scripts · Python CLI
- Uses
- Hashing (import), Audit (import), __future__, csv, json, pathlib
- Used by
- run by Audit Workflow (workflow run)
- Produces
- read_csv, write_json, main
- Defines here
- read_csv, write_json, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b scripts/build_declared.py:1-38 · blob fcaedcf83243db9c58189d15bb4e7e73616376b4 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
from __future__ import annotations
import csv
import json
from pathlib import Path
from lib.hashing import sha256_file
from lib.audit import write_receipts
DECLARED_DIR = Path("data/declared")
BUILD_JSON_DIR = Path("build/json/declared")
def read_csv(path: Path) -> list[dict[str, str]]:
with path.open("r", encoding="utf-8", newline="") as fh:
return list(csv.DictReader(fh))
def write_json(name: str, rows: list[dict[str, str]]) -> Path:
BUILD_JSON_DIR.mkdir(parents=True, exist_ok=True)
out = BUILD_JSON_DIR / f"{name}.json"
out.write_text(json.dumps(rows, indent=2, sort_keys=True) + "\n", encoding="utf-8")
return out
def main() -> int:
outputs: dict[str, str] = {}
for csv_path in sorted(DECLARED_DIR.glob("*.csv")):
rows = read_csv(csv_path)
out = write_json(csv_path.stem, rows)
outputs[str(out)] = sha256_file(out)
write_receipts("build_declared", {"status": "OK", "outputs": outputs})
print(f"Built {len(outputs)} declared JSON outputs")
return 0
if __name__ == "__main__":
raise SystemExit(main())Fetch CKAN Catalogue
A Python command-line tool in the scripts folder of Data UK DNO And TSO that reads sources, using SHA-256.
storagedata_uk_dno_and_tso / scripts/fetch_ckan_catalogue.py · lines 1–71 of 71 · Entry point · pattern load_sources (shared by 3 files)
- What it does
- It loads sources. Defines load_sources, portal_base_from_action_url, main. Uses libraries __future__, argparse, json, pathlib, urllib.parse. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'dno'): 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 sources.json; JSON file catalogue.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Its name says it fetches CKAN catalogue. Defines `load_sources` and `portal_base_from_action_url`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- data_uk_dno_and_tso · scripts · Python CLI
- Uses
- Audit (import), CKAN (import), Hashing (import), __future__, argparse, json, pathlib, urllib.parse
- Used by
- none found
- Produces
- load_sources, portal_base_from_action_url, main
- Defines here
- load_sources, portal_base_from_action_url, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b scripts/fetch_ckan_catalogue.py:1-71 · blob 4268faadac1d1c21015ac35b1d9b9ea98536b88a · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
from __future__ import annotations
import argparse
import json
from pathlib import Path
from urllib.parse import urlparse
from lib.audit import write_receipts
from lib.ckan import CKANPortal, get_action
from lib.hashing import sha256_file
ROOT = Path(__file__).resolve().parents[1]
SOURCES = ROOT / "config" / "sources.json"
def load_sources() -> list[dict]:
return json.loads(SOURCES.read_text(encoding="utf-8"))["sources"]
def portal_base_from_action_url(url: str) -> str:
parsed = urlparse(url)
marker = "/api/3/action"
base_path = parsed.path.split(marker)[0] if marker in parsed.path else ""
return f"{parsed.scheme}://{parsed.netloc}{base_path}"
def main() -> int:
parser = argparse.ArgumentParser(description="Fetch CKAN package_list catalogue metadata for one configured source.")
parser.add_argument("source_id")
args = parser.parse_args()
sources = {s["source_id"]: s for s in load_sources()}
source = sources.get(args.source_id)
if not source:
raise SystemExit(f"Unknown source_id: {args.source_id}")
if source.get("portal_family") != "ckan":
raise SystemExit(f"Source is not ckan: {args.source_id}")
if not source.get("candidate_urls"):
raise SystemExit(f"No candidate URLs for source: {args.source_id}")
working_url = source["candidate_urls"][0]
portal = CKANPortal(
base_url=portal_base_from_action_url(working_url),
api_key_env=None,
min_delay_seconds=float(source.get("min_delay_seconds", 1.0)),
)
payload = get_action(portal, "package_list")
out_dir = ROOT / source.get("target", f"audit/source_catalogues/{args.source_id}/")
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / "catalogue.json"
out_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
result = payload.get("result", []) if isinstance(payload, dict) else []
write_receipts(
"fetch_ckan_catalogue",
{
"status": "OK" if payload.get("success") else "DEGRADED",
"source_id": args.source_id,
"working_url": working_url,
"output": str(out_path),
"sha256": sha256_file(out_path),
"package_count_hint": len(result) if isinstance(result, list) else None,
},
)
print(f"Fetched CKAN catalogue for {args.source_id}: {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())Fetch NESO Distribution Network Operator (DNO) Boundaries
A Python command-line tool in the scripts folder of Data UK DNO And TSO that uses EPSG:27700 and EPSG:4326.
energy-datadata_uk_dno_and_tso / scripts/fetch_neso_dno_boundaries.py · lines 1–14 of 14 · Entry point
- What it does
- It calculates its inputs. Defines main. Uses libraries __future__.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'dno'): 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
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Its name says it fetches NESO DNO boundaries.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- data_uk_dno_and_tso · scripts · Python CLI
- Uses
- __future__
- Used by
- none found
- Produces
- main
- Defines here
- main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b scripts/fetch_neso_dno_boundaries.py:1-14 · blob 966f4ac3342659128a0299a53fa0178ddd3ab253 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
from __future__ import annotations
def main() -> int:
print(
"Fetcher placeholder only. Phase 2 must implement CKAN resource discovery, "
"licence capture, EPSG:27700 to EPSG:4326 reprojection, RFC 7946 validation, "
"and audit receipts before this script writes redistributed data."
)
return 0
if __name__ == "__main__":
raise SystemExit(main())Fetch Ods Catalogue
A Python command-line tool in the scripts folder of Data UK DNO And TSO that reads sources, using SHA-256.
storagedata_uk_dno_and_tso / scripts/fetch_ods_catalogue.py · lines 1–69 of 69 · Entry point · pattern load_sources (shared by 3 files)
- What it does
- It loads sources. Defines load_sources, portal_base_from_catalogue_url, main. Uses libraries __future__, argparse, json, pathlib, urllib.parse. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'dno'): 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 sources.json; JSON file catalogue.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Its name says it fetches ods catalogue. Defines `load_sources` and `portal_base_from_catalogue_url`. It accepts `--limit`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- data_uk_dno_and_tso · scripts · Python CLI
- Uses
- Audit (import), Hashing (import), Opendatasoft (import), __future__, argparse, json, pathlib, urllib.parse
- Used by
- none found
- Produces
- load_sources, portal_base_from_catalogue_url, main
- Defines here
- load_sources, portal_base_from_catalogue_url, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b scripts/fetch_ods_catalogue.py:1-69 · blob e16c74e3688dcd7fda1ef44b02ff86e9445891d7 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
from __future__ import annotations
import argparse
import json
from pathlib import Path
from urllib.parse import urlparse
from lib.audit import write_receipts
from lib.hashing import sha256_file
from lib.opendatasoft import ODSPortal, list_datasets
ROOT = Path(__file__).resolve().parents[1]
SOURCES = ROOT / "config" / "sources.json"
def load_sources() -> list[dict]:
return json.loads(SOURCES.read_text(encoding="utf-8"))["sources"]
def portal_base_from_catalogue_url(url: str) -> str:
parsed = urlparse(url)
return f"{parsed.scheme}://{parsed.netloc}"
def main() -> int:
parser = argparse.ArgumentParser(description="Fetch OpenDataSoft catalogue metadata for one configured source.")
parser.add_argument("source_id")
parser.add_argument("--limit", type=int, default=100)
args = parser.parse_args()
sources = {s["source_id"]: s for s in load_sources()}
source = sources.get(args.source_id)
if not source:
raise SystemExit(f"Unknown source_id: {args.source_id}")
if source.get("portal_family") != "opendatasoft":
raise SystemExit(f"Source is not opendatasoft: {args.source_id}")
if not source.get("candidate_urls"):
raise SystemExit(f"No candidate URLs for source: {args.source_id}")
working_url = source["candidate_urls"][0]
portal = ODSPortal(
base_url=portal_base_from_catalogue_url(working_url),
api_key_env=source.get("api_key_env"),
)
payload = list_datasets(portal, limit=args.limit)
out_dir = ROOT / source.get("target", f"audit/source_catalogues/{args.source_id}/")
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / "catalogue.json"
out_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
write_receipts(
"fetch_ods_catalogue",
{
"status": "OK",
"source_id": args.source_id,
"working_url": working_url,
"output": str(out_path),
"sha256": sha256_file(out_path),
"dataset_count_hint": len(payload.get("results", [])) if isinstance(payload, dict) else None,
},
)
print(f"Fetched ODS catalogue for {args.source_id}: {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())Audit
A Python module in the scripts folder of Data UK DNO And TSO that writes receipts (`write_receipts`).
storagedata_uk_dno_and_tso / scripts/lib/audit.py · lines 1–26 of 26 · pattern utc_now (shared by 43 files)
- What it does
- Defines utc_now, write_receipts. Uses libraries __future__, json, datetime, pathlib, typing. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'dno'): 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 3 files: Build Declared (data_uk_dno_and_tso); Fetch CKAN Catalogue (data_uk_dno_and_tso); Fetch Ods Catalogue (data_uk_dno_and_tso). Reached from 1 other entry point, including Audit Workflow (data_uk_dno_and_tso).
- What it achieves
- Defines `utc_now` and `write_receipts`.
- Why it matters
- Imported by Build Declared, Fetch CKAN Catalogue and Fetch Ods Catalogue.
- Application
- data_uk_dno_and_tso · scripts/lib · Python module
- Uses
- __future__, json, datetime, pathlib, typing
- Used by
- imported by Build Declared (import), imported by Fetch CKAN Catalogue (import), imported by Fetch Ods Catalogue (import)
- Produces
- utc_now, write_receipts
- Defines here
- utc_now, write_receipts
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b scripts/lib/audit.py:1-26 · blob 3aa58dd7d3bd8b30d32330b54a2e0fac78df23c2 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
def utc_now() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
def write_receipts(run_name: str, payload: dict[str, Any]) -> None:
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
out_dir = Path("audit") / run_name
out_dir.mkdir(parents=True, exist_ok=True)
json_path = out_dir / f"{stamp}.json"
md_path = out_dir / f"{stamp}.md"
payload = {"run_name": run_name, "created_at": utc_now(), **payload}
json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
lines = [f"# {run_name} audit receipt", "", f"Created: {payload['created_at']}", ""]
for key, value in payload.items():
if key == "created_at":
continue
lines.append(f"- {key}: `{value}`")
md_path.write_text("\n".join(lines) + "\n", encoding="utf-8")