GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / data-centres-gb / /

Lanes and 7 more files

A Python module in the assetpipe folder of Data Grid GB that runs commands (`run_commands`), fetches inputs (`fetch_inputs`) and reads manifest (`read_manifest`), using SHA-256.

698 lines of Python and HTML from data-centres-gb, data-grid-gb, in 8 files. Topic: Websites and apps. Section 1879 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Data Centres GB — App ingest · data-centres-gb / app.py lines 1–116
  2. Data Centres GB — Index Page render · data-centres-gb / index.html lines 1–103
  3. Data Grid GB — Assetpipe other · data-grid-gb / assetpipe/__init__.py lines 1–20
  4. Lanes storage · data-grid-gb / assetpipe/lanes.py lines 1–233
  5. Schema transform · data-grid-gb / assetpipe/schema.py lines 1–188
  6. Xlsx transform · data-grid-gb / assetpipe/xlsx.py lines 1–36
  7. Data Grid GB — Conventional other · data-grid-gb / conventional/__init__.py lines 1–1
  8. Conventional — Fetchers other · data-grid-gb / conventional/fetchers/__init__.py lines 1–1

Data Centres GB — App

A Python module that reads OSM centres. It is built from the root step (`root`), the health step (`health`) and the sources step (`sources`).

ingestdata-centres-gb / app.py · lines 1–116 of 116 · Entry point · pattern sources (shared by 6 files)

What it does
It loads OSM centres. Defines 7 functions or classes, including utc_now, available_exports, load_export, root, health. Uses libraries __future__, json, re, datetime, pathlib. Side effects: reads or writes files.
Downstream impact
Used directly by 41 files: CI Workflow (data-centres-gb); GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); Data Centres GB — Index Page (data-centres-gb); Homepage Versions — GlobalGrid2050 Page (globalgrid2050, https://globalgrid2050.com/homepage_versions/202608291526-globalgrid2050/); and 37 more. Reached from 85 other entry points, including GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html).
What it achieves
Defines `utc_now`, `available_exports`, `load_export` and 4 more.
Why it matters
Loaded by the GlobalGrid2050 Historical Builds map page in GlobalGrid2050 at https://globalgrid2050.com/historical_builds.html and 39 other pages. Run by CI Workflow.
Application
data-centres-gb · / · Python module
Uses
__future__, json, re, datetime, pathlib, typing, fastapi
Used by
run by CI Workflow (workflow run), named by URL in GlobalGrid2050 Historical Builds (estate URL), linked from Data Centres GB — Index Page (link), named by URL in Homepage Versions — GlobalGrid2050 Page (estate URL), named by URL in Homepage V002 (estate URL), named by URL in Homepage V003 (estate URL), named by URL in Homepage V004 (estate URL), named by URL in Homepage V005 (estate URL), and 33 more
Produces
utc_now, available_exports, load_export, root, health, sources, data_centres
Defines here
utc_now, available_exports, load_export, root, health, sources, data_centres
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-centres-gb@12c24a653e9d4eb3507857fd6e6d169b2dd1ff63 app.py:1-116 · blob 47c38ada2e981e438efb3777fe07a978ddfe9f56 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
from __future__ import annotations

import json
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

from fastapi import FastAPI, HTTPException, Query

APP_NAME = "Data Centres GB API"
APP_VERSION = "0.2.0"
ROOT = Path(__file__).resolve().parent
GENERATION = re.compile(r"^[0-9]{12}$")
EXPORT_SUFFIX = "-osm-data-centres.geojson"

SOURCE_POLICY = {
    "openstreetmap": {
        "status": "enabled-batch-only",
        "role": "sole facility source",
        "licence": "ODbL-1.0",
        "attribution": "© OpenStreetMap contributors",
        "request_handler_fetches": 0,
    },
    "openinframap": {
        "status": "visual-validation-only",
        "role": "OpenStreetMap renderer, not independent evidence",
        "request_handler_fetches": 0,
    },
    "datacentermap": {
        "status": "prohibited-from-ingestion",
        "role": "human-only market reference",
        "reason": "Current terms prohibit programmatic retrieval and external-database copying",
        "request_handler_fetches": 0,
    },
}

app = FastAPI(
    title=APP_NAME,
    version=APP_VERSION,
    description="Read-only API over deliberately landed OSM-derived candidate exports.",
)


def utc_now() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def available_exports() -> list[tuple[str, Path]]:
    exports: list[tuple[str, Path]] = []
    for path in (ROOT / "exports").glob(f"*{EXPORT_SUFFIX}"):
        generation = path.name.removesuffix(EXPORT_SUFFIX)
        if GENERATION.fullmatch(generation) and path.is_file() and not path.is_symlink():
            exports.append((generation, path))
    return sorted(exports)


def load_export(generation: str | None) -> dict[str, Any]:
    if generation is not None and not GENERATION.fullmatch(generation):
        raise HTTPException(status_code=400, detail="generation must be a 12-digit timestamp")
    exports = available_exports()
    if generation is None:
        if not exports:
            raise HTTPException(
                status_code=404,
                detail="No OSM data-centre export is installed; this API never fetches a source on demand",
            )
        selected_generation, path = exports[-1]
    else:
        selected_generation = generation
        path = ROOT / "exports" / f"{generation}{EXPORT_SUFFIX}"
        if not path.is_file() or path.is_symlink():
            raise HTTPException(status_code=404, detail="Requested generation is not installed")
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError) as exc:
        raise HTTPException(status_code=500, detail="Installed export is unreadable") from exc
    if (
        not isinstance(payload, dict)
        or payload.get("type") != "FeatureCollection"
        or payload.get("generation") != selected_generation
        or payload.get("licence") != "ODbL-1.0"
        or payload.get("attribution") != "© OpenStreetMap contributors"
        or not isinstance(payload.get("features"), list)
    ):
        raise HTTPException(status_code=500, detail="Installed export failed its data-law envelope")
    return payload


