// census.mjs — the perfect codes are a FINITE, named list. Verify the arithmetic
// of the whole census, including the ternary Golay code and the famous "phantom".
//   node research/perfect-codes/census.mjs
//
// A q-ary code of length n, size M, minimum distance d=2t+1 is PERFECT when its M
// Hamming balls of radius t tile the whole space F_q^n exactly:
//        M · Vol_q(n,t) = q^n,   Vol_q(n,t) = Σ_{i=0..t} C(n,i)(q-1)^i.
// The classification theorem (van Lint 1971; Tietäväinen 1973): over ANY finite
// field, the only perfect codes are
//   • the trivial ones (the whole space; a single codeword; binary repetition of odd length);
//   • the Hamming-parameter codes  [ (q^r−1)/(q−1), n−r, 3 ]  (t=1);
//   • the binary  Golay  [23, 12, 7]  (t=3);
//   • the ternary Golay  [11,  6, 5]  (t=2).
// Nothing else, for any q, n, t. This file checks every arithmetic claim in that
// list, constructs the ternary Golay from scratch, and exhibits the PHANTOM:
// a parameter set that satisfies the sphere bound with equality yet — proven —
// corresponds to no code at all.

const C = (n, k) => { let r = 1n; for (let i = 0n; i < BigInt(k); i++) r = r * (BigInt(n) - i) / (i + 1n); return r; };
const vol = (n, t, q) => { let s = 0n; for (let i = 0; i <= t; i++) s += C(n, i) * (BigInt(q) - 1n) ** BigInt(i); return s; };

let pass = 0, fail = 0;
const check = (c, m) => { (c ? pass++ : fail++); console.log((c ? '  ✓ ' : '  ✗ ') + m); };

console.log('The census of perfect codes — every sphere-packing identity, checked\n');

// ---------- Hamming family (t = 1) ----------
console.log('Hamming-parameter codes  [ (q^r−1)/(q−1), n−r, 3 ],  t = 1:');
for (const [q, r] of [[2, 3], [2, 4], [2, 5], [3, 2], [3, 3], [5, 2]]) {
  const n = (BigInt(q) ** BigInt(r) - 1n) / (BigInt(q) - 1n);
  const k = n - BigInt(r);
  const M = BigInt(q) ** k;
  const ok = M * vol(Number(n), 1, q) === BigInt(q) ** n;
  check(ok, `q=${q}, r=${r}: [${n}, ${k}, 3]  ${M}·(1+${n}·${q - 1}) = ${q}^${n}`);
}

// ---------- binary Golay [23,12,7] (verified in full in golay.mjs) ----------
console.log('\nGolay codes:');
check(4096n * vol(23, 3, 2) === 2n ** 23n,
  `binary  [23,12,7], t=3:  2^12·(1+23+253+1771)=2^12·2048 = 2^23  (code built in golay.mjs)`);

// ---------- ternary Golay [11,6,5] — construct from scratch over F3 ----------
// Extended ternary Golay [12,6,6] = [I_6 | B] over F3, B a bordered Paley matrix
// on the projective line over F5 = {∞,0,1,2,3,4}. Search conventions; accept only
// the B realising the known weight enumerator A0=1,A6=264,A9=440,A12=24 (sum 729).
const P5 = 5, QR5 = new Set([1, 4]);          // quadratic residues mod 5
const chi = x => { const m = ((x % P5) + P5) % P5; return m === 0 ? 0 : (QR5.has(m) ? 1 : 2); }; // {0,+1,-1≡2}
const mod3 = x => ((x % 3) + 3) % 3;

function buildB3({ scale, corner, border, bcol }) {
  const B = Array.from({ length: 6 }, () => new Array(6).fill(0));
  for (let i = 0; i < 5; i++) for (let j = 0; j < 5; j++) B[i][j] = mod3(scale * chi(i - j));
  for (let k = 0; k < 5; k++) { B[5][k] = border; B[k][5] = bcol; }
  B[5][5] = corner;
  return B;
}
function ternaryCode(B) {
  // generator rows over F3 (length 12): row r = e_r ++ B[r]
  const rows = [];
  for (let r = 0; r < 6; r++) { const row = new Array(12).fill(0); row[r] = 1; for (let c = 0; c < 6; c++) row[6 + c] = B[r][c]; rows.push(row); }
  const words = [];
  for (let m = 0; m < 729; m++) {
    const coeff = []; let mm = m; for (let r = 0; r < 6; r++) { coeff.push(mm % 3); mm = (mm / 3) | 0; }
    const w = new Array(12).fill(0);
    for (let r = 0; r < 6; r++) if (coeff[r]) for (let c = 0; c < 12; c++) w[c] = mod3(w[c] + coeff[r] * rows[r][c]);
    words.push(w);
  }
  return words;
}
const wt = w => w.reduce((s, x) => s + (x !== 0 ? 1 : 0), 0);
function enum3(words) { const A = {}; for (const w of words) { const k = wt(w); A[k] = (A[k] || 0) + 1; } return A; }
const TGOLAY12 = { 0: 1, 6: 264, 9: 440, 12: 24 };
const eqE = (a, b) => { const ks = new Set([...Object.keys(a), ...Object.keys(b)]); for (const k of ks) if ((a[k] || 0) !== (b[k] || 0)) return false; return true; };

