GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / tools/intelligence/cartridges/gb-electricity-context/assets

Build Payload and 3 more files (part 1)

A Python command-line tool in the grid actions inline folder of PipelineNews that works with tolerance km and voltages kV and calculates planar distances, covering grid substations.

606 lines of Python and JavaScript from pipelinenews, in 4 files. Topic: Electricity markets and data pipelines. Section 1036 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. GB Electricity Context render · pipelinenews / tools/intelligence/cartridges/gb-electricity-context/assets/{GEN}-gb-electricity-context.mjs lines 1–144
  2. Proof render · pipelinenews / tools/intelligence/cartridges/gb-electricity-context/proof.mjs lines 1–129
  3. Sync Payload ingest · pipelinenews / tools/intelligence/cartridges/gb-electricity-context/sync_payload.py lines 1–49
  4. Build Payload other · pipelinenews / tools/intelligence/cartridges/grid-actions-inline/build_payload.py lines 1–284

GB Electricity Context

A JavaScript module in the assets folder of PipelineNews that loads attested product (`loadAttestedProduct`) and validates product (`validateProduct`), covering solar, using SHA-256.

Set aside from the main view: 98% of its lines are the same as pipelinenews_intelligence/202608312339/assets/202608312339-gb-electricity-context.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with GB Electricity Context; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9837 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 pipelinenews_intelligence/202608312339/assets/202608312339-gb-electricity-context.mjs:1-144 2307d27693478862476b8676061e4a74a022668b
  • sha256 ee732063cc657665d856f59b416150f02a6c2813e6e73d016dce641319be28f6
  • target sha256 79cd1c74e26e489c8e2ec1c929db50dd0df8e12d794eeb981aafebd309aace3a
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderpipelinenews / tools/intelligence/cartridges/gb-electricity-context/assets/{GEN}-gb-electricity-context.mjs · lines 1–144 of 144 · Not reached from any entry point (candidate for review) · pattern mountGbElectricityContext (shared by 3 files)

What it does
It draws solar. Defines 9 functions or classes, including invariant, escapeHtml, digestHex, loadAttestedProduct, validateProduct. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: solar.
What it achieves
It loads attested product (`loadAttestedProduct`) and validates product (`validateProduct`). Defines `invariant`, `escapeHtml`, `digestHex` and 6 more.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/intelligence/cartridges/gb-electricity-context/assets · JavaScript module
Uses
none found
Used by
none found
Produces
GB_ELECTRICITY_CONTEXT_CONTRACT, mountGbElectricityContext
Defines here
invariant, escapeHtml, digestHex, loadAttestedProduct, validateProduct, number, money, render, mountGbElectricityContext
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/gb-electricity-context/assets/{GEN}-gb-electricity-context.mjs:1-144 · blob 991606ad6f476be6171f75b48db9b5dc02abdaab · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
export const GB_ELECTRICITY_CONTEXT_CONTRACT = Object.freeze({
  schema: "pipelinenews.gb-electricity-context-cartridge.v1",
  generation: "{GEN}",
  additive_only: true,
  mutates_existing_dom: false,
  project_bindings: 0,
  eligible_for_news_signal: false,
  source_repository: "Ventusltd/data-gb-electricity",
  source_schema: "data-gb-electricity.price-decade-rollup.v1",
});

function invariant(condition, message) {
  if (!condition) throw new Error(message);
}

function escapeHtml(value) {
  return String(value ?? "").replace(/[&<>"']/g, character => ({
    "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
  })[character]);
}

async function digestHex(buffer) {
  const digest = await crypto.subtle.digest("SHA-256", buffer);
  return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("");
}