@app.get("/")
def root() -> dict[str, Any]:
    return {
        "name": APP_NAME,
        "version": APP_VERSION,
        "status": "candidate-read-only",
        "endpoint": "/v1/data-centres",
        "source_policy": "/v1/data-centres/sources",
        "installed_generations": [generation for generation, _path in available_exports()],
    }


@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok", "time": utc_now()}


@app.get("/v1/data-centres/sources")
def sources() -> dict[str, Any]:
    return {"sources": SOURCE_POLICY, "network_requests_from_api": 0}


@app.get("/v1/data-centres")
def data_centres(
    generation: str | None = Query(default=None, description="12-digit immutable generation")
) -> dict[str, Any]:
    return load_export(generation)

Data Centres GB — Index Page

A web page using data from the data-federation-map-for-GlobalGrid2050-all-repos repository.

renderdata-centres-gb / index.html · lines 1–103 of 103 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Inputs & outputs
Out: web page.
Downstream impact
Used directly by 39 files: GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); Homepage Versions — GlobalGrid2050 Page (globalgrid2050, https://globalgrid2050.com/homepage_versions/202608291526-globalgrid2050/); Homepage V002 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v002.html); Homepage V003 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v003.html); and 35 more. Reached from 85 other entry points, including GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html).
What it achieves
Open data-centre and electricity-demand intelligence for Great Britain. Its code works with 125 GW and 41 GW.
Why it matters
Loaded by the GlobalGrid2050 Historical Builds map page in GlobalGrid2050 at https://globalgrid2050.com/historical_builds.html and 38 other pages.
Application
data-centres-gb · / · page
Uses
Data Centres GB — App (link), Spider Full Po Test (link)
Used by
linked from GlobalGrid2050 Historical Builds (link), linked from Homepage Versions — GlobalGrid2050 Page (link), linked from Homepage V002 (link), linked from Homepage V003 (link), linked from Homepage V004 (link), linked from Homepage V005 (link), linked from Homepage V006 (link), linked from Homepage V007 (link), and 31 more
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-centres-gb@12c24a653e9d4eb3507857fd6e6d169b2dd1ff63 index.html:1-103 · blob 572b42485237a5d7d0cf41619008367b6fbe56d3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: supporting_data
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Open data-centre and electricity-demand intelligence for Great Britain.">
<title>Data Centres GB · GlobalGrid2050</title>
<style>
  :root{
    color-scheme:dark;
    --bg:#0b0d12;
    --panel:#12151c;
    --panel2:#151923;
    --line:#262b36;
    --text:#eef2fb;
    --muted:#9aa3b5;
    --cyan:#00e5ff;
    --green:#53ff4c;
    --amber:#ffcc00;
  }
  *{box-sizing:border-box}
  html{background:var(--bg)}
  body{margin:0;background:radial-gradient(1100px 650px at 50% -10%,rgba(0,229,255,.08),transparent 60%),var(--bg);color:var(--text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;min-height:100vh}
  a{color:var(--cyan);text-decoration:none}
  a:hover{text-decoration:underline}
  .shell{width:min(1040px,calc(100% - 32px));margin:0 auto;padding:28px 0 60px}
  .eyebrow{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.7rem;letter-spacing:.2em;text-transform:uppercase;color:var(--cyan)}
  h1{font-size:clamp(2rem,6vw,4.4rem);line-height:.98;margin:10px 0 18px;letter-spacing:-.04em}
  .lead{max-width:820px;font-size:clamp(1rem,2.2vw,1.3rem);line-height:1.55;color:#cfd6e5}
  .status{display:flex;gap:8px 14px;flex-wrap:wrap;margin:22px 0 34px;font-family:ui-monospace,monospace;font-size:.75rem;text-transform:uppercase;letter-spacing:.08em}
  .pill{border:1px solid var(--line);border-radius:999px;padding:6px 10px;background:rgba(18,21,28,.75)}
  .live{color:var(--green);border-color:rgba(83,255,76,.35)}
  .dev{color:var(--amber);border-color:rgba(255,204,0,.35)}
  .grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
  .card{display:block;border:1px solid var(--line);border-radius:15px;background:linear-gradient(160deg,rgba(255,255,255,.055),rgba(255,255,255,.014));padding:18px;min-height:160px;box-shadow:0 18px 50px rgba(0,0,0,.15)}
  .card:hover{border-color:rgba(0,229,255,.55);text-decoration:none;transform:translateY(-1px)}
  .card small{display:block;font-family:ui-monospace,monospace;text-transform:uppercase;letter-spacing:.13em;color:var(--muted);margin-bottom:10px}
  .card strong{display:block;color:var(--text);font-size:1.2rem;margin-bottom:8px}
  .card span{display:block;color:var(--muted);line-height:1.45}
  .facts{margin:34px 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);padding:22px 0;display:grid;grid-template-columns:repeat(3,1fr);gap:18px}
  .fact b{display:block;color:var(--cyan);font-size:1.55rem}.fact span{color:var(--muted);font-size:.9rem}
  .note{color:var(--muted);line-height:1.55;font-size:.92rem}
  footer{margin-top:46px;padding-top:20px;border-top:1px solid var(--line);color:var(--muted);font-size:.86rem;line-height:1.5}
  @media(max-width:720px){.grid,.facts{grid-template-columns:1fr}.shell{width:min(100% - 24px,1040px);padding-top:20px}.card{min-height:0}}
</style>
</head>
<body>
<main class="shell">
  <div class="eyebrow">Ventus · GlobalGrid2050 · Great Britain</div>
  <h1>Data Centres GB</h1>
  <p class="lead">An independent open-source workstream for mapping data centres, separating every source, and connecting digital-infrastructure demand to the physical electricity grid.</p>

  <div class="status">
    <span class="pill live">Repository live</span>
    <span class="pill dev">API experimental</span>
    <span class="pill">Provenance first</span>
  </div>

  <section class="facts" aria-label="Current public context">
    <div class="fact"><b>564</b><span>UK data centres cited as listed by the BBC, 29 July 2026</span></div>
    <div class="fact"><b>125 GW</b><span>electricity connection capacity requested, up from 41 GW in one year</span></div>
    <div class="fact"><b>£237,500–£712,500/MW</b><span>Ofgem's proposed refundable connection deposit range</span></div>
  </section>

  <section class="grid">
    <a class="card" href="https://github.com/Ventusltd/data-centres-gb">
      <small>Open repository</small>
      <strong>Code, data contracts and development</strong>
      <span>Develop the data-centre layer independently without burying it inside the main GlobalGrid2050 repository.</span>
    </a>
    <a class="card" href="https://github.com/Ventusltd/data-centres-gb/blob/main/app.py">
      <small>Open API</small>
      <strong>Source-separated data adapter</strong>
      <span>FastAPI service with provenance labels, retrieval timestamps, caching and conservative parsing.</span>
    </a>
    <a class="card" href="https://www.datacentermap.com/united-kingdom/london/">
      <small>Source · separate</small>
      <strong>Data Center Map · London</strong>
      <span>Public directory source retained separately rather than silently merged into a single untraceable dataset.</span>
    </a>
    <a class="card" href="https://www.bbc.co.uk/news/articles/c9q90q9qnn2o">
      <small>Context source</small>
      <strong>BBC · grid-connection demand</strong>
      <span>Public context for the rapid increase in connection requests and Ofgem's proposed deposit mechanism.</span>
    </a>
    <a class="card" href="https://globalgrid2050.com/">
      <small>World-grid platform</small>
      <strong>Return to GlobalGrid2050</strong>
      <span>Connect this independent dataset to the wider grid-development, engineering and infrastructure platform.</span>
    </a>
    <a class="card" href="https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/sandbox/spider_full_po_test.html">
      <small>Federation</small>
      <strong>The Spider 🕷</strong>
      <span>Inspect the relationship between this repository, the current homepage, the next homepage and the wider federation.</span>
    </a>
  </section>

  <p class="note">Source records remain source-labelled. Counts, ownership, operational status, coordinates and power demand must not be treated as verified merely because a listing exists. Future sources should be added through separate adapters and reconciled only through explicit evidence rules.</p>

  <footer>Managed by Ventus Ltd as part of GlobalGrid2050. General technical documentation and research only; not formal engineering, planning, commercial or regulatory advice.</footer>
</main>
</body>
</html>

Data Grid GB — Assetpipe

A Python module that uses SHA-256.

otherdata-grid-gb / assetpipe/__init__.py · lines 1–20 of 20

Inputs & outputs
In: Excel file assetpipe.xlsx.
Downstream impact
Used directly by 7 files: Pipeline (data-grid-gb); Fetch Assets (data-grid-gb); Run Lanes (data-grid-gb); CI Verify (data-grid-gb); and 3 more. Reached from 2 other entry points, including Fetch Assets Workflow (data-grid-gb); Test Assets Workflow (data-grid-gb).
What it achieves
Shared, standard-library-only machinery for the two asset pipelines.
Why it matters
Imported by 5 files, including Pipeline, Fetch Assets and Run Lanes. Checked by 2 tests, including Test Assets.
Application
data-grid-gb · assetpipe · Python module
Uses
none found
Used by
imported by Pipeline (relative import), imported by Fetch Assets (import), imported by Run Lanes (import), imported by CI Verify (import), imported by Test Assets (import), imported by Test Lanes (import), imported by Reproduce (import)
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-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 assetpipe/__init__.py:1-20 · blob b8f2c33cf9f098b5cf12fde9a5555bc3d96cf644 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: unknown · users: none · canonical: supporting_data
"""Shared, standard-library-only machinery for the two asset pipelines.

    datacentres/   UK data-centre sites and pipeline entries (GridAtlas issue #73, steps 2-4)
    conventional/  UK conventional generation: gas, coal, oil, nuclear, biomass, EfW, diesel (step 5)

Each domain has the same shape:

    <domain>/sources.json        the source registry: URL, publisher, licence, licence URL,
                                 and whether the source is FULLY OPEN (yes / no / unverified)
    <domain>/fetchers/<id>.py    one module per source (see assetpipe.pipeline.FETCHER_CONTRACT)
    <domain>/raw/<id>/...        raw snapshots exactly as downloaded
    <domain>/raw/MANIFEST.json   url, bytes and sha256 of every raw file (the pin)
    <domain>/normalised/<id>.geojson   one deterministic FeatureCollection per source
    <domain>/normalised/INDEX.json     sha256, count and licence of every normalised output

Nothing in this package needs a third-party module. Spreadsheet sources may use
openpyxl through ``assetpipe.xlsx``, which says clearly when it is missing.
"""

DOMAINS = ("datacentres", "conventional")

Lanes

A Python module in the assetpipe folder of Data Grid GB that runs commands (`run_commands`), fetches inputs (`fetch_inputs`) and reads manifest (`read_manifest`), using SHA-256.

storagedata-grid-gb / assetpipe/lanes.py · lines 1–233 of 233 · pattern read_manifest (shared by 2 files)

What it does
It fetches data. Defines 16 functions or classes, including LaneError, lanes_dir, load_lanes, allowed, uncommitted_inputs. Uses libraries __future__, hashlib, os, shutil, subprocess. Side effects: reads or writes files; makes network requests; starts processes.
Inputs & outputs
In: JSON file lanes.json.
Downstream impact
Used directly by 3 files: Run Lanes (data-grid-gb); Test Lanes (data-grid-gb); Reproduce (data-grid-gb). Reached from 3 other entry points, including Fetch Assets Workflow (data-grid-gb); Test Assets Workflow (data-grid-gb); Test Assets (data-grid-gb).
What it achieves
It is built from the lane error class (`LaneError`), the lanes dir helper (`lanes_dir`) and the allowed step (`allowed`). Vendored lane scripts: run them, pin every file they read or write, and check the pins.
Why it matters
Imported by Run Lanes and Reproduce. Checked by Test Lanes.
Application
data-grid-gb · assetpipe · Python module
Uses
Pipeline (relative import), __future__, hashlib, os, shutil, subprocess, sys, tempfile, urllib.request
Used by
imported by Run Lanes (import), imported by Test Lanes (import), imported by Reproduce (import)
Produces
LaneError, lanes_dir, load_lanes, allowed, uncommitted_inputs, tracked_files, run_commands, fetch_inputs, inputs_present, read_manifest, retrieved_for, write_manifest
Defines here
LaneError, lanes_dir, load_lanes, allowed, uncommitted_inputs, tracked_files, _expand, run_commands, fetch_inputs, inputs_present, read_manifest, retrieved_for, write_manifest, check_manifest, today_utc, copy_tree
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 assetpipe/lanes.py:1-233 · blob 9bf69053e57d2eed21a3434c959faffb58eb4495 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: supporting_data
"""Vendored lane scripts: run them, pin every file they read or write, and check the pins.

The #73 work lanes (DC-A1, A3, A4, A6, A7) delivered standalone, standard-library
scripts, each with its own output schema. They are vendored here unchanged, except
for a marked path-redirect block in DC-A6. ``<domain>/lanes/lanes.json`` describes
how to run each one:

    fetch     commands that use the network (run by the manual fetch workflow)
    build     offline commands that turn the lane's raw snapshots into outputs
    selftest  offline commands that test the lane on synthetic fixtures
    inputs    pinned downloads (url + sha256) a build reads; "commit": false
              means the file is fetched at run time and never committed
    open      yes / no / unverified, with the same meaning as sources.json

Each command is ``[script, arg, ...]`` and runs as ``python -I script args`` with the
lane directory as the working directory. ``{today}`` is the UTC date of this run.
``{retrieved}`` is the date of the lane's last successful fetch, or "unspecified".
``{tmp}`` is a fresh scratch directory, deleted after the command (for self-tests).

``<domain>/lanes/MANIFEST.json`` pins the sha256 and size of every committed file in
every lane directory, and records each lane's last fetch: its date and each
command's exit code. A failed fetch is recorded as a failure and the previous
snapshot is kept. Unknown is never written as zero.
"""
from __future__ import annotations

import hashlib
import os
import shutil
import subprocess
import sys
import tempfile
import urllib.request
from datetime import datetime, timezone
from pathlib import Path

from .pipeline import ROOT, USER_AGENT, canonical_text, read_json, write_text

LANES_SCHEMA = "gb-asset-lanes.v1"
MANIFEST_SCHEMA = "gb-asset-lanes-manifest.v1"
IGNORED_PARTS = {"__pycache__", ".pytest_cache"}
COMMAND_TIMEOUT = 1800


class LaneError(RuntimeError):
    pass


def lanes_dir(domain: str, root: Path = ROOT) -> Path:
    return root / domain / "lanes"


def load_lanes(domain: str, root: Path = ROOT) -> dict:
    path = lanes_dir(domain, root) / "lanes.json"
    doc = read_json(path)
    if doc is None:
        return {"schema": LANES_SCHEMA, "domain": domain, "lanes": []}
    if doc.get("schema") != LANES_SCHEMA or doc.get("domain") != domain:
        raise LaneError(f"{domain}/lanes/lanes.json is not a {LANES_SCHEMA} file for {domain}")
    ids = [lane.get("id") for lane in doc.get("lanes", [])]
    if len(ids) != len(set(ids)) or not all(ids):
        raise LaneError(f"{domain}/lanes/lanes.json: missing or duplicate lane ids")
    return doc


def allowed(lane: dict, include_unverified: bool) -> tuple[bool, str]:
    if lane.get("open") == "yes":
        return True, "fully open"
    if lane.get("open") == "unverified" and include_unverified:
        return True, "licence unverified: included for review only"
    if lane.get("open") == "unverified":
        return False, "licence unverified (use --include-unverified to snapshot it for review)"
    return False, f"not fully open (open: {lane.get('open')})"


def uncommitted_inputs(lane: dict) -> set:
    return {i["file"] for i in lane.get("inputs", []) if not i.get("commit", True)}


def tracked_files(ldir: Path, lane: dict) -> dict:
    """Every committed file in a lane directory: {relative path: (sha256, bytes)}."""
    skip = uncommitted_inputs(lane)
    out = {}
    if not ldir.exists():
        return out
    for path in sorted(ldir.rglob("*")):
        rel = path.relative_to(ldir).as_posix()
        if not path.is_file() or IGNORED_PARTS & set(path.relative_to(ldir).parts) or path.suffix == ".pyc":
            continue
        if rel in skip:
            continue
        data = path.read_bytes()
        out[rel] = (hashlib.sha256(data).hexdigest(), len(data))
    return out


def _expand(arg: str, today: str, retrieved: str, tmp: str) -> str:
    return arg.replace("{today}", today).replace("{retrieved}", retrieved).replace("{tmp}", tmp)


def run_commands(ldir: Path, lane: dict, commands: list, *, today: str, retrieved: str, log=print) -> list:
    env = dict(os.environ)
    for key, value in (lane.get("env") or {}).items():
        env[key] = str(ldir / value) if not os.path.isabs(value) else value
    codes = []
    for command in commands:
        script, *args = command
        if not (ldir / script).exists():
            raise LaneError(f"{lane['id']}: script {script} missing")
        tmp = tempfile.mkdtemp(prefix=f"lane-{lane['id']}-")
        argv = [sys.executable, "-I", script, *[_expand(a, today, retrieved, tmp) for a in args]]
        log(f"  [{lane['id']}] $ {' '.join(argv[2:])}")
        try:
            proc = subprocess.run(argv, cwd=ldir, env=env, capture_output=True, text=True, timeout=COMMAND_TIMEOUT)
            code = proc.returncode
            tail = (proc.stdout + proc.stderr).strip().splitlines()[-12:]
        except subprocess.TimeoutExpired:
            code, tail = 124, ["timed out"]
        finally:
            shutil.rmtree(tmp, ignore_errors=True)
        for line in tail:
            log(f"    {line}")
        log(f"  [{lane['id']}] exit {code}")
        codes.append(code)
    return codes


def fetch_inputs(ldir: Path, lane: dict, *, opener=None, log=print) -> None:
    """Download pinned inputs that are not on disk; refuse bytes whose sha256 differs."""
    for item in lane.get("inputs", []):
        path = ldir / item["file"]
        if path.exists():
            if hashlib.sha256(path.read_bytes()).hexdigest() != item["sha256"]:
                raise LaneError(f"{lane['id']}: {item['file']} on disk is not the pinned bytes")
            continue
        if not item.get("url"):
            raise LaneError(f"{lane['id']}: {item['file']} is missing and has no URL")
        if opener is None:
            req = urllib.request.Request(item["url"], headers={"User-Agent": USER_AGENT})
            with urllib.request.urlopen(req, timeout=300) as response:  # noqa: S310 - pinned https URL
                data = response.read()
        else:
            data = opener(item["url"])
        digest = hashlib.sha256(data).hexdigest()
        if digest != item["sha256"]:
            raise LaneError(f"{lane['id']}: {item['url']} returned {digest[:12]}, pinned {item['sha256'][:12]}")
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(data)
        log(f"  [{lane['id']}] input {item['file']} {len(data):,} bytes ok")


def inputs_present(ldir: Path, lane: dict) -> bool:
    return all((ldir / i["file"]).exists() for i in lane.get("inputs", []))


def read_manifest(domain: str, root: Path = ROOT) -> dict:
    return read_json(lanes_dir(domain, root) / "MANIFEST.json",
                     {"schema": MANIFEST_SCHEMA, "domain": domain, "lanes": {}})


def retrieved_for(manifest: dict, lane_id: str) -> str:
    last = (manifest.get("lanes", {}).get(lane_id) or {}).get("last_fetch") or {}
    return last.get("date") if last.get("ok") else "unspecified"


def write_manifest(domain: str, root: Path = ROOT, *, fetches: dict | None = None) -> dict:
    doc = load_lanes(domain, root)
    old = read_manifest(domain, root)
    out = {"schema": MANIFEST_SCHEMA, "domain": domain, "lanes": {}}
    for lane in doc["lanes"]:
        ldir = lanes_dir(domain, root) / lane["id"]
        files = tracked_files(ldir, lane)
        entry = {"files": {rel: {"sha256": h, "bytes": n} for rel, (h, n) in files.items()}}
        last = (fetches or {}).get(lane["id"]) or (old.get("lanes", {}).get(lane["id"]) or {}).get("last_fetch")
        if last:
            entry["last_fetch"] = last
        out["lanes"][lane["id"]] = entry
    write_text(lanes_dir(domain, root) / "MANIFEST.json", canonical_text(out))
    return out


def check_manifest(domain: str, root: Path = ROOT, *, strict_open: bool = True) -> list:
    """Problems with the committed lane files; empty when everything matches its pin."""
    problems = []
    doc = load_lanes(domain, root)
    if not doc["lanes"]:
        return problems
    manifest = read_manifest(domain, root)
    if manifest.get("schema") != MANIFEST_SCHEMA:
        return [f"{domain}/lanes/MANIFEST.json missing or not {MANIFEST_SCHEMA}"]
    listed = set(manifest["lanes"])
    declared = {lane["id"] for lane in doc["lanes"]}
    if listed != declared:
        problems.append(f"MANIFEST lanes {sorted(listed)} != lanes.json {sorted(declared)}")
    for lane in doc["lanes"]:
        lid = lane["id"]
        ldir = lanes_dir(domain, root) / lid
        if lane.get("open") not in ("yes", "no", "unverified"):
            problems.append(f"{lid}: open must be yes/no/unverified")
        if lane.get("open") == "no":
            problems.append(f"{lid}: a lane that is not fully open may not be vendored")
        for command in lane.get("fetch", []) + lane.get("build", []) + lane.get("selftest", []):
            if not (ldir / command[0]).exists():
                problems.append(f"{lid}: script {command[0]} missing")
        for item in lane.get("inputs", []):
            if item.get("url") and not item["url"].startswith("https://"):
                problems.append(f"{lid}: input {item['file']} URL is not https")
            path = ldir / item["file"]
            if path.exists() and hashlib.sha256(path.read_bytes()).hexdigest() != item["sha256"]:
                problems.append(f"{lid}: input {item['file']} is not the pinned bytes")
        pinned = (manifest["lanes"].get(lid) or {}).get("files", {})
        actual = tracked_files(ldir, lane)
        for rel in sorted(set(pinned) | set(actual)):
            if rel not in actual:
                problems.append(f"{lid}: {rel} is pinned but missing")
            elif rel not in pinned:
                problems.append(f"{lid}: {rel} is on disk without a pin")
            elif (pinned[rel]["sha256"], pinned[rel]["bytes"]) != actual[rel]:
                problems.append(f"{lid}: {rel} does not match its pinned sha256")
        if strict_open and lane.get("open") != "yes":
            present = [o for o in lane.get("outputs", []) if (ldir / o).exists()]
            if present:
                problems.append(f"{lid}: outputs {present} from a source whose licence is {lane.get('open')}; "
                                "confirm the licence (open: yes) before merging")
    return problems


def today_utc() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%d")


def copy_tree(src: Path, dst: Path) -> None:
    shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))

