"""2kwas: independent check of iis:2611.00321 (proof of IIS-N-00001: the crossing tau_m of F_t(m+1) and F_t(m)).

c_{s,k} = k! S(s,k),  F_t(s) = sum_k (c_{s,k} k^(t-2s))^2,  h(m) = 2m + log(m+1)/log(1+1/m),  mu = I_1(1)/(2 I_0(1)).
Our own code (plain Python, exact integers, decimal arithmetic at 60 digits); the author's script is not run.

usage: python3 -I stirling_check.py > stirling_check.out
"""
from decimal import Decimal as Dc, getcontext
from fractions import Fraction as Fr
from math import comb, factorial
import time

getcontext().prec = 60
T0 = time.time()

# ------------------------------------------------------------------ exact Stirling numbers of the second kind
NMAX = 401
S = [[0] * (NMAX + 2) for _ in range(NMAX + 2)]
S[0][0] = 1
for n in range(1, NMAX + 1):
    for k in range(1, n + 1):
        S[n][k] = k * S[n - 1][k] + S[n - 1][k - 1]
# cross-check k! S(s,k) with inclusion-exclusion (number of surjections)
ok_surj = all(factorial(k) * S[s][k] == sum((-1) ** i * comb(k, i) * (k - i) ** s for i in range(k + 1))
              for s in range(1, 61) for k in range(1, s + 1))
print("k! S(s,k) = number of surjections [s] -> [k] (inclusion-exclusion), s <= 60:", ok_surj)

# Lemma 1 (Lewis-Won): S(n+1,k) <= C(k+1,2) S(n,k), 1 <= k <= n
print("Lemma 1, n <= %d:" % (NMAX - 1), all(2 * S[n + 1][k] <= k * (k + 1) * S[n][k] for n in range(1, NMAX) for k in range(1, n + 1)))
# Step 0: A_k < 0 for 2 <= k <= m, A_1 = 0, A_{m+1} > 0
ok0 = True
for m in range(2, NMAX):
    c0 = [factorial(k) * S[m][k] for k in range(m + 2)]
    c1 = [factorial(k) * S[m + 1][k] for k in range(m + 2)]
    sg = [c1[k] ** 2 - k ** 4 * c0[k] ** 2 for k in range(1, m + 2)]
    ok0 &= sg[0] == 0 and all(x < 0 for x in sg[1:-1]) and sg[-1] > 0
print("Step 0 sign pattern (A_1 = 0, A_k < 0 for 2 <= k <= m, A_(m+1) > 0), 2 <= m <= %d:" % (NMAX - 1), ok0)
# Lemma 2: j! S(n,n-j) <= C(n,2)^j
print("Lemma 2, n <= 200:", all(factorial(j) * S[n][n - j] <= comb(n, 2) ** j for n in range(1, 201) for j in range(n)))
# Lemma 3 (GKP (6.43)) with second-order Eulerian numbers from their own recurrence
JM = 25
E2 = [[0] * (JM + 2) for _ in range(JM + 2)]
E2[0][0] = 1
for n in range(1, JM + 1):
    for k in range(n):
        E2[n][k] = (k + 1) * E2[n - 1][k] + ((2 * n - 1 - k) * E2[n - 1][k - 1] if k else 0)
