GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Cables and conductors / graphics-engines-open-source / web/versions/202609262227-site-world/world

LiDAR Cable Sweep and 1 more file

A Python command-line tool that reads cable sweep receipt, cables and 132kV, using SHA-256. It loads cables (`load_cables`), routes meta (`route_meta`) and writes receipt (`write_receipt`).

700 lines of Python and JavaScript from graphics-engines-open-source, lidar, in 2 files. Topic: Cables and conductors. Section 34 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. Trench transform · graphics-engines-open-source / web/versions/202609262227-site-world/world/trench.mjs lines 1–343
  2. LiDAR Cable Sweep electrical · lidar / src/cable_sweep.py lines 1–357

Trench

A JavaScript module in the world folder of Graphics Engines Open Source that works with cut height (`cutHeight`) and offset line (`offsetLine`) and calculates planar distances.

transformgraphics-engines-open-source / web/versions/202609262227-site-world/world/trench.mjs · lines 1–343 of 343 · version 2026-09-26 22:27 · pattern mitredOutline (shared by 2 files)

What it does
It calculates its inputs. Defines 20 functions or classes, including createTrench, pointAt, candidates, floorAt, inside.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'trench'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 2 files: Design UI (graphics-engines-open-source); Layers (graphics-engines-open-source). Reached from 3 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/); Substrate (graphics-engines-open-source).
What it achieves
It is built from the point at helper (`pointAt`), the candidates step (`candidates`) and the floor at helper (`floorAt`). A trench is a function laid over the ground, never a stored mesh.
Why it matters
Imported by Design UI and Layers.
Application
graphics-engines-open-source · web/versions/202609262227-site-world/world · JavaScript module
Uses
none found
Used by
imported by Design UI (import), imported by Layers (import), mentioned in Standalone (comment link)
Produces
createTrench, composeGround
Defines here
createTrench, pointAt, candidates, floorAt, inside, cutHeight, chainage, length3dOn, spoilVolumeOn, dig, offsetLine, mitredOutline, pad, wallLines, push, topAt, bisector, composeGround, spoilStrips, bis
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/world/trench.mjs:1-343 · blob 755a8ca5284ba93b7706c4cd7cf7f03f8ed9b9f0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
// trench.mjs: a trench is a function laid over the ground, never a stored mesh.
//
// Local metres: x east, y north, z up. The ground is any function groundAt(x, y).
// A trench is a centreline path with a floor width and a depth. The floor follows
// the ground profile along the centreline, lowered by the depth, so a trench on a
// hillside keeps a constant depth down its length. Walls are vertical unless a
// benchSlope (horizontal metres per metre of height) gives them a batter.
//
// Corners are mitred: each segment owns the strip between the bisector lines at
// its two ends, so the outside of a bend is a sharp corner, not a rounded one.
// Ends are cut square. Where two trenches (or two parts of one) overlap, the
// lowest surface wins. Nothing here fills ground: the cut never rises above it.
//
// No imports, no DOM. Pure functions of their inputs.

const GRID = 0.25;          // integration cell for spoil volume, metres
const STEP = 0.25;          // sampling step along the centreline, metres
const EPS = 1e-9;

/**
 * createTrench({ path, width, depth, benchSlope = 0, groundAt? })
 * path: [[x, y], ...] with at least two distinct points.
 * groundAt is optional; when given, length3d and spoilVolumeM3 are numbers.
 */
