GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / data-gridatlas / compiler

Materialise Live Data Release and 3 more files

A Python command-line tool in the compiler folder of Data GridAtlas that reads sources, membership and live release, using SHA-256.

658 lines of Python and JavaScript from data-gridatlas, energy-transition-simulator, in 4 files. Topic: Maps, GIS and field navigation. Section 484 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. Materialise Live Data Release automation · data-gridatlas / compiler/202608291237-materialise-live-data-release.py lines 1–300
  2. Build Renewable Energy Planning Database (REPD) Routing Release automation · data-gridatlas / compiler/202608291410-build-repd-routing-release.py lines 1–113
  3. Fidelity storage · data-gridatlas / tools/202608301930-fidelity.py lines 1–171
  4. LiDAR Onsite geodesy · energy-transition-simulator / prototype/mod/lidar-onsite.js lines 1–74

Materialise Live Data Release

A Python command-line tool in the compiler folder of Data GridAtlas that reads sources, membership and live release, using SHA-256.

automationdata-gridatlas / compiler/202608291237-materialise-live-data-release.py · lines 1–300 of 300 · version 2026-08-29 12:37 · Entry point · pattern validate_candidate (shared by 2 files)

What it does
It loads sources, membership and live release. Defines 13 functions or classes, including reject_duplicate_keys, read_json, canonical_json, sha256, require. Uses libraries __future__, argparse, copy, hashlib, html. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: Parquet file layers.parquet; Parquet file sources.parquet; Parquet file layer_membership.parquet; JSON file release.json; JSON file browser-layer-registry.json; JSON file full-candidate-verification.json; JSON file 202608291237-live-data-release.json; DuckDB queries. Out: JSON file browser-layer-registry.json; JSON file release.json.
Downstream impact
Used directly by 1 file: Publish Live Data GridAtlas Workflow (data-gridatlas).
What it achieves
It reads JSON (`read_json`), finds placeholders (`find_placeholders`) and validates candidate (`validate_candidate`). Materialise the immutable Data Grid Atlas live release. It reads `browser-layer-registry.json`. It accepts `--repository`, `--contract` and `--candidate`.
Why it matters
Run by Publish Live Data GridAtlas Workflow.
Application
data-gridatlas · compiler · Python CLI
Uses
__future__, argparse, copy, hashlib, html, json, shutil, pathlib
Used by
run by Publish Live Data GridAtlas Workflow (workflow run)
Produces
reject_duplicate_keys, read_json, canonical_json, sha256, require, find_placeholders, validate_candidate, copy_tree, make_live_browser_registry, make_index, make_readme, materialise
Defines here
reject_duplicate_keys, read_json, canonical_json, sha256, require, find_placeholders, validate_candidate, copy_tree, make_live_browser_registry, make_index, make_readme, materialise, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-gridatlas@203f9dc3764c05153c2b95f8ace88eb543f26c1e compiler/202608291237-materialise-live-data-release.py:1-300 · blob ce72fd46c52af14fb97d7d1407a9adffec8e31e3 · 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
"""Materialise the immutable 202608291237 Data Grid Atlas live release."""

from __future__ import annotations

import argparse
import copy
import hashlib
import html
import json
import shutil
from pathlib import Path


def reject_duplicate_keys(pairs: list[tuple[str, object]]) -> dict:
    result: dict[str, object] = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"duplicate JSON key: {key}")
        result[key] = value
    return result


def read_json(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=reject_duplicate_keys)


def canonical_json(value: object) -> bytes:
    return (json.dumps(value, sort_keys=True, indent=2, ensure_ascii=False) + "\n").encode("utf-8")


