"""
Experiments for "Training Is Numerical Integration: What Numerical Analysis Says About Learning Rates"
(numericalmethod.com, 2026; revised edition).

Requirements: Python >= 3.9, numpy >= 1.24. No other dependencies.
Run:          python3 experiments.py            -> results.json next to this file (a few minutes on a laptop)

Gradient-descent paths on least-squares problems are computed with the exact spectral formula of
Proposition 3 (w_k = sum_i [1 - (1 - h s_i)^k] b_i / s_i v_i), which equals running gradient descent step by
step up to floating-point rounding; check_closed_form() verifies this on one data set. All seeds are fixed.
"""
import json
import math
import os
import sys
import time
import warnings

import numpy as np

warnings.filterwarnings('ignore', message='.*encountered in matmul')  # spurious numpy 2.x + Accelerate warnings
SEEDS = 50


def summary(v):
    v = np.asarray([x for x in np.ravel(v) if np.isfinite(x)], dtype=float)
    if not len(v):
        return None
    q1, med, q3 = np.percentile(v, [25, 50, 75])
    return {'median': float(med), 'q1': float(q1), 'q3': float(q3), 'n': int(len(v))}


# ---------------------------------------------------------------------------------------------------------------
# E1  Backward error analysis on a small tanh network, 50 initialisations
# ---------------------------------------------------------------------------------------------------------------
class TanhNet:
    def __init__(self, width=16, n=64, seed=0):
        rng = np.random.default_rng(seed)
        self.x = np.linspace(-2, 2, n)
        self.y = np.sin(2 * self.x) + 0.3 * self.x
        self.width = width
        self.theta0 = np.concatenate([rng.normal(0, 1.0, width), rng.normal(0, 0.5, width),
                                      rng.normal(0, 1.0 / math.sqrt(width), width)])

    def grad(self, th):
        w = self.width
        a, b, c = th[:w], th[w:2 * w], th[2 * w:]
        h = np.tanh(np.outer(self.x, a) + b)
        r = (h @ c - self.y) / len(self.x)
        dz = np.outer(r, c) * (1 - h ** 2)
        return np.concatenate([dz.T @ self.x, dz.sum(axis=0), h.T @ r])

    def hvp(self, th, v, eps=1e-6):
        return (self.grad(th + eps * v) - self.grad(th - eps * v)) / (2 * eps)


def rk4(f, x0, T, steps):
    x, dt = x0.copy(), T / steps
    for _ in range(steps):
        k1 = f(x); k2 = f(x + 0.5 * dt * k1); k3 = f(x + 0.5 * dt * k2); k4 = f(x + dt * k3)
        x = x + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    return x


def e1_modified_equation():
    hs = (0.2, 0.1, 0.05, 0.025, 0.0125)
    T, steps = 2.0, 2000
    d_flow, d_mod = np.zeros((SEEDS, len(hs))), np.zeros((SEEDS, len(hs)))
    for s in range(SEEDS):
        net = TanhNet(seed=s)
        flow = rk4(lambda th: -net.grad(th), net.theta0, T, steps)
        for j, h in enumerate(hs):
            x = net.theta0.copy()
            for _ in range(int(round(T / h))):
                x = x - h * net.grad(x)
            mod = rk4(lambda th: -net.grad(th) - 0.5 * h * net.hvp(th, net.grad(th)), net.theta0, T, steps)
            d_flow[s, j] = np.linalg.norm(x - flow)
            d_mod[s, j] = np.linalg.norm(x - mod)
    lh = np.log(hs[2:])
    slope = lambda D: np.array([np.polyfit(lh, np.log(row[2:]), 1)[0] for row in D])
    out = {'h': list(hs), 'T': T, 'seeds': SEEDS,
           'dist_to_gradient_flow': [summary(d_flow[:, j]) for j in range(len(hs))],
           'dist_to_modified_flow': [summary(d_mod[:, j]) for j in range(len(hs))],
           'slope_gradient_flow_smallest3h': summary(slope(d_flow)),
           'slope_modified_flow_smallest3h': summary(slope(d_mod)),
           'ratio_flow_over_mod_at_smallest_h': summary(d_flow[:, -1] / d_mod[:, -1])}
    print(f"E1 slopes (3 smallest h): flow {out['slope_gradient_flow_smallest3h']['median']:.3f} "
          f"modified {out['slope_modified_flow_smallest3h']['median']:.3f}; ratio at h=0.0125 "
          f"{out['ratio_flow_over_mod_at_smallest_h']['median']:.1f}", flush=True)
    return out