export function createTrench({ path, width, depth, benchSlope = 0, groundAt = null }) {
  if (!Array.isArray(path)) throw new Error('trench: path must be an array of [x, y]');
  if (!(width > 0) || !(depth > 0)) throw new Error('trench: width and depth must be positive');
  if (!(benchSlope >= 0)) throw new Error('trench: benchSlope must be zero or positive');

  // Drop repeated points so every segment has a direction.
  const pts = [];
  for (const p of path) {
    const q = [Number(p[0]), Number(p[1])];
    const last = pts[pts.length - 1];
    if (!last || Math.hypot(q[0] - last[0], q[1] - last[1]) > 1e-6) pts.push(q);
  }
  if (pts.length < 2) throw new Error('trench: path needs two distinct points');

  const half = width / 2;
  // How far out the batter may reach. The cut is clipped by the ground anyway, so
  // this only bounds the search; three depths covers steep side slopes.
  const reach = half + benchSlope * depth * 3;

  // Segments: start, unit direction, left normal, length, chainage at start.
  const segs = [];
  let s0 = 0;
  for (let i = 0; i < pts.length - 1; i++) {
    const [ax, ay] = pts[i], [bx, by] = pts[i + 1];
    const len = Math.hypot(bx - ax, by - ay);
    const dx = (bx - ax) / len, dy = (by - ay) / len;
    segs.push({ ax, ay, bx, by, dx, dy, nx: -dy, ny: dx, len, s0 });
    s0 += len;
  }
  const length2d = s0;
  const n = segs.length;

  // Cut lines at each end of each segment. At a path end the cut is square to the
  // segment; at a bend it is the bisector, so neighbours share the mitre line.
  for (let i = 0; i < n; i++) {
    const g = segs[i];
    g.first = i === 0;
    g.last = i === n - 1;
    g.mStart = g.first ? [g.dx, g.dy] : bisector(segs[i - 1], g);
    g.mEnd = g.last ? [g.dx, g.dy] : bisector(g, segs[i + 1]);
  }

  // Bounding box of everything the trench can touch, for quick rejection.
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  for (const [x, y] of pts) {
    minX = Math.min(minX, x); maxX = Math.max(maxX, x);
    minY = Math.min(minY, y); maxY = Math.max(maxY, y);
  }
  // A mitre can reach reach / cos(half the turn); cap the allowance at four times.
  const pad = reach * 4;
  const bbox = { minX: minX - pad, minY: minY - pad, maxX: maxX + pad, maxY: maxY + pad };

  function pointAt(s) {
    const c = Math.min(Math.max(s, 0), length2d);
    for (const g of segs) {
      if (c <= g.s0 + g.len || g.last) {
        const t = Math.min(Math.max(c - g.s0, 0), g.len);
        return [g.ax + g.dx * t, g.ay + g.dy * t];
      }
    }
    return pts[pts.length - 1];
  }

  // Every segment region the point falls in: chainage, lateral offset and how far
  // it lies beyond the floor edge (0 on the floor itself).
  function candidates(x, y, limit) {
    const out = [];
    if (x < bbox.minX || x > bbox.maxX || y < bbox.minY || y > bbox.maxY) return out;
    for (const g of segs) {
      const px = x - g.ax, py = y - g.ay;
      const t = px * g.dx + py * g.dy;
      const off = px * g.nx + py * g.ny;
      if (Math.abs(off) > limit + EPS) continue;
      let endExcess = 0;
      if (g.first) { if (t < 0) endExcess = -t; }
      else if (px * g.mStart[0] + py * g.mStart[1] < -EPS) continue;
      const qx = x - g.bx, qy = y - g.by;
      if (g.last) { if (t > g.len) endExcess = t - g.len; }
      else if (qx * g.mEnd[0] + qy * g.mEnd[1] > EPS) continue;
      const excess = Math.max(Math.abs(off) - half, endExcess, 0);
      if (excess > limit - half + EPS) continue;
      out.push({ s: g.s0 + Math.min(Math.max(t, 0), g.len), off, excess });
    }
    return out;
  }

  const floorAt = (s, g = groundAt) => {
    if (!g) throw new Error('trench: floorAt needs a ground function');
    const [x, y] = pointAt(s);
    return g(x, y) - depth;
  };

  const inside = (x, y) => candidates(x, y, half).some((c) => c.excess === 0);

  function cutHeight(x, y, g = groundAt) {
    const ground = g(x, y);
    const cs = candidates(x, y, benchSlope > 0 ? reach : half);
    let z = ground;
    for (const c of cs) {
      let surface = floorAt(c.s, g);
      if (c.excess > 0) {
        if (benchSlope === 0) continue;
        surface += c.excess / benchSlope;
      }
      if (surface < z) z = surface;
    }
    return z;
  }

  // Chainage of the nearest point on the centreline (inside or not).
  function chainage(x, y) {
    let best = Infinity, bestS = 0;
    for (const g of segs) {
      const t = Math.min(Math.max((x - g.ax) * g.dx + (y - g.ay) * g.dy, 0), g.len);
      const d = Math.hypot(x - (g.ax + g.dx * t), y - (g.ay + g.dy * t));
      if (d < best - EPS) { best = d; bestS = g.s0 + t; }
    }
    return bestS;
  }

  function length3dOn(g) {
    let total = 0, [px, py] = pointAt(0), pz = g(px, py);
    const steps = Math.max(1, Math.ceil(length2d / STEP));
    // Sample every vertex exactly as well as the regular steps.
    const marks = new Set();
    for (let k = 0; k <= steps; k++) marks.add(Math.min(k * length2d / steps, length2d));
    for (const sg of segs) marks.add(sg.s0);
    const ss = [...marks].sort((a, b) => a - b);
    for (let k = 1; k < ss.length; k++) {
      const [x, y] = pointAt(ss[k]);
      const z = g(x, y);
      total += Math.hypot(x - px, y - py, z - pz);
      px = x; py = y; pz = z;
    }
    return total;
  }

  // Excavated volume: ground minus cut surface, summed over a 0.25 m grid of cell
  // centres across the trench's reach, for this trench alone.
  function spoilVolumeOn(g) {
    if (benchSlope === 0) return spoilStrips(pts, width, depth, g); // vertical walls: exact strips, no grid aliasing
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    for (const [x, y] of mitredOutline(benchSlope > 0 ? reach : half)) {
      x0 = Math.min(x0, x); x1 = Math.max(x1, x);
      y0 = Math.min(y0, y); y1 = Math.max(y1, y);
    }
    const nx = Math.ceil((x1 - x0) / GRID - 1e-9), ny = Math.ceil((y1 - y0) / GRID - 1e-9);
    const dig = (x, y) => Math.max(0, g(x, y) - cutHeight(x, y, g));
    // Cell corners, computed once. A cell whose corners disagree on whether they
    // are dug straddles a wall, so it is split 8 x 8 to find where the wall runs.
    const cw = nx + 1, corner = new Float64Array(cw * (ny + 1));
    for (let j = 0; j <= ny; j++) for (let i = 0; i <= nx; i++) corner[j * cw + i] = dig(x0 + i * GRID, y0 + j * GRID);
    const SUB = 8, h = GRID / SUB;
    let vol = 0;
    for (let j = 0; j < ny; j++) {
      for (let i = 0; i < nx; i++) {
        const c = [corner[j * cw + i], corner[j * cw + i + 1], corner[(j + 1) * cw + i], corner[(j + 1) * cw + i + 1]];
        const dug = c.filter((d) => d > 0).length;
        const cx = x0 + i * GRID, cy = y0 + j * GRID;
        if (dug === 0 || dug === 4) {
          vol += dig(cx + GRID / 2, cy + GRID / 2) * GRID * GRID;
        } else {
          for (let b = 0; b < SUB; b++) for (let a = 0; a < SUB; a++) vol += dig(cx + (a + 0.5) * h, cy + (b + 0.5) * h) * h * h;
        }
      }
    }
    return vol;
  }

  // Offset polyline at signed distance h, with mitred vertices.
  function offsetLine(h) {
    const out = [];
    for (let k = 0; k <= n; k++) {
      let mx, my;
      if (k === 0) { mx = segs[0].nx; my = segs[0].ny; }
      else if (k === n) { mx = segs[n - 1].nx; my = segs[n - 1].ny; }
      else {
        const a = segs[k - 1], b = segs[k];
        const c = 1 + a.nx * b.nx + a.ny * b.ny;
        if (c < 1e-3) { mx = b.nx; my = b.ny; }            // a U-turn: no finite mitre
        else { mx = (a.nx + b.nx) / c; my = (a.ny + b.ny) / c; }
      }
      const s = k === n ? length2d : segs[k].s0;
      out.push([pts[k][0] + mx * h, pts[k][1] + my * h, s]);
    }
    return out;
  }

  function mitredOutline(h) {
    const L = offsetLine(h), R = offsetLine(-h);
    const e = benchSlope > 0 ? reach : half;
    const a = segs[0], b = segs[n - 1];
    // Square ends pushed out by the batter reach beyond the floor.
    const ext = e - half;
    const pad = (p, g, sign) => [p[0] + g.dx * ext * sign, p[1] + g.dy * ext * sign];
    return [...L, ...R, pad(L[0], a, -1), pad(R[0], a, -1), pad(L[n], b, 1), pad(R[n], b, 1)];
  }

  // Line pairs (x, y, z, x, y, z) for both floor edges, both wall tops, the uprights
  // at bends and ends, and the square end lines across the floor.
  function wallLines(g = groundAt) {
    if (!g) throw new Error('trench: wallLines needs a ground function');
    const v = [];
    const push = (a, b) => v.push(a[0], a[1], a[2], b[0], b[1], b[2]);
    const topAt = (x, y, floor) => {
      // With a batter the wall top sits out from the floor edge by depth * slope.
      return [x, y, Math.max(g(x, y), floor)];
    };
    for (const side of [1, -1]) {
      const edge = offsetLine(side * half);
      const top = benchSlope > 0 ? offsetLine(side * (half + benchSlope * depth)) : edge;
      for (let k = 0; k < n; k++) {
        const len = segs[k].len;
        const steps = Math.max(1, Math.ceil(len / 1));
        let prevF = null, prevT = null;
        for (let j = 0; j <= steps; j++) {
          const f = j / steps;
          const s = edge[k][2] + (edge[k + 1][2] - edge[k][2]) * f;
          const floor = floorAt(s, g);
          const ex = edge[k][0] + (edge[k + 1][0] - edge[k][0]) * f;
          const ey = edge[k][1] + (edge[k + 1][1] - edge[k][1]) * f;
          const tx = top[k][0] + (top[k + 1][0] - top[k][0]) * f;
          const ty = top[k][1] + (top[k + 1][1] - top[k][1]) * f;
          const F = [ex, ey, floor], T = topAt(tx, ty, floor);
          if (prevF) { push(prevF, F); push(prevT, T); }
          if (j === 0 || j === steps) push(F, T);
          prevF = F; prevT = T;
        }
      }
    }
    // Square end lines across the floor.
    for (const s of [0, length2d]) {
      const g0 = s === 0 ? segs[0] : segs[n - 1];
      const [cx, cy] = pointAt(s);
      const z = floorAt(s, g);
      push([cx + g0.nx * half, cy + g0.ny * half, z], [cx - g0.nx * half, cy - g0.ny * half, z]);
    }
    return new Float32Array(v);
  }

  const trench = {
    path: pts, width, depth, benchSlope, length2d, bbox,
    cutHeight, inside, floorAt, chainage, wallLines, pointAt,
    length3dOn, spoilVolumeOn,
  };
  let len3 = null, vol = null;
  Object.defineProperty(trench, 'length3d', {
    enumerable: true,
    get() {
      if (!groundAt) throw new Error('trench: length3d needs groundAt; use length3dOn(g)');
      return len3 ?? (len3 = length3dOn(groundAt));
    },
  });
  Object.defineProperty(trench, 'spoilVolumeM3', {
    enumerable: true,
    get() {
      if (!groundAt) throw new Error('trench: spoilVolumeM3 needs groundAt; use spoilVolumeOn(g)');
      return vol ?? (vol = spoilVolumeOn(groundAt));
    },
  });
  return trench;
}

