In this section
- Build Substation Subset electrical · claude / sessions/202609031559-skin-architecture/prototype/build-substation-subset.py lines 1–92
- Verify Renewable Energy Planning Database (REPD) Routing Release automation · code-generator / apps/substation-finder/Dt/202608291410-verify-repd-routing-release.py lines 1–119
- Build Atlas V9 Company Renewable Energy Planning Database (REPD) Links energy-data · code-generator / apps/substation-finder/Dt/202608300232-build-atlas-v9-company-repd-links.py lines 1–375
Build Substation Subset
A Python module in the prototype folder of Claude that reads grid substations and 400kV.
electricalclaude / sessions/202609031559-skin-architecture/prototype/build-substation-subset.py · lines 1–92 of 92 · version 2026-09-03 15:59 · Not reached from any entry point (candidate for review)
- What it does
- It loads grid substations and 400kV. Defines dk, rep. Uses libraries json, math, sys, os. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV.
- Inputs & outputs
- In: GeoJSON file grid_substations.geojson. Out: JSON file. Voltage levels named: 400kV.
- What it achieves
- Its name says it builds substation subset. Defines `rep`. Its code works with 400 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- claude · sessions/202609031559-skin-architecture/prototype · Python module
- Uses
- json, math, sys, os
- Used by
- none found
- Produces
- dk, rep
- Defines here
- dk, rep
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609031559-skin-architecture/prototype/build-substation-subset.py:1-92 · blob f52f33418a8ffa0e1e6f942a40401ca8f19ac38b · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: ICP_grid_engineer · canonical: unreached_review
import json, math, sys, os
SRC = r"C:\Users\vikra\OneDrive\Documents\GitHub\gridatlas\atlas\releases\202608300453-atlas-v9\data\grid_substations.geojson"
DST = r"C:\Users\vikra\OneDrive\Documents\GitHub\claude\sessions\202609031559-skin-architecture\prototype\substations.json"
R = 6378.137
D = math.pi / 180.0
def dk(a, b, c, d):
dla = (d - b) * D
dlo = (c - a) * D
x = math.sin(dla / 2) ** 2 + math.cos(b * D) * math.cos(d * D) * math.sin(dlo / 2) ** 2
return R * 2 * math.atan2(math.sqrt(x), math.sqrt(1 - x))
def rep(g):
if not g:
return None
t = g.get("type")
c = g.get("coordinates")
if t == "Point":
return c
ring = None
if t == "Polygon":
ring = c[0]
elif t == "MultiPolygon":
ring = c[0][0]
if not ring:
return None
return [sum(p[0] for p in ring) / len(ring), sum(p[1] for p in ring) / len(ring)]
with open(SRC, "r", encoding="utf-8") as fh:
gj = json.load(fh)
B = (-1.3489728, 51.8132088) # Botley West Solar Project
O = (0.15, 53.88) # Ossian, offshore
K = (-2.30, 56.15) # a Firth of Forth point, so the set covers a
# northern drag target for the move-the-project demo.
# NOT asserted to be any named project location.
seen = set()
rows = []
for f in gj["features"]:
p = f.get("properties") or {}
at = rep(f.get("geometry"))
if not at:
continue
v = str(p.get("voltage") or "")
kvs = []
for s in v.split(";"):
try:
n = round(float(s) / 1000)
except Exception:
continue
if n > 0 and n not in kvs:
kvs.append(n)
if not kvs:
continue
kvs.sort(reverse=True)
db = dk(B[0], B[1], at[0], at[1])
do = dk(O[0], O[1], at[0], at[1])
dbb = dk(K[0], K[1], at[0], at[1])
keep = (db <= 45) or (kvs[0] >= 400 and db <= 90) or (kvs[0] >= 275 and do <= 220) or (kvs[0] >= 275 and dbb <= 220)
if not keep:
continue
key = (round(at[0], 5), round(at[1], 5))
if key in seen:
continue
seen.add(key)
rows.append([p.get("name") or None, kvs, round(at[0], 6), round(at[1], 6)])
payload = {
"schema": "gridatlas.substations.subset/1",
"source": "gridatlas/atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson",
"source_features": len(gj["features"]),
"note": "A geographic subset, taken so this prototype loads in milliseconds. "
"Rows are [name, [kV...], lon, lat]. Representative point is the mean of "
"the outer ring, exactly as modules/202609011950-geodesy.js does it.",
"anchors": {"botley_west": list(B), "ossian": list(O), "firth_of_forth_point": list(K)},
"rows": rows,
}
os.makedirs(os.path.dirname(DST), exist_ok=True)
with open(DST, "w", encoding="utf-8", newline="\n") as fh:
json.dump(payload, fh, separators=(",", ":"))
print("features", len(gj["features"]), "kept", len(rows), "bytes", os.path.getsize(DST))
n400 = [r for r in rows if r[1][0] >= 400]
n400.sort(key=lambda r: dk(B[0], B[1], r[2], r[3]))
print("nearest 400kV to Botley:", n400[0][0], round(dk(B[0], B[1], n400[0][2], n400[0][3]), 3))
n400.sort(key=lambda r: dk(O[0], O[1], r[2], r[3]))
print("nearest 400kV to Ossian:", n400[0][0], round(dk(O[0], O[1], n400[0][2], n400[0][3]), 3))
n400.sort(key=lambda r: dk(K[0], K[1], r[2], r[3]))
print("nearest 400kV to Forth point:", n400[0][0], round(dk(K[0], K[1], n400[0][2], n400[0][3]), 3))Verify Renewable Energy Planning Database (REPD) Routing Release
A Python command-line tool in the substation finder folder of Code Generator that reads projects and the REPD register, using SHA-256.
automationcode-generator / apps/substation-finder/Dt/202608291410-verify-repd-routing-release.py · lines 1–119 of 119 · version 2026-08-29 14:10 · Entry point · pattern canonical_json (shared by 11 files)
- What it does
- It loads projects and the REPD register. Defines sha256, require, set_hash, canonical_json, main. Uses libraries __future__, argparse, hashlib, json, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'routing'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file projects.json; JSON file release.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It sets hash (`set_hash`) and is built from the sha256 step (`sha256`) and the require step (`require`). Fail-closed verification for the immutable REPD routing folder. It accepts `--contract`, `--release` and `--source-commit`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- code-generator · apps/substation-finder/Dt · Python CLI
- Uses
- __future__, argparse, hashlib, json, pathlib, re
- Used by
- none found
- Produces
- sha256, require, set_hash, canonical_json, main
- Defines here
- sha256, require, set_hash, canonical_json, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Dt/202608291410-verify-repd-routing-release.py:1-119 · blob ab43435c17b3989ce2eb342e5e051e8f300a0602 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: field_execution · users: IPP_developer, EPC_contractor, ICP_grid_engineer, landowner_planner · canonical: unknown
#!/usr/bin/env python3
"""Fail-closed verification for the immutable REPD routing folder."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import re
GENERATION = "202608291410"
RELEASE_ID = f"{GENERATION}-repd-routing"
SHA40 = re.compile(r"^[0-9a-f]{40}$")
def sha256(raw: bytes) -> str:
return hashlib.sha256(raw).hexdigest()
def require(condition: bool, message: str) -> None:
if not condition:
raise RuntimeError(message)
def set_hash(values: list[str]) -> str:
ordered = sorted(values, key=int)
return sha256((json.dumps(ordered, separators=(",", ":")) + "\n").encode("utf-8"))
def canonical_json(value: object) -> bytes:
return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n").encode("utf-8")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--contract", type=Path, required=True)
parser.add_argument("--release", type=Path, required=True)
parser.add_argument("--source-commit", required=True)
parser.add_argument("--source-committed-at", required=True)
args = parser.parse_args()
require(SHA40.fullmatch(args.source_commit) is not None, "source commit must be exact SHA-1")
require(re.fullmatch(r"\d{4}-\d{2}-\d{2}T[^\r\n]+", args.source_committed_at) is not None, "source timestamp is invalid")
contract = json.loads(args.contract.read_text(encoding="utf-8"))
require(contract.get("schema") == "data-gridatlas.repd-routing-source.v1", "source contract schema drift")
require(contract.get("generation") == GENERATION and contract.get("release_id") == RELEASE_ID, "source contract generation drift")
root = args.release
require(root.name == RELEASE_ID and root.is_dir(), "release folder identity drift")
entries = list(root.iterdir())
require(all(path.is_file() for path in entries), "directory or special entry in routing release")
actual = sorted(path.name for path in entries)
require(actual == ["index.html", "projects.json", "release.json", "sha256sums.txt"], f"release closure drift: {actual}")
require(not any(path.is_symlink() for path in entries), "symlink in routing release")
projects_raw = (root / "projects.json").read_bytes()
source = contract["source"]
require(len(projects_raw) == source["bytes"] and sha256(projects_raw) == source["sha256"], "projects bytes are not exact source")
payload = json.loads(projects_raw)
fields = {name: index for index, name in enumerate(payload["fields"])}
refs = [str(row[fields["repd_ref"]]) for row in payload["rows"]]
geometry = payload["dictionaries"]["geometry_status"]
map_refs = [str(row[fields["repd_ref"]]) for row in payload["rows"] if geometry[row[fields["geometry_status"]]] == "valid"]
no_map_refs = [str(row[fields["repd_ref"]]) for row in payload["rows"] if geometry[row[fields["geometry_status"]]] != "valid"]
closure = contract["closure"]
require(len(refs) == closure["projects"] and len(set(refs)) == closure["unique_numeric_repd_refs"], "project identity closure drift")
require(all(re.fullmatch(r"\d+", value) for value in refs), "non-numeric REPD identity")
require(len(map_refs) == closure["map_identities"] and len(no_map_refs) == closure["no_map_identities"], "map/no-map closure drift")
require(set_hash(map_refs) == closure["map_set_sha256"], "MAP set hash drift")
require(set_hash(no_map_refs) == closure["no_map_set_sha256"], "NO MAP set hash drift")
release_raw = (root / "release.json").read_bytes()
release = json.loads(release_raw)
require(release_raw == canonical_json(release), "release JSON is not canonical")
require(release.get("schema") == "data-gridatlas.repd-routing-release.v1", "release schema drift")
require(release.get("generation") == GENERATION and release.get("release_id") == RELEASE_ID, "release identity drift")
require(release.get("incepted_at") == contract["incepted_at"] and release.get("public_url") == contract["folder_contract"]["public_url"], "release timestamp/URL drift")
require(release.get("source_commit") == args.source_commit and release.get("source_committed_at") == args.source_committed_at, "release source commit binding drift")
require(release.get("source_parent_commit") == contract["source_parent_commit"], "release source parent binding drift")
require(release.get("source") == contract["source"], "release routing provenance drift")
require(release.get("immutable") is True, "release immutability drift")
require(release.get("classification") == "IMMUTABLE_REPD_ROUTING_RELEASE", "release classification drift")
require(release.get("coverage") == closure, "release coverage drift")
index_raw = (root / "index.html").read_bytes()
expected_files = {
"index": {"path": "index.html", "bytes": len(index_raw), "sha256": sha256(index_raw)},
"projects": {"path": "projects.json", "bytes": len(projects_raw), "sha256": sha256(projects_raw)},
}
require(release.get("files") == expected_files, "release file bindings drift")
expected_consumer = {
"decode_geometry_status": True,
"select_only_geometry_status_valid": True,
"identity_key": "repd_ref",
"existing_layer_release_pointer_unchanged": True,
}
require(release.get("consumer_contract") == expected_consumer, "consumer contract drift")
require(f'<time datetime="{contract["incepted_at"]}">'.encode() in index_raw, "timestamp missing from index")
for target in (b'href="projects.json"', b'href="release.json"', b'href="sha256sums.txt"'):
require(target in index_raw, f"index dependency link missing: {target!r}")
sums = (root / "sha256sums.txt").read_text(encoding="utf-8").splitlines()
expected_sums = [
f"{sha256((root / name).read_bytes())} {name}"
for name in ("index.html", "projects.json", "release.json")
]
require(sums == expected_sums, "sha256sums closure drift")
print(json.dumps({
"classification": "VERIFIED_REPD_ROUTING_RELEASE",
"release_id": RELEASE_ID,
"files": 4,
"projects": len(refs),
"map_identities": len(map_refs),
"no_map_identities": len(no_map_refs),
"projects_sha256": sha256(projects_raw),
"release_sha256": sha256(release_raw),
}, sort_keys=True))
if __name__ == "__main__":
main()Build Atlas V9 Company Renewable Energy Planning Database (REPD) Links
A Python command-line tool in the substation finder folder of Code Generator that reads atlas company REPD links, GridAtlas current, the REPD register and solar, using SHA-256.
energy-datacode-generator / apps/substation-finder/Dt/202608300232-build-atlas-v9-company-repd-links.py · lines 1–375 of 375 · version 2026-08-30 02:32 · Entry point · pattern normalise_base (shared by 2 files)
- What it does
- It loads atlas company REPD links, GridAtlas current, the REPD register and solar. Defines 18 functions or classes, including require, load, sha256_file, stable_id, quote_identifier. Uses libraries __future__, argparse, csv, hashlib, json. 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 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar.
- Inputs & outputs
- In: Parquet file atlas_v9_company_repd_links.parquet; JSON file live-set.json; JSON file gridatlas-v9-current.json; JSON file atlas-v9-current.json; JSON file atlas-v9-company-repd-links-manifest.json; DuckDB queries; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It normalises company number (`normalise_company_number`), normalises ref (`normalise_ref`) and normalises technology (`normalise_technology`). Build compact deterministic Companies ↔ REPD ↔ Atlas V9 deep-link relations. It accepts `--gridatlas`, `--globalgrid` and `--repo-root`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- code-generator · apps/substation-finder/Dt · Python CLI
- Uses
- GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL), __future__, argparse, csv, hashlib, json, re, sys, pathlib
- Used by
- none found
- Produces
- require, load, sha256_file, stable_id, quote_identifier, sql_path, first_column, normalise_company_number, normalise_ref, normalise_technology, normalise_base, build_url
- Defines here
- require, load, sha256_file, stable_id, quote_identifier, sql_path, first_column, normalise_company_number, normalise_ref, normalise_technology, normalise_base, build_url, candidate_parquets, mutable_text_files, rewrite_sources, extract_rows, write_parquet, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Dt/202608300232-build-atlas-v9-company-repd-links.py:1-375 · blob ba7fc725e4d4ba0ed1040f45cd60d4ff6abd5c89 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Build compact deterministic Companies ↔ REPD ↔ Atlas V9 deep-link relations."""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import re
import sys
from pathlib import Path
from typing import Any, Iterable
from urllib.parse import urlencode, urlparse
import duckdb
MIN_RENDER_READY_GENERATION = "202608292311"
VALID_TECHNOLOGIES = {"solar", "bess", "wind_onshore", "wind_offshore"}
PARQUET_ROOTS = {"data", "derived", "reports", "relationships", "outputs", "output"}
EXCLUDED_PARTS = {"raw", "bulk", "archive", "archives", "cache", "downloads", "work", "tmp", "node_modules", ".git"}
TEXT_EXTENSIONS = {".html", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".py", ".json"}
SOURCE_ROOTS = {"ui", "src", "javascript", "templates", "compiler", "app", "public", "scripts"}
TIMESTAMPED = re.compile(r"^\d{12}(?:-|$)")
MAX_INPUT_BYTES = 100 * 1024 * 1024
OLD_BASES = (
"https://globalgrid2050.com/repd_grid_atlasv8/",
"https://globalgrid2050.com/repd_grid_atlasv8",
"http://globalgrid2050.com/repd_grid_atlasv8/",
"http://globalgrid2050.com/repd_grid_atlasv8",
)
OLD_V9 = re.compile(r"https://ventusltd\.github\.io/gridatlas/\d{12}-atlas-v9/?")
REF_COLUMNS = ("repd_ref", "repd_reference", "repd_ref_id", "repd_reference_id", "ref_id")
TECH_COLUMNS = ("technology", "tech", "repd_technology", "technology_type")
COMPANY_COLUMNS = ("company_number", "company_no", "companies_house_number", "ch_company_number")
ROLE_COLUMNS = ("role", "company_role", "relationship_role", "relationship_type")
STATUS_COLUMNS = ("status", "match_status", "relationship_status", "method_status")
def require(condition: bool, message: str) -> None:
if not condition:
raise RuntimeError(message)
def load(path: Path) -> dict[str, Any]:
value = json.loads(path.read_text(encoding="utf-8"))
require(isinstance(value, dict), f"JSON root is not an object: {path}")
return value
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def stable_id(*parts: str) -> str:
return hashlib.sha256("\x1f".join(parts).encode("utf-8")).hexdigest()
def quote_identifier(value: str) -> str:
return '"' + value.replace('"', '""') + '"'
def sql_path(path: Path) -> str:
return str(path.resolve()).replace("'", "''")
def first_column(columns: dict[str, str], candidates: tuple[str, ...]) -> str | None:
for candidate in candidates:
if candidate in columns:
return columns[candidate]
return None
def normalise_company_number(value: object) -> str | None:
text = re.sub(r"\s+", "", str(value or "").upper())
return text if re.fullmatch(r"[A-Z0-9]{6,10}", text) else None
def normalise_ref(value: object) -> str | None:
text = str(value or "").strip()
return text if re.fullmatch(r"[A-Za-z0-9-]{1,40}", text) else None
def normalise_technology(value: object) -> str | None:
text = re.sub(r"[^a-z0-9]+", " ", str(value or "").lower()).strip()
if "solar" in text or text in {"pv", "photovoltaic"}:
return "solar"
if "battery" in text or "bess" in text or "storage" in text:
return "bess"
if "wind" in text and "offshore" in text:
return "wind_offshore"
if "wind" in text and "onshore" in text:
return "wind_onshore"
return None
def normalise_base(value: str) -> str:
parsed = urlparse(value)
require(parsed.scheme == "https", "Atlas base must use HTTPS")
require(parsed.netloc in {"globalgrid2050.com", "www.globalgrid2050.com"}, "Atlas base must use GlobalGrid2050")
require(re.fullmatch(r"/\d{12}-atlas-v9/", parsed.path) is not None, "Atlas base is not immutable")
return value.rstrip("/") + "/"
def build_url(base: str, repd_ref: str, technology: str) -> str:
require(technology in VALID_TECHNOLOGIES, "invalid Atlas technology")
return base + "?" + urlencode({"repd_ref": repd_ref, "technology": technology})
def candidate_parquets(root: Path) -> Iterable[Path]:
for top in sorted(PARQUET_ROOTS):
directory = root / top
if not directory.is_dir():
continue
for path in sorted(directory.rglob("*.parquet")):
relative = path.relative_to(root)
lower_parts = {part.lower() for part in relative.parts}
if lower_parts & EXCLUDED_PARTS:
continue
if path.name == "atlas_v9_company_repd_links.parquet":
continue
if path.stat().st_size > MAX_INPUT_BYTES:
continue
yield path
def mutable_text_files(root: Path) -> Iterable[Path]:
for path in sorted(root.rglob("*")):
if not path.is_file() or path.suffix.lower() not in TEXT_EXTENSIONS:
continue
relative = path.relative_to(root)
first = relative.parts[0]
if first in {".git", ".github", "node_modules", "archive", "archives", "releases", "data", "derived", "reports", "state"}:
continue
if TIMESTAMPED.match(first):
continue
if len(relative.parts) > 1 and first not in SOURCE_ROOTS:
continue
if relative.as_posix() == "scripts/202608300232-build-atlas-v9-company-repd-links.py":
continue
yield path
def rewrite_sources(root: Path, base_url: str) -> tuple[list[str], int]:
changed: list[str] = []
replacements = 0
for path in mutable_text_files(root):
try:
original = path.read_text(encoding="utf-8")
except UnicodeDecodeError:
continue
updated = original
count = 0
for old in OLD_BASES:
occurrences = updated.count(old)
if occurrences:
updated = updated.replace(old, base_url)
count += occurrences
updated, v9_count = OLD_V9.subn(base_url, updated)
count += v9_count
if count:
path.write_text(updated, encoding="utf-8", newline="\n")
changed.append(path.relative_to(root).as_posix())
replacements += count
return changed, replacements
def extract_rows(connection: duckdb.DuckDBPyConnection, root: Path, path: Path) -> tuple[list[dict[str, str]], dict[str, Any]]:
escaped = sql_path(path)
description = connection.execute(f"DESCRIBE SELECT * FROM read_parquet('{escaped}')").fetchall()
names = [str(row[0]) for row in description]
columns = {name.lower(): name for name in names}
ref_column = first_column(columns, REF_COLUMNS)
tech_column = first_column(columns, TECH_COLUMNS)
company_column = first_column(columns, COMPANY_COLUMNS)
role_column = first_column(columns, ROLE_COLUMNS)
status_column = first_column(columns, STATUS_COLUMNS)
source = path.relative_to(root).as_posix()
evidence = {
"path": source,
"bytes": path.stat().st_size,
"sha256": sha256_file(path),
"columns": names,
"eligible": bool(ref_column and tech_column and company_column),
"rows_scanned": 0,
"rows_linked": 0,
"rows_abstained": 0,
}
if not evidence["eligible"]:
return [], evidence
projections = [
f"CAST({quote_identifier(company_column)} AS VARCHAR) AS company_number",
f"CAST({quote_identifier(ref_column)} AS VARCHAR) AS repd_ref",
f"CAST({quote_identifier(tech_column)} AS VARCHAR) AS technology",
f"CAST({quote_identifier(role_column)} AS VARCHAR) AS role" if role_column else "NULL::VARCHAR AS role",
f"CAST({quote_identifier(status_column)} AS VARCHAR) AS source_status" if status_column else "NULL::VARCHAR AS source_status",
]
result = connection.execute(
f"SELECT {', '.join(projections)} FROM read_parquet('{escaped}')"
).fetchall()
linked: list[dict[str, str]] = []
for company_value, ref_value, tech_value, role_value, source_status_value in result:
evidence["rows_scanned"] += 1
company_number = normalise_company_number(company_value)
repd_ref = normalise_ref(ref_value)
technology = normalise_technology(tech_value)
if not company_number or not repd_ref or not technology:
evidence["rows_abstained"] += 1
continue
role = str(role_value or "").strip()[:120]
source_status = str(source_status_value or "").strip()[:120]
linked.append({
"relationship_id": stable_id(company_number, repd_ref, technology, source),
"company_number": company_number,
"repd_ref": repd_ref,
"technology": technology,
"role": role,
"source_status": source_status,
"source_artifact": source,
"evidence_class": "OFFICIAL_REPD_REFERENCE_RELATION",
"link_status": "LINKED",
})
evidence["rows_linked"] += 1
return linked, evidence
def write_parquet(connection: duckdb.DuckDBPyConnection, rows: list[dict[str, str]], output: Path) -> None:
output.parent.mkdir(parents=True, exist_ok=True)
jsonl = output.with_suffix(".jsonl.tmp")
with jsonl.open("w", encoding="utf-8", newline="\n") as handle:
for row in rows:
handle.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n")
escaped_jsonl = sql_path(jsonl)
escaped_output = sql_path(output)
if rows:
connection.execute(
f"""
COPY (
SELECT relationship_id, company_number, repd_ref, technology, role,
source_status, source_artifact, evidence_class, link_status,
atlas_v9_url, producer
FROM read_json_auto('{escaped_jsonl}', format='newline_delimited')
ORDER BY company_number, repd_ref, technology, source_artifact
) TO '{escaped_output}' (FORMAT PARQUET, COMPRESSION ZSTD, ROW_GROUP_SIZE 10000)
"""
)
else:
connection.execute(
f"""
COPY (
SELECT
NULL::VARCHAR AS relationship_id,
NULL::VARCHAR AS company_number,
NULL::VARCHAR AS repd_ref,
NULL::VARCHAR AS technology,
NULL::VARCHAR AS role,
NULL::VARCHAR AS source_status,
NULL::VARCHAR AS source_artifact,
NULL::VARCHAR AS evidence_class,
NULL::VARCHAR AS link_status,
NULL::VARCHAR AS atlas_v9_url,
NULL::VARCHAR AS producer
WHERE FALSE
) TO '{escaped_output}' (FORMAT PARQUET, COMPRESSION ZSTD)
"""
)
jsonl.unlink(missing_ok=True)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--gridatlas", required=True, type=Path)
parser.add_argument("--globalgrid", required=True, type=Path)
parser.add_argument("--repo-root", default=".", type=Path)
args = parser.parse_args()
atlas_state = load(args.gridatlas / "state/live-set.json")
generation = str(atlas_state.get("generation") or "")
if generation < MIN_RENDER_READY_GENERATION:
print(json.dumps({"classification": "WAITING_FOR_RENDER_READY_PROMOTION", "generation": generation}, sort_keys=True))
return 0
verification = atlas_state.get("verification") or {}
current = atlas_state.get("current") or {}
require(verification.get("promotion_eligible") is True, "Atlas release is not promotion eligible")
require(int(verification.get("failed_gates", -1)) == 0, "Atlas release has failed gates")
release_id = str(current.get("release_id") or "")
require(re.fullmatch(r"\d{12}-atlas-v9", release_id) is not None, "invalid Atlas release id")
global_pointer = load(args.globalgrid / "state/gridatlas-v9-current.json")
require(global_pointer.get("release_id") == release_id, "GlobalGrid mirror and Atlas pointer disagree")
require(global_pointer.get("classification") == "MIRRORED_PROMOTED_GRIDATLAS_V9", "GlobalGrid mirror is not promoted")
base_url = normalise_base(str(global_pointer.get("globalgrid_live_url") or ""))
root = args.repo_root.resolve()
connection = duckdb.connect()
connection.execute("PRAGMA threads=1")
connection.execute("SET preserve_insertion_order=true")
all_rows: list[dict[str, str]] = []
sources: list[dict[str, Any]] = []
for path in candidate_parquets(root):
rows, evidence = extract_rows(connection, root, path)
all_rows.extend(rows)
sources.append(evidence)
unique: dict[tuple[str, str, str, str], dict[str, str]] = {}
for row in all_rows:
row["atlas_v9_url"] = build_url(base_url, row["repd_ref"], row["technology"])
row["producer"] = "companies/scripts/202608300232-build-atlas-v9-company-repd-links.py"
key = (row["company_number"], row["repd_ref"], row["technology"], row["source_artifact"])
unique[key] = row
rows = [unique[key] for key in sorted(unique)]
output = root / "derived/atlas_v9_company_repd_links.parquet"
write_parquet(connection, rows, output)
linked_count = int(connection.execute(f"SELECT count(*) FROM read_parquet('{sql_path(output)}')").fetchone()[0])
require(linked_count == len(rows), "derived Parquet row closure mismatch")
connection.close()
changed_sources, replacement_count = rewrite_sources(root, base_url)
pointer = {
"schema": "companies.atlas-v9-pointer.v1",
"classification": "PROMOTED_ATLAS_V9_RELATION_SOURCE",
"generation": generation,
"release_id": release_id,
"base_url": base_url,
"privacy": "NO_PERSONAL_DATA",
"raw_companies_house_data_stored": False,
}
pointer_path = root / "state/atlas-v9-current.json"
pointer_path.parent.mkdir(parents=True, exist_ok=True)
pointer_path.write_text(json.dumps(pointer, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
manifest = {
"schema": "companies.atlas-v9-company-repd-links-manifest.v1",
"classification": "DETERMINISTIC_COMPACT_RELATION_BUILT",
"generation": generation,
"release_id": release_id,
"base_url": base_url,
"output": output.relative_to(root).as_posix(),
"output_rows": linked_count,
"output_bytes": output.stat().st_size,
"output_sha256": sha256_file(output),
"compression": "ZSTD",
"source_files": sources,
"source_rows_scanned": sum(int(item["rows_scanned"]) for item in sources),
"source_rows_linked_before_deduplication": sum(int(item["rows_linked"]) for item in sources),
"source_rows_abstained": sum(int(item["rows_abstained"]) for item in sources),
"mutable_source_files_rewritten": sorted(changed_sources),
"mutable_source_replacement_count": replacement_count,
"raw_companies_house_data_stored": False,
"personal_data": False,
"columns": [
"relationship_id", "company_number", "repd_ref", "technology", "role",
"source_status", "source_artifact", "evidence_class", "link_status",
"atlas_v9_url", "producer"
],
}
manifest_path = root / "reports/atlas-v9-company-repd-links-manifest.json"
manifest_path.parent.mkdir(parents=True, exist_ok=True)
manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
print(json.dumps(manifest, sort_keys=True))
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as error: # noqa: BLE001
print(f"COMPANIES_ATLAS_V9_BUILD_FAILED: {error}", file=sys.stderr)
raise