# ---------------------------------------------------------------------------------------------------------------
# Return-prediction data: p correlated weak signals, linear truth, Gaussian noise
# ---------------------------------------------------------------------------------------------------------------
def make_data(seed, p=200, n_train=300, n_val=250, n_test=5000, noise=1.0, beta_scale=0.35, target_r2=None):
    rng = np.random.default_rng([10, seed])
    F = rng.normal(size=(p, 5))
    Sx = (0.36 * F @ F.T + np.eye(p)) / p                     # population covariance of the signals

    def draw(n):
        return (rng.normal(size=(n, 5)) @ F.T * 0.6 + rng.normal(size=(n, p))) / math.sqrt(p)

    beta = rng.normal(0, 1, p) * beta_scale
    if target_r2 is not None:                                  # rescale the truth to a given population R^2
        v = beta @ Sx @ beta
        beta = beta * math.sqrt(target_r2 / (1 - target_r2) * noise ** 2 / v)
    Xtr, Xva, Xte = draw(n_train), draw(n_val), draw(n_test)
    ytr = Xtr @ beta + rng.normal(0, noise, n_train)
    yva = Xva @ beta + rng.normal(0, noise, n_val)
    yte = Xte @ beta + rng.normal(0, noise, n_test)
    return dict(Xtr=Xtr, ytr=ytr, Xva=Xva, yva=yva, Xte=Xte, yte=yte, beta=beta, Sx=Sx, noise=noise)


def r2(y, yhat):
    return 1 - np.sum((y - yhat) ** 2, axis=-1) / np.sum((y - y.mean()) ** 2)


class Spectral:
    """Exact GD / gradient-flow / ridge estimators for least squares from w0 = 0 (Proposition 3)."""

    def __init__(self, d):
        n = d['Xtr'].shape[0]
        A = d['Xtr'].T @ d['Xtr'] / n
        b = d['Xtr'].T @ d['ytr'] / n
        self.s, self.V = np.linalg.eigh(A)
        self.s = np.maximum(self.s, 1e-15)
        self.c = (self.V.T @ b) / self.s                        # OLS coefficients in the eigenbasis
        self.lmax = float(self.s.max())
        self.d = d
        self.Pte, self.Pva = d['Xte'] @ self.V, d['Xva'] @ self.V
        self.bV = self.V.T @ d['beta']
        self.SxV = self.V.T @ d['Sx'] @ self.V

    def filt_gd(self, h, ks):
        ks = np.asarray(ks, dtype=float)[:, None]
        return 1 - (1 - h * self.s[None, :]) ** ks

    def filt_ridge(self, alphas):
        return self.s[None, :] / (self.s[None, :] + np.asarray(alphas)[:, None])

    def scores(self, F):
        """test R^2, validation R^2 and population excess risk for each row of filters F."""
        coef = F * self.c[None, :]
        te = r2(self.d['yte'][None, :], coef @ self.Pte.T)
        va = r2(self.d['yva'][None, :], coef @ self.Pva.T)
        diff = coef - self.bV[None, :]
        risk = np.einsum('ij,jk,ik->i', diff, self.SxV, diff)
        return te, va, risk


def check_closed_form():
    d = make_data(0)
    sp = Spectral(d)
    n = d['Xtr'].shape[0]
    A = d['Xtr'].T @ d['Xtr'] / n
    b = d['Xtr'].T @ d['ytr'] / n
    h, k = 0.5 * 2 / sp.lmax, 400
    w = np.zeros(A.shape[0])
    for _ in range(k):
        w = w - h * (A @ w - b)
    w_cf = sp.V @ (sp.filt_gd(h, [k])[0] * sp.c)
    err = float(np.linalg.norm(w - w_cf) / np.linalg.norm(w))
    print(f"closed-form check: relative difference explicit GD vs formula after {k} steps = {err:.1e}", flush=True)
    return err


T_GRID = np.logspace(-1, 4.5, 140)
FRACS = (0.1, 0.5, 0.95)                                        # h * lambda_max / 2


def path_curves(sp):
    """Test R^2 along the path, for three step sizes (vs t = k h) and ridge (vs 1/alpha)."""
    out = {}
    for f in FRACS:
        h = f * 2 / sp.lmax
        ks = np.maximum(1, np.round(T_GRID / h)).astype(int)
        te, va, risk = sp.scores(sp.filt_gd(h, ks))
        out[f] = {'t': ks * h, 'test': te, 'val': va, 'risk': risk}
    te, va, risk = sp.scores(sp.filt_ridge(1.0 / T_GRID))
    out['ridge'] = {'t': T_GRID, 'test': te, 'val': va, 'risk': risk}
    return out


