GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / particle-physics-drawing-engine / measurements

Particles and 5 more files

A Python command-line tool in the tools folder of Particle Physics Drawing Engine that works with theta int (`theta_int`) and cmd layer (`cmd_layer`) (units: kV, kW), using SHA-256.

579 lines of Python and JavaScript from particle-physics-drawing-engine, in 6 files. Topic: Kuiper, cosmos and drawing engines. Section 1556 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. Coax Field Test test · particle-physics-drawing-engine / measurements/coax-field-test.mjs lines 1–154
  2. Exactness transform · particle-physics-drawing-engine / measurements/exactness.mjs lines 1–74
  3. Fault electrical · particle-physics-drawing-engine / tools/fault.py lines 1–70
  4. Geometry storage · particle-physics-drawing-engine / tools/geometry.py lines 1–74
  5. Particles storage · particle-physics-drawing-engine / tools/particles.py lines 1–180
  6. Png storage · particle-physics-drawing-engine / tools/png.py lines 1–27

Coax Field Test

A JavaScript module in the measurements folder of Particle Physics Drawing Engine that tests coax field result surface ring and cables.

testparticle-physics-drawing-engine / measurements/coax-field-test.mjs · lines 1–154 of 154 · Not reached from any entry point (candidate for review) · pattern solve (shared by 72 files)

