"""
Experiments for "Precision Is a Resource: How Much Arithmetic Does a Covariance Matrix Deserve?"
(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 (about 5-8 minutes on a laptop)
              python3 experiments.py speed      -> also runs the timing benchmark (adds about 1 minute)

Low precision is emulated in float64 arithmetic: every operation's result is rounded to a t-bit significand
(t = 8 bfloat16, 11 binary16, 24 binary32). By default only the significand is emulated. Experiment
'range' additionally emulates the exponent range (subnormals, underflow, overflow) of binary16 and bfloat16.
Rounding is round-to-nearest-even unless stated otherwise. All computations are batched over seeds: arrays
carry a leading batch axis, and every element is still computed with the same sequence of rounded operations.
All random seeds are fixed.
"""
import json
import math
import os
import sys
import time
import warnings

import numpy as np

# numpy 2.x + Apple Accelerate can emit spurious 'divide by zero/overflow in matmul' warnings.
warnings.filterwarnings('ignore', message='.*encountered in matmul')

FORMATS = {
    # t: significand bits incl. the implicit bit; emin: exponent of the smallest normal number; max: largest finite
    'bf16': {'t': 8, 'emin': -126, 'max': (2 - 2 ** -7) * 2.0 ** 127},
    'fp16': {'t': 11, 'emin': -14, 'max': 65504.0},
    'fp32': {'t': 24, 'emin': -126, 'max': (2 - 2 ** -23) * 2.0 ** 127},
}
U = {k: 2.0 ** -v['t'] for k, v in FORMATS.items()}
SEEDS = 50


# ---------------------------------------------------------------------------------------------------------------
# Rounding
# ---------------------------------------------------------------------------------------------------------------
class Arith:
    """Rounding to a t-bit significand; optionally also to the exponent range of a format."""

    def __init__(self, fmt, exponent_range=False):
        self.t = FORMATS[fmt]['t']
        self.full = exponent_range
        self.emin = FORMATS[fmt]['emin']
        self.max = FORMATS[fmt]['max']

    def __call__(self, x):
        x = np.asarray(x, dtype=np.float64)
        m, e = np.frexp(x)                                    # x = m 2^e, 0.5 <= |m| < 1
        y = np.ldexp(np.round(m * 2.0 ** self.t) / 2.0 ** self.t, e)
        if self.full:
            q = 2.0 ** (self.emin - self.t + 1)               # subnormal spacing
            small = np.abs(x) < 2.0 ** self.emin
            y = np.where(small, np.round(x / q) * q, y)       # gradual underflow (to zero below q/2)
            y = np.where(np.abs(y) > self.max, np.sign(y) * np.inf, y)  # overflow
        return y


def rnd_t(x, t):
    m, e = np.frexp(x)
    return np.ldexp(np.round(m * 2.0 ** t) / 2.0 ** t, e)


def rnd_sr(x, t, rng):
    """Stochastic rounding to t bits: round away from zero with probability equal to the fractional part."""
    m, e = np.frexp(x)
    s = m * 2.0 ** t
    lo = np.floor(s)
    up = rng.random(np.shape(s)) < (s - lo)
    return np.ldexp((lo + up) / 2.0 ** t, e)


# ---------------------------------------------------------------------------------------------------------------
# Batched Cholesky and triangular solves, every operation rounded
# ---------------------------------------------------------------------------------------------------------------
def cholesky_b(A, r):
    """A: (B,n,n) SPD. Returns L (B,n,n) with NaN rows for batch members whose factorization broke down."""
    A = r(np.array(A, dtype=np.float64))
    B, n, _ = A.shape
    L = np.zeros_like(A)
    ok = np.ones(B, dtype=bool)
    for k in range(n):
        d = A[:, k, k]
        bad = ~(d > 0) | ~np.isfinite(d)
        ok &= ~bad
        d = np.where(bad, np.nan, d)
        lkk = r(np.sqrt(d))
        L[:, k, k] = lkk
        col = r(A[:, k + 1:, k] / lkk[:, None])
        L[:, k + 1:, k] = col
        A[:, k + 1:, k + 1:] = r(A[:, k + 1:, k + 1:] - r(col[:, :, None] * col[:, None, :]))
    L[~ok] = np.nan
    return L, ok


