#!/usr/bin/env python3 """Capped Gram pair for the restricted support. The cap corrections are *quadratic forms* in the witness coefficients and the validated contraction (`compact_contract.correction_compact` for the numerator, `capped_numerator.violation_F2` for the denominator) is **linear** in the per-`nu` signature coefficients. So one contraction pass can record, for every signature slot, the scalar functional value `W[slot]` it carries; afterwards E(c) = sum_slot W[slot] * sig(c)[slot] (numerator correction) Delta(c) = sum_slot WD[slot] * SF2(c)[slot] (denominator correction) holds for **every** coefficient vector `c`, exactly, in rational arithmetic. Assembling the symmetric Gram matrices is then a cheap bilinear re-evaluation: E_sym[i][j] = W(sig(e_i + e_j)) (off-diagonal via polarisation) Delta_sym[i][j] = WD(SF2(e_i + e_j)) M2_cap = M2 + k * E_sym M1_cap = M1 - Delta_sym `tests/test_capped_gram.py` checks the recorded functionals against the direct per-witness contraction at small `k`, bit-for-bit. Conventions mirror `compact_contract.correction_compact` exactly (the binomial weight is applied outside / absent, as there), and `violation_F2` for Delta. Slot keys. For the numerator the recorded key is `(region, nu, slot)` with `slot` one of ("g2", p) from sigG2[(nu, p)] ("gt", p, cp, hc) from sigGT[(nu, p, cp, hc)] ("t2", cp, hc) from sigT2[(nu, cp, hc)] For the denominator the key is `(nu, e)` from `SF2[(nu, e)]`. """ from __future__ import annotations from collections import defaultdict from fractions import Fraction as Fr from math import comb from capped_numerator import region_planes # --------------------------------------------------------------------------- # compact-coefficient attribution # --------------------------------------------------------------------------- def build_A_attr(region, r, d, c, sigG2, sigGT, sigT2): """`build_A_compact` plus the slot attribution of every compact coefficient. Returns `(S, ATTR)` with S[nu][t] = compact coefficient (Fraction; may be 0) ATTR[nu][t][slot] = coefficient with which signature `slot` enters it Both are keyed by every `(nu, t)` the slots can produce; entries are kept even when `S` cancels to zero, so the recorded functional is witness independent. """ S: dict = defaultdict(lambda: defaultdict(Fr)) ATTR: dict = defaultdict(lambda: defaultdict(lambda: defaultdict(Fr))) if region == "E": for (nu, p), co in sigG2.items(): S[nu][p] += -co ATTR[nu][p][("g2", p)] += -1 elif region == "D": for (nu, p, cp, hc), co in sigGT.items(): for j in range(p + 1): cff = -2 * Fr(comb(p, j)) * (d ** (p - j + cp)) S[nu][j + hc] += co * cff ATTR[nu][j + hc][("gt", p, cp, hc)] += cff for (nu, cp, hc), co in sigT2.items(): cff = d ** cp S[nu][hc] += co * cff ATTR[nu][hc][("t2", cp, hc)] += cff elif region == "C": for (nu, p, cp, hc), co in sigGT.items(): for j in range(p + 1): cff = -2 * Fr(comb(p, j)) S[nu][(cp + j, hc + p - j)] += co * cff ATTR[nu][(cp + j, hc + p - j)][("gt", p, cp, hc)] += cff for (nu, cp, hc), co in sigT2.items(): S[nu][(cp, hc)] += co ATTR[nu][(cp, hc)][("t2", cp, hc)] += 1 return S, ATTR def _tdeg(region, t): return (t[0] + t[1]) if region == "C" else t def _attr_for_nu(region, d, g2list, gtlist, t2list): """Per-`nu` compact-key attribution `{t: {slot: coeff}}`. `g2list`/`gtlist`/`t2list` are the slot exponent tuples for one `nu`.""" tmap: dict = defaultdict(lambda: defaultdict(Fr)) if region == "E": for (p,) in g2list: tmap[p][("g2", p)] += -1 elif region == "D": for (p, cp, hc) in gtlist: for j in range(p + 1): cff = -2 * Fr(comb(p, j)) * (d ** (p - j + cp)) tmap[j + hc][("gt", p, cp, hc)] += cff for (cp, hc) in t2list: tmap[hc][("t2", cp, hc)] += d ** cp elif region == "C": for (p, cp, hc) in gtlist: for j in range(p + 1): cff = -2 * Fr(comb(p, j)) tmap[(cp + j, hc + p - j)][("gt", p, cp, hc)] += cff for (cp, hc) in t2list: tmap[(cp, hc)][("t2", cp, hc)] += 1 return tmap def _expand_key(region, t, r, d, U, c, jj): """Expansion of a single compact key into `{(i,k): coef}`, non-cached.""" from compact_contract import _expand_YZ_nc, _expand_YplusZ_nc if region == "C": A0 = c[r + 1] - r * d B0 = U - c[r + 1] - jj * d a, b = t return _expand_YZ_nc(A0, B0, a, b) if region == "D": B = U - (r + 1) * d - jj * d return _expand_YplusZ_nc(B, t) B = U - r * d - jj * d return _expand_YplusZ_nc(B, t) def _grouped_by_j(r, s, d, nu): from nu_fast import grouped_expansion_fast G = grouped_expansion_fast(r, s, d, nu) if not G: return {} byj: dict = defaultdict(lambda: defaultdict(Fr)) for (a, b, jj), co in G.items(): byj[jj][(a, b)] += co return {j: {k: v for k, v in m.items() if v} for j, m in byj.items()} def _seg_limits(planes): lo = hi = None for (A, B, C) in planes: if B == 0: if C < 0: return Fr(0), None continue v = Fr(C, B) if B > 0: hi = v if hi is None else min(hi, v) else: lo = v if lo is None else max(lo, v) if lo is None: lo = Fr(0) return lo, hi def _yline_limits(planes): lo = hi = None for (A, B, C) in planes: if A == 0: if C < 0: return Fr(0), None continue v = Fr(C, A) if A > 0: hi = v if hi is None else min(hi, v) else: lo = v if lo is None else max(lo, v) if lo is None: lo = Fr(0) return lo, hi # --------------------------------------------------------------------------- # numerator functional # --------------------------------------------------------------------------- def _accum(Pacc, tmap, exp, g): """Add one `(nu, jj)` block's functional `partial_t` into `Pacc[t]`. `partial_t = sum_{(i,k) in exp[t]} exp[t][(i,k)] * g[(i,k)]`. The slot attribution is applied *once* after the whole `jj` loop (it is independent of `jj`), which is what makes the pass affordable at k = 46: distributing inside the `jj` loop costs an extra factor `#jj`.""" for t in tmap: et = exp[t] if not et: continue partial = Fr(0) for (i, kk), cE in et.items(): gg = g.get((i, kk), Fr(0)) if gg and cE: partial += cE * gg if partial: Pacc[t] = Pacc.get(t, Fr(0)) + partial def numerator_functionals(region, k, d, U, ell, c, sigG2, sigGT, sigT2, only_r=None): """`{(region, nu, slot): W}` for one region (C, D or E). The recorded functional reproduces the contraction for every coefficient vector whose signature slots lie in the supplied sets: `sum_slot W[slot] * sig[slot] == correction_compact(region, ...)`. """ from compact_contract import _moments n = k - 1 W: dict = defaultdict(Fr) # group the signature slots by `nu`; the per-`nu` attribution is rebuilt # inside the r-loop and discarded, so peak memory stays at one `nu`. by_nu: dict = defaultdict(lambda: ([], [], [])) for (nu, p) in sigG2: by_nu[nu][0].append((p,)) for key in sigGT: by_nu[key[0]][1].append((key[1], key[2], key[3])) for key in sigT2: by_nu[key[0]][2].append((key[1], key[2])) if not by_nu: return {} if region == "E": wdeg = max((p for (nu, p) in sigG2), default=0) elif region == "D": wdeg = max([p + hc for (_n, p, _cp, hc) in sigGT] + [hc for (_n, _cp, hc) in sigT2] + [0]) else: wdeg = max([p + cp + hc for (_n, p, cp, hc) in sigGT] + [cp + hc for (_n, cp, hc) in sigT2] + [0]) pdeg = (n - 2) + max(sum(nu) for nu in by_nu) maxdeg = wdeg + pdeg for r in range(0, n + 1): if only_r is not None and r != only_r: continue s = n - r if region == "E": if r * d > ell: break if r == 0: continue elif r * d > c[r]: break for nu, (g2l, gtl, t2l) in by_nu.items(): tmap = _attr_for_nu(region, d, g2l, gtl, t2l) if not tmap: continue Gj = _grouped_by_j(r, s, d, nu) Pacc: dict = {} for jj, P in Gj.items(): if not P or (r + jj) * d > ell: continue planes = region_planes(region, r, jj, d, U, ell, c) exp = {t: _expand_key(region, t, r, d, U, c, jj) for t in tmap} if r == 0: lo, hi = _seg_limits(planes) if hi is None or lo >= hi: continue g = {} for t in tmap: for (i, kk) in exp[t]: if i != 0 or (i, kk) in g: continue acc = Fr(0) for (a, b), coef in P.items(): e = kk + b acc += coef * (hi ** (e + 1) - lo ** (e + 1)) / (e + 1) g[(i, kk)] = acc _accum(Pacc, tmap, exp, g) continue if s == 0: lo, hi = _yline_limits(planes) if hi is None or lo >= hi: continue g = {} for t in tmap: for (i, kk) in exp[t]: if kk != 0 or (i, kk) in g: continue acc = Fr(0) for (a, b), coef in P.items(): e = i + a acc += coef * (hi ** (e + 1) - lo ** (e + 1)) / (e + 1) g[(i, kk)] = acc _accum(Pacc, tmap, exp, g) continue M = _moments(region, r, jj, d, U, ell, c, maxdeg) if M is None: continue # g_{i,k} = sum_{(a,b) in P} P[a,b] * M[i+a][k+b] depends only on # (i,k), so it is computed once for the whole support. support = set() for t in tmap: support.update(exp[t]) g = {} for (i, kk) in support: acc = Fr(0) for (a, b), coef in P.items(): acc += coef * M[i + a][kk + b] g[(i, kk)] = acc _accum(Pacc, tmap, exp, g) for t, slotmap in tmap.items(): pt = Pacc.get(t) if not pt: continue for slot, cf in slotmap.items(): if cf: W[(region, nu, slot)] += cf * pt return {key: v for key, v in W.items() if v} # --------------------------------------------------------------------------- # denominator functional # --------------------------------------------------------------------------- def denominator_functionals(k, d, U, c, SF2, only_r=None): """`{(nu, e): WD}` for `Delta` (the `violation_F2` quadratic form).""" from radial_transform import int_scale_M, radial_T, integrate_A_T_scaled from moments_fast import polygon_moments_fast from capped_numerator import polygon_vertices, _expand_YplusZ W: dict = defaultdict(Fr) S: dict = defaultdict(set) for key in SF2: # accepts a dict or a key set nu, e = key S[nu].add(e) S = {nu: set(v) for nu, v in S.items()} for r in range(1, k + 1): s = k - r if r * d > U: break if r >= len(c): break if only_r is not None and r != only_r: continue for j in range(0, s + 1): if (r + j) * d > U: break planes = [(Fr(-1), Fr(0), Fr(0)), (Fr(0), Fr(-1), Fr(0)), (Fr(-1), Fr(0), -(c[r] - r * d)), (Fr(1), Fr(1), U - (r + j) * d)] V = polygon_vertices(planes) if not V: continue sign = Fr(comb(k, r) * (-1) ** j * comb(s, j)) maxA = maxT = 0 Ts = {} for nu in S: T2 = radial_T(r, j, s, d, nu) if not T2: continue Ts[nu] = T2 maxT = max(maxT, max((i + kk for (i, kk) in T2), default=0)) for nu, comp in S.items(): if nu not in Ts: continue maxA = max(maxA, max((e for e in comp), default=0)) if not Ts: continue M = polygon_moments_fast(planes, maxA + maxT) if M is None: continue Mint, dM = int_scale_M(M) dmax = len(M) - 1 for nu, comp in S.items(): T2 = Ts.get(nu) if T2 is None: continue for e in comp: Aj = _expand_YplusZ(U - r * d - j * d, e) val = integrate_A_T_scaled(Aj, T2, Mint, dM, dmax) W[(nu, e)] += sign * val return {key: v for key, v in W.items() if v} # --------------------------------------------------------------------------- # signature assembly + Gram matrices # --------------------------------------------------------------------------- def numerator_value(functionals, sG2, sGT, sT2): """`sum_slot W[slot]*sig[slot]` for the recorded numerator functionals.""" tot = Fr(0) for (nu, p), v in sG2.items(): if v: tot += v * functionals.get(("E", nu, ("g2", p)), Fr(0)) for region in ("C", "D"): for (nu, p, cp, hc), v in sGT.items(): if v: tot += v * functionals.get( (region, nu, ("gt", p, cp, hc)), Fr(0)) for (nu, cp, hc), v in sT2.items(): if v: tot += v * functionals.get( (region, nu, ("t2", cp, hc)), Fr(0)) return tot def denominator_value(functionals, SF2): tot = Fr(0) for (nu, e), v in SF2.items(): if v: tot += v * functionals.get((nu, e), Fr(0)) return tot def signature_parts(engine, coeffs): """`(sG2, sGT, sT2, SF2)` for the coefficient vector `coeffs`.""" from capped_numerator import (signature_F2, sig_GT, sig_square, sig_T2, signature_G, signature_T) terms = [(coeffs[i], engine.B[i][0], tuple(engine.B[i][1])) for i in range(engine.n) if coeffs[i] != 0] LG = signature_G(terms) LT = signature_T(terms) return sig_square(LG), sig_GT(LG, LT), sig_T2(LT), signature_F2(terms) def assemble_gram(functionals, engine, kind, verbose=False): """Symmetric quadratic-form matrix of the recorded `functionals`. `kind` is `"num"` (numerator correction) or `"den"` (Delta). No contraction is run: one signature assembly per basis element and per unordered pair. """ import sys from capped_numerator import (signature_F2, sig_GT, sig_square, sig_T2, signature_G, signature_T) n = engine.n def merged_lglt(cvec): terms = [(cvec[i], engine.B[i][0], tuple(engine.B[i][1])) for i in range(n) if cvec[i] != 0] return signature_G(terms), signature_T(terms) if kind == "num": def value_of(cvec): LG, LT = merged_lglt(cvec) return numerator_value(functionals, sig_square(LG), sig_GT(LG, LT), sig_T2(LT)) else: def value_of(cvec): terms = [(cvec[i], engine.B[i][0], tuple(engine.B[i][1])) for i in range(n) if cvec[i] != 0] return denominator_value(functionals, signature_F2(terms)) M = [[Fr(0)] * n for _ in range(n)] diag = [Fr(0)] * n for i in range(n): c = [Fr(0)] * n c[i] = Fr(1) diag[i] = value_of(c) M[i][i] = diag[i] for i in range(n): if verbose and i % 25 == 0: print(f" [{kind}] assemble row {i}/{n}", file=sys.stderr, flush=True) ci = [Fr(0)] * n ci[i] = Fr(1) for j in range(i + 1, n): c = list(ci) c[j] = Fr(1) s = value_of(c) M[i][j] = M[j][i] = (s - diag[i] - diag[j]) / 2 return M