// verify-heat.mjs: the two Gordon-Webb-Wolpert drums have DIFFERENT torsional rigidity,
// and therefore different heat content. Standalone (no imports), node 22:
//
//     node verify-heat.mjs            (exit 0 = every check passed; about 10 s)
//
// Torsional rigidity. Let u solve  -Δu = 1  on the drum, u = 0 on its rim. Then
// T = ∫u. Two variational principles pin T from both sides:
//
//   below:  T >= 2∫v - ∫|∇v|²   for EVERY v that vanishes on the rim
//           (the gap is exactly ∫|∇(u-v)|² >= 0);
//   above:  T <= ∫|σ|²          for EVERY vector field σ with div σ = -1
//           (because T = ∫σ·∇u <= |σ| |∇u| = |σ| √T).
//
// Neither needs the true u. So this file computes a good v and a good σ with ordinary
// floating-point solvers, ROUNDS THEM TO RATIONALS, and then evaluates both integrals in
// exact integer arithmetic (BigInt). The solvers can be as sloppy as they like: a worse
// v or σ only gives a weaker bound, never a false one. What must be exact is the mesh,
// the integrals and the comparison, and those are.
//
//   v : continuous, piecewise linear on a mesh of right triangles, zero on the rim.
//   σ : -(x - c)/2 + curl ψ, ψ continuous piecewise linear (no boundary condition).
//       -(x - c)/2 has divergence -1, and curl ψ is divergence-free with continuous
//       normal component across every mesh edge, so div σ = -1 on the whole drum.
//       Every integrand is a polynomial of degree <= 2 on each triangle, and the
//       edge-midpoint rule integrates those exactly.
//
// The heat content Q(t) = ∫u(x,t)dx, the heat left in a drum that starts at temperature 1
// with its rim held at 0, satisfies ∫_0^∞ Q(t) dt = T. So two drums with different T have
// different heat content. (Q(t) = Σ e^{-λt} (∫φ)², summed over normalised eigenfunctions,
// and T = Σ (∫φ)²/λ: van den Berg, Dryden and Kappeler 2014; Comer and McDonald 2021.)

// ---------- the drums (same data as the layer's page and verify.mjs) ----------
// Each drum: seven half-unit-squares; every triangle lists its right-angle corner first.
const MACROS_A = [[[0,0],[1,0],[0,1]],[[1,1],[1,2],[0,1]],[[1,1],[1,0],[0,1]],[[1,1],[1,2],[2,1]],[[2,2],[1,2],[2,1]],[[2,2],[1,2],[2,3]],[[2,2],[3,2],[2,1]]];
const MACROS_B = [[[1,1],[1,2],[0,1]],[[0,2],[1,2],[0,1]],[[1,1],[1,0],[0,1]],[[1,1],[1,2],[2,1]],[[2,2],[1,2],[2,1]],[[2,2],[3,2],[2,1]],[[2,2],[3,2],[2,3]]];
// the octagons they tile (research/hearing-the-shape/README.md)
const OCT_A = [[0,0],[0,1],[2,3],[2,2],[3,2],[2,1],[1,1],[1,0]];
const OCT_B = [[1,0],[0,1],[0,2],[2,2],[2,3],[3,2],[2,1],[1,1]];
const SQUARE = [[[0,0],[1,0],[0,1]],[[1,1],[0,1],[1,0]]];
// transplantation matrix from verify.mjs (Drum B piece k = Σ_l T[k][l] · Drum A piece l)
const T = [[1,1,0,0,1,0,0],[0,-1,1,1,0,0,0],[-1,0,1,0,0,0,1],[-1,0,0,1,0,1,0],[0,0,-1,0,1,-1,0],[0,-1,0,0,0,1,1],[0,0,0,-1,1,0,-1]];

let failed = 0;
const check = (ok, msg) => { console.log(`${ok ? 'ok  ' : 'FAIL'}  ${msg}`); if (!ok) failed++; };

