In this section
- Grid Proximity geodesy · pipelinenews / tools/intelligence/cartridges/grid-proximity/assets/{GEN}-grid-proximity.mjs lines 389–698
- Build Payload geodesy · pipelinenews / tools/intelligence/cartridges/grid-proximity/build_payload.py lines 1–390
Grid Proximity
A JavaScript module in PipelineNews that marks tabs, renders radius and sort, calculates great-circle distances and angles and reads inputs for gp centre, gp radius and gp target pick.
Set aside from the main view: 96% of its lines are the same as pipelinenews_intelligence/202609020611/assets/202608311610-grid-proximity.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Grid Proximity; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9603 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 pipelinenews_intelligence/202609020611/assets/202608311610-grid-proximity.mjs:1-702 00dafd47a1693591572cf0c05ec350151da8b181
- sha256 aee81376b86ecb580ad084ba9a402f1d5e863c4d4bce92f73be321dbb9e53f26
- target sha256 be8e57089d3075334085d91c77b68ac32b01171b24d8203d40a94d356bfd0cf5
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesypipelinenews / tools/intelligence/cartridges/grid-proximity/assets/{GEN}-grid-proximity.mjs · lines 389–698 of 698 (continued from section 1039) · Not reached from any entry point (candidate for review) · pattern mountGridProximity (shared by 3 files)
- What it does
- It draws substations, the REPD register, 66kV and cables. Defines 27 functions or classes, including atlasHaversineKm, boundingBox, esc, km, mw. 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: substations, the REPD register, 66kV, cables, 132kV.
- Inputs & outputs
- In: form fields (user input). Out: canvas drawing. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 132kV, 66kV.
- What it achieves
- It marks tabs (`markTabs`), renders radius (`renderRadius`) and renders sort (`renderSort`). Deployment: not-authorised. Its code works with 66 kV and 132 kV. It responds to click and keydown events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- pipelinenews · tools/intelligence/cartridges/grid-proximity/assets · JavaScript module
- Uses
- none found
- Used by
- none found
- Produces
- GRID_PROXIMITY_CARTRIDGE_CONTRACT, mountGridProximity
- Defines here
- lineFeature, renderMethod, injectScopeStyle, paintScope, toXY, bearingDeg, compass, acquire, step, renderTarget, go, table
- 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-proximity/assets/{GEN}-grid-proximity.mjs:389-698 · blob 6b75a075e8e52f68847e138ecf2b58caa0cb1654 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
function lineFeature(from, to, properties) {
return {
type: "Feature",
geometry: { type: "LineString", coordinates: [from, to] },
properties,
};
}
/* ---- METHOD ---------------------------------------------------------- */
function renderMethod(d) {
const e = d.earth_model;
const wrap = document.createElement("div");
wrap.innerHTML = `
<p class="section-title">HOW THESE DISTANCES ARE MEASURED</p>
<p class="meta"><strong>Formula.</strong> ${esc(e.formula)} on a sphere of
R = ${e.radius_km} km. ${esc(e.radius_source)}. The same constant is used by
${e.matches.map((m) => `<code>${esc(m)}</code>`).join(" and ")}, so a distance measured
here equals the same distance measured there.</p>
<p class="meta"><strong>To a circuit.</strong> ${esc(d.network.measure)}, across
${d.network.segments.toLocaleString()} segments of
${esc(d.network.voltages_kv.join("/"))} kV line. The site is projected onto the segment on a
local tangent plane built from the WGS84 radii of curvature at its own latitude
(${esc(e.segment_projection)}), so the foot of the perpendicular is correct rather than
snapped to the nearest drawn vertex.</p>
<p class="meta"><strong>To a substation.</strong> Straight line to the nearest of
${d.network.substations.toLocaleString()} mapped substation points.</p>
<p class="meta"><strong>Straight line.</strong> ${esc(d.caveat.straight_line)}</p>
<p class="meta"><strong>Substations.</strong> ${esc(d.caveat.substation)}</p>
<p class="meta"><strong>Coverage.</strong> ${esc(d.caveat.coverage)}</p>
<p class="meta"><strong>Precision.</strong> ${esc(d.caveat.precision)}</p>
<p class="meta"><strong>What changed.</strong> The earlier
<code>circuit_km</code> measured to the nearest point of a decimated sample of
400/275/132 kV vertices on a ${e.differs_from.project_intelligence_circuit_km} km sphere,
which reads ${e.differs_from.reads_short_by_pct}% short and could only overstate the
distance to the conductor. This figure measures to the line itself, includes 220 and
66 kV, and uses the Atlas radius.</p>
<p class="meta"><strong>Provenance.</strong> ${esc(d.provenance.spine)}. ${esc(d.provenance.network)}.</p>`;
body.appendChild(wrap);
}
/* ---- TARGET ----------------------------------------------------------
A targeting scope. The point is that the maths is legible as a picture:
range rings you can count, a bearing you can see, and every voltage in
reach drawn in the colour the estate has always used for it.
Voltage colours are the ones already established in the REPD atlas grid
model, so a 66 kV line is the same purple here as it is on the map. */
const KV_COLOUR = { 400: "#0054ff", 275: "#ff0000", 220: "#ff9900", 132: "#00cc00", 66: "#b200ff" };
const SCOPE_STYLE_ID = "gp-scope-style";
function injectScopeStyle() {
if (document.getElementById(SCOPE_STYLE_ID)) return;
const s = document.createElement("style");
s.id = SCOPE_STYLE_ID;
/* Every selector is scoped under the cartridge host, so nothing outside
it is restyled and the additive-only boundary holds. */
s.textContent = `
#gridProximityHost .gp-scope-wrap { display:grid; grid-template-columns:minmax(280px,1fr) minmax(220px,320px);
gap:18px; align-items:start; margin-top:10px; }
@media (max-width:720px){ #gridProximityHost .gp-scope-wrap { grid-template-columns:1fr; } }
#gridProximityHost .gp-scope { position:relative; background:#04070a; border:1px solid #1d2c22;
border-radius:2px; overflow:hidden; }
#gridProximityHost .gp-scope canvas { display:block; width:100%; height:auto; }
#gridProximityHost .gp-readout { font-family:ui-monospace,Menlo,Consolas,monospace; font-size:12px;
line-height:1.5; color:#8fe3b0; background:#04070a; border:1px solid #1d2c22; padding:12px 14px; }
#gridProximityHost .gp-readout h4 { margin:0 0 8px; font-size:11px; letter-spacing:.18em;
color:#39ff88; font-weight:600; text-transform:uppercase; }
#gridProximityHost .gp-readout dl { display:grid; grid-template-columns:auto 1fr; gap:3px 12px; margin:0; }
#gridProximityHost .gp-readout dt { color:#4d7a5f; letter-spacing:.06em; }
#gridProximityHost .gp-readout dd { margin:0; color:#d6ffe6; font-variant-numeric:tabular-nums; text-align:right; }
#gridProximityHost .gp-kv { display:flex; flex-wrap:wrap; gap:5px; margin-top:10px; }
#gridProximityHost .gp-kv span { font-family:ui-monospace,monospace; font-size:10.5px; padding:2px 6px;
border:1px solid currentColor; border-radius:2px; }
#gridProximityHost .gp-lock { font-family:ui-monospace,monospace; font-size:10.5px; padding:3px 8px;
border:1px solid #39ff88; background:transparent; color:#39ff88; cursor:pointer; border-radius:2px; }
#gridProximityHost .gp-lock:hover { background:#0d2a19; }
#gridProximityHost .gp-lock:focus-visible { outline:2px solid #39ff88; outline-offset:2px; }
@media (prefers-reduced-motion:reduce){ #gridProximityHost .gp-scope canvas { opacity:1; } }`;
document.head.appendChild(s);
}
let scopeFrame = null;
/** Draw one frame of the scope. `t` runs 0 to 1 during acquisition. */
function paintScope(canvas, row, t) {
// No 2D context means no picture, but the readout beside it still has to
// work. A missing canvas must degrade, never take the panel down.
const ctx = canvas && canvas.getContext && canvas.getContext("2d");
if (!ctx) return;
const W = canvas.width; const H = canvas.height;
const cx = W / 2; const cy = H / 2;
const pad = 26;
const R = Math.min(W, H) / 2 - pad;
// Range the scope covers: the furthest thing worth showing, rounded up.
const far = Math.max(
row.substation ? row.substation.km : 0,
...(row.substations_nearby || []).map((s) => s.km),
row.circuit ? row.circuit.km : 0,
);
const nice = [0.5, 1, 2, 5, 10, 20, 50, 100, 200];
const span = nice.find((n) => n >= far * 1.15) || Math.ceil(far * 1.15);
const toXY = (lon, lat) => {
const { kx, ky } = { kx: Math.cos(row.at[1] * Math.PI / 180) * 111.32, ky: 110.574 };
const dx = (lon - row.at[0]) * kx;
const dy = (lat - row.at[1]) * ky;
return [cx + (dx / span) * R, cy - (dy / span) * R];
};
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = "#04070a";
ctx.fillRect(0, 0, W, H);
// range rings
ctx.strokeStyle = "#12331f";
ctx.fillStyle = "#2f6a45";
ctx.font = "10px ui-monospace,monospace";
ctx.lineWidth = 1;
for (let i = 1; i <= 4; i += 1) {
const rr = (R * i) / 4;
ctx.beginPath(); ctx.arc(cx, cy, rr, 0, Math.PI * 2); ctx.stroke();
const label = (span * i) / 4;
ctx.fillText(`${label < 1 ? `${Math.round(label * 1000)}m` : `${label}km`}`, cx + 3, cy - rr - 3);
}
ctx.beginPath();
ctx.moveTo(cx - R, cy); ctx.lineTo(cx + R, cy);
ctx.moveTo(cx, cy - R); ctx.lineTo(cx, cy + R);
ctx.stroke();
ctx.fillStyle = "#2f6a45";
ctx.fillText("N", cx - 4, cy - R - 8);
// sweep, once, during acquisition
if (t < 1) {
const a = -Math.PI / 2 + t * Math.PI * 2;
const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, R);
g.addColorStop(0, "rgba(57,255,136,0.22)");
g.addColorStop(1, "rgba(57,255,136,0)");
ctx.fillStyle = g;
ctx.beginPath(); ctx.moveTo(cx, cy);
ctx.arc(cx, cy, R, a - 0.5, a); ctx.closePath(); ctx.fill();
}
// one vector per voltage in reach, in the estate's own colours
const entries = Object.entries(row.circuit_by_kv || {})
.map(([kv, v]) => ({ kv: Number(kv), ...v }))
.filter((v) => v.km <= span)
.sort((a, b) => b.kv - a.kv);
for (const v of entries) {
const [x, y] = toXY(v.foot[0], v.foot[1]);
ctx.strokeStyle = KV_COLOUR[v.kv] || "#666";
ctx.globalAlpha = 0.35 + 0.65 * Math.min(1, t * 1.6);
ctx.lineWidth = v.kv >= 275 ? 2 : 1.4;
ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(x, y); ctx.stroke();
ctx.fillStyle = KV_COLOUR[v.kv] || "#666";
ctx.beginPath(); ctx.arc(x, y, 3, 0, Math.PI * 2); ctx.fill();
ctx.globalAlpha = 1;
}
// substation blips
const subs = [row.substation, ...(row.substations_nearby || [])].filter(Boolean);
subs.forEach((s, i) => {
if (s.km > span) return;
const [x, y] = toXY(s.at[0], s.at[1]);
const primary = i === 0;
ctx.globalAlpha = Math.min(1, t * 2);
ctx.strokeStyle = primary ? "#39ff88" : "#2f6a45";
ctx.fillStyle = primary ? "#39ff88" : "#1c4630";
ctx.beginPath(); ctx.arc(x, y, primary ? 5 : 3.5, 0, Math.PI * 2);
ctx.fill(); ctx.stroke();
ctx.globalAlpha = 1;
});
// lock-on bracket around the nearest substation, closing as t -> 1
if (row.substation && row.substation.km <= span) {
const [x, y] = toXY(row.substation.at[0], row.substation.at[1]);
const grow = 26 - 14 * Math.min(1, t);
ctx.strokeStyle = t >= 1 ? "#39ff88" : "#8fe3b0";
ctx.lineWidth = 1.5;
const arm = 7;
[[-1, -1], [1, -1], [-1, 1], [1, 1]].forEach(([sx, sy]) => {
const px = x + sx * grow; const py = y + sy * grow;
ctx.beginPath();
ctx.moveTo(px, py - sy * arm); ctx.lineTo(px, py); ctx.lineTo(px - sx * arm, py);
ctx.stroke();
});
if (t >= 1) {
ctx.fillStyle = "#39ff88";
ctx.font = "bold 10px ui-monospace,monospace";
ctx.fillText("LOCK", x + grow + 4, y - grow - 2);
}
}
// the site itself
ctx.strokeStyle = "#d6ffe6"; ctx.lineWidth = 1;
ctx.beginPath(); ctx.arc(cx, cy, 4, 0, Math.PI * 2); ctx.stroke();
ctx.beginPath();
ctx.moveTo(cx - 9, cy); ctx.lineTo(cx - 5, cy);
ctx.moveTo(cx + 5, cy); ctx.lineTo(cx + 9, cy);
ctx.moveTo(cx, cy - 9); ctx.lineTo(cx, cy - 5);
ctx.moveTo(cx, cy + 5); ctx.lineTo(cx, cy + 9);
ctx.stroke();
}
function bearingDeg(lon1, lat1, lon2, lat2) {
const D = Math.PI / 180;
const p1 = lat1 * D; const p2 = lat2 * D; const dl = (lon2 - lon1) * D;
const y = Math.sin(dl) * Math.cos(p2);
const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
return (Math.atan2(y, x) / D + 360) % 360;
}
const compass = (deg) => ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"][Math.round(deg / 22.5) % 16];
function acquire(row, canvas, readout) {
// Animate where the host can; otherwise draw the settled state at once.
const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : null;
const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : () => {};
if (scopeFrame) caf(scopeFrame);
const reduced = !raf
|| (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches);
const DURATION = reduced ? 0 : 900;
const start = performance.now();
const sub = row.substation;
const brg = sub ? bearingDeg(row.at[0], row.at[1], sub.at[0], sub.at[1]) : 0;
const step = (now) => {
const t = DURATION === 0 ? 1 : Math.min(1, (now - start) / DURATION);
const eased = 1 - (1 - t) ** 3;
paintScope(canvas, row, eased);
if (readout) {
readout.innerHTML = `
<h4>${t >= 1 ? "Target acquired" : "Acquiring…"}</h4>
<dl>
<dt>SITE</dt><dd>${esc((row.name || "").slice(0, 26))}</dd>
<dt>CAPACITY</dt><dd>${mw(row.mw)} MW</dd>
<dt>SUBSTATION</dt><dd>${esc((sub && (sub.name || "unnamed")) || "none").slice(0, 22)}</dd>
<dt>RANGE</dt><dd>${sub ? km(sub.km * eased) : "n/a"}</dd>
<dt>BEARING</dt><dd>${sub ? `${(brg * eased).toFixed(0).padStart(3, "0")}° ${compass(brg)}` : "n/a"}</dd>
<dt>SUB kV</dt><dd>${sub && sub.kv.length ? sub.kv.join(" / ") : "unknown"}</dd>
<dt>CIRCUIT</dt><dd>${row.circuit ? `${km(row.circuit.km * eased)} · ${row.circuit.kv} kV` : "n/a"}</dd>
<dt>TRANSMISSION</dt><dd>${row.circuit_transmission ? `${km(row.circuit_transmission.km * eased)} · ${row.circuit_transmission.kv} kV` : "n/a"}</dd>
<dt>DISTRIBUTION</dt><dd>${row.circuit_distribution ? `${km(row.circuit_distribution.km * eased)} · ${row.circuit_distribution.kv} kV` : "n/a"}</dd>
<dt>GRID</dt><dd>${esc((row.grid_probable && row.grid_probable.band || "").toLowerCase())}</dd>
</dl>
<div class="gp-kv">${Object.entries(row.circuit_by_kv || {})
.map(([kv, v]) => ({ kv: Number(kv), km: v.km }))
.sort((a, b) => b.kv - a.kv)
.map((v) => `<span style="color:${KV_COLOUR[v.kv]}">${v.kv} kV · ${km(v.km)}</span>`).join("")}</div>
<p class="meta" style="margin:10px 0 0;font-size:11px;color:#4d7a5f">Straight line to mapped geometry.
A screen, not a route. Detailed design belongs in ETAP or DIgSILENT with a chartered engineer.</p>`;
}
if (t < 1 && raf) scopeFrame = raf(step);
};
if (raf && DURATION > 0) scopeFrame = raf(step);
else step(performance.now());
}
function renderTarget(d, preselect) {
injectScopeStyle();
const wrap = document.createElement("div");
wrap.innerHTML = `
<p class="section-title">DRAW STRAIGHT TO NEAREST SUBSTATION <span class="meta">· beta</span></p>
<p class="meta" style="font-size:11px;color:#4d7a5f">Working model under trial. Screening geometry
only; nothing here is a connection design.</p>
<p class="meta">Pick a project and the scope plots what is actually within reach: every
substation nearby, and the nearest circuit at each voltage in the colour the atlas has
always used for it. Range rings are geodesic.</p>
<div class="filters">
<input id="gpTargetPick" type="text" placeholder="Project name or REPD ref" style="min-width:18rem">
<button class="btn" id="gpTargetGo" type="button">ACQUIRE</button>
</div>
<div class="gp-scope-wrap">
<div class="gp-scope"><canvas id="gpScope" width="620" height="620"></canvas></div>
<div class="gp-readout" id="gpReadout"><h4>Standing by</h4>
<p style="margin:0;color:#4d7a5f">Name a project, or press LOCK beside one in CONNECT.</p></div>
</div>`;
body.appendChild(wrap);
const canvas = wrap.querySelector("#gpScope");
const readout = wrap.querySelector("#gpReadout");
const go = () => {
const raw = wrap.querySelector("#gpTargetPick").value.trim();
const needle = raw.toLowerCase();
const hit = d.rows.find((r) => r.ref === raw)
|| d.rows.find((r) => (r.name || "").toLowerCase().includes(needle));
if (!hit) { readout.innerHTML = `<h4>No target</h4><p style="margin:0;color:#4d7a5f">No project matches that.</p>`; return; }
acquire(hit, canvas, readout);
};
wrap.querySelector("#gpTargetGo").addEventListener("click", go);
wrap.querySelector("#gpTargetPick").addEventListener("keydown", (e) => { if (e.key === "Enter") go(); });
if (preselect) {
wrap.querySelector("#gpTargetPick").value = preselect.name;
acquire(preselect, canvas, readout);
}
}
/* ---- shared table ---------------------------------------------------- */
function table(rows, columns, sortKey, sortDir) {
const head = columns.map(([k, label]) => {
const mark = k === sortKey ? (sortDir === 1 ? " ▲" : " ▼") : "";
return `<th data-k="${esc(k)}" scope="col">${esc(label)}${mark}</th>`;
}).join("");
const cells = rows.map((r) => `<tr>${columns.map(([, , render]) => `<td>${render(r)}</td>`).join("")}</tr>`).join("");
return `<div style="overflow-x:auto"><table><thead><tr>${head}</tr></thead><tbody>${cells}</tbody></table></div>`;
}
markTabs();
note.textContent = "beta · working model · pick a tab";
return { payloadRequests, projectBindings: 0 };
}Build Payload
A Python command-line tool in the grid proximity folder of PipelineNews that reads grid 400kV, grid 275kV, grid 220kV and grid 132kV, using haversine and SHA-256.
geodesypipelinenews / tools/intelligence/cartridges/grid-proximity/build_payload.py · lines 1–390 of 533 · Entry point · pattern build_index (shared by 3 files)
- What it does
- It loads grid 400kV, grid 275kV, grid 220kV and grid 132kV. Defines 13 functions or classes, including curvature, haversine_km, cell_of, load_segments, load_substations. Uses libraries argparse, hashlib, json, math, os. 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: 400kV, 220kV, 132kV, 66kV, 33kV, 11kV.
- Inputs & outputs
- In: GeoJSON file grid_400kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_220kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file grid_33kv_East_of_England.geojson; GeoJSON file grid_33kv_London_Area.geojson; GeoJSON file grid_33kv_North_East_England.geojson. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 400kV, 220kV, 132kV, 66kV, 33kV, 11kV.
- Downstream impact
- Used directly by 2 files: Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
- What it achieves
- It loads segments (`load_segments`), loads substations (`load_substations`) and loads UKPN 11kv (`load_ukpn_11kv`). Grid proximity payload builder. Its code works with 11 kV, 33 kV and 132 kV. It accepts `--gg2050`, `--spine` and `--out`.
- Why it matters
- Loaded by the Genome page in Ventus Grid Engine at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by Build Graph, from Ventus Grid Engine.
- Application
- pipelinenews · tools/intelligence/cartridges/grid-proximity · Python CLI
- Uses
- argparse, hashlib, json, math, os, time
- Used by
- named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
- Produces
- curvature, haversine_km, cell_of, load_segments, load_substations, load_ukpn_11kv, build_index, swept_radius_km, nearest_segment, nearest_substations, grid_probable, main
- Defines here
- curvature, haversine_km, cell_of, load_segments, load_substations, load_ukpn_11kv, build_index, swept_radius_km, nearest_segment, nearest_substations, grid_probable, 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/grid-proximity/build_payload.py:1-390 · blob 674b71fb2cb346ad37891cbadcff12f0ba5eccec · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Grid proximity payload builder.
Recomputes network proximity for the REPD spine using the ORIGINAL line
geometry rather than a decimated point sample, and emits the payload the
grid-proximity cartridge serves.
Three corrections against the project-intelligence cartridge's circuit_km:
1. Point-to-SEGMENT, not point-to-vertex. The published figure measured to
the nearest sampled vertex, so it could only ever equal or overstate the
true distance to the conductor. This projects the site onto the segment.
2. All five mapped voltages. The published figure used 400/275/132 only.
220 kV and 66 kV are in the pinned layer set and are now included; 171
projects (5.6%) are nearest to a 220 or 66 kV circuit, and 71 of those
were pushed outside the 2 km band by the omission.
3. Full geometry, not a decimated sample. circuits-sampled.tsv carried
47,897 points; the source lines carry 163,905 vertices over 149,340
segments.
Earth model: haversine on R = 6378.137 km, matching ventus-corev8engine.js
(GridAtlas) and atlasHaversineKm (GIS SLD sandbox), so a distance measured in
Pipeline News equals the same distance measured in the Atlas or the Sandbox.
The project-intelligence cartridge used 6371.0088, which reads 0.112% short.
Local point-to-segment work is done on a tangent plane built from the WGS84
meridional and prime-vertical radii of curvature at the site's own latitude,
then reconciled to the haversine sphere, so the segment projection does not
inherit the sphere's anisotropy at UK latitudes.
Usage:
python build_payload.py --gg2050 <path to globalgrid2050> \
--spine <path to master.tsv> --out <file.json>
"""
import argparse
import hashlib
import json
import math
import os
import time
A_WGS84 = 6378.137
F_WGS84 = 1.0 / 298.257223563
E2 = F_WGS84 * (2.0 - F_WGS84)
R_ATLAS = 6378.137 # the constant GridAtlas and the Sandbox both use
DEG = math.pi / 180.0
VOLTAGE_LAYERS = [
("grid_400kv.geojson", 400),
("grid_275kv.geojson", 275),
("grid_220kv.geojson", 220),
("grid_132kv.geojson", 132),
("grid_66kv.geojson", 66),
# 33 kV arrives as eleven regional files. It is distribution, not
# transmission, and it is where most sub-50 MW solar actually connects, so
# measuring a 30 MW scheme only against 66-400 kV overstates how far it is
# from a usable connection.
("grid_33kv_East_of_England.geojson", 33),
("grid_33kv_London_Area.geojson", 33),
("grid_33kv_North_East_England.geojson", 33),
("grid_33kv_North_West_England.geojson", 33),
("grid_33kv_Scotland_North.geojson", 33),
("grid_33kv_Scotland_South.geojson", 33),
("grid_33kv_South_East_England.geojson", 33),
("grid_33kv_South_West_England.geojson", 33),
("grid_33kv_Wales_North.geojson", 33),
("grid_33kv_Wales_South.geojson", 33),
("grid_33kv_Yorkshire.geojson", 33),
]
SUBSTATIONS = "grid_substations.geojson"
# The UKPN 11 kV layer is POINTS, every one tagged "UKPN (est)" and "11kV (est)"
# at source. It is an estimate over one licence area, so it is carried in its
# own field, labelled estimated, and never merged into the confirmed set.
UKPN_11KV = "grid_11kv_ukpn.geojson"
EST_11KV_MAX_KM = 15.0 # beyond this the point is outside the licence area
VOLTAGES = [400, 275, 220, 132, 66, 33]
TRANSMISSION = [400, 275, 220, 132, 66]
CELL = 0.1 # index cell, degrees
def curvature(lat_deg):
"""Meridional and prime-vertical radii of curvature at this latitude."""
s = math.sin(lat_deg * DEG)
t = 1.0 - E2 * s * s
return A_WGS84 * (1.0 - E2) / t ** 1.5, A_WGS84 / math.sqrt(t)
def haversine_km(lon1, lat1, lon2, lat2, radius=R_ATLAS):
"""Identical in form and constant to ventus-corev8engine.js haversine()."""
d_lat = (lat2 - lat1) * DEG
d_lon = (lon2 - lon1) * DEG
x = (math.sin(d_lat / 2.0) ** 2
+ math.cos(lat1 * DEG) * math.cos(lat2 * DEG) * math.sin(d_lon / 2.0) ** 2)
return radius * 2.0 * math.atan2(math.sqrt(x), math.sqrt(1.0 - x))
def cell_of(lat, lon):
return int(math.floor(lat / CELL)), int(math.floor(lon / CELL))
def load_segments(root):
"""Every segment of every mapped circuit, tagged with its voltage."""
segments = []
for filename, kv in VOLTAGE_LAYERS:
path = os.path.join(root, filename)
if not os.path.exists(path):
raise SystemExit("missing voltage layer: %s" % path)
with open(path, encoding="utf-8") as handle:
layer = json.load(handle)
for feature in layer.get("features", []):
geometry = feature.get("geometry") or {}
if geometry.get("type") != "LineString":
continue
props = feature.get("properties") or {}
name = props.get("name") or props.get("ref") or ""
operator = props.get("operator") or props.get("brand") or ""
coords = geometry.get("coordinates") or []
for i in range(len(coords) - 1):
segments.append((coords[i][0], coords[i][1],
coords[i + 1][0], coords[i + 1][1],
kv, name, operator))
return segments
def load_substations(root):
path = os.path.join(root, SUBSTATIONS)
with open(path, encoding="utf-8") as handle:
layer = json.load(handle)
out = []
for feature in layer.get("features", []):
geometry = feature.get("geometry") or {}
if geometry.get("type") != "Point":
continue
props = feature.get("properties") or {}
lon, lat = geometry["coordinates"][0], geometry["coordinates"][1]
volts = []
for part in str(props.get("voltage") or "").split(";"):
part = part.strip()
if part.isdigit():
volts.append(int(part) // 1000)
out.append((lon, lat, props.get("name") or "",
props.get("operator") or props.get("owner") or "",
sorted(set(volts), reverse=True),
props.get("substation") or ""))
return out
def load_ukpn_11kv(root):
"""Estimated 11 kV substation points. Source tags them "(est)"; so do we."""
path = os.path.join(root, UKPN_11KV)
if not os.path.exists(path):
return []
with open(path, encoding="utf-8") as handle:
layer = json.load(handle)
out = []
for feature in layer.get("features", []):
geometry = feature.get("geometry") or {}
if geometry.get("type") != "Point":
continue
props = feature.get("properties") or {}
out.append((geometry["coordinates"][0], geometry["coordinates"][1],
props.get("name") or "", props.get("operator") or "",
[11], props.get("type") or ""))
return out
def build_index(items, lon_at, lat_at, extra=None):
"""Index by every cell an item's bounding box touches, not just its ends.
Registering a segment only by its two endpoints hides it from any cell it
merely passes through. With 0.1 degree cells (~11 km) that is rare but real:
it left one project reporting a 400 kV circuit at 3.792 km when a 132 kV
circuit crossed at 3.789 km.
"""
index = {}
for i, item in enumerate(items):
a_lat, a_lon = lat_at(item), lon_at(item)
b_lat, b_lon = extra(item)[::-1] if extra else (a_lat, a_lon)
i0, i1 = sorted((int(math.floor(a_lat / CELL)), int(math.floor(b_lat / CELL))))
j0, j1 = sorted((int(math.floor(a_lon / CELL)), int(math.floor(b_lon / CELL))))
for ci in range(i0, i1 + 1):
for cj in range(j0, j1 + 1):
index.setdefault((ci, cj), []).append(i)
return index
def swept_radius_km(lon0, lat0, ring, kx, ky):
"""Radius around (lon0, lat0) that a Chebyshev ring sweep has provably covered.
Sweeping cells within Chebyshev distance `ring` covers an axis-aligned box of
cells, NOT a disc centred on the query point. The query point sits somewhere
inside its own cell, so the guaranteed radius is the distance to the nearest
edge of that box - which can be almost a whole cell less than ring * CELL.
Assuming otherwise is what left eight projects reporting a circuit that was
not the nearest, worst by 10.5 km at Shetland, and fourteen with substations
a few metres out of order.
"""
ci = math.floor(lat0 / CELL)
cj = math.floor(lon0 / CELL)
lat_lo = (ci - ring) * CELL
lat_hi = (ci + ring + 1) * CELL
lon_lo = (cj - ring) * CELL
lon_hi = (cj + ring + 1) * CELL
return min((lat0 - lat_lo) * ky, (lat_hi - lat0) * ky,
(lon0 - lon_lo) * kx, (lon_hi - lon0) * kx)
def nearest_segment(lon0, lat0, segments, index, only_kv=None):
"""Exact perpendicular distance to the nearest circuit, and where it lands.
The projection is done on a local tangent plane so the foot of the
perpendicular is correct; the returned distance is then measured with the
same haversine the Atlas uses, so the number is directly comparable.
"""
meridional, prime_vertical = curvature(lat0)
kx = prime_vertical * math.cos(lat0 * DEG) * DEG
ky = meridional * DEG
ci, cj = cell_of(lat0, lon0)
best = (float("inf"), None, None)
for ring in range(0, 90):
candidates = []
for i in range(ci - ring, ci + ring + 1):
for j in range(cj - ring, cj + ring + 1):
if ring and abs(i - ci) != ring and abs(j - cj) != ring:
continue
candidates.extend(index.get((i, j), ()))
for idx in candidates:
if only_kv is not None and segments[idx][4] != only_kv:
continue
x1, y1, x2, y2 = segments[idx][:4]
ax, ay = (x1 - lon0) * kx, (y1 - lat0) * ky
bx, by = (x2 - lon0) * kx, (y2 - lat0) * ky
dx, dy = bx - ax, by - ay
length2 = dx * dx + dy * dy
if length2 == 0.0:
px, py, t = ax, ay, 0.0
else:
t = -(ax * dx + ay * dy) / length2
t = 0.0 if t < 0.0 else (1.0 if t > 1.0 else t)
px, py = ax + t * dx, ay + t * dy
d2 = px * px + py * py
if d2 < best[0]:
best = (d2, idx, t)
# Safe to stop only once the best hit is inside the area provably swept.
if best[1] is not None and math.sqrt(best[0]) <= swept_radius_km(lon0, lat0, ring, kx, ky):
break
if best[1] is None:
return None
x1, y1, x2, y2, kv, name, operator = segments[best[1]]
t = best[2]
foot_lon = x1 + (x2 - x1) * t
foot_lat = y1 + (y2 - y1) * t
return {
"km": round(haversine_km(lon0, lat0, foot_lon, foot_lat), 3),
"kv": kv,
"line": name,
"operator": operator,
"foot": [round(foot_lon, 6), round(foot_lat, 6)],
}
def nearest_substations(lon0, lat0, subs, index, want=5):
meridional, prime_vertical = curvature(lat0)
kx = prime_vertical * math.cos(lat0 * DEG) * DEG
ky = meridional * DEG
ci, cj = cell_of(lat0, lon0)
found = {}
for ring in range(0, 90):
for i in range(ci - ring, ci + ring + 1):
for j in range(cj - ring, cj + ring + 1):
if ring and abs(i - ci) != ring and abs(j - cj) != ring:
continue
for idx in index.get((i, j), ()):
if idx in found:
continue
lon, lat = subs[idx][0], subs[idx][1]
dx, dy = (lon - lon0) * kx, (lat - lat0) * ky
found[idx] = math.sqrt(dx * dx + dy * dy)
# Keep sweeping until `want` candidates are all provably inside the
# area already covered, not merely until `want` have been seen.
if len(found) >= want:
kth = sorted(found.values())[want - 1]
if kth <= swept_radius_km(lon0, lat0, ring, kx, ky):
break
if not found:
return []
# Rank on the metric that is REPORTED, not the one used to search. The plane
# metric and the haversine differ by ~0.1%, which was enough to emit pairs a
# few metres out of order when the search ranked on one and printed the other.
ranked = sorted(found, key=lambda i: haversine_km(lon0, lat0, subs[i][0], subs[i][1]))[:want]
out = []
for idx in ranked:
lon, lat, name, operator, volts, kind = subs[idx]
out.append({
"km": round(haversine_km(lon0, lat0, lon, lat), 3),
"name": name,
"operator": operator,
"kv": volts,
"kind": kind,
"at": [round(lon, 6), round(lat, 6)],
})
return out
# --- grid probable ----------------------------------------------------------
# A screening band, from measured geometry only. It says how close the mapped
# network is, not whether a connection is obtainable.
#
# Deliberately NOT in this model, because the sources have not been cited yet:
# - capacity-to-voltage suitability (needs ENA / DNO published practice)
# - connection queue position, curtailment, or headroom
# - 33 kV and 11 kV distribution, which is where most sub-50 MW schemes land
# - DNO licence area, ownership, or IDNO presence
# Adding a capacity rule from memory would be a guess. It waits for sources.
GRID_PROBABLE_BANDS = [
("STRONG", 2.0, 1.0),
("MODERATE", 5.0, 3.0),
("DISTANT", 15.0, 10.0),
]
def grid_probable(circuit, substation):
"""Band a site by how close the mapped network is. Inputs are shown, always."""
if not circuit or not substation:
return {"band": "UNKNOWN", "why": "no mapped circuit or substation in range"}
c = circuit["km"]
s = substation["km"]
for band, circuit_max, sub_max in GRID_PROBABLE_BANDS:
if c <= circuit_max and s <= sub_max:
break
else:
band = "REMOTE"
return {
"band": band,
"circuit_km": c,
"circuit_kv": circuit["kv"],
"substation_km": s,
"why": ("nearest circuit %.2f km at %d kV, nearest substation %.2f km"
% (c, circuit["kv"], s)),
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--gg2050", required=True, help="globalgrid2050 checkout")
parser.add_argument("--spine", required=True, help="master.tsv")
parser.add_argument("--out", required=True)
parser.add_argument("--generation", required=True)
args = parser.parse_args()
started = time.time()
segments = load_segments(args.gg2050)
subs = load_substations(args.gg2050)
ukpn = load_ukpn_11kv(args.gg2050)
ukpn_index = build_index(ukpn, lambda s: s[0], lambda s: s[1]) if ukpn else {}
seg_index = build_index(segments, lambda s: s[0], lambda s: s[1],
extra=lambda s: (s[2], s[3])) # (lon, lat) of the far end
sub_index = build_index(subs, lambda s: s[0], lambda s: s[1])
print("segments %d | substations %d | cells %d/%d"
% (len(segments), len(subs), len(seg_index), len(sub_index)))
rows = []
with open(args.spine, encoding="utf-8") as handle:
for line in handle:
if not line.strip():
continue
rows.append(line.rstrip("\n").split("\t"))
out_rows = []
for row in rows:
try:
lon, lat = float(row[10]), float(row[11])
except (ValueError, IndexError):
continue
# One search per voltage, and the overall nearest is the best of those.
# Running a separate unfiltered search alongside them let the two
# disagree: a sparser filtered sweep reaches further and can find a
# circuit the unfiltered sweep stopped short of. Deriving the overall
# answer from the per-voltage set makes disagreement impossible.
by_voltage = {}
per_voltage_full = {}
for kv in VOLTAGES:
hit = nearest_segment(lon, lat, segments, seg_index, only_kv=kv)
if hit:
by_voltage[str(kv)] = {"km": hit["km"], "foot": hit["foot"]}