def e2_early_stopping(label, **kw):
    """50 data sets; best test R^2 and its location for GD at three step sizes and for ridge; validated choice;
    collapse and GD-vs-ridge gaps measured on a common grid of t."""
    rows = {k: {'best': [], 't_best': [], 'validated': []} for k in (*FRACS, 'ridge')}
    collapse, gap, ols, oracle, curves = [], [], [], [], {k: [] for k in (*FRACS, 'ridge')}
    collapse_near, gap_near, hmin, r_tstar, df_gd, df_ridge = [], [], [], [], [], []
    for s in range(SEEDS):
        d = make_data(s, **kw)
        sp = Spectral(d)
        pc = path_curves(sp)
        for k, v in pc.items():
            i = int(np.argmax(v['test']))
            rows[k]['best'].append(v['test'][i]); rows[k]['t_best'].append(v['t'][i])
            rows[k]['validated'].append(v['test'][int(np.argmax(v['val']))])
            c = np.interp(np.log(T_GRID), np.log(v['t']), v['test'])
            c[T_GRID < v['t'][0] * (1 - 1e-9)] = np.nan          # times shorter than one step are not reachable
            curves[k].append(c)
        g = [np.interp(np.log(T_GRID), np.log(pc[f]['t']), pc[f]['test']) for f in FRACS]
        collapse.append(np.max(np.abs(g[0] - g[1])))               # h*lmax = 0.2 vs 1.0 on the same t grid
        gap.append(np.max(np.abs(g[0] - pc['ridge']['test'])))    # GD (h*lmax=0.2) at t vs ridge at 1/t
        # the same gaps restricted to the neighbourhood of the optimum, [t*/10, 10 t*] (t* of GD at h*lmax=0.2),
        # and to times that the larger step can actually reach (t >= h)
        tstar = pc[FRACS[0]]['t'][int(np.argmax(pc[FRACS[0]]['test']))]
        win = (T_GRID >= tstar / 10) & (T_GRID <= tstar * 10)
        h1 = FRACS[1] * 2 / sp.lmax
        collapse_near.append(np.max(np.abs(g[0] - g[1])[win & (T_GRID >= h1)]) if np.any(win & (T_GRID >= h1)) else np.nan)
        gap_near.append(np.max(np.abs(g[0] - pc['ridge']['test'])[win]))
        hmin.append({f: f * 2 / sp.lmax for f in FRACS})
        r_tstar.append(T_GRID[int(np.argmax(pc['ridge']['test']))] / tstar)
        # effective degrees of freedom at the optima: sum of the filter over all directions
        df_gd.append(float(np.sum(1 - (1 - FRACS[0] * 2 / sp.lmax * sp.s) ** round(tstar / (FRACS[0] * 2 / sp.lmax)))))
        a_star = 1.0 / T_GRID[int(np.argmax(pc['ridge']['test']))]
        df_ridge.append(float(np.sum(sp.s / (sp.s + a_star))))
        ols.append(r2(d['yte'], d['Xte'] @ np.linalg.lstsq(d['Xtr'], d['ytr'], rcond=None)[0]))
        oracle.append(r2(d['yte'], d['Xte'] @ d['beta']))
    out = {'label': label, 'params': {k: v for k, v in kw.items()}, 'seeds': SEEDS,
           'oracle_r2': summary(oracle), 'ols_r2': summary(ols),
           'max_gap_h02_vs_h10': summary(collapse), 'max_gap_gd_vs_ridge': summary(gap),
           'near_opt_gap_h02_vs_h10': summary(collapse_near), 'near_opt_gap_gd_vs_ridge': summary(gap_near),
           'smallest_reachable_t': {str(f): summary([h[f] for h in hmin]) for f in FRACS},
           'ridge_1_over_alpha_star_over_gd_tstar': summary(r_tstar),
           'df_gd_at_tstar': summary(df_gd), 'df_ridge_at_alpha_star': summary(df_ridge), 'p': int(d['Xtr'].shape[1]),
           'curves_t': T_GRID.tolist(),
           'curves': {str(k): {'median': np.nanmedian(v, axis=0).tolist(), 'q1': np.nanpercentile(v, 25, axis=0).tolist(),
                               'q3': np.nanpercentile(v, 75, axis=0).tolist()} for k, v in curves.items()}}
    for k, v in rows.items():
        out[str(k)] = {'best_test_r2': summary(v['best']), 't_at_best': summary(v['t_best']),
                       'validated_test_r2': summary(v['validated'])}
    print(f"E2 {label}: oracle {out['oracle_r2']['median']:.4f} | best GD(0.2) {out['0.1']['best_test_r2']['median']:.4f} "
          f"t*={out['0.1']['t_at_best']['median']:.1f} | GD(1.9) t*={out['0.95']['t_at_best']['median']:.1f} | ridge "
          f"{out['ridge']['best_test_r2']['median']:.4f} | validated GD {out['0.1']['validated_test_r2']['median']:.4f} | "
          f"OLS {out['ols_r2']['median']:.3f} | near-opt gaps: h0.2 vs h1.0 {out['near_opt_gap_h02_vs_h10']['median']:.4f} "
          f"GD-ridge {out['near_opt_gap_gd_vs_ridge']['median']:.4f} | t*(1.0)={out['0.5']['t_at_best']['median']:.1f} "
          f"best(1.0)={out['0.5']['best_test_r2']['median']:.4f} best(1.9)={out['0.95']['best_test_r2']['median']:.4f} "
          f"smallest t at 1.9: {out['smallest_reachable_t']['0.95']['median']:.1f}", flush=True)
    return out