Schema

A Python module in the assetpipe folder of Data Grid GB that works with postcodes. It validates datacentre (`validate_datacentre`), validates conventional (`validate_conventional`) and records feature (`record_to_feature`).

transformdata-grid-gb / assetpipe/schema.py · lines 1–188 of 188

What it does
It calculates postcodes. Defines 6 functions or classes, including _is_number, _check_mw, _check_common, validate_datacentre, validate_conventional. Uses libraries __future__, math, re.
Why it exists in the grid workflow
Domain terms in the code: postcodes.
Downstream impact
Used directly by 3 files: Pipeline (data-grid-gb); CI Verify (data-grid-gb); Test Assets (data-grid-gb). Reached from 6 other entry points, including Fetch Assets Workflow (data-grid-gb); Test Assets Workflow (data-grid-gb); Fetch Assets (data-grid-gb).
What it achieves
Record schemas for the two domains, and validators that return a list of problems.
Why it matters
Imported by Pipeline and CI Verify. Checked by Test Assets.
Application
data-grid-gb · assetpipe · Python module
Uses
__future__, math, re
Used by
imported by Pipeline (relative import), imported by CI Verify (import), imported by Test Assets (import)
Produces
validate_datacentre, validate_conventional, record_to_feature
Defines here
_is_number, _check_mw, _check_common, validate_datacentre, validate_conventional, record_to_feature
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 assetpipe/schema.py:1-188 · blob b12dadb971f163b67d6f0fb2207ef6e1e6e68e7d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: supporting_data
"""Record schemas for the two domains, and validators that return a list of problems.

The rules that matter most are written as code, not prose, so they cannot drift:

- IT load MW and grid connection MW are two separate fields and are never merged.
  A record that carries a bare ``mw``, ``capacity_mw`` or ``power_mw`` on a data
  centre is rejected: nobody downstream could tell which of the two it meant.
- Unknown is ``null``, never ``0``. A zero MW, a zero year or an empty string
  standing in for "not known" is rejected.
- Every record names its source, the source's licence and licence URL, and an
  evidence URL a person can open.
- A pipeline status is a stage in a public process, not a commitment; there is no
  "committed" or "confirmed" status to choose.
- Location precision is stated. A point placed at a postcode or a town centre
  says so, and a record with no location has ``precision: "unknown"`` and no point.
"""
from __future__ import annotations