def sha256(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 require(condition: bool, message: str) -> None:
    if not condition:
        raise SystemExit(message)


def find_placeholders(value: object, path: str = "contract") -> list[str]:
    found: list[str] = []
    if isinstance(value, dict):
        for key, item in value.items():
            found.extend(find_placeholders(item, f"{path}.{key}"))
    elif isinstance(value, list):
        for index, item in enumerate(value):
            found.extend(find_placeholders(item, f"{path}[{index}]"))
    elif isinstance(value, str) and value.startswith("__NEW_CANDIDATE_"):
        found.append(f"{path}={value}")
    return found


def validate_candidate(candidate: Path, proof_path: Path, contract: dict) -> tuple[dict, dict]:
    candidate_contract = contract["candidate"]
    manifest_path = candidate / "manifest.json"
    manifest = read_json(manifest_path)
    proof = read_json(proof_path)

    require(sha256(manifest_path) == candidate_contract["candidate_manifest_sha256"], "candidate manifest SHA-256 mismatch")
    require(sha256(proof_path) == candidate_contract["candidate_proof_sha256"], "candidate proof SHA-256 mismatch")
    require(manifest.get("classification") == "FULL_V8_TRANSPLANT_CANDIDATE", "candidate classification mismatch")
    require(manifest.get("release") is False, "input candidate release flag changed")
    require(manifest.get("pages_publication") is False, "input candidate Pages flag changed")
    require(manifest.get("current_pointer") is False, "input candidate current pointer changed")
    require(manifest.get("v8_untouched") is True, "input candidate does not preserve V8")
    require(manifest.get("source", {}).get("commit") == contract["oracle"]["commit"], "V8 oracle commit mismatch")
    require(manifest.get("source", {}).get("commit_tree_sha1") == contract["oracle"]["tree_sha1"], "V8 oracle tree mismatch")
    require(proof.get("classification") == candidate_contract["proof_classification"], "candidate proof classification mismatch")
    require(proof.get("failed") == 0, "candidate proof contains failures")
    require(proof.get("repository_source_commit") == candidate_contract["source_commit"], "candidate proof source commit mismatch")
    require(proof.get("v8_untouched") is True, "candidate proof does not preserve V8")

    closure = manifest.get("closure", {})
    for key in ("sources", "layers", "features", "layer_membership_rows", "coordinate_tuples"):
        require(closure.get(key) == contract["closure"][key], f"candidate closure mismatch: {key}")
    require(manifest.get("raw_geojson_outputs") == contract["closure"]["raw_geojson_outputs"], "raw GeoJSON output mismatch")

    declared_items = manifest.get("artifacts", [])
    declared = {item["path"]: item for item in declared_items}
    require(len(declared) == len(declared_items), "duplicate candidate artifact path")
    actual = {
        path.relative_to(candidate).as_posix()
        for path in candidate.rglob("*")
        if path.is_file()
    }
    require(actual == set(declared) | {"manifest.json"}, "candidate file closure mismatch")
    require(len(actual) == candidate_contract["candidate_files"], "candidate file count mismatch")
    require(sum((candidate / relative).stat().st_size for relative in actual) == candidate_contract["candidate_bytes"], "candidate byte closure mismatch")
    for relative, item in declared.items():
        path = candidate / relative
        require(path.stat().st_size == item["bytes"], f"candidate byte mismatch: {relative}")
        require(sha256(path) == item["sha256"], f"candidate SHA-256 mismatch: {relative}")
    return manifest, proof


def copy_tree(source: Path, destination: Path) -> None:
    for path in sorted(item for item in source.rglob("*") if item.is_file()):
        target = destination / path.relative_to(source)
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copyfile(path, target)


def make_live_browser_registry(candidate_registry: dict, contract: dict) -> dict:
    registry = copy.deepcopy(candidate_registry)
    registry["candidate_generation"] = registry.get("generation")
    registry["schema"] = "data-gridatlas.live-browser-layer-registry.v1"
    registry["classification"] = "LIVE_IMMUTABLE_DATA_RELEASE"
    registry["generation"] = contract["release_id"]
    registry["release"] = True
    registry["pages_publication"] = True
    registry["current_pointer"] = False
    registry["base_url"] = contract["publication"]["pages_url"]
    registry["data_base_path"] = "data/"
    registry["candidate_manifest_url"] = "data/manifest.json"
    registry["layers_url"] = "data/layers.parquet"
    registry["sources_url"] = "data/sources.parquet"
    registry["layer_membership_url"] = "data/layer_membership.parquet"
    registry["load_policy"] = {
        "initial_fetches": 0,
        "default_visible_layers": [],
        "fetch_on_user_enable_only": True,
    }
    registry["receipt_semantics"] = {
        "enabled": "selectable",
        "publishable": "available_in_this_immutable_public_release",
        "default_visible": False,
        "browser_initial_fetches": 0,
    }
    for group in registry.get("groups", []):
        for layer in group.get("layers", []):
            v9_data = layer.get("v9_data")
            require(isinstance(v9_data, dict), f"missing V9 data mapping: {layer.get('id')}")
            parquet_path = v9_data.get("parquet_path")
            require(isinstance(parquet_path, str), f"missing Parquet path: {layer.get('id')}")
            require(parquet_path.startswith(("partitions/", "derived/")), f"forbidden Parquet path: {parquet_path}")
            v9_data["candidate_enabled"] = layer.get("enabled")
            v9_data["candidate_publishable"] = layer.get("publishable")
            v9_data["candidate_preload"] = layer.get("preload")
            v9_data["parquet_url"] = f"data/{parquet_path}"
            v9_data["membership_url"] = "data/layer_membership.parquet"
            v9_data["data_live"] = True
            layer["available"] = True
            layer["publishable"] = True
            layer["enabled"] = True
            layer["default_visible"] = False
            layer["preload"] = False
            layer["url"] = None
    return registry


def make_index(contract: dict, candidate_manifest: dict) -> str:
    candidate = contract["candidate"]
    closure = contract["closure"]
    release_id = html.escape(contract["release_id"])
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>{release_id} — Data Grid Atlas V9</title>
  <style>
    :root {{ color-scheme:dark; font-family:ui-sans-serif,system-ui,sans-serif; }}
    body {{ max-width:880px; margin:auto; padding:2rem 1.25rem 4rem; background:#07111f; color:#eaf2ff; }}
    .live {{ color:#78e6a2; font-weight:800; letter-spacing:.08em; }}
    .card {{ background:#101f33; border:1px solid #29415f; border-radius:12px; padding:1rem 1.2rem; margin:1rem 0; }}
    dl {{ display:grid; grid-template-columns:max-content 1fr; gap:.45rem 1rem; }} dt {{ color:#9fb7d3; }} dd {{ margin:0; }}
    a {{ color:#8bc7ff; }} code {{ overflow-wrap:anywhere; }}
  </style>
</head>
<body>
  <p class="live">LIVE · IMMUTABLE · TIMESTAMPED</p>
  <h1>Data Grid Atlas V9</h1>
  <p>Release <code>{release_id}</code>. This receipt does not load the Parquet payload.</p>
  <div class="card"><dl>
    <dt>Sources</dt><dd>{closure['sources']:,}</dd>
    <dt>Layers</dt><dd>{closure['layers']:,}</dd>
    <dt>Features</dt><dd>{closure['features']:,}</dd>
    <dt>Memberships</dt><dd>{closure['layer_membership_rows']:,}</dd>
    <dt>Artifact</dt><dd><code>{html.escape(str(candidate['artifact_digest']))}</code></dd>
    <dt>Candidate manifest</dt><dd><code>{html.escape(str(candidate['candidate_manifest_sha256']))}</code></dd>
    <dt>V8 oracle</dt><dd><code>{html.escape(contract['oracle']['commit'])}</code> (untouched)</dd>
    <dt>Consumer</dt><dd>Timestamp-bound verification required; current pointer deferred.</dd>
  </dl></div>
  <p>All authority, licence and quarantine labels are preserved. Public availability does not rewrite those evidence states.</p>
  <ul>
    <li><a href="release.json">Release manifest</a></li>
    <li><a href="browser-layer-registry.json">Browser layer registry</a></li>
    <li><a href="sha256sums.txt">SHA-256 ledger</a></li>
    <li><a href="data/manifest.json">Exact CI candidate manifest</a></li>
    <li><a href="readme.md">Release readme</a></li>
  </ul>
</body>
</html>
"""


def make_readme(contract: dict) -> str:
    closure = contract["closure"]
    return f"""# {contract['release_id']}

Immutable live Data Grid Atlas V9 data release.

- Sources: {closure['sources']:,}
- Layers: {closure['layers']:,}
- Features: {closure['features']:,}
- Layer memberships: {closure['layer_membership_rows']:,}
- Format: DuckDB-readable ZSTD Parquet
- V8 oracle: `{contract['oracle']['repository']}@{contract['oracle']['commit']}` (untouched)
- Candidate run: `{contract['candidate']['workflow_run_id']}`
- Candidate artifact: `{contract['candidate']['artifact_id']}`
- Current pointer: deferred until exact Atlas V9 consumer and rendered-browser proof

The exact verified candidate is retained under `data/`. The top-level browser registry adds timestamp-bound Parquet URLs without rewriting the candidate registry. Authority, licence and quarantine labels remain visible and unchanged.
"""


def materialise(args: argparse.Namespace) -> None:
    repository = args.repository.resolve()
    contract = read_json(repository / args.contract)
    placeholders = find_placeholders(contract)
    require(not placeholders, "unresolved live-release placeholders: " + ", ".join(placeholders))
    require(args.source_commit != contract["candidate"]["source_commit"], "promotion source must succeed candidate source")

    candidate = args.candidate.resolve()
    proof_path = args.proof.resolve()
    output = args.output.resolve()
    require(not output.exists(), f"refusing existing output: {output}")
    require(output.name == contract["release_id"], "output folder must equal release id")
    candidate_manifest, candidate_proof = validate_candidate(candidate, proof_path, contract)

    output.mkdir(parents=True)
    copy_tree(candidate, output / "data")
    proof_target = output / "proof" / "full-candidate-verification.json"
    proof_target.parent.mkdir(parents=True)
    shutil.copyfile(proof_path, proof_target)
    for relative in contract["contract_snapshots"]:
        source = repository / relative
        target = output / "contracts" / Path(relative).name
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copyfile(source, target)

    live_registry = make_live_browser_registry(read_json(candidate / "browser-layer-registry.json"), contract)
    (output / "browser-layer-registry.json").write_bytes(canonical_json(live_registry))
    (output / "index.html").write_text(make_index(contract, candidate_manifest), encoding="utf-8", newline="\n")
    (output / "readme.md").write_text(make_readme(contract), encoding="utf-8", newline="\n")

    payload_files = []
    for path in sorted(item for item in output.rglob("*") if item.is_file()):
        payload_files.append({
            "path": path.relative_to(output).as_posix(),
            "bytes": path.stat().st_size,
            "sha256": sha256(path),
        })
    release = {
        "schema": "data-gridatlas.immutable-live-data-release.v1",
        "release_id": contract["release_id"],
        "incepted_at": contract["incepted_at"],
        "classification": "LIVE_IMMUTABLE_DATA_RELEASE",
        "release": True,
        "immutable": True,
        "current_pointer": False,
        "repository": contract["repository"],
        "repository_path": contract["publication"]["repository_path"],
        "pages_url": contract["publication"]["pages_url"],
        "packaging_source_commit": args.source_commit,
        "candidate": contract["candidate"],
        "candidate_proof_sha256": sha256(proof_path),
        "candidate_closure": candidate_manifest["closure"],
        "oracle": contract["oracle"],
        "runtime": candidate_manifest["runtime"],
        "authority_licence_and_quarantine_labels_preserved": True,
        "v8_untouched": candidate_manifest["v8_untouched"] and candidate_proof["v8_untouched"],
        "files": payload_files,
    }
    (output / "release.json").write_bytes(canonical_json(release))

    checksums = []
    for path in sorted(item for item in output.rglob("*") if item.is_file()):
        checksums.append(f"{sha256(path)}  {path.relative_to(output).as_posix()}")
    (output / "sha256sums.txt").write_text("\n".join(checksums) + "\n", encoding="utf-8", newline="\n")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--repository", type=Path, required=True)
    parser.add_argument("--contract", default="contracts/202608291237-live-data-release.json")
    parser.add_argument("--candidate", type=Path, required=True)
    parser.add_argument("--proof", type=Path, required=True)
    parser.add_argument("--source-commit", required=True)
    parser.add_argument("--output", type=Path, required=True)
    materialise(parser.parse_args())


if __name__ == "__main__":
    main()

Build Renewable Energy Planning Database (REPD) Routing Release

A Python command-line tool in the compiler folder of Data GridAtlas that reads projects and the REPD register, using SHA-256.

automationdata-gridatlas / compiler/202608291410-build-repd-routing-release.py · lines 1–113 of 113 · 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 canonical_json, sha256, record, require, main. Uses libraries __future__, argparse, hashlib, html, json. 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. Out: JSON file projects.json; JSON file release.json.
Downstream impact
Used directly by 1 file: Publish Renewable Energy Planning Database (REPD) Routing Workflow (data-gridatlas).
What it achieves
It is built from the canonical JSON helper (`canonical_json`), the sha256 step (`sha256`) and the record step (`record`). Compile the immutable PipelineNews/V8 deep-link routing dependency. It accepts `--contract`, `--source` and `--source-commit`.
Why it matters
Run by Publish Renewable Energy Planning Database (REPD) Routing Workflow.
Application
data-gridatlas · compiler · Python CLI
Uses
__future__, argparse, hashlib, html, json, pathlib, re
Used by
run by Publish Renewable Energy Planning Database (REPD) Routing Workflow (workflow run)
Produces
canonical_json, sha256, record, require, main
Defines here
canonical_json, sha256, record, require, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-gridatlas@203f9dc3764c05153c2b95f8ace88eb543f26c1e compiler/202608291410-build-repd-routing-release.py:1-113 · blob 77f72a56d8f9b86056eb2c05ccc925b26a0b716b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: field_execution · users: IPP_developer, EPC_contractor, landowner_planner · canonical: supporting_data
#!/usr/bin/env python3
"""Compile the immutable PipelineNews/V8 deep-link routing dependency."""

from __future__ import annotations

import argparse
import hashlib
import html
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 canonical_json(value: object) -> bytes:
    return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n").encode("utf-8")


def sha256(raw: bytes) -> str:
    return hashlib.sha256(raw).hexdigest()


def record(name: str, raw: bytes) -> dict:
    return {"path": name, "bytes": len(raw), "sha256": sha256(raw)}


def require(condition: bool, message: str) -> None:
    if not condition:
        raise RuntimeError(message)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--contract", type=Path, required=True)
    parser.add_argument("--source", type=Path, required=True)
    parser.add_argument("--source-commit", required=True)
    parser.add_argument("--source-parent-commit", required=True)
    parser.add_argument("--source-committed-at", required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()

    require(SHA40.fullmatch(args.source_commit) is not None, "source commit must be exact SHA-1")
    require(SHA40.fullmatch(args.source_parent_commit) is not None, "source parent commit must be exact SHA-1")
    require(re.match(r"^\d{4}-\d{2}-\d{2}T", 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")
    require(contract.get("source_parent_commit") == args.source_parent_commit, "source parent commit drift")
    source_raw = args.source.read_bytes()
    source = contract["source"]
    require(len(source_raw) == source["bytes"] and sha256(source_raw) == source["sha256"], "routing source bytes drift")
    payload = json.loads(source_raw)
    require(payload.get("schema") == source["schema"], "routing source schema drift")
    require(payload.get("generation") == "202608270055", "routing source generation drift")
    require(len(payload.get("rows", [])) == contract["closure"]["projects"], "routing source project count drift")

    require(not args.output.exists(), f"refusing existing output: {args.output}")
    require(args.output.name == RELEASE_ID, "output folder identity drift")
    args.output.mkdir(parents=True)
    projects_raw = source_raw
    (args.output / "projects.json").write_bytes(projects_raw)

    index_raw = f"""<!doctype html>
<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>Data Grid Atlas · REPD routing {GENERATION}</title><style>body{{font:16px/1.5 system-ui;max-width:860px;margin:3rem auto;padding:0 1rem;color:#132}}code{{word-break:break-all}}a{{color:#0563c1}}</style></head><body><main><h1>REPD deep-link routing data</h1><p>Immutable time  … [line shortened here: 1,050 characters; full line on GitHub]
""".encode("utf-8")
    (args.output / "index.html").write_bytes(index_raw)

    release = {
        "schema": "data-gridatlas.repd-routing-release.v1",
        "generation": GENERATION,
        "release_id": RELEASE_ID,
        "incepted_at": contract["incepted_at"],
        "source_commit": args.source_commit,
        "source_parent_commit": args.source_parent_commit,
        "source_committed_at": args.source_committed_at,
        "classification": "IMMUTABLE_REPD_ROUTING_RELEASE",
        "immutable": True,
        "public_url": contract["folder_contract"]["public_url"],
        "source": source,
        "coverage": contract["closure"],
        "files": {
            "index": record("index.html", index_raw),
            "projects": record("projects.json", projects_raw),
        },
        "consumer_contract": {
            "decode_geometry_status": True,
            "select_only_geometry_status_valid": True,
            "identity_key": "repd_ref",
            "existing_layer_release_pointer_unchanged": True,
        },
    }
    release_raw = canonical_json(release)
    (args.output / "release.json").write_bytes(release_raw)
    sums = "".join(
        f"{sha256(raw)}  {name}\n"
        for name, raw in sorted({"index.html": index_raw, "projects.json": projects_raw, "release.json": release_raw}.items())
    ).encode("utf-8")
    (args.output / "sha256sums.txt").write_bytes(sums)
    print(json.dumps({
        "classification": release["classification"],
        "release_id": RELEASE_ID,
        "files": 4,
        "projects_sha256": sha256(projects_raw),
        "release_sha256": sha256(release_raw),
    }, sort_keys=True))


if __name__ == "__main__":
    main()

Fidelity

A Python command-line tool in the tools folder of Data GridAtlas that compares one V8 GeoJSON source with one V9 Parquet partition, using SHA-256.

storagedata-gridatlas / tools/202608301930-fidelity.py · lines 1–171 of 171 · version 2026-08-30 19:30 · Entry point · pattern sha256_text (shared by 4 files)

What it does
It loads data. Defines canonical, sha256_text, parse_args, main. Uses libraries __future__, argparse, hashlib, json, os. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: 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
Defines `canonical`, `sha256_text` and `parse_args`. It accepts `--duckdb-runtime-bytes` and `--network-mbit`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-gridatlas · tools · Python CLI
Uses
__future__, argparse, hashlib, json, os, pathlib, sys, time
Used by
none found
Produces
canonical, sha256_text, parse_args, main
Defines here
canonical, sha256_text, parse_args, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-gridatlas@203f9dc3764c05153c2b95f8ace88eb543f26c1e tools/202608301930-fidelity.py:1-171 · blob 7077a8dce3e6e3f061f2c3684231d819ebad1838 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Compare one V8 GeoJSON source with one V9 Parquet partition.

Usage:
  python3 tools/202608301930-fidelity.py PARTITION.parquet ORIGINAL.geojson

The report deliberately separates fidelity from delivery cost. Dropped properties are
reported as a policy surface; they do not by themselves fail geometry fidelity.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path
import sys
import time
from typing import Any

import duckdb


def canonical(value: Any) -> str:
    return json.dumps(
        value,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
        allow_nan=False,
    )


def sha256_text(value: str) -> str:
    return hashlib.sha256(value.encode("utf-8")).hexdigest()


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("partition", type=Path)
    parser.add_argument("original", type=Path)
    parser.add_argument(
        "--duckdb-runtime-bytes",
        type=int,
        default=int(os.environ.get("DUCKDB_RUNTIME_BYTES", "35700000")),
        help="Estimated browser DuckDB-WASM module + worker bytes.",
    )
    parser.add_argument(
        "--network-mbit",
        type=float,
        default=float(os.environ.get("NETWORK_MBIT", "20")),
    )
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    started = time.monotonic()
    if not args.partition.is_file():
        raise FileNotFoundError(args.partition)
    if not args.original.is_file():
        raise FileNotFoundError(args.original)
    if args.network_mbit <= 0:
        raise ValueError("network-mbit must be positive")

    with args.original.open("r", encoding="utf-8") as handle:
        original = json.load(handle)
    features = original.get("features")
    if original.get("type") != "FeatureCollection" or not isinstance(features, list):
        raise ValueError("origin is not a GeoJSON FeatureCollection")

    escaped = str(args.partition).replace("'", "''")
    query = f"""
        SELECT feature_index,
               geometry_json,
               properties_json,
               original_feature_sha256,
               projected_feature_sha256
        FROM read_parquet('{escaped}')
        ORDER BY feature_index
    """
    connection = duckdb.connect(database=":memory:")
    try:
        rows = connection.sql(query).fetchall()
    finally:
        connection.close()

    dropped: set[str] = set()
    added: set[str] = set()
    changed: set[str] = set()
    report: dict[str, Any] = {
        "schema": "data-gridatlas.layer-fidelity.v1",
        "layer": args.partition.stem,
        "partition": str(args.partition),
        "origin": str(args.original),
        "original_features": len(features),
        "partition_rows": len(rows),
        "original_bytes": args.original.stat().st_size,
        "partition_bytes": args.partition.stat().st_size,
        "hash_mismatch": 0,
        "projected_mismatch": 0,
        "coord_mismatch": 0,
    }

    for index, (feature, row) in enumerate(zip(features, rows, strict=False)):
        _, geometry_json, properties_json, original_sha, projected_sha = row
        if sha256_text(canonical(feature)) != original_sha:
            report["hash_mismatch"] += 1

        geometry = json.loads(str(geometry_json))
        properties = json.loads(str(properties_json or "{}"))
        if geometry != feature.get("geometry"):
            report["coord_mismatch"] += 1

        projected = {"type": "Feature", "geometry": geometry, "properties": properties}
        if sha256_text(canonical(projected)) != projected_sha:
            report["projected_mismatch"] += 1

        original_properties = feature.get("properties") or {}
        for key, value in original_properties.items():
            if key not in properties:
                dropped.add(key)
            elif properties[key] != value:
                changed.add(key)
        for key in properties:
            if key not in original_properties:
                added.add(key)

    report["count_match"] = len(features) == len(rows)
    report["missing_partition_rows"] = max(0, len(features) - len(rows))
    report["extra_partition_rows"] = max(0, len(rows) - len(features))
    report["prop_keys_dropped"] = sorted(dropped)
    report["prop_keys_added"] = sorted(added)
    report["prop_keys_changed"] = sorted(changed)
    report["fidelity"] = (
        "PASS"
        if report["count_match"]
        and report["hash_mismatch"] == 0
        and report["projected_mismatch"] == 0
        and report["coord_mismatch"] == 0
        else "FAIL"
    )

    bits_per_second = args.network_mbit * 1_000_000
    report["network_mbit"] = args.network_mbit
    report["duckdb_runtime_bytes"] = args.duckdb_runtime_bytes
    report["delivery_budget_s_at_20mbit"] = round(report["original_bytes"] * 8 / bits_per_second, 1)
    report["on_demand_budget_s_at_20mbit"] = round(
        (args.duckdb_runtime_bytes + report["partition_bytes"]) * 8 / bits_per_second,
        1,
    )
    report["seconds"] = round(time.monotonic() - started, 2)
    print(json.dumps(report, ensure_ascii=False, sort_keys=True))
    return 0 if report["fidelity"] == "PASS" else 1


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as error:  # Fail closed with machine-readable evidence.
        print(
            json.dumps(
                {
                    "schema": "data-gridatlas.layer-fidelity.v1",
                    "fidelity": "ERROR",
                    "error": f"{type(error).__name__}: {error}",
                },
                sort_keys=True,
            )
        )
        raise SystemExit(2)

LiDAR Onsite

A JavaScript file in the prototype folder of Energy Transition Simulator that fetches LiDAR terrain, using OSTN15 and Helmert.

geodesyenergy-transition-simulator / prototype/mod/lidar-onsite.js · lines 1–74 of 74 · Not reached from any entry point (candidate for review)

What it does
It fetches LiDAR terrain. Defines 8 functions or classes, including PF, wait, b64, area, dist. Side effects: changes the web page (DOM); makes network requests.
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: LiDAR terrain.
Inputs & outputs
In: JSON file index.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
What it achieves
It is built from the wait step (`wait`), the b64 step (`b64`) and the area step (`area`). Onsite LiDAR survey as the wireframe ground mesh, on real coordinates. It reads `mod/lidar-onsite/index.json`.
Why it matters
No other file in the estate was found to import it.
Application
energy-transition-simulator · prototype/mod · script
Uses
none found
Used by
none found
Produces
PF, wait, b64, area, dist, mesh, H, refresh
Defines here
PF, wait, b64, area, dist, mesh, H, refresh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/lidar-onsite.js:1-74 · blob 5ece2b1d8af2ecdacedcd217a02c0b3e6418880a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
// lidar-onsite: onsite LiDAR survey as the wireframe ground mesh, on real coordinates.
// Data: EA LiDAR 1 m DTM read ONLY from local caches (E:\lidar-cache etc., via the local mirror), baked by
// mod/lidar-onsite/bake.py into mod/lidar-onsite/<area>.json. Never calls the EA WCS.
// Coordinates: every mesh node is a British National Grid point (E, N) on the 1 m lattice, turned into WGS84 with
// OSTN15 (place-frame fromBng) and then into the block's local metres around its place key. Heights are the
// LiDAR heights relative to the LiDAR height at the anchor, so the mesh sits on the map terrain at the anchor.
// One block per cached 1 km tile, its GPU buffer built once (PF.wireBuffer), never per frame.
(function () {
  const R = 1000, NEAR = 3000, NOD = -32768;
  let on = false, areas = null, loaded = {}, btn = null, lastKey = '';
  const PF = () => window.__pf && window.__pf.PF;
  function wait(f) { if (window.SIM && PF()) f(); else setTimeout(() => wait(f), 200); }
  const b64 = s => { const bin = atob(s), u = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i); return new Int16Array(u.buffer); };
  async function area(E, N) {
    if (!areas) areas = await fetch('mod/lidar-onsite/index.json').then(r => r.ok ? r.json() : []).catch(() => []);
    const a = areas.find(a => Math.hypot(a.E - E, a.N - N) < a.search - R);
    if (!a) return null;
    if (!loaded[a.name]) loaded[a.name] = await fetch('mod/lidar-onsite/' + a.name + '.json').then(r => r.json());
    return loaded[a.name];
  }
  // Distance from (E, N) to a patch rectangle, metres.
  const dist = (p, E, N) => Math.hypot(Math.max(p.e0 - E, 0, E - (p.e0 + (p.w - 1) * p.step)), Math.max(p.n0 - N, 0, N - (p.n0 + (p.h - 1) * p.step)));
  function mesh(p) {
    if (p.block) return p.block;
    const P = PF(), q = b64(p.cm), s = p.step, ec = p.e0 + (p.w - 1) * s / 2, nc = p.n0 + (p.h - 1) * s / 2;
    const g = P.fromBng(ec, nc), anchor = P.placeKey(g.lat, g.lon); p.engine = g.engine;
    // Real coordinates: node (E, N) -> WGS84 by OSTN15 -> local metres around the anchor. Exact at 3 control
    // nodes, affine between them (the OSTN15 shift varies by millimetres across 1 km).
    const o = P.bngToWire(anchor, p.e0, p.n0), ex = P.bngToWire(anchor, p.e0 + 1000, p.n0), ny = P.bngToWire(anchor, p.e0, p.n0 + 1000);
    const ax = (ex.x - o.x) / 1000, ay = (ex.y - o.y) / 1000, bx = (ny.x - o.x) / 1000, by = (ny.y - o.y) / 1000;
    const H = (i, j) => q[j * p.w + i];
    // Reference height: the LiDAR sample nearest the anchor (so the anchor's map-terrain height lines up with it).
    const aE = P.wireToBng(anchor, 0, 0); let best = 1e18, ref = 0;
    for (let j = 0; j < p.h; j++) for (let i = 0; i < p.w; i++) { const v = H(i, j); if (v === NOD) continue;
      const d = (p.e0 + i * s - aE.e) ** 2 + (p.n0 + j * s - aE.n) ** 2; if (d < best) { best = d; ref = v; } }
    const L = [], X = (i, j) => { const de = i * s, dn = j * s; return [o.x + ax * de + bx * dn, o.y + ay * de + by * dn, (H(i, j) - ref) / 100]; };
    for (let j = 0; j < p.h; j++) for (let i = 0; i < p.w; i++) {
      if (H(i, j) === NOD) continue; const a = X(i, j);
      if (i + 1 < p.w && H(i + 1, j) !== NOD) { const b = X(i + 1, j); L.push([a[0], a[1], a[2], b[0], b[1], b[2]]); }
      if (j + 1 < p.h && H(i, j + 1) !== NOD) { const b = X(i, j + 1); L.push([a[0], a[1], a[2], b[0], b[1], b[2]]); }
    }
    p.block = { lon: anchor.lon, lat: anchor.lat, anchor, lines: L, buf: P.wireBuffer(anchor, L), lidar: true, tile: p.tile };
    return p.block;
  }
  async function refresh(force) {
    const S = window.SIM, P = PF();
    if (!on) { S.removeWhere(b => b.lidar); lastKey = ''; return; }
    const c = S.map.getCenter(), g = P.toBng(c.lat, c.lng), key = Math.round(g.e / 100) + ',' + Math.round(g.n / 100);
    if (key === lastKey && !force) return; lastKey = key;
    const a = await area(g.e, g.n);
    S.removeWhere(b => b.lidar);
    if (!a) { S.info('No LiDAR cached here (no baked local-cache area covers this point). Heights: none drawn.'); return; }
    const within = a.patches.filter(p => dist(p, g.e, g.n) <= R);
    const near = a.patches.filter(p => dist(p, g.e, g.n) <= NEAR).sort((x, y) => dist(x, g.e, g.n) - dist(y, g.e, g.n));
    for (const p of near) S.addBlock(mesh(p));
    const eng = near.length && near[0].engine !== 'OSTN15' ? 'Helmert (estimate, about 1-3 m)' : 'OSTN15';
    const cr = a.credit + '. Mesh every ' + a.step + ' m on the national grid, placed by ' + eng + '.';
    if (within.length) {
      const km2 = within.reduce((s, p) => s + p.valid, 0) / 1e6;
      S.info(`Onsite LiDAR: ${within.length} cached 1 km tile(s) within 1 km, ${km2.toFixed(2)} km² of measured ground. ${cr}`);
    } else if (near.length) {
      const p = near[0], d = dist(p, g.e, g.n), pe = p.e0 + p.w * p.step / 2 - g.e, pn = p.n0 + p.h * p.step / 2 - g.n;
      const dir = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.round(((Math.atan2(pe, pn) * 180 / Math.PI + 360) % 360) / 45) % 8];
      S.info(`No LiDAR cached here (none within 1 km). Nearest cached patches drawn: ${near.length}, the closest ${(d / 1000).toFixed(1)} km ${dir}. Unmeasured ground is not drawn. ${cr}`);
    } else S.info('No LiDAR cached here (none within 3 km). ' + a.credit);
  }
  wait(() => {
    const S = window.SIM;
    btn = S.addButton ? S.addButton('LiDAR onsite', () => { on = !on; btn.classList.toggle('on', on); refresh(true); }) : null;
    S.map.on('moveend', () => refresh(false));
    window.__lidarOnsite = { enable() { on = true; if (btn) btn.classList.add('on'); return refresh(true); }, count: () => S.blocks.filter(b => b.lidar).length,
      segs: () => S.blocks.filter(b => b.lidar).reduce((s, b) => s + b.lines.length, 0) };
  });
})();