// Unit normal of the mitre line between two segments: the sum of their directions.
// For a U-turn the sum vanishes, so fall back to the incoming direction.
function bisector(a, b) {
  const x = a.dx + b.dx, y = a.dy + b.dy, l = Math.hypot(x, y);
  return l < 1e-6 ? [a.dx, a.dy] : [x / l, y / l];
}

/**
 * composeGround(groundAt, trenches) -> a new heightAt with every trench cut in.
 * Each trench cuts against the original ground; where they overlap the lowest wins.
 */
export function composeGround(groundAt, trenches) {
  const list = [...trenches];
  return function heightAt(x, y) {
    let z = groundAt(x, y);
    for (const t of list) {
      const b = t.bbox;
      if (x < b.minX || x > b.maxX || y < b.minY || y > b.maxY) continue;
      const c = t.cutHeight(x, y, groundAt);
      if (c < z) z = c;
    }
    return z;
  };
}

// Spoil for vertical walls: integrate along strips that follow each segment from mitre line to mitre line.
// Walls fall on strip edges, so there is no lattice to alias with (tester 4, 26 Sept: worst 0.021 %,
// 73 x faster than the 0.25 m grid, which was up to 4 % out on trenches running along a grid axis).
function spoilStrips(path, width, depth, g, { nt = 6, du = 0.25 } = {}) {
  const p = [];
  for (const q of path) { const l = p[p.length - 1]; if (!l || Math.hypot(q[0] - l[0], q[1] - l[1]) > 1e-6) p.push([+q[0], +q[1]]); }
  const segs = [];
  for (let i = 0; i < p.length - 1; i++) {
    const len = Math.hypot(p[i + 1][0] - p[i][0], p[i + 1][1] - p[i][1]);
    segs.push({ a: p[i], dx: (p[i + 1][0] - p[i][0]) / len, dy: (p[i + 1][1] - p[i][1]) / len, len });
  }
  const bis = (s, t) => { const x = s.dx + t.dx, y = s.dy + t.dy, l = Math.hypot(x, y); return l < 1e-6 ? [s.dx, s.dy] : [x / l, y / l]; };
  let vol = 0;
  segs.forEach((s, i) => {
    const nx = -s.dy, ny = s.dx;
    const mS = i === 0 ? null : bis(segs[i - 1], s), mE = i === segs.length - 1 ? null : bis(s, segs[i + 1]);
    for (let k = 0; k < nt; k++) {
      const t = ((k + 0.5) / nt - 0.5) * width;
      const u0 = mS ? -t * (nx * mS[0] + ny * mS[1]) / (s.dx * mS[0] + s.dy * mS[1]) : 0;
      const u1 = mE ? s.len - t * (nx * mE[0] + ny * mE[1]) / (s.dx * mE[0] + s.dy * mE[1]) : s.len;
      const m = Math.max(1, Math.ceil((u1 - u0) / du)), h = (u1 - u0) / m;
      for (let j = 0; j < m; j++) {
        const u = u0 + (j + 0.5) * h, uc = Math.min(Math.max(u, 0), s.len);
        const x = s.a[0] + s.dx * u + nx * t, y = s.a[1] + s.dy * u + ny * t;
        const floor = g(s.a[0] + s.dx * uc, s.a[1] + s.dy * uc) - depth;
        vol += Math.max(0, g(x, y) - floor) * h;
      }
    }
  });
  return vol * width / nt;
}

