GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/world

Atlas — World Page and 2 more files

A map page in GridAtlas that maps grid 400kV, grid line and scope pt. Published at https://gridatlas.globalgrid2050.com/atlas/world/.

636 lines of HTML and Python from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 612 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. Atlas — World Page render · gridatlas / atlas/world/index.html lines 1–325
  2. Compare Live vs Candidate storage · gridatlas / atman/202608290828-compare-live-vs-candidate.py lines 1–125
  3. Compare Incumbent Successor storage · gridatlas / atman/202608291239-compare-incumbent-successor.py lines 1–186

Atlas — World Page

A map page in GridAtlas that maps grid 400kV, grid line and scope pt. Published at https://gridatlas.globalgrid2050.com/atlas/world/.

rendergridatlas / atlas/world/index.html · lines 1–325 of 325 · Entry point · pattern bounds (shared by 8 files)

What it does
It maps grid 400kV, grid line and scope pt. Defines 8 functions or classes, including closeAll, item, toggle, note, Flow. Side effects: changes the web page (DOM); makes network requests.
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: 400kV. README: "`atlas/index.html` is the stable composer."
Inputs & outputs
In: GeoJSON file grid_400kv.geojson. Out: web page; interactive map. Voltage levels named: 400kV.
Downstream impact
Used directly by 2 files: Runners (claude); Summon (claude). It is itself an entry point, published at https://gridatlas.globalgrid2050.com/atlas/world/.
What it achieves
It is built from the close all helper (`closeAll`), the item step (`item`) and the toggle step (`toggle`). The README says: `atlas/index.html` is the stable composer. Its code works with 400 kV. It responds to click and change events.
Why it matters
Imported by Runners and Summon, from Claude.
Application
gridatlas · atlas/world · page
Uses
https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css, https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js
Used by
named by URL in Runners (estate URL), named by URL in Summon (estate URL)
Produces
closeAll, item, toggle, note, Flow, mk, stat, bounds
Defines here
closeAll, item, toggle, note, Flow, mk, stat, bounds
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/world/index.html:1-325 · blob 554b021777a5c7ef344462262302aeb47d293b7c · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover,user-scalable=no">
<title>GridAtlas World</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css">
<style>
  :root { color-scheme: dark; }
  html, body { margin:0; padding:0; height:100%; background:#000; overflow:hidden;
    font:12px/1.35 ui-monospace,SFMono-Regular,Menlo,monospace; color:#cfeef6;
    -webkit-text-size-adjust:100%; }

  /* THE WORLD IS THE PAGE. One bar of chrome, closed at rest, everything else map. */
  #map { position:fixed; inset:0; top:34px; background:#000; }
  #hud { position:fixed; inset:auto 0 0 0; padding:6px 10px calc(6px + env(safe-area-inset-bottom));
    background:linear-gradient(transparent,rgba(0,0,0,.82) 40%); pointer-events:none;
    display:flex; gap:14px; flex-wrap:wrap; font-size:11px; color:#8fd8e8; }
  #hud b { color:#eafcff; font-weight:600; }

  nav#bar { position:fixed; top:0; left:0; right:0; height:34px; z-index:40; display:flex;
    background:rgba(4,10,13,.94); border-bottom:1px solid rgba(80,220,240,.26);
    backdrop-filter:blur(6px); -webkit-backdrop-filter:blur(6px); }
  .m { position:relative; }
  .t { appearance:none; background:transparent; border:0; color:#cfeef6; font:inherit;
    letter-spacing:.06em; text-transform:uppercase; min-height:34px; padding:0 11px; cursor:pointer; }
  .t:hover, .m.open .t { background:rgba(80,220,240,.16); color:#eafcff; }
  .p { display:none; position:absolute; top:100%; left:0; min-width:230px; max-height:70vh;
    overflow:auto; padding:6px; background:rgba(4,10,13,.98);
    border:1px solid rgba(80,220,240,.3); border-top:0; box-shadow:0 12px 34px rgba(0,0,0,.6); }
  .m.open .p { display:block; }
  .p button, .p label { display:flex; align-items:center; gap:8px; width:100%; min-height:44px;
    box-sizing:border-box; background:transparent; border:0; color:#cfeef6; font:inherit;
    text-align:left; padding:0 10px; cursor:pointer; }
  .p button:hover, .p label:hover { background:rgba(80,220,240,.14); color:#eafcff; }
  .p hr { border:0; border-top:1px solid rgba(80,220,240,.18); margin:5px 2px; }
  .p .note { padding:6px 10px; color:#7fa6b0; font-style:italic; }
  .sw { width:11px; height:11px; border-radius:2px; flex:0 0 auto; }

  @media (max-width:700px) { .t { padding:0 8px; font-size:11px; } }
</style>

<nav id="bar" aria-label="World menu"></nav>
<div id="map"></div>
<div id="hud">
  <span>fps <b id="fps">—</b></span>
  <span>circuits <b id="nlines">0</b></span>
  <span>carriers <b id="nparts">0</b></span>
  <span>cores <b id="cores">—</b></span>
  <span>gpu <b id="gpu">—</b></span>
</div>

<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js"></script>
<script>
/* ══════════════════════════════════════════════════════════════════════
   GridAtlas World - a 2D world that is alive, not a document about one.

   The rule this is built to: text documents physics, it is not physics. So
   nothing here describes what the grid does. It draws it moving, on the GPU,
   and the machine's own numbers are on screen while it happens.

   ONE BAR OF CHROME, CLOSED AT REST. Six menus, the conventional desktop
   pattern. The map is the product and the first impression; the bar is 34px
   and everything else is world.

   WHY A CUSTOM WEBGL LAYER. The carriers moving along every circuit are one
   instanced draw call on the GPU, not DOM, not markers, not a per-frame
   GeoJSON rewrite. That is the difference between a few hundred moving things
   and tens of thousands of them, and it is why this is a simulation surface
   rather than a picture.
   ══════════════════════════════════════════════════════════════════════ */
'use strict';

const DATA = './grid_400kv.geojson';
const MENUS = ['File', 'Edit', 'Scope', 'View', 'Select layers', 'About'];

/* ── the bar ──────────────────────────────────────────────────────────── */
const bar = document.getElementById('bar');
const panels = {};
MENUS.forEach(name => {
  const m = document.createElement('div'); m.className = 'm';
  const t = document.createElement('button'); t.className = 't'; t.type = 'button';
  t.textContent = name; t.setAttribute('aria-expanded', 'false');
  const p = document.createElement('div'); p.className = 'p';
  t.addEventListener('click', e => {
    e.stopPropagation();
    const wasOpen = m.classList.contains('open');
    closeAll();
    if (!wasOpen) { m.classList.add('open'); t.setAttribute('aria-expanded', 'true'); }
  });
  m.append(t, p); bar.appendChild(m); panels[name] = p;
});
function closeAll() {
  bar.querySelectorAll('.m.open').forEach(m => {
    m.classList.remove('open');
    const t = m.querySelector('.t'); if (t) t.setAttribute('aria-expanded', 'false');
  });
}
document.addEventListener('click', closeAll);   /* self-minimising, per the brief */

function item(menu, label, fn) {
  const b = document.createElement('button');
  b.type = 'button'; b.textContent = label;
  b.addEventListener('click', () => { fn(); closeAll(); });
  panels[menu].appendChild(b); return b;
}
function toggle(menu, label, colour, on, fn) {
  const l = document.createElement('label');
  const c = document.createElement('input'); c.type = 'checkbox'; c.checked = on;
  c.style.cssText = 'width:18px;height:18px;accent-color:#4fd7ee';
  const sw = document.createElement('span'); sw.className = 'sw'; sw.style.background = colour;
  const s = document.createElement('span'); s.textContent = label;
  c.addEventListener('change', () => fn(c.checked));
  l.append(c, sw, s); panels[menu].appendChild(l); return c;
}
function note(menu, text) {
  const d = document.createElement('div'); d.className = 'note'; d.textContent = text;
  panels[menu].appendChild(d);
}

/* ── the map ──────────────────────────────────────────────────────────── */
const map = new maplibregl.Map({
  container: 'map',
  style: {
    version: 8, sources: {},   /* no glyphs key at all: null fails validation */
    layers: [{ id: 'void', type: 'background', paint: { 'background-color': '#000' } }]
  },
  center: [-2.6, 54.2], zoom: 5.2, attributionControl: false, antialias: true
});
map.addControl(new maplibregl.AttributionControl({ compact: true }), 'bottom-right');

/* ── the living layer: carriers advancing along every circuit, on the GPU ── */
class Flow {
  constructor(segments) {
    this.id = 'flow'; this.type = 'custom'; this.renderingMode = '2d';
    this.segments = segments;      // [ax,ay,bx,by] in mercator, flattened
    this.n = segments.length / 4;
    this.speed = 1.0; this.running = true; this.t = 0;
  }
  onAdd(_, gl) {
    const vs = `#version 300 es
      precision highp float;
      layout(location=0) in vec4 seg;      // ax ay bx by
      layout(location=1) in float phase;
      uniform mat4 u_matrix; uniform float u_t; uniform float u_size;
      out float v_a;
      void main(){
        float f = fract(phase + u_t);
        vec2 p = mix(seg.xy, seg.zw, f);
        gl_Position = u_matrix * vec4(p, 0.0, 1.0);
        gl_PointSize = u_size;
        v_a = 1.0 - abs(f - 0.5) * 1.2;    // brightest mid-span
      }`;
    const fs = `#version 300 es
      precision highp float;
      in float v_a; out vec4 o;
      void main(){
        vec2 d = gl_PointCoord - 0.5;
        float r = 1.0 - smoothstep(0.18, 0.5, length(d));
        o = vec4(0.42, 0.92, 1.0, r * v_a * 0.9);
      }`;
    const mk = (t, s) => { const sh = gl.createShader(t); gl.shaderSource(sh, s); gl.compileShader(sh); return sh; };
    this.prog = gl.createProgram();
    gl.attachShader(this.prog, mk(gl.VERTEX_SHADER, vs));
    gl.attachShader(this.prog, mk(gl.FRAGMENT_SHADER, fs));
    gl.linkProgram(this.prog);
    this.uM = gl.getUniformLocation(this.prog, 'u_matrix');
    this.uT = gl.getUniformLocation(this.prog, 'u_t');
    this.uS = gl.getUniformLocation(this.prog, 'u_size');

    this.bSeg = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, this.bSeg);
    gl.bufferData(gl.ARRAY_BUFFER, this.segments, gl.STATIC_DRAW);

    const ph = new Float32Array(this.n);
    for (let i = 0; i < this.n; i++) ph[i] = Math.random();
    this.bPh = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, this.bPh);
    gl.bufferData(gl.ARRAY_BUFFER, ph, gl.STATIC_DRAW);
  }
  render(gl, matrix) {
    if (this.running) this.t = (this.t + 0.0025 * this.speed) % 1;
    gl.useProgram(this.prog);
    gl.uniformMatrix4fv(this.uM, false, matrix);
    gl.uniform1f(this.uT, this.t);
    gl.uniform1f(this.uS, Math.max(2.0, Math.min(7.0, map.getZoom() - 2.2)));
    gl.bindBuffer(gl.ARRAY_BUFFER, this.bSeg);
    gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 4, gl.FLOAT, false, 0, 0);
    gl.bindBuffer(gl.ARRAY_BUFFER, this.bPh);
    gl.enableVertexAttribArray(1); gl.vertexAttribPointer(1, 1, gl.FLOAT, false, 0, 0);
    gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
    gl.drawArrays(gl.POINTS, 0, this.n);
    if (this.running) map.triggerRepaint();
  }
}

