#!/usr/bin/env python3
"""Write masters/t40_even_44_eleven.txt: the eleven master integrals of the even topology-40 (Apery K3')
sector returned by the reduction at seeding (4,4), decoded from the run's integer labels.
usage: build_t40_masters.py RAW_MASTERS WEIGHTS.json OUT"""
import sys, json
from common import sha256_file
raw, wfile, out = sys.argv[1:4]
W = json.load(open(wfile))
weights = W['weights']
ids = [l.split('#')[0].strip() for l in open(raw) if l.strip()]
vecs = [weights[i] for i in ids]
PROPS = ["k1^2", "(k1-k2)^2", "(k2-k3-q)^2", "(k2+k4)^2", "k3^2", "k4^2",
         "2u1.(k1-k3)  [cut]", "2u1.(k2-k3)  [cut]", "2u2.k3  [cut]", "2u2.(k3+k4)  [cut]",
         "k2^2", "(k2-q)^2", "2u1.k2", "2u2.k2", "2u2.k1", "2u1.k4", "(k1+q)^2", "(k3+q)^2", "(k4+q)^2",
         "(k1-k3)^2", "(k1-k4)^2", "(k3-k4)^2"]
hdr = ["# Master integrals of the even sector of topology 40 (labels of Brammer et al., arXiv:2505.10274), the Apery K3' sector at 5PM-2SF,",
       "# in the momentum routing given below, as returned by our",
       "# reduction at seeding (4,4): all integration-by-parts identities generated from seeds of the ten-propagator sector with at most",
       f"# {W['dots']} dots and at most {W['s_isp']} numerator powers ({W['n_eq']:,} equations in {W['n_cols']:,} distinct integrals), reduced with Kira",
       f"# as a user-defined system with the kinematic value y = {W['y0']} substituted.  Result: {len(vecs)} master integrals.",
       "# The worldline-exchange symmetry of the sector (u1<->u2 with k1->k2+k4, k3->k2-k3-q, k4->k1-k2) is NOT imposed in this list.",
       "# Adding the relations it generates to the same system and reducing again leaves 9 master integrals, entries 1, 2, 3, 4, 6, 7, 8, 9, 11",
       "# below (Sec. 5.5 of the paper and the supplementary material), the number Duhr et al. (arXiv:2503.20655, ancillary files) list",
       "# for this sector on the maximal cut.",
       "# Propagators P_1..P_22 (four loop momenta k_1..k_4; u_1^2 = u_2^2 = 1, u_1.u_2 = y, q^2 = -1, u_i.q = 0); P_1..P_10 define the sector,",
       "# P_7..P_10 are the cut worldline lines, P_11..P_22 are auxiliary (numerators):"]
for i, p in enumerate(PROPS, 1):
    hdr.append(f"#   P_{i:<2d} = {p}")
hdr.append("# One master per line: J[n_1,...,n_22] (n_i = exponent of P_i; negative = numerator), then a short description.")
def desc(v):
    dots = [i+1 for i, n in enumerate(v[:10]) if n > 1]
    nums = [(i+1, -n) for i, n in enumerate(v) if n < 0]
    s = []
    s.append('corner integral' if not dots and not nums else '')
    if dots: s.append('dot on ' + ', '.join(f'P_{d}' for d in dots))
    if nums: s.append('numerator ' + ' '.join(f'P_{i}' + (f'^{k}' if k > 1 else '') for i, k in nums))
    return '; '.join(x for x in s if x)
body = [f"J[{','.join(str(n) for n in v)}]   # {desc(v)}" for v in vecs]
open(out, 'w').write('\n'.join(hdr + body) + '\n')
print(f"wrote {out.split('/')[-1]}: {len(vecs)} masters; ids {ids}; raw sha256 {sha256_file(raw)[:16]}, weights sha256 {sha256_file(wfile)[:16]}")
