#!/usr/bin/env python3 """Fourth Liouvillian moments from the archived fixed-radius charge samples. No new disorder draws are made. Each bootstrap unit retains all charges and couplings of one archived direction. The coefficient formulas are conditional on every normalized quadratic direction. Run with --bootstrap 2000. """ import os for key in ('OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'OMP_NUM_THREADS'): os.environ[key] = '1' import argparse import csv import json import math import time from pathlib import Path import numpy as np from scipy.linalg import eigh from charge_dynamics import basis_for, charge_signs, exact_gamma2 ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / 'results' def exact_coefficients(N): d = math.comb(N, 4) M = 2 * math.comb(N-2, 3) K = 4 * math.comb(N-4, 3) + 4*(N-4) alpha = 16 * (1.5*M*M + M*K) / (d*(d+2)) beta = 512*(N-4)*(2*N-9)/(N*N*(N-1)*(N-3)) return alpha, beta def run_size(N): saved = np.load(OUT/f'charge_samples_N{N}.npz') b = basis_for(N) q = charge_signs(b) n, d4 = saved['u4'].shape coefficients = np.empty((n, 3)) g2 = np.empty(n) spectral_check = 0. start = time.perf_counter() for j in range(n): A = b.assemble(4, saved['u4'][j]*np.sqrt(d4)) B = saved['lambda'][j] @ q sums = np.zeros(4) for qa in q: C = A*(qa[None, :]-qa[:, None]) X = A@C-C@A Y = (B[:, None]-B[None, :])*C sums += [np.vdot(X, X).real/b.d, np.vdot(Y, Y).real/b.d, np.vdot(X, Y).real/b.d, np.vdot(C, C).real/b.d] coefficients[j] = sums[:3]/len(q) g2[j] = sums[3]/len(q) # Independently recover the fourth moment in an energy basis once. if j == 0 and N in (10, 14): kappa = 4. H = (A+kappa*np.diag(B))/np.sqrt(1+kappa*kappa) E, V = eigh(H, check_finite=False) gap4 = (E[:, None]-E[None, :])**4 spec = 0. for qa in q: Qe = (V.conj().T*qa[None, :])@V spec += np.sum(abs(Qe)**2*gap4)/(b.d*len(q)) direct = (coefficients[j, 0]+2*kappa*coefficients[j, 2] +kappa*kappa*coefficients[j, 1])/(1+kappa*kappa)**2 spectral_check = abs(spec/direct-1) if (j+1) % 16 == 0: print(f'N={N}: {j+1}/{n}, {time.perf_counter()-start:.1f} s', flush=True) check2 = float(np.max(abs(g2/saved['gamma0_by_charge'].mean(axis=1)-1))) np.savez_compressed(OUT/f'frequency_moments_N{N}.npz', N=N, sample_indices=saved['sample_indices'], coefficients=coefficients, gamma2_kappa0=g2, coefficient_names=np.array(['alpha', 'beta', 'cross']), gamma2_reconstruction_relative_error=check2, spectral_fourth_relative_error=spectral_check) return {'N': N, 'samples': n, 'seconds': time.perf_counter()-start, 'gamma2_relative_error': check2, 'spectral_fourth_relative_error': spectral_check} def analyze(nboot): rng = np.random.default_rng(2026111893) rows = [] inelastic = [] for N in (10, 14, 18, 22): f = np.load(OUT/f'frequency_moments_N{N}.npz') old = np.load(OUT/f'charge_samples_N{N}.npz') c = f['coefficients'] indices = rng.integers(len(c), size=(nboot, len(c))) boot = c[indices].mean(axis=1) for col, (name, theory) in enumerate(zip(('alpha', 'beta'), exact_coefficients(N))): ci = np.quantile(boot[:, col]/theory, [.025, .975]) rows.append(dict(N=N, coefficient=name, samples=len(c), exact=theory, estimate=float(c[:, col].mean()), estimate_over_exact=float(c[:, col].mean()/theory), ratio_ci_low=float(ci[0]), ratio_ci_high=float(ci[1]))) for ki, k in enumerate(old['kappas']): fourth = (c[:, 0]+2*k*c[:, 2]+k*k*c[:, 1])/(1+k*k)**2 second = f['gamma2_kappa0']/(1+k*k) deficit = 1-old['pdiag'][:, ki].mean(axis=1) kurt = fourth.mean()*deficit.mean()/second.mean()**2 kb = fourth[indices].mean(axis=1)*deficit[indices].mean(axis=1)/second[indices].mean(axis=1)**2 lo, hi = np.quantile(kb, [.025, .975]) inelastic.append(dict(N=N, kappa=float(k), fourth_moment=float(fourth.mean()), theoretical_fourth=(exact_coefficients(N)[0]+k*k*exact_coefficients(N)[1])/(1+k*k)**2, inelastic_kurtosis=float(kurt), ci_low=float(lo), ci_high=float(hi), cross_coefficient_mean=float(c[:, 2].mean()), cross_coefficient_max_abs=float(abs(c[:, 2]).max()))) for name, data in [('frequency_coefficient_validation.csv', rows), ('frequency_inelastic_kurtosis.csv', inelastic)]: with (OUT/name).open('w', newline='') as stream: w = csv.DictWriter(stream, fieldnames=list(data[0])) w.writeheader(); w.writerows(data) lines = [r'\begin{table}[tbp]', r'\centering\small', r'\caption{Validation of the fourth Liouvillian moment. Each entry is the sample coefficient divided by its exact angular expectation; brackets give 95\% bootstrap intervals over complete disorder samples.}', r'\label{tab:frequency-validation}', r'\begin{tabular}{rrrr}\toprule', r'$N$ & Samples & $\widehat\alpha_N/\alpha_N$ & $\widehat\beta_N/\beta_N$ \\ \midrule'] for N in (10, 14, 18, 22): pair = [r for r in rows if r['N'] == N] cells = [f"{r['estimate_over_exact']:.4f} [{r['ratio_ci_low']:.4f},{r['ratio_ci_high']:.4f}]" for r in pair] lines.append(f"{N} & {pair[0]['samples']} & {cells[0]} & {cells[1]} \\") lines += [r'\bottomrule\end{tabular}', r'\end{table}'] # Literal TeX row terminators require two backslashes. lines = [s+'\\' if s.endswith('\\') and not s.endswith('\\\\') else s for s in lines] (OUT/'frequency_validation_table.tex').write_text('\n'.join(lines)+'\n') print(json.dumps({'coefficient_validation': rows, 'inelastic_kurtosis': inelastic}, indent=2), flush=True) def main(): ap = argparse.ArgumentParser() ap.add_argument('--stage', choices=['all', 'analyze'], default='all') ap.add_argument('--bootstrap', type=int, default=2000) args = ap.parse_args() if args.stage == 'all': checks = [run_size(N) for N in (10, 14, 18, 22)] (OUT/'frequency_moment_checks.json').write_text(json.dumps(checks, indent=2)+'\n') analyze(args.bootstrap) if __name__ == '__main__': main()