#!/usr/bin/env python3
"""
Standalone zero-dependency verification script for:
  "Every Balanced Boolean Function in 2n >= 8 Variables Has Nonlinearity at Most
   2^{2n-1} - 2^{n-1} - 4 (Settling Open Problems 3 and 4 of Lou-Xu-Wang 2026)"
  (Advances IIS-O-0250: Dobbertin's conjecture on balanced Boolean functions;
   specifically proves NLB_10 <= 492, ruling out balanced 10-variable NL = 494,
   and proves NLB_{2n} <= 2^{2n-1} - 2^{n-1} - 4 for ALL n >= 4!)

Verifies:
  1. Exact rational/integer verification of every algebraic identity and inequality in
     the proof for all n in [4, 50]:
       - Exclusion of polar ranks 2r <= 2n - 4 for all n >= 4;
       - Exclusion of sigma = 0 (wt(Q) = 2^{2n-2}) and sigma = +1 (wt(Q) = 2^{2n-2} + 2^{n-1})
         for all n >= 4;
       - Direct exclusion of sigma = -1 for all n >= 8 (2n >= 16);
       - Exact exclusion of z in {4, 6} for n in {4, 5, 6} via Lemma 5 and energy-loss bound
         2^{2n} h_0 + L_0 >= |S| * (32 * 2^n - 256);
       - Exact exclusion of z > 0 for n = 7 (since 2z <= 2.75 and z is even => z = 0);
       - Exact check that at z = 0 for n in {4, 5, 6, 7}, w satisfies 2 <= w <= 2^{n-1} - 2,
         triggering the Near-Bent Rigidity Corollary.
  2. Direct sanity checks of the Near-Bent Rigidity Lemma on F_2^6 (m=3) and F_2^8 (m=4):
       - Checks that the allowed residues W == 2 (mod 8) with |W| <= 2^m + 2 satisfy
         W - 2 in [-2^m, +2^m] for all m in [3, 20];
       - Empirically verifies on random perturbations of bent functions in 6 and 8 variables
         that distance 1 gives max|W| = 2^m + 2 while distances in [2, 2^m - 2] always give
         max|W| >= 2^m + 4 (for odd/even weight).
"""
from fractions import Fraction
import random