def forward_b(L, b, r):
    """Solve L y = b column by column; entry i accumulates its products in the order j = 0, 1, ..., i-1."""
    y = r(np.array(b, dtype=np.float64))
    n = y.shape[1]
    for j in range(n):
        y[:, j] = r(y[:, j] / L[:, j, j])
        if j + 1 < n:
            y[:, j + 1:] = r(y[:, j + 1:] - r(L[:, j + 1:, j] * y[:, j][:, None]))
    return y


def backward_b(L, y, r):
    """Solve L^T x = y."""
    x = np.array(y, dtype=np.float64)
    n = x.shape[1]
    for i in range(n - 1, -1, -1):
        x[:, i] = r(x[:, i] / L[:, i, i])
        if i > 0:
            x[:, :i] = r(x[:, :i] - r(L[:, i, :i] * x[:, i][:, None]))
    return x


def solve_b(A, b, r):
    L, ok = cholesky_b(A, r)
    return backward_b(L, forward_b(L, b, r), r), ok, L


def weights(x):
    return x / x.sum(axis=-1, keepdims=True)


def rel(a, b):
    return np.linalg.norm(a - b, axis=-1) / np.linalg.norm(b, axis=-1)


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))}


# ---------------------------------------------------------------------------------------------------------------
# Synthetic markets
# ---------------------------------------------------------------------------------------------------------------
def factor_model(n, rng, k=5, idio=(0.10, 0.30), market=1.0, vol_scale=1.0):
    """Daily covariance of a k-factor model with a market factor. Annualised vols 10-30% idiosyncratic."""
    Bm = rng.normal(0.0, 0.15, size=(n, k)) / math.sqrt(252)
    Bm[:, 0] = market * rng.uniform(0.5, 1.5, size=n) * 0.18 / math.sqrt(252)
    D = np.diag((rng.uniform(*idio, size=n) / math.sqrt(252)) ** 2)
    return (Bm @ Bm.T + D) * vol_scale ** 2


def draw_returns(Sigma, T, rng, dist='gauss'):
    """Returns (T,n) with covariance Sigma. 'student4': multivariate t with 4 dof, scaled to covariance Sigma.
    'regime': two volatility regimes (multipliers 0.7 and 1.8, persistence 0.98), scaled so that the
    unconditional covariance is Sigma."""
    n = Sigma.shape[0]
    C = np.linalg.cholesky(Sigma)
    Z = rng.standard_normal((T, n))
    if dist == 'student4':
        nu = 4.0
        w = rng.chisquare(nu, size=T) / nu
        Z = Z / np.sqrt(w)[:, None] * math.sqrt((nu - 2) / nu)
    elif dist == 'regime':
        m = np.array([0.7, 1.8])
        p_stay = 0.98
        s = np.empty(T, dtype=int)
        s[0] = rng.integers(2)
        flips = rng.random(T) > p_stay
        for i in range(1, T):
            s[i] = 1 - s[i - 1] if flips[i] else s[i - 1]
        # the chain is symmetric, so both regimes have stationary probability 1/2
        Z = Z * (m[s] / math.sqrt(np.mean(m ** 2)))[:, None]
    return Z @ C.T


def sample_cov(R):
    Rc = R - R.mean(axis=-2, keepdims=True)
    return np.swapaxes(Rc, -1, -2) @ Rc / (R.shape[-2] - 1)


def ledoit_wolf(R):
    """Ledoit and Wolf (2004) shrinkage towards a scaled identity, with the 1/T normalisation of the paper."""
    T, n = R.shape
    X = R - R.mean(axis=0)
    S = X.T @ X / T
    m = np.trace(S) / n
    d2 = np.sum((S - m * np.eye(n)) ** 2) / n
    b2bar = np.sum([np.sum((np.outer(x, x) - S) ** 2) for x in X]) / n / T ** 2
    b2 = min(b2bar, d2)
    delta = b2 / d2
    return delta * m * np.eye(n) + (1 - delta) * S, float(delta)