What it does
It tests coax field result surface ring and cables. Defines 8 functions or classes, including Vexact, Eexact, gridSolve, solve5, waferSolve. Uses libraries node:fs. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage field_execution (path word 'field'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: cables.
Inputs & outputs
Out: JSON file coax-field-result-v2-surface-ring.json.
What it achieves
It is built from the vexact class (`Vexact`), the eexact class (`Eexact`) and the grid solve helper (`gridSolve`). Can a field of wafer particles do real electrostatics? It writes `./coax-field-result-v2-surface-ring.json`.
Why it matters
No other file in the estate was found to import it.
Application
particle-physics-drawing-engine · measurements · JavaScript module
Uses
node:fs
Used by
none found
Produces
Vexact, Eexact, gridSolve, solve5, waferSolve, cell, mul, dot
Defines here
Vexact, Eexact, gridSolve, solve5, waferSolve, cell, mul, dot
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 measurements/coax-field-test.mjs:1-154 · blob 532f50a58d69e9dc02eec0ce569a30291a4e5a93 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
/* coax-field-test.mjs — Assessor 1, 18 Sept 2026.
 * Can a field of wafer particles do real electrostatics?  A test that can fail.
 *
 * Problem: coaxial cable, inner conductor radius r0 at V = 1, earthed sheath radius R at V = 0,
 * one homogeneous dielectric. Laplace's equation. Analytic answer:
 *     V(r) = ln(R/r) / ln(R/r0),     E(r) = V0 / (r ln(R/r0)).
 * Normalised units throughout (V0 = 1, r0 = 1, R = 2.5). No manufacturer data. Not a cable design.
 *
 * Method A: 5-point finite differences on a square grid, SOR. (The textbook method.)
 * Method B: the wafer's own law. Nodes at r = s*sqrt(key), theta = key*GOLDEN (lib.mjs line 11, 19).
 *           Meshless generalised finite differences: weighted least-squares second-order Taylor fit
 *           over the nearest neighbours gives Laplacian weights; sparse system solved by BiCGSTAB.
 *           Conductor = every key below k0; sheath = every key above K. With K = 250,174 the sheath
 *           is the rim of today's wafer.
 * Exit codes: 0 pass, 1 fail, 3 examined nothing.
 */
const GOLDEN = Math.PI * (3 - Math.sqrt(5));
const RATIO = 2.5, LN = Math.log(RATIO);
const Vexact = r => r <= 1 ? 1 : r >= RATIO ? 0 : Math.log(RATIO / r) / LN;
const Eexact = r => 1 / (r * LN);

/* ---------- Method A: square grid, SOR ---------- */
function gridSolve(n) {               /* n cells across the half-width R */
  const h = RATIO / n, W = 2 * n + 1, u = new Float64Array(W * W), fixed = new Uint8Array(W * W);
  for (let j = 0; j < W; j++) for (let i = 0; i < W; i++) {
    const x = (i - n) * h, y = (j - n) * h, r = Math.hypot(x, y), id = j * W + i;
    if (r <= 1) { u[id] = 1; fixed[id] = 1; } else if (r >= RATIO || i === 0 || j === 0 || i === W - 1 || j === W - 1) { u[id] = 0; fixed[id] = 1; }
    else u[id] = Vexact(r) * 0 + 0.5;
  }
  const omega = 2 / (1 + Math.sin(Math.PI / W)); let sweeps = 0, res = 1;
  while (res > 1e-10 && sweeps < 200000) {
    res = 0;
    for (let j = 1; j < W - 1; j++) for (let i = 1; i < W - 1; i++) {
      const id = j * W + i; if (fixed[id]) continue;
      const d = 0.25 * (u[id - 1] + u[id + 1] + u[id - W] + u[id + W]) - u[id];
      u[id] += omega * d; if (Math.abs(d) > res) res = Math.abs(d);
    }
    sweeps++;
  }
  let maxV = 0, maxE = 0, maxEsurf = 0, free = 0, nE = 0;
  for (let j = 1; j < W - 1; j++) for (let i = 1; i < W - 1; i++) {
    const id = j * W + i; if (fixed[id]) continue; free++;
    const x = (i - n) * h, y = (j - n) * h, r = Math.hypot(x, y);
    maxV = Math.max(maxV, Math.abs(u[id] - Vexact(r)));
    if (fixed[id - 1] || fixed[id + 1] || fixed[id - W] || fixed[id + W]) continue;   /* E only where the central difference is clean */
    const ex = -(u[id + 1] - u[id - 1]) / (2 * h), ey = -(u[id + W] - u[id - W]) / (2 * h);
    const er = (ex * x + ey * y) / r, rel = Math.abs(er - Eexact(r)) / Eexact(r);
    nE++; maxE = Math.max(maxE, rel); if (r < 1 + 3 * h) maxEsurf = Math.max(maxEsurf, rel);
  }
  return { method: 'A square grid', free, h, sweeps, residual: res, maxVerr: maxV, maxErelErr: maxE, maxErelErrNearConductor: maxEsurf, nE };
}

/* ---------- Method B: phyllotaxis nodes, meshless GFDM ---------- */
function solve5(A, b) {               /* 5x5 Gaussian elimination with pivoting */
  const n = 5, M = A.map((r, i) => [...r, b[i]]);
  for (let c = 0; c < n; c++) {
    let p = c; for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
    if (Math.abs(M[p][c]) < 1e-300) return null; [M[c], M[p]] = [M[p], M[c]];
    for (let r = 0; r < n; r++) if (r !== c) { const f = M[r][c] / M[c][c]; for (let k = c; k <= n; k++) M[r][k] -= f * M[c][k]; }
  }
  return M.map((r, i) => r[n] / r[i]);
}
function waferSolve(K, NB = 14) {
  const k0 = Math.round(K / (RATIO * RATIO)), s = 1 / Math.sqrt(k0);      /* so that key k0 sits at r = 1 and key K at r = 2.5 */
  const hbar0 = s * Math.sqrt(Math.PI), GAP = 0.4 * hbar0;
  /* v2: the surfaces are made of nodes. A ring of fixed nodes sits exactly on r = 1 (V = 1) and on r = 2.5 (V = 0),
     spaced one mean spacing apart. Wafer particles inside the conductor, outside the sheath, or closer than 0.4 spacings
     to a surface take no part. Every other particle keeps its wafer place: r = s*sqrt(key), theta = key*GOLDEN. */
  const xs = [], ys = [], fixedV = [];
  for (let k = k0; k <= K; k++) { const r = s * Math.sqrt(k); if (r > 1 + GAP && r < RATIO - GAP) { const t = k * GOLDEN; xs.push(r * Math.cos(t)); ys.push(r * Math.sin(t)); fixedV.push(-1); } }
  for (const [rad, val] of [[1, 1], [RATIO, 0]]) { const m = Math.ceil(2 * Math.PI * rad / hbar0); for (let q = 0; q < m; q++) { const t = 2 * Math.PI * q / m; xs.push(rad * Math.cos(t)); ys.push(rad * Math.sin(t)); fixedV.push(val); } }
  const N = xs.length, X = Float64Array.from(xs), Y = Float64Array.from(ys), Rr = new Float64Array(N);
  for (let i = 0; i < N; i++) Rr[i] = Math.hypot(X[i], Y[i]);
  const hbar = s * Math.sqrt(Math.PI);                                   /* mean spacing: one node per pi*s^2 of area */
  /* spatial hash */
  const cs = 2.2 * hbar, G = Math.ceil(2 * (RATIO * 1.05) / cs) + 2, off = G / 2, head = new Int32Array(G * G).fill(-1), next = new Int32Array(N);
  const cell = i => (Math.floor(Y[i] / cs + off)) * G + Math.floor(X[i] / cs + off);
  for (let i = 0; i < N; i++) { const c = cell(i); next[i] = head[c]; head[c] = i; }
  const free = []; const idx = new Int32Array(N).fill(-1);
  for (let i = 0; i < N; i++) { if (fixedV[i] < 0) { idx[i] = free.length; free.push(i); } }
  const F = free.length; if (!F) return null;
  const nbr = new Int32Array(F * NB), wL = new Float64Array(F * NB), wGx = new Float64Array(F * NB), wGy = new Float64Array(F * NB);
  let negW = 0;
  for (let f = 0; f < F; f++) {
    const i = free[f], cx = Math.floor(X[i] / cs + off), cy = Math.floor(Y[i] / cs + off), cand = [];
    for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) { let j = head[(cy + dy) * G + cx + dx]; while (j >= 0) { if (j !== i) { const d2 = (X[j] - X[i]) ** 2 + (Y[j] - Y[i]) ** 2; cand.push([d2, j]); } j = next[j]; } }
    cand.sort((a, b) => a[0] - b[0]); if (cand.length < NB) throw new Error('too few neighbours');
    const rad2 = cand[NB - 1][0] * 1.21;
    const A = [0, 0, 0, 0, 0].map(() => [0, 0, 0, 0, 0]), P = [];
    for (let m = 0; m < NB; m++) {
      const j = cand[m][1], dx = X[j] - X[i], dy = Y[j] - Y[i], q = cand[m][0] / rad2, w = (1 - q) ** 2;   /* compact weight */
      const p = [dx, dy, dx * dx / 2, dx * dy, dy * dy / 2]; P.push([p, w, j]);
      for (let a = 0; a < 5; a++) for (let b = 0; b < 5; b++) A[a][b] += w * p[a] * p[b];
    }
    /* Laplacian weight of neighbour m = w * p . (A^-1 (e3 + e5));  gradient likewise with e1, e2 */
    const cL = solve5(A, [0, 0, 1, 0, 1]), cX = solve5(A, [1, 0, 0, 0, 0]), cY = solve5(A, [0, 1, 0, 0, 0]);
    for (let m = 0; m < NB; m++) {
      const [p, w, j] = P[m]; let l = 0, gx = 0, gy = 0; for (let a = 0; a < 5; a++) { l += p[a] * cL[a]; gx += p[a] * cX[a]; gy += p[a] * cY[a]; }
      nbr[f * NB + m] = j; wL[f * NB + m] = w * l; wGx[f * NB + m] = w * gx; wGy[f * NB + m] = w * gy; if (w * l < 0) negW++;
    }
  }
  /* system: sum_m wL (u_j - u_i) = 0 for free i; u known on fixed nodes. */
  const uAll = new Float64Array(N); for (let i = 0; i < N; i++) uAll[i] = Math.max(0, fixedV[i]);
  const diag = new Float64Array(F), rhs = new Float64Array(F);
  for (let f = 0; f < F; f++) { let d = 0; for (let m = 0; m < NB; m++) { const w = wL[f * NB + m], j = nbr[f * NB + m]; d -= w; if (idx[j] < 0) rhs[f] -= w * uAll[j]; } diag[f] = d; }
  const mul = (x, out) => { for (let f = 0; f < F; f++) { let a = diag[f] * x[f]; for (let m = 0; m < NB; m++) { const j = idx[nbr[f * NB + m]]; if (j >= 0) a += wL[f * NB + m] * x[j]; } out[f] = a / diag[f]; } };   /* Jacobi-scaled rows */
  const b = rhs.map((v, f) => v / diag[f]);
  const dot = (a, c) => { let t = 0; for (let i = 0; i < F; i++) t += a[i] * c[i]; return t; };
  /* BiCGSTAB */
  const x = new Float64Array(F).fill(0.5), r = new Float64Array(F), rh = new Float64Array(F), p = new Float64Array(F), v = new Float64Array(F), sV = new Float64Array(F), t = new Float64Array(F);
  mul(x, r); for (let i = 0; i < F; i++) { r[i] = b[i] - r[i]; rh[i] = r[i]; }
  let rho = 1, alpha = 1, om = 1, it = 0; const bn = Math.sqrt(dot(b, b)); let rel = Math.sqrt(dot(r, r)) / bn;
  while (rel > 1e-11 && it < 20000) {
    const rhoN = dot(rh, r), beta = (rhoN / rho) * (alpha / om); rho = rhoN;
    for (let i = 0; i < F; i++) p[i] = r[i] + beta * (p[i] - om * v[i]);
    mul(p, v); alpha = rho / dot(rh, v);
    for (let i = 0; i < F; i++) sV[i] = r[i] - alpha * v[i];
    mul(sV, t); om = dot(t, sV) / dot(t, t);
    for (let i = 0; i < F; i++) { x[i] += alpha * p[i] + om * sV[i]; r[i] = sV[i] - om * t[i]; }
    rel = Math.sqrt(dot(r, r)) / bn; it++;
    if (!Number.isFinite(rel)) break;
  }
  for (let f = 0; f < F; f++) uAll[free[f]] = x[f];
  let maxV = 0, maxE = 0, maxEsurf = 0, sumE2 = 0, nE = 0;
  for (let f = 0; f < F; f++) {
    const i = free[f], rr = Rr[i]; maxV = Math.max(maxV, Math.abs(x[f] - Vexact(rr)));
    let gx = 0, gy = 0, clean = true;
    for (let m = 0; m < NB; m++) { const j = nbr[f * NB + m]; if (idx[j] < 0) clean = false; gx += wGx[f * NB + m] * (uAll[j] - x[f]); gy += wGy[f * NB + m] * (uAll[j] - x[f]); }
    /* v2: surface nodes lie on the true surface, so every stencil is smooth and every free node is judged, including those touching the conductor */
    const er = -(gx * X[i] + gy * Y[i]) / rr, e = Math.abs(er - Eexact(rr)) / Eexact(rr);
    nE++; sumE2 += e * e; maxE = Math.max(maxE, e); if (rr < 1 + 4 * hbar) maxEsurf = Math.max(maxEsurf, e);
  }
  return { method: 'B2 wafer law + surface rings (meshless GFDM)', K, k0, free: F, h: hbar, neighbours: NB, negativeLaplacianWeights: negW, iterations: it, residual: rel, maxVerr: maxV, maxErelErr: maxE, rmsErelErr: Math.sqrt(sumE2 / Math.max(1, nE)), maxErelErrNearConductor: maxEsurf, nE };
}

