"""Step 7. [HP] App. B series re-summed at the independently computed root, and the assembly of the quartic coefficient.

The series coefficients a_n, b_n and the one-loop numbers c_3, Q_4, C_41 are MICROSCOPIC INPUTS OF THE PAPER
([HP] section 6, App. B); they are not recomputed here (that would need the full Hamiltonian/three-loop machinery).
What is checked: arithmetic of the printed tables, truncation / tail sensitivity, Pade spread, the assembly
b = g^4 [ -4 beta_0^2 I + beta_0 q_4 ], the sign margin of section 7, scheme invariance, the near-BPS and pure-YM tables.
Outputs: results/hp_series_resum.csv, results/hp_series_truncation.csv, results/hp_quartic.json, results/hp_budget.csv,
         results/hp_nearbps_check.csv, results/hp_sign_scenarios.csv
"""
from fractions import Fraction
import numpy as np
import mpmath as mp
from common import Tee, event, save_json, save_csv, read_csv, load_json, check

mp.mp.dps = 40


def pade_value(co, L, M, y):
    """[L/M] Pade approximant of sum co[k] y^k evaluated at y (own linear solve)."""
    co = [mp.mpf(c) for c in co]
    if M == 0:
        return sum(co[k] * y**k for k in range(L + 1))
    A = mp.matrix(M, M); rhs = mp.matrix(M, 1)
    for i in range(M):
        for j in range(M):
            k = L + 1 + i - (j + 1)
            A[i, j] = co[k] if k >= 0 else 0
        rhs[i] = -co[L + 1 + i]
    q = mp.lu_solve(A, rhs)
    qq = [mp.mpf(1)] + [q[j] for j in range(M)]
    pp = [sum(qq[j] * co[k - j] for j in range(0, min(k, M) + 1)) for k in range(L + 1)]
    return sum(pp[k] * y**k for k in range(L + 1)) / sum(qq[k] * y**k for k in range(M + 1))


def tails(ns, co, y):
    """Tail estimators for sum_{n>N} co_n y^n from the last coefficients."""
    terms = [co[i] * y ** ns[i] for i in range(len(ns))]
    out = {}
    r = terms[-1] / terms[-2]
    out["geometric_last_ratio"] = terms[-1] * r / (1 - r)
    # power-law coefficient growth co_n ~ C n^p (nearest singularity at y = 1): fit on the last four coefficients
    k = min(4, len(ns))
    X = np.array([[1.0, np.log(n)] for n in ns[-k:]]); Y = np.array([float(mp.log(abs(c))) for c in co[-k:]])
    (lc, p), *_ = np.linalg.lstsq(X, Y, rcond=None)
    sign = -1 if co[-1] < 0 else 1
    # normalise the model on the last coefficient
    C = abs(co[-1]) / mp.mpf(ns[-1]) ** p
    out["power_law_fit"] = sign * mp.nsum(lambda n: C * n ** mp.mpf(p) * y**n, [ns[-1] + 1, mp.inf])
    out["power_law_exponent"] = float(p)
    # Aitken delta^2 on the last three partial sums
    S = [sum(terms[: i + 1]) for i in range(len(terms))]
    s0, s1, s2 = S[-3], S[-2], S[-1]
    out["aitken"] = (s2 - (s2 - s1) ** 2 / ((s2 - s1) - (s1 - s0))) - s2
    out["last_ratio"] = float(r)
    return out, S, terms