async function loadAttestedProduct(asset) {
  invariant(asset && typeof asset.url === "string", "GB price payload URL missing");
  invariant(Number.isInteger(asset.bytes) && asset.bytes > 0, "GB price payload byte pin missing");
  invariant(/^[a-f0-9]{64}$/u.test(asset.sha256), "GB price payload digest pin missing");
  const target = new URL(asset.url, location.href);
  invariant(target.origin === location.origin, "cross-origin GB price payload rejected");
  const response = await fetch(target.href, { cache: "no-store" });
  invariant(response.ok, `GB price payload returned HTTP ${response.status}`);
  const raw = await response.arrayBuffer();
  invariant(raw.byteLength === asset.bytes, "GB price payload byte drift");
  invariant(await digestHex(raw) === asset.sha256, "GB price payload digest drift");
  return JSON.parse(new TextDecoder().decode(raw));
}

function validateProduct(product) {
  invariant(product?.schema === GB_ELECTRICITY_CONTEXT_CONTRACT.source_schema,
    "GB price product schema changed");
  invariant(typeof product.not_a_forecast === "string" && product.not_a_forecast.length > 30,
    "GB price product lost its no-forecast boundary");
  invariant(product.solar?.present === false, "GB price product unexpectedly claims solar data");
  invariant(product.price?.unit === "GBP per MWh", "GB price unit changed");
  invariant(Array.isArray(product.price.span) && product.price.span.length === 2,
    "GB price span missing");
  invariant(Array.isArray(product.price.by_year) && product.price.by_year.length >= 10,
    "GB yearly rollup is not a decade");
  const completeDays = product.price.by_year.reduce((sum, row) => sum + Number(row.days), 0);
  const negativeDays = product.price.by_year.reduce((sum, row) =>
    sum + Number(row.days_with_a_negative_settlement_period), 0);
  invariant(completeDays === product.derived_from.complete_days,
    "GB complete-day provenance disagrees with yearly rows");
  invariant(negativeDays === product.price.days_with_a_negative_settlement_period,
    "GB negative-settlement-day headline disagrees with yearly rows");
  invariant(product.price.by_year.every((row, index, rows) => index === 0
    || Number(rows[index - 1].year) < Number(row.year)), "GB years are not strictly increasing");
}

function number(value, digits = 0) {
  return Number(value).toLocaleString("en-GB", {
    minimumFractionDigits: digits,
    maximumFractionDigits: digits,
  });
}

function money(value) {
  const numeric = Number(value);
  return `${numeric < 0 ? "-" : ""}£${number(Math.abs(numeric), 2)}`;
}