/* ---------- run ---------- */
const out = { date: new Date().toISOString(), problem: 'coax, V0=1, r0=1, R=2.5, homogeneous dielectric, normalised units', runs: [] };
let examined = 0, fail = false;
for (const n of [160]) { const t0 = Date.now(); const r = gridSolve(n); r.ms = Date.now() - t0; out.runs.push(r); examined += r.free; console.log(JSON.stringify(r)); }
for (const K of [2500, 25000, 250174]) { const t0 = Date.now(); const r = waferSolve(K); if (!r) continue; r.ms = Date.now() - t0; out.runs.push(r); examined += r.free; console.log(JSON.stringify(r)); }
if (!examined) { console.error('EXAMINED NOTHING'); process.exit(3); }
/* pass criteria, declared before the run: at the finest level of each method, potential within 1 % of V0 everywhere,
   field within 2 % on clean stencils, solver residual below 1e-8, and error must fall as the node count rises. */
const A = out.runs.filter(r => r.method.startsWith('A')), B = out.runs.filter(r => r.method.startsWith('B'));
/* v2 judges the wafer-law method only. Grid A keeps its staircase surface as a labelled reference; it FAILED in v1 and is not re-judged here. */
for (const S of [B]) {
  const last = S[S.length - 1];
  if (!(last.residual < 1e-8)) { fail = true; console.log('FAIL residual', last.method); }
  if (!(last.maxVerr < 0.01)) { fail = true; console.log('FAIL potential', last.method); }
  if (!(last.maxErelErr < 0.02)) { fail = true; console.log('FAIL field', last.method); }
  if (!(last.maxVerr < S[0].maxVerr)) { fail = true; console.log('FAIL no convergence', last.method); }
}
out.verdict = fail ? 'FAIL' : 'PASS';
import('node:fs').then(fs => { fs.writeFileSync(new URL('./coax-field-result-v2-surface-ring.json', import.meta.url), JSON.stringify(out, null, 1)); console.log(out.verdict); process.exit(fail ? 1 : 0); });

Exactness

A JavaScript module in the measurements folder of Particle Physics Drawing Engine that works with theta true (`thetaTrue`) and int frac32 (`intFrac32`).

transformparticle-physics-drawing-engine / measurements/exactness.mjs · lines 1–74 of 74 · Not reached from any entry point (candidate for review) · pattern sector (shared by 2 files)

What it does
It calculates its inputs. Defines 12 functions or classes, including isqrt, mod, fixOfDouble, num, wrap.
What it achieves
It is built from the isqrt step (`isqrt`), the mod step (`mod`) and the fix of double helper (`fixOfDouble`). Test T2 of the 2030 stone, actually run.
Why it matters
No other file in the estate was found to import it.
Application
particle-physics-drawing-engine · measurements · JavaScript module
Uses
none found
Used by
none found
Produces
isqrt, mod, fixOfDouble, num, wrap, thetaTrue, px, intFrac32, row, mulhi32, top32, sector
Defines here
isqrt, mod, fixOfDouble, num, wrap, thetaTrue, px, intFrac32, row, mulhi32, top32, sector
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 measurements/exactness.mjs:1-74 · blob 3de6ed7d81591ffa737656e229858acb278dae4f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
/* 03-exactness.mjs: test T2 of the 2030 stone, actually run.
   Truth is computed in 256-bit fixed point with BigInt: theta_true = 2*pi*frac(key*(3-sqrt5)/2).
   Each law's angle is converted EXACTLY (no rounding) to the same fixed point and compared on the circle. */
const B = 256n, ONE = 1n << B;
const isqrt = v => { let x = 1n << 300n; for (;;) { const y = (x + v / x) >> 1n; if (y >= x) return x; x = y; } };
const SQRT5 = isqrt(5n * ONE * ONE);                               /* sqrt(5) * 2^256 */
const INV_PHI2 = (3n * ONE - SQRT5) / 2n;                          /* (3 - sqrt5)/2 = 1/phi^2 */
const PI = BigInt('3141592653589793238462643383279502884197169399375105820974944592307816406286') * ONE / (10n ** 75n);
const TAU = 2n * PI;
const mod = (a, m) => ((a % m) + m) % m;
const fixOfDouble = d => { const dv = new DataView(new ArrayBuffer(8)); dv.setFloat64(0, d); const hi = dv.getUint32(0), lo = dv.getUint32(4); const e = (hi >>> 20) & 0x7ff; const m = (BigInt(hi & 0xfffff) << 32n) | BigInt(lo); const mant = e ? m | (1n << 52n) : m; const sh = BigInt((e || 1) - 1075) + B; const v = sh >= 0n ? mant << sh : mant >> -sh; return hi >>> 31 ? -v : v; };
const num = v => Number(v * (1n << 80n) / ONE) / 2 ** 80;          /* fixed point -> double, for printing small differences */
const wrap = v => { let d = mod(v, TAU); if (d > PI) d -= TAU; return num(d); };
const thetaTrue = k => (mod(BigInt(k) * INV_PHI2, ONE) * TAU) >> B;