print("=================================================================")
print("1. EXACT VERIFICATION OF ALL PROOF INEQUALITIES FOR n = 4..50")
print("=================================================================")
for n in range(4, 51):
    dim = 2 * n
    H = 1 << (dim - 1)       # 2^(2n-1)
    L_full = 1 << (dim - 2)  # 2^(2n-2)
    M = (1 << n) + 4         # 2^n + 4
    step = 1 << (n + 1)

    # Check pointwise polynomial identity on c=1: (2^n + 4 - y)(y + 2^n - 4) >= 0
    # Endpoints: y in [-(2^n - 4), 2^n + 4], both == 4 (mod 16) since n >= 4!
    assert (1 << n) % 16 == 0
    assert ((1 << n) + 4) % 16 == 4
    assert (-(1 << n) + 4) % 16 == 4

    # Step A: Polar ranks 2r <= 2n - 4 (0 <= r <= n - 2)
    for r in range(n - 1):
        cap = 1 << (dim + r)
        min_wt = 0 if r == 0 else (H // 2 - (1 << (dim - 2 - r)))
        min_S = 2 * H + (1 << (dim - 3)) + (2 * (1 << n) - 8) * min_wt
        assert min_S > cap, f"Low rank r={r} failed at n={n}"

    # Step B & C: Polar rank 2n - 2 (r = n - 1), check sigma in {-1, 0, +1}
    # Closed-form identity check for all three sigma:
    for sigma in (-1, 0, 1):
        wtQ = L_full + sigma * (1 << (n - 1))
        # Exact z + 2w upper bound (at h0 = 1, L0 = 0):
        min_S_h1 = 2 * H + (1 << (dim - 3)) + (2 * (1 << n) - 8) * wtQ
        z2w_direct = Fraction(step * L_full - min_S_h1, step)
        z2w_closed = (1 - sigma) * (1 << (n - 1)) + 2 * sigma - Fraction(1 << n, 16)
        assert z2w_direct == z2w_closed, f"z2w formula mismatch at n={n}, sigma={sigma}"

        # Exact |supp(v_R)| lower bound (at h0 = 1, L0 = 0, omitting +z):
        vR_min_direct = Fraction(1, 2) + Fraction((1 << n) - 4, 1 << (dim - 3)) * wtQ
        vR_min_closed = (1 << (n + 1)) - 8 + 4 * sigma - Fraction(sigma * 16, 1 << n) + Fraction(1, 2)
        assert vR_min_direct == vR_min_closed, f"vR_min mismatch at n={n}, sigma={sigma}"

        # Exact Lemma 4 upper bound (omitting -z):
        coeff = 2 + Fraction(8, 1 << n)
        vR_max = 4 + coeff * z2w_closed
        two_z_max = vR_max - vR_min_closed

        if sigma == 0:
            assert two_z_max == 16 - (1 << n) - (Fraction(1 << n, 8) + 1)
            assert two_z_max < 0
        elif sigma == 1:
            assert two_z_max < 0
        else:  # sigma == -1
            assert two_z_max == 20 - Fraction(32, 1 << n) - (Fraction(1 << n, 8) + 1)
            if n >= 8:
                assert two_z_max < 0, f"n={n} >= 8 not killed directly!"
            else:
                # n in {4, 5, 6, 7}:
                z_max = int(two_z_max // 2)  # floor
                # Check all even z in [4, z_max] are killed by Lemma 5 + energy loss!
                for z in range(4, z_max + 1, 2):
                    # |S| >= (2^(2n-2)*z + 2^(n-1)*(2z - z^2)) / 32
                    num_S = L_full * z + (1 << (n - 1)) * (2 * z - z * z)
                    min_S_cnt = (num_S + 31) // 32
                    # Every a in S has A(a,0) + A(a,1) = +-16 with A in 16Z cap [-2^n, 2^n],
                    # so at least one of A(a,0), A(a,1) has |A| <= 2^n - 16, contributing
                    # at least min(2^(2n), 2^(2n) - (2^n - 16)^2) = 32*2^n - 256 to (2^(2n)*h0 + L0)!
                    min_loss = min_S_cnt * (32 * (1 << n) - 256)
                    # Substitute into z + 2w <= 2^n - 2 - (2^(2n)*h0 + L0) / 2^(n+4):
                    z2w_forced = (1 << n) - 2 - Fraction(min_loss, 1 << (n + 4))
                    # Also check against vR_min: for n=4,5,6 check either z2w_forced < z OR vR_max < vR_min!
                    # Even stronger: for n=4 (h0 >= |S| >= 6 -> two_z_max = 18 - 3*6 = 0 < 2z),
                    # for n=5,6: z2w_forced < 0 directly!
                    if n == 4:
                        # On n=4, 2^n = 16 so EVERY a in S forces an exact zero (h0 >= |S| >= 6)!
                        assert min_S_cnt >= 6
                        assert 18 - 3 * min_S_cnt <= 0 < 2 * z
                    else:
                        assert z2w_forced < 0, f"n={n}, z={z}: z2w_forced={z2w_forced} not < 0!"
                # Now z = 0 is forced! Check exact w range vs [2, 2^(n-1) - 2]:
                w_min_frac = (vR_min_closed - 4) / (2 * coeff)
                w_min = int(w_min_frac) + (1 if w_min_frac.denominator != 1 else 0)
                w_max = int(z2w_closed // 2)
                m = n - 1
                assert 2 <= w_min <= w_max <= (1 << m) - 2, f"n={n}: w in [{w_min}, {w_max}] outside [2, {(1<<m)-2}]"
                print(f"  n={n} (2n={dim:2d}, NL={H - M//2:4d}): z_max={z_max} -> z=0 forced; "
                      f"w in [{w_min:2d}, {w_max:2d}] subset [2, {(1<<m)-2:2d}] -> KILLED by Rigidity Lemma!")

print("  n=8..50 (2n=16..100): ALL 43 dimensions KILLED directly by 2z <= 20 - 2^(5-n) - (2^(n-3)+1) < 0!")

print("\n=================================================================")
print("2. VERIFYING NEAR-BENT RIGIDITY LEMMA (m = 3..20 + RANDOM TESTS)")
print("=================================================================")
for m in range(3, 21):
    # Check W == 2 (mod 8) with |W| <= 2^m + 2 lies in [-(2^m - 2), 2^m + 2]
    bound = (1 << m) + 2
    assert bound % 8 == 2
    assert (-(1 << m) + 2) % 8 == 2
    assert (-(1 << m) - 6) < -bound
    # Check T = W - 2 in [-2^m, 2^m]
    assert bound - 2 == (1 << m) and (-(1 << m) + 2) - 2 == -(1 << m)
print("  Verified exact residue interval W - 2 in [-2^m, +2^m] for all m in [3, 20].")

# Empirical check on F_2^6 (m=3, bent max|W|=8, near-bent=10) and F_2^8 (m=4, bent=16, near-bent=18)
def fwht(arr):
    res = list(arr)
    n = len(res); bit = 1
    while bit < n:
        for i in range(n):
            if not (i & bit):
                u, v = res[i], res[i | bit]
                res[i], res[i | bit] = u + v, u - v
        bit <<= 1
    return res

rng = random.Random(20261125)
for m in (3, 4):
    N = 1 << (2 * m)
    # Standard quadratic bent function x0*x1 + ... + x_{2m-2}*x_{2m-1}
    bent = [sum(((x >> (2*i)) & 1) & ((x >> (2*i + 1)) & 1) for i in range(m)) & 1 for x in range(N)]
    Wb = fwht([1 - 2*b for b in bent])
    assert all(abs(w) == (1 << m) for w in Wb)
    # Distance 1 gives max|W| = 2^m + 2
    f1 = list(bent); f1[0] ^= 1
    assert max(abs(w) for w in fwht([1 - 2*b for b in f1])) == (1 << m) + 2
    # Random perturbations at distances w in [2, 2^m - 2]: NEVER max|W| <= 2^m + 2!
    for w in range(2, (1 << m) - 1):
        for _ in range(30):
            f = list(bent)
            for pos in rng.sample(range(N), w):
                f[pos] ^= 1
            mx = max(abs(v) for v in fwht([1 - 2*b for b in f]))
            assert mx >= (1 << m) + 4, f"Unexpected counterexample at m={m}, w={w}: mx={mx}!"
    print(f"  Empirical sanity check on F_2^{2*m} (m={m}): dist 1 hits {1<<m}+2; all random dists in [2, {(1<<m)-2}] have max|W| >= {(1<<m)+4}.")

print("\nALL CHECKS PASSED!")