/* ── build the world ──────────────────────────────────────────────────── */
let flow = null;
const stat = (id, v) => { document.getElementById(id).textContent = v; };

map.on('load', async () => {
  stat('cores', navigator.hardwareConcurrency || '?');
  const gl = map.painter.context.gl;
  const dbg = gl.getExtension('WEBGL_debug_renderer_info');
  const rend = dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
  stat('gpu', String(rend).replace(/\s*\(.*$/, '').slice(0, 28));

  let fc;
  try {
    const r = await fetch(DATA, { cache: 'force-cache' });
    if (!r.ok) throw new Error('HTTP ' + r.status);
    fc = await r.json();
  } catch (e) {
    note('About', 'network: ' + e.message);
    return;
  }

  map.addSource('grid', { type: 'geojson', data: fc });
  map.addLayer({ id: 'grid-line', type: 'line', source: 'grid',
    paint: { 'line-color': '#1d6f86', 'line-width': ['interpolate', ['linear'], ['zoom'], 4, 0.5, 10, 2.2],
             'line-opacity': 0.85 } });

  /* every segment of every circuit, in mercator, flattened for one draw call */
  const segs = [];
  for (const f of fc.features || []) {
    const g = f.geometry; if (!g) continue;
    const lines = g.type === 'MultiLineString' ? g.coordinates
                : g.type === 'LineString' ? [g.coordinates] : [];
    for (const line of lines) {
      for (let i = 1; i < line.length; i++) {
        const a = maplibregl.MercatorCoordinate.fromLngLat(line[i - 1]);
        const b = maplibregl.MercatorCoordinate.fromLngLat(line[i]);
        segs.push(a.x, a.y, b.x, b.y);
      }
    }
  }
  flow = new Flow(new Float32Array(segs));
  map.addLayer(flow);
  stat('nlines', (fc.features || []).length.toLocaleString());
  stat('nparts', flow.n.toLocaleString());

  /* ── menus, wired to the world ── */
  item('File', 'Reload the world', () => location.reload());
  item('File', 'Copy this view as a link', () => {
    const c = map.getCenter();
    const u = location.origin + location.pathname
      + `?lng=${c.lng.toFixed(5)}&lat=${c.lat.toFixed(5)}&z=${map.getZoom().toFixed(2)}`;
    navigator.clipboard && navigator.clipboard.writeText(u);
  });

  item('Edit', 'Pause the flow', function () {
    flow.running = !flow.running;
    this.textContent = flow.running ? 'Pause the flow' : 'Resume the flow';
    if (flow.running) map.triggerRepaint();
  });
  item('Edit', 'Faster', () => { flow.speed = Math.min(8, flow.speed * 1.6); });
  item('Edit', 'Slower', () => { flow.speed = Math.max(0.12, flow.speed / 1.6); });

  item('Scope', 'Measure from a point I choose', () => {
    scoping = true; map.getCanvas().style.cursor = 'crosshair';
  });
  item('Scope', 'Clear what I measured', () => {
    if (map.getLayer('scope-pt')) map.removeLayer('scope-pt');
    if (map.getSource('scope')) map.removeSource('scope');
  });
  note('Scope', 'Straight-line only. A straight line is not a route.');

  item('View', 'Fit the whole network', () => map.fitBounds(bounds(fc), { padding: 40, duration: 900 }));
  item('View', 'Full screen', () => {
    const el = document.documentElement;
    if (!document.fullscreenElement) el.requestFullscreen && el.requestFullscreen().catch(() => {});
    else document.exitFullscreen && document.exitFullscreen();
  });

  toggle('Select layers', 'Circuits', '#1d6f86', true,
    v => map.setLayoutProperty('grid-line', 'visibility', v ? 'visible' : 'none'));
  toggle('Select layers', 'Carriers in motion', '#6bebff', true, v => {
    flow.running = v; if (v) map.triggerRepaint();
    map.setLayoutProperty('flow', 'visibility', v ? 'visible' : 'none');
  });
  note('Select layers', 'More layers port in here as each one is clicked and confirmed.');

  note('About', 'GridAtlas World - the network drawn moving, on the GPU.');
  note('About', `${(fc.features || []).length.toLocaleString()} circuits, ` +
    `${flow.n.toLocaleString()} carriers, one instanced draw call.`);
  note('About', 'Circuit geometry: the estate 400 kV shared runtime product.');
  note('About', 'Nothing here grades a connection.');

  map.fitBounds(bounds(fc), { padding: 40, duration: 0 });
});

function bounds(fc) {
  let w = 180, s = 90, e = -180, n = -90;
  for (const f of fc.features || []) {
    const g = f.geometry; if (!g) continue;
    const ls = g.type === 'MultiLineString' ? g.coordinates : g.type === 'LineString' ? [g.coordinates] : [];
    for (const l of ls) for (const [x, y] of l) {
      if (x < w) w = x; if (x > e) e = x; if (y < s) s = y; if (y > n) n = y;
    }
  }
  return [[w, s], [e, n]];
}

/* ── scope: click the world, measure from there ───────────────────────── */
let scoping = false;
map.on('click', ev => {
  if (!scoping) return;
  scoping = false; map.getCanvas().style.cursor = '';
  const pt = { type: 'FeatureCollection', features: [
    { type: 'Feature', geometry: { type: 'Point', coordinates: [ev.lngLat.lng, ev.lngLat.lat] }, properties: {} }] };
  if (map.getSource('scope')) map.getSource('scope').setData(pt);
  else {
    map.addSource('scope', { type: 'geojson', data: pt });
    map.addLayer({ id: 'scope-pt', type: 'circle', source: 'scope',
      paint: { 'circle-radius': 7, 'circle-color': '#ff9d3c', 'circle-opacity': 0.9,
               'circle-stroke-width': 2, 'circle-stroke-color': '#ffd9a8' } });
  }
});

/* ── the machine's own numbers, on screen while it runs ───────────────── */
let frames = 0, last = performance.now();
(function tick(now) {
  frames++;
  if (now - last >= 500) { stat('fps', Math.round(frames * 1000 / (now - last))); frames = 0; last = now; }
  requestAnimationFrame(tick);
})(performance.now());
</script>

Compare Live vs Candidate

A Python command-line tool in the atman folder of GridAtlas that reads postcodes and the Renewable Energy Planning Database (REPD) register, using SHA-256.

storagegridatlas / atman/202608290828-compare-live-vs-candidate.py · lines 1–125 of 125 · version 2026-08-29 08:28 · Entry point · pattern metrics (shared by 6 files)

What it does
It loads postcodes and the REPD register. Defines load_manifest, metrics, main. Uses libraries argparse, hashlib, json, pathlib, duckdb. 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. Domain terms in the code: postcodes, the REPD register.
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 `load_manifest` and `metrics`. It accepts `--incumbent-site`, `--candidate-site` and `--output`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · atman · Python CLI
Uses
argparse, hashlib, json, pathlib, duckdb
Used by
none found
Produces
load_manifest, metrics, main
Defines here
load_manifest, metrics, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atman/202608290828-compare-live-vs-candidate.py:1-125 · blob 13c770ab1f050cb496236902dc0902b78f4247f8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
import argparse
import hashlib
import json
from pathlib import Path

import duckdb


def load_manifest(site):
    matches = sorted((site / "data").glob("repd_v9_manifest_*.json"))
    if len(matches) != 1:
        raise SystemExit(f"expected one V9 manifest in {site}, found {len(matches)}")
    path = matches[0]
    manifest = json.loads(path.read_text(encoding="utf-8"))
    parquet = site / "data" / manifest["parquet"]["path"]
    if not parquet.is_file():
        raise SystemExit(f"missing Parquet declared by {path}: {parquet}")
    digest = hashlib.sha256(parquet.read_bytes()).hexdigest()
    if digest != manifest["parquet"]["sha256"] or parquet.stat().st_size != manifest["parquet"]["bytes"]:
        raise SystemExit(f"Parquet identity mismatch for {site}")
    return manifest, parquet


def metrics(connection, relation):
    row = connection.execute(
        f"""
        SELECT
          count(*) AS rows,
          count(DISTINCT repd_ref) AS unique_repd_refs,
          count(repd_address_display) AS addresses,
          count(repd_postcode_raw) AS postcodes,
          count(*) FILTER (WHERE postcode_valid) AS valid_postcodes,
          round(sum(capacity_mw), 6) AS capacity_mw
        FROM {relation}
        """
    ).fetchone()
    return dict(zip(("rows", "unique_repd_refs", "addresses", "postcodes", "valid_postcodes", "capacity_mw"), row))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--incumbent-site", required=True)
    parser.add_argument("--candidate-site", required=True)
    parser.add_argument("--output", required=True)
    args = parser.parse_args()
    incumbent_site = Path(args.incumbent_site)
    candidate_site = Path(args.candidate_site)
    incumbent_manifest, incumbent_parquet = load_manifest(incumbent_site)
    candidate_manifest, candidate_parquet = load_manifest(candidate_site)

    con = duckdb.connect()
    con.execute("PRAGMA threads=1")
    incumbent_sql = str(incumbent_parquet).replace("'", "''")
    candidate_sql = str(candidate_parquet).replace("'", "''")
    con.execute(f"CREATE VIEW incumbent AS SELECT * FROM read_parquet('{incumbent_sql}')")
    con.execute(f"CREATE VIEW candidate AS SELECT * FROM read_parquet('{candidate_sql}')")
    incumbent = metrics(con, "incumbent")
    candidate = metrics(con, "candidate")
    added = con.execute("SELECT count(*) FROM candidate c ANTI JOIN incumbent i USING (repd_ref)").fetchone()[0]
    removed = con.execute("SELECT count(*) FROM incumbent i ANTI JOIN candidate c USING (repd_ref)").fetchone()[0]
    changed = con.execute(
        """
        SELECT count(*)
        FROM candidate c
        JOIN incumbent i USING (repd_ref)
        WHERE c.source_row_sha256 IS DISTINCT FROM i.source_row_sha256
           OR c.longitude IS DISTINCT FROM i.longitude
           OR c.latitude IS DISTINCT FROM i.latitude
           OR c.capacity_mw IS DISTINCT FROM i.capacity_mw
           OR c.repd_address_display IS DISTINCT FROM i.repd_address_display
           OR c.repd_postcode IS DISTINCT FROM i.repd_postcode
        """
    ).fetchone()[0]
    con.close()

    same_source = incumbent_manifest["source"]["sha256"] == candidate_manifest["source"]["sha256"]
    failures = []
    if candidate["rows"] != candidate["unique_repd_refs"]:
        failures.append("candidate REPD identity is not unique")
    if candidate_manifest["v8_oracle"]["match_ratio"] < 0.95:
        failures.append("candidate V8 oracle parity is below 95%")
    if same_source and (added or removed or changed):
        failures.append("same-source candidate changed typed REPD truth")
    if not same_source:
        incumbent_rows = max(incumbent["rows"], 1)
        if removed / incumbent_rows > 0.05:
            failures.append("candidate removes more than 5% of incumbent REPD refs")
        for field in ("addresses", "valid_postcodes"):
            old_rate = incumbent[field] / incumbent_rows
            new_rate = candidate[field] / max(candidate["rows"], 1)
            if new_rate < old_rate - 0.01:
                failures.append(f"candidate {field} coverage falls by more than one percentage point")

    report = {
        "schema": "gridatlas.incumbent-candidate.v1",
        "classification": "REJECTED" if failures else "VERIFIED_NO_DATA_REGRESSION",
        "incumbent_generation": incumbent_manifest["generation"],
        "candidate_generation": candidate_manifest["generation"],
        "same_official_source": same_source,
        "incumbent": incumbent,
        "candidate": candidate,
        "delta": {
            "rows": candidate["rows"] - incumbent["rows"],
            "addresses": candidate["addresses"] - incumbent["addresses"],
            "postcodes": candidate["postcodes"] - incumbent["postcodes"],
            "valid_postcodes": candidate["valid_postcodes"] - incumbent["valid_postcodes"],
            "capacity_mw": round(candidate["capacity_mw"] - incumbent["capacity_mw"], 6),
            "added_repd_refs": added,
            "removed_repd_refs": removed,
            "changed_repd_refs": changed,
        },
        "v8_oracle_match_ratio": candidate_manifest["v8_oracle"]["match_ratio"],
        "failures": failures,
    }
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    print(json.dumps(report, sort_keys=True))
    if failures:
        raise SystemExit("incumbent-versus-candidate gate failed")


if __name__ == "__main__":
    main()

Compare Incumbent Successor

A Python command-line tool in the atman folder of GridAtlas that reads Renewable Energy Planning Database (REPD) browser registry, membership and the REPD register, using SHA-256.

storagegridatlas / atman/202608291239-compare-incumbent-successor.py · lines 1–186 of 186 · version 2026-08-29 12:39 · Entry point · pattern classified (shared by 2 files)

What it does
It loads REPD browser registry, membership and the REPD register. Defines 7 functions or classes, including reject_duplicate_keys, read_json, sha256, tree, goal. Uses libraries __future__, argparse, hashlib, json, pathlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (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. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file release-manifest.json; JSON file browser-layer-registry.json; JSON file repd_browser_registry_202608290716.json; Parquet file layer_membership.parquet; 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 reads JSON (`read_json`) and is built from the reject duplicate keys helper (`reject_duplicate_keys`) and the sha256 step (`sha256`). Classify every Atlas V9 live-successor promotion goal. It reads `release-manifest.json`. It accepts `--repository`, `--build-a` and `--build-b`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · atman · Python CLI
Uses
__future__, argparse, hashlib, json, pathlib
Used by
none found
Produces
reject_duplicate_keys, read_json, sha256, tree, goal, classified, main
Defines here
reject_duplicate_keys, read_json, sha256, tree, goal, classified, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atman/202608291239-compare-incumbent-successor.py:1-186 · blob 80099ea493e2dbdc133665356fa469c5c36d2cab · 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: production_core
#!/usr/bin/env python3
"""Classify every Atlas V9 live-successor promotion goal."""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path

ALLOWED = {"MATCH", "EXPECTED_CHANGE", "REGRESSION", "UNKNOWN"}
RELEASE_ID = "202608291239-atlas-v9"
ROOT_INDEX_SHA256 = "4d059a6963ee73378b21bf378a3590292bbced0bba6f3cacf4acd9c6bc695533"
REPD_REGISTRY_SHA256 = "c8a5c59be878c52014a272eb0e4d09af06a0d301d10a8d6b5d0b116b5d1bb6bc"
TRANSPORT_LAYERS = {
    "rail", "elizabeth", "lu", "dlr", "metro", "tram", "mainline_rail",
    "hs2", "eurostar_route", "eurostar_station",
}


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 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 tree(directory: Path) -> dict[str, tuple[int, str]]:
    return {
        path.relative_to(directory).as_posix(): (path.stat().st_size, sha256(path))
        for path in sorted(item for item in directory.rglob("*") if item.is_file())
    }


def goal(status: str, evidence: object) -> dict:
    if status not in ALLOWED:
        raise ValueError(status)
    return {"status": status, "evidence": evidence}


def classified(condition: bool, evidence: object, *, expected_change: bool = False) -> dict:
    return goal("EXPECTED_CHANGE" if condition and expected_change else "MATCH" if condition else "REGRESSION", evidence)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--repository", type=Path, required=True)
    parser.add_argument("--build-a", type=Path, required=True)
    parser.add_argument("--build-b", type=Path, required=True)
    parser.add_argument("--data-release", type=Path, required=True)
    parser.add_argument("--browser-proof", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    repository = args.repository.resolve()
    build_a = args.build_a.resolve()
    build_b = args.build_b.resolve()
    data = args.data_release.resolve()
    browser = read_json(args.browser_proof.resolve()) if args.browser_proof.is_file() else None
    release = read_json(build_a / "release-manifest.json")
    data_manifest = read_json(data / "data/manifest.json")
    data_registry = read_json(data / "browser-layer-registry.json")
    repd_registry = read_json(repository / "data/repd_browser_registry_202608290716.json")
    flat_layers = [layer for group in data_registry.get("groups", []) for layer in group.get("layers", [])]
    layer_ids = {layer.get("id") for layer in flat_layers}
    app_source = (build_a / "assets/atlas-v9.mjs").read_text(encoding="utf-8")
    client_source = (build_a / "assets/data-gridatlas-client.mjs").read_text(encoding="utf-8")
    golden = next((row for row in repd_registry.get("records", []) if str(row.get("repd_ref")) == "16135"), None)
    build_a_tree = tree(build_a)
    build_b_tree = tree(build_b)

    sections = {
        "source_closure": {
            "timestamp_identity": classified(release.get("release_id") == RELEASE_ID, release.get("release_id")),
            "superseded_public_candidate": classified(release.get("supersedes_candidate", {}).get("release_id") == "202608291237-atlas-v9" and release.get("supersedes_candidate", {}).get("classification") == "PUBLIC_PROOF_REJECTED_NO_POINTER" and release.get("supersedes_candidate", {}).get("pointer_created") is False, release.get("supersedes_candidate"), expected_change=True),
            "data_generation": classified(release.get("data_release", {}).get("source_generation") == "202608291015", release.get("data_release", {}).get("source_generation")),
            "v8_oracle": classified(data_manifest.get("source", {}).get("commit") == "f2f343a92ee972cc74ed23b4b99d8a22896791ad" and data_manifest.get("v8_untouched") is True, data_manifest.get("source")),
        },
        "v8_layer_semantics": {
            "layer_count": classified(len(flat_layers) == 60 and len(layer_ids) == 60, len(flat_layers)),
            "group_count": classified(len(data_registry.get("groups", [])) == 11, len(data_registry.get("groups", []))),
            "exact_membership": classified(data_manifest.get("closure", {}).get("layer_membership_rows") == 526388, data_manifest.get("closure", {}).get("layer_membership_rows")),
            "full_parquet_consumer": classified("SEMI JOIN read_parquet" in client_source and "layer_membership.parquet" in client_source, "partition + exact membership join", expected_change=True),
        },
        "repd_incumbent_regression": {
            "registry_identity": classified(sha256(repository / "data/repd_browser_registry_202608290716.json") == REPD_REGISTRY_SHA256, REPD_REGISTRY_SHA256),
            "row_closure": classified(len(repd_registry.get("records", [])) == 11069, len(repd_registry.get("records", []))),
            "golden_16135": classified(golden is not None and golden.get("repd_postcode") == "MK43 0ZY" and golden.get("county") == "Bedfordshire", golden),
            "address_cartridge": classified(sha256(build_a / "cartridges/202608290716-repd-address-flyto.mjs") == "b4dcfcb9cf815012dab6cc634c099179a155ea2f0120f6c61797087fbef1f64a", "byte-identical incumbent cartridge"),
            "cluster_count_labels": classified('id: "repd-clusters"' in app_source and 'id: "repd-points"' in app_source and 'id: "repd-selected"' in app_source and 'map.on("click", "repd-clusters"' in app_source and 'id: "repd-cluster-count"' not in app_source and '"text-field"' not in app_source, "cluster circles, expansion click, points and selection retained; glyph-dependent numeric label omit  … [line shortened here: 428 characters; full line on GitHub]
            "deep_link_query_contract": classified(release.get("route_contract", {}).get("query_parameter") == "repd_ref", release.get("route_contract")),
            "golden_deep_link": classified(release.get("route_contract", {}).get("golden_deep_link") == "https://ventusltd.github.io/gridatlas/202608291239-atlas-v9/?repd_ref=16135", release.get("route_contract", {}).get("golden_deep_link"), expected_change=True),
        },
        "lazy_runtime": {
            "zero_boot_parquet": classified(release.get("loading_contract", {}).get("parquet_on_boot") == 0 and app_source.count("dataClient.queryLayer(") == 1, release.get("loading_contract")),
            "user_activation": classified("EXPLICIT_USER_LAYER_TOGGLE" in client_source and 'input.addEventListener("change"' in app_source, "explicit checkbox activation"),
            "bounded_query": classified(all(token in client_source for token in ("p.max_x", "p.min_x", "p.max_y", "p.min_y")), "map-bounds predicate"),
            "browser_compute": classified("duckdb-wasm@1.29.0" in json.dumps(release), "DuckDB-WASM 1.29.0", expected_change=True),
            "heavy_layer_zoom_gate": goal("UNKNOWN", "browser proof missing") if browser is None else classified(browser.get("heavy_layer_zoom_gate") is True, browser.get("heavy_layer_zoom_gate")),
            "failed_query_isolation": goal("UNKNOWN", "browser proof missing") if browser is None else classified(browser.get("failed_query_isolated") is True, browser.get("failed_query_isolated")),
            "unload_release": goal("UNKNOWN", "browser proof missing") if browser is None else classified(browser.get("unload_released_render_and_handlers") is True, browser.get("unload_released_render_and_handlers")),
        },
        "rendered_desktop_mobile": {
            "browser_classification": goal("UNKNOWN", "browser proof missing") if browser is None else classified(browser.get("classification") == "VERIFIED_RENDERED_BROWSER" and browser.get("failed") == 0, browser.get("classification")),
            "desktop_1440": goal("UNKNOWN", "browser proof missing") if browser is None else classified("1440x900" in browser.get("viewports", []), browser.get("viewports")),
            "mobile_390": goal("UNKNOWN", "browser proof missing") if browser is None else classified("390x844" in browser.get("viewports", []), browser.get("viewports")),
            "initial_payload": goal("UNKNOWN", "browser proof missing") if browser is None else classified(browser.get("initial_v8_parquet_requests") == 0 and browser.get("initial_v8_parquet_bytes") == 0, {"requests": browser.get("initial_v8_parquet_requests"), "bytes": browser.get("initial_v8_parquet_bytes")}),
            "visible_quarantine_provenance": goal("UNKNOWN", "browser proof missing") if browser is None else classified(browser.get("quarantined_visible_badges") == 5, browser.get("quarantined_visible_badges")),
            "glyphless_style_symbol_guard": goal("UNKNOWN", "browser proof missing") if browser is None else classified(browser.get("glyphless_style_symbol_guard") is True, browser.get("glyphless_style_symbol_guard")),
            "repd_cluster_expansion": goal("UNKNOWN", "browser proof missing") if browser is None else classified(browser.get("repd_cluster_expand_click") is True and browser.get("repd_cluster_layers") == ["repd-clusters", "repd-points", "repd-selected"], {"click": browser.get("repd_cluster_expand_click"), "layers": browser.get("repd_cluster_layers")}),
            "map_load_stall_deep_link": goal("UNKNOWN", "browser proof missing") if browser is None else classified(browser.get("map_load_stall_deep_link") is True, browser.get("map_load_stall_deep_link")),
        },
        "public_transport": {
            "layer_closure": classified(TRANSPORT_LAYERS.issubset(layer_ids), sorted(TRANSPORT_LAYERS & layer_ids)),
            "lazy_transport": classified("item.preload" not in app_source and release.get("loading_contract", {}).get("automatic_v8_layer_loads") == 0, "no automatic transport payload"),
        },
        "output_closure": {
            "deterministic_ab": classified(build_a_tree == build_b_tree, {"a_files": len(build_a_tree), "b_files": len(build_b_tree)}),
            "timestamp_index": classified((build_a / "index.html").is_file() and build_a.name == RELEASE_ID, str(build_a / "index.html"), expected_change=True),
            "seven_files": classified(len(build_a_tree) == 7, sorted(build_a_tree)),
        },
        "rollback": {
            "root_index_unchanged": classified(sha256(repository / "index.html") == ROOT_INDEX_SHA256, ROOT_INDEX_SHA256),
            "last_green_parent": classified(release.get("parent_release", {}).get("commit") == "514fce2f3605ae53267c5ee955b301604a91b2fd", release.get("parent_release")),
            "separate_route": classified(release.get("route_contract", {}).get("route") == f"/gridatlas/{RELEASE_ID}/", release.get("route_contract"), expected_change=True),
        },
    }
    statuses = [item["status"] for section in sections.values() for item in section.values()]
    failed = sum(status in {"REGRESSION", "UNKNOWN"} for status in statuses)
    status_counts = {status: statuses.count(status) for status in sorted(ALLOWED)}
    report = {
        "schema": "gridatlas.incumbent-successor-comparator.v1",
        "classification": "VERIFIED_LIVE_ATLAS_V9" if failed == 0 else "REJECTED_LIVE_ATLAS_V9",
        "release_id": RELEASE_ID,
        "failed": failed,
        "promotion_eligible": failed == 0,
        "allowed_statuses": sorted(ALLOWED),
        "baseline_vs_successor": {
            "baseline": {
                "name": "Atlas V8-backed last-green root",
                "generation": "202608290716",
                "commit": "514fce2f3605ae53267c5ee955b301604a91b2fd",
                "route": "/gridatlas/",
                "root_index_sha256": ROOT_INDEX_SHA256,
            },
            "successor": {
                "name": "Atlas V9 timestamp-folder release",
                "generation": "202608291239",
                "release_id": RELEASE_ID,
                "route": release.get("route_contract", {}).get("route"),
                "query_parameter": release.get("route_contract", {}).get("query_parameter"),
                "golden_deep_link": release.get("route_contract", {}).get("golden_deep_link"),
            },
            "status_counts": status_counts,
            "expected_changes": [
                "timestamped immutable route",
                "full V8 Parquet queried lazily in-browser",
                "desktop/mobile live rendering",
                "REPD cluster circles retained without undeclared glyph-dependent count labels",
                "failed 202608291237 public candidate retained immutable without a current pointer",
            ],
        },
        "sections": sections,
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(report, sort_keys=True, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(report, sort_keys=True))
    if failed:
        raise SystemExit(f"successor comparator rejected {failed} goals")


if __name__ == "__main__":
    main()