In this section
- Hazards geodesy · galaxies-wafers / iterations/27-earth-radii-and-argument-order/hazards.mjs lines 383–483
- Iterations — 27 Earth Radii and Argument Order Page render · galaxies-wafers / iterations/27-earth-radii-and-argument-order/index.html lines 1–87
- Iterations — 28 Nearest Search Trap Page render · galaxies-wafers / iterations/28-nearest-search-trap/index.html lines 1–71
- Trap render · galaxies-wafers / iterations/28-nearest-search-trap/trap.css lines 1–51
- Trap render · galaxies-wafers / iterations/28-nearest-search-trap/trap.mjs lines 1–390
Hazards
A JavaScript module in Galaxies Wafers that paints mods and controls, wraps lon, calculates great-circle distances and draws on a canvas. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/27-earth-radii-and-argument-order/.
geodesygalaxies-wafers / iterations/27-earth-radii-and-argument-order/hazards.mjs · lines 383–483 of 483 (continued from section 1198) · Entry point · pattern paintResults (shared by 2 files)
- What it does
- It draws cables. Defines 38 functions or classes, including $, el, nf, fmtLen, fmtLat. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain terms in the code: cables.
- Inputs & outputs
- Out: canvas drawing.
- Downstream impact
- Used directly by 1 file: Iterations — 27 Earth Radii and Argument Order Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/27-earth-radii-and-argument-order/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/27-earth-radii-and-argument-order/.
- What it achieves
- It paints mods (`paintMods`), paints controls (`paintControls`) and maps projection (`mapProjection`). Two Hazards on One Map — Earth radii and argument order, charted from the engine's own geodesy. It responds to click, input and resize events.
- Why it matters
- Loaded by the 27 Earth Radii and Argument Order page at https://ventusltd.github.io/galaxies-wafers/iterations/27-earth-radii-and-argument-order/.
- Application
- galaxies-wafers · iterations/27-earth-radii-and-argument-order · JavaScript module
- Uses
- none found
- Used by
- loaded by Iterations — 27 Earth Radii and Argument Order Page (script src)
- Produces
- $, el, nf, fmtLen, fmtLat, fmtLon, fmtPt, paintMods, dFromT, seg, paintControls, fit
- Defines here
- corridorText, paintQuestions, update
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/27-earth-radii-and-argument-order/hazards.mjs:383-483 · blob cf91f31e5bfd0eda3b8141da655f2497dbcda735 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
if (!m.ok) {
$('leg').textContent = '';
fill(row(rl, 'r-empty'), 'EMPTY', '', '', emptyReason(), true);
fill(row(ol, 'o-empty'), 'EMPTY', '', '', emptyReason(), true);
return;
}
for (const id of ['r-empty', 'o-empty']) if (rowCache.has(id)) { rowCache.get(id).li.remove(); rowCache.delete(id); }
const rr = m.radii;
setT($('leg'), `From A ${fmtPt(rr.A)}, bearing ${nf(rr.bearing, 5)}° ${rr.same ? '(A and B coincide, so due north)' : 'toward B'}, to E ${fmtPt({ lat: +rr.end.lat.toFixed(6), lon: +rr.end.lon.toFixed(6) })}: destinationPoint(A, leg, bearing) in v9-geodesy.js, which stands on EARTH_RADIUS_KM.`);
for (const r of rr.rows) {
fill(row(rl, 'r-' + r.key, COL[r.key]), r.label, fmtLen(r.km, 10), `${r.fn} · radius ${nf(r.R, 8)} km`,
r.diffKm === 0 ? 'difference from R_ATLAS: 0 (the same radius value returns the same number)'
: `difference from R_ATLAS: ${r.diffKm > 0 ? '+' : ''}${fmtLen(r.diffKm, 4)} · ${r.ppm > 0 ? '+' : '−'}${nf(Math.abs(r.ppm), 5)} ppm`);
}
const o = m.order;
setT($('orderdoc'), `geo-core.js documents haversine(lon1, lat1, lon2, lat2) as taking “(lon, lat) pairs — GeoJSON order, not the (lat, lon) order most haversine implementations take”; v9-geodesy.js exports distanceKm(lon1, lat1, lon2, lat2). Both are called below with A ${fmtPt(S.A)} and B ${fmtPt(S.B)}, first as documented, then with each pair swapped.`);
fill(row(ol, 'o-c', COL.correct), 'documented order · geo-core.js', fmtLen(o.correct, 8),
`haversine(${S.A.lon}, ${S.A.lat}, ${S.B.lon}, ${S.B.lat})`, `v9-geodesy.js distanceKm in the same order: ${fmtLen(o.correct9, 8)}`);
fill(row(ol, 'o-s', COL.swapped), 'swapped order · geo-core.js', fmtLen(o.swapped, 8),
`haversine(${S.A.lat}, ${S.A.lon}, ${S.B.lat}, ${S.B.lon})`,
`v9-geodesy.js distanceKm in the same order: ${fmtLen(o.swapped9, 8)}. ` + (o.swapDrawable
? `The swapped call measures from A′ ${fmtPt(o.Aswap)} to B′ ${fmtPt(o.Bswap)}: the dashed arc.`
: 'Arc EMPTY: a longitude beyond ±90° read as a latitude is not a point on the globe, so no arc is drawn. The function returned the value above without refusing.'),
!Number.isFinite(o.swapped));
const ratioEmpty = o.ratio == null;
fill(row(ol, 'o-r', '#ffffff'), 'ratio · swapped ÷ documented',
ratioEmpty ? 'EMPTY' : '× ' + nf(o.ratio, 6),
ratioEmpty ? '' : `difference ${o.swapped - o.correct > 0 ? '+' : ''}${fmtLen(o.swapped - o.correct, 6)}`,
ratioEmpty
? (o.correct === 0 ? 'A and B coincide: the documented distance is zero and a ratio to zero is undefined.' : 'The swapped call did not return a finite number, so there is no ratio.')
: (o.ratio === 1 ? 'The swapped call returned the same distance for this pair: the hazard is present and gives no sign of itself.' : 'Both are plausible distances; nothing in the returned number shows which order was used.'),
ratioEmpty);
}
/* ── Questions and machine detail: cited from source, live where computable ─ */
function corridorText(r) {
if (r == null) return 'null (forCable returns null: no finite distance above zero)';
if (r.km == null) return `withheld: “${r.withheld}”`;
return fmtLen(r.km, 6);
}
function paintQuestions(m) {
const qa = $('qa');
const ce = mod['corridor-estimate.js'];
const items = [];
const live = m.ok && m.corridor;
items.push([
'How does this help draw a system or a single-line diagram?',
'It feeds the cable route: the straight-line km between two ends of a circuit. engine/corridor-estimate.js says its caller “is expected to have produced that km via v9-geodesy.js distanceKm or geo-core.js haversine” (lines 17–19) and forCable(km) multiplies it by CABLE_FACTOR' + (ce ? ` (${ce.CABLE_FACTOR}, read from the module)` : '') + ' into a corridor length. It also ranks substations (bus … [line shortened here: 522 characters; full line on GitHub]
live ? `Live, A to B: forCable(documented) = ${corridorText(m.corridor.documented)}; forCable(swapped) = ${corridorText(m.corridor.swapped)}. Scenario leg: forCable on R_MEAN = ${corridorText(m.corridor.legMean)}, on R_ATLAS = ${corridorText(m.corridor.legAtlas)}, on R_UK = ${corridorText(m.corridor.legUK)}. When both corridor estimates are offered, a wrong radius or a swapped call moves the c … [line shortened here: 495 characters; full line on GitHub]
: (m.ok ? 'Live corridor lengths EMPTY: engine/corridor-estimate.js has not loaded.' : 'Live corridor lengths EMPTY: ' + emptyReason())
]);
items.push([
'What is this code used for?',
`engine/geo-core.js exports ${mod['geo-core.js'] ? Object.keys(mod['geo-core.js']).join(', ') : '(not loaded)'}; engine/v9-geodesy.js exports ${mod['v9-geodesy.js'] ? Object.keys(mod['v9-geodesy.js']).join(', ') : '(not loaded)'}; commit ${COMMIT.slice(0, 12)}. Callers read from import lines in the engine at that commit: geo-area.js imports EARTH_RADIUS_KM and haversine (line 30); geo-shapes.j … [line shortened here: 774 characters; full line on GitHub]
''
]);
items.push([
'Where does it lead next?',
'From the straight-line km to the corridor length (forCable), and from a corridor length to a cable length on a feeder drawing. Whether any estate page passes a forCable length into a feeder calculation such as engine/voltage-drop.js is not established: this page has not traced such a call.',
''
]);
if (qa.childElementCount !== items.length) { qa.textContent = ''; for (let i = 0; i < items.length; i++) { const li = el('li'); li.append(el('b'), el('div'), el('div', 'live')); qa.append(li); } }
items.forEach(([q, a, l], i) => { const li = qa.children[i]; setT(li.children[0], q); setT(li.children[1], a); setT(li.children[2], l); });
const mc = $('machine');
const b = el('b', null, 'Machine detail. ');
const gc = mod['geo-core.js'];
const txt = `Inputs: lon and lat in decimal degrees (east, north); radiusKm in km (haversine default R_ATLAS${gc ? ' = ' + gc.R_ATLAS : ''}); leg length in km; bearing in degrees clockwise from north. Outputs: haversine, haversineUK, distanceKm return great-circle km on a sphere; destinationPoint returns [lon, lat] degrees; initialBearingDeg returns degrees in [0, 360); forCable returns {km, fac … [line shortened here: 735 characters; full line on GitHub]
if (mc.textContent !== 'Machine detail. ' + txt) { mc.textContent = ''; mc.append(b, txt); }
}
/* ── one frame per change ────────────────────────────────────────────────── */
let pending = false;
function update() {
paintControls();
if (pending) return; pending = true;
requestAnimationFrame(() => {
pending = false;
const m = compute();
paintResults(m); drawMap(m); drawRadii(m); drawGap(m); paintQuestions(m);
window.__hazards = {
state: JSON.parse(JSON.stringify(S)), d: m.ok ? m.d : null, mods: { ...modState },
radii: m.ok ? m.radii.rows.map(r => ({ key: r.key, R: r.R, km: r.km, diffKm: r.diffKm, ppm: r.ppm })) : null,
order: m.ok ? { correct: m.order.correct, swapped: m.order.swapped, correct9: m.order.correct9, swapped9: m.order.swapped9, ratio: m.order.ratio, swapDrawable: m.order.swapDrawable } : null,
corridor: m.ok ? m.corridor : null,
mapH: proj ? proj.h : null
};
});
}
window.addEventListener('resize', update);
if (window.matchMedia('(min-width: 900px)').matches) $('questions').open = true;
update();
await Promise.all(MODULES.map(async m => {
modState[m] = 'LOAD'; paintMods();
try { mod[m] = await import(ENGINE + m); modState[m] = 'OK'; }
catch (e) { const msg = (e && e.message) || String(e); modState[m] = 'FAIL ' + msg; if (m !== 'corridor-estimate.js') loadError = `engine/${m} did not load: ${msg}`; }
paintMods();
}));
update();Iterations — 27 Earth Radii and Argument Order Page
A web page in Galaxies Wafers that uses haversine. Published at https://ventusltd.github.io/galaxies-wafers/iterations/27-earth-radii-and-argument-order/.
rendergalaxies-wafers / iterations/27-earth-radii-and-argument-order/index.html · lines 1–87 of 87 · Entry point
- What it does
- It draws its content. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: form fields (user input). Out: web page. Coordinate systems named: WGS84 / EPSG:4326.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/27-earth-radii-and-argument-order/.
- What it achieves
- Two Hazards on One Map — Earth radii and argument order in distance code. Its code works with 100 kW.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- galaxies-wafers · iterations/27-earth-radii-and-argument-order · page
- Uses
- Hazards (stylesheet), Galaxies Wafers — Iterations Page (link), Hazards (script src)
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/27-earth-radii-and-argument-order/index.html:1-87 · blob e1fe0686ad96c993732e544f7bf6c85e219e4f7e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>Two Hazards on One Map — Earth radii and argument order in distance code</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="hazards.css">
</head>
<body>
<main>
<header>
<h1>TWO HAZARDS ON ONE MAP</h1>
<div class="dim">Two ways distance code in this estate can return a plausible number that is not the number intended: which Earth radius it stands on, and which order it takes latitude and longitude in. Every distance, bearing and arc point below is returned at run time by published engine modules called in this page. The comparisons between them (differences, parts per million and ratios) are … [line shortened here: 455 characters; full line on GitHub]
<div id="mods" class="mods" aria-live="polite"></div>
</header>
<div class="cols">
<section class="mapcol">
<h2>THE MAP · TAP TO PLACE A AND B</h2>
<div class="seg" id="views"></div>
<div class="seg" id="nexts"></div>
<canvas id="map" role="img" aria-label="Latitude and longitude graticule with points A and B, the great-circle arc of the documented call, the arc the swapped call measures, and the scenario leg used for the radii"></canvas>
<div id="mapkey" class="key small"></div>
<div id="coords" class="coords small"></div>
<h2>PRESET PAIRS · DEFINED ONLY BY COORDINATES</h2>
<div class="seg presets" id="presets"></div>
<p class="dim small">Graticule only. No coastline is drawn and no grid data is fetched: a place on this page is the pair of coordinates printed beside it.</p>
</section>
<section class="side">
<h2>HAZARD 1 · EARTH RADII</h2>
<div class="in">
<div class="row"><label for="in-d">leg length</label><span class="tag">SCENARIO INPUT</span></div>
<div class="row"><output id="out-d"></output><span class="dim small">log scale</span></div>
<input id="in-d" type="range" min="0" max="1000" step="1" value="667">
<div id="leg" class="dim small"></div>
</div>
<canvas id="radii" role="img" aria-label="Concentric arcs of each Earth radius the modules export, with the gaps between them magnified"></canvas>
<div id="radiikey" class="dim small"></div>
<h2>RESULTS · THE SAME TWO POINTS ON EACH RADIUS</h2>
<p class="boundary">Illustrative physics drawn by a computer from published data. Not an engineering design or certified calculation. Any real design above 100 kW needs study and approval by a qualified chartered electrical engineer under the applicable standards.</p>
<ol id="radiires" class="results"></ol>
<canvas id="gap" role="img" aria-label="Difference from the default radius against leg length, both on log axes"></canvas>
<div id="gapkey" class="dim small"></div>
<h2>THE ESTATE DISAGREES WITH ITSELF · STATED, NOT RESOLVED</h2>
<div class="pair">
<blockquote>
<div class="who">ventus-grid-engine · engine/geo-core.js lines 33–34</div>
<p>“R_ATLAS (6378.137) stays the default, because every deployed tool uses it and every published Ventus figure depends on it.”</p>
<div class="who">engine/v9-geodesy.js lines 13–14</div>
<p>“Radius 6378.137 km, matching Ventusltd/grid-distance-maths. Haversine. No projection, no turf, no second radius for geometry.”</p>
<div class="dim small">commit <span class="pin"></span></div>
</blockquote>
<blockquote>
<div class="who">gridmachine1 · CABLE-ENGINE-DATASHEETS.md line 11, rules common to every engine</div>
<p>“Distances are computed on the WGS84 ellipsoid”</p>
<p>“Measured 2026-09-07: on a 235 km span a sphere understates by 450 to 713 m depending on the radius chosen. No single sphere is right across an area.”</p>
<div class="dim small">commit bcdab92900c8</div>
</blockquote>
</div>
<p class="dim small">Neither module on this page implements an ellipsoid, so this page cannot compute the ellipsoidal distance and does not draw one. The engine keeps a sphere so that its results agree with deployed tools; the datasheet asks for the ellipsoid. Both are quoted as written.</p>
<h2>HAZARD 2 · ARGUMENT ORDER</h2>
<p class="dim small" id="orderdoc"></p>
<p class="boundary">Illustrative physics drawn by a computer from published data. Not an engineering design or certified calculation. Any real design above 100 kW needs study and approval by a qualified chartered electrical engineer under the applicable standards.</p>
<ol id="orderres" class="results"></ol>
<p class="dim small">This page charts the hazard. It does not say whether any call site in the estate makes the swapped call; it has not looked, and a chart of what a swapped call would return is not evidence that one exists.</p>
<details id="questions" class="questions">
<summary>Questions</summary>
<ol id="qa" class="qa small"></ol>
</details>
<p id="machine" class="machine small"></p>
<footer class="dim small">
Modules imported from ventus-grid-engine at commit <span class="pin"></span>: engine/geo-core.js, engine/v9-geodesy.js and engine/corridor-estimate.js. Radius names and values, distances, bearings and arc points are returned by those modules. The page adds the map projection (plain equirectangular), the magnification of the radii drawing, and the differences, parts per million and ratios b … [line shortened here: 423 characters; full line on GitHub]
<a href="../">every version</a>
</footer>
</section>
</div>
</main>
<script type="module" src="hazards.mjs"></script>
</body>
</html>Iterations — 28 Nearest Search Trap Page
A web page in Galaxies Wafers covering substations and cables, using haversine. Published at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.
rendergalaxies-wafers / iterations/28-nearest-search-trap/index.html · lines 1–71 of 71 · Entry point
- What it does
- It draws substations and cables. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain terms in the code: substations, cables. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- Out: web page.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.
- What it achieves
- The Nearest-Search Trap — a gate made visible. Its code works with 100 kW.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- galaxies-wafers · iterations/28-nearest-search-trap · page
- Uses
- Trap (stylesheet), Galaxies Wafers — Iterations Page (link), Trap (script src)
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/28-nearest-search-trap/index.html:1-71 · blob f36cd4f9a98a74f5046d3d28c6e38b5ba7ef2bd4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>The Nearest-Search Trap — a gate made visible</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="trap.css">
</head>
<body>
<main>
<header>
<h1>THE NEAREST-SEARCH TRAP</h1>
<div class="dim">A proof in the grid engine plants two mapped nodes around one query point: a true nearest node almost due east, and a decoy almost due north. A search that scans every node finds the true one. A search that first cuts the map to a square box drawn in <i>degrees</i> can silently keep the decoy and drop the true node, because a degree of longitude is shorter than a degree of lat … [line shortened here: 517 characters; full line on GitHub]
<div id="mods" class="mods" aria-live="polite"></div>
</header>
<div class="cols">
<section class="chart">
<h2>THE PLANE · FIXTURE NODES FROM THE PROOF</h2>
<canvas id="plane" role="img" aria-label="Map-like plane with the query point, the proof's substation nodes, and both searches"></canvas>
<div class="controls">
<button id="runA" type="button">▶ (a) scan every node</button>
<button id="runB" type="button">▶ (b) degree-box pre-filter</button>
<button id="step" type="button">step</button>
<button id="reset" type="button">query back to the proof's fixture</button>
<button id="gridBtn" type="button" aria-pressed="false">show the query grid</button>
</div>
<div id="key" class="dim small key"></div>
<p class="dim small">Drag or tap anywhere on the plane to move the query point. The nodes stay where the proof put them.</p>
</section>
<section class="side">
<p class="boundary">A distance is a distance: this page reports the nearest <b>mapped</b> node to a point and how far away it is, never whether anything can be joined to it. Illustrative physics drawn by a computer from published data. Not an engineering design or certified calculation. Any real design above 100 kW needs study and approval by a qualified chartered electrical engineer under t … [line shortened here: 428 characters; full line on GitHub]
<h2>AT YOUR QUERY POINT</h2>
<div id="query" class="small"></div>
<div class="pair">
<div class="panel" id="panelA"><h3>(a) scan every node</h3><ol id="stepsA" class="steps"></ol><div id="ansA" class="ans"></div></div>
<div class="panel mag" id="panelB"><h3>(b) degree-box pre-filter</h3><ol id="stepsB" class="steps"></ol><div id="ansB" class="ans"></div></div>
</div>
<div id="compare" class="compare"></div>
<h2>THE GATE · THE PROOF'S OWN TRAP CHECKS, RUN AGAINST BOTH SEARCHES</h2>
<p class="boundary">A distance is a distance: nearest mapped node only. Illustrative physics drawn by a computer from published data. Not an engineering design or certified calculation. Any real design above 100 kW needs study and approval by a qualified chartered electrical engineer under the applicable standards.</p>
<div id="gate" class="gate small"></div>
<details id="questions" class="questions">
<summary>Questions</summary>
<h3>1. How does this help draw a system or a single-line diagram?</h3>
<p>It feeds one element: the <b>far end of a cable route</b>, the substation node at the network end of an onshore connection. <code>index(points).nearest(lon, lat, { minimumKv })</code> returns <code>{ point, km }</code>: <code>point.name</code> and <code>point.location</code> name and place that node, <code>point.voltages_kv</code> gives the voltages its busbars declare, and <code>km</co … [line shortened here: 784 characters; full line on GitHub]
<h3>2. What is this code used for?</h3>
<p>Module <code>engine/v9-nearest-search.js</code> in ventus-grid-engine at commit d9cd18b, exporting <code>normalise</code>, <code>index</code> and <code>schema</code>; it imports <code>distanceKm</code> from <code>engine/v9-geodesy.js</code>. Package export <code>./v9-nearest-search</code> (<code>package.json</code>). Callers inside the engine at that commit, by source: <code>proofs/v9-e … [line shortened here: 1,270 characters; full line on GitHub]
<h3>3. Where does it lead next?</h3>
<p>The next element is the <b>cable route</b> from the site to that node, and at the node, the substation busbar of the voltage asked for. In the estate's engine routing (gridmachine1 <code>CABLE-ENGINES.md</code>) this search is E1, "substation finder within a radius", the general case and the declared fallback for offshore wind (E3) and declared transmission connections (E4). A route mod … [line shortened here: 539 characters; full line on GitHub]
</details>
<p class="machine small"><b>Machine detail</b> · inputs: <code>points</code> [{ name, location { lon °, lat ° }, voltages_kv [kV] }], query <code>lon</code> ° and <code>lat</code> ° (decimal degrees), <code>minimumKv</code> kV (floor on the highest declared voltage; default 0), <code>limit</code> count (default 1; 0 is read as 1) · outputs: <code>{ point, km }</code> or <code>null</code> for … [line shortened here: 1,071 characters; full line on GitHub]
<h2>HOW OFTEN THE PRE-FILTER DISAGREES</h2>
<div id="grid" class="small"></div>
<h2>WHAT THIS PAGE IS AND IS NOT</h2>
<div id="notes" class="dim small notes"></div>
<footer class="dim small"><span id="pin"></span> <a href="../">every version</a></footer>
</section>
</div>
</main>
<script type="module" src="trap.mjs"></script>
</body>
</html>Trap
A style sheet in the iterations folder of Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.
rendergalaxies-wafers / iterations/28-nearest-search-trap/trap.css · lines 1–51 of 51 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Downstream impact
- Used directly by 1 file: Iterations — 28 Nearest Search Trap Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Loaded by the 28 Nearest Search Trap page at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.
- Application
- galaxies-wafers · iterations/28-nearest-search-trap · style sheet
- Uses
- none found
- Used by
- loaded by Iterations — 28 Nearest Search Trap Page (stylesheet)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/28-nearest-search-trap/trap.css:1-51 · blob 6def3b3931d838994c1f659c41b139f36d21f6da · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
:root{--ink:#d8dee9;--dim:#8b93a7;--grey:#8b93a7;--ground:#0b0d12;--edge:#1b2030;--mag:#ff2bd6;--white:#ffffff}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
padding:calc(env(safe-area-inset-top,0px) + .8rem) 1rem calc(env(safe-area-inset-bottom,0px) + 2rem)}
main{max-width:74rem;margin:0 auto}
h1{font-size:13px;letter-spacing:.16em;font-weight:600;margin:0 0 .3rem}
h2{font-size:11px;letter-spacing:.14em;font-weight:400;color:var(--dim);margin:1.1rem 0 .4rem}
h3{font-size:11px;letter-spacing:.08em;font-weight:600;margin:0 0 .3rem}
.dim{color:var(--dim)} .small{font-size:11.5px}
a{color:var(--white)}
.mods{margin:.5rem 0 0;display:flex;flex-wrap:wrap;gap:.3rem .8rem;font-size:11.5px}
.mods b{font-weight:600}
.boundary{border:1px solid var(--edge);border-left:3px solid var(--white);background:#10131b;padding:.5rem .6rem;margin:.6rem 0;font-size:11.5px}
canvas{display:block;width:100%;height:420px;background:#05060a;border:1px solid var(--edge);border-radius:.4rem;touch-action:none;cursor:crosshair}
.controls{display:flex;flex-wrap:wrap;gap:.35rem;margin:.5rem 0}
.controls button{font:inherit;font-size:12px;color:var(--ink);background:#10131b;border:1px solid var(--edge);border-radius:.35rem;padding:.45rem .6rem;min-height:40px}
.controls button[aria-pressed=true]{border-color:var(--white);box-shadow:inset 0 0 0 1px var(--white)}
.controls #runB{border-color:#5a1f4f}
.key{display:flex;flex-wrap:wrap;gap:.2rem .9rem}
.key i{display:inline-block;width:.8em;height:.8em;border-radius:50%;vertical-align:-.05em;margin-right:.3em}
.pair{display:grid;gap:.5rem;margin-top:.4rem}
.panel{border:1px solid var(--edge);border-left:3px solid var(--white);border-radius:.4rem;padding:.45rem .6rem;background:#10131b}
.panel.mag{border-left-color:var(--mag)}
.panel.mag h3{color:var(--mag)}
.steps{margin:0;padding-left:1.4rem;font-size:11.5px}
.steps li{margin:.12rem 0;color:var(--dim)}
.steps li.on{color:var(--ink)}
.steps li.now{color:var(--white);background:#1b2030;border-radius:.2rem}
.steps .km{color:var(--white);font-weight:600}
.ans{margin-top:.35rem;border-top:1px solid var(--edge);padding-top:.3rem}
.ans b{color:var(--white)}
.empty{color:var(--grey);border:1px dashed var(--grey);border-radius:.25rem;padding:0 .3rem}
.compare{margin:.5rem 0;border:1px solid var(--edge);border-radius:.4rem;padding:.45rem .6rem}
.compare b{color:var(--white)}
.gate pre{white-space:pre-wrap;margin:.3rem 0;padding:.45rem .6rem;background:#07080c;border:1px solid var(--edge);border-radius:.35rem;font-size:11px}
.gate pre.b{border-left:3px solid var(--mag)} .gate pre.a{border-left:3px solid var(--white)}
.gate .v{font-weight:700;color:var(--white)}
.notes p{margin:.3rem 0}
footer{margin-top:1.2rem}
code{font-size:.95em;color:var(--white)}
.questions{border:1px solid var(--edge);border-radius:.4rem;padding:.35rem .6rem;background:#10131b;margin:1rem 0 .4rem;font-size:11.5px}
.questions summary{cursor:pointer;min-height:36px;display:flex;align-items:center;letter-spacing:.12em;color:var(--white)}
.questions h3{margin:.7rem 0 .2rem}
.questions p{margin:.2rem 0 .4rem;color:var(--ink)}
.machine{border-left:3px solid var(--grey);padding:.35rem .6rem;background:#0e1118;margin:.4rem 0}
@media (min-width:900px){
.cols{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr);gap:1.4rem;align-items:start}
.chart{position:sticky;top:.8rem}
canvas{height:560px}
}Trap
A JavaScript module in the iterations folder of Galaxies Wafers that paints mods, builds steps and renders steps, covering substations and 33kV, using haversine. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.
rendergalaxies-wafers / iterations/28-nearest-search-trap/trap.mjs · lines 1–390 of 445 · Entry point · pattern paintKey (shared by 2 files)
- What it does
- It draws substations and 33kV. Defines 43 functions or classes, including near, $, el, f, paintMods. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: substations, 33kV.
- Inputs & outputs
- Out: canvas drawing. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 33kV.
- Downstream impact
- Used directly by 1 file: Iterations — 28 Nearest Search Trap Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.
- What it achieves
- It paints mods (`paintMods`), builds steps (`buildSteps`) and renders steps (`renderSteps`). The Nearest-Search Trap — the ring-search bug class from `proofs/v9-engine.proof`.mjs, made visible. Its code works with 33 kV. It responds to pointerdown, pointermove and pointerup events.
- Why it matters
- Loaded by the 28 Nearest Search Trap page at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.
- Application
- galaxies-wafers · iterations/28-nearest-search-trap · JavaScript module
- Uses
- none found
- Used by
- loaded by Iterations — 28 Nearest Search Trap Page (script src)
- Produces
- near, $, el, f, paintMods, load, inBox, searchA, searchB, buildSteps, kmOf, renderSteps
- Defines here
- near, $, el, f, paintMods, load, inBox, searchA, searchB, buildSteps, kmOf, renderSteps, ansNode, renderPanels, runGate, check, renderGate, runGrid, pct, li, KM_PER_DEG, resize, px, unpx, dot, label, edgePoint, draw, line, paintKey
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/28-nearest-search-trap/trap.mjs:1-390 · blob be5297c56db4a51c203a0b496f9b8701292d1226 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
/* The Nearest-Search Trap — the ring-search bug class from
proofs/v9-engine.proof.mjs, made visible.
Every distance and every nearest answer is returned by the engine's own
modules at the pinned commit (v9-geodesy.js distanceKm, v9-nearest-search.js
index().nearest). The page never measures a distance itself. The degree-box
pre-filter in (b) is NOT engine code: it is the "optimisation" the proof
warns about, built here by handing the module a box-filtered list. */
const COMMIT = 'd9cd18b0e2034325814924e6e4a0e958014f2748';
const ENGINE = `https://cdn.jsdelivr.net/gh/Ventusltd/ventus-grid-engine@${COMMIT}/`;
const MODULES = ['engine/v9-geodesy.js', 'engine/v9-nearest-search.js'];
const PROOF = 'proofs/v9-engine.proof.mjs';
/* ── The proof's fixture, as written in proofs/v9-engine.proof.mjs ─────────
(the expressions are the proof's own; the nodes are fictional test nodes) */
const QUERY = [0, 55];
const DECOY_NORTH = { name: 'Decoy North Grid Substation', voltages_kv: [400],
location: { lon: 0, lat: 55 + 6.6 / 111.32 } };
const TRUE_EAST = { name: 'True East Substation', voltages_kv: [400],
location: { lon: 6.0 / (111.32 * Math.cos(55 * Math.PI / 180)), lat: 55 } };
const FAR = { name: 'Far Away Substation', voltages_kv: [400],
location: { lon: 1.5, lat: 56.2 } };
const LOW_VOLTAGE = { name: 'Local 33kV Point', voltages_kv: [33],
location: { lon: 0.001, lat: 55.001 } };
const NODES = [DECOY_NORTH, TRUE_EAST, FAR, LOW_VOLTAGE];
const MIN_KV = 100; // the proof's minimumKv
const BOX_DEG = 0.06; // the proof's "naive square bounding box drawn in DEGREES (+/-0.06 deg)"
const near = (a, b, tol) => Math.abs(a - b) <= tol; // the proof's helper
/* The deterministic grid of query positions the disagreement count runs over. */
const GRID = { lonMin: -0.2, lonMax: 0.2, latMin: 54.9, latMax: 55.1, n: 41 };
const $ = id => document.getElementById(id);
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const f = (v, d = 3) => Number(v).toFixed(d);
const SHORT = new Map([[DECOY_NORTH, 'Decoy North'], [TRUE_EAST, 'True East'], [FAR, 'Far Away'], [LOW_VOLTAGE, 'Local 33kV']]);
window.__trap = { commit: COMMIT, ready: false };
/* ── loading, Grid Atlas grammar ─────────────────────────────────────────── */
const modState = Object.fromEntries(MODULES.map(m => [m, 'WAIT']));
function paintMods() {
const box = $('mods'); box.textContent = '';
for (const m of MODULES) {
const st = modState[m], sp = st.indexOf(' ');
const s = el('span'); const b = el('b', null, sp < 0 ? st : st.slice(0, sp));
s.append(b, ` ${m}` + (sp < 0 ? '' : ' — ' + st.slice(sp + 1)));
box.append(s);
}
$('pin').textContent = `Modules imported from ventus-grid-engine at commit ${COMMIT.slice(0, 12)}; fixture, check names and box width from ${PROOF} at the same commit.`;
}
paintMods();
/* Questions: collapsed on phone, open on a wide screen */
if (window.matchMedia && window.matchMedia('(min-width: 900px)').matches) $('questions').open = true;
let geo = null, ns = null;
async function load() {
const out = await Promise.all(MODULES.map(async m => {
modState[m] = 'LOAD'; paintMods();
try { const x = await import(ENGINE + m); modState[m] = 'OK'; paintMods(); return x; }
catch (e) { modState[m] = 'FAIL ' + ((e && e.message) || 'import failed'); paintMods(); return null; }
}));
[geo, ns] = out;
if (!geo || !ns) {
for (const id of ['stepsA', 'stepsB', 'gate', 'grid', 'query']) {
$(id).textContent = '';
$(id).append(el('span', 'empty', 'EMPTY — an engine module did not load, so no distance can be shown; nothing is drawn in its place.'));
}
window.__trap.ready = 'failed';
draw(); return;
}
start();
}
/* ── the two searches, both answered by the module ───────────────────────── */
let fullIdx;
function inBox(p, lon, lat) {
return Math.abs(p.location.lon - lon) <= BOX_DEG && Math.abs(p.location.lat - lat) <= BOX_DEG;
}
function searchA(lon, lat) {
return { best: fullIdx.nearest(lon, lat, { minimumKv: MIN_KV }),
list: fullIdx.nearest(lon, lat, { minimumKv: MIN_KV, limit: NODES.length }) };
}
function searchB(lon, lat) {
const kept = NODES.filter(p => inBox(p, lon, lat));
const idx = ns.index(kept);
return { kept, best: idx.nearest(lon, lat, { minimumKv: MIN_KV }),
list: idx.nearest(lon, lat, { minimumKv: MIN_KV, limit: NODES.length }) };
}
/* ── state ───────────────────────────────────────────────────────────────── */
const S = { lon: QUERY[0], lat: QUERY[1], run: null, step: -1, timer: 0, showGrid: false };
let stepsA = [], stepsB = [], A = null, B = null, gridCells = [];
function buildSteps() {
A = searchA(S.lon, S.lat); B = searchB(S.lon, S.lat);
const kmOf = (list, p) => { const hit = (list || []).find(x => x.point === p); return hit ? hit.km : null; };
stepsA = NODES.map(p => {
const km = kmOf(A.list, p);
return { node: p, kind: km == null ? 'floor' : 'scan',
text: km == null
? [`${p.name} (${p.voltages_kv.join(', ')} kV): below minimumKv ${MIN_KV}, the module skips it`]
: [`${p.name}: distanceKm = `, [f(km)], ' km'] };
});
stepsA.push({ kind: 'answer', text: A.best
? ['sorted by km; nearest() returns ', [A.best.point.name], ' at ', [f(A.best.km)], ' km']
: ['nearest() returned null'] });
stepsB = [{ kind: 'box', text: [`draw a square ±${BOX_DEG}° box in degrees around the query`] }];
for (const p of NODES) {
const inside = B.kept.includes(p);
stepsB.push({ node: p, kind: inside ? 'keep' : 'drop',
text: [`${p.name}: Δlon ${f(p.location.lon - S.lon, 4)}°, Δlat ${f(p.location.lat - S.lat, 4)}° → ${inside ? 'kept' : 'dropped before any distance is measured'}`] });
}
stepsB.push({ kind: 'scan', text: B.list.length
? ['module scans the kept list: ', ...B.list.flatMap((x, i) => [(i ? '; ' : '') + `${SHORT.get(x.point)} `, [f(x.km)], ' km'])]
: [`module scans the kept list: no kept node at or above ${MIN_KV} kV`] });
stepsB.push({ kind: 'answer', text: B.best
? ['nearest() returns ', [B.best.point.name], ' at ', [f(B.best.km)], ' km']
: ['nearest() returned null'] });
}
function renderSteps(list, ol, active) {
ol.textContent = '';
list.forEach((s, i) => {
const li = el('li');
for (const part of s.text) li.append(Array.isArray(part) ? el('span', 'km', part[0]) : part);
if (active == null || i <= active) li.classList.add('on');
if (active === i) li.classList.add('now');
ol.append(li);
});
}
function ansNode(r, lead) {
const d = el('div');
if (!r.best) {
d.append(lead, el('span', 'empty', `EMPTY — no mapped node at or above ${MIN_KV} kV inside the box; the module returns null`));
return d;
}
d.append(lead, el('b', null, r.best.point.name), ' · ', el('b', null, f(r.best.km) + ' km'), ' to the nearest mapped node');
return d;
}
function renderPanels() {
const q = $('query'); q.textContent = '';
const atFixture = S.lon === QUERY[0] && S.lat === QUERY[1];
q.append(`query lon ${f(S.lon, 4)}°, lat ${f(S.lat, 4)}°`,
atFixture ? ' — the proof\'s fixture query' : ' — moved from the proof\'s fixture query');
const act = S.run;
renderSteps(stepsA, $('stepsA'), act === 'a' ? S.step : act === 'b' ? -1 : null);
renderSteps(stepsB, $('stepsB'), act === 'b' ? S.step : act === 'a' ? -1 : null);
$('ansA').replaceChildren(ansNode(A, 'answer: '));
$('ansB').replaceChildren(ansNode(B, 'answer: '));
const c = $('compare'); c.textContent = '';
if (!A.best) c.append(el('span', 'empty', 'EMPTY — the full scan found no node'));
else if (!B.best) c.append('At this point the pre-filter returns ', el('span', 'empty', 'EMPTY'),
' where the full scan finds ', el('b', null, A.best.point.name), ' at ', el('b', null, f(A.best.km) + ' km'), '.');
else if (B.best.point === A.best.point) c.append('At this point both searches return the same node, ',
el('b', null, A.best.point.name), ', at ', el('b', null, f(A.best.km) + ' km'), '.');
else c.append('At this point the pre-filter returns ', el('b', null, B.best.point.name), ' at ', el('b', null, f(B.best.km) + ' km'),
'; the full scan returns ', el('b', null, A.best.point.name), ' at ', el('b', null, f(A.best.km) + ' km'),
'. The pre-filter\'s distance is ', el('b', null, f(B.best.km - A.best.km) + ' km'), ' longer (',
el('b', null, f(100 * (B.best.km / A.best.km - 1), 1) + '%'), '), with no error raised.');
}
/* ── the gate: the proof's trap checks, verbatim names, both searches ──────── */
function runGate(search, tag) {
const failures = []; let passed = 0;
const check = (name, condition) => { if (condition) passed += 1; else failures.push(name); };
const best = search(QUERY[0], QUERY[1]).best;
const dEast = geo.distanceKm(QUERY[0], QUERY[1], TRUE_EAST.location.lon, TRUE_EAST.location.lat);
const dNorth = geo.distanceKm(QUERY[0], QUERY[1], DECOY_NORTH.location.lon, DECOY_NORTH.location.lat);
check('the fixture is actually a trap: the true nearest node is closer than '
+ 'the decoy, but sits outside a naive degree-square box that still '
+ 'contains the decoy — if this fails the test has stopped testing anything',
dEast < dNorth
&& Math.abs(TRUE_EAST.location.lon - QUERY[0]) > 0.06
&& Math.abs(DECOY_NORTH.location.lat - QUERY[1]) < 0.06);
check('nearest() returns the TRUE nearest node, not the one a degree-box '
+ 'pre-filter would have left behind — this is the ring-search bug class, '
+ 'and it inflates a reported grid distance by kilometres when present',
best && best.point.name === 'True East Substation');
check('the reported distance is the true one, roughly 6 km and not the decoy 6.6',
best && near(best.km, 6.0, 0.05));
const report = failures.length
? 'v9-engine proof FAILED (' + failures.length + ' of ' + (failures.length + passed) + '):\n- ' + failures.join('\n- ')
: 'v9-engine proof PASS — ' + passed + ' checks';
return { tag, passed, failures, report, best, dEast, dNorth };
}
function renderGate() {
const ga = runGate(searchA, 'a'), gb = runGate(searchB, 'b');
const g = $('gate'); g.textContent = '';
g.append(el('p', null, `At the fixture query (${QUERY[0]}, ${QUERY[1]}) the module measures True East at ${f(ga.dEast)} km and Decoy North at ${f(ga.dNorth)} km. True East's longitude offset is ${f(TRUE_EAST.location.lon - QUERY[0], 4)}°, outside the ±${BOX_DEG}° box; Decoy North's latitude offset is ${f(DECOY_NORTH.location.lat - QUERY[1], 4)}°, inside it.`));
for (const r of [ga, gb]) {
const p = el('p');
p.append(r.tag === 'a' ? '(a) the scan the module ships: ' : '(b) the same module handed a degree-box pre-filtered list: ',
el('span', 'v', r.failures.length ? 'the gate FAILS' : 'the gate HOLDS'),
` — ${r.passed} of ${r.passed + r.failures.length} checks pass`);
g.append(p, el('pre', r.tag, r.report));
}
g.append(el('p', 'dim', 'The report lines are the proof\'s own check names and report format, evaluated here against each search. The proof in the engine runs only against (a); (b) is how the gate reads when someone adds the filter it was written to catch. Seeing it fail is what makes its pass worth trusting.'));
window.__trap.gate = { a: { passed: ga.passed, failed: ga.failures.length }, b: { passed: gb.passed, failed: gb.failures.length } };
}
/* ── the grid count ──────────────────────────────────────────────────────── */
function runGrid() {
gridCells = [];
let same = 0, other = 0, empty = 0, worst = 0, worstAt = null;
for (let j = 0; j < GRID.n; j++) for (let i = 0; i < GRID.n; i++) {
const lon = GRID.lonMin + (GRID.lonMax - GRID.lonMin) * i / (GRID.n - 1);
const lat = GRID.latMin + (GRID.latMax - GRID.latMin) * j / (GRID.n - 1);
const a = searchA(lon, lat).best, b = searchB(lon, lat).best;
let k;
if (!b) { k = 'empty'; empty++; }
else if (b.point === a.point) { k = 'same'; same++; }
else { k = 'other'; other++; const d = b.km - a.km; if (d > worst) { worst = d; worstAt = [lon, lat, a, b]; } }
gridCells.push({ lon, lat, k });
}
const total = gridCells.length;
const g = $('grid'); g.textContent = '';
const pct = v => f(100 * v / total, 1) + '%';
g.append(el('p', null, `Query grid: ${GRID.n} × ${GRID.n} = ${total} positions, longitude ${GRID.lonMin}° to ${GRID.lonMax}°, latitude ${GRID.latMin}° to ${GRID.latMax}°, evenly spaced; both searches run at every position when this page loads. Tap "show the query grid" to see them on the plane.`));
const ul = el('ul');
const li = (...parts) => { const x = el('li'); x.append(...parts); ul.append(x); };
li(el('b', null, String(same)), ` (${pct(same)}) — the pre-filter returns the same node as the full scan`);
li(el('b', null, String(other)), ` (${pct(other)}) — the pre-filter returns a different, farther node, silently`);
li(el('b', null, String(empty)), ` (${pct(empty)}) — the pre-filter returns `, el('span', 'empty', 'EMPTY'), ' (null) while the full scan finds a node');
g.append(ul);
const dis = other + empty;
g.append(el('p', null, `The pre-filter disagrees with the full scan at ${dis} of ${total} grid positions (${pct(dis)}).`));
if (same + other) g.append(el('p', null, `Counting only positions where the box kept at least one node at or above ${MIN_KV} kV, it returns a farther node at ${other} of ${same + other} (${f(100 * other / (same + other), 1)}%): the silent failures, where an answer arrives and looks fine.`));
if (worstAt) g.append(el('p', null, `Largest silent inflation on the grid: ${f(worst)} km, at lon ${f(worstAt[0], 3)}°, lat ${f(worstAt[1], 3)}° — pre-filter ${worstAt[3].point.name} ${f(worstAt[3].km)} km, full scan ${worstAt[2].point.name} ${f(worstAt[2].km)} km.`));
g.append(el('p', 'dim', 'Grid positions are a drawing of the question, not proposed sites. The count belongs to the proof\'s four fixture nodes and its box width; with a real node set it would differ, and it is not shown for one.'));
window.__trap.grid = { total, same, other, empty, disagree: dis, worstKm: worst };
}
/* ── canvas ──────────────────────────────────────────────────────────────── */
const cv = $('plane'), ctx = cv.getContext('2d');
let W = 0, H = 0, DPR = 1, scale = 1, cx = 0, cy = 0;
/* drawing scale only; before the module loads nothing is placed */
const KM_PER_DEG = () => (geo ? geo.EARTH_RADIUS_KM : 6378.137) * Math.PI / 180;
const COS0 = Math.cos(QUERY[1] * Math.PI / 180);
function resize() {
const r = cv.getBoundingClientRect();
DPR = Math.min(window.devicePixelRatio || 1, 3);
W = r.width; H = r.height;
cv.width = Math.round(W * DPR); cv.height = Math.round(H * DPR);
const halfWkm = (GRID.lonMax - GRID.lonMin) / 2 * KM_PER_DEG() * COS0 + 0.8;
const halfHkm = (GRID.latMax - GRID.latMin) / 2 * KM_PER_DEG() + 0.8;
scale = Math.min(W / (2 * halfWkm), H / (2 * halfHkm));
cx = W / 2; cy = H / 2;
draw();
}
/* a local flat projection centred on the fixture query, for display */
const px = (lon, lat) => [cx + (lon - QUERY[0]) * KM_PER_DEG() * COS0 * scale, cy - (lat - QUERY[1]) * KM_PER_DEG() * scale];
const unpx = (x, y) => [QUERY[0] + (x - cx) / (KM_PER_DEG() * COS0 * scale), QUERY[1] - (y - cy) / (KM_PER_DEG() * scale)];
const MAG = '#ff2bd6', GREY = '#8b93a7';
function dot(x, y, r, fill, stroke) {
ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2);
if (fill) { ctx.fillStyle = fill; ctx.fill(); }
if (stroke) { ctx.strokeStyle = stroke; ctx.lineWidth = 1.5; ctx.stroke(); }
}
function label(text, x, y, color, align = 'left') {
ctx.font = '11px ui-monospace, Menlo, Consolas, monospace';
ctx.textAlign = align; ctx.textBaseline = 'middle';
ctx.lineWidth = 3; ctx.strokeStyle = '#05060a'; ctx.strokeText(text, x, y);
ctx.fillStyle = color; ctx.fillText(text, x, y);
}
function edgePoint(x, y) {
const dx = x - cx, dy = y - cy, m = 14;
const t = Math.min((W / 2 - m) / Math.abs(dx || 1e-9), (H / 2 - m) / Math.abs(dy || 1e-9));
return t < 1 ? [cx + dx * t, cy + dy * t, true] : [x, y, false];
}
function draw() {
if (!W) return;
ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
ctx.clearRect(0, 0, W, H);
if (!geo || !ns) {
label(window.__trap.ready === 'failed' ? 'EMPTY — engine modules did not load' : 'WAIT — loading engine modules', W / 2, H / 2, GREY, 'center');
return;
}
// graticule every 0.02 degrees, so the reader can see degrees are not square here
ctx.strokeStyle = '#161b28'; ctx.lineWidth = 1;
const [lon0, lat1] = unpx(0, 0), [lon1, lat0] = unpx(W, H);
for (let k = Math.ceil(lon0 / 0.02); k * 0.02 <= lon1; k++) { const [x] = px(k * 0.02, QUERY[1]); ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, H); ctx.stroke(); }
for (let k = Math.ceil(lat0 / 0.02); k * 0.02 <= lat1; k++) { const [, y] = px(QUERY[0], k * 0.02); ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y); ctx.stroke(); }
const barKm = 2, bx = 12, by = H - 14;
ctx.strokeStyle = GREY; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(bx, by); ctx.lineTo(bx + barKm * scale, by); ctx.stroke();
label(`${barKm} km (drawing)`, bx + barKm * scale + 6, by, GREY);
label('graticule 0.02°', W - 10, H - 14, GREY, 'right');
if (S.showGrid) for (const c of gridCells) {
const [x, y] = px(c.lon, c.lat);
if (c.k === 'same') dot(x, y, 1.3, 'rgba(255,255,255,.55)');
else if (c.k === 'other') dot(x, y, 2, MAG);
else dot(x, y, 0.9, GREY);
}
const runA = S.run === 'a', runB = S.run === 'b';
const stepA = runA ? stepsA[S.step] : null, stepB = runB ? stepsB[S.step] : null;
const [qx, qy] = px(S.lon, S.lat);
if (!S.run || runB) {
const [x0, y0] = px(S.lon - BOX_DEG, S.lat + BOX_DEG), [x1, y1] = px(S.lon + BOX_DEG, S.lat - BOX_DEG);
ctx.save(); ctx.setLineDash([6, 4]); ctx.strokeStyle = MAG; ctx.lineWidth = runB && S.step === 0 ? 2.2 : 1.4;
ctx.globalAlpha = runB ? 1 : 0.6; ctx.strokeRect(x0, y0, x1 - x0, y1 - y0); ctx.restore();
label(`±${BOX_DEG}° box`, x1 - 4, y0 + 10, MAG, 'right');
}
const doneA = !S.run || (stepA && stepA.kind === 'answer');
const doneB = !S.run || (stepB && stepB.kind === 'answer');
const line = (best, color, dash, off) => {
if (!best) return;
const [x, y] = edgePoint(...px(best.point.location.lon, best.point.location.lat));
ctx.save(); ctx.setLineDash(dash); ctx.strokeStyle = color; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(qx + off, qy + off); ctx.lineTo(x + off, y + off); ctx.stroke(); ctx.restore();
};
if (doneA) line(A.best, '#ffffff', [], 0);
if (doneB) line(B.best, MAG, [7, 5], 1.5);
const hl = (stepA && stepA.node) || (stepB && stepB.node) || null;
if (hl) {
const [x, y] = edgePoint(...px(hl.location.lon, hl.location.lat));
ctx.save(); ctx.setLineDash([2, 4]); ctx.strokeStyle = runB ? MAG : '#ffffff'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(qx, qy); ctx.lineTo(x, y); ctx.stroke(); ctx.restore();
}
const listA = A.list || [];
for (const p of NODES) {
const [x, y, clipped] = edgePoint(...px(p.location.lon, p.location.lat));
const floor = Math.max(...p.voltages_kv) < MIN_KV;
const kmA = listA.find(e => e.point === p);
if (hl === p) dot(x, y, 12, 'rgba(255,255,255,.14)');
if (floor) dot(x, y, 3.5, null, GREY);
else { dot(x, y, 7, 'rgba(0,0,0,.85)'); dot(x, y, clipped ? 3.5 : 5, '#ffffff'); }
const droppedNow = runB && S.step > 0 && !B.kept.includes(p) && stepsB.indexOf(stepsB.find(s => s.node === p)) <= S.step;
if (droppedNow && !floor) dot(x, y, 9.5, null, GREY);
let t = SHORT.get(p) + (kmA ? ` ${f(kmA.km, 2)} km` : floor ? ' · below floor' : '');
if (clipped) t = t + ' (off plane)';
if (droppedNow && !floor) t += ' · dropped';
ctx.font = '11px ui-monospace, Menlo, Consolas, monospace';
const tw = ctx.measureText(t).width;
/* place each label where it does not sit on the query: below for nodes
level with it, above otherwise; always kept inside the plane */
let ly = clipped ? y + 16 : floor ? y + 16 : Math.abs(y - qy) < 26 ? y + 20 : y - 13;
if (floor && Math.abs(y - qy) < 26 && Math.abs(x - qx) < 30) ly = qy - 24;
let lx = x - tw / 2;
lx = Math.max(6, Math.min(W - 6 - tw, lx));
ly = Math.max(10, Math.min(H - 30, ly));
label(t, lx, ly, floor ? GREY : '#ffffff', 'left');
}
dot(qx, qy, 13, 'rgba(255,255,255,.08)');
ctx.strokeStyle = '#ffffff'; ctx.lineWidth = 1.5; ctx.beginPath();
ctx.moveTo(qx - 16, qy); ctx.lineTo(qx - 7, qy); ctx.moveTo(qx + 7, qy); ctx.lineTo(qx + 16, qy);
ctx.moveTo(qx, qy - 16); ctx.lineTo(qx, qy - 7); ctx.moveTo(qx, qy + 7); ctx.lineTo(qx, qy + 16); ctx.stroke();
dot(qx, qy, 5, null, '#ffffff');
label('query', qx - 12, qy + 24, '#ffffff', 'right');
}
function paintKey() {
const k = $('key'); k.textContent = '';
const item = (style, text) => { const s = el('span'); const i = el('i'); Object.assign(i.style, style); s.append(i, text); k.append(s); };
item({ background: '#fff' }, `mapped node at or above ${MIN_KV} kV (substations white)`);
item({ border: `1.5px solid ${GREY}`, boxSizing: 'border-box' }, 'below the floor, or dropped by the box');
item({ background: GREY, width: '.4em', height: '.4em' }, 'grid position where (b) returns EMPTY');
item({ background: '#fff', width: '.45em', height: '.45em' }, 'grid position where both agree');
item({ background: '#fff', borderRadius: '0', height: '2px' }, '(a) full-scan answer');
item({ background: MAG, borderRadius: '0', height: '2px' }, '(b) pre-filter answer and box');
item({ background: MAG }, 'grid position where (b) returns another node');
}
function notes() {
const n = $('notes'); n.textContent = '';
const p = t => n.append(el('p', null, t));
p(`Distances are measured by distanceKm in engine/v9-geodesy.js: haversine on a sphere of radius ${geo.EARTH_RADIUS_KM} km, as the module states. That is a sphere, not the WGS84 ellipsoid used in some cable-engine datasheets; the difference is stated, not hidden. The plane is drawn in a flat local projection for display only; no distance is read off the drawing.`);
p(`The nearest answers are index(points).nearest(lon, lat, { minimumKv: ${MIN_KV} }) from engine/v9-nearest-search.js. That module is an exhaustive scan with no box or ring pre-filter, which is why (a) holds. Its own header records that it is not the copy the live Atlas loads, and that the production copy is also an exhaustive scan.`);
p(`Search (b) is not in the engine. It is the pre-filter the proof describes, built on this page by passing the module only the nodes within ±${BOX_DEG}° of the query in both longitude and latitude. It exists here so the gate can be seen to fail.`);
p('The four nodes are the proof\'s fictional test fixture, placed by the proof\'s own expressions. No real grid data is fetched or shown. A nearest mapped node is only the closest point in a list; it says nothing about capacity, permission, or whether anything could ever be joined to it.');
}
/* ── interaction ─────────────────────────────────────────────────────────── */
function stopRun() { clearTimeout(S.timer); S.timer = 0; }
function publish() {
Object.assign(window.__trap, {
query: [S.lon, S.lat], run: S.run, step: S.step,
a: A.best ? { name: A.best.point.name, km: A.best.km } : null,
b: B.best ? { name: B.best.point.name, km: B.best.km } : null,
kept: B.kept.map(p => p.name)
});
}
function refresh() { buildSteps(); renderPanels(); draw(); publish(); }