// ---------- mesh: integer coordinates (the drum scaled by n), unit right triangles ----------
function mesh(macros, n) {
  const idx = new Map(), X = [], Y = [], tris = [];
  const get = (x, y) => { const k = x + ',' + y; let id = idx.get(k); if (id === undefined) { id = X.length; X.push(x); Y.push(y); idx.set(k, id); } return id; };
  for (const [A, B, C] of macros) {
    const g = [];
    for (let i = 0; i <= n; i++) { g[i] = []; for (let j = 0; j <= n - i; j++) { const c = n - i - j; g[i][j] = get(i * A[0] + j * B[0] + c * C[0], i * A[1] + j * B[1] + c * C[1]); } }
    for (let i = 0; i < n; i++) for (let j = 0; j < n - i; j++) { tris.push([g[i][j], g[i + 1][j], g[i][j + 1]]); if (j < n - i - 1) tris.push([g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]); }
  }
  // per triangle: det (= ±1 here) and the integer gradient numerators
  const geo = tris.map(([a, b, c]) => {
    const x0 = X[a], y0 = Y[a], x1 = X[b], y1 = Y[b], x2 = X[c], y2 = Y[c];
    const det = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0);
    return { det, gx: [y1 - y2, y2 - y0, y0 - y1], gy: [x2 - x1, x0 - x2, x1 - x0] };
  });
  const ec = new Map(), ek = (a, b) => a < b ? a + '_' + b : b + '_' + a;
  for (const [a, b, c] of tris) for (const [u, v] of [[a, b], [b, c], [c, a]]) ec.set(ek(u, v), (ec.get(ek(u, v)) || 0) + 1);
  const rim = new Uint8Array(X.length);
  for (const [k, c] of ec) if (c === 1) for (const s of k.split('_')) rim[+s] = 1;
  return { n, X, Y, tris, geo, rim, N: X.length };
}

// ---------- sparse SPD solve (floating point; only used to FIND v and ψ) ----------
function solveSPD(N, rows, b) {
  const rp = new Int32Array(N + 1); let nnz = 0; for (let i = 0; i < N; i++) { rp[i] = nnz; nnz += rows[i].size; } rp[N] = nnz;
  const ci = new Int32Array(nnz), va = new Float64Array(nnz), D = new Float64Array(N);
  for (let i = 0; i < N; i++) { let p = rp[i]; for (const [c, v] of rows[i]) { ci[p] = c; va[p++] = v; if (c === i) D[i] = v; } }
  const x = new Float64Array(N), r = Float64Array.from(b), z = new Float64Array(N), p = new Float64Array(N), q = new Float64Array(N);
  let rz = 0, bn = 0; for (let i = 0; i < N; i++) { z[i] = r[i] / D[i]; p[i] = z[i]; rz += r[i] * z[i]; bn += b[i] * b[i]; } bn = Math.sqrt(bn);
  for (let it = 0; it < 100000; it++) {
    for (let i = 0; i < N; i++) { let s = 0; for (let k = rp[i]; k < rp[i + 1]; k++) s += va[k] * p[ci[k]]; q[i] = s; }
    let pq = 0; for (let i = 0; i < N; i++) pq += p[i] * q[i];
    const al = rz / pq; let rn = 0;
    for (let i = 0; i < N; i++) { x[i] += al * p[i]; r[i] -= al * q[i]; rn += r[i] * r[i]; }
    if (Math.sqrt(rn) < 1e-12 * bn) break;
    let rz2 = 0; for (let i = 0; i < N; i++) { z[i] = r[i] / D[i]; rz2 += r[i] * z[i]; }
    const be = rz2 / rz; rz = rz2; for (let i = 0; i < N; i++) p[i] = z[i] + be * p[i];
  }
  return x;
}

const S = 2n ** 40n;                 // v and ψ are rounded to multiples of 1/S
const toQ = (x) => BigInt(Math.round(x * 2 ** 40));

