In this section
- Test Dcmerge test · data-grid-gb / datacentres/lanes/dc-a7-merge/test_dcmerge.py lines 508–533
- Datacentres — Locations other · data-grid-gb / datacentres/locations/__init__.py lines 1–1
- Build storage · data-grid-gb / datacentres/locations/build.py lines 1–252
- Pipeline energy-data · data-grid-gb / datacentres/locations/pipeline.py lines 1–252
- Fetch Assets other · data-grid-gb / pipelines/fetch_assets.py lines 1–71
Test Dcmerge
A test in the lanes folder of Data Grid GB that checks Dcingest and Dcmerge, using SHA-256 using data from National Energy System Operator (NESO) data portal.
testdata-grid-gb / datacentres/lanes/dc-a7-merge/test_dcmerge.py · lines 508–533 of 533 (continued from section 746) · Entry point · pattern SchemaTests (shared by 2 files)
- What it does
- It tests its inputs. Defines 64 functions or classes, including mk, SchemaTests, test_valid_record, test_status_enum, test_mw_needs_source. Uses libraries copy, json, os, random, sys. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'dc'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 400kV.
- Inputs & outputs
- In: data source: NESO data portal; GeoJSON file osm.geojson; JSON file plan.json; GeoJSON file out.geojson; JSON file x.json. Out: JSON file. Voltage levels named: 400kV.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- It merges tests (`MergeTests`) and is built from the schema tests class (`SchemaTests`) and the normaliser tests class (`NormaliserTests`). Synthetic unit tests for dcschema / dcmerge / dcingest (stdlib unittest). Its code works with 12 MW and 400 kV.
- Why it matters
- Guards the behaviour of Dcingest, Dcmerge and Dcschema.
- Application
- data-grid-gb · datacentres/lanes/dc-a7-merge · test
- Uses
- Dcingest (import), Dcmerge (import), Dcschema (import), copy, json, os, random, sys, tempfile, unittest, jsonschema
- Used by
- none found
- Produces
- mk, SchemaTests, NormaliserTests, MergeTests, EvidenceUrlTests, ConflictTests, DeterminismTests, IngestTests, LaneShapeTests
- Defines here
- test_neso_non_dc_row_rejected, test_grouped_site_members
- 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 datacentres/lanes/dc-a7-merge/test_dcmerge.py:508-533 · blob f9b89666f65e4cb91f753678ee1ed3218d406fbe · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
self.assertEqual(rec["location"]["precision"], "unknown")
def test_neso_non_dc_row_rejected(self):
rec, why = dcingest.normalise(self._neso(False, 50.0), None, {}, None, "DC-A1", "x.json", "0" * 64)
self.assertIsNone(rec)
self.assertIn("not data-centre-like", why)
def test_grouped_site_members(self):
r = {"name": "Virtus London6", "status": "operational", "lat": 51.5, "lon": -0.4,
"location_precision": "site = 3 source object(s); point: OSM node or footprint centre",
"mw_unclassified": [{"property": "P2109", "raw": "12", "mw": 12.0, "source_id": "osm-1"}],
"sources": [{"source": "OSM", "source_id": "osm-1", "name": "Virtus London5", "licence": "ODbL 1.0",
"evidence_url": "https://www.openstreetmap.org/way/1"},
{"source": "OSM", "source_id": "osm-2", "name": "Virtus London6", "licence": "ODbL 1.0",
"evidence_url": "https://www.openstreetmap.org/way/2"}]}
rec, why = dcingest.normalise(r, None, {}, None, "DC-A4", "x.json", "0" * 64)
self.assertIsNone(why)
self.assertEqual(len(rec["sources"]), 2)
self.assertEqual(rec["aliases"], ["Virtus London5"])
self.assertEqual(rec["location"]["precision"], "exact_site")
self.assertEqual(rec["unclassified_mw"]["value"], 12.0)
self.assertIsNone(rec["it_load_mw"]["value"])
if __name__ == "__main__":
unittest.main()Datacentres — Locations
A Python module in Data Grid GB.
otherdata-grid-gb / datacentres/locations/__init__.py · lines 1–1 of 1 · Not reached from any entry point (candidate for review)
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentres'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- What it achieves
- Address/location stage for the existing data-centre data owners.
- Why it matters
- No other file in the estate was found to import it.
- Application
- data-grid-gb · datacentres/locations · 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 datacentres/locations/__init__.py:1-1 · blob 8d03998758b976b1715a5f5d8610758bf1a718af · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
"""Address/location stage for the existing data-centre data owners."""Build
A Python module in the locations folder of Data Grid GB that reads postcodes, using SHA-256 from postcodes.io and the GridAtlas repository.
storagedata-grid-gb / datacentres/locations/build.py · lines 1–252 of 252 · pattern postcode (shared by 2 files)
- What it does
- It loads postcodes. Defines 14 functions or classes, including encoded, sha, postcode, point, statements. Uses libraries __future__, hashlib, json, math, re. Side effects: uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentres'): 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: postcodes.
- Inputs & outputs
- In: data source: gridatlas data; data source: postcodes.io; DuckDB queries.
- Downstream impact
- Used directly by 2 files: Pipeline (data-grid-gb); Test DC Address Locations (data-grid-gb). Reached from 2 other entry points, including Datacentre Addresses Workflow (data-grid-gb); Test Assets Workflow (data-grid-gb).
- What it achieves
- It writes Parquet (`write_parquet`) and is built from the encoded step (`encoded`) and the sha step (`sha`). Offline DC address/location projection. No identity or grid-capacity approval.
- Why it matters
- Imported by Pipeline. Checked by Test DC Address Locations.
- Application
- data-grid-gb · datacentres/locations · Python module
- Uses
- GridAtlas — Atlas Page (estate URL), __future__, hashlib, json, math, re, urllib.parse, duckdb
- Used by
- imported by Pipeline (relative import), imported by Test DC Address Locations (import)
- Produces
- encoded, sha, postcode, point, statements, statement_value, text_claims, address_metadata, screening_url, distance_m, source_qids, cross_references
- Defines here
- encoded, sha, postcode, point, statements, statement_value, text_claims, address_metadata, screening_url, distance_m, source_qids, cross_references, build, write_parquet
- 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 datacentres/locations/build.py:1-252 · blob fd37522ae08e67dd039f0657f245d7893570def7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
"""Offline DC address/location projection. No identity or grid-capacity approval."""
from __future__ import annotations
import hashlib
import json
import math
import re
from urllib.parse import urlencode
SCHEMA = 'data-grid-gb.dc-address-locations.v1'
POSTCODE = re.compile(r'\b(?:GIR\s?0AA|[A-PR-UWYZ][A-HK-Y]?\d[\dA-HJKPSTUW]?\s?\d[ABD-HJLNP-UW-Z]{2})\b', re.I)
QID = re.compile(r'Q[1-9]\d*\Z')
FOOTNOTE = 'Screening only; not a grid-capacity assessment.'
GEOCODER_LICENCE = 'https://postcodes.io/docs/licences/'
GB_ATTRIBUTION = ['Contains Ordnance Survey data © Crown copyright and database right 2025',
'Contains Royal Mail data © Royal Mail copyright and database right 2025',
'Contains National Statistics data © Crown copyright and database right 2025',
'Contains NRS data © Crown copyright and database right 2025']
def encoded(value):
return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False) + '\n').encode('utf-8')
def sha(data):
return hashlib.sha256(data).hexdigest()
def postcode(value):
compact = re.sub(r'\s+', '', value.upper())
return compact[:-3] + ' ' + compact[-3:]
def point(lon, lat):
if (type(lon) not in (int, float) or type(lat) not in (int, float)
or not math.isfinite(lon) or not math.isfinite(lat)
or not (-180 <= lon <= 180 and -90 <= lat <= 90) or (lon, lat) == (0, 0)):
raise ValueError('Invalid geographic point')
return {'type': 'Point', 'coordinates': [lon, lat]}
def statements(entity, prop):
rows = [s for s in entity.get('claims', {}).get(prop, [])
if s.get('rank') != 'deprecated' and s.get('mainsnak', {}).get('snaktype') == 'value']
preferred = [s for s in rows if s.get('rank') == 'preferred']
return preferred or rows
def statement_value(statement):
return statement['mainsnak']['datavalue']['value']
def text_claims(entity, prop):
result = []
for s in statements(entity, prop):
value = statement_value(s)
text = value.get('text') if isinstance(value, dict) else value
if not isinstance(text, str) or not text.strip():
raise ValueError('Invalid textual address claim')
refs = sorted({r['datavalue']['value'] for ref in s.get('references', [])
for r in ref.get('snaks', {}).get('P854', [])
if r.get('snaktype') == 'value' and isinstance(r.get('datavalue', {}).get('value'), str)})
result.append({'statement_id': s['id'], 'rank': s['rank'], 'text': text,
'language': value.get('language') if isinstance(value, dict) else None,
'reference_urls': refs})
return sorted(result, key=lambda x: (x['text'], x['statement_id']))
def address_metadata(entity, country):
addresses = text_claims(entity, 'P6375') + text_claims(entity, 'P969')
declared = text_claims(entity, 'P281')
# Only a full, unambiguous GB postcode can request a GB lookup. No address guessing.
candidates = set()
if country in ('GB', 'UK'):
for s in addresses + declared:
candidates.update(postcode(m.group()) for m in POSTCODE.finditer(s['text']))
return addresses, declared, sorted(candidates)
def screening_url(geometry, name):
if geometry is None:
return None
lon, lat = geometry['coordinates']
point(lon, lat)
return 'https://ventusltd.github.io/gridatlas/atlas/?' + urlencode({
'longitude': lon, 'latitude': lat, 'zoom': 12, 'project': name,
'technology': 'datacentre'})
def distance_m(a, b):
lon1, lat1 = map(math.radians, a)
lon2, lat2 = map(math.radians, b)
h = math.sin((lat2-lat1)/2)**2 + math.cos(lat1)*math.cos(lat2)*math.sin((lon2-lon1)/2)**2
return 6371008.8 * 2 * math.asin(math.sqrt(min(1, max(0, h))))
def source_qids(properties):
"""Facility IDs only. Deliberately ignores operator:wikidata and arbitrary text."""
ids = set()
for key in ('wikidata', 'wikidata_id'):
value = properties.get(key)
if isinstance(value, str) and QID.fullmatch(value):
ids.add(value)
for row in properties.get('sources', []) + properties.get('records', []):
if not isinstance(row, dict) or row.get('source', '').lower() != 'wikidata':
continue
value = row.get('source_id', row.get('id', ''))
value = value.removeprefix('wd:') if isinstance(value, str) else ''
if QID.fullmatch(value):
ids.add(value)
return ids
def cross_references(feature, references):
"""Retain explicit source joins; name/spatial discovery never supplies geometry."""
result = []
properties = feature['properties']
qid = properties['wikidata_id']
normalized = re.sub(r'\W+', ' ', properties['name'].casefold()).strip()
for ref in references:
if ref.get('country_scope', 'GB') != properties['country']['code']:
continue
for other in ref['document'].get('features', []):
p = other.get('properties') or {}
if ref.get('class_filter') and p.get('class') != ref['class_filter']:
continue
exact = qid in source_qids(p)
same_name = normalized and normalized == re.sub(r'\W+', ' ', str(p.get('name', '')).casefold()).strip()
if not exact and not same_name:
continue
geometry = other.get('geometry')
gap = None
if feature['geometry'] and geometry and geometry.get('type') == 'Point':
coords = geometry['coordinates']
point(*coords)
gap = round(distance_m(feature['geometry']['coordinates'], coords), 1)
result.append({'dataset_id': ref['id'], 'record_id': p.get('id', other.get('id')),
'source_sha256': ref['sha256'], 'source_url': ref['url'],
'method': 'EXPLICIT_WIKIDATA_SOURCE_ID' if exact else 'EXACT_NAME_CANDIDATE',
'review_state': 'SOURCE_ID_JOIN' if exact else 'CANDIDATE',
'distance_m': gap, 'source_licence': ref['licence'],
'source_attribution': ref['attribution'], 'geometry_adopted': False})
return sorted(result, key=lambda x: (x['dataset_id'], str(x['record_id'])))
def build(cohort, entities, geocodes, receipt, references=()):
if cohort.get('schema') != 'globalgrid2050.global-datacentres.projects.v1':
raise ValueError('Expected the existing Pipeline source-indexed DC cohort')
records = cohort.get('records', [])
if not records or cohort.get('record_count') != len(records):
raise ValueError('DC cohort count mismatch')
features, seen = [], set()
for row in sorted(records, key=lambda x: x['id']):
rid = row['id']
qid = rid.removeprefix('DC-WD-')
if not QID.fullmatch(qid) or rid in seen:
raise ValueError('Invalid or duplicate original DC source identity')
seen.add(rid)
entity = entities[qid]
if entity.get('id') != qid or type(entity.get('lastrevid')) is not int:
raise ValueError('Missing source entity/revision closure')
source_countries = {statement_value(s).get('id') for s in statements(entity, 'P17')}
if source_countries != {row['country']['wikidata_id']}:
raise ValueError('Current source country conflicts with the original cohort')
revision = f"https://www.wikidata.org/w/index.php?title={qid}&oldid={entity['lastrevid']}"
addresses, postal_claims, postcodes = address_metadata(entity, row['country']['code'])
geometry, precision, locator = None, 'UNKNOWN', None
coordinate_claims = statements(entity, 'P625')
points = []
for s in coordinate_claims:
v = statement_value(s)
if v.get('globe') != 'http://www.wikidata.org/entity/Q2':
raise ValueError('Unsupported coordinate reference globe')
coords = point(v.get('longitude'), v.get('latitude'))
if type(v.get('precision')) not in (int, float) or not math.isfinite(v['precision']) or v['precision'] <= 0:
raise ValueError('Missing coordinate precision')
points.append((coords, v['precision'], s['id']))
notes = []
if len(points) == 1:
geometry, degrees, statement_id = points[0]
precision = 'WIKIDATA_REPORTED_POINT'
locator = {'revision_url': revision, 'statement_id': statement_id, 'precision_degrees': degrees}
elif len(points) > 1:
notes.append('Conflicting coordinate statements: no automatic point selection')
elif len(postcodes) == 1:
pc = postcodes[0]
if pc.startswith('BT'):
notes.append('Northern Ireland postcode geocoding withheld: distinct reuse terms')
else:
geo = geocodes.get(pc)
if geo is not None:
if postcode(geo.get('postcode', '')) != pc:
raise ValueError('Geocoder returned another postcode')
if geo.get('country') not in ('England', 'Scotland', 'Wales'):
raise ValueError('Geocoder result outside supported GB licence scope')
if geo.get('latitude') is not None and geo.get('longitude') is not None:
geometry = point(geo['longitude'], geo['latitude'])
# A postcode/country label alone cannot bless a remote or false-origin point.
# This is a gross GB geographic sanity bound, not an accuracy certificate.
if not (-8.7 <= geo['longitude'] <= 2.0 and 49.8 <= geo['latitude'] <= 61.2):
raise ValueError('Geocoder coordinates are outside Great Britain bounds')
precision = 'POSTCODE_CENTROID_APPROXIMATE'
locator = {'postcode': pc, 'endpoint': 'https://api.postcodes.io/postcodes',
'quality': geo.get('quality'), 'licence_url': GEOCODER_LICENCE}
elif len(postcodes) > 1:
notes.append('Multiple source postcodes: no automatic address selection')
if geometry is None and not notes:
notes.append('No supported unambiguous coordinate or geocoded postcode')
props = {'id': rid, 'wikidata_id': qid, 'name': row['name'], 'country': row['country'],
'addresses': addresses, 'postal_code_statements': postal_claims,
'postcode_candidates': postcodes, 'location_precision': precision,
'location_source': locator, 'source_revision_url': revision,
'original_pipeline_revision_url': row['source']['revision_url'],
'source_statement_licence': 'CC0-1.0', 'source_statement_licence_url': 'https://www.wikidata.org/wiki/Wikidata:Copyright',
'geometry_licence': ('OS OpenData: GB postcode source terms' if precision == 'POSTCODE_CENTROID_APPROXIMATE' else 'CC0-1.0') if geometry else None,
'geometry_licence_url': (GEOCODER_LICENCE if precision == 'POSTCODE_CENTROID_APPROXIMATE' else 'https://www.wikidata.org/wiki/Wikidata:Copyright') if geometry else None,
'geometry_attribution': GB_ATTRIBUTION if precision == 'POSTCODE_CENTROID_APPROXIMATE' else ['Wikidata structured statements: CC0'] if geometry else [],
'source_retrieved_at': receipt['retrieved_at'], 'notes': notes,
'screening_note': FOOTNOTE, 'facility_identity_review': 'NOT_INDEPENDENTLY_VERIFIED',
'grid_connection_assessed': False}
feature = {'type': 'Feature', 'id': rid, 'geometry': geometry, 'properties': props}
props['screening_url'] = screening_url(geometry, row['name'])
props['cross_references'] = cross_references(feature, references)
features.append(feature)
counts = {'records': len(features), 'with_address': sum(bool(f['properties']['addresses']) for f in features),
'with_geometry': sum(f['geometry'] is not None for f in features),
'postcode_centroids': sum(f['properties']['location_precision'] == 'POSTCODE_CENTROID_APPROXIMATE' for f in features),
'unknown_geometry': sum(f['geometry'] is None for f in features)}
return {'type': 'FeatureCollection', 'schema': SCHEMA, 'counts': counts,
'attribution': ['Wikidata structured statements: CC0'] + GB_ATTRIBUTION +
sorted({r['attribution'] for r in references}),
'source_receipt': receipt, 'screening_note': FOOTNOTE, 'features': features}
def write_parquet(document, path):
"""Serialize every GeoJSON feature, then compare every row after readback."""
import duckdb
with duckdb.connect() as db:
db.execute('CREATE TABLE locations(id VARCHAR PRIMARY KEY, name VARCHAR, longitude DOUBLE, latitude DOUBLE, location_precision VARCHAR, feature_json VARCHAR)')
rows = []
for f in document['features']:
p = f['properties']
lon, lat = f['geometry']['coordinates'] if f['geometry'] else (None, None)
rows.append((f['id'], p['name'], lon, lat, p['location_precision'], encoded(f).decode('utf-8')))
db.executemany('INSERT INTO locations VALUES (?,?,?,?,?,?)', rows)
db.sql('SELECT * FROM locations ORDER BY id').write_parquet(str(path), compression='zstd')
actual = db.execute('SELECT * FROM read_parquet(?,hive_partitioning=false) ORDER BY id', [str(path)]).fetchall()
if actual != sorted(rows):
raise ValueError('Full-row Parquet readback mismatch')
if db.execute('SELECT DISTINCT compression FROM parquet_metadata(?)', [str(path)]).fetchall() != [('ZSTD',)]:
raise ValueError('Parquet compression mismatch')
return {'engine': 'duckdb-' + duckdb.__version__, 'rows': len(rows), 'full_row_readback': 'PASS', 'sha256': sha(path.read_bytes())}Pipeline
A Python command-line tool in the locations folder of Data Grid GB that fetches inputs, cohort, datacentre locations and readback repeat, using SHA-256 from postcodes.io.
energy-datadata-grid-gb / datacentres/locations/pipeline.py · lines 1–252 of 252 · Entry point · pattern collect (shared by 23 files)
- What it does
- It fetches inputs, cohort, datacentre locations and readback repeat. Defines 10 functions or classes, including resource_path, Collector, __init__, fetch, extract_entities. Uses libraries __future__, argparse, datetime, gzip, io. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentres'): 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: data source: postcodes.io; JSON file source-snapshot.json; JSON file inputs.json; JSON file cohort.json; GeoJSON file datacentre-locations.geojson; Parquet file datacentre-locations.parquet; Parquet file readback-repeat.parquet; DuckDB queries. Out: JSON file inputs.json; JSON file source-snapshot.json; GeoJSON file datacentre-locations.geojson.
- Downstream impact
- Used directly by 1 file: Test DC Address Locations (data-grid-gb). Reached from 2 other entry points, including Datacentre Addresses Workflow (data-grid-gb); Test Assets Workflow (data-grid-gb).
- What it achieves
- It extracts entities (`extract_entities`), parses geocodes (`parse_geocodes`) and loads snapshot (`load_snapshot`). Bounded manual address stage beside the existing DC-A4 producer. It reads `cohort.json`. It accepts `--inputs`, `--snapshot` and `--output`.
- Why it matters
- Checked by Test DC Address Locations.
- Application
- data-grid-gb · datacentres/locations · Python CLI
- Uses
- Build (relative import), __future__, argparse, datetime, gzip, io, json, os, pathlib
- Used by
- imported by Test DC Address Locations (import)
- Produces
- resource_path, Collector, extract_entities, parse_geocodes, load_snapshot, collect, product, main
- Defines here
- resource_path, Collector, __init__, fetch, extract_entities, parse_geocodes, load_snapshot, collect, product, main
- 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 datacentres/locations/pipeline.py:1-252 · blob 3ad802e3a1564a5444e403b03f280f506fea071a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
"""Bounded manual address stage beside the existing DC-A4 producer.
Collects Wikidata structured facts and GB postcode points, then rebuilds offline.
Never scrapes linked publisher bodies or edits accepted data generations.
"""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
import gzip
import io
import json
import os
from pathlib import Path
import re
import tempfile
import tarfile
from urllib.parse import urlencode, urlsplit
from urllib.request import Request, urlopen
from .build import address_metadata, build, encoded, postcode, sha, write_parquet
MAX_RESPONSE_BYTES = 8 * 1024 * 1024
MAX_TOTAL_BYTES = 32 * 1024 * 1024
MAX_REQUESTS = 32
PROPERTIES = ('P17', 'P625', 'P6375', 'P969', 'P281', 'P856')
USER_AGENT = 'GlobalGrid2050-DC-addresses/1.0 (https://github.com/Ventusltd/data-grid-gb)'
def resource_path(folder, relative):
allowed = r'(?:inputs\.json|cohort\.json|(?:wikidata|postcodes)-[0-9]{3}\.json|references/[a-z][a-z0-9_-]{0,79}\.geojson)'
if not isinstance(relative, str) or not re.fullmatch(allowed, relative):
raise ValueError('Unsafe snapshot resource path')
path = folder / relative
if not path.resolve().is_relative_to(folder.resolve()):
raise ValueError('Unsafe snapshot resource path')
return path
class Collector:
def __init__(self, folder):
self.folder = folder
self.resources = []
self.total = 0
def fetch(self, relative, url, payload=None, expected=None):
path = resource_path(self.folder, relative)
if path.exists():
raise FileExistsError('Captured source already exists')
if len(self.resources) >= MAX_REQUESTS:
raise ValueError('Request budget exceeded')
p = urlsplit(url)
if p.scheme != 'https' or p.hostname not in ('raw.githubusercontent.com', 'www.wikidata.org', 'api.postcodes.io'):
raise ValueError('Endpoint is outside the existing approved source stage')
req = Request(url, data=encoded(payload) if payload is not None else None,
headers={'User-Agent': USER_AGENT, 'Content-Type': 'application/json', 'Accept': 'application/json'})
with urlopen(req, timeout=45) as response:
if response.status != 200 or urlsplit(response.geturl()).hostname != p.hostname:
raise ValueError('Unexpected source status or redirect')
raw = response.read(MAX_RESPONSE_BYTES + 1)
self.total += len(raw)
if len(raw) > MAX_RESPONSE_BYTES or self.total > MAX_TOTAL_BYTES:
raise ValueError('Source byte budget exceeded')
if expected is not None and sha(raw) != expected:
raise ValueError('Pinned source bytes changed: ' + relative)
document = json.loads(raw)
if isinstance(document, dict) and 'error' in document:
raise ValueError('Source returned an API error')
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('xb') as stream:
stream.write(raw)
self.resources.append({'path': relative, 'url': url, 'method': 'POST' if payload else 'GET',
'request_json': payload, 'http_status': 200, 'sha256': sha(raw), 'bytes': len(raw)})
return document
def extract_entities(responses):
entities = {}
for document in responses:
for qid, entity in document['entities'].items():
if qid in entities or 'missing' in entity:
raise ValueError('Duplicate or missing source entity')
entities[qid] = {k: entity[k] for k in ('id', 'lastrevid')}
entities[qid]['claims'] = {p: entity.get('claims', {}).get(p, []) for p in PROPERTIES}
return entities
def parse_geocodes(document):
if document.get('status') != 200:
raise ValueError('Postcode source did not succeed')
result = {}
for row in document.get('result', []):
key = postcode(row['query'])
if key in result:
raise ValueError('Duplicate postcode response')
result[key] = row['result']
return result
def load_snapshot(folder):
"""Every replay rechecks the actual source bytes, never merely saved counts."""
snapshot_bytes = (folder / 'source-snapshot.json').read_bytes()
snapshot = json.loads(snapshot_bytes)
documents = {}
for r in snapshot['resources']:
path = resource_path(folder, r['path'])
if r['path'] in documents:
raise ValueError('Unsafe snapshot resource path')
raw = path.read_bytes()
if len(raw) != r['bytes'] or sha(raw) != r['sha256']:
raise ValueError('Snapshot resource bytes do not match receipt')
documents[r['path']] = json.loads(raw)
config = documents['inputs.json']
cohort = documents['cohort.json']
by_path = {r['path']: r for r in snapshot['resources']}
if by_path['cohort.json']['sha256'] != config['cohort']['sha256']:
raise ValueError('Cohort differs from the pinned input configuration')
for ref in config['references']:
if by_path['references/' + ref['id'] + '.geojson']['sha256'] != ref['sha256']:
raise ValueError('Reference differs from the pinned input configuration')
entities = extract_entities([documents[r['path']] for r in snapshot['resources'] if r['path'].startswith('wikidata-')])
geocodes = {}
for r in snapshot['resources']:
if r['path'].startswith('postcodes-'):
batch = parse_geocodes(documents[r['path']])
requested = {postcode(p) for p in r['request_json']['postcodes']}
if set(batch) != requested or set(geocodes) & set(batch):
raise ValueError('Postcode response does not match requested identities')
geocodes.update(batch)
references = [{**r, 'document': documents['references/' + r['id'] + '.geojson']} for r in config['references']]
receipt = {'retrieved_at': snapshot['retrieved_at'], 'snapshot_sha256': sha(snapshot_bytes),
'cohort_sha256': config['cohort']['sha256'], 'cohort_source_url': config['cohort']['url'],
'resources': snapshot['resources'], 'producer': 'data-grid-gb/datacentres/locations'}
return build(cohort, entities, geocodes, receipt, references)
def collect(config_path, folder):
config_raw = config_path.read_bytes()
config = json.loads(config_raw)
ids = [ref['id'] for ref in config['references']]
if len(ids) != len(set(ids)):
raise ValueError('Duplicate reference dataset identity')
for identity in ids:
resource_path(folder, 'references/' + identity + '.geojson')
(folder / 'inputs.json').write_bytes(config_raw)
c = Collector(folder)
c.resources.append({'path': 'inputs.json', 'url': None, 'method': 'LOCAL_CONFIG',
'request_json': None, 'http_status': None, 'sha256': sha(config_raw), 'bytes': len(config_raw)})
cohort = c.fetch('cohort.json', config['cohort']['url'], expected=config['cohort']['sha256'])
rows = cohort['records']
if not 0 < len(rows) <= 1000 or cohort['record_count'] != len(rows):
raise ValueError('Cohort exceeds the bounded source stage')
ids = sorted({row['id'].removeprefix('DC-WD-') for row in rows})
if len(ids) != len(rows) or any(not re.fullmatch(r'Q[1-9]\d*', qid) for qid in ids):
raise ValueError('Invalid source cohort identities')
raw_entities = []
for offset in range(0, len(ids), 50):
url = 'https://www.wikidata.org/w/api.php?' + urlencode({'action': 'wbgetentities',
'ids': '|'.join(ids[offset:offset+50]), 'props': 'claims|info', 'format': 'json', 'maxlag': 5})
raw_entities.append(c.fetch(f'wikidata-{offset//50:03}.json', url))
entities = extract_entities(raw_entities)
if set(entities) != set(ids):
raise ValueError('Source response does not close the requested cohort')
postcodes = set()
for row in rows:
_, _, pcs = address_metadata(entities[row['id'][6:]], row['country']['code'])
if len(pcs) == 1 and not pcs[0].startswith('BT'):
postcodes.add(pcs[0])
postcodes = sorted(postcodes)
for offset in range(0, len(postcodes), 100):
c.fetch(f'postcodes-{offset//100:03}.json',
'https://api.postcodes.io/postcodes?filter=postcode,longitude,latitude,quality,country',
payload={'postcodes': postcodes[offset:offset+100]})
for ref in config['references']:
c.fetch('references/' + ref['id'] + '.geojson', ref['url'], expected=ref['sha256'])
snapshot = {'schema': 'data-grid-gb.dc-address-source-snapshot.v1',
'retrieved_at': datetime.now(timezone.utc).isoformat(), 'resources': c.resources,
'bounds': {'max_requests': MAX_REQUESTS, 'max_response_bytes': MAX_RESPONSE_BYTES,
'max_total_bytes': MAX_TOTAL_BYTES, 'actual_requests': len(c.resources)-1,
'actual_response_bytes': c.total}}
(folder / 'source-snapshot.json').write_bytes(encoded(snapshot))
def product(folder, document, parquet=False):
geojson = encoded(document)
(folder / 'datacentre-locations.geojson').write_bytes(geojson)
manifest = {'schema': 'data-grid-gb.dc-address-product-manifest.v1', 'counts': document['counts'],
'source_snapshot_sha256': document['source_receipt']['snapshot_sha256'],
'products': {'datacentre-locations.geojson': {'sha256': sha(geojson), 'bytes': len(geojson)}}}
if parquet:
p = folder / 'datacentre-locations.parquet'
proof = write_parquet(document, p)
second = folder / 'readback-repeat.parquet'
write_parquet(document, second)
if p.read_bytes() != second.read_bytes():
raise ValueError('Independent repeated Parquet builds differ')
second.unlink()
manifest['products'][p.name] = {**proof, 'bytes': p.stat().st_size, 'repeated_compile': 'IDENTICAL'}
manifest['code_sha256'] = {p.name: sha(p.read_bytes()) for p in (Path(__file__), Path(__file__).with_name('build.py'))}
snapshot_path = folder / 'source-snapshot.json'
if snapshot_path.exists():
# A compact, reproducible source closure avoids repeated expanded copies of
# the already-owned reference GeoJSON. It is not a browser dependency.
snapshot = json.loads(snapshot_path.read_bytes())
paths = sorted(r['path'] for r in snapshot['resources']) + ['source-snapshot.json']
archive_path = folder / 'source-snapshot.tar.gz'
with archive_path.open('xb') as stream, gzip.GzipFile(filename='', fileobj=stream, mode='wb', mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode='w') as archive:
for relative in paths:
path = snapshot_path if relative == 'source-snapshot.json' else resource_path(folder, relative)
raw = path.read_bytes()
info = tarfile.TarInfo(relative)
info.size, info.mtime, info.mode = len(raw), 0, 0o644
archive.addfile(info, io.BytesIO(raw))
manifest['source_archive'] = {'path': archive_path.name, 'sha256': sha(archive_path.read_bytes()),
'bytes': archive_path.stat().st_size, 'resources': len(paths)}
# Final manifest is the completion marker; a partially written scratch is never accepted.
(folder / 'manifest.json').write_bytes(encoded(manifest))
return manifest
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('mode', choices=('collect', 'build'))
parser.add_argument('--inputs', type=Path, default=Path(__file__).with_name('inputs.json'))
parser.add_argument('--snapshot', type=Path)
parser.add_argument('--output', type=Path, required=True, help='New generation folder; never an existing accepted folder')
parser.add_argument('--parquet', action='store_true', help='Also build and fully read back with the declared DuckDB version')
args = parser.parse_args(argv)
if args.output.exists():
raise FileExistsError('Output generation already exists')
args.output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='dc-address-stage-', dir=args.output.parent) as scratch:
stage = Path(scratch) / 'generation'
stage.mkdir()
if args.mode == 'collect':
collect(args.inputs, stage)
document = load_snapshot(stage)
else:
if args.snapshot is None:
raise ValueError('Offline build requires --snapshot')
document = load_snapshot(args.snapshot)
manifest = product(stage, document, args.parquet)
if args.output.exists():
raise FileExistsError('Output appeared during build; no history replacement')
os.rename(stage, args.output)
print(json.dumps(manifest, sort_keys=True))
return 0
if __name__ == '__main__':
raise SystemExit(main())Fetch Assets
A Python command-line tool in the pipelines folder of Data Grid GB covering sources, using SHA-256. It is built from the cmd list helper (`cmd_list`).
otherdata-grid-gb / pipelines/fetch_assets.py · lines 1–71 of 71 · Entry point · pattern cmd_list (shared by 3 files)
- What it does
- Defines cmd_list, main. Uses libraries __future__, argparse, sys, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file sources.json; JSON file INDEX.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Fetch Assets Workflow (data-grid-gb).
- What it achieves
- Fetch, pin and normalise the data-centre and conventional-generation sources. It accepts `--source`, `--include-unverified` and `--update-pins`.
- Why it matters
- Run by Fetch Assets Workflow.
- Application
- data-grid-gb · pipelines · Python CLI
- Uses
- Data Grid GB — Assetpipe (import), Pipeline (import), __future__, argparse, sys, pathlib
- Used by
- run by Fetch Assets Workflow (workflow run)
- Produces
- cmd_list, main
- Defines here
- cmd_list, main
- 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 pipelines/fetch_assets.py:1-71 · blob 01b1f34e56d8eb2021fffcfde492d009d435b34a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Fetch, pin and normalise the data-centre and conventional-generation sources.
python pipelines/fetch_assets.py fetch [datacentres|conventional|all] [--source ID ...]
[--include-unverified] [--update-pins]
python pipelines/fetch_assets.py normalise [datacentres|conventional|all] [--source ID ...]
python pipelines/fetch_assets.py list [datacentres|conventional|all]
``fetch`` downloads every source that is FULLY OPEN (``open: "yes"`` in
``<domain>/sources.json``) and whose fetcher is ready, writes the raw bytes under
``<domain>/raw/<source>/`` and pins each file's sha256 in ``<domain>/raw/MANIFEST.json``.
A pinned file whose upstream bytes changed fails the run until ``--update-pins``.
``normalise`` needs no network: it re-reads the pinned raw bytes (checking each
sha256), runs each source's deterministic normaliser and writes
``<domain>/normalised/<source>.geojson`` plus ``normalised/INDEX.json``.
Standard library only. A spreadsheet normaliser needs openpyxl (requirements.txt).
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from assetpipe import DOMAINS # noqa: E402
from assetpipe.pipeline import (PipelineError, fetch_domain, load_module, # noqa: E402
load_registry, normalise_domain)
def cmd_list(domains) -> int:
for domain in domains:
print(f"{domain}:")
for entry in load_registry(domain)["sources"]:
module = load_module(domain, entry) if entry.get("module") else None
status = getattr(module, "STATUS", "no fetcher") if module else "no fetcher"
print(f" {entry['id']:<26} open={entry['open']:<10} {status:<12} {entry['licence']:<10} lane={entry.get('lane')}")
return 0
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("command", choices=("fetch", "normalise", "list"))
parser.add_argument("domain", nargs="?", default="all", choices=(*DOMAINS, "all"))
parser.add_argument("--source", action="append", help="limit to this source id (repeatable)")
parser.add_argument("--include-unverified", action="store_true",
help="also snapshot sources whose licence is unverified (never normalised)")
parser.add_argument("--update-pins", action="store_true", help="accept changed upstream bytes")
args = parser.parse_args(argv)
domains = DOMAINS if args.domain == "all" else (args.domain,)
try:
if args.command == "list":
return cmd_list(domains)
for domain in domains:
print(f"{args.command} {domain}")
if args.command == "fetch":
fetch_domain(domain, only=args.source, include_unverified=args.include_unverified,
update_pins=args.update_pins)
else:
normalise_domain(domain, only=args.source)
except PipelineError as error:
print(f"::error::{error}")
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())