"""GPU refinement of a step function for the first autocorrelation constant C1 (minimize).

usage: py -3.15 c1_opt.py --init FILE.json [--upsample R] [--minutes M] [--lr LR]
                          [--beta0 B0] [--beta1 B1] [--out c1/best.npy] [--seed S]

score(a) = 2N max_k (a*a)_k / (sum a)^2 for heights a >= 0 on N equal steps of [-1/4,1/4].
Minimizes a log-sum-exp smoothing of the max with Adam (float64, FFT convolution on CUDA), with
beta annealed geometrically from B0 to B1 (in units of 1/score), projection onto a >= 0, and keeps
the best true (unsmoothed) score. --upsample R splits every step into R equal steps (same function,
same score, R times the freedom). Writes the best heights (float64) to --out and prints progress.
Score the result exactly with c1_to_cert.py + c1_score.py before trusting it.
"""
import argparse, json, math, time
from fractions import Fraction
import torch

ap = argparse.ArgumentParser()
ap.add_argument("--init", required=True); ap.add_argument("--upsample", type=int, default=1)
ap.add_argument("--minutes", type=float, default=5); ap.add_argument("--lr", type=float, default=1e-6)
ap.add_argument("--beta0", type=float, default=1e5); ap.add_argument("--beta1", type=float, default=1e8)
ap.add_argument("--out", default="c1/best.npy"); ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--report", type=int, default=2000)
A = ap.parse_args()
torch.manual_seed(A.seed); dev = "cuda"; dt = torch.float64

if A.init.endswith(".npy"):
    import numpy as np
    a0 = torch.tensor(np.load(A.init), dtype=dt)
else:
    d = json.load(open(A.init))
    v = d.get("heights", d.get("values", d)) if isinstance(d, dict) else d
    a0 = torch.tensor([float(Fraction(x)) for x in v], dtype=dt)
a0 = a0.repeat_interleave(A.upsample).to(dev)
N = a0.numel(); L = 1 << (2 * N - 1).bit_length()

def conv(a):
    F = torch.fft.rfft(a, n=L)
    return torch.fft.irfft(F * F, n=L)[: 2 * N - 1]

def true_score(a):
    with torch.no_grad():
        return float(2 * N * conv(a).max() / a.sum() ** 2)

a0 = a0 / a0.mean()                      # scale so heights ~ 1
x = a0.clone().requires_grad_(True)
opt = torch.optim.Adam([x], lr=A.lr)
best = true_score(a0); best_a = a0.clone(); start = best
print(f"N={N} start score {start:.15f}", flush=True)
t0 = time.time(); it = 0; T = A.minutes * 60
while time.time() - t0 < T:
    it += 1
    frac = min(1.0, (time.time() - t0) / T)
    beta = A.beta0 * (A.beta1 / A.beta0) ** frac
    c = 2 * N * conv(x) / x.sum() ** 2
    loss = torch.logsumexp(beta * c, 0) / beta
    opt.zero_grad(); loss.backward(); opt.step()
    with torch.no_grad():
        x.clamp_(min=0)
    if it % 50 == 0:
        s = true_score(x.detach())
        if s < best:
            best = s; best_a = x.detach().clone()
    if it % A.report == 0:
        print(f"[{time.time() - t0:6.0f}s] it {it} beta {beta:.3g} current {true_score(x.detach()):.15f} "
              f"best {best:.15f} gain {start - best:.3e}", flush=True)
import numpy as np
np.save(A.out, best_a.cpu().numpy())
print(f"done it {it}: start {start:.15f} best {best:.15f} gain {start - best:.3e} -> {A.out}", flush=True)