function render(host, product) {
  const price = product.price;
  const low = price.lowest_settlement_period;
  const high = price.highest_settlement_period;
  const yearRows = price.by_year.map(row => `
    <tr>
      <th scope="row">${escapeHtml(row.year)}</th>
      <td>${number(row.days)}</td>
      <td>${number(row.mean_gbp_per_mwh, 2)}</td>
      <td>${number(row.min_daily_mean, 2)}</td>
      <td>${number(row.max_daily_mean, 2)}</td>
      <td>${number(row.days_with_a_negative_settlement_period)}</td>
    </tr>`).join("");

  const style = document.createElement("style");
  style.textContent = `
    #gbElectricityHost .gbe-wrap{border:1px solid #21454b;background:#061215;padding:12px;color:#c8dadd}
    #gbElectricityHost .gbe-head{display:flex;flex-wrap:wrap;justify-content:space-between;gap:8px;align-items:baseline}
    #gbElectricityHost .gbe-head h3{margin:0;color:#70d2db;font:700 13px ui-monospace,monospace;letter-spacing:.08em}
    #gbElectricityHost .gbe-head span{color:#779096;font:10px ui-monospace,monospace}
    #gbElectricityHost .gbe-cards{display:grid;grid-template-columns:repeat(4,minmax(130px,1fr));gap:7px;margin:10px 0}
    #gbElectricityHost .gbe-card{border:1px solid #1a353b;background:#030a0d;padding:8px}
    #gbElectricityHost .gbe-card b{display:block;color:#e4f4f5;font:700 18px ui-monospace,monospace}
    #gbElectricityHost .gbe-card span{color:#82989d;font:9px/1.4 ui-monospace,monospace;text-transform:uppercase}
    #gbElectricityHost .gbe-table{overflow-x:auto;overscroll-behavior-x:contain}
    #gbElectricityHost table{width:100%;min-width:650px;border-collapse:collapse;font:10px/1.4 ui-monospace,monospace}
    #gbElectricityHost th,#gbElectricityHost td{padding:5px 7px;border-bottom:1px solid #14282d;text-align:right;white-space:nowrap}
    #gbElectricityHost th:first-child,#gbElectricityHost td:first-child{text-align:left}
    #gbElectricityHost thead th{color:#70d2db;font-size:9px;vertical-align:bottom}
    #gbElectricityHost .gbe-note{margin:9px 0 0;color:#8ca1a6;font:10px/1.55 ui-monospace,monospace}
    #gbElectricityHost .gbe-note strong{color:#d7a95e}
    #gbElectricityHost .gbe-source{color:#70d2db}
    @media(max-width:720px){#gbElectricityHost .gbe-cards{grid-template-columns:repeat(2,minmax(0,1fr))}}
    @media(max-width:420px){#gbElectricityHost .gbe-wrap{padding:9px}#gbElectricityHost .gbe-card b{font-size:15px}}
  `;
  host.replaceChildren(style);
  const panel = document.createElement("div");
  panel.className = "gbe-wrap";
  panel.innerHTML = `
    <div class="gbe-head"><h3>HISTORIC GB SYSTEM PRICE</h3>
      <span>${escapeHtml(price.span.join("-"))} · ${number(product.derived_from.settlement_periods)} settlement periods</span></div>
    <div class="gbe-cards">
      <div class="gbe-card"><b>${money(price.decade_mean)}</b><span>mean of complete daily means · £/MWh</span></div>
      <div class="gbe-card"><b>${number(price.days_with_a_negative_settlement_period)}</b><span>complete days containing at least one negative settlement period</span></div>
      <div class="gbe-card"><b>${money(low.value)}</b><span>lowest settlement period · ${escapeHtml(low.date)}</span></div>
      <div class="gbe-card"><b>${money(high.value)}</b><span>highest settlement period · ${escapeHtml(high.date)}</span></div>
    </div>
    <div class="gbe-table"><table>
      <thead><tr><th>YEAR</th><th>COMPLETE DAYS</th><th>MEAN £/MWh</th><th>LOW DAILY MEAN</th><th>HIGH DAILY MEAN</th><th>DAYS WITH A NEGATIVE PERIOD</th></tr></thead>
      <tbody>${yearRows}</tbody>
    </table></div>
    <p class="gbe-note"><strong>Historic context only. Not a forecast.</strong> ${escapeHtml(product.not_a_forecast)}
      This panel is not joined to a project and cannot create or alter a REPD news signal.</p>
    <p class="gbe-note"><strong>Solar is not in this product.</strong> ${escapeHtml(product.solar.why)}</p>
    <p class="gbe-note">Source: Elexon system sell price via the attested
      <a class="gbe-source" href="https://github.com/Ventusltd/data-gb-electricity" target="_blank" rel="noopener">Ventusltd/data-gb-electricity rollup</a>.
      Product grain is calendar year over complete daily means; days with fewer than
      ${number(product.grain.minimum_periods_per_day)} settlement periods are excluded.</p>`;
  host.appendChild(panel);
}

export async function mountGbElectricityContext({ host, payloadAsset }) {
  invariant(host && typeof host.replaceChildren === "function", "GB electricity host missing");
  const product = await loadAttestedProduct(payloadAsset);
  validateProduct(product);
  render(host, product);
  host.dataset.gbElectricityState = "ready";
  return Object.freeze({ payloadRequests: 1, projectBindings: 0,
    years: product.price.by_year.length, completeDays: product.derived_from.complete_days });
}

Proof

A JavaScript module in the GB electricity context folder of PipelineNews that makes host (`makeHost`), covering solar, using SHA-256. It makes host (`makeHost`).

renderpipelinenews / tools/intelligence/cartridges/gb-electricity-context/proof.mjs · lines 1–129 of 129 · Not reached from any entry point (candidate for review)