LiDAR Cable Sweep

A Python command-line tool that reads cable sweep receipt, cables and 132kV, using SHA-256. It loads cables (`load_cables`), routes meta (`route_meta`) and writes receipt (`write_receipt`).

electricallidar / src/cable_sweep.py · lines 1–357 of 454 · Entry point · pattern ground_from (shared by 2 files)

What it does
It loads cable sweep receipt, cables and 132kV. Defines 21 functions or classes, including to_host, Ground, __init__, h, ground_from. Uses libraries argparse, hashlib, json, math, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'cable'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, 132kV, 33kV.
Inputs & outputs
In: JSON file cable_sweep_receipt.json; JSON file cables.json; JSON file source.json; command-line arguments. Voltage levels named: 132kV, 33kV.
Downstream impact
Used directly by 1 file: Test Cable Sweep (lidar).
What it achieves
How long is a buried cable over real ground, counted two ways? Its code works with 132 kV and 33 kV. It accepts `--tiles`, `--seed` and `--routes`.
Why it matters
Checked by Test Cable Sweep.
Application
lidar · src · Python CLI
Uses
argparse, hashlib, json, math, os, sys, time, numpy
Used by
imported by Test Cable Sweep (sys.path import)
Produces
to_host, Ground, ground_from, min_radius, plan, arc_point, ragged, electron, crossings, positron, draw, pair
Defines here
to_host, Ground, __init__, h, ground_from, min_radius, plan, arc_point, ragged, electron, _F, crossings, _stable_argsort_int, positron, draw, pair, load_cables, sweep
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lidar@2ddf7257e4847e5f387e03aaecbc1cc425c4e387 src/cable_sweep.py:1-357 · blob 2924b82b1abbb83c7f033d20debe2afaaea53b9c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
# SPDX-License-Identifier: Apache-2.0
"""Cable sweep: how long is a buried cable over real ground, counted two ways?

Two channels a case, photons back (the electron/positron pattern of pair_gpu.py and
earthworks_pair.py). Where the channels disagree by more than 0.1 % a photon is COUNTED,
never suppressed, and the worst routes are kept with their places.

A route is a plan polyline (straight, or 1-4 bends) whose corners are filleted with circular
arcs, as web/world/cable-route.mjs does: every corner asks for the minimum bend radius R; a
corner whose legs are too short gets the largest radius its legs allow (a short leg is shared
between its two corners in proportion to what each asks) and is counted as a violation. The
cable lies a fixed depth below the ground directly under the centreline (0.9 m at 33 kV,
1.05 m at 132 kV), so its slope is the ground's slope along the route.

R comes from cables.json (graphics-engines-open-source-world/web/world/data): the cable of the
voltage and conductor size (1000 mm2), a verified OD preferred, times the governing (largest)
installation multiple listed for that voltage.

  electron   dense sampling: the filleted centreline sampled every <= 0.05 m of chainage, each
             sample dropped onto the bilinear ground, the 3D chords summed.
  positron   analytic plan length (straights plus r |theta|) plus a vertical correction
             integral of (sqrt(1 + g^2) - 1) ds, g = dz/ds. Every piece is cut exactly where it
             crosses a grid line; inside one cell a straight's slope is linear in s, so its
             integral is closed form; an arc's is 6-point Gauss-Legendre on a smooth integrand.

Ground is the bilinear surface of the float64 source (source.npy, SW origin in source.json).
Seeded (default_rng), bounded (--routes or --seconds, whichever first). Witness: the first
routes recomputed in NumPy on the CPU, agreeing with the card within 1e-9.

    E:/swarm/gpu-bench/venv/Scripts/python.exe src/cable_sweep.py --tiles DIR
      [--routes 40000] [--seconds 60] [--seed N] [--cpu] [--cables PATH]
"""
import argparse, hashlib, json, math, os, sys, time
import numpy as np