let tern = null;
for (const scale of [1, 2])
  for (const corner of [0, 1, 2])
    for (const border of [0, 1, 2])
      for (const bcol of [0, 1, 2]) {
        const B = buildB3({ scale, corner, border, bcol });
        const words = ternaryCode(B);
        if (eqE(enum3(words), TGOLAY12)) { tern = { B, words, conv: { scale, corner, border, bcol } }; break; }
      }
check(!!tern, tern
  ? `ternary [12,6,6] built (Paley/F5, conv ${JSON.stringify(tern.conv)}) — weight enum A0=1,A6=264,A9=440,A12=24`
  : 'could not construct the extended ternary Golay code');

if (tern) {
  // puncture to [11,6,5]: drop last coordinate
  const w11 = tern.words.map(w => w.slice(0, 11));
  const distinct = new Set(w11.map(w => w.join(''))).size;
  check(distinct === 729, `puncturing keeps 729 = 3^6 distinct words ⇒ ternary Golay [11,6,5]`);
  const nz = w11.map(wt).filter(x => x > 0);
  check(Math.min(...nz) === 5, `ternary Golay minimum distance d = 5 ⇒ corrects t = 2 errors`);
  check(729n * vol(11, 2, 3) === 3n ** 11n,
    `PERFECT: 3^6·(1+11·2+55·4)=3^6·(1+22+220)=3^6·243 = 3^11 = ${3n ** 11n}`);
}

// ---------- trivial perfect codes ----------
console.log('\nTrivial perfect codes:');
check(2n ** 7n * vol(7, 0, 2) === 2n ** 7n,
  `whole space (t=0): every point is its own ball, M·1 = q^n trivially`);
check(2n * vol(7, 3, 2) === 2n ** 7n,
  `binary repetition [7,1,7], t=3: the 2 words {0000000,1111111}, 2·64 = 2^7`);
check(2n * vol(5, 2, 2) === 2n ** 5n,
  `binary repetition [5,1,5], t=2: 2·(1+5+10) = 2·16 = 2^5`);

// ---------- the PHANTOM: passes the bound, but no code exists ----------
console.log('\nThe phantom — the sphere bound is NECESSARY, not SUFFICIENT:');
const ball90 = vol(90, 2, 2); // 1 + 90 + C(90,2)
check(ball90 === 4096n && ball90 === 2n ** 12n,
  `a [90,78,5] 2-error-correcting binary code would need balls of 1+90+4005 = 4096 = 2^12`);
check(2n ** 78n * ball90 === 2n ** 90n,
  `and 2^78·2^12 = 2^90 EXACTLY — the sphere-packing identity is satisfied with equality`);
// Lloyd's theorem (S. P. Lloyd 1957, binary; extended to prime powers by Delsarte and
// others): if a perfect e-error-correcting code of length n exists, the Lloyd polynomial
//   L_e(x) = sum_{j=0..e} (-1)^j (q-1)^(e-j) C(x-1, j) C(n-x, e-j)
// has e distinct integer zeros in 1..n. The phantom balances the count but FAILS this
// test: for n = 90, e = 2 it is 2(x^2 - 91x + 2048), zeros (91 ± sqrt 89)/2. Corrected
// 2026-09-28: this file used to print that the phantom "even satisfies Lloyd's theorem"
// from four check(true, ...) lines that computed nothing; the page said the same.
const Cx = (a, b) => (b < 0 || a < b || a < 0) ? 0n : C(a, b);
const lloyd = (n, e, q, x) => { let s = 0n; for (let j = 0; j <= e; j++) s += (j % 2 ? -1n : 1n) * (BigInt(q) - 1n) ** BigInt(e - j) * Cx(x - 1, j) * Cx(n - x, e - j); return s; };
const zeros = (n, e, q) => { const z = []; for (let x = 1; x <= n; x++) if (lloyd(n, e, q, x) === 0n) z.push(x); return z; };
const zG23 = zeros(23, 3, 2), zG11 = zeros(11, 2, 3), zP90 = zeros(90, 2, 2);
check(zG23.length === 3,
  `Lloyd's test, positive control: binary Golay n=23, e=3 has 3 integer zeros {${zG23.join(', ')}}`);
check(zG11.length === 2,
  `Lloyd's test, positive control: ternary Golay n=11, e=2 has 2 integer zeros {${zG11.join(', ')}}`);
check(zP90.length === 0 && lloyd(90, 2, 2, 41) === 2n * (41n * 41n - 91n * 41n + 2048n),
  `the phantom FAILS it: L_2(x) = 2(x^2 - 91x + 2048) for n=90 has no integer zero in 1..90, so no such code exists`);
console.log(`   The count opens a door that Lloyd's theorem (1957) shuts: necessary, not sufficient.`);
console.log(`   (It is also neither a Hamming nor a Golay parameter set, so the classification forbids it too.)`);

console.log(`\n${pass}/${pass + fail} checks passed.`);
process.exit(fail ? 1 : 0);