What it does
It draws solar. Defines makeHost. Uses libraries node:assert/strict, node:crypto, node:fs/promises, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: solar.
Inputs & outputs
In: command-line arguments.
What it achieves
Render and integrity proof for the GB electricity context cartridge.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/intelligence/cartridges/gb-electricity-context · JavaScript module
Uses
node:assert/strict, node:crypto, node:fs/promises, node:path, node:url
Used by
none found
Produces
makeHost
Defines here
makeHost
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/gb-electricity-context/proof.mjs:1-129 · blob 5d8fdb431bf49dc2245e0af98ef8808fd35d22e0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/** Render and integrity proof for the GB electricity context cartridge. */

import assert from "node:assert/strict";
import crypto from "node:crypto";
import { readFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";

const root = process.argv[2];
const gen = process.argv[3];
if (!root || !gen) {
  console.error("usage: node proof.mjs <release-directory> <generation>");
  process.exit(2);
}

const releaseRoot = resolve(root);
const payloadPath = join(releaseRoot, "data", `${gen}-price-decade-rollup.json`);
const payloadBytes = await readFile(payloadPath);
const payload = JSON.parse(payloadBytes.toString("utf8"));
const payloadSha = crypto.createHash("sha256").update(payloadBytes).digest("hex");

const created = [];
globalThis.document = {
  createElement(tagName) {
    const element = {
      tagName: String(tagName).toUpperCase(),
      className: "",
      innerHTML: "",
      textContent: "",
      dataset: {},
    };
    created.push(element);
    return element;
  },
};
globalThis.location = new URL("https://globalgrid2050.com/pipelinenews_intelligence/test/");
assert.ok(globalThis.crypto?.subtle || crypto.webcrypto?.subtle,
  "Node must provide Web Crypto for the browser digest parity check");

let fetchCalls = 0;
let responseBytes = payloadBytes;
globalThis.fetch = async () => {
  fetchCalls += 1;
  const body = responseBytes;
  return {
    ok: true,
    status: 200,
    arrayBuffer: async () => body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength),
  };
};

const moduleUrl = pathToFileURL(
  join(releaseRoot, "assets", `${gen}-gb-electricity-context.mjs`),
).href;
const cartridge = await import(moduleUrl);
assert.equal(fetchCalls, 0, "import must not request the payload");
assert.equal(cartridge.GB_ELECTRICITY_CONTEXT_CONTRACT.generation, gen);
assert.equal(cartridge.GB_ELECTRICITY_CONTEXT_CONTRACT.project_bindings, 0);

function makeHost() {
  return {
    children: [],
    dataset: {},
    replaceChildren(...children) { this.children = [...children]; },
    appendChild(child) { this.children.push(child); return child; },
  };
}

const host = makeHost();
const result = await cartridge.mountGbElectricityContext({
  host,
  payloadAsset: {
    url: `data/${gen}-price-decade-rollup.json`,
    bytes: payloadBytes.byteLength,
    sha256: payloadSha,
  },
});