# ---------------------------------------------------------------------------------------------------------------
# E1  Main table: numerical vs statistical error, 50 seeds, plus u*sqrt(T) vs u*sqrt(T-n) fit   (B1, B4)
# ---------------------------------------------------------------------------------------------------------------
def e1_main():
    out = []
    for n, T in [(50, 100), (50, 250), (50, 1000), (50, 4000), (50, 16000),
                 (200, 250), (200, 400), (200, 1000), (200, 4000), (200, 16000)]:
        if True:
            stat, kap, Ss, w64s = [], [], [], []
            for s in range(SEEDS):
                rng = np.random.default_rng([1, n, T, s])
                Sigma = factor_model(n, rng)
                S = sample_cov(draw_returns(Sigma, T, rng))
                w_true = weights(np.linalg.solve(Sigma, np.ones(n)))
                w64 = weights(np.linalg.solve(S, np.ones(n)))
                stat.append(rel(w64, w_true))
                kap.append(np.linalg.cond(S))
                Ss.append(S)
                w64s.append(w64)
            Ss, w64s = np.array(Ss), np.array(w64s)
            row = {'n': n, 'T': T, 'stat': summary(stat), 'kappa': summary(kap)}
            for f in FORMATS:
                x, ok, _ = solve_b(Ss, np.ones((SEEDS, n)), Arith(f))
                num = np.where(ok, rel(weights(x), w64s), np.nan)
                ratio = num / np.array(stat)
                row[f] = {
                    'breakdowns': int((~ok).sum()),
                    'num': summary(num),
                    'ratio_over_u_sqrtT': summary(ratio / (U[f] * math.sqrt(T))),
                    'ratio_over_u_sqrtTmn': summary(ratio / (U[f] * math.sqrt(T - n))),
                    'num_over_u_sqrtn': summary(num / (U[f] * math.sqrt(n))),
                }
            row['stat_over_sqrt_n_over_Tmn'] = summary(np.array(stat) / math.sqrt(n / (T - n)))
            out.append(row)
            c = row['fp16']['ratio_over_u_sqrtT']
            print(f"E1 n={n:3d} T={T:5d} stat={row['stat']['median']:.3f} fp16 C={c['median']:.2f} "
                  f"[{c['q1']:.2f},{c['q3']:.2f}] bf16 breakdowns={row['bf16']['breakdowns']}", flush=True)
    return out