import math
import re

SCHEMA_DATACENTRE = "gb-datacentre-pipeline-record.v1"
SCHEMA_CONVENTIONAL = "gb-conventional-generation-record.v1"
SCHEMA_COLLECTION = "gb-asset-collection.v1"

DATACENTRE_STATUSES = (
    "operational",
    "under_construction",
    "consented",
    "in_planning",
    "connection_request",
    "announced",
    "unknown",
)
CONVENTIONAL_STATUSES = (
    "operational",
    "mothballed",
    "closed",
    "under_construction",
    "consented",
    "in_planning",
    "unknown",
)
CONVENTIONAL_FUELS = (
    "gas",
    "coal",
    "oil",
    "nuclear",
    "biomass",
    "efw",        # energy from waste
    "diesel",
    "gas_oil_dual",
    "other_thermal",
)
LOCATION_PRECISIONS = (
    "exact",       # a mapped building or site outline / its centroid
    "site",        # a published site point (e.g. a register's grid reference)
    "address",     # geocoded street address
    "postcode",    # postcode centroid
    "locality",    # town or village centre
    "region",      # local authority / region only
    "unknown",     # no location; geometry is null
)
OPEN_VALUES = ("yes", "no", "unverified")

# A rectangle round Great Britain, Northern Ireland and the islands, not the border.
GB_BOUNDS = (-11.0, 49.0, 2.5, 61.5)  # west, south, east, north