def main():
    H = load_json("hp_hagedorn.json")
    yH_cf = 2 - mp.sqrt(3)
    yH = mp.sqrt(mp.mpf(H["x_H_modesum"]))            # independently computed root (mode sum, s06)
    b0 = -2 * mp.log(yH)
    R = {"checks": [], "y_H_used": mp.nstr(yH, 30), "y_H_minus_closed_form": float(yH - yH_cf)}; C = R["checks"]
    rows = read_csv("hp_series_extracted.csv")
    out_rows = []; trunc_rows = []
    best = {}
    for which, paper_val, paper_err, label in (("a", -0.7340, 1e-4, "q4a tree kernel"), ("b", -1.500, 3e-3, "q4b loop kernel")):
        rr = [r for r in rows if r["series"] == which]
        ns = [int(r["n"]) for r in rr]
        co = [mp.mpf(Fraction(r["coeff_tex"]).numerator) / Fraction(r["coeff_tex"]).denominator if r["exact_rational"] == "True" else mp.mpf(r["coeff_tex"]) for r in rr]
        tl, S, terms = tails(ns, co, yH)
        print(f"== series {which} ({label}): {len(ns)} coefficients, n = {ns[0]}..{ns[-1]}; evaluated at y_H = {mp.nstr(yH, 20)}")
        nterm_ok = npart_ok = 0
        for i, r in enumerate(rr):
            dt = abs(float(terms[i]) - float(r["term_printed"])); dp = abs(float(S[i]) - float(r["partial_printed"]))
            nterm_ok += dt <= 0.6e-5; npart_ok += dp <= 1.01e-4
            out_rows.append([which, ns[i], r["coeff_tex"], r["exact_rational"], float(terms[i]), r["term_printed"], dt, float(S[i]), r["partial_printed"], dp,
                             float(terms[i] / terms[i - 1]) if i else ""])
        print(f"  printed term sizes reproduced (|diff| <= 0.6e-5): {nterm_ok}/{len(rr)}; printed partial sums reproduced (|diff| <= 1e-4): {npart_ok}/{len(rr)}")
        C.append({"label": f"series {which}: printed terms reproduced", "computed": nterm_ok, "paper": len(rr), "absdiff": len(rr) - nterm_ok, "tol": 0, "pass": nterm_ok == len(rr), "source": "[HP] App. B", "unit": ""})
        C.append({"label": f"series {which}: printed partial sums reproduced", "computed": npart_ok, "paper": len(rr), "absdiff": len(rr) - npart_ok, "tol": 0, "pass": npart_ok == len(rr), "source": "[HP] App. B", "unit": ""})
        ratios = [float(terms[i] / terms[i - 1]) for i in range(1, len(terms))]
        print(f"  successive term ratios: {[round(x, 4) for x in ratios]}")
        print(f"  coefficient growth ~ n^p with p = {tl['power_law_exponent']:.2f} (last four coefficients); asymptotic term ratio must tend to y_H = {float(yH):.4f}, last observed {tl['last_ratio']:.4f}")
        print(f"  partial sum {mp.nstr(S[-1], 8)}; tails: geometric {mp.nstr(tl['geometric_last_ratio'], 4)}, power-law model {mp.nstr(tl['power_law_fit'], 4)}, Aitken {mp.nstr(tl['aitken'], 4)}")
        # Pade table on the reduced series sum_k co_k y^k (after factoring y^n0)
        n0 = ns[0]; K = len(co) - 1
        pades = {}
        for M in range(1, K // 2 + 2):
            for Lp in range(max(0, K - M - 2), K - M + 1):
                if Lp >= 0 and Lp + M <= K:
                    try:
                        val = yH**n0 * pade_value(co, Lp, M, yH)
                        ref = yH**n0 * mp.pade([float(c) for c in co[: Lp + M + 1]], Lp, M)[0][0] if False else None
                        pades[f"[{Lp}/{M}]"] = float(val)
                    except ZeroDivisionError:
                        pass
        top = {k: v for k, v in pades.items() if int(k[1:].split("/")[0]) + int(k.split("/")[1][:-1]) == K}
        near = {k: v for k, v in pades.items() if abs(v - float(S[-1])) < 0.05}
        print(f"  Pade approximants using all coefficients (L+M = {K}): " + ", ".join(f"{k} {v:.5f}" for k, v in top.items()))
        est = [float(S[-1] + tl[k]) for k in ("geometric_last_ratio", "power_law_fit", "aitken")]
        allv = est + list(top.values())
        allv_f = [v for v in allv if abs(v - float(S[-1])) < 0.05]
        centre = float(S[-1] + tl["power_law_fit"])
        best[which] = dict(partial=float(S[-1]), estimates=dict(geometric=est[0], power_law=est[1], aitken=est[2]), pade_top=top, pade_all=pades,
                           min=min(allv_f), max=max(allv_f), centre_power_law=centre, paper=paper_val, paper_err=paper_err, last_ratio=tl["last_ratio"], p=tl["power_law_exponent"],
                           n_outlier_pade=len(allv) - len(allv_f))
        print(f"  all estimators (excluding {len(allv)-len(allv_f)} defective Pade with a nearby pole): [{min(allv_f):.5f}, {max(allv_f):.5f}]; power-law-tail value {centre:.5f}; paper {paper_val}({paper_err})")
        C.append(check(f"q4{which}(x_H) with power-law tail", centre, paper_val, max(paper_err * 1.5, 2e-4), f"[HP] eq. (q4{which})"))
        # truncation sensitivity
        for kk in range(3, len(ns) + 1):
            tl_k, S_k, _ = tails(ns[:kk], co[:kk], yH)
            trunc_rows.append([which, ns[kk - 1], float(S_k[-1]), float(S_k[-1] + tl_k["geometric_last_ratio"]), float(S_k[-1] + tl_k["power_law_fit"]), float(S_k[-1] + tl_k["aitken"])])
        # sensitivity to the root
        dq = sum(co[i] * ns[i] * yH ** (ns[i] - 1) for i in range(len(ns)))
        best[which]["dq_dy"] = float(dq)
        print(f"  d q/d y at y_H = {float(dq):.3f}: a shift of y_H by 1e-6 moves the sum by {float(dq)*1e-6:.1e}")
    save_csv("hp_series_resum.csv", ["series", "n", "coeff", "exact_rational", "term_at_yH", "term_printed", "term_absdiff", "partial_sum", "partial_printed", "partial_absdiff", "ratio_to_previous_term"], out_rows)
    save_csv("hp_series_truncation.csv", ["series", "truncated_at_n", "partial_sum", "plus_geometric_tail", "plus_power_law_tail", "plus_aitken"], trunc_rows)
    R["series"] = best
    C.append(check("geometric remainder of series b", best["b"]["estimates"]["geometric"] - best["b"]["partial"], -0.007, 5e-4, "[HP] App. B Table (q4b) caption"))
    C.append(check("remainder of series a after y^16", best["a"]["estimates"]["geometric"] - best["a"]["partial"], -0.0001, 5e-5, "[HP] App. B Table (q4a) caption"))
    C.append(check("last term ratio of series a ('tends to 0.37')", best["a"]["last_ratio"], 0.37, 0.01, "[HP] App. B Table (q4a) caption"))
    pt = list(best["b"]["pade_top"].values())
    inside = [v for v in pt if -1.5044 - 5e-4 <= v <= -1.4987 + 5e-4]
    print(f"  series b: {len(inside)}/{len(pt)} top-order Pade values fall in the paper's quoted range [-1.5044, -1.4987]")
    R["pade_b_inside_paper_range"] = [len(inside), len(pt)]
    unconf = float(sum(mp.mpf(Fraction(r["coeff_tex"]).numerator) / Fraction(r["coeff_tex"]).denominator * yH ** int(r["n"]) for r in rows if r["series"] == "b" and int(r["n"]) >= 7))
    unconf_tail = unconf + (best["b"]["centre_power_law"] - best["b"]["partial"])
    print(f"  single-engine part of series b (n >= 7): {unconf:.4f} without tail, {unconf_tail:.4f} with tail (paper: -0.34 of -1.50)")
    C.append(check("unconfirmed (single-engine) part of q4b", unconf, -0.34, 0.01, "[HP] section 6.4 caveat"))
    R["unconfirmed_part_q4b"] = dict(without_tail=unconf, with_tail=unconf_tail)

    print("== assembly of the quartic coefficient ([HP] eq. master2, section 7.1)")
    A2 = mp.mpf(H["A2"])
    inp = dict(c3=(0.16821, 1e-5), Q4=(2.1222, 3e-4), q4a=(-0.7340, 1e-4), q4b=(-1.500, 3e-3))       # [HP] section 7.1 (paper inputs, literal scheme)
    I = inp["Q4"][0] / 2 + 2 * inp["c3"][0] ** 2 / A2
    q4 = inp["q4a"][0] + inp["q4b"][0]
    one = -4 * b0**2 * I; two = b0 * q4
    b = one + two
    pieces = [["square of one-loop operator: -4 beta0^2 Q4/2", float(-4 * b0**2 * inp["Q4"][0] / 2), -29.45],
              ["exchange of u_2: -4 beta0^2 2 c3^2/A2", float(-4 * b0**2 * 2 * inp["c3"][0] ** 2 / A2), -1.61],
              ["two-loop operator, tree part: beta0 q4a", float(b0 * inp["q4a"][0]), -1.93],
              ["two-loop operator, loop part: beta0 q4b", float(b0 * inp["q4b"][0]), -3.95]]
    save_csv("hp_budget.csv", ["contribution", "value_in_g4_units", "paper_value"], pieces)
    for nm, v, ref in pieces:
        C.append(check(nm, v, ref, 6e-3, "[HP] section 7.1, Fig. budget"))
    C.append(check("I = Q4/2 + 2 c3^2/A2", I, 1.11918, 2e-5, "[HP] eq. (schemes)"))
    C.append(check("beta_0^2", b0**2, 6.93751, 5e-6, "[HP] section 7.1"))
    C.append(check("-4 beta_0^2 I", one, -31.057, 2e-3, "[HP] eq. (b)"))
    C.append(check("beta_0 q4", two, -5.884, 2e-3, "[HP] eq. (b)"))
    C.append(check("b / g^4", b, -36.94, 6e-3, "[HP] eq. (b)"))
    C.append(check("b / lambda^2 = b/(256 pi^4)", b / (256 * mp.pi**4), -1.481e-3, 6e-7, "[HP] eq. (b-lambda)"))
    C.append(check("one-loop share of b", (pieces[0][1] + pieces[1][1]) / float(b), 0.84, 6e-3, "[HP] section 7.1"))
    qcrit = 4 * b0 * I
    C.append(check("q4 needed to flip the sign: 4 beta_0 I", qcrit, 11.79, 6e-3, "[HP] section 7.1"))
    C.append(check("sign margin q4_crit - q4", qcrit - q4, 14.0, 0.05, "[HP] section 6.4, 8.2 ('fourteen')"))
    # error propagation: linear and Monte Carlo
    dI = mp.sqrt((inp["Q4"][1] / 2) ** 2 + (4 * inp["c3"][0] * inp["c3"][1] / A2) ** 2)
    dq = mp.sqrt(inp["q4a"][1] ** 2 + inp["q4b"][1] ** 2)
    db = mp.sqrt((4 * b0**2 * dI) ** 2 + (b0 * dq) ** 2)
    rng = np.random.default_rng(20261119)
    n = 400000
    smp = {k: rng.normal(v[0], v[1], n) for k, v in inp.items()}
    bs = -4 * float(b0) ** 2 * (smp["Q4"] / 2 + 2 * smp["c3"] ** 2 / float(A2)) + float(b0) * (smp["q4a"] + smp["q4b"])
    print(f"  I = {float(I):.5f} +- {float(dI):.5f} (paper 1.11918(15));  q4 = {q4:.4f} +- {float(dq):.4f} (paper -2.234(3))")
    print(f"  b/g^4 = {float(b):.4f} +- {float(db):.4f} (linear), Monte Carlo mean {bs.mean():.4f} sd {bs.std():.4f}, P(b>0) = {np.mean(bs>0):.1e}  (paper -36.94(1))")
    C.append(check("uncertainty of b/g^4 (linear propagation of the quoted input errors)", db, 0.01, 4e-3, "[HP] eq. (b)"))
    # with the series re-summed here instead of the paper's quoted sums
    q4_here = best["a"]["centre_power_law"] + best["b"]["centre_power_law"]
    b_here = float(one) + float(b0) * q4_here
    b_lo = float(one) + float(b0) * (best["a"]["min"] + best["b"]["min"]); b_hi = float(one) + float(b0) * (best["a"]["max"] + best["b"]["max"])
    print(f"  with the series re-summed here: q4 = {q4_here:.4f} (range [{best['a']['min']+best['b']['min']:.4f}, {best['a']['max']+best['b']['max']:.4f}]) -> b/g^4 = {b_here:.3f} (range [{b_lo:.3f}, {b_hi:.3f}])")
    comm = 1.400 / 2 + 2 * 0.4523**2 / float(A2)
    C.append(check("commutator-scheme I = 1.400/2 + 2(0.4523)^2/A2", comm, 1.1200, 2e-4, "[HP] eq. (schemes)"))
    C.append({"label": "scheme invariance |I_lit - I_comm| within quoted error 0.0016", "computed": float(abs(I - comm)), "paper": 0.0016, "absdiff": float(abs(I - comm)), "tol": 0.0016,
              "pass": bool(abs(I - comm) <= 0.0016), "source": "[HP] eq. (schemes)", "unit": ""})
    scen = [["paper inputs", q4, float(b)],
            ["series re-summed here (power-law tails)", q4_here, b_here],
            ["drop the single-engine terms of q4b (n>=7)", q4 - unconf_tail, float(one) + float(b0) * (q4 - unconf_tail)],
            ["flip the sign of the single-engine terms", q4 - 2 * unconf_tail, float(one) + float(b0) * (q4 - 2 * unconf_tail)],
            ["two-loop operator switched off (q4 = 0)", 0.0, float(one)],
            ["shift q4 by +0.8 (size of the unresolved AMMPV class-7 discrepancy)", q4 + 0.8, float(one) + float(b0) * (q4 + 0.8)],
            ["shift q4 by -0.8", q4 - 0.8, float(one) + float(b0) * (q4 - 0.8)],
            ["q4 at which b = 0", float(qcrit), 0.0]]
    save_csv("hp_sign_scenarios.csv", ["scenario", "q4", "b_over_g4"], scen)
    for s in scen:
        print(f"  scenario: {s[0]:68s} q4 = {s[1]:+8.4f}  b/g^4 = {s[2]:+9.4f}")
    R["quartic"] = dict(I=float(I), dI=float(dI), q4=q4, dq4=float(dq), b_over_g4=float(b), db=float(db), b_over_lambda2=float(b / (256 * mp.pi**4)), q4_crit=float(qcrit),
                        margin=float(qcrit - q4), margin_in_units_of_dq4=float((qcrit - q4) / dq), mc_mean=float(bs.mean()), mc_sd=float(bs.std()), mc_prob_positive=float(np.mean(bs > 0)),
                        q4_resummed_here=q4_here, b_resummed_here=b_here, b_range_resummed=[b_lo, b_hi], I_commutator=comm, beta0=float(b0), scenarios=scen)
    # window and three temperatures
    C.append(check("(T_H - T_c)/T_H = |b|/(6 beta_0), coefficient of g^4", -b / (6 * b0), 2.337, 6e-4, "[HP] eq. (window)"))
    C.append(check("(T_H - T_c)/T_H coefficient of lambda^2", -b / (6 * b0) / (256 * mp.pi**4), 9.37e-5, 6e-8, "[HP] eq. (window)"))
    C.append(check("(T_H - T_min)/T_H = |b|/(3 beta_0), coefficient of g^4", -b / (3 * b0), 4.67, 6e-3, "[HP] eq. (window)"))
    hw = mp.mpf(H["HW_two_loop_coefficient"])
    C.append(check("T_c g^4 coefficient", hw + b / (6 * b0), -13.84, 6e-3, "[HP] eq. (three-T)"))
    C.append(check("T_min g^4 coefficient", hw + b / (3 * b0), -16.18, 6e-3, "[HP] eq. (three-T)"))
    C.append(check("jump: sqrt|b|/4 in units of g^2", mp.sqrt(-b) / 4, 1.52, 6e-3, "[HP] section 7.2"))
    C.append(check("pure YM (AMMPV): -5.7e-4 lambda_A^2 with lambda_A = lambda/2, in units of lambda^2", -5.7e-4 / 4, -1.4e-4, 6e-6, "[HP] section 7.1"))
    C.append(check("ratio N=4 / pure YM quartic coefficient ('ten times')", float(b / (256 * mp.pi**4)) / (-5.7e-4 / 4), 10, 0.6, "[HP] section 7.1"))

    print("== near-BPS table ([HP] section 7.3): b/G^2 = -(Q4/2 + 2 c3^2/A2) recomputed from the printed columns")
    nb = read_csv("hp_nearbps_extracted.csv"); nrows = []
    nok = 0
    for r in nb:
        A2s = float(Fraction(r["A2"])); c3 = float(r["c3"]); Q4s = float(r["Q4"]); pr = float(r["b_over_G2"])
        val = -(Q4s / 2 + 2 * c3**2 / A2s)
        dec = len(r["b_over_G2"].split(".")[1])
        tol = 0.5 * 10 ** (-dec) + 2 * abs(4 * c3 / A2s) * 0.5e-5 + 0.5e-5 / 2 + abs(2 * c3**2 / A2s**2) * 0.5e-5
        ok = abs(val - pr) <= tol; nok += ok
        nrows.append([r["sector"], r["xH"], A2s, c3, Q4s, pr, val, abs(val - pr), tol, bool(ok), bool(val < 0)])
        print(f"  {r['sector']:22s} printed {pr:+.5f}  recomputed {val:+.5f}  |diff| {abs(val-pr):.1e} (rounding tolerance {tol:.1e}) {'ok' if ok else 'MISMATCH'}")
    save_csv("hp_nearbps_check.csv", ["sector", "xH", "A2", "c3", "Q4", "b_over_G2_printed", "b_over_G2_recomputed", "absdiff", "rounding_tol", "consistent", "negative"], nrows)
    C.append({"label": "near-BPS table rows consistent with b = -(Q4/2+2c3^2/A2)", "computed": nok, "paper": len(nb), "absdiff": len(nb) - nok, "tol": 0, "pass": nok == len(nb), "source": "[HP] Table (near-BPS)", "unit": ""})
    C.append({"label": "near-BPS: all nine coefficients negative", "computed": sum(r[-1] for r in nrows), "paper": 9, "absdiff": 0, "tol": 0, "pass": all(r[-1] for r in nrows), "source": "[HP] section 7.3", "unit": ""})
    # su(2) row from the closed forms of App. B: c3 = 2x^3, Q4 = 4x^3 + 8x^4, z = 2x, x_H = 1/2
    xh = Fraction(1, 2)
    su2 = -((4 * xh**3 + 8 * xh**4) / 2 + 2 * (2 * xh**3) ** 2 / (1 - 2 * xh**2))
    C.append(check("su(2) sector exactly from c3 = 2x^3, Q4 = 4x^3+8x^4, A2 = 1-2x^2 at x = 1/2", float(su2), -0.75, 0, "[HP] App. B, Table (near-BPS)"))
    C.append(check("su(1|2), su(1,1|1) Hagedorn point (3-sqrt5)/2", (3 - mp.sqrt(5)) / 2, 0.381966, 5e-7, "[HP] Table (near-BPS)"))
    C.append(check("su(1,2|3) Hagedorn point (7-3 sqrt5)/2", (7 - 3 * mp.sqrt(5)) / 2, 0.145898, 5e-7, "[HP] Table (near-BPS)"))
    xf = mp.findroot(lambda x: x + x ** mp.mpf(1.5) - 1, 0.57)
    C.append(check("su(1|1), fermionic su(1,1) Hagedorn point: root of x + x^(3/2) = 1 (our identification)", xf, 0.569840, 5e-7, "[HP] Table (near-BPS)"))

    print("== pure Yang-Mills comparison table ([HP] section 8.2): arithmetic only")
    ym = read_csv("hp_ym_extracted.csv")
    s_this = sum(float(r["this_work"]) for r in ym); s_am = sum(float(r["AMMPV"]) for r in ym)
    C.append(check("sum of 'this work' column", s_this, -3.42, 6e-3, "[HP] Table (ym)"))
    C.append(check("sum of AMMPV column", s_am, -4.5, 0.05, "[HP] Table (ym)"))
    d7 = float(ym[-1]["this_work"]) - float(ym[-1]["AMMPV"])
    C.append(check("class-7 difference", d7, 1.29, 6e-3, "[HP] section 8.2"))
    C.append(check("difference of sums", s_this - s_am, 1.1, 0.05, "[HP] section 8.2"))
    C.append(check("class-7 difference in units of q4: 1.29e-4 * 64 pi^4", d7 * 1e-4 * 64 * mp.pi**4, 0.8, 0.02, "[HP] section 8.2"))
    R["ym"] = dict(sum_this=s_this, sum_AMMPV=s_am, class7_diff=d7, class7_in_q4_units=float(d7 * 1e-4 * 64 * mp.pi**4))
    R["n_checks"] = len(C); R["n_pass"] = sum(bool(c["pass"]) for c in C)
    print(f"SUMMARY: {R['n_pass']}/{R['n_checks']} checks pass")
    for c in C:
        if not c["pass"]:
            print("  NOT PASSED:", c["label"], c["computed"], c["paper"])
    save_json("hp_quartic.json", R)
    event("compute", "App. B series re-summed and quartic coefficient assembled",
          f"q4a = {best['a']['centre_power_law']:.5f}, q4b = {best['b']['centre_power_law']:.4f} (estimator range [{best['b']['min']:.4f}, {best['b']['max']:.4f}]); b/g^4 = {float(b):.3f}; sign margin {float(qcrit-q4):.2f}; {R['n_pass']}/{R['n_checks']} checks pass",
          outputs=["results/hp_quartic.json", "results/hp_series_resum.csv"])


if __name__ == "__main__":
    with Tee("s07_hp_series_quartic"):
        main()