# ---------------------------------------------------------------------------------------------------------------
# E-align  Do sampling and rounding errors excite the same eigen-directions of Sigma_hat?   (B4)
# ---------------------------------------------------------------------------------------------------------------
def e_align():
    out = []
    n = 100
    r = Arith('fp16')
    for T in (2000, 500, 200, 125):          # n/T = 0.05, 0.2, 0.5, 0.8
        rows = {'stat': [], 'num': [], 'rand': []}
        amp = {'stat': [], 'num': [], 'rand': []}
        for s in range(SEEDS):
            rng = np.random.default_rng([2, T, s])
            Sigma = factor_model(n, rng)
            S = sample_cov(draw_returns(Sigma, T, rng))
            lam, V = np.linalg.eigh(S)
            x = np.linalg.solve(S, np.ones(n))
            L, ok = cholesky_b(S[None], r)
            if not ok[0]:
                continue
            E = {'stat': Sigma - S, 'num': L[0] @ L[0].T - S}
            G = rng.standard_normal((n, n))
            E['rand'] = (G + G.T) / 2
            k = max(1, n // 10)                 # bottom decile of eigenvalues
            for key, Ek in E.items():
                c = (V.T @ (Ek @ x)) / lam      # eigen-components of the first-order error Sigma^-1 E x
                rows[key].append(np.sum(c[:k] ** 2) / np.sum(c ** 2))
                # amplification relative to the worst case 1/lambda_min, for a perturbation of unit size
                amp[key].append(np.linalg.norm(c) / (np.linalg.norm(Ek @ x) / lam[0]))
        res = {'n': n, 'T': T, 'n_over_T': n / T}
        for key in rows:
            res[f'bottom_decile_share_{key}'] = summary(rows[key])
            res[f'amplification_vs_worst_{key}'] = summary(amp[key])
        res['amp_ratio_num_over_stat'] = summary(np.array(amp['num']) / np.array(amp['stat']))
        out.append(res)
        print(f"Ealign n/T={n / T:.2f} share bottom decile: stat={res['bottom_decile_share_stat']['median']:.2f} "
              f"num={res['bottom_decile_share_num']['median']:.2f} rand={res['bottom_decile_share_rand']['median']:.2f} "
              f"amp ratio num/stat={res['amp_ratio_num_over_stat']['median']:.2f}", flush=True)
    return out


# ---------------------------------------------------------------------------------------------------------------
# E-robust  Heavy tails, regime switching, Ledoit-Wolf shrinkage   (B5)
# ---------------------------------------------------------------------------------------------------------------
def e_robust():
    out = []
    n = 100
    for est in ('sample', 'lw'):
        for dist in ('gauss', 'student4', 'regime'):
            for T in (1000, 4000):
                stat, As, w64s, deltas, kap = [], [], [], [], []
                for s in range(SEEDS):
                    rng = np.random.default_rng([3, T, s])
                    Sigma = factor_model(n, rng)
                    R = draw_returns(Sigma, T, rng, dist)
                    if est == 'lw':
                        A, dl = ledoit_wolf(R)
                        deltas.append(dl)
                    else:
                        A = sample_cov(R)
                    w_true = weights(np.linalg.solve(Sigma, np.ones(n)))
                    w64 = weights(np.linalg.solve(A, np.ones(n)))
                    stat.append(rel(w64, w_true))
                    kap.append(np.linalg.cond(A))
                    As.append(A)
                    w64s.append(w64)
                As, w64s = np.array(As), np.array(w64s)
                row = {'estimator': est, 'dist': dist, 'n': n, 'T': T, 'stat': summary(stat), 'kappa': summary(kap)}
                if deltas:
                    row['lw_shrinkage'] = summary(deltas)
                for f in ('bf16', 'fp16'):
                    x, ok, _ = solve_b(As, np.ones((SEEDS, n)), Arith(f))
                    num = np.where(ok, rel(weights(x), w64s), np.nan)
                    row[f] = {'num': summary(num), 'C': summary(num / np.array(stat) / (U[f] * math.sqrt(T))),
                              'breakdowns': int((~ok).sum())}
                out.append(row)
                print(f"Erobust {est:6s} {dist:8s} T={T:4d} stat={row['stat']['median']:.3f} "
                      f"C_fp16={row['fp16']['C']['median']:.2f} [{row['fp16']['C']['q1']:.2f},{row['fp16']['C']['q3']:.2f}] "
                      f"kappa={row['kappa']['median']:.0f}", flush=True)
    return out


# ---------------------------------------------------------------------------------------------------------------
# E-rolling  Daily re-estimation on a rolling window: turnover and its numerical component   (B2)
# ---------------------------------------------------------------------------------------------------------------
def e_rolling():
    out = []
    for n, T, days in ((50, 250, 250), (50, 1000, 250), (100, 1000, 100)):
        Sigmas = [factor_model(n, np.random.default_rng([4, T, s])) for s in range(SEEDS)]
        R = np.array([draw_returns(Sigmas[s], T + days, np.random.default_rng([40, T, s])) for s in range(SEEDS)])
        W = {k: np.empty((days, SEEDS, n)) for k in ('fp64', *FORMATS)}
        for d in range(days):
            S = sample_cov(R[:, d:d + T, :])
            W['fp64'][d] = weights(np.linalg.solve(S, np.ones((SEEDS, n, 1)))[..., 0])
            for f in FORMATS:
                x, ok, _ = solve_b(S, np.ones((SEEDS, n)), Arith(f))
                W[f][d] = np.where(ok[:, None], weights(x), np.nan)
        one_way = lambda a: 0.5 * np.abs(np.diff(a, axis=0)).sum(axis=-1)   # (days-1, seeds)
        true_turn = one_way(W['fp64']).mean(axis=0)                           # per seed, average daily
        row = {'n': n, 'T': T, 'days': days, 'true_turnover': summary(true_turn)}
        for f in FORMATS:
            turn = one_way(W[f]).mean(axis=0)
            num = one_way(W[f] - W['fp64']).mean(axis=0)                        # numerical part of daily change
            level = (0.5 * np.abs(W[f] - W['fp64']).sum(axis=-1)).mean(axis=0)  # distance from binary64 weights
            row[f] = {'turnover': summary(turn), 'numerical_turnover': summary(num),
                      'numerical_share_of_true': summary(num / true_turn),
                      'excess_turnover_rel': summary((turn - true_turn) / true_turn),
                      'level_distance': summary(level)}
        out.append(row)
        print(f"Erolling n={n} T={T}: true turnover {row['true_turnover']['median']:.4f}; numerical/true: " + ", ".join(
            f"{f} {row[f]['numerical_share_of_true']['median']:.3g}" for f in FORMATS), flush=True)
    return out


# ---------------------------------------------------------------------------------------------------------------
# E-range  Exponent range: raw daily variances vs rescaled problems   (B6)
# ---------------------------------------------------------------------------------------------------------------
def e_range():
    out = []
    n, T = 50, 1000
    for universe, vs in (('typical daily', 1.0), ('low-volatility daily', 0.1)):
        Ss, w64s, diag = [], [], []
        for s in range(SEEDS):
            rng = np.random.default_rng([5, s])
            Sigma = factor_model(n, rng, vol_scale=vs)
            S = sample_cov(draw_returns(Sigma, T, rng))
            Ss.append(S)
            w64s.append(weights(np.linalg.solve(S, np.ones(n))))
            diag.append(np.diag(S))
        Ss, w64s, diag = np.array(Ss), np.array(w64s), np.array(diag)
        x_raw = np.linalg.solve(Ss, np.ones((SEEDS, n, 1)))[..., 0]
        row = {'universe': universe, 'variance_range': [float(diag.min()), float(diag.max())],
               'offdiag_abs_median': float(np.median(np.abs(Ss[:, ~np.eye(n, dtype=bool)]))),
               'solution_abs_max': float(np.abs(x_raw).max())}
        for f in ('fp16', 'bf16'):
            for scaling in ('raw', 'basis points', 'correlation'):
                for full in (False, True):
                    r = Arith(f, exponent_range=full)
                    if scaling == 'raw':
                        x, ok, _ = solve_b(Ss, np.ones((SEEDS, n)), r)
                        w = weights(x)
                    elif scaling == 'basis points':
                        x, ok, _ = solve_b(Ss * 1e8, np.ones((SEEDS, n)), r)  # returns in bp: covariance x 1e8
                        w = weights(x)
                    else:
                        dsq = np.sqrt(diag)                                      # scaling done in binary64 (O(n))
                        Rm = Ss / dsq[:, :, None] / dsq[:, None, :]
                        y, ok, _ = solve_b(Rm, 1.0 / dsq, r)                     # Sigma = D^1/2 C D^1/2: C y = D^-1/2 1
                        w = weights(y / dsq)                                     # x = D^{-1/2} y
                    err = rel(w, w64s)
                    finite = np.isfinite(err) & ok
                    row[f'{f}|{scaling}|{"full format" if full else "significand only"}'] = {
                        'failed_or_nonfinite': int((~finite).sum()), 'num': summary(err[finite]) if finite.any() else None}
        out.append(row)
        print(f"Erange {universe}: variances {row['variance_range'][0]:.1e}..{row['variance_range'][1]:.1e}; " + "; ".join(
            f"{k}: fail={v['failed_or_nonfinite']}" for k, v in row.items() if isinstance(v, dict) and k.startswith('fp16')), flush=True)
    return out


# ---------------------------------------------------------------------------------------------------------------
# E-IR  Low-precision Cholesky as a preconditioner, binary64 residuals (deterministic, six matrices)
# ---------------------------------------------------------------------------------------------------------------
def e_refinement():
    out = []
    n, T = 100, 1000
    for strength in (1.0, 4.0, 12.0):
        for idio_lo in (0.10, 0.02):
            rng = np.random.default_rng(int(strength * 100 + idio_lo * 1000))
            Sigma = factor_model(n, rng, idio=(idio_lo, 0.30), market=strength)
            S = sample_cov(draw_returns(Sigma, T, rng))
            b = np.ones(n)
            x64 = np.linalg.solve(S, b)
            row = {'kappa': float(np.linalg.cond(S))}
            for f in FORMATS:
                r = Arith(f)
                L, ok = cholesky_b(S[None], r)
                if not ok[0]:
                    row[f] = {'kappa_u': row['kappa'] * U[f], 'errors': None}
                    continue
                x = backward_b(L, forward_b(L, r(b)[None], r), r)[0]
                errs = [float(np.linalg.norm(x - x64) / np.linalg.norm(x64))]
                for _ in range(12):
                    res = b - S @ x
                    sc = np.max(np.abs(res))
                    if sc > 0:
                        x = x + backward_b(L, forward_b(L, r(res / sc)[None], r), r)[0] * sc
                    errs.append(float(np.linalg.norm(x - x64) / np.linalg.norm(x64)))
                row[f] = {'kappa_u': row['kappa'] * U[f], 'errors': errs}
            out.append(row)
            print(f"EIR kappa={row['kappa']:.2e} " + " ".join(
                f"{f}:" + ("FAIL" if row[f]['errors'] is None else f"{row[f]['errors'][-1]:.1e}") for f in FORMATS), flush=True)
    return out


# ---------------------------------------------------------------------------------------------------------------
# E-sum  Long accumulations in an 11-bit significand: RN, SR, Kahan, pairwise; 100 runs   (B7)
# ---------------------------------------------------------------------------------------------------------------
def e_summation(runs=100):
    t = 11
    out = []
    for N in (2 ** 10, 2 ** 12, 2 ** 14, 2 ** 16, 2 ** 18):
        rng = np.random.default_rng([6, N])
        X = rnd_t(rng.uniform(0.5e-3, 1.5e-3, size=(runs, N)), t)      # representable positive increments
        exact = np.array([math.fsum(row) for row in X])
        g = np.random.default_rng([60, N])
        s_rn = np.zeros(runs); s_sr = np.zeros(runs); s_k = np.zeros(runs); c_k = np.zeros(runs)
        for i in range(N):
            x = X[:, i]
            s_rn = rnd_t(s_rn + x, t)
            s_sr = rnd_sr(s_sr + x, t, g)
            # Kahan compensated summation, every operation rounded to t bits
            y = rnd_t(x - c_k, t)
            tt = rnd_t(s_k + y, t)
            c_k = rnd_t(rnd_t(tt - s_k, t) - y, t)
            s_k = tt
        P = X.copy()                                                      # pairwise (binary tree), rounded
        while P.shape[1] > 1:
            P = rnd_t(P[:, 0::2] + P[:, 1::2], t)
        res = {'N': N, 'runs': runs}
        for name, v in (('round_to_nearest', s_rn), ('stochastic', s_sr), ('kahan', s_k), ('pairwise', P[:, 0])):
            e = np.abs(v - exact) / exact
            res[name] = summary(e)
            res[name]['rms'] = float(np.sqrt(np.mean(((v - exact) / exact) ** 2)))
        out.append(res)
        print(f"Esum N={N:6d} RN={res['round_to_nearest']['median']:.2e} SR={res['stochastic']['median']:.2e} "
              f"(rms {res['stochastic']['rms']:.2e}) Kahan={res['kahan']['median']:.2e} pairwise={res['pairwise']['median']:.2e}", flush=True)
    return out


# ---------------------------------------------------------------------------------------------------------------
# E-speed  binary32 vs binary64 dense linear algebra on this machine   (B8)
# ---------------------------------------------------------------------------------------------------------------
def e_speed():
    import platform
    out = {'machine': platform.machine(), 'processor': platform.processor(), 'numpy': np.__version__, 'rows': []}
    try:
        import subprocess
        out['cpu'] = subprocess.run(['sysctl', '-n', 'machdep.cpu.brand_string'], capture_output=True, text=True).stdout.strip()
    except Exception:
        out['cpu'] = None
    rng = np.random.default_rng(7)
    for n in (100, 250, 500, 1000, 2000, 4000):
        G = rng.standard_normal((n, 2 * n))
        A64 = G @ G.T / (2 * n) + np.eye(n)
        b64 = np.ones(n)
        row = {'n': n}
        for name, dt in (('fp64', np.float64), ('fp32', np.float32)):
            A = A64.astype(dt); b = b64.astype(dt)
            for op, fn in (('cholesky', lambda: np.linalg.cholesky(A)), ('solve', lambda: np.linalg.solve(A, b)),
                           ('matmul', lambda: A @ A)):
                fn()
                reps = max(3, int(2e8 / n ** 3))
                ts = []
                for _ in range(5):
                    t0 = time.perf_counter()
                    for _ in range(reps):
                        fn()
                    ts.append((time.perf_counter() - t0) / reps)
                row[f'{op}_{name}_s'] = float(np.median(ts))
        for op in ('cholesky', 'solve', 'matmul'):
            row[f'{op}_speedup_fp32'] = row[f'{op}_fp64_s'] / row[f'{op}_fp32_s']
        out['rows'].append(row)
        print(f"Espeed n={n:5d} speed-up fp32/fp64: cholesky {row['cholesky_speedup_fp32']:.2f}x "
              f"solve {row['solve_speedup_fp32']:.2f}x matmul {row['matmul_speedup_fp32']:.2f}x", flush=True)
    return out


if __name__ == '__main__':
    t0 = time.time()
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'results.json')
    results = {'numpy': np.__version__, 'seeds': SEEDS}
    steps = [('e1_main', e1_main), ('e_align', e_align), ('e_robust', e_robust), ('e_rolling', e_rolling),
             ('e_range', e_range), ('e_refinement', e_refinement), ('e_summation', e_summation)]
    if 'speed' in sys.argv:
        steps.append(('e_speed', e_speed))
    only = [a for a in sys.argv[1:] if a.startswith('e')]
    if only and os.path.exists(path):
        results = json.load(open(path))
        steps = [s for s in steps if s[0] in only]
    for name, fn in steps:
        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)
    print(f"done in {time.time() - t0:.0f}s -> {path}")