assert.equal(fetchCalls, 1, "explicit mount must fetch exactly one snapshot");
assert.equal(result.projectBindings, 0);
assert.equal(result.years, payload.price.by_year.length);
assert.equal(host.children.length, 2, "render must stay inside its supplied host");
const [style, panel] = host.children;
const markup = panel.innerHTML;
assert.equal((markup.match(/<tr>/g) || []).length - 1, payload.price.by_year.length);
assert.match(markup, new RegExp(String(payload.price.days_with_a_negative_settlement_period)));
assert.match(markup, /containing at least one negative settlement period/i);
assert.match(markup, /historic context only/i);
assert.match(markup, /not a forecast/i);
assert.match(markup, /not joined to a project/i);
assert.match(markup, /solar is not in this product/i);
assert.match(markup, /class="gbe-table"/, "table must have its own horizontal overflow wrapper");
const selectors = [...style.textContent.matchAll(/([^{}]+)\{/g)]
  .map(match => match[1].trim())
  .filter(selector => !selector.startsWith("@"));
assert.ok(selectors.every(selector => selector.split(",").every(part =>
  part.trim().startsWith("#gbElectricityHost"))),
  "cartridge CSS selectors must stay under its host");

const completeDays = payload.price.by_year.reduce((sum, row) => sum + row.days, 0);
const negativeDays = payload.price.by_year.reduce((sum, row) =>
  sum + row.days_with_a_negative_settlement_period, 0);
assert.equal(completeDays, payload.derived_from.complete_days);
assert.equal(negativeDays, payload.price.days_with_a_negative_settlement_period);
assert.equal(payload.solar.present, false);

// The byte pin must be substantive rather than decorative.
responseBytes = Buffer.from(payloadBytes);
responseBytes[responseBytes.length - 2] ^= 1;
const diseasedHost = makeHost();
await assert.rejects(() => cartridge.mountGbElectricityContext({
  host: diseasedHost,
  payloadAsset: {
    url: `data/${gen}-price-decade-rollup.json`,
    bytes: responseBytes.byteLength,
    sha256: payloadSha,
  },
}), /digest drift/);

console.log(JSON.stringify({
  schema: "pipelinenews.gb-electricity-context-proof.v1",
  generation: gen,
  checks: "PASS",
  years: result.years,
  complete_days: result.completeDays,
  payload_requests: 1,
  project_bindings: 0,
  tampered_payload: "REJECTED",
}, null, 2));

Sync Payload

A Python command-line tool in the GB electricity context folder of PipelineNews that reads price decade rollup and solar.

ingestpipelinenews / tools/intelligence/cartridges/gb-electricity-context/sync_payload.py · lines 1–49 of 49 · Entry point

What it does
It loads price decade rollup and solar. Defines main. Uses libraries argparse, io, json, os, shutil. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: solar.
Inputs & outputs
In: JSON file price-decade-rollup.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Pin the browser-sized GB price rollup owned by data-GB-electricity. It accepts `--source`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · tools/intelligence/cartridges/gb-electricity-context · Python CLI
Uses
argparse, io, json, os, shutil
Used by
none found
Produces
main
Defines here
main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/gb-electricity-context/sync_payload.py:1-49 · blob c5f0d8f31a2d2527e86f5d6cf17ea2a56e5689c5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Pin the browser-sized GB price rollup owned by data-gb-electricity.

This copies an already-derived product. It does not read the Parquet, call an
API, recompute a price, or create a competing definition. The PipelineNews
release builder later hashes the exact snapshot into its registry.
"""

import argparse
import io
import json
import os
import shutil


HERE = os.path.dirname(os.path.abspath(__file__))
DEST = os.path.join(HERE, "data", "{GEN}-price-decade-rollup.json")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--source", required=True,
                        help="data-gb-electricity/derived/price-decade-rollup.json")
    args = parser.parse_args()

    with io.open(args.source, encoding="utf-8") as handle:
        product = json.load(handle)
    if product.get("schema") != "data-gb-electricity.price-decade-rollup.v1":
        raise SystemExit("wrong GB electricity product schema")
    price = product.get("price") or {}
    years = price.get("by_year") or []
    if len(years) < 10:
        raise SystemExit("price rollup does not cover a decade")
    if sum(int(row["days"]) for row in years) != product["derived_from"]["complete_days"]:
        raise SystemExit("yearly complete-day total disagrees with provenance")
    if sum(int(row["days_with_a_negative_settlement_period"]) for row in years) \
            != price["days_with_a_negative_settlement_period"]:
        raise SystemExit("yearly negative-settlement-day total disagrees with headline")
    if product.get("solar", {}).get("present") is not False:
        raise SystemExit("snapshot unexpectedly claims a solar series")

    os.makedirs(os.path.dirname(DEST), exist_ok=True)
    shutil.copyfile(args.source, DEST)
    print("pinned %s complete days across %d calendar years" %
          (product["derived_from"]["complete_days"], len(years)))
    print("wrote %s" % DEST)


if __name__ == "__main__":
    main()

Build Payload

A Python command-line tool in the grid actions inline folder of PipelineNews that works with tolerance km and voltages kV and calculates planar distances, covering grid substations.

otherpipelinenews / tools/intelligence/cartridges/grid-actions-inline/build_payload.py · lines 1–284 of 284 · Entry point · pattern latest_grid_proximity (shared by 2 files)

What it does
Defines 6 functions or classes, including tolerance_km, voltages_kv, centre, latest_grid_proximity, main. Uses libraries argparse, glob, hashlib, io, json. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: 33kV, transformers, 11kV.
Inputs & outputs
In: GeoJSON file grid_substations.geojson; command-line arguments. Voltage levels named: 33kV, 11kV.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the tolerance km helper (`tolerance_km`), the voltages kV helper (`voltages_kv`) and the centre step (`centre`). Build the substation payload: nearest 33kV+ substation per project. Its code works with 33 kV, 11 kV and 40 MW. It accepts `--gen` and `--source`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · tools/intelligence/cartridges/grid-actions-inline · Python CLI
Uses
argparse, glob, hashlib, io, json, math, os, re
Used by
none found
Produces
tolerance_km, voltages_kv, centre, latest_grid_proximity, main
Defines here
tolerance_km, voltages_kv, centre, latest_grid_proximity, main, measure
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-actions-inline/build_payload.py:1-284 · blob 015c96b6fea0205e42f2db7921823ceda2101a65 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Build the substation payload: nearest 33 kV+ substation per project.

WHY A SUBSTATION AND NOT ONLY A CIRCUIT
---------------------------------------
A utility-scale solar or battery scheme of a few tens of MW connects at a
SUBSTATION. It does not connect to a conductor it happens to sit under. So
"how far is the nearest circuit" answers whether the network runs past the
gate, and "how far is the nearest substation" is closer to where the scheme
would actually attach.

Measured over the 3,047 projects the grid layers cover:

    nearest 33 kV+ substation   median 1.52 km, 36.1% inside 1 km
    nearest 33 kV circuit       median 6.44 km

and for the 30-40 MW band specifically, the substation is the closer of the two
for 68% of projects. It is the more useful number for screening, which is why
it now sits beside the circuit distance rather than only inside the panel.

WHY EVERY SUBSTATION IN THE LAYER QUALIFIES
-------------------------------------------
The scope is 33 kV and above: 11 kV is rare for utility-scale export and, where
it does occur, is often a private network behind the meter, so it is not a
screening signal. That turns out to require no filtering at all. All 5,800
substations in the Atlas layer carry at least one voltage of 33 kV or more --
4,342 of them carry 33 kV itself, and not one has a highest voltage below it.
So the published `substation.km` in the grid-proximity payload IS the nearest
33 kV+ substation, and this carries it across rather than recomputing it.

Two tagging details matter when reading the layer:

  * `voltage` is written `33000`, or `33000;11000` for two voltages, or
    `33000:11000` for a TRANSFORMER RATIO -- a 33/11 primary, which still means
    33 kV is present. Splitting only on `;` drops the ratio tags.
  * Substations are mapped as points AND as polygons. A polygon's first ring
    vertex is a corner, not the site; the ring mean is used instead.

As with the circuit column, every carried distance is re-measured against the
canonical geodesy in Ventusltd/grid-distance-maths before it is written. All
3,047 reproduce exactly.

    python build_payload.py
"""

import argparse
import glob
import hashlib
import io
import json
import math
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(HERE))))
RELEASES = os.path.join(REPO, "releases")
WORKSPACE = os.path.dirname(REPO)
OUT = os.path.join(HERE, "data", "{GEN}-substation-33kv.json")