// lower bound, as an exact fraction num / (6 S²) on the drum scaled by n
function lower(m) {
  const map = new Int32Array(m.N).fill(-1); let k = 0;
  for (let i = 0; i < m.N; i++) if (!m.rim[i]) map[i] = k++;
  const rows = Array.from({ length: k }, () => new Map()), b = new Float64Array(k);
  m.tris.forEach((t, e) => { const g = m.geo[e], A2 = Math.abs(g.det);
    for (let a = 0; a < 3; a++) { const ia = map[t[a]]; if (ia < 0) continue; b[ia] += A2 / 6;
      for (let c = 0; c < 3; c++) { const ic = map[t[c]]; if (ic < 0) continue;
        rows[ia].set(ic, (rows[ia].get(ic) || 0) + (g.gx[a] * g.gx[c] + g.gy[a] * g.gy[c]) / (2 * A2)); } } });
  const u = solveSPD(k, rows, b);
  const V = new Array(m.N).fill(0n); for (let i = 0; i < m.N; i++) if (map[i] >= 0) V[i] = toQ(u[map[i]]);
  // 2∫v - ∫|∇v|², with |det| = 1: per triangle 2·(1/6)ΣV/S - (1/2)|G|²/S²; times 6S²: 2SΣV - 3|G|²
  let num = 0n;
  m.tris.forEach((t, e) => { const g = m.geo[e];
    if (Math.abs(g.det) !== 1) throw new Error('mesh triangle with |det| != 1');
    const Gx = BigInt(g.gx[0]) * V[t[0]] + BigInt(g.gx[1]) * V[t[1]] + BigInt(g.gx[2]) * V[t[2]];
    const Gy = BigInt(g.gy[0]) * V[t[0]] + BigInt(g.gy[1]) * V[t[1]] + BigInt(g.gy[2]) * V[t[2]];
    num += 2n * S * (V[t[0]] + V[t[1]] + V[t[2]]) - 3n * (Gx * Gx + Gy * Gy); });
  return { num, den: 6n * S * S, float: u };
}

// upper bound, as an exact fraction num / (96 S²) on the drum scaled by n
function upper(m) {
  let sx = 0, sy = 0; for (let i = 0; i < m.N; i++) { sx += m.X[i]; sy += m.Y[i]; }
  const cx = Math.round(sx / m.N), cy = Math.round(sy / m.N);          // any c works; an integer keeps it exact
  const rows = Array.from({ length: m.N - 1 }, () => new Map()), b = new Float64Array(m.N - 1);
  m.tris.forEach((t, e) => { const g = m.geo[e], d = g.det;
    const mx = (m.X[t[0]] + m.X[t[1]] + m.X[t[2]]) / 3 - cx, my = (m.Y[t[0]] + m.Y[t[1]] + m.Y[t[2]]) / 3 - cy;
    const s0x = -mx / 2, s0y = -my / 2;                                // σ0 at the centroid (linear, so its mean)
    for (let a = 0; a < 3; a++) { const ia = t[a] - 1; if (ia < 0) continue;   // ψ at node 0 fixed to 0
      // curl φ_a = (∂y φ_a, -∂x φ_a) = (gy_a, -gx_a)/d ; area |d|/2
      b[ia] -= (Math.abs(d) / 2) * (s0x * g.gy[a] - s0y * g.gx[a]) / d;
      for (let c = 0; c < 3; c++) { const ic = t[c] - 1; if (ic < 0) continue;
        rows[ia].set(ic, (rows[ia].get(ic) || 0) + (g.gx[a] * g.gx[c] + g.gy[a] * g.gy[c]) / (2 * Math.abs(d))); } } });
  const p = solveSPD(m.N - 1, rows, b);
  const P = new Array(m.N).fill(0n); for (let i = 1; i < m.N; i++) P[i] = toQ(p[i - 1]);
  // σ = σ0 + curl ψ. At an edge midpoint (p_i+p_j)/2: σ0 = -(p_i+p_j-2c)/4, curl ψ = (Gy, -Gx)/(d S).
  // q = (-(p_i+p_j-2c)·S + 4·d·(Gy, -Gx)) / (4S)   (d = ±1, so 1/d = d)
  // ∫|q|² = (|d|/2)(1/3) Σ_mid |q|²  ->  times 96 S²: Σ_mid |4S·q|²
  let num = 0n;
  m.tris.forEach((t, e) => { const g = m.geo[e], d = BigInt(g.det);
    if (Math.abs(g.det) !== 1) throw new Error('mesh triangle with |det| != 1');
    const Gx = BigInt(g.gx[0]) * P[t[0]] + BigInt(g.gx[1]) * P[t[1]] + BigInt(g.gx[2]) * P[t[2]];
    const Gy = BigInt(g.gy[0]) * P[t[0]] + BigInt(g.gy[1]) * P[t[1]] + BigInt(g.gy[2]) * P[t[2]];
    for (const [i, j] of [[0, 1], [1, 2], [2, 0]]) {
      const qx = -BigInt(m.X[t[i]] + m.X[t[j]] - 2 * cx) * S + 4n * d * Gy;
      const qy = -BigInt(m.Y[t[i]] + m.Y[t[j]] - 2 * cy) * S - 4n * d * Gx;
      num += qx * qx + qy * qy;
    } });
  return { num, den: 96n * S * S };
}