FORBIDDEN_DATACENTRE_MW_KEYS = ("mw", "capacity_mw", "power_mw", "load_mw", "demand_mw")
DATE_RE = re.compile(r"^\d{4}(-\d{2}(-\d{2})?)?$")  # year, year-month or full date
URL_RE = re.compile(r"^https://\S+$")
ID_RE = re.compile(r"^[a-z0-9][a-z0-9_.:-]*$")

DATACENTRE_DATE_KEYS = ("announced", "application", "consented", "connection_offer",
                        "energisation", "operational")


def _is_number(value) -> bool:
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)


def _check_mw(rec: dict, key: str, problems: list) -> None:
    if key not in rec:
        problems.append(f"{key} missing (use null when unknown)")
        return
    value = rec[key]
    if value is None:
        return
    if not _is_number(value):
        problems.append(f"{key} is not a number or null: {value!r}")
    elif value <= 0:
        problems.append(f"{key} is {value}: unknown is null, not zero or negative")


def _check_common(rec: dict, problems: list) -> None:
    if not isinstance(rec.get("id"), str) or not ID_RE.match(rec["id"]):
        problems.append(f"id missing or not a lower-case slug: {rec.get('id')!r}")
    for key in ("name", "operator"):
        if key not in rec:
            problems.append(f"{key} missing (use null when unknown)")
        elif rec[key] is not None and (not isinstance(rec[key], str) or not rec[key].strip()):
            problems.append(f"{key} is an empty string; unknown is null")
    source = rec.get("source")
    if not isinstance(source, dict):
        problems.append("source object missing")
    else:
        for key in ("id", "licence", "licence_url", "evidence_url"):
            if not isinstance(source.get(key), str) or not source[key].strip():
                problems.append(f"source.{key} missing")
        for key in ("licence_url", "evidence_url"):
            if isinstance(source.get(key), str) and not URL_RE.match(source[key]):
                problems.append(f"source.{key} is not an https URL: {source[key]!r}")
    location = rec.get("location")
    if not isinstance(location, dict):
        problems.append("location object missing")
        return
    precision = location.get("precision")
    if precision not in LOCATION_PRECISIONS:
        problems.append(f"location.precision {precision!r} not in {LOCATION_PRECISIONS}")
    lon, lat = location.get("lon"), location.get("lat")
    if precision == "unknown":
        if lon is not None or lat is not None:
            problems.append("location.precision is unknown but a point is given")
    else:
        if not (_is_number(lon) and _is_number(lat)):
            problems.append("location.lon/lat missing for a located record")
        else:
            w, s, e, n = GB_BOUNDS
            if not (w <= lon <= e and s <= lat <= n):
                problems.append(f"location ({lon}, {lat}) is outside the GB/NI rectangle")