const GOLDEN = Math.PI * (3 - Math.sqrt(5));
const G32 = Math.fround(GOLDEN);
const C32 = 2654435769;                     /* floor(2^32/phi), the stone's constant */
const C64 = 11400714819323198485n;          /* floor(2^64/phi) */
const RIM_PX = 1000;
const px = d => 2 * RIM_PX * Math.abs(Math.sin(d / 2));            /* chord at the rim of a 1,000-px-radius view */

console.log(`GOLDEN (f64) = ${GOLDEN}; exact golden angle - GOLDEN = ${num(((INV_PHI2 * TAU) >> B) - fixOfDouble(GOLDEN)).toExponential(3)} rad`);
console.log(`fround(GOLDEN) = ${G32}; fround(GOLDEN) - GOLDEN = ${(G32 - GOLDEN).toExponential(3)} rad per key`);
console.log(`prose constant 2.39996 - GOLDEN = ${(2.39996 - GOLDEN).toExponential(4)} rad per key; at key 250174: ${((2.39996 - GOLDEN) * 250174).toFixed(4)} rad`);
console.log(`2^32/phi = ${num((ONE * (1n << 32n) * 2n * ONE) / (ONE + SQRT5) )}; C32 = ${C32}; truncation = ${num((ONE * (1n << 32n) * 2n * ONE) / (ONE + SQRT5) - BigInt(C32) * ONE).toFixed(6)} of one unit in 2^32`);
const perSlot = num(((ONE * (1n << 32n) * 2n * ONE) / (ONE + SQRT5) - BigInt(C32) * ONE) * TAU >> (B + 32n));
console.log(`=> the whole-number law drifts from the true golden angle by ${perSlot.toExponential(4)} rad per slot (predicted)`);

