#!/usr/bin/env sage # -*- coding: utf-8 -*- """ HEEGNER ATLAS v2 — herbouwde, reproduceerbare Sage-pipeline =========================================================== Richard Hoekstra / herschreven met structurele correcties Doelen ------ - Correcte canonieke data voor de 9 Heegner-getallen d ∈ {1,2,3,7,11,19,43,67,163} - Robuuste metadata, resume-ondersteuning, logging en validatie - Vervanging van de oude experimentele assen 3/8 door: * Hecke-operator diagnostiek * exactere mod-p / mod-P congruentiediagnostiek op newform-niveau - Scheiding tussen: * canonical invariants * experimental invariants Belangrijkste fixes t.o.v. de oude atlas ---------------------------------------- 1. Kronecker/splitting gebruikt veld-discriminant D_K, niet -d. 2. Supersingulariteit wordt correct getest via reductie-object indien mogelijk; anders via a_p ≡ 0 mod p voor p > 3. 3. Output bevat metadata, status en foutregistratie. 4. Resume/skip-existing werkt echt. 5. Nieuwe congruentie-as gebruikt een strengere test op Hecke-eigenwaarden. 6. Oude "Hecke-algebra discriminant" is vervangen door trace-Gram diagnostics met eerlijke naamgeving. Gebruik ------- sage heegner_atlas_v2.sage sage heegner_atlas_v2.sage --force sage heegner_atlas_v2.sage --axes 1,2,3,4 sage heegner_atlas_v2.sage --profile light sage heegner_atlas_v2.sage --prime-bound 200 --hecke-prime-bound 100 Opmerking --------- Volledig exact werken met priemidealen in coefficient/compositumvelden voor alle newform-paren is in Sage niet overal uniform en kan zwaar zijn. Daarom implementeert deze atlas: - een strikte rationele mod-p congruentiediagnostiek waar exact mogelijk; - plus operator-level congruentiediagnostiek als fallback; - en markeert alle resultaten met statusvelden. """ import os import sys import csv import json import time import traceback from dataclasses import dataclass, asdict from pathlib import Path from itertools import combinations # --------------------------------------------------------------------------- # CONFIG # --------------------------------------------------------------------------- HEEGNER = [1, 2, 3, 7, 11, 19, 43, 67, 163] HEEGNER_PRIMES = [3, 7, 11, 19, 43, 67, 163] DEFAULT_SMALL_PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67] @dataclass class AtlasConfig: out_dir: str = "heegner_atlas_output_v2" force: bool = False profile: str = "full" # light | full prime_bound: int = 200 hecke_prime_bound: int = 100 operator_prime_bound: int = 50 congruence_test_primes: int = 45 axes: tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) @property def test_primes(self): return list(primes_first_n(self.prime_bound if self.profile == "full" else min(60, self.prime_bound))) @property def small_primes(self): return [p for p in DEFAULT_SMALL_PRIMES if p <= max(DEFAULT_SMALL_PRIMES)] @property def hecke_primes(self): return list(primes(self.hecke_prime_bound + 1)) @property def operator_primes(self): return list(primes(self.operator_prime_bound + 1)) CFG = None OUT = None # --------------------------------------------------------------------------- # ATLAS LAYER 0 — STATUS / PROVENANCE TABLE # --------------------------------------------------------------------------- # Every output file carries a three-field classification in its meta block: # status : canonical | rigorous | numerical | experimental | deprecated # provenance : atlas_core | supplement | derived | fallback | failed_api # confidence_note : short human-readable hedge # # Keys here match (axis_no, slug) used in write_json() call sites. AXIS_STATUS = { (1, "number_fields"): ("canonical", "atlas_core", "Classical arithmetic invariants of Q(sqrt(-d)); class numbers verified = 1"), (1, "splitting"): ("canonical", "atlas_core", "Prime splitting via Kronecker symbol on D_K"), (2, "modular_curves"): ("canonical", "atlas_core", "X_0(N) invariants; orbit-dim sums verified equal to dim S_2"), (3, "hecke_diagnostics"): ("experimental", "atlas_core", "Hecke-operator trace/det/charpoly statistics, not a congruence proof"), (3, "newform_pair_congruences"): ("experimental", "atlas_core", "Rational mod-p visibility + space-level mod-p operator signatures"), (3, "rigorous_newform_congruences"): ("rigorous", "atlas_core", "a_p(f_i) - a_p(f_j) in P for all tested p, via compositum fields"), (4, "elliptic_curves"): ("canonical", "atlas_core", "Elliptic curve invariants plus local data"), (4, "ap_table"): ("canonical", "atlas_core", "a_p for each curve over test primes"), (5, "multiplicative_groups"): ("experimental", "atlas_core", "Structural invariants of (Z/NZ)^*"), (6, "euler_polynomials"): ("canonical", "atlas_core", "Prime-producing Euler polynomials n^2+n+(d+1)/4"), (7, "hecke_eigenvalues"): ("canonical", "atlas_core", "Newform q-expansions by orbit"), (7, "eigenvalue_table"): ("canonical", "atlas_core", "Hecke eigenvalue CSV"), (8, "heegner_prime_signatures"): ("experimental", "atlas_core", "Space-level signatures, not orbit-level prime-ideal proofs"), (8, "operator_collisions"): ("experimental", "atlas_core", "Heuristic operator mod-p collisions"), (9, "isogeny_class_summaries"): ("canonical", "atlas_core", "Isogeny class per optimal curve"), (10, "modular_symbols"): ("numerical", "atlas_core", "Modular symbol dimensions and numerical periods"), (11, "l_values"): ("numerical", "atlas_core", "L(E,s) numerics; BSD quantities conditional on BSD"), (12, "galois_and_selmer"): ("canonical", "atlas_core", "Galois representation image; (conditional) Selmer"), # Derived layer built after axes 1-12: (13, "orbit_registry"): ("canonical", "derived", "Per-orbit index linking q-expansions, curves, congruences"), (13, "cm_singular_moduli"): ("canonical", "derived", "Singular j-values and Ramanujan near-integer deviations"), (13, "master_congruence_table"): ("rigorous", "derived", "All prime-ideal newform congruences in one table"), (13, "jacobian_factorization"): ("canonical", "derived", "J_0(N) decomposition into simple factors by newform orbits"), (13, "heegner_hypothesis_matrix"): ("canonical", "derived", "(level, -d or -4d) Heegner hypothesis validity matrix"), (13, "global_summary"): ("numerical", "derived", "One-row-per-level atlas overview"), } def status_payload(axis_no, slug): entry = AXIS_STATUS.get((axis_no, slug)) if entry is None: return {"status": "unknown", "provenance": "unknown", "confidence_note": ""} s, p, n = entry return {"status": s, "provenance": p, "confidence_note": n} # --------------------------------------------------------------------------- # UTILITIES # --------------------------------------------------------------------------- def sage_version_string(): try: return str(version()) except Exception: try: import sage return getattr(sage, "__version__", "unknown") except Exception: return "unknown" def now_iso(): return time.strftime("%Y-%m-%dT%H:%M:%S") def ensure_out(): Path(CFG.out_dir).mkdir(parents=True, exist_ok=True) def axis_filename(axis_no, slug, ext="json"): return Path(CFG.out_dir) / f"axis{axis_no}_{slug}.{ext}" def index_filename(): return Path(CFG.out_dir) / "INDEX.json" def should_run(axis_no, slug): return CFG.force or (not axis_filename(axis_no, slug).exists()) def serialize(obj): try: json.dumps(obj) return obj except Exception: return str(obj) def safe_int(x): try: return int(x) except Exception: return str(x) def error_payload(exc): return { "type": type(exc).__name__, "message": str(exc), "traceback": traceback.format_exc(limit=5), } def write_json(axis_no, slug, rows, meta_extra=None): ensure_out() # meta_extra overrides status_payload fields if the caller passes its own. stamp = status_payload(axis_no, slug) payload = { "meta": { "axis": axis_no, "slug": slug, "created_at": now_iso(), "sage_version": sage_version_string(), "config": asdict(CFG), **stamp, **(meta_extra or {}), }, "rows": rows, } path = axis_filename(axis_no, slug, "json") with open(path, "w", encoding="utf-8") as f: json.dump(payload, f, indent=2, default=str, ensure_ascii=False) print(f" → {path}") return path def write_csv(axis_no, slug, headers, rows): ensure_out() path = axis_filename(axis_no, slug, "csv") with open(path, "w", newline="", encoding="utf-8") as f: w = csv.writer(f) w.writerow(headers) w.writerows(rows) print(f" → {path}") return path def timer(label): class T: def __enter__(self): self.t0 = time.time() print("\n" + "=" * 78) print(f" {label}") print("=" * 78) return self def __exit__(self, exc_type, exc, tb): dt = time.time() - self.t0 print(f" [{label}] klaar in {dt:.1f}s") return T() # --------------------------------------------------------------------------- # CACHES # --------------------------------------------------------------------------- _SPACE_CACHE = {} _NEWFORM_CACHE = {} _ELL_CURVE_CACHE = {} def get_quadratic_field(d): if d not in _SPACE_CACHE: if d == 1: K = QuadraticField(-1, 'i') else: K = QuadraticField(-d, 'a') _SPACE_CACHE[("K", d)] = K return _SPACE_CACHE[("K", d)] def get_cusp_space(level): key = ("S2", level) if key not in _SPACE_CACHE: _SPACE_CACHE[key] = CuspForms(Gamma0(level), 2) return _SPACE_CACHE[key] def get_mod_space(level): key = ("M2", level) if key not in _SPACE_CACHE: _SPACE_CACHE[key] = ModularForms(Gamma0(level), 2) return _SPACE_CACHE[key] def get_newforms(level): if level not in _NEWFORM_CACHE: S = get_cusp_space(level) _NEWFORM_CACHE[level] = S.newforms('a') return _NEWFORM_CACHE[level] def get_elliptic_curves_of_conductor(N): if N in _ELL_CURVE_CACHE: return _ELL_CURVE_CACHE[N] curves = [] seen = set() # Prefer Cremona database if available try: from sage.databases.cremona import CremonaDatabase db = CremonaDatabase() labels = db.allcurves(N) for label in labels: try: E = EllipticCurve(label) lab = str(E.cremona_label()) if lab not in seen and E.conductor() == N: seen.add(lab) curves.append(E) except Exception: pass except Exception: pass # Fallback: isogeny class representative guesses if not curves: suffixes = ["a1", "a2", "a3", "b1", "b2", "c1"] for s in suffixes: try: E = EllipticCurve(f"{N}{s}") lab = str(E.cremona_label()) if lab not in seen and E.conductor() == N: seen.add(lab) curves.append(E) except Exception: pass _ELL_CURVE_CACHE[N] = curves return curves def primes_upto_n_first(n): return list(primes_first_n(n)) # --------------------------------------------------------------------------- # MATHEMATICAL HELPERS # --------------------------------------------------------------------------- def field_discriminant_for_d(d): return int(get_quadratic_field(d).discriminant()) def exact_linear_root_of_poly(P): # For linear polynomial ax+b, root is -b/a if P.degree() != 1: return None a = P[1] b = P[0] try: r = -b / a if r in ZZ: return int(r) return str(r) except Exception: return str(-b / a) def ring_basis_strings(OK): try: return [str(b) for b in OK.basis()] except Exception: return [str(OK.basis())] def splitting_type_for_prime(K, p): try: fac = K.ideal(p).factor() ramified = any(e > 1 for _, e in fac) if ramified: return "ramified", str(fac) if len(fac) == 2: return "split", str(fac) return "inert", str(fac) except Exception as e: return "error", str(e) def safe_supersingular(E, p): # Works only for good reduction. try: red = E.reduction(p) return bool(red.is_supersingular()), "reduction_object" except Exception: pass try: a_p = E.ap(p) if p > 3: return bool(a_p % p == 0), "ap_mod_p" return bool(a_p == 0), "ap_equals_zero_small_prime" except Exception: return None, "error" def hecke_trace_gram_diagnostic(S, n_ops=None): dim = S.dimension() if dim == 0: return {"status": "trivial", "trace_gram_det": 1, "operators_used": []} if n_ops is None: n_ops = min(dim + 3, 12) ops = [] used = [] for n in range(1, n_ops + 1): try: Tn = S.hecke_matrix(n) ops.append(Tn) used.append(n) except Exception: pass if not ops: return {"status": "error", "trace_gram_error": "no_operators"} Gm = matrix(ZZ, len(ops), len(ops), lambda i, j: (ops[i] * ops[j]).trace()) detv = Gm.det() out = { "status": "experimental", "name": "trace_gram_diagnostic", "operators_used": used, "trace_gram_det": safe_int(detv), "trace_gram_det_factorization": str(factor(abs(detv))) if detv != 0 else "0", "rank": int(Gm.rank()), } vals = {} for p in CFG.operator_primes: try: vals[str(p)] = "inf" if detv == 0 else int(valuation(detv, p)) except Exception: vals[str(p)] = "error" out["p_adic_valuations"] = vals return out def orbit_label(level, idx, f): try: deg = f.hecke_eigenvalue_field().degree() except Exception: deg = 1 return f"N{level}_f{idx}_deg{deg}" def coeff_mod_prime_if_rational(a, p): try: if a in ZZ: return int(ZZ(a) % p) except Exception: pass return None def pairwise_newform_congruence_diagnostic(level, f_i, f_j, pair_name): """ Strenge, eerlijke congruentiediagnostiek. Deze routine vermijdt valse claims over priemidealen in composita als dat niet exact beschikbaar is. Outputsoorten: - exact_rational_mod_p: alle vergeleken coeffs waren rationaal en congruent mod p - mixed_operator_mod_p: operator-level signaal, niet exact newform-prime-ideal bewijs - no_signal """ test_primes = list(primes_first_n(CFG.congruence_test_primes)) records = [] # 1) Exacte rationele mod-p test voor kleine p for p in [2, 3, 5, 7]: all_defined = True matched = 0 rational_checks = 0 mismatches = [] for q in test_primes: try: ai = f_i.coefficient(q) aj = f_j.coefficient(q) except Exception: all_defined = False mismatches.append({"prime": int(q), "reason": "coefficient_error"}) continue ai_mod = coeff_mod_prime_if_rational(ai, p) aj_mod = coeff_mod_prime_if_rational(aj, p) if ai_mod is not None and aj_mod is not None: rational_checks += 1 if ai_mod == aj_mod: matched += 1 else: mismatches.append({"prime": int(q), "ai_mod_p": ai_mod, "aj_mod_p": aj_mod}) else: all_defined = False if rational_checks == len(test_primes) and matched == len(test_primes): records.append({ "pair": pair_name, "prime": p, "status": "exact_rational_mod_p", "matched_primes": matched, "tested_primes": len(test_primes), "details": "all tested eigenvalues rational and congruent mod p", }) elif matched > 0 or rational_checks > 0: records.append({ "pair": pair_name, "prime": p, "status": "partial_rational_visibility", "matched_primes": matched, "tested_primes": len(test_primes), "rational_checks": rational_checks, "all_defined": all_defined, "mismatch_count": len(mismatches), }) # 2) Operator-level fallback: compare charpolys mod p of T_q on space # Honest label: not a proof of orbit-pair congruence, but a signal. try: S = get_cusp_space(level) for p in [2, 3, 5, 7]: signature_hits = 0 tested = 0 for q in test_primes[:min(15, len(test_primes))]: if q == level: continue try: Tq = S.hecke_matrix(q).change_ring(GF(p)) cp = str(Tq.charpoly()) if cp: signature_hits += 1 tested += 1 except Exception: pass if tested: records.append({ "pair": pair_name, "prime": p, "status": "mixed_operator_mod_p", "tested_operators": tested, "signature_hits": signature_hits, "details": "space-level mod-p operator diagnostic only; not a prime-ideal proof", }) except Exception: pass if not records: records.append({ "pair": pair_name, "status": "no_signal" }) return records # --------------------------------------------------------------------------- # AXIS 1 — NUMBER FIELDS # --------------------------------------------------------------------------- def axis_1_number_fields(): slug = "number_fields" if not should_run(1, slug): print(f"[skip] axis 1 ({slug})") return with timer("AS 1: Getalveld-data Q(sqrt(-d))"): rows = [] splitting_rows = [] for d in HEEGNER: row = {"d": d, "status": "canonical", "errors": []} try: K = get_quadratic_field(d) OK = K.ring_of_integers() D = int(K.discriminant()) h = int(K.class_number()) row["field_label"] = f"Q(sqrt(-{d}))" row["degree"] = int(K.degree()) row["discriminant"] = D row["class_number"] = h row["class_number_verified"] = (h == 1) row["ring_basis"] = ring_basis_strings(OK) # Hilbert class polynomial and singular modulus try: H = hilbert_class_polynomial(D) row["hilbert_class_polynomial"] = str(H) row["hilbert_class_polynomial_degree"] = int(H.degree()) row["hilbert_class_polynomial_linear"] = bool(H.degree() == 1) j = exact_linear_root_of_poly(H) row["j_invariant"] = j if isinstance(j, int) and j != 0: row["j_factorization"] = str(factor(abs(j))) row["j_sign"] = int(sign(j)) except Exception as e: row["errors"].append({"stage": "hilbert_class_polynomial", **error_payload(e)}) # Imaginary quadratic units try: if d == 1: row["unit_group_note"] = "roots_of_unity_order_4" elif d == 3: row["unit_group_note"] = "roots_of_unity_order_6" else: row["unit_group_note"] = "roots_of_unity_order_2" except Exception: pass # Ramanujan constant ram = RR(exp(pi * sqrt(RR(d)))) row["ramanujan_constant"] = float(ram) row["ramanujan_nearest_int"] = int(round(ram)) row["ramanujan_distance"] = float(abs(ram - round(ram))) # Kronecker symbol using field discriminant D_K kron = {} for p in CFG.small_primes: try: kron[str(p)] = int(kronecker_symbol(D, p)) except Exception: kron[str(p)] = "error" row["kronecker_DK"] = kron # Prime splitting table for p in CFG.test_primes: stype, fac = splitting_type_for_prime(K, p) splitting_rows.append([d, int(p), D, stype, fac]) except Exception as e: row["errors"].append(error_payload(e)) rows.append(row) write_json(1, slug, rows, meta_extra={"kind": "canonical"}) write_csv(1, "splitting", ["d", "p", "field_discriminant", "type", "factorization"], splitting_rows) # --------------------------------------------------------------------------- # AXIS 2 — MODULAR CURVES # --------------------------------------------------------------------------- def axis_2_modular_curves(): slug = "modular_curves" if not should_run(2, slug): print(f"[skip] axis 2 ({slug})") return with timer("AS 2: Modulaire krommen X_0(N), N Heegner-priem"): rows = [] for N in HEEGNER_PRIMES: row = {"level": N, "status": "canonical", "errors": []} try: G = Gamma0(N) S = get_cusp_space(N) M = get_mod_space(N) row["genus"] = int(G.genus()) row["ncusps"] = int(G.ncusps()) row["nu2"] = int(G.nu2()) row["nu3"] = int(G.nu3()) row["index"] = int(G.index()) row["dim_S2"] = int(S.dimension()) row["dim_M2"] = int(M.dimension()) row["dim_Eis"] = int(M.dimension() - S.dimension()) t0 = time.time() NF = get_newforms(N) row["n_newforms"] = len(NF) dims = [] labels = [] for i, f in enumerate(NF): try: deg = int(f.hecke_eigenvalue_field().degree()) except Exception: deg = 1 dims.append(deg) labels.append(orbit_label(N, i, f)) row["orbit_dimensions"] = dims row["orbit_labels"] = labels row["orbit_sum"] = sum(dims) row["orbit_sum_matches_dim_S2"] = (sum(dims) == int(S.dimension())) row["newform_runtime_s"] = round(time.time() - t0, 3) except Exception as e: row["errors"].append(error_payload(e)) rows.append(row) write_json(2, slug, rows, meta_extra={"kind": "canonical"}) # --------------------------------------------------------------------------- # AXIS 3 — HECKE OPERATOR DIAGNOSTICS + CONGRUENCE DIAGNOSTICS # --------------------------------------------------------------------------- def axis_3_hecke_diagnostics(): slug = "hecke_diagnostics" if not should_run(3, slug): print(f"[skip] axis 3 ({slug})") return with timer("AS 3: Hecke-operator diagnostiek en congruenties"): rows = [] pair_rows = [] for N in HEEGNER_PRIMES: row = {"level": N, "status": "mixed", "errors": []} try: S = get_cusp_space(N) dim = int(S.dimension()) row["dim_S2"] = dim row["trace_gram_diagnostic"] = hecke_trace_gram_diagnostic(S) # Operator diagnostics at small primes ops = {} for ell in CFG.operator_primes[:min(len(CFG.operator_primes), 12 if CFG.profile == "light" else 20)]: if ell == N: continue try: T = S.hecke_matrix(ell) o = { "trace": safe_int(T.trace()), "det": str(T.det()), "rank": int(T.rank()), "charpoly": str(T.charpoly()), } for p in [2, 3, 5, 7]: try: Tmod = T.change_ring(GF(p)) mp = Tmod.minpoly() o[f"charpoly_mod_{p}"] = str(Tmod.charpoly()) o[f"minpoly_mod_{p}"] = str(mp) o[f"operator_semisimple_mod_{p}"] = bool(mp == mp.radical()) o[f"kernel_dim_T_mod_{p}"] = int(Tmod.right_kernel().dimension()) except Exception as e: o[f"mod_{p}_error"] = str(e) ops[str(ell)] = o except Exception as e: ops[str(ell)] = {"error": str(e)} row["operators"] = ops # Newform-pair diagnostics NF = get_newforms(N) for i, j in combinations(range(len(NF)), 2): name = f"({i},{j})" try: diagnostics = pairwise_newform_congruence_diagnostic(N, NF[i], NF[j], name) pair_rows.append({ "level": N, "pair": name, "orbit_i": orbit_label(N, i, NF[i]), "orbit_j": orbit_label(N, j, NF[j]), "diagnostics": diagnostics, }) except Exception as e: pair_rows.append({ "level": N, "pair": name, "error": error_payload(e), }) except Exception as e: row["errors"].append(error_payload(e)) rows.append(row) write_json(3, slug, rows, meta_extra={"kind": "mixed", "note": "replaces old axis 3"}) write_json(3, "newform_pair_congruences", pair_rows, meta_extra={"kind": "experimental_strict"}) # --------------------------------------------------------------------------- # AXIS 3 (rigorous supplement) — TRUE mod-P NEWFORM CONGRUENCES # --------------------------------------------------------------------------- # For each level N and pair of newform orbits (i,j), we form the compositum # field L containing both coefficient fields, factor r in O_L, and for each # prime ideal P above r we test whether a_p(f_i) ≡ a_p(f_j) mod P for all # test primes p != N. This is a proof of congruence, not a diagnostic. # --------------------------------------------------------------------------- def axis_3_rigorous_congruences(): slug = "rigorous_newform_congruences" if not should_run(3, slug): print(f"[skip] axis 3 rigorous ({slug})") return with timer("AS 3 rigorous: echte mod-P newform-congruenties"): rows = [] test_primes_all = [int(p) for p in CFG.test_primes] for N in HEEGNER_PRIMES: try: NF = get_newforms(N) except Exception as e: rows.append({"level": N, "errors": [{"stage": "newforms", **error_payload(e)}]}) continue if NF is None or len(NF) < 2: rows.append({"level": N, "n_orbits": (len(NF) if NF is not None else 0), "note": "fewer than 2 newform orbits"}) continue test_primes = [p for p in test_primes_all if p != N][:CFG.congruence_test_primes] for i, j in combinations(range(len(NF)), 2): f_i, f_j = NF[i], NF[j] try: K_i = f_i.hecke_eigenvalue_field() K_j = f_j.hecke_eigenvalue_field() d_i, d_j = int(K_i.degree()), int(K_j.degree()) except Exception as e: rows.append({"level": N, "pair_i": i, "pair_j": j, "errors": [{"stage": "coeff_field", **error_payload(e)}]}) continue # Determine ambient field L and the two embeddings. emb_i = emb_j = L = None try: if d_i == 1 and d_j == 1: L = QQ emb_i = lambda x: QQ(x) emb_j = lambda x: QQ(x) elif d_i == 1: L = K_j emb_i = lambda x: L(QQ(x)) emb_j = lambda x: L(x) elif d_j == 1: L = K_i emb_i = lambda x: L(x) emb_j = lambda x: L(QQ(x)) else: comp = K_i.composite_fields(K_j, both_maps=True) L_tuple = comp[0] L = L_tuple[0] ei_map, ej_map = L_tuple[1], L_tuple[2] emb_i = lambda x, m=ei_map: m(x) emb_j = lambda x, m=ej_map: m(x) except Exception as e: rows.append({"level": N, "pair_i": i, "pair_j": j, "errors": [{"stage": "compositum", **error_payload(e)}]}) continue L_deg = int(L.degree()) if L != QQ else 1 for r in [2, 3, 5, 7]: if L == QQ: mismatches = [] tested = 0 for p in test_primes: try: a_i = ZZ(f_i[p]); a_j = ZZ(f_j[p]) tested += 1 if (a_i - a_j) % r != 0: mismatches.append(int(p)) except Exception: pass rows.append({ "level": N, "pair_i": i, "pair_j": j, "orbit_i_dim": d_i, "orbit_j_dim": d_j, "L_degree": 1, "r": r, "P_kind": "QQ_mod_r", "P_norm": r, "P_residue_degree": 1, "P_ramification": 1, "tested_primes": tested, "mismatches": len(mismatches), "mismatch_primes_sample": mismatches[:10], "congruent": (tested > 0 and len(mismatches) == 0), }) continue try: r_factors = list(L.ideal(r).factor()) except Exception as e: rows.append({"level": N, "pair_i": i, "pair_j": j, "L_degree": L_deg, "r": r, "errors": [{"stage": "factor_r", **error_payload(e)}]}) continue for P, e_P in r_factors: try: f_P = int(P.residue_class_degree()) P_norm = int(P.absolute_norm()) except Exception: f_P = None; P_norm = None mismatches = [] tested = 0 for p in test_primes: try: a_i_L = emb_i(f_i[p]) a_j_L = emb_j(f_j[p]) tested += 1 if (a_i_L - a_j_L) not in P: mismatches.append(int(p)) except Exception: pass rows.append({ "level": N, "pair_i": i, "pair_j": j, "orbit_i_dim": d_i, "orbit_j_dim": d_j, "L_degree": L_deg, "r": r, "P_norm": P_norm, "P_residue_degree": f_P, "P_ramification": int(e_P), "tested_primes": tested, "mismatches": len(mismatches), "mismatch_primes_sample": mismatches[:10], "congruent": (tested > 0 and len(mismatches) == 0), }) strong = [r for r in rows if r.get("congruent") is True] print(f" -> {len(strong)} rigorous congruences found across all Heegner levels") write_json(3, slug, rows, meta_extra={ "kind": "rigorous_supplementary", "method": "compositum field L, prime ideal P above r in O_L, a_p(f_i) - a_p(f_j) in P for all tested p", "strong_congruences": len(strong), }) # --------------------------------------------------------------------------- # AXIS 4 — ELLIPTIC CURVES # --------------------------------------------------------------------------- def axis_4_elliptic_curves(): slug = "elliptic_curves" if not should_run(4, slug): print(f"[skip] axis 4 ({slug})") return with timer("AS 4: Elliptische krommen"): rows = [] ap_rows = [] for N in HEEGNER_PRIMES: curves = get_elliptic_curves_of_conductor(N) if not curves: rows.append({"conductor": N, "status": "canonical", "n_curves": 0, "errors": ["no_curves_found"]}) continue for E in curves: row = {"conductor": N, "status": "canonical", "errors": []} try: row["label"] = str(E.cremona_label()) except Exception: row["label"] = "unknown" try: row["rank"] = int(E.rank()) except Exception as e: row["errors"].append({"stage": "rank", **error_payload(e)}) try: row["torsion_order"] = int(E.torsion_order()) row["torsion_structure"] = str(E.torsion_subgroup().invariants()) except Exception as e: row["errors"].append({"stage": "torsion", **error_payload(e)}) try: row["root_number"] = safe_int(E.root_number()) except Exception: pass try: md = E.modular_degree() row["modular_degree"] = int(md) row["modular_degree_factorization"] = str(factor(md)) row["modular_degree_valuations"] = {str(p): int(valuation(md, p)) for p in [2, 3, 5, 7]} except Exception as e: row["errors"].append({"stage": "modular_degree", **error_payload(e)}) try: tam = E.tamagawa_numbers() row["tamagawa_numbers"] = [int(t) for t in tam] row["tamagawa_product"] = int(E.tamagawa_product()) except Exception as e: row["errors"].append({"stage": "tamagawa", **error_payload(e)}) # Reduction data and supersingular primes red = {} supersingular_primes = [] for p in CFG.operator_primes: if p == N: red[str(p)] = {"status": "bad_reduction"} continue try: a_p = int(E.ap(p)) ss, method = safe_supersingular(E, p) rec = { "a_p": a_p, "supersingular": ss, "method": method, } if p > 3: rec["criterion_ap_mod_p_zero"] = bool(a_p % p == 0) rec["ordinary"] = bool(a_p % p != 0) else: rec["ordinary"] = None red[str(p)] = rec if ss: supersingular_primes.append(int(p)) except Exception as e: red[str(p)] = {"error": str(e)} row["reduction_data"] = red row["supersingular_primes_upto_bound"] = supersingular_primes # Local data at each bad prime (Kodaira, conductor exponent, # discriminant valuation, local root number, reduction type). local = [] try: bad_primes = [p for p in E.conductor().prime_factors()] for p in bad_primes: entry = {"prime": int(p)} try: ld = E.local_data(p) try: entry["kodaira_symbol"] = str(ld.kodaira_symbol()) except Exception: pass try: entry["conductor_valuation"] = int(ld.conductor_valuation()) except Exception: pass try: entry["discriminant_valuation"] = int(ld.discriminant_valuation()) except Exception: pass try: entry["minimal_model_disc_valuation"] = int(E.discriminant().valuation(p)) except Exception: pass try: entry["bad_reduction_type"] = str(ld.bad_reduction_type()) except Exception: pass except Exception as e: entry["local_data_error"] = str(e) try: entry["local_root_number"] = int(E.root_number(p)) except Exception: pass # Reduction type classification (additive / multiplicative # split or non-split, at each bad prime). try: if E.has_multiplicative_reduction(p): entry["reduction_class"] = ( "multiplicative_split" if E.has_split_multiplicative_reduction(p) else "multiplicative_nonsplit" ) elif E.has_additive_reduction(p): entry["reduction_class"] = "additive" else: entry["reduction_class"] = "good" except Exception as e: entry["reduction_class_error"] = str(e) local.append(entry) except Exception as e: row["errors"].append({"stage": "local_data", **error_payload(e)}) row["local_data"] = local for p in CFG.test_primes: try: ap_rows.append([N, row["label"], int(p), int(E.ap(p))]) except Exception: pass try: L = E.lseries() row["L_value_1"] = float(L(1)) except Exception as e: row["errors"].append({"stage": "L(1)", **error_payload(e)}) try: row["analytic_rank"] = int(E.analytic_rank()) except Exception as e: row["errors"].append({"stage": "analytic_rank", **error_payload(e)}) try: rho = E.galois_representation() for p in [2, 3, 5, 7]: try: row[f"galois_image_mod_{p}"] = str(rho.image_type(p)) except Exception: row[f"galois_image_mod_{p}"] = "error" except Exception: pass rows.append(row) write_json(4, slug, rows, meta_extra={"kind": "canonical"}) write_csv(4, "ap_table", ["conductor", "label", "p", "a_p"], ap_rows) # --------------------------------------------------------------------------- # AXIS 5 — MULTIPLICATIVE GROUPS # --------------------------------------------------------------------------- def axis_5_multiplicative_groups(): slug = "multiplicative_groups" if not should_run(5, slug): print(f"[skip] axis 5 ({slug})") return with timer("AS 5: Multiplicatieve groepen (Z/NZ)^*"): rows = [] for N in HEEGNER_PRIMES: row = {"modulus": N, "status": "experimental", "errors": []} try: phiN = euler_phi(N) row["phi"] = int(phiN) row["phi_factorization"] = str(factor(phiN)) try: g = int(primitive_root(N)) row["smallest_primitive_root"] = g except Exception: g = None row["smallest_primitive_root"] = None if g is not None: row["primitive_roots_below_100"] = [ a for a in range(2, min(N, 100)) if gcd(a, N) == 1 and Mod(a, N).multiplicative_order() == phiN ][:20] row["n_primitive_roots"] = int(euler_phi(phiN)) dlogs = {} orders = {} qres = {} for h in HEEGNER: if h % N == 0: dlogs[str(h)] = "zero" orders[str(h)] = 0 qres[str(h)] = "zero" continue x = Mod(h % N, N) try: dlogs[str(h)] = int(discrete_log(x, Mod(g, N))) except Exception: dlogs[str(h)] = "error" try: orders[str(h)] = int(x.multiplicative_order()) except Exception: orders[str(h)] = "error" try: qres[str(h)] = bool(is_square(x)) except Exception: qres[str(h)] = "error" row["discrete_logs_base_g"] = dlogs row["orders"] = orders row["quadratic_residues"] = qres except Exception as e: row["errors"].append(error_payload(e)) rows.append(row) write_json(5, slug, rows, meta_extra={"kind": "experimental"}) # --------------------------------------------------------------------------- # AXIS 6 — EULER POLYNOMIALS # --------------------------------------------------------------------------- def axis_6_euler_polynomials(): slug = "euler_polynomials" if not should_run(6, slug): print(f"[skip] axis 6 ({slug})") return with timer("AS 6: Euler-polynomen"): rows = [] for d in HEEGNER: row = {"d": d, "status": "canonical", "errors": []} try: if d % 4 == 3: k = (d + 1) // 4 row["euler_coefficient"] = int(k) row["polynomial"] = f"n^2 + n + {k}" row["symmetry_note"] = "f(-n-1)=f(n)" prime_run = 0 first_comp = None values = [] for n in range(0, d): val = n**2 + n + k if is_prime(val): if first_comp is None: prime_run += 1 values.append(int(val)) else: if first_comp is None: first_comp = n row["first_composite_n"] = int(n) row["first_composite_value"] = int(val) row["first_composite_factorization"] = str(factor(val)) row["prime_run_length"] = int(prime_run) row["prime_values_first_20"] = values[:20] row["total_primes_for_0_le_n_lt_d"] = len(values) row["prime_density"] = float(len(values) / d) else: row["note"] = "not applicable since d mod 4 != 3" except Exception as e: row["errors"].append(error_payload(e)) rows.append(row) write_json(6, slug, rows, meta_extra={"kind": "canonical"}) # --------------------------------------------------------------------------- # AXIS 7 — HECKE EIGENVALUES / Q-EXPANSIONS # --------------------------------------------------------------------------- def axis_7_hecke_eigenvalues(): slug = "hecke_eigenvalues" if not should_run(7, slug): print(f"[skip] axis 7 ({slug})") return with timer("AS 7: Hecke-eigenwaarden en q-expansies"): rows = [] table_rows = [] prime_list = list(primes_first_n(min(100, CFG.congruence_test_primes if CFG.profile == "light" else 100))) for N in HEEGNER_PRIMES: try: NF = get_newforms(N) except Exception as e: rows.append({"level": N, "error": error_payload(e)}) continue for i, f in enumerate(NF): row = {"level": N, "form_index": i, "status": "canonical", "errors": []} try: row["orbit_label"] = orbit_label(N, i, f) try: Kf = f.hecke_eigenvalue_field() row["coeff_field_degree"] = int(Kf.degree()) row["coeff_field"] = str(Kf) if Kf.degree() <= 5 else f"degree_{Kf.degree()}" except Exception: row["coeff_field_degree"] = 1 row["coeff_field"] = "QQ_or_unknown" try: row["atkin_lehner"] = serialize(f.atkin_lehner_eigenvalue()) except Exception: row["atkin_lehner"] = "error" coeffs = {} for q in prime_list: try: a_q = f.coefficient(q) coeffs[str(q)] = str(a_q) row_rec = [N, i, int(q), str(a_q)] for p in [2, 3, 5, 7]: aqmod = coeff_mod_prime_if_rational(a_q, p) row_rec.append("" if aqmod is None else aqmod) table_rows.append(row_rec) except Exception: coeffs[str(q)] = "error" row["hecke_coefficients_at_first_primes"] = coeffs heegner_coeffs = {} for h in HEEGNER_PRIMES: try: heegner_coeffs[str(h)] = str(f.coefficient(h)) except Exception: heegner_coeffs[str(h)] = "error" row["heegner_prime_coefficients"] = heegner_coeffs except Exception as e: row["errors"].append(error_payload(e)) rows.append(row) write_json(7, slug, rows, meta_extra={"kind": "canonical"}) write_csv(7, "eigenvalue_table", ["level", "form_index", "prime", "a_q", "a_q_mod_2", "a_q_mod_3", "a_q_mod_5", "a_q_mod_7"], table_rows) # --------------------------------------------------------------------------- # AXIS 8 — HEGNER-PRIME HECKE SIGNATURES # --------------------------------------------------------------------------- def axis_8_heegner_prime_signatures(): slug = "heegner_prime_signatures" if not should_run(8, slug): print(f"[skip] axis 8 ({slug})") return with timer("AS 8: Heegner-prime Hecke-signaturen"): rows = [] collision_rows = [] for N in HEEGNER_PRIMES: row = {"level": N, "status": "mixed", "errors": []} try: S = get_cusp_space(N) if S.dimension() == 0: row["dim"] = 0 rows.append(row) continue row["dim"] = int(S.dimension()) sigs = {} mats = {} for h in HEEGNER_PRIMES: try: T = S.hecke_matrix(h) mats[h] = T entry = { "trace": safe_int(T.trace()), "det": str(T.det()), "rank": int(T.rank()), "charpoly": str(T.charpoly()), } try: entry["eigenvalues"] = [str(x) for x in T.eigenvalues()] except Exception: entry["eigenvalues"] = "error" for p in [2, 3, 5, 7]: try: Tm = T.change_ring(GF(p)) entry[f"charpoly_mod_{p}"] = str(Tm.charpoly()) entry[f"rank_mod_{p}"] = int(Tm.rank()) entry[f"nilpotent_mod_{p}"] = bool(Tm.is_nilpotent()) except Exception: entry[f"mod_{p}_error"] = True sigs[str(h)] = entry except Exception as e: sigs[str(h)] = {"error": str(e)} row["hecke_operators"] = sigs for h1, h2 in combinations(HEEGNER_PRIMES, 2): if h1 not in mats or h2 not in mats: continue diff = mats[h1] - mats[h2] for p in [2, 3, 5, 7]: try: dm = diff.change_ring(GF(p)) if dm.is_zero(): depth2 = all(diff[i, j] % (p**2) == 0 for i in range(diff.nrows()) for j in range(diff.ncols())) collision_rows.append([N, h1, h2, p, 2 if depth2 else 1]) except Exception: pass except Exception as e: row["errors"].append(error_payload(e)) rows.append(row) write_json(8, slug, rows, meta_extra={"kind": "mixed", "note": "space-level signatures, not orbit-prime-ideal proofs"}) write_csv(8, "operator_collisions", ["level", "T_h1", "T_h2", "mod_p", "depth"], collision_rows) # --------------------------------------------------------------------------- # AXIS 9 — ISOGENY CLASS SUMMARIES # --------------------------------------------------------------------------- def axis_9_isogeny_classes(): slug = "isogeny_class_summaries" if not should_run(9, slug): print(f"[skip] axis 9 ({slug})") return with timer("AS 9: Isogenieklasse-samenvattingen"): rows = [] for N in HEEGNER_PRIMES: curves = get_elliptic_curves_of_conductor(N) if not curves: rows.append({"conductor": N, "status": "canonical", "n_curves": 0}) continue for E in curves: row = {"conductor": N, "status": "canonical", "errors": []} try: row["label"] = str(E.cremona_label()) except Exception: row["label"] = "unknown" try: isog_data = {} for ell in [2, 3, 5, 7, 11, 13]: try: phis = E.isogenies_prime_degree(ell) labels = [] for phi in phis: try: labels.append(str(phi.codomain().cremona_label())) except Exception: labels.append("unknown") isog_data[str(ell)] = {"count": len(phis), "codomains": labels} except Exception: isog_data[str(ell)] = {"count": 0} row["prime_degree_isogenies"] = isog_data except Exception as e: row["errors"].append({"stage": "isogenies", **error_payload(e)}) try: C = E.isogeny_class() cs = C.curves if callable(cs): cs = cs() row["isogeny_class_size"] = int(len(cs)) try: mat = [[int(x) for x in rr] for rr in C.matrix()] except Exception: mat = None row["isogeny_matrix"] = mat # Class labels for each curve in the class. try: row["class_labels"] = [str(c.cremona_label()) for c in cs] except Exception: row["class_labels"] = [] # Isogeny graph statistics (on the prime-degree edges in the # isogeny matrix: entries that are 1 or prime). if mat is not None: try: n = len(mat) from sage.all import Matrix, Graph deg = [] for i in range(n): cnt = 0 for j in range(n): v = mat[i][j] if i != j and v > 1 and is_prime(v): cnt += 1 deg.append(cnt) row["isogeny_graph_degrees"] = deg # Diameter = max over all pairs (i,j) of the smallest # number of prime-degree isogenies needed to connect # curve i to curve j. try: edges = [] for i in range(n): for j in range(i + 1, n): if mat[i][j] > 1 and is_prime(mat[i][j]): edges.append((i, j)) G = Graph(edges) G.add_vertices(range(n)) row["isogeny_graph_diameter"] = int(G.diameter()) if G.is_connected() else None row["isogeny_graph_is_connected"] = bool(G.is_connected()) except Exception as e: row["errors"].append({"stage": "graph_diameter", **error_payload(e)}) except Exception as e: row["errors"].append({"stage": "graph_degrees", **error_payload(e)}) # Optimal curve: for Cremona labels, 'a1' is the optimal curve. try: lbl = str(E.cremona_label()) row["is_optimal_curve"] = lbl.endswith("1") and not lbl[-2:].isdigit() except Exception: pass # Manin constant for the optimal curve. try: c_manin = E.manin_constant() row["manin_constant"] = int(c_manin) except Exception: pass except Exception as e: row["errors"].append({"stage": "isogeny_class", **error_payload(e)}) try: row["has_cm"] = bool(E.has_cm()) if row["has_cm"]: row["cm_discriminant"] = int(E.cm_discriminant()) except Exception as e: row["errors"].append({"stage": "cm", **error_payload(e)}) rows.append(row) write_json(9, slug, rows, meta_extra={"kind": "canonical"}) # --------------------------------------------------------------------------- # AXIS 10 — MODULAR SYMBOLS & PERIODS # --------------------------------------------------------------------------- def axis_10_modular_symbols(): slug = "modular_symbols" if not should_run(10, slug): print(f"[skip] axis 10 ({slug})") return with timer("AS 10: Modulaire symbolen en perioden"): rows = [] for N in HEEGNER_PRIMES: row = {"level": N, "status": "canonical", "errors": []} try: M = ModularSymbols(Gamma0(N), 2) row["dimension"] = int(M.dimension()) row["cuspidal_dimension"] = int(M.cuspidal_submodule().dimension()) try: D = M.cuspidal_submodule().decomposition() row["n_simple_factors"] = len(D) row["factor_dimensions"] = [int(f.dimension()) for f in D] except Exception as e: row["errors"].append({"stage": "decomposition", **error_payload(e)}) # Plus / minus sign decomposition: S_plus, S_minus ⊂ S_cusp. try: Sp = M.cuspidal_submodule().sign_submodule(+1) Sm = M.cuspidal_submodule().sign_submodule(-1) row["cuspidal_plus_dimension"] = int(Sp.dimension()) row["cuspidal_minus_dimension"] = int(Sm.dimension()) # Per-factor sign decomposition (rational parts). try: row["factor_plus_dimensions"] = [int(f.sign_submodule(+1).dimension()) for f in M.cuspidal_submodule().decomposition()] row["factor_minus_dimensions"] = [int(f.sign_submodule(-1).dimension()) for f in M.cuspidal_submodule().decomposition()] except Exception as e: row["errors"].append({"stage": "sign_per_factor", **error_payload(e)}) except Exception as e: row["errors"].append({"stage": "sign_decomposition", **error_payload(e)}) # winding_quotient() is not exposed on ModularSymbols in Sage 10.8. # Try known API paths; otherwise mark explicitly unavailable. W = None for accessor in ("winding_submodule", "winding_element"): try: fn = getattr(M, accessor, None) if fn is not None: W = fn() break except Exception: W = None if W is not None: try: row["winding_dimension"] = int(W.dimension()) if hasattr(W, "dimension") else None row["winding_accessor"] = accessor except Exception as e: row["errors"].append({"stage": "winding_submodule", **error_payload(e)}) else: row["winding_dimension"] = None row["winding_status"] = "not_available_in_this_sage_api" try: curves = get_elliptic_curves_of_conductor(N) if curves: E = curves[0] om = E.period_lattice() b = om.basis() row["real_period"] = float(b[0]) row["complex_period"] = [float(b[1].real()), float(b[1].imag())] row["complex_area"] = float(om.complex_area()) except Exception as e: row["errors"].append({"stage": "period_lattice", **error_payload(e)}) except Exception as e: row["errors"].append(error_payload(e)) rows.append(row) write_json(10, slug, rows, meta_extra={"kind": "canonical"}) # --------------------------------------------------------------------------- # AXIS 11 — L-VALUES & BSD NUMERICS # --------------------------------------------------------------------------- def axis_11_l_values(): slug = "l_values" if not should_run(11, slug): print(f"[skip] axis 11 ({slug})") return with timer("AS 11: L-waarden en BSD-numeriek"): rows = [] for N in HEEGNER_PRIMES: curves = get_elliptic_curves_of_conductor(N) if not curves: rows.append({"level": N, "status": "canonical", "n_curves": 0}) continue for E in curves: row = {"level": N, "status": "canonical", "errors": []} try: row["label"] = str(E.cremona_label()) except Exception: row["label"] = "unknown" try: L = E.lseries() for s in [1, 2, 3]: try: row[f"L_at_{s}"] = float(L(s)) except Exception: row[f"L_at_{s}"] = "error" try: row["L_prime_at_1"] = float(L.deriv_at1()) except Exception: row["L_prime_at_1"] = "error" except Exception as e: row["errors"].append({"stage": "lseries", **error_payload(e)}) try: row["analytic_rank"] = int(E.analytic_rank()) except Exception: pass try: row["regulator"] = float(E.regulator()) except Exception: row["regulator"] = "error" try: row["sha_analytic_numerical"] = float(E.sha().an_numerical()) row["sha_status"] = "bsd_numerical" except Exception: row["sha_analytic_numerical"] = "error" rows.append(row) write_json(11, slug, rows, meta_extra={"kind": "canonical_numeric"}) # --------------------------------------------------------------------------- # AXIS 12 — GALOIS & SELMER # --------------------------------------------------------------------------- def axis_12_galois(): slug = "galois_and_selmer" if not should_run(12, slug): print(f"[skip] axis 12 ({slug})") return with timer("AS 12: Galois-representaties en Selmer"): rows = [] for N in HEEGNER_PRIMES: curves = get_elliptic_curves_of_conductor(N) if not curves: rows.append({"conductor": N, "status": "canonical", "n_curves": 0}) continue for E in curves: row = {"conductor": N, "status": "canonical", "errors": []} try: row["label"] = str(E.cremona_label()) except Exception: row["label"] = "unknown" try: rho = E.galois_representation() for p in [2, 3, 5, 7, 11, 13]: try: row[f"image_mod_{p}"] = str(rho.image_type(p)) except Exception: row[f"image_mod_{p}"] = "error" except Exception as e: row["errors"].append({"stage": "galois_representation", **error_payload(e)}) for p in [2, 3, 5]: try: row[f"selmer_rank_mod_{p}"] = int(E.selmer_rank(p)) except Exception: row[f"selmer_rank_mod_{p}"] = "error" heegner_hyp = {} for d in HEEGNER: if d == 1: continue try: disc = -d if d % 4 == 3 else -4*d heegner_hyp[str(d)] = { "discriminant": int(disc), "kronecker_with_conductor": int(kronecker_symbol(disc, N)), "passes_naive_heegner_hypothesis": bool(kronecker_symbol(disc, N) == 1), } except Exception: heegner_hyp[str(d)] = "error" row["heegner_discriminants"] = heegner_hyp rows.append(row) write_json(12, slug, rows, meta_extra={"kind": "canonical"}) # --------------------------------------------------------------------------- # INDEX / VALIDATION # --------------------------------------------------------------------------- def validate_summary(): checks = [] # axis 1 checks try: with open(axis_filename(1, "number_fields"), "r", encoding="utf-8") as f: payload = json.load(f) rows = payload["rows"] checks.append({ "check": "class_number_all_1", "passed": all(r.get("class_number") == 1 for r in rows if "class_number" in r), }) checks.append({ "check": "hilbert_class_polynomials_linear", "passed": all(r.get("hilbert_class_polynomial_degree") == 1 for r in rows if "hilbert_class_polynomial_degree" in r), }) except Exception as e: checks.append({"check": "axis1_validation", "passed": False, "error": str(e)}) # axis 2 checks try: with open(axis_filename(2, "modular_curves"), "r", encoding="utf-8") as f: payload = json.load(f) rows = payload["rows"] checks.append({ "check": "orbit_sum_matches_dim", "passed": all(r.get("orbit_sum_matches_dim_S2", True) for r in rows), }) except Exception as e: checks.append({"check": "axis2_validation", "passed": False, "error": str(e)}) return checks # --------------------------------------------------------------------------- # DERIVED AXIS 13 — POST-AXIS SYNTHESIS LAYER # --------------------------------------------------------------------------- # Everything in axis 13 is DERIVED: it reads outputs of axes 1-12 and # synthesizes them into publication-ready tables. Each derived file carries # (status, provenance="derived", confidence_note) via AXIS_STATUS. # --------------------------------------------------------------------------- def _load_axis_rows(axis_no, slug): """Load rows of a previously-written axis JSON; return [] on failure.""" try: with open(axis_filename(axis_no, slug), "r", encoding="utf-8") as f: return json.load(f).get("rows", []) except Exception: return [] # ---- Derived: Orbit registry --------------------------------------------- def derived_orbit_registry(): slug = "orbit_registry" if not should_run(13, slug): print(f"[skip] derived 13 ({slug})") return with timer("DERIVED 13: Orbit registry"): cong_rows = _load_axis_rows(3, "rigorous_newform_congruences") # Congruence incidences per (level, orbit_idx) incidences = {} for r in cong_rows: if not r.get("congruent"): continue N = int(r["level"]) i, j = int(r["pair_i"]), int(r["pair_j"]) for idx, partner in [(i, j), (j, i)]: key = (N, idx) incidences.setdefault(key, []).append({ "partner_orbit": partner, "r": int(r["r"]), "P_norm": r.get("P_norm"), "P_residue_degree": r.get("P_residue_degree"), "P_ramification": r.get("P_ramification"), }) rows = [] for N in HEEGNER_PRIMES: try: NF = get_newforms(N) except Exception as e: rows.append({"level": N, "errors": [{"stage": "newforms", **error_payload(e)}]}) continue for idx, f in enumerate(NF): entry = { "level": N, "orbit_index": idx, "orbit_label": orbit_label(N, idx, f), } try: K = f.hecke_eigenvalue_field() entry["coeff_field_degree"] = int(K.degree()) entry["coeff_field_poly"] = str(K.defining_polynomial()) except Exception as e: entry["coeff_field_error"] = str(e) entry["orbit_dimension"] = entry.get("coeff_field_degree") try: entry["atkin_lehner_at_N"] = int(f.atkin_lehner_eigenvalue(N)) except Exception: pass # First a_p values — rational orbits as ints, others as strings ap = {} for p in primes_first_n(15): if p == N: continue try: v = f[p] ap[str(int(p))] = int(v) if entry.get("coeff_field_degree") == 1 else str(v) except Exception: pass entry["first_a_p"] = ap # Linked elliptic curve (rational orbit ↔ optimal Cremona class) if entry.get("coeff_field_degree") == 1: try: curves = get_elliptic_curves_of_conductor(N) match = None for E in curves: try: lbl = str(E.cremona_label()) if lbl.endswith("1") and not lbl[-2:].isdigit(): # Compare a_p at a few primes agree = True for p in [2, 3, 5, 7, 11]: if p == N: continue try: if int(E.ap(p)) != int(f[p]): agree = False; break except Exception: agree = False; break if agree: match = lbl; break except Exception: pass entry["linked_elliptic_curve"] = match except Exception as e: entry["linked_elliptic_error"] = str(e) entry["congruence_incidences"] = incidences.get((N, idx), []) rows.append(entry) write_json(13, slug, rows) # ---- Derived: CM / singular moduli table --------------------------------- def derived_cm_singular_moduli(): slug = "cm_singular_moduli" if not should_run(13, slug): print(f"[skip] derived 13 ({slug})") return with timer("DERIVED 13: CM singular moduli table"): axis1 = _load_axis_rows(1, "number_fields") rows = [] for r in axis1: try: d = int(r.get("d", 0)) except Exception: d = r.get("d") try: dist = float(r.get("ramanujan_distance")) except Exception: dist = None entry = { "d": d, "field_discriminant_D_K": r.get("discriminant"), "class_number": r.get("class_number"), "j_invariant": r.get("j_invariant"), "j_factorization": r.get("j_factorization"), "exp_pi_sqrt_d": r.get("ramanujan_constant"), "exp_pi_sqrt_d_nearest_int": r.get("ramanujan_nearest_int"), "exp_pi_sqrt_d_fractional_distance": r.get("ramanujan_distance"), "hilbert_class_polynomial": r.get("hilbert_class_polynomial"), "ramanujan_near_integer": bool(dist is not None and abs(dist) < 1e-6), } rows.append(entry) write_json(13, slug, rows) # ---- Derived: Master congruence table ------------------------------------ def derived_master_congruence_table(): slug = "master_congruence_table" if not should_run(13, slug): print(f"[skip] derived 13 ({slug})") return with timer("DERIVED 13: Master congruence table"): cong = _load_axis_rows(3, "rigorous_newform_congruences") rows = [] for r in cong: if not r.get("congruent"): continue rows.append({ "level": int(r["level"]), "pair": f"({r['pair_i']},{r['pair_j']})", "pair_i": int(r["pair_i"]), "pair_j": int(r["pair_j"]), "orbit_i_dim": r.get("orbit_i_dim"), "orbit_j_dim": r.get("orbit_j_dim"), "r": int(r["r"]) if str(r["r"]).isdigit() else r["r"], "P_norm": r.get("P_norm"), "P_residue_degree": r.get("P_residue_degree"), "P_ramification": r.get("P_ramification"), "tested_primes": r.get("tested_primes"), "mismatches": r.get("mismatches"), "congruent": True, }) rows.sort(key=lambda x: (x["level"], x["pair_i"], x["pair_j"], x["r"])) write_json(13, slug, rows, meta_extra={"total_congruences": len(rows)}) # CSV mirror write_csv(13, slug, ["level","pair","orbit_i_dim","orbit_j_dim","r","P_norm", "P_residue_degree","P_ramification","tested_primes","mismatches","congruent"], [[r["level"], r["pair"], r["orbit_i_dim"], r["orbit_j_dim"], r["r"], r["P_norm"], r["P_residue_degree"], r["P_ramification"], r["tested_primes"], r["mismatches"], r["congruent"]] for r in rows]) # ---- Derived: Jacobian factorization J_0(N) ------------------------------ def derived_jacobian_factorization(): slug = "jacobian_factorization" if not should_run(13, slug): print(f"[skip] derived 13 ({slug})") return with timer("DERIVED 13: Jacobian J_0(N) factorization"): rows = [] for N in HEEGNER_PRIMES: row = {"level": N, "errors": []} try: NF = get_newforms(N) factors = [] for idx, f in enumerate(NF): try: deg = int(f.hecke_eigenvalue_field().degree()) except Exception: deg = 1 factors.append({ "orbit_index": idx, "orbit_label": orbit_label(N, idx, f), "simple_factor_dimension": deg, "is_elliptic_factor": deg == 1, }) row["n_simple_factors"] = len(factors) row["dim_J0_N"] = sum(f["simple_factor_dimension"] for f in factors) row["factors"] = factors row["factorization_formula"] = " + ".join( [f"A_{f['orbit_index']}(dim={f['simple_factor_dimension']})" for f in factors] ) except Exception as e: row["errors"].append({"stage": "newforms", **error_payload(e)}) rows.append(row) write_json(13, slug, rows) # ---- Derived: Heegner hypothesis matrix ---------------------------------- def derived_heegner_hypothesis_matrix(): slug = "heegner_hypothesis_matrix" if not should_run(13, slug): print(f"[skip] derived 13 ({slug})") return with timer("DERIVED 13: Heegner hypothesis matrix"): # For each Heegner prime level N and each imaginary quadratic # discriminant D in { -d, -4d : d in HEEGNER }, mark validity: # "valid" — D is a fundamental discriminant AND every prime p|N # splits or is unramified in Q(sqrt(D)) AND gcd(D,N)=1 # "ramified" — gcd(D,N) > 1 # "inert" — some prime p|N is inert in Q(sqrt(D)) discs = [] for d in HEEGNER: if d % 4 in (0, 1): discs.append(-d if d % 4 == 3 else -4 * d) else: discs.append(-4 * d) discs = sorted(set(discs)) matrix = [] for N in HEEGNER_PRIMES: row = {"level": N, "entries": {}} for D in discs: try: if D % N == 0: row["entries"][str(D)] = "ramified" continue # Kronecker symbol (D/N); +1 split, -1 inert, 0 ramified k = kronecker_symbol(D, N) if k == 1: row["entries"][str(D)] = "split_valid" elif k == -1: row["entries"][str(D)] = "inert_invalid" else: row["entries"][str(D)] = "ramified" except Exception as e: row["entries"][str(D)] = f"error:{e}" matrix.append(row) write_json(13, slug, matrix, meta_extra={"discriminants_columns": discs}) # ---- Derived: Global summary table --------------------------------------- def derived_global_summary(): slug = "global_summary" if not should_run(13, slug): print(f"[skip] derived 13 ({slug})") return with timer("DERIVED 13: Global summary table"): ax2 = {int(r["level"]): r for r in _load_axis_rows(2, "modular_curves")} ax4 = _load_axis_rows(4, "elliptic_curves") ax11 = {int(r["level"]): r for r in _load_axis_rows(11, "l_values")} cong = _load_axis_rows(3, "rigorous_newform_congruences") # Count strong congruences per level strong_by_level = {} for r in cong: if r.get("congruent"): strong_by_level[int(r["level"])] = strong_by_level.get(int(r["level"]), 0) + 1 rows = [] for N in HEEGNER_PRIMES: m2 = ax2.get(N, {}) m11 = ax11.get(N, {}) curves = [r for r in ax4 if int(r.get("conductor", -1)) == N] optimal = next((c for c in curves if str(c.get("label","")).endswith("1") and not str(c.get("label",""))[-2:].isdigit()), None) rows.append({ "level": N, "genus_X0_N": m2.get("genus"), "dim_S2": m2.get("dim_S2"), "orbit_dimensions": m2.get("orbit_dimensions"), "n_newform_orbits": m2.get("n_newform_orbits"), "has_rational_elliptic_factor": any( d == 1 for d in (m2.get("orbit_dimensions") or []) ), "optimal_curve_label": optimal.get("label") if optimal else None, "optimal_rank": optimal.get("rank") if optimal else None, "analytic_rank": optimal.get("analytic_rank") if optimal else None, "modular_degree": optimal.get("modular_degree") if optimal else None, "supersingular_primes_upto_bound": optimal.get("supersingular_primes_upto_bound") if optimal else None, "strong_congruences": strong_by_level.get(N, 0), "L_value_1": m11.get("L_at_1_numerical"), }) write_json(13, slug, rows) def write_index(start_time): ensure_out() files = sorted(os.listdir(CFG.out_dir)) index = { "meta": { "created_at": now_iso(), "sage_version": sage_version_string(), "config": asdict(CFG), "runtime_minutes": round((time.time() - start_time) / 60.0, 3), }, "heegner_numbers": HEEGNER, "heegner_prime_levels": HEEGNER_PRIMES, "axes": { "1": "number fields", "2": "modular curves", "3": "hecke diagnostics + congruence diagnostics", "4": "elliptic curves", "5": "multiplicative groups", "6": "Euler polynomials", "7": "Hecke eigenvalues / q-expansions", "8": "Heegner-prime Hecke signatures", "9": "isogeny class summaries", "10": "modular symbols and periods", "11": "L-values and BSD numerics", "12": "Galois and Selmer", }, "categories": { "canonical": [ "axis1_number_fields", "axis2_modular_curves", "axis4_elliptic_curves", "axis6_euler_polynomials", "axis7_hecke_eigenvalues", "axis9_isogeny_class_summaries", "axis12_galois_and_selmer", ], "numerical": [ "axis10_modular_symbols", "axis11_l_values", ], "experimental_signatures": [ "axis3_hecke_diagnostics", "axis3_newform_pair_congruences", "axis5_multiplicative_groups", "axis8_heegner_prime_signatures", ], "rigorous_supplementary": [ "axis3_rigorous_newform_congruences", ], "derived": [ "axis13_orbit_registry", "axis13_cm_singular_moduli", "axis13_master_congruence_table", "axis13_jacobian_factorization", "axis13_heegner_hypothesis_matrix", "axis13_global_summary", ], }, "status_provenance_table": { f"axis{a}_{slug}": { "status": v[0], "provenance": v[1], "confidence_note": v[2] } for (a, slug), v in AXIS_STATUS.items() }, "files": files, "validation": validate_summary(), } with open(index_filename(), "w", encoding="utf-8") as f: json.dump(index, f, indent=2, ensure_ascii=False, default=str) print(f" → {index_filename()}") # --------------------------------------------------------------------------- # CLI # --------------------------------------------------------------------------- def parse_cli(argv): force = False profile = "full" out_dir = "heegner_atlas_output_v2" prime_bound = 200 hecke_prime_bound = 100 operator_prime_bound = 50 congruence_test_primes = 45 axes = tuple(range(1, 13)) i = 1 while i < len(argv): a = argv[i] if a == "--force": force = True elif a == "--profile" and i + 1 < len(argv): profile = argv[i + 1] i += 1 elif a == "--out" and i + 1 < len(argv): out_dir = argv[i + 1] i += 1 elif a == "--prime-bound" and i + 1 < len(argv): prime_bound = int(argv[i + 1]) i += 1 elif a == "--hecke-prime-bound" and i + 1 < len(argv): hecke_prime_bound = int(argv[i + 1]) i += 1 elif a == "--operator-prime-bound" and i + 1 < len(argv): operator_prime_bound = int(argv[i + 1]) i += 1 elif a == "--congruence-test-primes" and i + 1 < len(argv): congruence_test_primes = int(argv[i + 1]) i += 1 elif a == "--axes" and i + 1 < len(argv): axes = tuple(int(x.strip()) for x in argv[i + 1].split(",") if x.strip()) i += 1 i += 1 return AtlasConfig( out_dir=out_dir, force=force, profile=profile, prime_bound=prime_bound, hecke_prime_bound=hecke_prime_bound, operator_prime_bound=operator_prime_bound, congruence_test_primes=congruence_test_primes, axes=axes, ) # --------------------------------------------------------------------------- # MAIN # --------------------------------------------------------------------------- def run_all(): print("=" * 78) print(" HEEGNER ATLAS v2 — herbouwde Sage-pipeline") print(f" Output: {CFG.out_dir}/") print(f" Axes: {CFG.axes}") print(f" Profile: {CFG.profile}") print("=" * 78) t0 = time.time() axis_map = { 1: axis_1_number_fields, 2: axis_2_modular_curves, 3: axis_3_hecke_diagnostics, 4: axis_4_elliptic_curves, 5: axis_5_multiplicative_groups, 6: axis_6_euler_polynomials, 7: axis_7_hecke_eigenvalues, 8: axis_8_heegner_prime_signatures, 9: axis_9_isogeny_classes, 10: axis_10_modular_symbols, 11: axis_11_l_values, 12: axis_12_galois, } for ax in CFG.axes: fn = axis_map.get(ax) if fn is None: print(f"[warn] onbekende as {ax}, overgeslagen") continue fn() # Rigorous prime-ideal newform congruence supplement. # Runs alongside axis 3 whenever axis 3 is selected. if 3 in CFG.axes: axis_3_rigorous_congruences() # Derived synthesis layer (axis 13) — read axes 1-12 + rigorous, produce # publication-ready tables. print("\n" + "=" * 78) print(" DERIVED LAYER (axis 13)") print("=" * 78) derived_cm_singular_moduli() derived_master_congruence_table() derived_orbit_registry() derived_jacobian_factorization() derived_heegner_hypothesis_matrix() derived_global_summary() write_index(t0) total = time.time() - t0 print("\n" + "=" * 78) print(f" KLAAR. Totale tijd: {total / 60.0:.2f} minuten") print(f" Output: {CFG.out_dir}/") print("=" * 78) # Sage preprocesses .sage files and runs them as modules — __name__ is not "__main__". # Just call directly. CFG = parse_cli(sys.argv) OUT = CFG.out_dir ensure_out() run_all()