def e3_filters():
    out = []
    t, ss = 10.0, np.logspace(-3, 0, 200)
    for frac in FRACS:
        h = frac * 2
        k = int(round(t / h))
        gd, flow, ridge = 1 - (1 - h * ss) ** k, 1 - np.exp(-t * ss), ss / (ss + 1 / t)
        out.append({'h': h, 'k': k, 's': ss.tolist(), 'gd': gd.tolist(), 'flow': flow.tolist(), 'ridge': ridge.tolist(),
                    'max_gap_gd_flow': float(np.max(np.abs(gd - flow))), 'max_gap_flow_ridge': float(np.max(np.abs(flow - ridge)))})
    z = np.linspace(1e-6, 50, 2_000_001)
    g = 1 - np.exp(-z) - z / (1 + z)
    return {'filters': out, 'sup_flow_minus_ridge': float(g.max()), 'argmax_z': float(z[np.argmax(g)])}


def e_noise():
    """Prediction 'Noise': validated and oracle stopping time against the noise level (fixed truth)."""
    sigmas = (0.25, 0.5, 1.0, 2.0, 4.0, 8.0)
    out = {'sigmas': list(sigmas), 'rows': []}
    for sg in sigmas:
        t_val, t_orc, best = [], [], []
        for s in range(SEEDS):
            d = make_data(s, noise=sg)
            sp = Spectral(d)
            h = 0.1 * 2 / sp.lmax
            ks = np.maximum(1, np.round(T_GRID / h)).astype(int)
            te, va, risk = sp.scores(sp.filt_gd(h, ks))
            t_val.append(ks[np.argmax(va)] * h)
            t_orc.append(ks[np.argmin(risk)] * h)
            best.append(te.max())
        out['rows'].append({'sigma': sg, 't_validated': summary(t_val), 't_oracle': summary(t_orc), 'best_test_r2': summary(best),
                            'at_grid_end_oracle': int(np.sum(np.array(t_orc) >= 0.95 * T_GRID[-1]))})
    lo = np.log(sigmas)
    for key in ('t_validated', 't_oracle'):
        med = np.log([r[key]['median'] for r in out['rows']])
        out[f'slope_{key}'] = float(np.polyfit(lo, med, 1)[0])
        out[f'local_slopes_{key}'] = (np.diff(med) / np.diff(lo)).tolist()
    print("Enoise: " + "; ".join(f"sigma={r['sigma']}: t_val={r['t_validated']['median']:.1f} t_orc={r['t_oracle']['median']:.1f}"
                                for r in out['rows']) + f" | slopes val {out['slope_t_validated']:.2f} oracle {out['slope_t_oracle']:.2f}", flush=True)
    return out