const intFrac32 = k => (Math.imul(k | 0, C32 | 0) >>> 0);
function row(k) {
  const T = thetaTrue(k);
  const t64 = k * GOLDEN, t32 = Math.fround(Math.fround(k) * G32);
  const u = intFrac32(k);                                          /* frac(k/phi) * 2^32, exact integer */
  const thInt = ((ONE - (BigInt(u) << (B - 32n))) * TAU) >> B;      /* 2*pi*(1 - frac), exact */
  const thIntNo = ((BigInt(u) << (B - 32n)) * TAU) >> B;            /* 2*pi*frac: is it the mirror image? */
  const u64 = (BigInt(k) * C64) & ((1n << 64n) - 1n);
  const thInt64 = ((ONE - (u64 << (B - 64n))) * TAU) >> B;
  const thShader = Math.fround(Math.fround(6.283185307179586) * Math.fround(1 - u / 4294967296)); /* the int law finished in float32 */
  const e64 = wrap(fixOfDouble(t64) - T), e32 = wrap(fixOfDouble(t32) - T), eI = wrap(thInt - T), eI64 = wrap(thInt64 - T), eSh = wrap(fixOfDouble(thShader) - T);
  const mirror = wrap(thIntNo + T);
  return { key: k, 'f64 err rad': e64.toExponential(3), 'f64 px': px(e64).toExponential(2), 'f32 err rad': e32.toExponential(3), 'f32 px': px(e32).toFixed(3), 'int32 law err rad': eI.toExponential(3), 'int32 px': px(eI).toFixed(4), 'int32 law finished in f32, px': px(eSh).toFixed(4), 'int64 law err rad': eI64.toExponential(3), 'mirror test (2pi*frac + true) rad': mirror.toExponential(3), 'f32 ulp   … [line shortened here: 539 characters; full line on GitHub]
}
const KEYS = [1, 250174, 262143, 2 ** 24, 2 ** 31];
const rows = KEYS.map(row); console.table(rows);
console.log(`keys examined in the table: ${rows.length}`);

/* every slot of one 2^18 layer: worst disagreement between the int32 law and the running f64 law */
let worst = 0, at = 0, cnt = 0; for (let s = 1; s < 262144; s++) { const u = intFrac32(s); const a = 2 * Math.PI * (1 - u / 4294967296), b = s * GOLDEN; let d = (a - b) % (2 * Math.PI); if (d > Math.PI) d -= 2 * Math.PI; if (d < -Math.PI) d += 2 * Math.PI; if (Math.abs(d) > worst) { worst = Math.abs(d); at = s; } cnt++; }
console.log(`one layer: ${cnt} slots examined; worst |int32 law - f64 law| = ${worst.toExponential(4)} rad at slot ${at} = ${px(worst).toFixed(4)} px at a 1,000-px rim`);

/* the 64-bit constant with only 32-bit operations (what a WebGL2 shader can do): 16-bit limbs */
function mulhi32(a, b) { const a0 = a & 0xffff, a1 = a >>> 16, b0 = b & 0xffff, b1 = b >>> 16; const p00 = a0 * b0, p01 = a0 * b1, p10 = a1 * b0, p11 = a1 * b1; const mid = (p00 >>> 16) + (p01 & 0xffff) + (p10 & 0xffff); return (p11 + (p01 >>> 16) + (p10 >>> 16) + (mid >>> 16)) >>> 0; }
const CHI = Number(C64 >> 32n), CLO = Number(C64 & 0xffffffffn);
const top32 = s => ((Math.imul(s, CHI | 0) >>> 0) + mulhi32(s >>> 0, CLO)) >>> 0;
let bad = 0, tested = 0; for (let i = 0; i < 1000000; i++) { const s = (Math.imul(i, 2246822519) >>> 0); const want = Number(((BigInt(s) * C64) & ((1n << 64n) - 1n)) >> 32n); if (top32(s) !== want) bad++; tested++; }
console.log(`limb law: ${tested} slots examined across 0..2^32, top 32 bits of slot*C64 mod 2^64 by 16-bit limbs disagree with BigInt on ${bad}`);

/* continued fraction of C32/2^32: how long does it stay golden? */
{ let a = BigInt(C32), b = 1n << 32n, q = [], h0 = 0n, h1 = 1n, k0 = 1n, k1 = 0n, firstBad = -1, den = 0n; while (b) { const t = a / b; q.push(t); [h0, h1] = [h1, t * h1 + h0]; [k0, k1] = [k1, t * k1 + k0]; if (q.length > 1 && t !== 1n && firstBad < 0) { firstBad = q.length - 1; den = k0; } [a, b] = [b, a % b]; }
  console.log(`continued fraction of C32/2^32: ${q.length} terms: [${q.join(',')}]`);
  console.log(`first term that is not 1 is term ${firstBad}; the last all-golden convergent has denominator ${den}. Neighbours in the spiral are about 2*sqrt(pi*k) keys apart, so the lattice stops being golden near k = ${(Number(den) ** 2 / (4 * Math.PI)).toExponential(2)}`); }

/* packing far out: a thin sector of the annulus starting at key K, three laws */
function sector(K, law) {
  const SPAN = 8000000, HALF = 0.004, pts = [];
  const r0 = Math.sqrt(K), r1 = Math.sqrt(K + SPAN);
  for (let k = K; k < K + SPAN; k++) { let t; if (law === 'f64') t = (k * GOLDEN) % (2 * Math.PI); else if (law === 'f32') t = Math.fround(Math.fround(k) * G32) % (2 * Math.PI); else t = 2 * Math.PI * (1 - intFrac32(k) / 4294967296); if (t > Math.PI) t -= 2 * Math.PI; if (Math.abs(t) < HALF) { const r = Math.sqrt(k); pts.push(r * Math.cos(t) - r0, r * Math.sin(t)); } }
  const m = pts.length / 2, H = HALF * r0; let mn = Infinity, inner = 0; const nn = [];
  for (let i = 0; i < m; i++) { const x = pts[2 * i], y = pts[2 * i + 1]; if (x < 4 || x > r1 - r0 - 4 || Math.abs(y) > H - 4) continue; let b = Infinity; for (let j = 0; j < m; j++) if (j !== i) { const d = (pts[2 * j] - x) ** 2 + (pts[2 * j + 1] - y) ** 2; if (d < b) b = d; } nn.push(Math.sqrt(b)); inner++; }
  nn.sort((a, b) => a - b); return { K, law, inSector: m, interiorExamined: inner, nnMin: nn.length ? +nn[0].toFixed(4) : null, nnMedian: nn.length ? +nn[nn.length >> 1].toFixed(4) : null };
}
const sec = []; for (const K of [2 ** 18, 2 ** 24, 2 ** 28, 2 ** 31]) for (const law of ['f64', 'int32', 'f32']) sec.push(sector(K, law));
console.table(sec);

Fault

A Python command-line tool in the tools folder of Particle Physics Drawing Engine that reads fault network and 20kV, using IEC 60909. It is built from the geo step (`geo`).

electricalparticle-physics-drawing-engine / tools/fault.py · lines 1–70 of 70 · Entry point

What it does
It loads fault network and 20kV. Defines geo, main. Uses libraries argparse, json, math, os, pandapower. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: 20kV, 110kV. README: "`tools/fault.py` runs a three-phase fault on pandapower's published 20 kV example network (mv_oberrhein) with pandapower's IEC 60909 short-circuit module, and the translator carries each line's initial symmetrical short-circuit current as an edge weight."
Inputs & outputs
In: command-line arguments. Out: JSON file fault-network.json. Voltage levels named: 110kV, 20kV.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
A fault study by an existing open-source solver, translated into the wafer's language. Its code works with 100 kW, 20 kV and 1000 MVA. It accepts `--bus` and `--out`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
particle-physics-drawing-engine · tools · Python CLI
Uses
argparse, json, math, os, pandapower, pandapower.networks, pandapower.shortcircuit
Used by
none found
Produces
geo, main
Defines here
geo, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 tools/fault.py:1-70 · blob f9ea639bfab961517ac682b37cdef2bc6b6e8e51 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""fault.py: a fault study by an existing open-source solver, translated into the wafer's language.

Solver: pandapower (BSD 3-clause; Thurner et al., "pandapower: An Open Source Python Tool for Convenient Modeling,
Analysis, and Optimization of Electric Power Systems", IEEE Transactions on Power Systems, 2018). Its IEC 60909
short-circuit module computes the initial symmetrical short-circuit current I"k for a three-phase fault.
Network: pandapower's mv_oberrhein, a 20 kV distribution network with coordinates (a generic, published example,
not a real utility's data).

The translator carries each line's I"k as an edge weight, so the wafer places more of its particles on the paths
that carry the fault current: illumination by density, no new colour, no new size. Every number here comes
from the solver; the fault bus, the case and the solver version are written into the file. It charts a
calculation on a published example; it is not a design, and above 100 kW a chartered engineer signs.
"""
import argparse, json, math, os
import pandapower as pp, pandapower.networks as nw, pandapower.shortcircuit as sc


def geo(net, b):
    g = net.bus.at[b, "geo"]
    if isinstance(g, str):
        g = json.loads(g)
    return g["coordinates"]


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--bus", type=int, default=-1, help="faulted bus index; -1 = the bus with the lowest fault level (furthest, electrically)")
    ap.add_argument("--out", default="out/networks")
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    net = nw.mv_oberrhein()
    # the example carries no short-circuit parameters: state them (typical 110 kV supply), and leave generation out of the fault contribution
    net.ext_grid["s_sc_max_mva"] = 1000.0; net.ext_grid["rx_max"] = 0.1; net.ext_grid["s_sc_min_mva"] = 800.0; net.ext_grid["rx_min"] = 0.1
    net.sgen["in_service"] = False
    if "endtemp_degree" in net.line.columns: net.line["endtemp_degree"] = net.line["endtemp_degree"].fillna(80.0)
    # fault level at every bus first (case max, 3ph), to choose and to report
    sc.calc_sc(net, fault="3ph", case="max", ip=False, ith=False, branch_results=False)
    ikss_bus = net.res_bus_sc["ikss_ka"]
    bus = int(ikss_bus.idxmin()) if a.bus < 0 else a.bus
    # the study: a three-phase fault at that bus, with branch results, so every line carries its share
    sc.calc_sc(net, fault="3ph", case="max", ip=False, ith=False, branch_results=True, bus=bus)
    line_ik = net.res_line_sc["ikss_ka"].fillna(0.0)
    peak = float(line_ik.max()) or 1.0
    buses = list(net.bus.index)
    idx = {b: i for i, b in enumerate(buses)}
    pts = [geo(net, b) for b in buses]
    lat0 = sum(p[1] for p in pts) / len(pts); c = math.cos(math.radians(lat0))
    xs = [p[0] * c for p in pts]; ys = [p[1] for p in pts]
    x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys); s = max(x1 - x0, y1 - y0) or 1
    stations = [[round((x - x0) / s * 1.8 - 0.9 * (x1 - x0) / s, 4), round((y - y0) / s * 1.8 - 0.9 * (y1 - y0) / s, 4),
                 (f"bus {b}: fault here, I\"k {ikss_bus[b]:.2f} kA" if b == bus else f"bus {b}: I\"k {ikss_bus[b]:.2f} kA")] for (x, y), b in zip(zip(xs, ys), buses)]
    edges = []
    for l in net.line.index:
        w = float(line_ik[l]) / peak
        edges.append([idx[int(net.line.at[l, "from_bus"])], idx[int(net.line.at[l, "to_bus"])], round(max(w, 0.02), 4)])
    carrying = int((line_ik > 0.05 * peak).sum())
    facts = {"solver": f"pandapower {pp.__version__}, IEC 60909 calc_sc, fault 3ph, case max; supply stated as 1000 MVA, R/X 0.1; generation excluded", "network": "pandapower mv_oberrhein (20 kV, published example)",
             "fault_bus": bus, "ikss_at_fault_ka": round(float(ikss_bus[bus]), 3), "peak_line_ikss_ka": round(peak, 3), "lines": len(net.line), "lines_carrying_over_5pct": carrying,
             "min_bus_ikss_ka": round(float(ikss_bus.min()), 3), "max_bus_ikss_ka": round(float(ikss_bus.max()), 3)}
    net_out = {"name": "fault", "source": f"pandapower mv_oberrhein; three-phase fault at bus {bus}; I\"k at the fault {facts['ikss_at_fault_ka']} kA; peak line current {facts['peak_line_ikss_ka']} kA",
               "attribution": "Solver and network: pandapower (BSD 3-clause), Thurner et al. 2018, pandapower.readthedocs.io. IEC 60909 method. A published example network, not a real utility's data; not a design; above 100 kW a chartered engineer signs.",
               "law": "edge weight = the line's initial symmetrical short-circuit current divided by the largest; particles along an edge in proportion to length x weight, so the fault current paths are the dense ones",
               "facts": facts, "stations": stations, "edges": edges}
    p = os.path.join(a.out, "fault-network.json"); json.dump(net_out, open(p, "w"), separators=(",", ":"))
    print(json.dumps(facts)); print(f"-> {p}, {os.path.getsize(p):,} bytes")


if __name__ == "__main__":
    main()

Geometry

A Python command-line tool in the tools folder of Particle Physics Drawing Engine that reads trench network and cables.

storageparticle-physics-drawing-engine / tools/geometry.py · lines 1–74 of 74 · Entry point · pattern circle (shared by 9 files)

What it does
It loads trench network and cables. Defines 6 functions or classes, including circle, rect, trench, add, fit. Uses libraries argparse, json, math, os. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: cables.
Inputs & outputs
In: command-line arguments. Out: JSON file trench-network.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the circle step (`circle`), the rect step (`rect`) and the trench step (`trench`). The translator's second input. Geometry (sections, not routes) into the wafer's network language. It accepts `--circuits`, `--per-row` and `--cable-od`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
particle-physics-drawing-engine · tools · Python CLI
Uses
argparse, json, math, os
Used by
none found
Produces
circle, rect, trench, fit, main
Defines here
circle, rect, trench, add, fit, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 tools/geometry.py:1-74 · blob d2f83181dc56d7ae5e70d7247695e127b33f984c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""geometry.py: the translator's second input. Geometry (sections, not routes) into the wafer's network language.

Rules, fixed: a circle becomes a ring of N nodes joined in a loop (N from its circumference at a stated node
spacing); a rectangle becomes its four corners joined; everything is in millimetres in the plane of the section,
then fitted to the unit square like every other layer. Nothing is invented: the shapes come from stated inputs,
and the inputs are written into the file.

First geometry: a buried cable trench in flat formation, the inputs of the estate's cable-trench-or-drill
calculator (circuit quantity, cables per row, cable outer diameter, horizontal and vertical spacing, burial
depth). This is a picture of a stated arrangement; it is not a design, and it says so.
"""
import argparse, json, math, os


def circle(cx, cy, r, spacing_mm):
    n = max(12, int(2 * math.pi * r / spacing_mm))
    pts = [[cx + r * math.cos(2 * math.pi * i / n), cy + r * math.sin(2 * math.pi * i / n)] for i in range(n)]
    return pts, [[i, (i + 1) % n] for i in range(n)]


def rect(x0, y0, x1, y1):
    return [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], [[0, 1], [1, 2], [2, 3], [3, 0]]


def trench(circuits, per_row, cable_od, spacing_h, spacing_v, depth, cables_per_circuit=3, node_spacing=6.0):
    """Flat formation: each circuit's cables side by side; rows of `per_row` circuits; the trench outline around them."""
    nodes, edges, shapes = [], [], []
    def add(pts, eds, label):
        o = len(nodes); nodes.extend([[p[0], p[1], label if i == 0 else ""] for i, p in enumerate(pts)]); edges.extend([[a + o, b + o] for a, b in eds])
    pitch = cable_od + spacing_h
    rows = math.ceil(circuits / per_row)
    row_w = per_row * cables_per_circuit * pitch + (per_row - 1) * spacing_h
    for c in range(circuits):
        row, col = divmod(c, per_row)
        y = -(depth + row * (cable_od + spacing_v))
        x0 = -row_w / 2 + col * (cables_per_circuit * pitch + spacing_h) + cable_od / 2
        for k in range(cables_per_circuit):
            pts, eds = circle(x0 + k * pitch, y, cable_od / 2, node_spacing)
            add(pts, eds, f"circuit {c + 1} cable {k + 1}")
    margin = cable_od
    top, bottom = 0.0, -(depth + (rows - 1) * (cable_od + spacing_v) + cable_od / 2 + margin)
    pts, eds = rect(-row_w / 2 - margin, bottom, row_w / 2 + margin, top)
    add(pts, eds, "trench outline, ground level at the top")
    return nodes, edges


def fit(nodes):
    xs = [n[0] for n in nodes]; ys = [n[1] for n in nodes]
    x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys); sc = max(x1 - x0, y1 - y0) or 1
    return [[round((n[0] - x0) / sc * 1.8 - 0.9 * (x1 - x0) / sc, 4), round((n[1] - y0) / sc * 1.8 - 0.9 * (y1 - y0) / sc, 4), n[2]] for n in nodes]


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--circuits", type=int, default=4)
    ap.add_argument("--per-row", type=int, default=2)
    ap.add_argument("--cable-od", type=float, default=90.0, help="cable outer diameter, mm")
    ap.add_argument("--spacing-h", type=float, default=150.0, help="clear horizontal spacing between cables, mm")
    ap.add_argument("--spacing-v", type=float, default=300.0, help="clear vertical spacing between rows, mm")
    ap.add_argument("--depth", type=float, default=900.0, help="depth to the first row's centre, mm")
    ap.add_argument("--out", default="out/networks")
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    nodes, edges = trench(a.circuits, a.per_row, a.cable_od, a.spacing_h, a.spacing_v, a.depth)
    inputs = {"circuits": a.circuits, "per_row": a.per_row, "cable_od_mm": a.cable_od, "spacing_h_mm": a.spacing_h, "spacing_v_mm": a.spacing_v, "depth_mm": a.depth, "cables_per_circuit": 3, "node_spacing_mm": 6.0}
    net = {"name": "trench", "source": f"a stated trench arrangement: {json.dumps(inputs)}", "attribution": "inputs as used by Ventusltd/cable-trench-or-drill; a picture of an arrangement, not a design; a chartered engineer signs",
           "law": "flat formation; each cable a ring of nodes at 6 mm spacing; rows below one another; the trench outline around them", "inputs": inputs, "stations": fit(nodes), "edges": edges}
    p = os.path.join(a.out, "trench-network.json"); json.dump(net, open(p, "w"), separators=(",", ":"))
    print(f"trench: {a.circuits} circuits x 3 cables, {len(nodes)} nodes, {len(edges)} edges, {os.path.getsize(p):,} bytes -> {p}")


if __name__ == "__main__":
    main()

Particles

A Python command-line tool in the tools folder of Particle Physics Drawing Engine that works with theta int (`theta_int`) and cmd layer (`cmd_layer`) (units: kV, kW), using SHA-256.

storageparticle-physics-drawing-engine / tools/particles.py · lines 1–180 of 180 · Entry point · pattern digest (shared by 56 files)

What it does
It loads data. Defines 11 functions or classes, including digest, line_for, weight, theta_int, f32. Uses libraries argparse, hashlib, json, math, os. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: command-line arguments. Out: JSON file.
Downstream impact
Used directly by 4 files: Scope Check (particle-physics-drawing-engine); Spiral vs Stack (particle-physics-drawing-engine); Nightly Workflow (particle-physics-drawing-engine); Particles Workflow (particle-physics-drawing-engine).
What it achieves
It is built from the digest step (`digest`), the line for helper (`line_for`) and the weight step (`weight`). Procedural layers, the DNA test and the exactness test. It accepts `--layer`, `--recipe` and `--seed`.
Why it matters
Imported by Spiral vs Stack. Run by Scope Check, Nightly Workflow and Particles Workflow.
Application
particle-physics-drawing-engine · tools · Python CLI
Uses
argparse, hashlib, json, math, os, platform, struct, sys
Used by
run by Scope Check (script call), imported by Spiral vs Stack (import), run by Nightly Workflow (workflow run), run by Particles Workflow (workflow run)
Produces
digest, line_for, weight, theta_int, f32, cmd_layer, regen_hash, cmd_dna, cmd_compare, cmd_exactness, main
Defines here
digest, line_for, weight, theta_int, f32, cmd_layer, regen_hash, cmd_dna, cmd_compare, cmd_exactness, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 tools/particles.py:1-180 · blob 5442841acdb7a1f5bf2d24c7f83fb896da37d249 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""particles.py: procedural layers, the DNA test and the exactness test.

The laws it implements (see README, "The plan"):
  Law 1  a layer is 2^18 = 262,144 slots; address = layer * 2^18 + slot.
  Law 2  the angle within a layer is exact whole-number arithmetic:
         frac = (slot * 2654435769) mod 2^32 / 2^32,  theta = 2*pi*(1 - frac),
         which is the golden angle to 7.3e-10 rad per slot, the same bits on every machine.
  Law 3  a generated layer stores no lines: recipe + seed + slot regenerate every line,
         and the DNA test regenerates and compares hashes, or fails.
  Density: same-sized particles, r = sqrt(sum of bounded weights), weight from line length,
         bounded to [0.25, 1] and taken by rank, which measured zero overlaps on 250,174 real lines.

House rules: no random module; every number printed is measured; exit non-zero on failure;
positions are computed, never stored.
"""
import argparse, hashlib, json, math, os, platform, struct, sys, time

SLOTS = 1 << 18
C32 = 2654435769                      # floor(2^32 / phi)
GOLDEN = math.pi * (3 - math.sqrt(5)) # the golden angle, 2.39996... rad
RASTER = 512


def digest(recipe, seed, slot):
    return hashlib.sha256(f"{recipe}|{seed}|{slot}".encode()).digest()


def line_for(recipe, seed, slot):
    """One generated line of code. Deterministic in (recipe, seed, slot)."""
    d = digest(recipe, seed, slot)
    u = int.from_bytes(d[:8], "big")
    if recipe == "grid-feeder":
        kv = (11, 33, 66, 132, 275, 400)[u % 6]
        kw = 50 + (u >> 8) % 20000
        fed = (u >> 32) % slot if slot else 0
        return f"bus[{slot}] = Bus(kv={kv}, load_kw={kw}, fed_from=bus[{fed}])"
    if recipe == "prose":
        n = 8 + (u >> 8) % 120
        return "x" * n
    sys.exit(f"FAIL: unknown recipe {recipe!r}")


def weight(chars):
    return min(1.0, max(0.25, chars / 80.0))


def theta_int(slot):
    frac = ((slot * C32) & 0xFFFFFFFF) / 4294967296.0
    return 2 * math.pi * (1 - frac)


def f32(x):
    return struct.unpack("f", struct.pack("f", x))[0]


# ---------------------------------------------------------------- layer
def cmd_layer(a):
    os.makedirs(a.out, exist_ok=True)
    t0 = time.time()
    raster = [0] * (RASTER * RASTER)
    chain = hashlib.sha256()
    cum = 0.0
    chars_sum = 0
    sample = {}
    for slot in range(SLOTS):
        line = line_for(a.recipe, a.seed, slot)
        chain.update(hashlib.sha256(line.encode()).digest())
        n = len(line)
        chars_sum += n
        cum += weight(n)
        r = math.sqrt(cum)
        th = theta_int(slot)
        if slot in (0, 1, 39885, SLOTS - 1):
            sample[str(slot)] = line
        # density raster of the whole layer (positions are not stored)
        R = math.sqrt(SLOTS)  # r never exceeds sqrt(SLOTS * 1.0)
        x = int((r * math.cos(th) / R + 1) * 0.5 * (RASTER - 1))
        y = int((r * math.sin(th) / R + 1) * 0.5 * (RASTER - 1))
        raster[y * RASTER + x] += 1
    peak = max(raster)
    pgm = os.path.join(a.out, f"layer-{a.layer}-density.pgm")
    with open(pgm, "wb") as f:
        f.write(f"P5 {RASTER} {RASTER} 255\n".encode())
        f.write(bytes(min(255, v * 255 // max(1, peak)) for v in raster))
    manifest = {
        "layer": a.layer, "recipe": a.recipe, "seed": a.seed, "slots": SLOTS,
        "address_first": a.layer * SLOTS, "address_last": a.layer * SLOTS + SLOTS - 1,
        "sha256_of_line_hashes": chain.hexdigest(),
        "chars_total": chars_sum, "rim_radius": round(math.sqrt(cum), 4),
        "raster_peak_particles_per_cell": peak, "sample": sample,
        "generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "python": platform.python_version(), "platform": platform.platform(),
        "seconds": round(time.time() - t0, 2),
    }
    path = os.path.join(a.out, f"layer-{a.layer}.json")
    with open(path, "w") as f:
        json.dump(manifest, f, indent=1)
    print(f"layer {a.layer}: {SLOTS} slots generated, {chars_sum} chars, "
          f"hash {manifest['sha256_of_line_hashes'][:16]}..., {manifest['seconds']} s -> {path}")


# ---------------------------------------------------------------- dna
def regen_hash(m):
    chain = hashlib.sha256()
    for slot in range(m["slots"]):
        chain.update(hashlib.sha256(line_for(m["recipe"], m["seed"], slot).encode()).digest())
    return chain.hexdigest()


def cmd_dna(a):
    m = json.load(open(a.manifest))
    got = regen_hash(m)
    ok = got == m["sha256_of_line_hashes"]
    print(f"DNA: regenerated {m['slots']} of {m['slots']} slots on {platform.platform()}; "
          f"{'MATCH' if ok else 'MISMATCH'} {got[:16]}... vs {m['sha256_of_line_hashes'][:16]}...")
    sys.exit(0 if ok else 1)


def cmd_compare(a):
    ms = [json.load(open(p)) for p in a.manifests]
    keys = ("recipe", "seed", "slots", "sha256_of_line_hashes", "chars_total")
    same = all(m[k] == ms[0][k] for m in ms for k in keys)
    for p, m in zip(a.manifests, ms):
        print(f"{m['platform']}: {m['sha256_of_line_hashes'][:16]}... chars {m['chars_total']}  ({p})")
    print(f"compare: {len(ms)} manifests examined; {'IDENTICAL' if same else 'DIFFER'}")
    sys.exit(0 if same else 1)


# ---------------------------------------------------------------- exactness (T2)
def cmd_exactness(a):
    keys = [1, 250174, SLOTS - 1, 1 << 24, 1 << 31]
    rim_px = 1000.0
    print(f"{'key':>12} {'f32 err rad':>12} {'f32 px':>10} {'int law err rad':>16} {'int px':>10}")
    worst_in_layer = 0.0
    for k in keys:
        exact = (k * GOLDEN) % (2 * math.pi)
        f32v = (f32(f32(k) * f32(GOLDEN))) % (2 * math.pi)
        intv = theta_int(k % SLOTS)                      # slot within its layer
        e32 = abs((f32v - exact + math.pi) % (2 * math.pi) - math.pi)
        eint = abs((intv - exact + math.pi) % (2 * math.pi) - math.pi)
        print(f"{k:>12} {e32:>12.3e} {e32 * rim_px:>10.3f} {eint:>16.3e} {eint * rim_px:>10.3f}")
        if k < SLOTS:
            worst_in_layer = max(worst_in_layer, eint * rim_px)
    # every slot of one layer, not a sample
    worst = 0.0
    for s in range(SLOTS):
        exact = (s * GOLDEN) % (2 * math.pi)
        e = abs((theta_int(s) - exact + math.pi) % (2 * math.pi) - math.pi)
        worst = max(worst, e)
    print(f"whole layer: {SLOTS} slots examined; worst |int law - exact| = {worst:.3e} rad "
          f"= {worst * rim_px:.3f} px at a {rim_px:.0f}-px rim")
    limit = 0.25
    print(f"{'PASS' if worst * rim_px < limit else 'FAIL'}: limit {limit} px within one layer")
    sys.exit(0 if worst * rim_px < limit else 1)


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = p.add_subparsers(dest="cmd", required=True)
    s = sub.add_parser("layer", help="generate a layer: manifest + density raster, no lines stored")
    s.add_argument("--layer", type=int, default=1)
    s.add_argument("--recipe", default="grid-feeder")
    s.add_argument("--seed", default="2026-09-18")
    s.add_argument("--out", default="out")
    s.set_defaults(fn=cmd_layer)
    s = sub.add_parser("dna", help="regenerate a layer from its manifest and compare the hash")
    s.add_argument("manifest")
    s.set_defaults(fn=cmd_dna)
    s = sub.add_parser("compare", help="compare manifests made on different machines")
    s.add_argument("manifests", nargs="+")
    s.set_defaults(fn=cmd_compare)
    s = sub.add_parser("exactness", help="test T2: the angle law in 32-bit, and the whole-number law")
    s.set_defaults(fn=cmd_exactness)
    a = p.parse_args()
    a.fn(a)


if __name__ == "__main__":
    main()

Png

A Python module in the tools folder of Particle Physics Drawing Engine that writes grey (`write_grey`). It is built from the raster to png helper (`raster_to_png`).

storageparticle-physics-drawing-engine / tools/png.py · lines 1–27 of 27 · pattern _chunk (shared by 2 files)

What it does
It loads data. Defines _chunk, write_grey, raster_to_png. Uses libraries struct, zlib. Side effects: reads or writes files.
Downstream impact
Used directly by 2 files: Spiral vs Stack (particle-physics-drawing-engine); Underground (particle-physics-drawing-engine). Reached from 2 other entry points, including Nightly Workflow (particle-physics-drawing-engine); Scope Check (particle-physics-drawing-engine).
What it achieves
The smallest PNG writer, no dependencies.
Why it matters
Imported by Spiral vs Stack and Underground.
Application
particle-physics-drawing-engine · tools · Python module
Uses
struct, zlib
Used by
imported by Spiral vs Stack (import), imported by Underground (import)
Produces
write_grey, raster_to_png
Defines here
_chunk, write_grey, raster_to_png
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 tools/png.py:1-27 · blob d2361909302323393ba787aa5d384433d9705886 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
"""png.py: the smallest PNG writer, no dependencies. 8-bit greyscale. Black ground, particles are light."""
import struct, zlib


def _chunk(tag, data):
    c = struct.pack(">I", len(data)) + tag + data
    return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)


def write_grey(path, width, height, pixels):
    """pixels: bytes or list of ints 0..255, row-major, len == width*height."""
    raw = bytearray()
    for y in range(height):
        raw.append(0)
        raw += bytes(pixels[y * width:(y + 1) * width])
    with open(path, "wb") as f:
        f.write(b"\x89PNG\r\n\x1a\n")
        f.write(_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0)))
        f.write(_chunk(b"IDAT", zlib.compress(bytes(raw), 9)))
        f.write(_chunk(b"IEND", b""))


def raster_to_png(path, size, counts, gamma=0.5):
    """Density raster (counts per cell) to PNG; gamma < 1 lifts sparse cells so a lone particle is visible."""
    peak = max(counts) or 1
    px = bytes(int(255 * (c / peak) ** gamma) if c else 0 for c in counts)
    write_grey(path, size, size, px)