try:
    import cupy as cp
    cp.cuda.runtime.getDeviceCount()
except Exception:  # no card, no CuPy: the same arithmetic runs in NumPy and says so
    cp = None

SEED = 20260926
TOL = 1e-3            # relative disagreement that makes a photon (0.1 %)
DS_E = 0.05           # electron sampling step along chainage (m)
WIT_TOL = 1e-9
KEEP = 8
NB = 4                # most bends a route has
NP = 2 * NB + 1       # pieces a route: line, arc, line, ... line
RECEIPT = "cable_sweep_receipt.json"
CSA = 1000
DEPTH = {33: 0.9, 132: 1.05}
CABLES = os.path.join(os.path.expanduser("~"), "Documents", "GitHub", "graphics-engines-open-source-world",
                      "web", "world", "data", "cables.json")
GL_X, GL_W = np.polynomial.legendre.leggauss(6)


# ---------------------------------------------------------------- ground (as earthworks_pair.py)
def to_host(a):
    return cp.asnumpy(a) if cp is not None and isinstance(a, cp.ndarray) else np.asarray(a)


class Ground:
    """Bilinear ground in local metres (x east, y north from the source's SW corner)."""
    def __init__(self, grid, oe, on, sp, xp):
        self.xp, self.g, self.oe, self.on, self.sp = xp, xp.asarray(grid), oe, on, sp
        self.ny, self.nx = grid.shape

    def h(self, x, y):
        xp, g = self.xp, self.g
        gx, gy = x / self.sp, y / self.sp
        j = xp.clip(xp.floor(gx), 0, self.nx - 2).astype(xp.int64)
        i = xp.clip(xp.floor(gy), 0, self.ny - 2).astype(xp.int64)
        fx, fy = gx - j, gy - i
        a = g[i, j] + (g[i, j + 1] - g[i, j]) * fx
        b = g[i + 1, j] + (g[i + 1, j + 1] - g[i + 1, j]) * fx
        return a + (b - a) * fy


def ground_from(tiles_dir, xp):
    """source.npy (float64) with its SW origin and spacing from source.json beside it."""
    grid = np.load(os.path.join(tiles_dir, "source.npy")).astype(np.float64)
    meta = json.load(open(os.path.join(tiles_dir, "source.json"), encoding="utf-8"))
    pick = lambda *ks: next((meta[k] for k in ks if k in meta), None)
    oe, on = pick("origin_e_m", "origin_e", "sw_e", "x0"), pick("origin_n_m", "origin_n", "sw_n", "y0")
    sp = pick("spacing_m", "spacing", "cell_m", "res_m")
    if oe is None or on is None or sp is None:
        raise ValueError(f"{tiles_dir}/source.json: need SW origin and spacing_m")
    if str(meta.get("rows", "south_to_north")).startswith("north"):
        grid = grid[::-1]
    return Ground(grid, float(oe), float(on), float(sp), xp)


# ---------------------------------------------------------------- bend rule
def min_radius(cables, kv, csa=CSA, when="installation"):
    """Governing minimum bend radius (m) for a single-core cable of kv and csa, with its sources."""
    cands = [c for c in cables["cables"] if c["voltage_kv"] == kv and c["csa_mm2"] == csa]
    if not cands:
        raise ValueError(f"cables.json: no {kv} kV {csa} mm2 cable")
    cab = sorted(cands, key=lambda c: (c.get("od_status") != "verified", "spec" in c["id"]))[0]
    rules = [r for r in cables["rules"] if r["voltage_kv"] == kv and r["when"] == when and r.get("multiple_of_od")]
    if not rules:
        raise ValueError(f"cables.json: no {when} rule at {kv} kV")
    rule = max(rules, key=lambda r: r["multiple_of_od"])
    return dict(voltage_kv=kv, cable_id=cab["id"], od_mm=cab["od_mm"], od_status=cab.get("od_status"),
                multiple_of_od=rule["multiple_of_od"], construction=rule["construction"], when=when,
                rule_status=rule.get("status"), rule_source=rule["source"],
                radius_m=rule["multiple_of_od"] * cab["od_mm"] / 1000.0, depth_m=DEPTH.get(kv))