// an exact fraction on the scaled drum -> the unit drum (T scales as length⁴)
const frac = (r, n) => ({ num: r.num, den: r.den * BigInt(n) ** 4n });
const dec = (f, k = 7) => { const s = 10n ** BigInt(k + 2); return (Number((f.num * s) / f.den) / Number(s)).toFixed(k); };
const lt = (f, g) => f.num * g.den < g.num * f.den;        // exact comparison of positive fractions
function bracket(macros, n) { const m = mesh(macros, n); return { lo: frac(lower(m), n), hi: frac(upper(m), n), mesh: m }; }

// ---------- 0. the meshes tile the octagons exactly ----------
{
  const inPoly = (P, x, y) => { let c = false; for (let i = 0, j = P.length - 1; i < P.length; j = i++) { const [xi, yi] = P[i], [xj, yj] = P[j]; if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c; } return c; };
  const inTri = ([a, b, c], x, y) => { const s = (p, q) => (q[0] - p[0]) * (y - p[1]) - (q[1] - p[1]) * (x - p[0]); const d1 = s(a, b), d2 = s(b, c), d3 = s(c, a); return (d1 > 0 && d2 > 0 && d3 > 0) || (d1 < 0 && d2 < 0 && d3 < 0); };
  for (const [nm, M, O] of [['A', MACROS_A, OCT_A], ['B', MACROS_B, OCT_B]]) {
    let bad = 0, pts = 0;
    // probe points off every lattice line and diagonal: (i + 0.13)/8, (j + 0.41)/8
    for (let i = -4; i < 28; i++) for (let j = -4; j < 28; j++) { const x = (i + 0.13) / 8, y = (j + 0.41) / 8; pts++;
      const cover = M.filter(t => inTri(t, x, y)).length; if (cover !== (inPoly(O, x, y) ? 1 : 0)) bad++; }
    const halfsq = M.every(([r, p, q]) => { const ux = p[0] - r[0], uy = p[1] - r[1], vx = q[0] - r[0], vy = q[1] - r[1]; return ux * vx + uy * vy === 0 && ux * ux + uy * uy === 1 && vx * vx + vy * vy === 1; });
    check(bad === 0 && halfsq, `Drum ${nm}: seven half unit squares (right angle listed first) covering its octagon exactly once at all ${pts} probe points`);
  }
}

// ---------- 1. the method on a shape with a known answer ----------
{
  let Tsq = 0; for (let j = 1; j < 4000; j += 2) for (let k = 1; k < 4000; k += 2) Tsq += 1 / (j * j * k * k * (j * j + k * k));
  Tsq *= 64 / Math.PI ** 6;      // unit square (Pólya and Szegő 1951; Comer and McDonald 2021, eq. for rectangles)
  const r = bracket(SQUARE, 32);
  const lo = Number(dec(r.lo, 9)), hi = Number(dec(r.hi, 9));
  check(lo < Tsq && Tsq < hi, `unit square: exact bounds [${dec(r.lo)}, ${dec(r.hi)}] contain the series value ${Tsq.toFixed(7)}`);
}

// ---------- 2. the two drums ----------
const res = {};
for (const n of [16, 64]) res[n] = { A: bracket(MACROS_A, n), B: bracket(MACROS_B, n) };
{
  for (const n of [16, 64]) console.log(`n=${n} (triangles of leg 1/${n}, ${res[n].A.mesh.tris.length} per drum):  T_A in [${dec(res[n].A.lo)}, ${dec(res[n].A.hi)}]   T_B in [${dec(res[n].B.lo)}, ${dec(res[n].B.hi)}]`);
  check(!lt(res[16].A.hi, res[16].B.lo) && !lt(res[16].B.hi, res[16].A.lo), 'control: at n=16 the two brackets overlap, so a coarse mesh does not separate the drums (the separation below is earned by refinement)');
  check(lt(res[64].A.hi, res[64].B.lo), `n=64: upper bound for Drum A (${dec(res[64].A.hi)}) < lower bound for Drum B (${dec(res[64].B.lo)}), compared as exact fractions`);
  const gap = { num: res[64].B.lo.num * res[64].A.hi.den - res[64].A.hi.num * res[64].B.lo.den, den: res[64].B.lo.den * res[64].A.hi.den };
  console.log(`      so T_B - T_A >= ${dec(gap, 7)}  (unit legs, area 7/2)`);
  check(true, 'hence T_A ≠ T_B: the drums have different torsional rigidity, so their heat contents differ (∫₀^∞ Q(t) dt = T)');
}

