#!/usr/bin/env sage # -*- coding: utf-8 -*- """ COMPREHENSIVE COHERENCE CHECK for N in {43, 67, 163}. For each relevant pair (i, j) and congruence prime r (from axis3_rigorous_newform_congruences.json), this script tests f_i[p] ≡ f_j[p] mod P for all prime ideals P dividing (r) in the relevant coefficient field (or compositum) and compares against the certified row list. Outputs: - quivers/coherence_results.json : machine-readable level summary - quivers/COHERENCE_CHECK.txt : human-readable log """ import json from collections import defaultdict from pathlib import Path from datetime import datetime RIGOROUS_JSON = Path(__file__).resolve().parent / "axis3_rigorous_newform_congruences.json" OUT_DIR = Path(__file__).resolve().parent / "quivers" OUT_DIR.mkdir(exist_ok=True) OUT_JSON = OUT_DIR / "coherence_results.json" OUT_TXT = OUT_DIR / "COHERENCE_CHECK.txt" HEEGNER_PRIMES = [43, 67, 163] PRIME_TEST_BOUND = 200 PRIME_TEST_COUNT = 45 SCHEMA_VERSION = "heegner-coherence-phase1-v1.2" def _read_json(path): try: with open(path, "r", encoding="utf-8") as fh: return json.load(fh) except Exception: return {} def _to_int(v): try: if v is None: return None return int(v) except Exception: return None def _to_int_list(values): out = [] for value in values: i = _to_int(value) if i is not None: out.append(i) return out def _now_iso(): return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") def _shorten(text, limit=90): text = str(text) if len(text) <= limit: return text return text[: limit - 3] + "..." def _coerce_for_json(obj): if obj is None or isinstance(obj, (str, bool, int, float)): return obj if isinstance(obj, dict): return {str(k): _coerce_for_json(v) for k, v in obj.items()} if isinstance(obj, (list, tuple)): return [_coerce_for_json(x) for x in obj] try: return int(obj) except Exception: pass try: return float(obj) except Exception: pass return str(obj) def _load_rigorous_rows(): """ Group rows as level -> (i, j) -> r -> [rows]. """ payload = _read_json(RIGOROUS_JSON) rows = payload.get("rows", []) grouped = {} for row in rows: level = _to_int(row.get("level")) if level not in HEEGNER_PRIMES: continue i = _to_int(row.get("pair_i")) j = _to_int(row.get("pair_j")) r = _to_int(row.get("r")) if i is None or j is None or r is None: continue if i == j: continue key = (min(i, j), max(i, j)) level_bucket = grouped.setdefault(level, {}) pair_bucket = level_bucket.setdefault(key, {}) pair_bucket.setdefault(r, []).append({ "r": r, "P_norm": _to_int(row.get("P_norm")), "f": _to_int(row.get("P_residue_degree")), "e": _to_int(row.get("P_ramification")), "L_degree": _to_int(row.get("L_degree")), "tested_primes": _to_int(row.get("tested_primes")), "mismatches": _to_int(row.get("mismatches")), "first_mismatches": _to_int_list(row.get("mismatch_primes_sample", [])), "congruent": bool(row.get("congruent")), }) return grouped def _test_prime_ideals_at_r(N, f_i, f_j, r): """ Re-test all prime ideals above r in the relevant coefficient field/compositum. Returns records per prime ideal. """ Ki = f_i.hecke_eigenvalue_field() Kj = f_j.hecke_eigenvalue_field() test_primes = [p for p in primes(PRIME_TEST_BOUND) if p != N][:PRIME_TEST_COUNT] def _run_in_field(field, embed_i, embed_j): records = [] for P, e_P in field.ideal(r).factor(): mismatches = [] tested = 0 for p in test_primes: try: a_i = embed_i(f_i[p]) a_j = embed_j(f_j[p]) tested += 1 if (a_i - a_j) not in P: mismatches.append(int(p)) except Exception: pass records.append({ "r": r, "P_desc": str(P), "P_norm": _to_int(P.absolute_norm()), "f": _to_int(P.residue_class_degree()), "e": _to_int(e_P), "tested": tested, "mismatches": len(mismatches), "first_mismatches": mismatches[:5], "congruent": bool(tested > 0 and not mismatches), }) return records # Same coefficient field. if Ki == Kj: embed_i = lambda x: Ki(x) embed_j = lambda x: Kj(x) try: return _run_in_field(Ki, embed_i, embed_j) except Exception: return [] # Rational/non-rational pair: embed into non-rational field. if Ki == QQ and Kj != QQ: try: return _run_in_field(Kj, lambda x: Kj(ZZ(x)), lambda x: Kj(x)) except Exception: return [] if Kj == QQ and Ki != QQ: try: return _run_in_field(Ki, lambda x: Ki(x), lambda x: Ki(ZZ(x))) except Exception: return [] # Both non-rational: use compositum maps. comp = Ki.composite_fields(Kj, both_maps=True) if not comp: return [] L_bundle = comp[0] if len(L_bundle) < 3: return [] L, map_i, map_j = L_bundle[0], L_bundle[1], L_bundle[2] try: return _run_in_field(L, map_i, map_j) except Exception: return [] def _support_mode(total_count, support_count): if total_count <= 0: return "none" if support_count == total_count and total_count > 1: return "complete" if support_count == 1: return "unique" return "split" def _summarize_level(level, pair_data): level_payload = { "level": level, "pair_checks": [], "n_pairs": len(pair_data), "n_arrows": 0, "n_retested_prime_ideals": 0, "n_unique_support": 0, "n_split_support": 0, "n_complete_support": 0, "all_unique": True, "all_arrow_tests_match_certified": True, "discrepancies": [], } print(f"\n{'='*78}") print(f"COHERENCE CHECK — Q_{level}") print(f"{'='*78}") NF = CuspForms(Gamma0(level), 2).newforms("a") for (i, j) in sorted(pair_data): for r in sorted(pair_data[(i, j)]): certified_rows = sorted( pair_data[(i, j)][r], key=lambda row: (row.get("P_norm", 0), row.get("f", 0), row.get("e", 0)), ) records = _test_prime_ideals_at_r(level, NF[i], NF[j], r) level_payload["n_retested_prime_ideals"] += len(records) support_rows = [r for r in records if r["congruent"]] support_count = len(support_rows) rec_key_count = len(records) support_mode = _support_mode(rec_key_count, support_count) congruent_count = sum(1 for rr in certified_rows if rr.get("congruent")) total_certified = len(certified_rows) certified_mode = _support_mode(total_certified, congruent_count) if support_count > 0: level_payload["n_arrows"] += 1 if support_mode == "unique": level_payload["n_unique_support"] += 1 elif support_mode == "split": level_payload["n_split_support"] += 1 level_payload["all_unique"] = False elif support_mode == "complete": level_payload["n_complete_support"] += 1 if support_count != congruent_count or rec_key_count != total_certified: level_payload["all_arrow_tests_match_certified"] = False level_payload["discrepancies"].append({ "pair": [i, j], "r": r, "certified_rows": total_certified, "retested_rows": rec_key_count, "certified_congruent": congruent_count, "retested_congruent": support_count, }) print( f" pair ({i},{j}) at r={r}: " f"{len(records)} prime(s) tested, support={support_count} congruent " f"(mode={support_mode}, certified={certified_mode})" ) for rec in records: tag = "CONGRUENT" if rec["congruent"] else f"NOT ({rec['first_mismatches'][:3]})" print( f" P={_shorten(rec['P_desc'])} norm={rec['P_norm']} f={rec['f']} e={rec['e']}: " f"{rec['tested']-rec['mismatches']}/{rec['tested']} -> {tag}" ) level_payload["pair_checks"].append({ "pair": [i, j], "r": r, "arrow_supports": records, "support_count": support_count, "tested_prime_ideals": rec_key_count, "support_mode": support_mode, "certified_support_mode": certified_mode, "certified": certified_rows, }) level_payload["all_support_is_unique"] = all( pc["support_mode"] == "unique" for pc in level_payload["pair_checks"] if pc["support_count"] > 0 ) return level_payload def main(): certified = _load_rigorous_rows() results = { "schema_version": SCHEMA_VERSION, "generated_at": _now_iso(), "levels": [], "summary": { "levels_checked": [], "all_checked_levels_unique": True, "all_levels_match_certified": True, }, } text_lines = [ "=" * 78, "COMPREHENSIVE COHERENCE CHECK", "=" * 78, ] for level in HEEGNER_PRIMES: pair_data = certified.get(level, {}) if not pair_data: text_lines.append(f"Q_{level}: no certified rows available") continue level_result = _summarize_level(level, pair_data) results["levels"].append(level_result) results["summary"]["levels_checked"].append(level) if not level_result["all_support_is_unique"]: results["summary"]["all_checked_levels_unique"] = False if not level_result["all_arrow_tests_match_certified"]: results["summary"]["all_levels_match_certified"] = False n_arrows = level_result["n_arrows"] n_unique = level_result["n_unique_support"] text_lines.append("") text_lines.append( f"Q_{level}: arrows={n_arrows}, unique={n_unique}, " f"split={level_result['n_split_support']}, complete={level_result['n_complete_support']}, " f"all_unique={level_result['all_support_is_unique']}" ) for pc in level_result["pair_checks"]: text_lines.append( f" pair {tuple(pc['pair'])} at r={pc['r']}: " f"{pc['support_count']}/{pc['tested_prime_ideals']} support -> {pc['support_mode']} " f"(certified {pc['certified_support_mode']})" ) text_lines.append(f" Verdict: {'unique' if level_result['all_support_is_unique'] else 'not unique'}") text_lines.extend([ "", "=" * 78, "GLOBAL VERDICT", "=" * 78, f"All checked levels prime-ideal unique: {results['summary']['all_checked_levels_unique']}", f"All re-tests match certified row payloads: {results['summary']['all_levels_match_certified']}", ]) with open(OUT_JSON, "w", encoding="utf-8") as fh: json.dump(_coerce_for_json(results), fh, indent=2) with open(OUT_TXT, "w", encoding="utf-8") as fh: fh.write("\n".join(text_lines) + "\n") print(f"\nSaved JSON: {OUT_JSON}") print(f"Saved text: {OUT_TXT}") print("Summary:\n all_unique =", results["summary"]["all_checked_levels_unique"]) print(" certified_match =", results["summary"]["all_levels_match_certified"]) if __name__ == "__main__": main()