# ---------------------------------------------------------------- plan geometry (host, NumPy)
def plan(x0, y0, h0, legs, turns, R):
    """Filleted plan geometry of n routes.

    x0, y0, h0 (n,), legs (n, NB+1) leg lengths (0 past the last), turns (n, NB) signed radians
    (0 past the last bend), R (n,) requested radius. Returns pieces (n, NP) with start x, y,
    heading, curvature and length, plus fitted radii, violations and the analytic plan length.
    """
    n = len(x0)
    tturn = np.tan(np.abs(turns) / 2)
    want = np.zeros((n, NB + 2)); want[:, 1:NB + 1] = R[:, None] * tturn
    cap = want.copy()
    for k in range(NB + 1):
        t0, t1, L = want[:, k], want[:, k + 1], legs[:, k]
        over = t0 + t1 > L
        f0 = np.where(t0 + t1 > 0, t0 / np.where(t0 + t1 > 0, t0 + t1, 1), 0.5)
        cap[:, k] = np.where(over, np.minimum(cap[:, k], L * f0), cap[:, k])
        cap[:, k + 1] = np.where(over, np.minimum(cap[:, k + 1], L * (1 - f0)), cap[:, k + 1])
    t = cap[:, 1:NB + 1]
    bend = turns != 0
    r = np.where(bend, t / np.where(bend, tturn, 1), 0.0)
    viol = bend & (r < R[:, None] * (1 - 1e-9))
    P = {k: np.zeros((n, NP)) for k in ("x", "y", "h", "kap", "L")}
    x, y, h = x0.astype(float).copy(), y0.astype(float).copy(), h0.astype(float).copy()
    tpad = np.concatenate([np.zeros((n, 1)), t, np.zeros((n, 1))], 1)
    for k in range(NB + 1):
        Ll = np.maximum(legs[:, k] - tpad[:, k] - tpad[:, k + 1], 0.0)
        P["x"][:, 2 * k], P["y"][:, 2 * k], P["h"][:, 2 * k], P["L"][:, 2 * k] = x, y, h, Ll
        x, y = x + Ll * np.cos(h), y + Ll * np.sin(h)
        if k < NB:
            th, rk = turns[:, k], r[:, k]
            La = rk * np.abs(th)
            kap = np.where(rk > 0, np.sign(th) / np.where(rk > 0, rk, 1), 0.0)
            P["x"][:, 2 * k + 1], P["y"][:, 2 * k + 1], P["h"][:, 2 * k + 1] = x, y, h
            P["kap"][:, 2 * k + 1], P["L"][:, 2 * k + 1] = kap, La
            x, y = arc_point(x, y, h, kap, La, np)
            h = h + th
    P["S0"] = np.concatenate([np.zeros((n, 1)), np.cumsum(P["L"], 1)[:, :-1]], 1)
    P["L2d"] = P["L"].sum(1)
    return P, r, viol


def arc_point(x, y, h, kap, u, xp):
    """Point at chainage u along a piece starting at (x, y) heading h with curvature kap."""
    half = kap * u / 2
    ch = u * xp.sinc(half / np.pi)          # chord length; u on a straight
    return x + ch * xp.cos(h + half), y + ch * xp.sin(h + half)


def ragged(xp, counts):
    """Owner and local index of a ragged range: counts (m,) -> (owner, j) of length counts.sum()."""
    ends = xp.cumsum(counts)
    tot = int(ends[-1]) if len(counts) else 0
    k = xp.arange(tot)
    owner = xp.searchsorted(ends, k, side="right")
    return owner, k - (ends - counts)[owner]


# ---------------------------------------------------------------- electron
def electron(P, depth, G, ds=DS_E):
    """3D length from dense samples, and the 2D chord sum (a plan check), per route."""
    xp = G.xp
    n = len(P["L2d"])
    L2 = xp.asarray(P["L2d"])
    ns = xp.ceil(L2 / ds).astype(xp.int64) + 1
    own, j = ragged(xp, ns)
    s = j * (L2 / (ns - 1))[own]
    S0 = xp.asarray(P["S0"])[own]
    pid = (s[:, None] >= S0[:, 1:]).sum(1)
    g = lambda k: xp.asarray(P[k])[own, pid]
    u = s - S0[xp.arange(own.size), pid]
    x, y = arc_point(g("x"), g("y"), g("h"), g("kap"), u, xp)
    z = G.h(x, y) - xp.asarray(depth)[own]
    same = own[1:] == own[:-1]
    dx, dy, dz = x[1:] - x[:-1], y[1:] - y[:-1], z[1:] - z[:-1]
    d2 = xp.where(same, xp.sqrt(dx * dx + dy * dy), 0)
    d3 = xp.where(same, xp.sqrt(dx * dx + dy * dy + dz * dz), 0)
    L3 = to_host(xp.bincount(own[:-1], weights=d3, minlength=n))
    C2 = to_host(xp.bincount(own[:-1], weights=d2, minlength=n))
    return L3, C2, int(own.size)


# ---------------------------------------------------------------- positron
def _F(u, xp):
    return (u * xp.sqrt(1 + u * u) + xp.arcsinh(u)) / 2