GEODESY_SRC = os.path.join(WORKSPACE, "grid-distance-maths", "src")
if not os.path.isfile(os.path.join(GEODESY_SRC, "geodesy.py")):
    raise SystemExit(
        "canonical geodesy not found at %s\n"
        "Clone Ventusltd/grid-distance-maths beside this repository." % GEODESY_SRC)
sys.path.insert(0, GEODESY_SRC)

import geodesy as G  # noqa: E402

SUBSTATIONS = os.path.join(WORKSPACE, "globalgrid2050", "repd_grid_atlasv8",
                           "data", "grid_substations.geojson")

# Same derivation as the circuit column: the source rounds distances to 3 dp and
# coordinates to 6 dp, so agreement finer than those roundings is not available
# from the stored data. See grid-distance-column/build_payload.py.
KM_DECIMALS = 3
COORD_DECIMALS = 6
KM_PER_DEG_LAT = 111.32

MIN_KV = 33.0


def tolerance_km(latitudes):
    km_rounding = 0.5 * 10 ** -KM_DECIMALS
    half = 0.5 * 10 ** -COORD_DECIMALS
    lowest = min((abs(v) for v in latitudes), default=0.0)
    kx = KM_PER_DEG_LAT * math.cos(math.radians(lowest))
    return km_rounding + 2 * math.hypot(half * kx, half * KM_PER_DEG_LAT)