// ---------- 3. why the transplantation does not carry the heat across ----------
{
  // A transplantation U maps Drum A's heat flow to Drum B's; Q_B(t) = <Uᵀ1, e^{tΔ}Uᵀ1>.
  // If a unitary U had every column summing to 1 then Uᵀ1 = 1 and the heat contents would be
  // equal (the criterion Herbrich 2014, §6.5, uses). The recipe here has unequal column sums.
  const cs = [0, 1, 2, 3, 4, 5, 6].map(l => T.reduce((s, r) => s + r[l], 0));
  check(new Set(cs).size > 1, `column sums of the transplantation matrix are ${cs.join(', ')}: not all equal, so the recipe does not carry the constant temperature 1 to a constant`);
}

// ---------- 4. the late-time heat: the first mode's share (numerical, not a bound) ----------
{
  // Q(t) ~ e^{-λ1 t} (∫φ1)² as t -> ∞, and λ1 is the same for both drums, so the late-time
  // heat content compares (∫φ1)². Estimated from inverse iteration on the n=64 mesh.
  function firstMode(m) {
    const map = new Int32Array(m.N).fill(-1); let k = 0; for (let i = 0; i < m.N; i++) if (!m.rim[i]) map[i] = k++;
    const Kr = Array.from({ length: k }, () => new Map()), Mr = Array.from({ length: k }, () => new Map());
    m.tris.forEach((t, e) => { const g = m.geo[e];
      for (let a = 0; a < 3; a++) { const ia = map[t[a]]; if (ia < 0) continue;
        for (let c = 0; c < 3; c++) { const ic = map[t[c]]; if (ic < 0) continue;
          Kr[ia].set(ic, (Kr[ia].get(ic) || 0) + (g.gx[a] * g.gx[c] + g.gy[a] * g.gy[c]) / 2);
          Mr[ia].set(ic, (Mr[ia].get(ic) || 0) + (a === c ? 2 : 1) / 24); } } });
    const mul = (R, x) => { const y = new Float64Array(k); for (let i = 0; i < k; i++) { let s = 0; for (const [c, v] of R[i]) s += v * x[c]; y[i] = s; } return y; };
    let x = new Float64Array(k).fill(1), lam = 0;
    for (let it = 0; it < 40; it++) { const y = solveSPD(k, Kr, mul(Mr, x)); const My = mul(Mr, y); let nn = 0, kk = 0; const Ky = mul(Kr, y);
      for (let i = 0; i < k; i++) { nn += y[i] * My[i]; kk += y[i] * Ky[i]; } lam = kk / nn; const s = 1 / Math.sqrt(nn); for (let i = 0; i < k; i++) x[i] = y[i] * s; }
    const M1 = mul(Mr, new Float64Array(k).fill(1)); let I = 0; for (let i = 0; i < k; i++) I += M1[i] * x[i];
    return { lam: lam * m.n * m.n, a2: (I * I) / (m.n * m.n) };   // back to the unit drum
  }
  const fa = firstMode(res[64].A.mesh), fb = firstMode(res[64].B.mesh);
  console.log(`first mode, n=64:  λ1 A ${fa.lam.toFixed(4)}  B ${fb.lam.toFixed(4)}   (∫φ1)²  A ${fa.a2.toFixed(4)}  B ${fb.a2.toFixed(4)}`);
  check(Math.abs(fa.lam - fb.lam) / fa.lam < 1e-8 && Math.abs(fa.a2 - fb.a2) / fa.a2 > 0.05, 'same lowest note, but its share of the heat differs by more than 5% (so the drums differ in heat content at late times too; numerical estimate, not a bound)');
}

console.log(failed ? `\n${failed} CHECK(S) FAILED` : '\nALL CHECKS PASS');
process.exit(failed ? 1 : 0);