def crossings(P, G):
    """Breakpoints (piece id, s) where each piece meets a grid line, plus its two ends."""
    xp, sp = G.xp, G.sp
    flat = {k: xp.asarray(P[k]).ravel() for k in ("x", "y", "h", "kap", "L")}
    live = xp.nonzero(flat["L"] > 0)[0]
    x0, y0, h0, kap, L = (flat[k][live] for k in ("x", "y", "h", "kap", "L"))
    arc = kap != 0
    PID, S = [live, live], [xp.zeros_like(L), L]
    # straights: s = (k sp - x0) / ux between the ends
    ln = xp.nonzero(~arc)[0]
    x1, y1 = arc_point(x0[ln], y0[ln], h0[ln], kap[ln], L[ln], xp)
    for a0, a1, c in ((x0[ln], x1, xp.cos(h0[ln])), (y0[ln], y1, xp.sin(h0[ln]))):
        lo, hi = xp.floor(xp.minimum(a0, a1) / sp), xp.floor(xp.maximum(a0, a1) / sp)
        o, j = ragged(xp, (hi - lo).astype(xp.int64))
        s = ((lo[o] + 1 + j) * sp - a0[o]) / c[o]
        PID.append(live[ln][o]); S.append(s)
    # arcs: polar angle alpha = alpha0 + kap s about the centre
    ac = xp.nonzero(arc)[0]
    ka, xa, ya, ha, La = kap[ac], x0[ac], y0[ac], h0[ac], L[ac]
    r = 1 / xp.abs(ka)
    cx, cy = xa - xp.sin(ha) / ka, ya + xp.cos(ha) / ka
    al0 = xp.arctan2(ya - cy, xa - cx)
    sg = xp.sign(ka)
    for c0, is_x in ((cx, True), (cy, False)):
        lo, hi = xp.floor((c0 - r) / sp), xp.floor((c0 + r) / sp)
        o, j = ragged(xp, (hi - lo).astype(xp.int64))
        v = xp.clip(((lo[o] + 1 + j) * sp - c0[o]) / r[o], -1, 1)
        base = xp.arccos(v) if is_x else xp.arcsin(v)
        for alpha in ((base, -base) if is_x else (base, np.pi - base)):
            s = xp.mod((alpha - al0[o]) * sg[o], 2 * np.pi) * r[o]
            PID.append(live[ac][o]); S.append(s)
    pid, s = xp.concatenate(PID), xp.concatenate(S)
    keep = (s >= 0) & (s <= flat["L"][pid])
    pid, s = pid[keep], s[keep]
    o1 = xp.argsort(s, kind="stable") if xp is np else xp.argsort(s)
    pid, s = pid[o1], s[o1]
    o2 = xp.argsort(pid, kind="stable") if xp is np else _stable_argsort_int(pid, xp)
    return pid[o2], s[o2], flat


def _stable_argsort_int(a, xp):
    """Stable argsort of a non-negative int array on CuPy: sort (a, position) packed in one int64."""
    pos = xp.arange(a.size, dtype=xp.int64)
    return xp.argsort(a.astype(xp.int64) * (1 << 34) + pos) if a.size < (1 << 34) else xp.argsort(a)