def voltages_kv(props):
    """Every voltage named on a substation, in kV. Handles `;` lists and `:`
    transformer ratios alike; a 33/11 primary counts as 33 kV present."""
    raw = props.get("voltage") or props.get("kv") or ""
    out = []
    for token in re.split(r"[;,|:\s]+", str(raw)):
        token = token.strip()
        if not token:
            continue
        try:
            value = float(token)
        except ValueError:
            continue
        out.append(value / 1000 if value > 1000 else value)
    return out


def centre(geometry):
    """A representative point. A polygon's ring mean, not its first corner."""
    coords = geometry.get("coordinates")
    kind = geometry.get("type")
    if not coords:
        return None
    if kind == "Point":
        return coords[0], coords[1]
    ring = coords[0] if kind == "Polygon" else (
        coords[0][0] if kind == "MultiPolygon" else None)
    if not ring:
        return None
    return (sum(p[0] for p in ring) / len(ring),
            sum(p[1] for p in ring) / len(ring))


def latest_grid_proximity():
    hits = sorted(glob.glob(os.path.join(
        RELEASES, "*-pipelinenews", "data", "*-grid-proximity.json")))
    if not hits:
        raise SystemExit("no grid-proximity payload found under %s" % RELEASES)
    return hits[-1]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--gen", default="{GEN}")
    ap.add_argument("--source")
    a = ap.parse_args()

    # ---- the layer, and the scope claim ---------------------------------
    layer = json.loads(io.open(SUBSTATIONS, encoding="utf-8").read())["features"]
    points = []
    below = 0
    at33 = 0
    untagged = 0
    for feature in layer:
        vs = voltages_kv(feature.get("properties", {}))
        if not vs:
            untagged += 1
            continue
        if max(vs) < MIN_KV - 0.5:
            below += 1
            continue
        if any(abs(v - 33) < 0.51 for v in vs):
            at33 += 1
        spot = centre(feature.get("geometry") or {})
        if spot:
            points.append(spot)

    print("substation layer            %d features" % len(layer))
    print("  carrying 33 kV or above   %d" % len(points))
    print("  carrying 33 kV itself     %d" % at33)
    print("  highest voltage below 33  %d" % below)
    print("  no parseable voltage      %d" % untagged)
    if below or untagged:
        print("  NOTE: the layer is not purely 33 kV+; the filter above is doing work")

    # ---- carry the published distances across, and check every one -------
    source = a.source or latest_grid_proximity()
    src = json.loads(io.open(source, encoding="utf-8").read())
    print("\nsource   %s" % os.path.relpath(source, REPO).replace("\\", "/"))

    index = G.SpatialIndex(0.1)
    for i, (lon, lat) in enumerate(points):
        index.add(i, lon, lat)

    tol = tolerance_km([(r.get("at") or [None, None])[1] for r in src.get("rows", [])
                        if (r.get("at") or [None, None])[1] is not None])

    out = {}
    checked = 0
    worst = 0.0
    failures = []
    bands = {}
    for row in src.get("rows", []):
        ref = str(row.get("ref") or "").strip()
        at = row.get("at") or []
        published = (row.get("substation") or {}).get("km")
        if not ref or len(at) != 2 or published is None:
            continue
        lon, lat = at

        def measure(i, lon=lon, lat=lat):
            return G.distance_km(lon, lat, points[i][0], points[i][1])

        hit = index.nearest(lon, lat, measure)
        if hit is None:
            continue
        checked += 1
        delta = abs(hit["km"] - published)
        worst = max(worst, delta)
        if delta > tol:
            failures.append((ref, published, hit["km"], delta))

        entry = {"k": round(published, 3)}
        name = (row.get("substation") or {}).get("name") or ""
        if name:
            entry["n"] = name
        kv = (row.get("substation") or {}).get("kv") or []
        if kv:
            entry["v"] = kv
        band = ("STRONG" if published <= 1 else "MODERATE" if published <= 3
                else "DISTANT" if published <= 10 else "REMOTE")
        entry["b"] = band
        bands[band] = bands.get(band, 0) + 1
        out[ref] = entry

    print("\nverification against Ventusltd/grid-distance-maths")
    print("  rows re-measured        %d" % checked)
    print("  worst disagreement      %.3e km" % worst)
    print("  rounding bound          %.3e km" % tol)
    if failures:
        print("\n%d rows disagree beyond the bound. Writing nothing." % len(failures))
        for ref, pub, meas, delta in failures[:10]:
            print("   ref %-8s published %.6f  canonical %.6f  delta %.3e"
                  % (ref, pub, meas, delta))
        return 1
    print("  RESULT                  every published substation distance reproduces")

    payload = {
        "schema": "pipelinenews.substation-33kv.v1",
        "generation": a.gen,
        "projects": len(out),
        "network_at_runtime": False,
        "scope": {
            "minimum_kv": MIN_KV,
            "why": "33 kV and above. 11 kV is rare for utility-scale export and "
                   "where it occurs is often a private network behind the meter, "
                   "so it is not a screening signal.",
            "layer_features": len(layer),
            "qualifying": len(points),
            "carrying_33kv_itself": at33,
            "excluded_below_33kv": below,
            "tagging_note": "OSM writes voltage as 33000, as 33000;11000 for two "
                            "voltages, and as 33000:11000 for a transformer "
                            "ratio. A 33/11 primary carries 33 kV and counts.",
            "geometry_note": "Substations are mapped as points and as polygons. "
                             "A polygon is reduced to its ring mean, not its "
                             "first vertex.",
        },
        "bands": {
            "STRONG": "substation within 1 km",
            "MODERATE": "within 3 km",
            "DISTANT": "within 10 km",
            "REMOTE": "beyond 10 km",
            "counts": bands,
            "purpose": "Proximity to a mapped substation. Not a statement that "
                       "it has capacity, or that a connection there is available.",
        },
        "earth_model": {
            "formula": "haversine",
            "radius_km": G.R_ATLAS,
            "implementation": "Ventusltd/grid-distance-maths src/geodesy.py",
            "verified": {"rows": checked, "worst_delta_km": worst,
                         "tolerance_km": tol},
        },
        "caveat": dict(G.STRAIGHT_LINE_CAVEAT),
        "substation": out,
    }

    body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n"
    path = OUT.replace("{GEN}", a.gen) if a.gen != "{GEN}" else OUT
    os.makedirs(os.path.dirname(path), exist_ok=True)
    io.open(path, "w", encoding="utf-8", newline="").write(body)
    digest = hashlib.sha256(body.encode("utf-8")).hexdigest()
    io.open(path + ".sha256", "w", encoding="utf-8", newline="").write(
        digest + "  " + os.path.basename(path) + "\n")
    print("\nwrote %s  (%s bytes)"
          % (os.path.basename(path), format(len(body.encode("utf-8")), ",")))
    for k in ("STRONG", "MODERATE", "DISTANT", "REMOTE"):
        print("  %-10s %5d" % (k.lower(), bands.get(k, 0)))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())