def validate_datacentre(rec) -> list:
    problems: list = []
    if not isinstance(rec, dict):
        return ["record is not an object"]
    _check_common(rec, problems)
    for key in FORBIDDEN_DATACENTRE_MW_KEYS:
        if key in rec:
            problems.append(f"{key} is ambiguous: use it_load_mw or grid_connection_mw, never both in one field")
    if rec.get("status") not in DATACENTRE_STATUSES:
        problems.append(f"status {rec.get('status')!r} not in {DATACENTRE_STATUSES}")
    _check_mw(rec, "it_load_mw", problems)
    _check_mw(rec, "grid_connection_mw", problems)
    dates = rec.get("dates")
    if not isinstance(dates, dict):
        problems.append("dates object missing (use {} when none are known)")
    else:
        for key, value in dates.items():
            if key not in DATACENTRE_DATE_KEYS:
                problems.append(f"dates.{key} is not one of {DATACENTRE_DATE_KEYS}")
            elif value is not None and (not isinstance(value, str) or not DATE_RE.match(value)):
                problems.append(f"dates.{key} is not YYYY[-MM[-DD]] or null: {value!r}")
    return problems


def validate_conventional(rec) -> list:
    problems: list = []
    if not isinstance(rec, dict):
        return ["record is not an object"]
    _check_common(rec, problems)
    if rec.get("fuel") not in CONVENTIONAL_FUELS:
        problems.append(f"fuel {rec.get('fuel')!r} not in {CONVENTIONAL_FUELS}")
    if rec.get("status") not in CONVENTIONAL_STATUSES:
        problems.append(f"status {rec.get('status')!r} not in {CONVENTIONAL_STATUSES}")
    _check_mw(rec, "capacity_mw", problems)
    if rec.get("capacity_mw") is not None and not (isinstance(rec.get("capacity_basis"), str)
                                                   and rec["capacity_basis"].strip()):
        problems.append("capacity_basis missing: say what the MW is (e.g. 'DUKES installed capacity')")
    year = rec.get("commissioned_year")
    if year is not None and not (isinstance(year, int) and not isinstance(year, bool) and 1880 <= year <= 2100):
        problems.append(f"commissioned_year is not a plausible year or null: {year!r}")
    return problems


