In this section
- Review1 Check render · globalgrid2050 / testcode/202609142225/proof/review1-check.mjs lines 1–105
- Review2 Check render · globalgrid2050 / testcode/202609142225/proof/review2-check.mjs lines 1–130
- Test Dual Compute test · globalgrid2050 / testcode/202609150010/test_dual_compute.py lines 1–55
- Build render · globalgrid2050 / testcode/202609150125/proof/build.py lines 1–410
Review1 Check
A JavaScript module in the proof folder of GlobalGrid2050 that draws review1 report. It is built from the sleep step (`sleep`), the open step (`open`) and the legend step (`legend`).
renderglobalgrid2050 / testcode/202609142225/proof/review1-check.mjs · lines 1–105 of 105 · version 2026-09-14 22:25 · Not reached from any entry point (candidate for review) · pattern INSTRUMENT (shared by 3 files)
- What it does
- It draws review1 report. Defines sleep, INSTRUMENT, open, legend, tap. Uses libraries node:module, node:fs, C:/Users/vikra/Desktop/Claude-Sandbox-MSI/bench/node_modules/puppeteer-core. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: JSON file review1-report.json; command-line arguments. Out: JSON file review1-report.json.
- What it achieves
- Adversarial review round 1 — refutation checks against the served page (read-only on the page; writes only `review1-report.json` here).
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · testcode/202609142225/proof · JavaScript module
- Uses
- node:module, node:fs, C:/Users/vikra/Desktop/Claude-Sandbox-MSI/bench/node_modules/puppeteer-core
- Used by
- none found
- Produces
- sleep, INSTRUMENT, open, legend, tap
- Defines here
- sleep, INSTRUMENT, open, legend, tap
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609142225/proof/review1-check.mjs:1-105 · blob af5c2fa155cdc9eb60f911598ee6ca9e6d552012 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unreached_review
// Adversarial review round 1 — refutation checks against the served page (read-only on the page; writes only review1-report.json here).
// node C:/Users/vikra/Documents/GitHub/globalgrid2050/testcode/202609142225/proof/review1-check.mjs <port>
import { createRequire } from 'node:module';
import fs from 'node:fs';
const require = createRequire(import.meta.url);
const puppeteer = require('C:/Users/vikra/Desktop/Claude-Sandbox-MSI/bench/node_modules/puppeteer-core');
const PORT = process.argv[2] || '8893', BASE = `http://127.0.0.1:${PORT}/testcode/202609142225/`;
const OUT = 'C:/Users/vikra/Documents/GitHub/globalgrid2050/testcode/202609142225/proof/';
const LENSES = ['ring', 'particle', 'chord', 'river', 'table', 'column'];
const sleep = ms => new Promise(r => setTimeout(r, ms));
const browser = await puppeteer.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: 'new', args: ['--enable-gpu', '--use-gl=angle', '--use-angle=d3d11', '--ignore-gpu-blocklist', '--no-first-run'] });
const report = { run_utc: new Date().toISOString(), base: BASE, checks: {} };
// count GL uploads per frame while idle: refutes "no per-instance CPU work per frame" if > 0
const INSTRUMENT = () => {
const B = window.__rv = { bufferData: 0, bufferSubData: 0, texSubImage2D: 0, texImage2D: 0, draws: 0, requests: [] };
for (const n of ['bufferData', 'bufferSubData', 'texSubImage2D', 'texImage2D']) { const o = WebGL2RenderingContext.prototype[n]; WebGL2RenderingContext.prototype[n] = function (...a) { B[n]++; return o.apply(this, a); }; }
for (const n of ['drawArrays', 'drawArraysInstanced']) { const o = WebGL2RenderingContext.prototype[n]; WebGL2RenderingContext.prototype[n] = function (...a) { B.draws++; return o.apply(this, a); }; }
};
async function open(url, width, opts = {}) {
const page = await browser.newPage(); const mobile = width <= 600;
await page.setViewport({ width, height: 900, deviceScaleFactor: mobile ? 2 : 1, isMobile: mobile, hasTouch: mobile });
await page.evaluateOnNewDocument(INSTRUMENT);
const errors = [], responses = [];
page.on('console', m => { if (m.type() === 'error' || m.type() === 'warning') errors.push(m.type() + ': ' + m.text()); });
page.on('pageerror', e => errors.push('pageerror: ' + e.message)); page.on('requestfailed', r => errors.push('requestfailed: ' + r.url()));
page.on('response', r => { const u = r.url(); if (/202609142202\/data|ventusltd\.github\.io|raw\.githubusercontent/.test(u)) responses.push([r.status(), u.replace(/^https?:\/\/[^/]+/, '')]); });
await page.goto(BASE + url, { waitUntil: 'load', timeout: 90000 });
await page.waitForFunction(() => window.__star && window.__star.core.packLoaded() && window.__star.core.U.names, { timeout: 90000 }).catch(() => errors.push('pack or names never loaded'));
await sleep(opts.wait || 1800);
page.__errors = errors; page.__responses = responses; return page;
}
const state = () => ({ url: location.search, focus: window.__star.state.focus >= 0 ? window.__star.core.keyStr[window.__star.state.focus] : null, trail: window.__star.state.trail.map(i => window.__star.core.keyStr[i]), recipe: window.__star.state.recipe.slice(), lens: window.__star.state.lens, hist: history.length, panel: !document.getElementById('panel').hidden, panelHead: (document.querySelector … [line shortened here: 446 characters; full line on GitHub]
const legend = () => [...document.querySelectorAll('#legend .lg:not(.cat)')].map(b => ({ word: b.textContent.trim(), off: b.classList.contains('off'), title: b.title }));
try {
// A. idle frame loop: uploads per frame must be 0; draws per frame small and constant. Data path must resolve (200 on ../202609142202/data/*).
for (const width of [1440, 430]) {
const p = await open('?lens=ring&key=family:80299&trail=block:Gc,family:80299', width);
const a = await p.evaluate(async () => { const B = window.__rv, S = window.__star; const f0 = S.G.frames, u0 = { bd: B.bufferData, bsd: B.bufferSubData, tsi: B.texSubImage2D, d: B.draws }; await new Promise(r => setTimeout(r, 2000)); const f1 = S.G.frames; return { frames: f1 - f0, bufferDataPerFrame: (B.bufferData - u0.bd) / (f1 - f0), bufferSubDataPerFrame: (B.bufferSubData - u0.bsd) / (f1 - … [line shortened here: 925 characters; full line on GitHub]
a.errors = p.__errors; a.dataResponses = p.__responses.filter(x => /202609142202/.test(x[1]));
report.checks[`idle-${width}`] = a; console.log(`idle-${width}`, JSON.stringify(a));
await p.close();
}
// B. legend words + dim state after tab switches (one page), key/trail/recipe survival, Measure text after switch
for (const width of [1440, 430]) {
const p = await open('?lens=ring&key=family:80299&trail=block:Gc,family:80299&recipe=block:Si,family:80299', width);
const tap = async sel => { const r = await p.evaluate(s => { const e = document.querySelector(s); e.scrollIntoView({ block: 'nearest' }); const b = e.getBoundingClientRect(); return { x: b.left + b.width / 2, y: b.top + b.height / 2 }; }, sel); if (width <= 600) await p.touchscreen.tap(r.x, r.y); else await p.mouse.click(r.x, r.y); };
// Measure the focus first, so the code text is in the panel
await tap('#panel-foot button:nth-child(2)'); await sleep(2500);
const before = await p.evaluate(() => ({ ...(() => ({ url: location.search }))(), code: (document.querySelector('#panel .u-code') || {}).textContent || '', legend: [...document.querySelectorAll('#legend .lg:not(.cat)')].map(b => ({ word: b.textContent.trim(), off: b.classList.contains('off'), title: b.title })), draws: window.__star.lens.draws }));
const steps = [{ lens: 'ring', measuredTextPresent: !/text on Measure/.test(before.code) && before.code.length > 50, legend: before.legend, draws: before.draws, url: before.url }];
for (const lens of LENSES.slice(1)) {
await tap(`#lensbar a:nth-child(${LENSES.indexOf(lens) + 1})`); await sleep(1500);
const s = await p.evaluate(() => { const S = window.__star; return { lens: S.state.lens, url: location.search, focus: S.core.keyStr[S.state.focus], trail: S.state.trail.map(i => S.core.keyStr[i]), recipe: S.state.recipe.slice(), draws: S.lens.draws, legend: [...document.querySelectorAll('#legend .lg:not(.cat)')].map(b => ({ word: b.textContent.trim(), off: b.classList.contains('off'), title: … [line shortened here: 638 characters; full line on GitHub]
s.measuredTextPresent = !/text on Measure/.test(s.code) && s.code.length > 50;
s.legendStale = s.legend.filter(c => c.off !== !s.draws.includes(c.word)).map(c => `${c.word}: off=${c.off} but draws=${s.draws.includes(c.word)} (title "${c.title}")`);
steps.push(s); console.log(width, lens, s.url, 'legendStale', s.legendStale.length, 'measuredText', s.measuredTextPresent, 'bounds', s.bounds);
}
report.checks[`switch-${width}`] = { words: steps.map(s => s.legend.map(c => c.word).join('|')), steps, errors: p.__errors };
await p.close();
}
// C. column lens: segment control with no focus; table lens: "show 40 more" with and without focus
{
const p = await open('?lens=column', 1440);
const s0 = await p.evaluate(state);
await p.click('.col .seg button:nth-child(2)'); await sleep(1200);
const s1 = await p.evaluate(state);
report.checks['column-seg-no-focus'] = { before: s0, afterClickingShowDependsOn: s1, errors: p.__errors };
console.log('column seg', JSON.stringify({ before: s0.focus, after: s1.focus, trail: s1.trail, url: s1.url, hist: [s0.hist, s1.hist], panel: s1.panel }));
await p.close();
}
{
const p = await open('?lens=table', 1440);
const s0 = await p.evaluate(state);
await p.evaluate(() => { const m = document.querySelector('#overlay .u-more'); m.scrollIntoView(); }); await p.click('#overlay .u-more'); await sleep(1200);
const s1 = await p.evaluate(state);
report.checks['table-more-no-focus'] = { before: s0, after: s1, errors: p.__errors };
console.log('table more (no focus)', JSON.stringify({ before: s0.focus, after: s1.focus, trail: s1.trail, url: s1.url, hist: [s0.hist, s1.hist], panel: s1.panel }));
await p.close();
const q = await open('?lens=table&key=block:Cg', 1440);
const t0 = await q.evaluate(state);
await q.evaluate(() => { const m = document.querySelector('#overlay .u-more'); m.scrollIntoView(); }); await q.click('#overlay .u-more'); await sleep(1200);
const t1 = await q.evaluate(state);
report.checks['table-more-with-focus'] = { before: t0, after: t1, errors: q.__errors };
console.log('table more (focus Cg)', JSON.stringify({ before: t0.focus, after: t1.focus, trail: t1.trail, hist: [t0.hist, t1.hist] }));
await q.close();
}
// D. table lens at 430 with a family focus: does the overlay scroll to the family's block tile?
{
const p = await open('?lens=table&key=family:80299', 430, { wait: 2500 });
const s = await p.evaluate(() => { const ov = document.getElementById('overlay'), st = document.getElementById('stage').getBoundingClientRect(), t = document.querySelector('#overlay .tile.focus'); const r = t && t.getBoundingClientRect(); return { overlayScrollTop: ov.scrollTop, overlayScrollHeight: ov.scrollHeight, stageH: st.height, focusTile: t && t.textContent.trim().slice(0, 30), focusTil … [line shortened here: 504 characters; full line on GitHub]
report.checks['table-430-family'] = { ...s, errors: p.__errors }; console.log('table-430-family', JSON.stringify(s));
await p.close();
}
// E. compose with line:17: the hand-off attributes the line to one family of many
{
const p = await open('?lens=ring&recipe=line:17', 1440);
const s = await p.evaluate(async () => { const S = window.__star; const j = await S.recipeJSON(); return { families17: (S.core.familiesOfLine(17) || []).length, resolved: S.core.keyStr[S.core.resolve('line:17')], handOff: S.handOffURL(), lines: j.lines, blocks: j.blocks.map(b => b.symbol), tray: document.getElementById('tray').textContent }; });
report.checks['line17'] = { ...s, errors: p.__errors }; console.log('line17', JSON.stringify(s));
await p.close();
}
} finally { await browser.close(); }
fs.writeFileSync(OUT + 'review1-report.json', JSON.stringify(report, null, 1));
console.log('written', OUT + 'review1-report.json');Review2 Check
A JavaScript module in the proof folder of GlobalGrid2050 that draws blocks and review2 report, and uses data from the stars and code-generator repositories.
renderglobalgrid2050 / testcode/202609142225/proof/review2-check.mjs · lines 1–130 of 130 · version 2026-09-14 22:25 · Not reached from any entry point (candidate for review) · pattern INSTRUMENT (shared by 3 files)
- What it does
- It draws blocks and review2 report. Defines 6 functions or classes, including sleep, say, INSTRUMENT, open, tapper. Uses libraries node:module, node:fs, C:/Users/vikra/Desktop/Claude-Sandbox-MSI/bench/node_modules/puppeteer-core. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "`proof/review2-check.mjs` is the second review round's refutation harness (`proof/review2-report.json`)."
- Inputs & outputs
- In: data source: stars data; data source: code-generator data; JSON file index.json; JSON file blocks.json; JSON file 160.json; JSON file review2-report.json; command-line arguments. Out: JSON file review2-report.json.
- What it achieves
- It is built from the sleep step (`sleep`), the say step (`say`) and the open step (`open`). Adversarial review round 2 — refutation checks against the served page. It reads `review2-report.json` and writes `review2-report.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · testcode/202609142225/proof · JavaScript module
- Uses
- Code Generator — Index Page (estate URL), node:module, node:fs, C:/Users/vikra/Desktop/Claude-Sandbox-MSI/bench/node_modules/puppeteer-core
- Used by
- none found
- Produces
- sleep, say, INSTRUMENT, open, tapper, litCount
- Defines here
- sleep, say, INSTRUMENT, open, tapper, litCount
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609142225/proof/review2-check.mjs:1-130 · blob c9cbf6b5a4b560a9b0ae484923fd45dda12922da · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
// Adversarial review round 2 — refutation checks against the served page. Read-only on the page; writes only review2-report.json here.
// node C:/Users/vikra/Documents/GitHub/globalgrid2050/testcode/202609142225/proof/review2-check.mjs <port>
import { createRequire } from 'node:module';
import fs from 'node:fs';
const require = createRequire(import.meta.url);
const puppeteer = require('C:/Users/vikra/Desktop/Claude-Sandbox-MSI/bench/node_modules/puppeteer-core');
const PORT = process.argv[2] || '8866', BASE = `http://127.0.0.1:${PORT}/testcode/202609142225/`;
const OUT = 'C:/Users/vikra/Documents/GitHub/globalgrid2050/testcode/202609142225/proof/';
const LENSES = ['ring', 'particle', 'chord', 'river', 'table', 'column'];
const sleep = ms => new Promise(r => setTimeout(r, ms));
const browser = await puppeteer.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: 'new', args: ['--enable-gpu', '--use-gl=angle', '--use-angle=d3d11', '--ignore-gpu-blocklist', '--no-first-run'], protocolTimeout: 120000 });
const report = { run_utc: new Date().toISOString(), base: BASE, checks: {} };
const ONLY = (process.argv[3] || 'ABCDEFG'); const want = c => ONLY.includes(c);
const say = (k, v) => { report.checks[k] = v; console.log(k, JSON.stringify(v)); };
const INSTRUMENT = () => {
const B = window.__rv = { bufferData: 0, bufferSubData: 0, texSubImage2D: 0, texImage2D: 0, draws: 0, drawInst: 0 };
for (const n of ['bufferData', 'bufferSubData', 'texSubImage2D', 'texImage2D']) { const o = WebGL2RenderingContext.prototype[n]; WebGL2RenderingContext.prototype[n] = function (...a) { B[n]++; return o.apply(this, a); }; }
{ const o = WebGL2RenderingContext.prototype.drawArrays; WebGL2RenderingContext.prototype.drawArrays = function (...a) { B.draws++; B.drawInst += a[2]; return o.apply(this, a); }; }
{ const o = WebGL2RenderingContext.prototype.drawArraysInstanced; WebGL2RenderingContext.prototype.drawArraysInstanced = function (...a) { B.draws++; B.drawInst += a[3]; return o.apply(this, a); }; }
};
async function open(url, width, opts = {}) {
const page = await browser.newPage(); const mobile = width <= 600;
await page.setViewport({ width, height: 900, deviceScaleFactor: mobile ? 2 : 1, isMobile: mobile, hasTouch: mobile });
await page.evaluateOnNewDocument(INSTRUMENT);
const errors = [], responses = [];
page.on('console', m => { if (m.type() === 'error' || m.type() === 'warning') errors.push(m.type() + ': ' + m.text()); });
page.on('pageerror', e => errors.push('pageerror: ' + e.message)); page.on('requestfailed', r => errors.push('requestfailed: ' + r.url()));
page.on('response', r => { const u = r.url(); if (/202609142202\/data|ventusltd\.github\.io|raw\.githubusercontent/.test(u)) responses.push([r.status(), u.replace(/^https?:\/\/[^/]+/, '')]); });
await page.goto(BASE + url, { waitUntil: 'load', timeout: 90000 });
if (opts.clearRecipe) { await page.evaluate(() => { try { localStorage.removeItem('star-generator.recipe'); } catch (e) {} }); await page.goto(BASE + url, { waitUntil: 'load', timeout: 90000 }); }
await page.waitForFunction(() => window.__star && window.__star.core.packLoaded() && window.__star.core.U.names, { timeout: 90000 }).catch(() => errors.push('pack or names never loaded'));
await sleep(opts.wait || 1800);
page.__errors = errors; page.__responses = responses; return page;
}
const STATE = () => { const S = window.__star; return { lens: S.state.lens, url: location.search, focus: S.state.focus >= 0 ? S.core.keyStr[S.state.focus] : null, focusKey: S.state.focusKey, measure: S.state.measure >= 0 ? S.core.keyStr[S.state.measure] : null, trail: S.state.trail.map(i => S.core.keyStr[i]), recipe: S.state.recipe.slice(), kindsOn: S.state.kindsOn, cat: S.state.cat, panelHead: (d … [line shortened here: 713 characters; full line on GitHub]
const tapper = (page, width) => async sel => { const r = await page.evaluate(s => { const e = typeof s === 'string' ? document.querySelector(s) : s; e.scrollIntoView({ block: 'nearest' }); const b = e.getBoundingClientRect(); return { x: b.left + b.width / 2, y: b.top + b.height / 2 }; }, sel); if (width <= 600) await page.touchscreen.tap(r.x, r.y); else await page.mouse.click(r.x, r.y); };
try {
if (want('A')) // A. per-frame GPU work in every lens, idle 2 s: uploads must be 0; draws per frame constant; lines resident once
for (const [lens, width] of [...LENSES.map(l => [l, 1440]), ['ring', 430], ['table', 430], ['river', 430]]) {
const p = await open(`?lens=${lens}&key=family:80299&trail=block:Gc,family:80299`, width);
const a = await p.evaluate(async () => { const B = window.__rv, S = window.__star; const f0 = S.G.frames, u0 = { ...B }; await new Promise(r => setTimeout(r, 2000)); const f1 = S.G.frames; const n = f1 - f0; return { frames: n, bufferDataPerFrame: (B.bufferData - u0.bufferData) / n, bufferSubDataPerFrame: (B.bufferSubData - u0.bufferSubData) / n, texSubImagePerFrame: (B.texSubImage2D - u0.texS … [line shortened here: 782 characters; full line on GitHub]
a.errors = p.__errors; a.dataResponses = p.__responses.filter(x => /202609142202/.test(x[1]));
say(`A-idle-${lens}-${width}`, a); await p.close();
}
if (want('B')) // B. lens switch keeps key / trail / recipe / measure / edges mask / cat; legend words identical in six lenses; via tab, keyboard and Open-in
for (const width of [1440, 430]) {
const p = await open('?lens=ring&key=family:80299&trail=block:Gc,family:80299&recipe=block:Si,family:80299&m=block:Gc&edges=cdub&cat=geodesy', width, { clearRecipe: true });
const tap = tapper(p, width);
const steps = [await p.evaluate(STATE)];
for (const lens of LENSES.slice(1)) { await tap(`#lensbar a:nth-child(${LENSES.indexOf(lens) + 1})`); await sleep(1200); steps.push(await p.evaluate(STATE)); }
await p.keyboard.press('1'); await sleep(800); steps.push({ via: 'key 1', ...(await p.evaluate(STATE)) });
await p.keyboard.press(']'); await sleep(800); steps.push({ via: 'key ]', ...(await p.evaluate(STATE)) });
const s0 = steps[0]; const same = steps.map(s => ({ lens: s.lens, via: s.via, key: s.focus === s0.focus, trail: JSON.stringify(s.trail) === JSON.stringify(s0.trail), recipe: JSON.stringify(s.recipe) === JSON.stringify(s0.recipe), measure: s.measure === s0.measure, kindsOn: s.kindsOn === s0.kindsOn, cat: s.cat === s0.cat, urlHasKey: /key=family:80299/.test(s.url), urlHasTrail: /trail=block:Gc,f … [line shortened here: 665 characters; full line on GitHub]
say(`B-switch-${width}`, { same, wordsIdentical: new Set(steps.map(s => s.legendWords.join('|'))).size === 1, errors: p.__errors });
await p.close();
}
if (want('C')) // C. count sentence: unique lines from index.json, never lines.bin length; chip titles for random/entangled
{
const p = await open('?lens=ring', 1440);
const c = await p.evaluate(async () => { const S = window.__star; const idx = await fetch('https://ventusltd.github.io/stars/code/index.json').then(r => r.json()); const bin = S.core.U.packBytes.byteLength / 4; return { count: document.getElementById('count').textContent, title: document.getElementById('count').title, indexLines: idx.lines, indexFamilies: idx.families, binEntries: bin, distinc … [line shortened here: 923 characters; full line on GitHub]
c.countSaysIndexLines = c.count.includes(Number(c.indexLines).toLocaleString('en-GB') + ' unique numbered lines'); c.countSaysBinLength = c.count.includes(Number(c.binEntries).toLocaleString('en-GB'));
say('C-counts', c); await p.close();
}
if (want('D')) // D. compose hand-off: keys permanent, commits from blocks.json and the family bucket, none invented
{
const p = await open('?lens=ring&recipe=block:Si,family:80299,group:x100,line:17', 1440, { clearRecipe: true });
const d = await p.evaluate(async () => { const S = window.__star; const j = await S.recipeJSON(); const live = await fetch('https://ventusltd.github.io/stars/blocks/blocks.json').then(r => r.json()); const bucket = await fetch('https://ventusltd.github.io/stars/code/f/160.json').then(r => r.json()); const bySym = new Map(live.blocks.map(b => [b.symbol, b]));
const blocksOk = j.blocks.map(b => { const lb = bySym.get(b.symbol); return { symbol: b.symbol, number: b.number, files: b.files.length, inLive: !!lb, commitsMatchLive: !!lb && JSON.stringify(b.files.map(f => f.commit)) === JSON.stringify((lb.files || []).map(f => f.commit)), all40hex: b.files.every(f => /^[0-9a-f]{40}$/.test(f.commit)) }; });
const fam = j.families[0]; const rec = bucket['80299']; const famOk = fam && rec && rec.places && rec.places[0] && fam.place && fam.place.commit === rec.places[0].commit && fam.place.path === rec.places[0].path && fam.place.repo === rec.places[0].repo;
return { handOff: S.handOffURL(), keys: j.keys, blocks: blocksOk, family: fam, famCommitMatchesBucket: !!famOk, lines: j.lines, needs: j.needs.length, trail: j.trail, data: j.data, tray: document.getElementById('tray').textContent, sheetFiles: null }; });
await p.click('#tray .cnt'); await sleep(400);
d.sheet = await p.evaluate(() => ({ pinned: [...document.querySelectorAll('#sheet .pin div')].map(e => e.textContent), url: (document.getElementById('sheet').innerText.match(/https:\/\/ventusltd\.github\.io\/code-generator\/\S+/) || [null])[0], head: document.querySelector('#sheet .u-h').textContent }));
say('D-handoff', { ...d, errors: p.__errors }); await p.close();
}
if (want('E')) // E. category dim chip: does clicking it change the lit bytes on the GPU (bit 32) without a navigate?
{
const p = await open('?lens=ring&key=block:Gc', 1440);
const litCount = () => p.evaluate(() => { const S = window.__star; let n = 0; for (let i = 0; i < S.G.N; i++) if (S.G.meta[4 * i + 2] & 32) n++; return { dim32: n, cat: S.state.cat, url: location.search, tilesDim: document.querySelectorAll('.tile.dim').length }; });
const before = await litCount();
await p.evaluate(() => document.querySelectorAll('#legend .lg.cat')[2].click()); await sleep(600);
const afterClick = await litCount();
await p.evaluate(() => document.querySelector('#panel-foot button').click()); await sleep(600); // Navigate here → computeLit
const afterNavigate = await litCount();
await p.evaluate(() => document.querySelector('#legend .lg.cat.on').click()); await sleep(600);
const afterUnclick = await litCount();
say('E-cat-dim', { before, afterClick, afterNavigate, afterUnclick, errors: p.__errors }); await p.close();
}
if (want('F')) // F. DECISION.md Table B claims against the current code: h3 height, smallest tap target, tiles at 430 family focus
for (const width of [1440, 430]) {
const p = await open('?lens=table&key=family:80299', width, { wait: 2500 });
const f = await p.evaluate(() => { const sels = { search: '.u-search', crumb: '#trail a', legendChip: '#legend .lg', lensTab: '#lensbar a', panelButton: '#panel-foot button, #panel-foot .u-chip', panelChip: '#panel-body .u-chip', tile: '.tile', repoChip: '.tb-repos .u-chip', catHeading: '.tb-cat h3', foldSummary: 'details summary', more: '.u-more' }; const t = {}; let smallest = null; for (con … [line shortened here: 813 characters; full line on GitHub]
const ov = document.getElementById('overlay'), st = document.getElementById('stage').getBoundingClientRect(), tile = document.querySelector('#overlay .tile.focus'), P = document.getElementById('panel').getBoundingClientRect(); const tr = tile && tile.getBoundingClientRect();
const lab = [...document.querySelectorAll('#labels span')].filter(s => !s.hidden).map(s => s.textContent);
return { targets: t, smallest, overlayScrollTop: ov.scrollTop, tileTopInStage: tr ? Math.round(tr.top - st.top) : null, inBand: tr ? tr.top >= st.top && tr.bottom <= Math.min(st.bottom, P.top) : null, labels: lab.slice(0, 10), scrollWidth: document.documentElement.scrollWidth, innerWidth }; });
say(`F-table-${width}`, f); await p.close();
}
if (want('G')) // G. the picker: which query parameters the public page reads (from its own source)
{
const p = await browser.newPage(); await p.goto('https://ventusltd.github.io/code-generator/', { waitUntil: 'load', timeout: 60000 });
const g = await p.evaluate(() => { const src = [...document.scripts].map(s => s.textContent).join('\n'); return { params: [...new Set((src.match(/\.get\(['"][a-z_]+['"]\)/g) || []))], workflow: (src.match(/gh workflow run[^`\n]*/g) || []).slice(0, 2), extScripts: [...document.scripts].map(s => s.src).filter(Boolean) }; });
say('G-picker', g); await p.close();
}
if (want('H')) // H. legend kind toggle vs chord geometry; which <summary> is 21 px at 430; Open-in menu switch keeps state
{
const p = await open('?lens=chord&key=block:Gc', 1440);
const g0 = await p.evaluate(() => ({ geom: window.__star.G.geomCount, kindsOn: window.__star.state.kindsOn, viewKinds: window.__star.view.kindsOn }));
await p.evaluate(() => [...document.querySelectorAll('#legend .lg')].find(b => b.textContent.trim() === 'depends on').click()); await sleep(500);
const g1 = await p.evaluate(() => ({ geom: window.__star.G.geomCount, kindsOn: window.__star.state.kindsOn, viewKinds: window.__star.view.kindsOn, url: location.search }));
await p.evaluate(() => document.querySelector('#panel-foot button').click()); await sleep(600);
const g2 = await p.evaluate(() => ({ geom: window.__star.G.geomCount, kindsOn: window.__star.state.kindsOn, viewKinds: window.__star.view.kindsOn }));
say('H-chord-kind-toggle', { beforeToggle: g0, afterToggle: g1, afterNavigate: g2, errors: p.__errors });
await p.close();
const q = await open('?lens=table', 430);
const sums = await q.evaluate(() => [...document.querySelectorAll('#overlay summary')].map(s => ({ text: s.textContent, h: Math.round(s.getBoundingClientRect().height), parentClass: s.parentElement.className, matchedRule: s.matches('.tb-cat details summary') })));
say('H-summaries-430', sums);
await q.close();
const r = await open('?lens=ring&key=family:80299&trail=block:Gc,family:80299&recipe=block:Si', 1440, { clearRecipe: true });
await r.evaluate(() => [...document.querySelectorAll('#panel-foot .u-chip')].find(b => b.textContent.startsWith('Open in')).click()); await sleep(200);
await r.evaluate(() => [...document.querySelectorAll('#panel-foot .open-in .menu a')].find(a => a.textContent === 'column').click()); await sleep(1200);
say('H-open-in-column', await r.evaluate(STATE));
await r.close();
}
} finally { await browser.close(); }
const prev = fs.existsSync(OUT + 'review2-report.json') ? JSON.parse(fs.readFileSync(OUT + 'review2-report.json', 'utf8')) : { checks: {} };
report.checks = { ...prev.checks, ...report.checks };
fs.writeFileSync(OUT + 'review2-report.json', JSON.stringify(report, null, 1));
console.log('written', OUT + 'review2-report.json');Test Dual Compute
A test in the testcode folder of GlobalGrid2050 that checks Concept Compute and Merge Results. It sets up class (`setUpClass`) and is built from the dual compute test class (`DualComputeTest`).
testglobalgrid2050 / testcode/202609150010/test_dual_compute.py · lines 1–55 of 55 · version 2026-09-15 00:10 · Entry point · pattern result (shared by 8 files)
- What it does
- It tests its inputs. Defines 6 functions or classes, including DualComputeTest, setUpClass, result, test_pinned_solar_evidence, test_local_and_ci_merge_when_identical. Uses libraries copy, json, tempfile, unittest, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Downstream impact
- Used directly by 2 files: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Testcode Dual Compute Workflow (globalgrid2050).
- What it achieves
- Defines `DualComputeTest`, `setUpClass`, `result` and 3 more.
- Why it matters
- Run by GlobalGrid2050 Project Signals Acid Workflow and GlobalGrid2050 Testcode Dual Compute Workflow.
- Application
- globalgrid2050 · testcode/202609150010 · test
- Uses
- Concept Compute (import), Merge Results (import), copy, json, tempfile, unittest, pathlib
- Used by
- run by GlobalGrid2050 Project Signals Acid Workflow (workflow run), run by GlobalGrid2050 Testcode Dual Compute Workflow (workflow run)
- Produces
- DualComputeTest
- Defines here
- DualComputeTest, setUpClass, result, test_pinned_solar_evidence, test_local_and_ci_merge_when_identical, test_merge_rejects_divergence
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150010/test_dual_compute.py:1-55 · blob 89e74250e4b4ceff7249d9c0e485b26ed5e8b6ad · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: production_core
import copy
import json
import tempfile
import unittest
from pathlib import Path
import concept_compute
import merge_results
ROOT = Path(__file__).resolve().parents[2]
class DualComputeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.payload = concept_compute.build_payload(ROOT)
def result(self, lane):
return {
"lane": lane,
"generated_utc": "2026-09-15T00:10:00Z",
"runner": {"python": "test", "system": "test"},
"git_commit": "test",
"payload_sha256": concept_compute.digest(concept_compute.canonical(self.payload)),
"payload": self.payload,
}
def test_pinned_solar_evidence(self):
pipeline = self.payload["inputs"]["pipeline"]
self.assertEqual(3563, pipeline["solar_projects"])
self.assertEqual(67013, pipeline["solar_mw_rounded"])
self.assertEqual(3558, pipeline["solar_with_coordinates"])
self.assertEqual(
{"14773", "17260", "1613", "17120", "1616"},
{p["repd_ref"] for p in pipeline["missing_coordinate_projects"]},
)
self.assertFalse(self.payload["reconciliation_findings"][0]["matches"])
self.assertTrue(self.payload["all_checks_pass"])
def test_local_and_ci_merge_when_identical(self):
merged = merge_results.merge(self.result("local"), self.result("ci"))
self.assertTrue(merged["agreement"])
def test_merge_rejects_divergence(self):
local = self.result("local")
ci = copy.deepcopy(self.result("ci"))
ci["payload"]["checks"]["solar_projects"] = False
ci["payload_sha256"] = concept_compute.digest(concept_compute.canonical(ci["payload"]))
with self.assertRaisesRegex(ValueError, "divergence"):
merge_results.merge(local, ci)
if __name__ == "__main__":
unittest.main()Build
A Python module in the proof folder of GlobalGrid2050 that reads profit over 1m and provenance, using SHA-256 from postcodes.io and the star-solar-star and ventus-grid-engine repositories.
renderglobalgrid2050 / testcode/202609150125/proof/build.py · lines 1–410 of 718 · version 2026-09-15 01:25 · Not reached from any entry point (candidate for review) · pattern category_of (shared by 2 files)
- What it does
- It loads profit over 1m, provenance, top within miles of ha4 lt by substation and outcode centroids. Defines 10 functions or classes, including cell, category_of, section_of, sha256, miles. Uses libraries hashlib, json, math, re, subprocess. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'testcode'): 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: 132kV. README: "One function, `cell()` in `proof/build.py`, applies all of them:"
- Inputs & outputs
- In: data source: postcodes.io; data source: star-solar-star data; data source: ventus-grid-engine data; Parquet file profit-over-1m.parquet; JSON file PROVENANCE.json; Excel file Top-1000-within-100-miles-of-HA4-0LT-by-substation.xlsx; JSON file outcode-centroids.json; JSON file leak-check.json. Out: JSON file sectors.json; JSON file geography.json; JSON file provenance.json. Voltage levels named: 132kV.
- What it achieves
- It is built from the cell step (`cell`), the category of helper (`category_of`) and the section of helper (`section_of`). Sector Star build script — testcode/. Its code works with 132 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · testcode/202609150125/proof · Python module
- Uses
- hashlib, json, math, re, subprocess, sys, time, datetime
- Used by
- none found
- Produces
- cell, category_of, section_of, sha256, miles, band, geo, money_block, cat_cells, place
- Defines here
- cell, category_of, section_of, sha256, miles, band, geo, money_block
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150125/proof/build.py:1-410 · blob 306b831b2be512c648ddd90d43c5afaa855adc5b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: experimental · users: none · canonical: unreached_review
"""Sector Star build script — testcode/202609150125.
Reads the private Ventus Companies House working set by absolute path and writes ONLY aggregates
into ../data/. No company name, registration number, address, full postcode, link, telephone,
e-mail or per-company row is ever written. This script is public; it embeds no data.
Deterministic techniques (stated in README.md and data/provenance.json):
- the suppression rule is ONE function, `cell()` below, used for every published group;
- every counted-but-withheld cell is tallied and the tallies go into provenance.json;
- every output file carries its source, fetch time and sha256;
- no randomness anywhere (no random module is imported).
Run: python proof/build.py
"""
import hashlib, json, math, re, subprocess, sys, time
from datetime import datetime, timezone
from pathlib import Path
import pandas as pd
import numpy as np
HERE = Path(__file__).resolve().parent
OUT = HERE.parent / "data"
OUT.mkdir(exist_ok=True)
SRC = Path(r"C:\Users\vikra\Desktop\CompaniesHouse")
PARQUET = SRC / "out" / "202609141922" / "profit-over-1m.parquet"
SUMMARY = SRC / "out" / "202609141922" / "SUMMARY.txt"
PROVENANCE = SRC / "PROVENANCE.json"
SUBSTATIONS = SRC / "out" / "202609142054-top1000-targets" / "Top-1000-within-100-miles-of-HA4-0LT-by-substation.xlsx"
CENTROIDS = SRC / "out" / "outcode-centroids.json"
OUTCODE_META = Path(r"C:\Users\vikra\AppData\Local\Temp\ss-build\outcode_meta.json")
MIN_N = 5 # any cell with fewer than this many companies is withheld
MIN_N_SUM = 10 # a sum is published only from this many companies upwards
MAX_SHARE = 0.50 # ... and only when the largest single contributor is under this share
HOME = "HA4" # Vikram's own public outcode, HA4 0LT
# ---------------------------------------------------------------- the one suppression function
TALLY = {"cells_withheld_n_lt_5": 0, "sums_withheld_n_lt_10": 0,
"sums_withheld_dominant_contributor": 0, "sums_withheld_not_positive": 0,
"cells_published": 0, "sums_published": 0}
def cell(values=None, n=None, want_sum=False):
"""The single suppression rule for every published group.
Returns {"n": int} plus, when allowed, "median" and "sum".
n < MIN_N -> {"n": None, "withheld": "n < 5"}
sum needs n >= MIN_N_SUM, a positive sum, and max contributor < MAX_SHARE.
Never returns a maximum or a top-N.
"""
v = np.asarray([], dtype=float) if values is None else np.asarray(values, dtype=float)
v = v[~np.isnan(v)]
count = int(n if n is not None else v.size)
if count < MIN_N:
TALLY["cells_withheld_n_lt_5"] += 1
return {"n": None, "withheld": "n < 5"}
TALLY["cells_published"] += 1
out = {"n": count}
if v.size:
out["median"] = round(float(np.median(v)), 2)
out["n_with_value"] = int(v.size)
if want_sum:
if v.size < MIN_N_SUM:
TALLY["sums_withheld_n_lt_10"] += 1
out["sum"] = None
out["sum_withheld"] = "n < 10"
else:
s = float(v.sum())
if s <= 0:
TALLY["sums_withheld_not_positive"] += 1
out["sum"] = None
out["sum_withheld"] = "sum not positive, dominance cannot be tested"
elif float(v.max()) / s >= MAX_SHARE:
TALLY["sums_withheld_dominant_contributor"] += 1
out["sum"] = None
out["sum_withheld"] = "largest single contributor >= 50% of the sum"
else:
TALLY["sums_published"] += 1
out["sum"] = round(s, 2)
return out
# ---------------------------------------------------------------- official UK SIC 2007 titles
SECTIONS = [
("A", "Agriculture, forestry and fishing", 1, 3),
("B", "Mining and quarrying", 5, 9),
("C", "Manufacturing", 10, 33),
("D", "Electricity, gas, steam and air conditioning supply", 35, 35),
("E", "Water supply; sewerage, waste management and remediation activities", 36, 39),
("F", "Construction", 41, 43),
("G", "Wholesale and retail trade; repair of motor vehicles and motorcycles", 45, 47),
("H", "Transportation and storage", 49, 53),
("I", "Accommodation and food service activities", 55, 56),
("J", "Information and communication", 58, 63),
("K", "Financial and insurance activities", 64, 66),
("L", "Real estate activities", 68, 68),
("M", "Professional, scientific and technical activities", 69, 75),
("N", "Administrative and support service activities", 77, 82),
("O", "Public administration and defence; compulsory social security", 84, 84),
("P", "Education", 85, 85),
("Q", "Human health and social work activities", 86, 88),
("R", "Arts, entertainment and recreation", 90, 93),
("S", "Other service activities", 94, 96),
("T", "Activities of households as employers; undifferentiated goods- and services-producing activities of households for own use", 97, 98),
("U", "Activities of extraterritorial organisations and bodies", 99, 99),
]
DIVISIONS = {
"01": "Crop and animal production, hunting and related service activities",
"02": "Forestry and logging", "03": "Fishing and aquaculture",
"05": "Mining of coal and lignite", "06": "Extraction of crude petroleum and natural gas",
"07": "Mining of metal ores", "08": "Other mining and quarrying",
"09": "Mining support service activities",
"10": "Manufacture of food products", "11": "Manufacture of beverages",
"12": "Manufacture of tobacco products", "13": "Manufacture of textiles",
"14": "Manufacture of wearing apparel", "15": "Manufacture of leather and related products",
"16": "Manufacture of wood and of products of wood and cork, except furniture",
"17": "Manufacture of paper and paper products",
"18": "Printing and reproduction of recorded media",
"19": "Manufacture of coke and refined petroleum products",
"20": "Manufacture of chemicals and chemical products",
"21": "Manufacture of basic pharmaceutical products and pharmaceutical preparations",
"22": "Manufacture of rubber and plastic products",
"23": "Manufacture of other non-metallic mineral products",
"24": "Manufacture of basic metals",
"25": "Manufacture of fabricated metal products, except machinery and equipment",
"26": "Manufacture of computer, electronic and optical products",
"27": "Manufacture of electrical equipment",
"28": "Manufacture of machinery and equipment n.e.c.",
"29": "Manufacture of motor vehicles, trailers and semi-trailers",
"30": "Manufacture of other transport equipment", "31": "Manufacture of furniture",
"32": "Other manufacturing", "33": "Repair and installation of machinery and equipment",
"35": "Electricity, gas, steam and air conditioning supply",
"36": "Water collection, treatment and supply", "37": "Sewerage",
"38": "Waste collection, treatment and disposal activities; materials recovery",
"39": "Remediation activities and other waste management services",
"41": "Construction of buildings", "42": "Civil engineering",
"43": "Specialised construction activities",
"45": "Wholesale and retail trade and repair of motor vehicles and motorcycles",
"46": "Wholesale trade, except of motor vehicles and motorcycles",
"47": "Retail trade, except of motor vehicles and motorcycles",
"49": "Land transport and transport via pipelines", "50": "Water transport",
"51": "Air transport", "52": "Warehousing and support activities for transportation",
"53": "Postal and courier activities", "55": "Accommodation",
"56": "Food and beverage service activities", "58": "Publishing activities",
"59": "Motion picture, video and television programme production, sound recording and music publishing activities",
"60": "Programming and broadcasting activities", "61": "Telecommunications",
"62": "Computer programming, consultancy and related activities",
"63": "Information service activities",
"64": "Financial service activities, except insurance and pension funding",
"65": "Insurance, reinsurance and pension funding, except compulsory social security",
"66": "Activities auxiliary to financial services and insurance activities",
"68": "Real estate activities", "69": "Legal and accounting activities",
"70": "Activities of head offices; management consultancy activities",
"71": "Architectural and engineering activities; technical testing and analysis",
"72": "Scientific research and development",
"73": "Advertising and market research",
"74": "Other professional, scientific and technical activities",
"75": "Veterinary activities", "77": "Rental and leasing activities",
"78": "Employment activities",
"79": "Travel agency, tour operator and other reservation service and related activities",
"80": "Security and investigation activities",
"81": "Services to buildings and landscape activities",
"82": "Office administrative, office support and other business support activities",
"84": "Public administration and defence; compulsory social security",
"85": "Education", "86": "Human health activities", "87": "Residential care activities",
"88": "Social work activities without accommodation",
"90": "Creative, arts and entertainment activities",
"91": "Libraries, archives, museums and other cultural activities",
"92": "Gambling and betting activities",
"93": "Sports activities and amusement and recreation activities",
"94": "Activities of membership organisations",
"95": "Repair of computers and personal and household goods",
"96": "Other personal service activities",
"97": "Activities of households as employers of domestic personnel",
"98": "Undifferentiated goods- and services-producing activities of private households for own use",
"99": "Activities of extraterritorial organisations and bodies",
}
CATEGORIES = [
{"id": "farmers", "name": "Farmers and growers", "colour": "#e0c97f",
"rule": "SIC 2007 divisions 01 and 03"},
{"id": "manufacturers", "name": "Manufacturers", "colour": "#ffd54a",
"rule": "SIC 2007 divisions 10 to 33"},
{"id": "other_high_energy", "name": "Other high energy users", "colour": "#00e5ff",
"rule": "SIC 2007 divisions 05-09, 35, 36-39, 41-43 (includes 43.21 electrical installation), "
"49-53, 55-56, 86, 93, group 63.1 (data processing and hosting), plus any group whose "
"median filed SECR kWh is above the overall median"},
{"id": "rest", "name": "Rest of the qualifying population", "colour": "#7da0c8",
"rule": "every other SIC 2007 division, including 02 forestry, which the category list does not name"},
]
HIGH_DIVS = set(["%02d" % d for d in list(range(5, 10)) + [35] + list(range(36, 40)) +
list(range(41, 44)) + list(range(49, 54)) + [55, 56, 86, 93]])
HIGH_GROUPS = {"63.1"}
def category_of(div, grp, extra_groups):
if div in ("01", "03"):
return "farmers"
if div.isdigit() and 10 <= int(div) <= 33:
return "manufacturers"
if div in HIGH_DIVS or grp in HIGH_GROUPS or grp in extra_groups:
return "other_high_energy"
return "rest"
def section_of(div):
if not div.isdigit():
return None
d = int(div)
for code, _name, lo, hi in SECTIONS:
if lo <= d <= hi:
return code
return None
def sha256(p):
return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def miles(lat1, lon1, lat2, lon2):
"""Great-circle miles. Straight line, not a driving distance."""
r = 3958.7613
p1, p2 = math.radians(lat1), math.radians(lat2)
dp, dl = p2 - p1, math.radians(lon2 - lon1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * r * math.asin(math.sqrt(a))
def band(m):
if m is None:
return "unplaced"
if m <= 25:
return "0-25 miles"
if m <= 50:
return "25-50 miles"
if m <= 100:
return "50-100 miles"
return "over 100 miles"
# ---------------------------------------------------------------- load
t0 = time.time()
BUILT = datetime.now(timezone.utc)
COLS = ["postcode", "sic_1", "status", "accounts_period_end", "profit_before_tax",
"profit_measure", "balance_value", "net_assets", "cash", "wages", "staff_costs",
"employees", "energy_kwh", "co2_scope1_tonnes", "co2_scope2_tonnes", "qualifies_on"]
df = pd.read_parquet(PARQUET, columns=COLS)
ROWS_IN = len(df)
pc = df["postcode"].fillna("").str.upper().str.replace(r"\s+", " ", regex=True).str.strip()
df["outcode"] = pc.str.split(" ").str[0]
df.loc[~df["outcode"].str.match(r"^[A-Z]{1,2}\d[A-Z\d]?$", na=False), "outcode"] = ""
df["area"] = df["outcode"].str.extract(r"^([A-Z]{1,2})")[0].fillna("")
sic5 = df["sic_1"].fillna("").str.extract(r"^(\d{5})")[0]
df["sic5"] = sic5.fillna("")
df["div"] = df["sic5"].str[:2]
df["grp"] = df["sic5"].str[:2] + "." + df["sic5"].str[2:3]
df.loc[df["sic5"] == "", ["div", "grp"]] = ""
NO_SIC = int((df["sic5"] == "").sum())
DORMANT = int((df["sic5"] == "99999").sum())
NO_PC = int((df["outcode"] == "").sum())
# tCO2e from the two filed scopes; scope 3 is never filed in this working set
df["tco2e"] = df[["co2_scope1_tonnes", "co2_scope2_tonnes"]].sum(axis=1, min_count=1)
# the "above the overall median SECR kWh" extension to other_high_energy
kwh = df.loc[df["energy_kwh"].notna(), ["grp", "energy_kwh"]]
overall_median_kwh = float(kwh["energy_kwh"].median()) if len(kwh) else None
extra_groups = set()
if overall_median_kwh is not None:
g = kwh.groupby("grp")["energy_kwh"].agg(["median", "size"])
extra_groups = set(g.index[(g["median"] > overall_median_kwh) & (g["size"] >= MIN_N)])
df["category"] = [category_of(d, g, extra_groups) for d, g in zip(df["div"], df["grp"])]
df["section"] = df["div"].map(section_of)
# outcode geography (postcodes.io; public open data)
meta = json.loads(OUTCODE_META.read_text())
local_centroids = json.loads(CENTROIDS.read_text())
for o, ll in local_centroids.items():
if o not in meta or not meta[o] or meta[o].get("lat") is None:
meta[o] = {"lat": ll[0], "lon": ll[1], "region": None, "country": None,
"county": None, "district": None}
home = meta.get(HOME) or {}
HOME_LL = (home.get("lat"), home.get("lon"))
def geo(o, key):
m = meta.get(o) or {}
return m.get(key)
df["lat"] = [geo(o, "lat") for o in df["outcode"]]
df["lon"] = [geo(o, "lon") for o in df["outcode"]]
# postcodes.io does not return an ONS region for an outcode, so England regions are approximated
# from the postcode area letters. Wales comes from the authoritative country field.
AREA_REGION = {
"North East": "DH DL NE SR TS",
"North West": "BB BL CA CH CW FY L LA M OL PR SK WA WN",
"Yorkshire and The Humber": "BD DN HD HG HU HX LS S WF YO",
"East Midlands": "DE LE LN NG NN",
"West Midlands": "B CV DY HR ST SY TF WR WS WV",
"East of England": "AL CB CM CO IP LU NR PE SG SS WD",
"London": "BR CR E EC EN HA IG KT N NW RM SE SM SW TW UB W WC",
"South East": "BN CT DA GU HP ME MK OX PO RG RH SL SO TN",
"South West": "BA BH BS DT EX GL PL SN SP TA TQ TR",
}
AREA_TO_REGION = {a: r for r, aa in AREA_REGION.items() for a in aa.split()}
country = [geo(o, "country") for o in df["outcode"]]
df["region"] = [("Wales" if c == "Wales" else AREA_TO_REGION.get(a))
for c, a in zip(country, df["area"])]
df["county"] = [(geo(o, "county") or geo(o, "district")) for o in df["outcode"]]
dist_by_outcode = {}
for o, m in meta.items():
if m and m.get("lat") is not None and HOME_LL[0] is not None:
dist_by_outcode[o] = round(miles(HOME_LL[0], HOME_LL[1], m["lat"], m["lon"]), 1)
df["miles"] = [dist_by_outcode.get(o) for o in df["outcode"]]
df["band"] = [band(m) for m in df["miles"]]
MONEY = {"profit_before_tax_gbp": "profit_before_tax", "profit_measure_gbp": "profit_measure",
"net_worth_gbp": "balance_value", "cash_gbp": "cash", "wages_gbp": "wages",
"employees": "employees"}
def money_block(sub):
out = {}
for label, col in MONEY.items():
out[label] = cell(sub[col].values, n=len(sub), want_sum=True)
e = sub.loc[sub["energy_kwh"].notna()]
c = sub.loc[sub["tco2e"].notna()]
out["secr"] = {
"n_filing_energy": int(len(e)),
"energy_kwh": cell(e["energy_kwh"].values, want_sum=True) if len(e) else
{"n": None, "withheld": "not filed"},
"n_filing_co2": int(len(c)),
"tco2e": cell(c["tco2e"].values, want_sum=True) if len(c) else
{"n": None, "withheld": "not filed"},
}
return out
TOTAL = len(df)
# ---------------------------------------------------------------- sectors.json
cat_counts = df["category"].value_counts().to_dict()
cats = []
for c in CATEGORIES:
sub = df[df["category"] == c["id"]]
cats.append({**c, "count": int(len(sub)),
"share": round(len(sub) / TOTAL, 6), **money_block(sub)})
sections = []
for code, name, lo, hi in SECTIONS:
sub = df[df["section"] == code]
if not len(sub):
continue
sections.append({"code": code, "name": name, "divisions": "%02d-%02d" % (lo, hi),
"count": int(len(sub)), "share": round(len(sub) / TOTAL, 6),
**money_block(sub)})
divisions, div_other = [], 0
for d, sub in df[df["div"] != ""].groupby("div"):
if d not in DIVISIONS:
div_other += len(sub)
continue
if len(sub) < MIN_N:
TALLY["cells_withheld_n_lt_5"] += 1
div_other += len(sub)
continue
divisions.append({"code": d, "name": DIVISIONS[d], "section": section_of(d),
"category": category_of(d, d + ".0", extra_groups),
"count": int(len(sub)), "share": round(len(sub) / TOTAL, 6),
**money_block(sub)})
divisions.sort(key=lambda x: -x["count"])
groups, grp_other = [], 0
class_titles = (df.loc[df["sic5"] != ""].groupby("sic5")["sic_1"].first().to_dict())
for g, sub in df[df["grp"] != ""].groupby("grp"):
d = g[:2]
if d not in DIVISIONS:
grp_other += len(sub)
continue
if len(sub) < MIN_N:
TALLY["cells_withheld_n_lt_5"] += 1
grp_other += len(sub)
continue
classes, cls_other = [], 0
for code, csub in sub.groupby("sic5"):
if len(csub) < MIN_N:
TALLY["cells_withheld_n_lt_5"] += 1
cls_other += len(csub)
continue
title = (class_titles.get(code) or "").split(" - ", 1)
classes.append({"code": code, "title": title[1] if len(title) > 1 else None,
"count": int(len(csub))})
classes.sort(key=lambda x: -x["count"])
groups.append({"code": g, "division": d, "section": section_of(d),
"category": category_of(d, g, extra_groups),
"name": None,
"name_note": "the ONS group title is not held in this build; the official SIC 2007 "
"class titles inside the group are listed instead",
"count": int(len(sub)), "share": round(len(sub) / TOTAL, 6),
"classes": classes,
"classes_withheld_n_lt_5": int(cls_other),