ok3 = all(sum(E2[j][:j]) == factorial(2 * j) // (2 ** j * factorial(j)) for j in range(1, JM + 1))
ok3 &= all(S[n][n - j] == sum(E2[j][k] * comb(n + j - 1 - k, 2 * j) for k in range(j))
           for j in range(1, JM + 1) for n in range(j + 1, NMAX + 1))
print("Lemma 3: S(n,n-j) = sum_k <<j,k>> C(n+j-1-k,2j) and sum_k <<j,k>> = (2j-1)!!, j <= %d, n <= %d:" % (JM, NMAX), ok3)
ok3a = ok3b = True
for j in range(1, JM + 1):
    for n in range(2 * j, NMAX):
        main = Fr(n ** (2 * j), 2 ** j * factorial(j))
        ok3a &= main * (1 - Fr(2 * j * j, n)) <= S[n][n - j] <= main
        r = Fr(S[n + 1][n + 1 - j], S[n][n - j])
        ok3b &= 1 + Fr(2 * j, n - j) <= r <= 1 + Fr(2 * j, n - 2 * j + 1)
print("Lemma 3(a): n^(2j)/(2^j j!) (1 - 2j^2/n) <= S(n,n-j) <= n^(2j)/(2^j j!), exact, j <= %d, 2j <= n <= %d:" % (JM, NMAX - 1), ok3a)
print("Lemma 3(b): 1 + 2j/(n-j) <= S(n+1,n+1-j)/S(n,n-j) <= 1 + 2j/(n-2j+1), exact, same range:", ok3b)

# ------------------------------------------------------------------ constants
mu_num = sum(Dc(j) / (Dc(4) ** j * Dc(factorial(j)) ** 2) for j in range(60))
mu_den = sum(Dc(1) / (Dc(4) ** j * Dc(factorial(j)) ** 2) for j in range(60))
MU = mu_num / mu_den
print("mu = sum j/(4^j j!^2) / sum 1/(4^j j!^2) =", str(MU)[:22], "(paper: 0.2231949829...)")


def h_of(m):
    return 2 * m + Dc(m + 1).ln() / (Dc(1) + Dc(1) / m).ln()


def lse(xs):
    M = max(xs)
    return M + sum((x - M).exp() for x in xs).ln()


# ------------------------------------------------------------------ A. tau_m straight from the definition (full rows)
def tau_direct(m):
    lc = {s: [None] + [(Dc(factorial(k) * S[s][k])).ln() for k in range(1, s + 1)] for s in (m, m + 1)}
    lk = [None] + [Dc(k).ln() for k in range(1, m + 2)]

    def f(t):   # log F_t(m+1) - log F_t(m)
        a = lse([2 * (lc[m + 1][k] + (t - 2 * (m + 1)) * lk[k]) for k in range(1, m + 2)])
        b = lse([2 * (lc[m][k] + (t - 2 * m) * lk[k]) for k in range(1, m + 1)])
        return a - b
    h = h_of(m)
    lo, hi = h - 30, h + 10
    assert f(lo) < 0 < f(hi)
    for _ in range(90):
        mid = (lo + hi) / 2
        if f(mid) < 0: lo = mid
        else: hi = mid
    return (lo + hi) / 2, h


print()
print("A. tau_m from the definition (all k, exact Stirling rows, 60-digit arithmetic, bisection):")
print("     m   h(m)                 tau_m                h - tau_m        mu(log m + 3)    residual       residual*m/log^2 m")
directA = {}
for m in (2, 3, 4, 5, 10, 16, 20, 50, 64, 100, 200, 256, 300, 400):
    tau, h = tau_direct(m)
    directA[m] = tau
    lm = Dc(m).ln()
    res = h - tau - MU * (lm + 3)
    print("%6d   %-20s %-20s %-16s %-16s %-14s %s" % (m, str(h)[:18], str(tau)[:18], str(h - tau)[:14], str(MU * (lm + 3))[:14],
                                                     "%.3e" % float(res), "%.4f" % float(res * m / lm ** 2)))

# ------------------------------------------------------------------ A2. m = 1, and the poser's data (first integer wins m = 4..15; residuals at m = 16, 64, 256)
def F_int(s, t):   # F_t(s) exactly, for an integer t
    return sum(Fr(factorial(k) * S[s][k]) ** 2 * Fr(k) ** (2 * t - 4 * s) for k in range(1, s + 1))


print()
print("A2. m = 1: F_t(2) - F_t(1) = 4^(t-3) > 0 for every integer -10 <= t <= 20, so there is no crossing at m = 1:",
      all(F_int(2, t) - F_int(1, t) == Fr(4) ** (t - 3) for t in range(-10, 21)))
wins = {}
for m in range(2, 16):
    t = 0
    while F_int(m + 1, t) <= F_int(m, t): t += 1
    wins[m] = t
for m in range(2, 16):
    if m not in directA: directA[m] = tau_direct(m)[0]
POSER = [15, 19, 24, 29, 34, 39, 45, 50, 55, 61, 67, 72]
print("    first integer t with F_t(m+1) > F_t(m), exact rationals, m = 2..15:", [wins[m] for m in range(2, 16)])
print("    equal to floor(tau_m) + 1 from A for every m = 2..15:", all(wins[m] == int(directA[m]) + 1 for m in range(2, 16)))
print("    equal to the poser's list for m = 4..15 (15, 19, 24, 29, 34, 39, 45, 50, 55, 61, 67, 72):", [wins[m] for m in range(4, 16)] == POSER)
for m, val, val2 in ((16, "-0.0943891", "-0.09438905578"), (64, "-0.0552746", "-0.05527462884"), (256, "-0.0241813", "-0.02418133684")):
    res = h_of(m) - directA[m] - MU * (Dc(m).ln() + 3)
    print("    residual h - tau_m - mu(log m + 3) at m = %d from A: %s (poser: %s; conjecture review: %s)" % (m, str(res)[:16], val, val2))

# ------------------------------------------------------------------ B. large m: exact reduction + head terms j <= J
J = 40
targets = {300, 400, 1000, 1024, 2048, 4096, 8192, 10000, 16384, 32768, 65536, 100000, 131072, 262144}
need = set()
for m in targets: need |= {m, m + 1}
snap = {}
Dv = [1] + [0] * J            # Dv[j] = S(n, n-j) for the current n, starting at n = 1
for n in range(2, max(need) + 1):
    for j in range(J, 0, -1):
        Dv[j] += (n - j) * Dv[j - 1]
    if n in need:
        snap[n] = list(Dv)
print()
print("near-diagonal rows S(n, n-j), j <= %d, by recurrence up to n = %d (%.0f s); they agree with the full table at n = 300, 301, 400, 401:"
      % (J, max(need), time.time() - T0),
      all(snap[n][j] == S[n][n - j] for n in (300, 301, 400, 401) for j in range(J + 1)))


def setup(m):
    out = {}
    for s in (m, m + 1):
        lS = [Dc(snap[s][j]).ln() for j in range(J + 1)]
        lfall = [Dc(0)]
        for j in range(1, J + 1): lfall.append(lfall[-1] + Dc(s - j + 1).ln())
        l1 = [(Dc(s - j) / Dc(s)).ln() for j in range(J + 1)]
        out[s] = (lS, lfall, l1)
    return out


def logG(pre, s, eta):
    lS, lfall, l1 = pre[s]
    return lse([2 * (lS[j] - lfall[j] + eta * l1[j]) for j in range(J + 1)]), [2 * (lS[j] - lfall[j] + eta * l1[j]) for j in (J,)][0]


def tau_reduced(m):
    pre = setup(m)
    L = (Dc(1) + Dc(1) / m).ln()
    E = Dc(m + 1).ln() / L

    def f(d):   # log F_t(m+1) - log F_t(m) at t = h(m) - d, through the exact identity -2 d L + Delta
        return -2 * d * L + logG(pre, m + 1, E - d - 2)[0] - logG(pre, m, E - d)[0]
    lo, hi = Dc(0), Dc(m).ln()
    assert f(lo) > 0 > f(hi)
    for _ in range(90):
        mid = (lo + hi) / 2
        if f(mid) > 0: lo = mid
        else: hi = mid
    d = (lo + hi) / 2
    last = max(logG(pre, m + 1, E - d - 2)[1], logG(pre, m, E - d)[1])
    return d, pre, L, E, last


print()
print("B. tau_m through the exact identity log F(m+1) - log F(m) = -2dL + Delta, with the terms j <= %d:" % J)
EARLIER = {1024: "poser -0.0092107, conjecture review -0.009210674995", 4096: "poser -0.0032384, conjecture review -0.003238441218",
           16384: "poser -0.0010804, conjecture review -0.00108035591", 65536: "poser -0.0003471, conjecture review -0.0003470952671",
           262144: "conjecture review -0.00010837031"}
print("     m        h - tau_m          mu(log m + 3)      residual           residual*m/log^2 m   log of the j=%d term" % J)
for m in sorted(targets):
    d, pre, L, E, last = tau_reduced(m)
    lm = Dc(m).ln()
    res = d - MU * (lm + 3)
    extra = ""
    if m in EARLIER:
        extra = "   (earlier values: %s)" % EARLIER[m]
    if m in directA:
        extra = "   (A gives h - tau_m = %s; difference %.1e)" % (str(h_of(m) - directA[m])[:16], float(abs(h_of(m) - directA[m] - d)))
    print("%8d   %-18s %-18s %-18s %-20s %.0f%s" % (m, str(d)[:16], str(MU * (lm + 3))[:16], "%.10e" % float(res),
                                                  "%.4f" % float(res * m / lm ** 2), float(last), extra))

# ------------------------------------------------------------------ C. Step 4's uniform error
print()
print("C. |Delta - 2 mu (log m + 3)/m| * m^2 / log^2 m at d = 0, mu(log m + 3), log m (the author reports 0.781732, 0.709814, 0.665754):")
for m in (1000, 10000, 100000):
    pre = setup(m)
    L = (Dc(1) + Dc(1) / m).ln()
    E = Dc(m + 1).ln() / L
    lm = Dc(m).ln()
    vals = []
    for d in (Dc(0), MU * (lm + 3), lm):
        Delta = logG(pre, m + 1, E - d - 2)[0] - logG(pre, m, E - d)[0]
        vals.append(abs(Delta - 2 * MU * (lm + 3) / m) * m * m / lm ** 2)
    print("  m = %6d: %s ; max %.6f" % (m, ", ".join("%.6f" % float(v) for v in vals), float(max(vals))))

# ------------------------------------------------------------------ D. Step 2's pointwise bounds, all j, full rows
print()
print("D. Step 2: W_s(j) <= e^(2j)/j!^2 for j <= s/2 and W_s(j) <= (e/2)^(2s) 2^(-2 eta_s) for j > s/2, s in {m, m+1}, all j, d in {0, mu(log m + 3), log m}:")
for m in (50, 100, 200, 300, 400):
    L = (Dc(1) + Dc(1) / m).ln(); E = Dc(m + 1).ln() / L; lm = Dc(m).ln()
    ok = True; worst_lo = None
    for d in (Dc(0), MU * (lm + 3), lm):
        for s, eta in ((m, E - d), (m + 1, E - d - 2)):
            lsf = Dc(factorial(s)).ln()
            for j in range(s):
                k = s - j
                lw = 2 * (Dc(factorial(k) * S[s][k]).ln() - lsf + eta * (Dc(k) / Dc(s)).ln())
                if 2 * j <= s:
                    bound = 2 * j - 2 * Dc(factorial(j)).ln()
                else:
                    bound = 2 * s * (1 - Dc(2).ln()) - 2 * eta * Dc(2).ln()
                ok &= lw <= bound
                if j >= 1:      # j = 0 is the equality W_s(0) = 1
                    gap = bound - lw
                    worst_lo = gap if worst_lo is None or gap < worst_lo else worst_lo
    print("  m = %3d: %s (smallest log-margin over j >= 1: %.3f)" % (m, ok, float(worst_lo)))

# ------------------------------------------------------------------ E. the constants hidden in Steps 3(a), 3(b) and 4, j <= J = floor(m^(1/4))
from math import isqrt
print()
print("E. max over j <= J = floor(m^(1/4)) and d in {0, mu(log m + 3), log m} of")
print("   a = |W_m(j)/pi_j - 1| * m/(j^2 log m)   (Step 3(a))")
print("   b = |delta_j - 2j(log m + 3)/m| * m^2/(j^2 log m)   (Step 3(b))")
print("   c = |sum_j q_j j - mu| * m/log m   (Step 4)")
for m in (1000, 10000, 100000, 262144):
    pre = setup(m)
    L = (Dc(1) + Dc(1) / m).ln(); E = Dc(m + 1).ln() / L; lm = Dc(m).ln()
    JJ = isqrt(isqrt(m))
    A3 = B3 = C4 = Dc(0)
    for d in (Dc(0), MU * (lm + 3), lm):
        tm = [2 * (pre[m][0][j] - pre[m][1][j] + (E - d) * pre[m][2][j]) for j in range(JJ + 1)]
        tm1 = [2 * (pre[m + 1][0][j] - pre[m + 1][1][j] + (E - d - 2) * pre[m + 1][2][j]) for j in range(JJ + 1)]
        W = [x.exp() for x in tm]
        for j in range(1, JJ + 1):
            pj = Dc(1) / (Dc(4) ** j * Dc(factorial(j)) ** 2)
            A3 = max(A3, abs(W[j] / pj - 1) * m / (j * j * lm))
            B3 = max(B3, abs((tm1[j] - tm[j]) - 2 * j * (lm + 3) / m) * m * m / (j * j * lm))
        C4 = max(C4, abs(sum(j * W[j] for j in range(JJ + 1)) / sum(W) - MU) * m / lm)
    print("  m = %6d, J = %2d: a = %.4f, b = %.4f, c = %.4f" % (m, JJ, float(A3), float(B3), float(C4)))
print("total time %.0f s" % (time.time() - T0))