VALIDATORS = {
    "datacentres": (SCHEMA_DATACENTRE, validate_datacentre),
    "conventional": (SCHEMA_CONVENTIONAL, validate_conventional),
}


def record_to_feature(rec: dict) -> dict:
    """A record as a GeoJSON Feature; the location block stays in properties too."""
    location = rec.get("location") or {}
    geometry = None
    if location.get("precision") != "unknown" and _is_number(location.get("lon")) and _is_number(location.get("lat")):
        geometry = {"type": "Point", "coordinates": [round(location["lon"], 6), round(location["lat"], 6)]}
    return {"type": "Feature", "id": rec["id"], "geometry": geometry, "properties": rec}

Xlsx

A Python module in the assetpipe folder of Data Grid GB that works with missing dependency (`MissingDependency`) and sheet rows (`sheet_rows`).

transformdata-grid-gb / assetpipe/xlsx.py · lines 1–36 of 36 · pattern available (shared by 2 files)

What it does
It calculates its inputs. Defines MissingDependency, available, sheet_rows. Uses libraries __future__, io, openpyxl.
Downstream impact
Used directly by 2 files: Test Assets (data-grid-gb); Reproduce (data-grid-gb). Reached from 3 other entry points, including Fetch Assets Workflow (data-grid-gb); Test Assets Workflow (data-grid-gb); Test Lanes (data-grid-gb).
What it achieves
It is built from the missing dependency class (`MissingDependency`) and the available step (`available`). Read a worksheet from raw .xlsx bytes (DUKES 5.11 and similar government tables).
Why it matters
Imported by Reproduce. Checked by Test Assets.
Application
data-grid-gb · assetpipe · Python module
Uses
__future__, io, openpyxl
Used by
imported by Test Assets (import), imported by Reproduce (import)
Produces
MissingDependency, available, sheet_rows
Defines here
MissingDependency, available, sheet_rows
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 assetpipe/xlsx.py:1-36 · blob ceee1b1786cd2c1f5c589e17aae5fcf95f57a13d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: supporting_data
"""Read a worksheet from raw .xlsx bytes (DUKES 5.11 and similar government tables).

openpyxl is the only optional dependency of the asset pipelines (requirements.txt).
Fetching, pinning, verifying and reproducing never need it; only a normaliser that
reads a spreadsheet does, and it fails with a clear message when it is absent.
"""
from __future__ import annotations