def positron(P, G):
    """Analytic plan length plus an exact per-cell vertical correction, per route."""
    xp, sp = G.xp, G.sp
    n = len(P["L2d"])
    pid, s, f = crossings(P, G)
    same = pid[1:] == pid[:-1]
    a, b, p = s[:-1][same], s[1:][same], pid[:-1][same]
    dl = b - a
    x0, y0, h0, kap = f["x"][p], f["y"][p], f["h"][p], f["kap"][p]
    # the cell of each interval, from its middle
    xm, ym = arc_point(x0, y0, h0, kap, (a + b) / 2, xp)
    j = xp.clip(xp.floor(xm / sp), 0, G.nx - 2).astype(xp.int64)
    i = xp.clip(xp.floor(ym / sp), 0, G.ny - 2).astype(xp.int64)
    g = G.g
    A = g[i, j]; B = g[i, j + 1] - A; C = g[i + 1, j] - A; D = g[i + 1, j + 1] - g[i + 1, j] - g[i, j + 1] + A
    # straights: dz/ds = p0 + q s inside one cell, integral closed form
    ln = kap == 0
    xs, ys = arc_point(x0, y0, h0, kap, a, xp)
    fx, fy = xs / sp - j, ys / sp - i
    ux, uy = xp.cos(h0), xp.sin(h0)
    p0 = (B * ux + C * uy + D * (ux * fy + uy * fx)) / sp
    q = 2 * D * ux * uy / (sp * sp)
    qs = xp.where(xp.abs(q * dl) > 1e-7, q, 1.0)
    exact = (_F(p0 + q * dl, xp) - _F(p0, xp)) / qs - dl
    gm = p0 + q * dl / 2
    small = gm * gm / (1 + xp.sqrt(1 + gm * gm)) * dl
    corr = xp.where(ln, xp.where(xp.abs(q * dl) > 1e-7, exact, small), 0.0)
    # arcs: 6-point Gauss-Legendre with the cell's gradient
    ai = xp.nonzero(~ln)[0]
    if ai.size:
        gx, gw = xp.asarray(GL_X), xp.asarray(GL_W)
        aa, bb = a[ai], b[ai]
        sq = (aa + bb)[:, None] / 2 + (bb - aa)[:, None] / 2 * gx[None]
        X, Y = arc_point(x0[ai, None], y0[ai, None], h0[ai, None], kap[ai, None], sq, xp)
        FX, FY = X / sp - j[ai, None], Y / sp - i[ai, None]
        hx = (B[ai, None] + D[ai, None] * FY) / sp
        hy = (C[ai, None] + D[ai, None] * FX) / sp
        ph = h0[ai, None] + kap[ai, None] * sq
        gg = hx * xp.cos(ph) + hy * xp.sin(ph)
        val = gg * gg / (1 + xp.sqrt(1 + gg * gg))
        corr[ai] = (val * gw[None]).sum(1) * (bb - aa) / 2
    V = to_host(xp.bincount(p // NP, weights=corr, minlength=n))
    return P["L2d"] + V, V, int(dl.size)


# ---------------------------------------------------------------- sweep
def draw(rng, n, G, rule, margin=3.0, leg=(3.0, 300.0)):
    """n seeded routes wholly inside the site: 0-4 bends (uniform), 33 or 132 kV (half each)."""
    W, H = G.sp * (G.nx - 1), G.sp * (G.ny - 1)
    out = {k: [] for k in ("x0", "y0", "h0", "legs", "turns", "kv")}
    have = 0
    while have < n:
        m = 2 * (n - have) + 16
        nb = rng.integers(0, NB + 1, m)
        kv = np.where(rng.random(m) < 0.5, 33, 132)
        legs = np.exp(rng.uniform(math.log(leg[0]), math.log(leg[1]), (m, NB + 1)))
        legs[np.arange(NB + 1)[None] > nb[:, None]] = 0
        turns = rng.uniform(np.radians(5), np.radians(150), (m, NB)) * rng.choice([-1, 1], (m, NB))
        turns[np.arange(NB)[None] >= nb[:, None]] = 0
        x0, y0, h0 = rng.uniform(margin, W - margin, m), rng.uniform(margin, H - margin, m), rng.uniform(0, 2 * np.pi, m)
        hv = h0[:, None] + np.concatenate([np.zeros((m, 1)), np.cumsum(turns, 1)], 1)
        vx = x0[:, None] + np.concatenate([np.zeros((m, 1)), np.cumsum(legs * np.cos(hv), 1)], 1)
        vy = y0[:, None] + np.concatenate([np.zeros((m, 1)), np.cumsum(legs * np.sin(hv), 1)], 1)
        ok = (vx.min(1) > margin) & (vy.min(1) > margin) & (vx.max(1) < W - margin) & (vy.max(1) < H - margin)
        ok &= np.cumsum(ok) <= n - have
        for k, v in (("x0", x0), ("y0", y0), ("h0", h0), ("legs", legs), ("turns", turns), ("kv", kv)):
            out[k].append(v[ok])
        have += int(ok.sum())
    D = {k: np.concatenate(v) for k, v in out.items()}
    D["R"] = np.where(D["kv"] == 33, rule[33]["radius_m"], rule[132]["radius_m"])
    D["depth"] = np.where(D["kv"] == 33, rule[33]["depth_m"], rule[132]["depth_m"])
    return D


def pair(D, G):
    P, r, viol = plan(D["x0"], D["y0"], D["h0"], D["legs"], D["turns"], D["R"])
    e3, c2, ns = electron(P, D["depth"], G)
    p3, corr, ni = positron(P, G)
    rel = np.abs(e3 - p3) / np.maximum(np.maximum(e3, p3), 1e-12)
    return dict(P=P, r=r, viol=viol, e3=e3, c2=c2, p3=p3, corr=corr, rel=rel, samples=ns, intervals=ni)


def load_cables(path):
    return json.load(open(path, encoding="utf-8"))


def sweep(tiles_dir, seed=SEED, routes=40000, seconds=60.0, batch=2000, use_gpu=True, witness=32,
          cables=None, cables_path=CABLES):
    t0 = time.perf_counter()
    xp = cp if (use_gpu and cp is not None) else np
    device = cp.cuda.runtime.getDeviceProperties(0)["name"].decode() if xp is not np else "cpu (numpy)"
    cables = cables if cables is not None else load_cables(cables_path)
    rule = {kv: min_radius(cables, kv) for kv in (33, 132)}
    G = ground_from(tiles_dir, xp)
    rng = np.random.default_rng(seed)
    cols = {k: [] for k in ("kv", "nb", "L2d", "c2", "e3", "p3", "corr", "rel", "nviol", "rmin")}
    meta, samples, intervals, stopped, first = [], 0, 0, "routes", None
    while sum(map(len, cols["kv"])) < routes:
        if cols["kv"] and time.perf_counter() - t0 > seconds:
            stopped = "seconds"; break
        D = draw(rng, min(batch, routes - sum(map(len, cols["kv"]))), G, rule)
        if first is None:
            first = {k: v[:witness].copy() for k, v in D.items()}
        R = pair(D, G)
        samples += R["samples"]; intervals += R["intervals"]
        bend = D["turns"] != 0
        for k, v in (("kv", D["kv"]), ("nb", bend.sum(1)), ("L2d", R["P"]["L2d"]), ("c2", R["c2"]), ("e3", R["e3"]),
                     ("p3", R["p3"]), ("corr", R["corr"]), ("rel", R["rel"]), ("nviol", R["viol"].sum(1)),
                     ("rmin", np.where(bend, R["r"], np.inf).min(1))):
            cols[k].append(v)
        top = np.argsort(-R["rel"])[:KEEP]
        meta += [dict(route_meta(D, R, i, G), rel=float(R["rel"][i])) for i in top]
        if xp is not np:
            cp.cuda.Stream.null.synchronize()
    C = {k: np.concatenate(v) for k, v in cols.items()}