#!/usr/bin/env python3 """Test the exact directional cubic-trace variance from saved iid spectra. No matrices are rediagonalized. The known ensemble mean of tr(H**3) is zero, so the sample second moment is an unbiased estimate of its variance. Bootstrap resampling preserves all couplings and the two radius ensembles. """ import os for _name in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"): os.environ[_name] = "1" from pathlib import Path from math import comb import csv import json import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from plot_style import configure BASE = Path(__file__).resolve().parents[1] RESULTS = BASE / "results" FIGURES = RESULTS / "figures" def coefficients(N): d4, d2 = comb(N, 4), comb(N, 2) a = 540 * comb(N, 6) / (d4 * (d4 + 2) * (d4 + 4)) b = 12 / (d2 * (d2 + 2)) return a, b def predictions(N, kappa): if np.isinf(kappa): return 0., 0. d4, d2 = comb(N, 4), comb(N, 2) a, b = coefficients(N) fixed = (a + 9 * kappa ** 4 * b) / (1 + kappa ** 2) ** 3 gaussian = (540 * comb(N, 6) / d4 ** 3 + 108 * kappa ** 4 / d2 ** 2) / (1 + kappa ** 2) ** 3 return gaussian, fixed def main(): configure() rows = [] metadata = {"bootstrap_replicates": 1000, "seed": 2026111807, "target": "E[(tr_D H^3)^2], whose ensemble mean trace is exactly zero", "confidence": "pointwise 95% whole-draw percentile intervals"} fig, axes = plt.subplots(1, 2, figsize=(9.0, 3.4), sharey=False) for ax, N in zip(axes, (14, 18)): with np.load(RESULTS / f"syk_samples_N{N}.npz") as data: eigenvalues = data["eigenvalues"] kappas = data["kappas"] m3 = np.mean(eigenvalues ** 3, axis=-1) squared = m3 ** 2 ns = squared.shape[1] rng = np.random.default_rng(metadata["seed"] + N) weights = rng.multinomial(ns, np.full(ns, 1 / ns), size=1000) boots = np.einsum("bs,esk->bek", weights / ns, squared) lo, hi = np.quantile(boots, (.025, .975), axis=0) estimates = squared.mean(axis=1) for e, name in enumerate(("gaussian", "fixed_radii")): for j, k in enumerate(kappas): exact = predictions(N, k)[e] rows.append({"N": N, "ensemble": name, "kappa": float(k), "samples": ns, "estimate": estimates[e,j], "ci_low": lo[e,j], "ci_high": hi[e,j], "exact_variance_m3": exact, "estimated_C6_coefficient": estimates[e,j]/36, "exact_C6_coefficient": exact/36, "sample_mean_m3": m3[e,:,j].mean()}) np.savez_compressed(RESULTS / f"directional_moments_N{N}.npz", N=N, kappas=kappas, m3=m3, bootstrap_weights=weights, bootstrap_m3_second_moment=boots) finite = np.isfinite(kappas) for e, name, color, offset in [(0,"Gaussian radii","#bd5936",-.06), (1,"Fixed radii","#236b8e",.06)]: idx = np.flatnonzero(finite) exact = np.array([predictions(N,k)[e] for k in kappas[finite]]) ratio = estimates[e,finite] / exact err = np.vstack((ratio-lo[e,finite]/exact,hi[e,finite]/exact-ratio)) ax.errorbar(np.arange(len(idx))+offset,ratio,yerr=err,fmt="o",ms=4, color=color,capsize=2,label=name) ax.axhline(1, color="0.3",lw=.8,ls="--") ax.set_xticks(np.arange(finite.sum()), [f"{k:g}" for k in kappas[finite]]) ax.set_xlabel(r"$\kappa$") ax.set_title(f"N = {N}; {ns:,} paired samples") ax.set_ylabel("Cubic variance / exact prediction") ax.grid(axis="y",alpha=.2) axes[0].legend(frameon=False,fontsize=8) fig.tight_layout() FIGURES.mkdir(exist_ok=True) fig.savefig(FIGURES / "directional_moments.pdf",bbox_inches="tight") fig.savefig(FIGURES / "directional_moments.png",dpi=180,bbox_inches="tight") with (RESULTS / "directional_moments_summary.csv").open("w",newline="") as f: w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows) (RESULTS / "directional_moments_config.json").write_text(json.dumps(metadata,indent=2)) for row in rows: if row["ensemble"] == "fixed_radii" and row["kappa"] in (0.,4.): print(row) if __name__ == "__main__": main()