import io


class MissingDependency(RuntimeError):
    pass


def available() -> bool:
    try:
        import openpyxl  # noqa: F401
    except ImportError:
        return False
    return True


def sheet_rows(data: bytes, sheet: str) -> list:
    """Every row of ``sheet`` as a list of plain values (str, int, float, None)."""
    try:
        import openpyxl
    except ImportError as error:
        raise MissingDependency("reading .xlsx sources needs openpyxl: pip install -r requirements.txt") from error
    book = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True)
    try:
        if sheet not in book.sheetnames:
            raise KeyError(f"sheet {sheet!r} not in {book.sheetnames}")
        return [list(row) for row in book[sheet].iter_rows(values_only=True)]
    finally:
        book.close()

Data Grid GB — Conventional

A Python module.

otherdata-grid-gb / conventional/__init__.py · lines 1–1 of 1 · Not reached from any entry point (candidate for review)

What it achieves
UK conventional generation: see `conventional/README.md`.
Why it matters
No other file in the estate was found to import it.
Application
data-grid-gb · conventional · Python module
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-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 conventional/__init__.py:1-1 · blob 693eaea2537aa42e5d93b13f75fe48ea1907c13b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
"""UK conventional generation: see conventional/README.md."""

Conventional — Fetchers

A Python module in Data Grid GB.

otherdata-grid-gb / conventional/fetchers/__init__.py · lines 1–1 of 1 · Not reached from any entry point (candidate for review)

What it achieves
One module per source; the contract is in `assetpipe/pipeline.py` (`FETCHER_CONTRACT`).
Why it matters
No other file in the estate was found to import it.
Application
data-grid-gb · conventional/fetchers · Python module
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-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 conventional/fetchers/__init__.py:1-1 · blob ef8acc85a3d62cc58e7f8cefc1df9efbbe1cc400 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
"""One module per source; the contract is in assetpipe/pipeline.py (FETCHER_CONTRACT)."""