#!/usr/bin/env python3
"""Second, independent pass over one lattice certificate from algebraic_bound.py.

* Recomputes a_i, delta_i exactly as algebraic_bound.py, then checks with mpmath (independent
  library, 50 extra digits) that |a_i - (e+pi)^i 2^s| <= delta_i for every i.
* Re-runs LLL (FLINT) and recomputes the Gram-Schmidt squared norms with plain Python
  Fractions (classical Gram-Schmidt, no determinant formula), and compares the resulting H_max
  with the value from the minor-ratio formula.

Usage: python verify_algebraic.py D d s
"""
import sys, os, math
from fractions import Fraction
import mpmath, flint
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import algebraic_bound as ab
from gmpy2 import mpz

D, d, s = map(int, sys.argv[1:4])
mL, kL = ab.read_dyadic(os.path.join(ab.DATA, f"enclosure_lower_{D}.txt"))
mU, kU = ab.read_dyadic(os.path.join(ab.DATA, f"enclosure_upper_{D}.txt"))
t = s + 4 * d + 64
sf = lambda m, k: (m << (k + t)) if k + t >= 0 else (m >> (-(k + t)))
Ln = sf(mL, kL); Un = sf(mU, kU) + 1
a, delta = [], []
for i in range(d + 1):
    lo, hi = Ln ** i, Un ** i; sh = t * i - s; w = hi - lo
    if sh >= 0: a.append(int(lo >> sh)); delta.append(int((w >> sh) + 2))
    else: a.append(int(lo << -sh)); delta.append(int((w << -sh) + 2))
mpmath.mp.prec = s + 8 * d + 200
alpha = mpmath.e + mpmath.pi
worst = max(abs(mpmath.mpf(a[i]) - alpha ** i * mpmath.mpf(2) ** s) / delta[i] for i in range(d + 1))
print("max_i |a_i - alpha^i 2^s| / delta_i (mpmath) =", mpmath.nstr(worst, 6), "-> OK" if worst <= 1 else "-> FAIL")
n = d + 1
B = flint.fmpz_mat([[1 if j == i else 0 for j in range(n)] + [a[i]] for i in range(n)])
Bp, T = B.lll(transform=True)
assert T * B == Bp and abs(T.det()) == 1
vecs = [[Fraction(int(Bp[i, j])) for j in range(n + 1)] for i in range(n)]
gs = []
for v in vecs:
    w = v[:]
    for g, gg in gs:
        mu = sum(x * y for x, y in zip(v, g)) / gg
        w = [x - mu * y for x, y in zip(w, g)]
    gs.append((w, sum(x * x for x in w)))
m2 = min(gg for _, gg in gs)
Hmax2 = m2 / (1 + sum(x * x for x in delta))
print("log10 H_max (Fractions Gram-Schmidt) =", round(0.5 * (math.log10(Hmax2.numerator) - math.log10(Hmax2.denominator)), 3))
r = ab.run(D, d, s)
print("log10 H_max (minor-ratio formula)    =", r["log10_Hmax"])