def e_sgd():
    """Minibatch SGD on the original least-squares problem; 50 seeds (data and sampling)."""
    p, n = 200, 300
    t_check = np.unique(np.round(np.logspace(0, math.log10(400), 40), 1))
    configs = [(B, f) for B in (10, 30, n) for f in (0.25, 0.125)]   # f = h * lambda_max
    res = {f'B={B},h*lmax={f}': [] for B, f in configs}
    for s in range(SEEDS):
        d = make_data(s)
        Xtr, ytr, Xte, yte = d['Xtr'], d['ytr'], d['Xte'], d['yte']
        lmax = float(np.linalg.eigvalsh(Xtr.T @ Xtr / n).max())
        rng = np.random.default_rng([20, s])
        for B, f in configs:
            h = f / lmax
            w = np.zeros(p)
            curve, t, nxt = [], 0.0, 0
            while nxt < len(t_check):
                if B == n:
                    g = Xtr.T @ (Xtr @ w - ytr) / n
                else:
                    idx = rng.choice(n, B, replace=False)
                    g = Xtr[idx].T @ (Xtr[idx] @ w - ytr[idx]) / B
                w = w - h * g
                t += h
                while nxt < len(t_check) and t >= t_check[nxt] - 1e-12:
                    curve.append(float(r2(yte, Xte @ w)))
                    nxt += 1
            res[f'B={B},h*lmax={f}'].append(curve)
    out = {'t': t_check.tolist(), 'seeds': SEEDS, 'configs': {}}
    for key, curves in res.items():
        C = np.array(curves)
        i_best = np.argmax(C, axis=1)
        out['configs'][key] = {'best_test_r2': summary(C.max(axis=1)), 't_at_best': summary(t_check[i_best]),
                               'median_curve': np.median(C, axis=0).tolist()}
    full = np.array(res[f'B={n},h*lmax=0.25'])
    tstar_full = t_check[np.argmax(full, axis=1)]
    win = (t_check[None, :] >= tstar_full[:, None] / 10) & (t_check[None, :] <= tstar_full[:, None] * 10)
    wmax = lambda D: np.array([np.max(np.abs(d)[w]) for d, w in zip(D, win)])
    for B in (10, 30, n):
        a, b = np.array(res[f'B={B},h*lmax=0.25']), np.array(res[f'B={B},h*lmax=0.125'])
        out['configs'][f'B={B}'] = {'max_gap_between_step_sizes_same_t': summary(np.max(np.abs(a - b), axis=1)),
                                    'near_opt_gap_between_step_sizes': summary(wmax(a - b)),
                                    'best_r2_difference_h_minus_halfh': summary(a.max(axis=1) - b.max(axis=1))}
    for B in (10, 30):
        a = np.array(res[f'B={B},h*lmax=0.25'])
        out['configs'][f'B={B}']['max_gap_to_full_batch_same_t'] = summary(np.max(np.abs(a - full), axis=1))
        out['configs'][f'B={B}']['near_opt_gap_to_full_batch'] = summary(wmax(a - full))
        out['configs'][f'B={B}']['tstar_ratio_to_full_batch'] = summary(t_check[np.argmax(a, axis=1)] / tstar_full)
    print("Esgd: " + "; ".join(f"{k}: best {v['best_test_r2']['median']:.4f} t*={v['t_at_best']['median']:.1f}"
                               for k, v in out['configs'].items() if 'best_test_r2' in v), flush=True)
    for B in (10, 30, n):
        c = out['configs'][f'B={B}']
        print(f"   B={B}: near-opt gap h vs h/2 = {c['near_opt_gap_between_step_sizes']['median']:.4f}"
              + (f", vs full batch = {c['near_opt_gap_to_full_batch']['median']:.4f}, t* ratio to full batch "
                 f"{c['tstar_ratio_to_full_batch']['median']:.2f}" if B != n else ''), flush=True)
    return out


if __name__ == '__main__':
    t0 = time.time()
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'results.json')
    steps = [('closed_form_check', check_closed_form), ('e1_modified_equation', e1_modified_equation),
             ('e2_original', lambda: e2_early_stopping('original: 200 signals, 300 training days')),
             ('e2_realistic', lambda: [e2_early_stopping(f'realistic: oracle R2 {r}, {n} training days', n_train=n, target_r2=r)
                                       for n in (300, 1250) for r in (0.005, 0.01, 0.02)]),
             ('e3_filters', e3_filters), ('e_noise', e_noise), ('e_sgd', e_sgd)]
    only = sys.argv[1:]
    results = json.load(open(path)) if only and os.path.exists(path) else {'numpy': np.__version__, 'seeds': SEEDS}
    for name, fn in steps:
        if only and name not in only:
            continue
        t1 = time.time()
        results[name] = fn()
        print(f"-- {name} done in {time.time() - t1:.0f}s", flush=True)
        json.dump(results, open(path, 'w'), indent=1, default=float)
    print(f"done in {time.time() - t0:.0f}s -> {path}")
