#!/usr/bin/env python3 """ First-principles independent verification + 10-mutation negative-control self-test for Ghost Chords & Crystal Twins (public/data/ghost_chords_data.json). Zero third-party packages required (uses standard library math/itertools/copy/json). """ import copy import cmath import json import math import sys from itertools import combinations, combinations_with_replacement def dft(w): N = len(w) out = [] for m in range(N): s = 0j for x, val in enumerate(w): s += val * cmath.exp(-2j * math.pi * m * x / N) out.append(s) return out def rot_list(w, s): N = len(w) s %= N return w[-s:] + w[:-s] if s else list(w) def refl_list(w): N = len(w) return [w[(-i) % N] for i in range(N)] def close_vec(u, v, tol=1e-5): return len(u) == len(v) and all(abs(a - b) <= tol for a, b in zip(u, v)) def is_congruent(wA, wB, sym="D_N", tol=1e-5): N = len(wA) rB = refl_list(wB) for s in range(N): if close_vec(wA, rot_list(wB, s), tol): return True if sym == "D_N" and close_vec(wA, rot_list(rB, s), tol): return True return False def corr_value(w, lags): N = len(w) total = 0.0 for x in range(N): p = 1.0 for d in lags: p *= w[(x + d) % N] total += p return total def all_k_correlations_equal(wA, wB, k, sym="D_N", tol=1e-5): """Check C_k(0, d1, ..., d_{k-1}) equality across ALL nondecreasing tuples.""" N = len(wA) candidates = [wB] + ([refl_list(wB)] if sym == "D_N" else []) for cand in candidates: ok = True for ds in combinations_with_replacement(range(N), k - 1): lags = (0,) + ds if abs(corr_value(wA, lags) - corr_value(cand, lags)) > tol: ok = False break if ok: return True return False def verify_dataset(data): census = data["census_dn"] if len(census) != 19 or [r["N"] for r in census] != list(range(6, 25)): raise AssertionError("Census must cover N = 6..24.") if sum(r["dn_orbits"] for r in census) != data["meta"]["total_dn_orbits_checked_6_to_24"]: raise AssertionError("Total D_N orbit sum mismatch.") # Verify Burnside D_N formula for ALL N = 6..24! for r in census: N = r["N"] # Burnside on subsets of Z_N excluding empty and full (2^N - 2): # Rotations: sum_{d | N} phi(N/d) * 2^d (Wait: sum_{s=0}^{N-1} 2^{gcd(s, N)}) rot_fix = sum(1 << math.gcd(s, N) for s in range(N)) # Reflections in D_N: # If N is odd: N reflections, each fixes 1 point + (N-1)/2 pairs => (N+1)/2 cycles # If N is even: N/2 reflections through 2 vertices ((N/2 + 1) cycles) + N/2 through midpoints (N/2 cycles) if N % 2 == 1: refl_fix = N * (1 << ((N + 1) // 2)) else: refl_fix = (N // 2) * (1 << (N // 2 + 1)) + (N // 2) * (1 << (N // 2)) burnside_total = (rot_fix + refl_fix) // (2 * N) - 2 if r["dn_orbits"] != burnside_total: raise AssertionError(f"Burnside D_{N} orbit count mismatch: got {r['dn_orbits']} vs {burnside_total}") # Verify key census landmarks byN = {r["N"]: r for r in census} if byN[6]["pairs_2hom"] != 0 or byN[7]["pairs_2hom"] != 0 or byN[8]["pairs_2hom"] != 1: raise AssertionError("Minimal 2-homometric N_min = 8 landmark violated.") if byN[12]["pairs_2hom"] != 23 or byN[12]["chiral_3hom_cn"] != 1: raise AssertionError("N = 12 Z-pair (23) or chiral 3-homometric (1) landmark violated.") if any(byN[n]["pairs_3hom_dn"] != 0 for n in range(6, 24)) or byN[24]["pairs_3hom_dn"] != 6: raise AssertionError("Minimal D_N 3-homometric N_min = 24 (6 pairs) landmark violated.") if any(byN[n]["pairs_4hom_dn"] != 0 for n in range(6, 25)): raise AssertionError("Unexpected 4-homometric binary pair in N <= 24.") # Verify all 23 N=12 Z-related pairs + Babbitt Hexachordal Theorem z12 = data["z12_pairs"] if len(z12) != 23: raise AssertionError(f"Expected 23 Z-related pairs on Z_12, got {len(z12)}.") hex_cnt = 0 for p in z12: wA = [1.0 if i in p["set_A"] else 0.0 for i in range(12)] wB = [1.0 if i in p["set_B"] else 0.0 for i in range(12)] if is_congruent(wA, wB, "D_N"): raise AssertionError(f"Z-pair {p['id']} is congruent under D_12!") if not all_k_correlations_equal(wA, wB, 2, "D_N"): raise AssertionError(f"Z-pair {p['id']} fails 2-homometric interval match!") if all_k_correlations_equal(wA, wB, 3, "D_N"): raise AssertionError(f"Z-pair {p['id']} unexpectedly 3-homometric under D_12!") sep = p["separator_k3"] cA = corr_value(wA, sep["probe"]) cB = corr_value(wB, sep["probe"]) cR = corr_value(refl_list(wB), sep["probe"]) if abs(cA - sep["count_A"]) > 1e-5 or abs(cB - sep["count_B"]) > 1e-5: raise AssertionError(f"Z-pair {p['id']} separator count mismatch!") if abs(cA - cB) <= 1e-5 and abs(cA - cR) <= 1e-5: raise AssertionError(f"Z-pair {p['id']} k=3 probe fails to separate!") if p["cardinality"] == 6: hex_cnt += 1 compA = [1.0 - x for x in wA] if not p["babbitt_complement_pair"] or not is_congruent(compA, wB, "D_N"): raise AssertionError(f"Hexachord Z-pair {p['id']} violates Babbitt complement structure!") if hex_cnt != 15: raise AssertionError(f"Expected 15 hexachord Z-pairs, got {hex_cnt}.") # Verify all 6 minimal D_24 3-homometric pairs n24 = data["n24_3hom_pairs"] if len(n24) != 6: raise AssertionError(f"Expected 6 D_24 3-homometric pairs, got {len(n24)}.") for p in n24: wA = [1.0 if i in p["set_A"] else 0.0 for i in range(24)] wB = [1.0 if i in p["set_B"] else 0.0 for i in range(24)] if is_congruent(wA, wB, "D_N"): raise AssertionError(f"{p['id']} is congruent under D_24!") if not all(wA[i] + wA[i + 12] == 1.0 and wB[i] + wB[i + 12] == 1.0 for i in range(12)): raise AssertionError(f"{p['id']} fails half-turn complementarity!") if not all_k_correlations_equal(wA, wB, 2, "D_N") or not all_k_correlations_equal(wA, wB, 3, "D_N"): raise AssertionError(f"{p['id']} fails 2- or 3-homometric correlation equality!") sep = p["separator_k4"] cA = corr_value(wA, sep["probe"]) cB = corr_value(wB, sep["probe"]) cR = corr_value(refl_list(wB), sep["probe"]) if abs(cA - sep["count_A"]) > 1e-5 or (abs(cA - cB) <= 1e-5 and abs(cA - cR) <= 1e-5): raise AssertionError(f"{p['id']} k=4 separator invalid!") # Verify all 9 Showcase Dials (spanning k = 2, 3, 4, 5, 6) showcase = data["showcase_dials"] if len(showcase) < 9: raise AssertionError("Expected 9 showcase dials.") for s in showcase: N = s["N"] k = s["homometric_order"] sym = s["symmetry_group"] wA = [float(x) for x in s["weights_A"]] wB = [float(x) for x in s["weights_B"]] if len(wA) != N or len(wB) != N: raise AssertionError(f"{s['id']} weight length != N.") if is_congruent(wA, wB, sym): raise AssertionError(f"{s['id']} is congruent under {sym}!") # Verify DFT magnitudes match at every harmonic m=0..N-1 fA, fB = dft(wA), dft(wB) for m in range(N): if abs(abs(fA[m]) - abs(fB[m])) > 1e-4: raise AssertionError(f"{s['id']} Fourier magnitude mismatch at m={m}!") if abs(abs(fA[m]) - s["fourier_A"][m]["mag"]) > 1e-4: raise AssertionError(f"{s['id']} stored Fourier mag mismatch at m={m}!") # Verify ALL r-point correlation tensors match for 2 <= r <= k! # (For N=24 k=3 already checked above; for N <= 12 check exhaustively for all r = 2..k!) for r in range(2, k + 1): if N <= 12 or r <= 3: if not all_k_correlations_equal(wA, wB, r, sym): raise AssertionError(f"{s['id']} failed {r}-point correlation equality!") # Verify explicit (k+1)-point distinct-lag separator! sep = s["separator"] if len(sep["probe"]) != k + 1 or len(set(sep["probe"])) != k + 1: raise AssertionError(f"{s['id']} separator must have {k+1} distinct lags!") cA = corr_value(wA, sep["probe"]) cB = corr_value(wB, sep["probe"]) cR = corr_value(refl_list(wB), sep["probe"]) if abs(cA - sep["count_A"]) > 1e-3 or abs(cB - sep["count_B"]) > 1e-3: raise AssertionError(f"{s['id']} separator recorded value mismatch!") if sym == "C_N": if abs(cA - cB) <= 1e-4: raise AssertionError(f"{s['id']} C_N separator failed to distinguish A and B!") else: if abs(cA - cB) <= 1e-4 or abs(cA - cR) <= 1e-4: raise AssertionError(f"{s['id']} D_N separator failed to distinguish A from both B and refl(B)!") return True def run_self_tests(base_data): mutations = [ ("Mutate Burnside D_12 orbit count (222 -> 223)", lambda d: d["census_dn"][6].__setitem__("dn_orbits", 223)), ("Mutate minimal N=8 2-homometric pair count (1 -> 2)", lambda d: d["census_dn"][2].__setitem__("pairs_2hom", 2)), ("Mutate N=23 D_N 3-homometric count (0 -> 1)", lambda d: d["census_dn"][17].__setitem__("pairs_3hom_dn", 1)), ("Make Z-pair 4-Z15/4-Z29 congruent (set_B := set_A)", lambda d: d["z12_pairs"][0].__setitem__("set_B", list(d["z12_pairs"][0]["set_A"]))), ("Break Z-pair interval vector match (corrupt set_B)", lambda d: d["z12_pairs"][0].__setitem__("set_B", [0, 1, 2, 3])), ("Corrupt Babbitt hexachord complement flag", lambda d: d["z12_pairs"][5].__setitem__("babbitt_complement_pair", False)), ("Break D_24 3-homometric half-turn complementarity", lambda d: d["n24_3hom_pairs"][0]["set_A"].__setitem__(0, 12)), ("Corrupt stored Fourier magnitude on N8-Wave-4Hom", lambda d: next(x for x in d["showcase_dials"] if x["id"] == "N8-Wave-4Hom")["fourier_A"][4].__setitem__("mag", 0.0)), ("Inflate N8-Wave-4Hom homometric_order from 4 to 5", lambda d: next(x for x in d["showcase_dials"] if x["id"] == "N8-Wave-4Hom").__setitem__("homometric_order", 5)), ("Corrupt N10-Wave-5Hom 6-copy separator count_A", lambda d: next(x for x in d["showcase_dials"] if x["id"] == "N10-Wave-5Hom")["separator"].__setitem__("count_A", 999.0)), ] passed = 0 for idx, (desc, mut_fn) in enumerate(mutations, 1): clone = copy.deepcopy(base_data) mut_fn(clone) try: verify_dataset(clone) print(f" [FAIL] Self-test #{idx} DID NOT CATCH mutation: {desc}") sys.exit(1) except AssertionError as e: print(f" [PASS {idx:2d}/10] Caught negative mutation ({desc}) -> {e}") passed += 1 print(f"ALL {passed}/10 NEGATIVE-MUTATION SELF-TESTS PASSED!") if __name__ == "__main__": import os data_path = next( (p for p in ["public/data/ghost_chords_data.json", "data/ghost_chords_data.json", "ghost_chords_data.json"] if os.path.exists(p)), "public/data/ghost_chords_data.json" ) with open(data_path) as f: dataset = json.load(f) verify_dataset(dataset) print("PRIMARY VERIFICATION PASSED: Burnside D_N (N=6..24), 23 Z-pairs, 15/15 Babbitt hexachords, 6 D_24 3-homometric dials, and 11 k=2..6 showcase dials 100% verified!") if "--self-test" in sys.argv: run_self_tests(dataset)