#!/usr/bin/env python3 """Quadratic normal-mode charge memory in the fixed-radius SYK ensemble. The physical calculation uses one parity block and even charges Q_a=2n_a-1. An SO(N) normal form for the quadratic coupling is chosen first. Conditional orthogonal invariance of the independent quartic direction permits its direct sampling in this basis, without a many-body change-of-basis calculation. Usage: python charge_dynamics.py --stage pilot python charge_dynamics.py --stage main --sizes 10,14,18,22 --samples 256,256,128,32 python charge_dynamics.py --stage analyze --bootstrap 2000 python charge_dynamics.py --stage plot The main time variable is x=t/tau_Nk, where tau_Nk is the deterministic inverse root of the exact mean squared commutator. Every sample at fixed (N,kappa) therefore uses the same physical times. Bootstrap units are disorder samples, with all normal-mode charges averaged inside a sample. """ import os for _key in ("OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "OMP_NUM_THREADS", "VECLIB_MAXIMUM_THREADS", "NUMEXPR_NUM_THREADS"): os.environ[_key] = "1" import argparse import csv import itertools import json import math import sys import time from pathlib import Path import numpy as np import scipy from scipy.linalg import eigh, schur # This module is shipped beside the original, independently validated basis. from run_experiments import SYKBasis ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "results" FIG = OUT / "figures" SEED = 2026111879 KAPPAS = np.array([0., 4., 16., 64.]) EPSILONS = np.array([.1, .5]) XGRID = np.unique(np.r_[0., np.geomspace(1e-5, .1, 31), np.linspace(.1, 5., 100), np.geomspace(5., 128., 50)]) _BASES = {} def save_json(path, obj): path.write_text(json.dumps(obj, indent=2, allow_nan=False) + "\n") def save_csv(path, rows): if not rows: return with path.open("w", newline="") as stream: writer = csv.DictWriter(stream, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) def basis_for(N): if N not in _BASES: _BASES[N] = SYKBasis(N, parity=1) return _BASES[N] def exact_gamma2(N, kappa): return 32. * (N-4) / (N*(N-1)*(1+kappa*kappa)) def charge_signs(basis): return np.array([2*((basis.states >> a) & 1)-1 for a in range(basis.N//2)], dtype=float) def draw_canonical(N, sample_index, basis): """Draw the exact fixed-radius law in an oriented quadratic normal frame.""" rng = np.random.default_rng(np.random.SeedSequence([SEED, N, sample_index])) g2 = rng.standard_normal(math.comb(N, 2)) K = np.zeros((N, N)) upper = np.triu_indices(N, 1) K[upper] = g2 K[(upper[1], upper[0])] = -g2 T, O = schur(K, output="real", check_finite=False) # A reflection exchanges many-body parity. Correct it explicitly. if np.linalg.det(O) < 0: O[:, 0] *= -1 T[0, :] *= -1 T[:, 0] *= -1 lam = T[np.arange(0, N, 2), np.arange(1, N, 2)].copy() canonical = np.zeros_like(K) canonical[np.arange(0, N, 2), np.arange(1, N, 2)] = lam canonical[np.arange(1, N, 2), np.arange(0, N, 2)] = -lam schur_error = np.max(abs(K-O@canonical@O.T)) lam /= np.linalg.norm(lam) u = rng.standard_normal(math.comb(N, 4)) u /= np.linalg.norm(u) A = basis.assemble(4, u*np.sqrt(len(u))) q = charge_signs(basis) Bdiag = lam @ q return A, Bdiag, lam, u, q, float(schur_error) def one_sample(N, sample_index, basis=None, keep_directions=True): start = time.perf_counter() if basis is None: basis = basis_for(N) D, m = basis.d, N//2 A, Bdiag, lam, u, q, schur_error = draw_canonical(N, sample_index, basis) absA2 = abs(A)**2 gamma0_by_charge = np.array([ np.sum(absA2*(qa[:, None]-qa[None, :])**2)/D for qa in q]) curves = np.empty((len(KAPPAS), len(XGRID))) pdiag = np.empty((len(KAPPAS), m)) penergy = np.empty_like(pdiag) gamma_spec = np.empty_like(pdiag) spectra = np.empty((len(KAPPAS), D)) sample_tau = np.empty(len(KAPPAS)) tau = np.array([1/np.sqrt(exact_gamma2(N, k)) for k in KAPPAS]) timings = {"assembly": time.perf_counter()-start, "eigh": 0., "charge_weights": 0., "memory": 0.} checks = { "SO_normal_form_error": schur_error, "charge_trace_error": float(np.max(abs(q.mean(axis=1)))), "charge_square_error": float(np.max(abs(q*q-1))), "charge_orthogonality_error": float(np.max(abs(q@q.T/D-np.eye(m)))), "quartic_norm_error": float(abs(np.sum(absA2)/D-1)), "quadratic_norm_error": float(abs(np.mean(Bdiag**2)-1)), "quartic_trace_error": float(abs(np.trace(A)/D)), "quadratic_trace_error": float(abs(np.mean(Bdiag))), "grade_orthogonality_error": float(abs(np.dot(np.diag(A), Bdiag)/D)), "charge_bilinear_representation_error": 0., "curvature_spectral_relative_error": 0., "memory_bound_violation": 0., "memory_zero_error": 0., "energy_overlap_error": 0., "plateau_projection_violation": 0., "small_time_curvature_relative_error": 0., "min_eigenvalue_gap": 1e100, "near_degenerate_pairs": 0, } # Verify the even Clifford implementation independently once per size. if sample_index == 0: pairs = list(itertools.combinations(range(N), 2)) for a in range(m): v = np.zeros(len(pairs)) v[pairs.index((2*a, 2*a+1))] = np.sqrt(len(pairs)) Qa = basis.assemble(2, v) checks["charge_bilinear_representation_error"] = max( checks["charge_bilinear_representation_error"], float(np.max(abs(Qa-np.diag(q[a]))))) for ki, kappa in enumerate(KAPPAS): H = A / np.sqrt(1+kappa*kappa) H = H.copy() H[np.diag_indices(D)] += kappa*Bdiag/np.sqrt(1+kappa*kappa) before = time.perf_counter() E, V = eigh(H, check_finite=False, driver="evr", overwrite_a=True) timings["eigh"] += time.perf_counter()-before spectra[ki] = E gap = np.diff(E) checks["min_eigenvalue_gap"] = min(checks["min_eigenvalue_gap"], float(gap.min())) tol = 64*np.finfo(float).eps*max(1., np.max(abs(E))) labels = np.r_[0, np.cumsum(np.diff(E) > tol)] zero_gap = labels[:, None] == labels[None, :] checks["near_degenerate_pairs"] += int((zero_gap.sum()-D)//2) gap2 = (E[:, None]-E[None, :])**2 before = time.perf_counter() VH = V.conj().T W = np.zeros((D, D)) for a in range(m): Qe = (VH*q[a][None, :]) @ V Wa = (Qe.real**2+Qe.imag**2)/D W += Wa/m pdiag[ki, a] = np.sum(Wa[zero_gap]) penergy[ki, a] = (kappa*lam[a]/np.sqrt(1+kappa*kappa))**2 measured_overlap = np.dot(E, np.diag(Qe).real)/D checks["energy_overlap_error"] = max( checks["energy_overlap_error"], float(abs(measured_overlap-kappa*lam[a]/np.sqrt(1+kappa*kappa)))) gamma_spec[ki, a] = np.sum(Wa*gap2) timings["charge_weights"] += time.perf_counter()-before gamma_target = gamma0_by_charge/(1+kappa*kappa) sample_tau[ki] = 1/np.sqrt(gamma_target.mean()) checks["curvature_spectral_relative_error"] = max( checks["curvature_spectral_relative_error"], float(np.max(abs(gamma_spec[ki]/gamma_target-1)))) checks["plateau_projection_violation"] = max( checks["plateau_projection_violation"], float(np.max(penergy[ki]-pdiag[ki]))) before = time.perf_counter() physical_times = XGRID*tau[ki] phase = np.exp(-1j*E[:, None]*physical_times[None, :]) curves[ki] = np.einsum("it,it->t", phase.conj(), W@phase).real timings["memory"] += time.perf_counter()-before checks["memory_zero_error"] = max(checks["memory_zero_error"], float(abs(curves[ki, 0]-1))) lower = 1-.5*gamma_target.mean()*physical_times**2 checks["memory_bound_violation"] = max( checks["memory_bound_violation"], float(np.max(lower-curves[ki]))) # A stable finite-difference check supplements the exact spectral moment. ix = int(np.argmin(abs(XGRID-.001))) # For large kappa the fixed x corresponds to too long a physical time; # pick the largest grid point whose phase bandwidth remains below .02. safe = np.where((physical_times > 0) & (physical_times*(E[-1]-E[0]) < .02))[0] if len(safe): ix = int(safe[-1]) fd = 2*(curves[ki, 0]-curves[ki, ix])/physical_times[ix]**2 checks["small_time_curvature_relative_error"] = max( checks["small_time_curvature_relative_error"], float(abs(fd/gamma_target.mean()-1))) if checks["memory_bound_violation"] > 2e-9: raise AssertionError(("samplewise charge-memory bound", N, sample_index, checks)) if checks["curvature_spectral_relative_error"] > 2e-8: raise AssertionError(("commutator curvature", N, sample_index, checks)) if checks["near_degenerate_pairs"]: # Projector-group formula is already used above; mark any such samples. print(f"Detected unresolved energy pairs: N={N}, sample={sample_index}", flush=True) timings["total"] = time.perf_counter()-start return {"C": curves, "pdiag": pdiag, "penergy": penergy, "gamma2": gamma_spec, "gamma0_by_charge": gamma0_by_charge, "sample_tau": sample_tau, "tau": tau, "eigenvalues": spectra, "lambda": lam, "u4": u if keep_directions else np.zeros(0), "checks": checks, "timings": timings} def pilot(): OUT.mkdir(parents=True, exist_ok=True) reports = [] for N in (10, 14, 18, 22): begin = time.perf_counter() basis = basis_for(N) init = time.perf_counter()-begin result = one_sample(N, 0, basis) record = {"N": N, "D": basis.d, "basis_seconds": init, "timings": result["timings"], "checks": result["checks"], "plateaus": result["pdiag"].mean(axis=1).tolist(), "C_at_horizon": result["C"][:, -1].tolist()} reports.append(record) print(json.dumps(record), flush=True) save_json(OUT/"charge_pilot.json", reports) return reports def run(sizes, sample_counts): OUT.mkdir(parents=True, exist_ok=True) config = { "seed": SEED, "seed_rule": "SeedSequence([seed, N, sample_index])", "sizes": sizes, "sample_counts": sample_counts, "kappas": KAPPAS.tolist(), "parity": 1, "time_variable": "x=t/tau_Nk; deterministic tau_Nk=1/sqrt(32*(N-4)/(N*(N-1)*(1+kappa**2)))", "x_grid": XGRID.tolist(), "all_charges_averaged_before_disorder": True, "normal_form": "real Schur with det(O)=+1; signed lambda preserves the selected parity", "quartic_sampling": "independent uniform sphere in the oriented quadratic frame; exactly the conditional law by O(N) invariance", "elastic_component": "sum of spectral-projector blocks; no unresolved degeneracies expected in these parity blocks", "endpoint": "kappa=infinity is exactly B: every charge is conserved, C=1 and pdiag=1", "blas_threads": 1, "worker_processes": 1, "numpy": np.__version__, "scipy": scipy.__version__, "old_disorder_samples_reused": False, } save_json(OUT/"charge_config.json", config) total_begin = time.perf_counter() timings = [] for N, ns in zip(sizes, sample_counts): path = OUT/f"charge_samples_N{N}.npz" if path.exists(): old = np.load(path) if len(old["sample_indices"]) == ns: print(f"Reusing {path.name}", flush=True) continue raise RuntimeError(f"{path.name} already contains a different number of samples") begin = time.perf_counter() basis = basis_for(N) results = [] for sid in range(ns): results.append(one_sample(N, sid, basis)) if (sid+1) % max(1, ns//8) == 0: print(f"N={N}: {sid+1}/{ns} samples; elapsed {time.perf_counter()-begin:.1f} s", flush=True) arrays = {} for key in ("C", "pdiag", "penergy", "gamma2", "gamma0_by_charge", "sample_tau", "eigenvalues", "lambda", "u4"): arrays[key] = np.array([r[key] for r in results]) check_names = list(results[0]["checks"]) check_values = np.array([[r["checks"][key] for key in check_names] for r in results]) np.savez_compressed(path, N=N, D=basis.d, kappas=KAPPAS, x=XGRID, tau=results[0]["tau"], physical_times=results[0]["tau"][:, None]*XGRID, sample_indices=np.arange(ns), seed=SEED, check_names=np.array(check_names), check_values=check_values, **arrays) worst = {} for j, key in enumerate(check_names): worst[key] = float(np.min(check_values[:, j]) if key == "min_eigenvalue_gap" else np.max(check_values[:, j])) record = {"N": N, "samples": ns, "seconds": time.perf_counter()-begin, "checks": worst, "mean_gamma0": float(arrays["gamma0_by_charge"].mean()), "exact_mean_gamma0": exact_gamma2(N, 0.)} timings.append(record) print(json.dumps(record), flush=True) save_json(OUT/"charge_timing.json", {"wall_seconds": time.perf_counter()-total_begin, "runs": timings}) del results, arrays return timings def crossing(x, curve, epsilon): """First observed grid crossing, linearly interpolated; NaN means censored.""" hit = np.flatnonzero(curve <= 1-epsilon) if not len(hit): return np.nan j = int(hit[0]) if j == 0: return float(x[0]) y0, y1 = curve[j-1], curve[j] if y0 == y1: return float(x[j]) return float(x[j-1]+(x[j]-x[j-1])*(y0-(1-epsilon))/(y0-y1)) def analyze(nboot=2000): OUT.mkdir(parents=True, exist_ok=True) summary, crossings, curve_rows, validation = [], [], [], [] mode_names = ("raw", "energy_removed", "dephased") for path in sorted(OUT.glob("charge_samples_N*.npz")): data = np.load(path) N, D = int(data["N"]), int(data["D"]) C, ns = data["C"], len(data["sample_indices"]) p = data["pdiag"].mean(axis=2) gamma = data["gamma2"].mean(axis=2) x, tau = data["x"], data["tau"] pE = KAPPAS**2/((N/2)*(1+KAPPAS**2)) cmean, pmean = C.mean(axis=0), p.mean(axis=0) cE = (cmean-pE[:, None])/(1-pE[:, None]) cD = (cmean-pmean[:, None])/(1-pmean[:, None]) rng = np.random.default_rng(np.random.SeedSequence([SEED, 4242, N])) counts = rng.multinomial(ns, np.full(ns, 1/ns), size=nboot) weights = counts/ns cb = (weights@C.reshape(ns, -1)).reshape(nboot, len(KAPPAS), len(x)) pb = weights@p gb = weights@gamma eb = (cb-pE[None, :, None])/(1-pE[None, :, None]) db = (cb-pb[:, :, None])/(1-pb[:, :, None]) modes = np.stack([cmean, cE, cD]) b_modes = (cb, eb, db) intervals = np.array([np.quantile(v, [.025, .975], axis=0) for v in b_modes]) pci = np.quantile(pb, [.025, .975], axis=0) gci = np.quantile(gb, [.025, .975], axis=0) bt_cross = np.full((nboot, len(KAPPAS), 3, len(EPSILONS)), np.nan) for ki, k in enumerate(KAPPAS): p_excess = (pmean[ki]-pE[ki])/(1-pE[ki]) ex_boot = (pb[:, ki]-pE[ki])/(1-pE[ki]) exci = np.quantile(ex_boot, [.025, .975]) summary.append({ "N": N, "D": D, "samples": ns, "kappa": float(k), "tau_analytic": float(tau[ki]), "mean_commutator_squared": float(gamma[:, ki].mean()), "commutator_ci_low": float(gci[0, ki]), "commutator_ci_high": float(gci[1, ki]), "exact_mean_commutator_squared": exact_gamma2(N, k), "energy_projection": float(pE[ki]), "plateau": float(pmean[ki]), "plateau_ci_low": float(pci[0, ki]), "plateau_ci_high": float(pci[1, ki]), "energy_removed_plateau": float(p_excess), "energy_removed_plateau_ci_low": float(exci[0]), "energy_removed_plateau_ci_high": float(exci[1]), "tau_inelastic": float(tau[ki]*np.sqrt(1-pmean[ki])), "tau_inelastic_ci_low": float(tau[ki]*np.sqrt(1-pci[1, ki])), "tau_inelastic_ci_high": float(tau[ki]*np.sqrt(1-pci[0, ki])), "C_at_last_time": float(cmean[ki, -1]), "last_physical_time": float(tau[ki]*x[-1]), }) for mode, name in enumerate(mode_names): for ei, epsilon in enumerate(EPSILONS): value = crossing(x, modes[mode, ki], epsilon) hits = np.flatnonzero(modes[mode, ki] <= 1-epsilon) j = int(hits[0]) if len(hits) else -1 for b in range(nboot): bt_cross[b, ki, mode, ei] = crossing(x, b_modes[mode][b, ki], epsilon) samples = bt_cross[:, ki, mode, ei] extended = np.where(np.isfinite(samples), samples, np.inf) ci = np.quantile(extended, [.025, .975], method="inverted_cdf") mass = (1., 1-pE[ki], 1-pmean[ki])[mode] boot_mass = (np.ones(nboot), np.full(nboot, 1-pE[ki]), 1-pb[:, ki])[mode] curv_extended = extended/np.sqrt(boot_mass) curv_ci = np.quantile(curv_extended, [.025, .975], method="inverted_cdf") empirical_bound_x = np.sqrt(2*epsilon*mass/gamma[:, ki].mean())/tau[ki] population_bound_x = (np.sqrt(2*epsilon*mass) if mode < 2 else np.nan) clean = lambda v: float(v) if np.isfinite(v) else "" crossings.append({ "N": N, "kappa": float(k), "mode": name, "epsilon": float(epsilon), "first_resolved_x": clean(value), "first_resolved_physical_time": clean(value*tau[ki]), "grid_bracket_low": float(x[max(j-1, 0)]) if j >= 0 else float(x[-1]), "grid_bracket_high": float(x[j]) if j >= 0 else "", "bootstrap_x_ci_low": clean(ci[0]), "bootstrap_x_ci_high": clean(ci[1]), "bootstrap_crossing_fraction": float(np.mean(np.isfinite(samples))), "first_resolved_curvature_units": clean(value/np.sqrt(mass)), "bootstrap_curvature_ci_low": clean(curv_ci[0]), "bootstrap_curvature_ci_high": clean(curv_ci[1]), "right_censored": not np.isfinite(value), "censor_x": float(x[-1]), "finite_ensemble_bound_x": float(empirical_bound_x), "population_analytic_bound_x": clean(population_bound_x), "ratio_to_finite_ensemble_bound": clean(value/empirical_bound_x), "ratio_to_population_bound": clean(value/population_bound_x), }) for ti, xx in enumerate(x): curve_rows.append({ "N": N, "kappa": float(k), "mode": name, "x": float(xx), "physical_time": float(xx*tau[ki]), "mean": float(modes[mode, ki, ti]), "ci_low": float(intervals[mode, 0, ki, ti]), "ci_high": float(intervals[mode, 1, ki, ti]), }) np.savez_compressed( OUT/f"charge_analysis_N{N}.npz", N=N, D=D, samples=ns, kappas=KAPPAS, x=x, tau=tau, means=modes, intervals=intervals, mode_names=np.array(mode_names), pdiag=pmean, pdiag_ci=pci, penergy=pE, gamma2=gamma.mean(axis=0), gamma2_ci=gci, bootstrap_counts=counts.astype(np.uint16), bootstrap_plateaus=pb, bootstrap_gamma2=gb, bootstrap_crossings=bt_cross, epsilons=EPSILONS, bootstrap_seed=np.array([SEED, 4242, N]), ) cv = data["check_values"] names = list(data["check_names"]) worst = {str(name): float(np.min(cv[:, j]) if name == "min_eigenvalue_gap" else np.max(cv[:, j])) for j, name in enumerate(names)} validation.append({"N": N, "samples": ns, "checks": worst, "kappa_infinity": {"C_for_every_time": 1., "full_dephasing_plateau": 1., "commutator_squared": 0., "energy_projection_average": 2/N, "dephased_normalization_defined": False}}) print(f"Analyzed N={N}: {ns} samples, {nboot} paired bootstrap replicates", flush=True) save_csv(OUT/"charge_summary.csv", summary) save_csv(OUT/"charge_crossings.csv", crossings) save_csv(OUT/"charge_curves.csv", curve_rows) save_json(OUT/"charge_validation.json", validation) save_json(OUT/"charge_analysis_settings.json", { "bootstrap_replicates": nboot, "bootstrap_unit": "independent disorder sample", "paired_across_kappas": True, "intervals": "pointwise percentile 95%", "dephased_curve": "(mean C - mean pdiag)/(1 - mean pdiag)", "mean_of_sample_normalized_curves": False, "crossing": "first resolved crossing of the ensemble curve, linearly interpolated on saved grid", "crossing_intervals": "paired bootstrap; no-crossing replicates are right-censored beyond x=128", "crossing_grid_brackets_saved": True, "censoring_is_not_a_claim_of_no_event_at_later_times": True, "infinite_endpoint": "exactly conserved, treated analytically", }) write_table(summary, crossings) def write_table(summary, crossings): lookup = {(r["N"], r["kappa"], r["epsilon"]): r for r in crossings if r["mode"] == "raw"} lines = [ r"\begin{table}[t]", r"\centering\small", r"\begin{tabular}{rrrrrr}", r"\toprule", r"$N$ & $\kappa$ & $p_E$ & $\widehat\pi_\infty$ [95\% CI] & $x_{0.1}$ & $x_{0.5}$ \\", r"\midrule", ] previous = None for r in summary: if previous is not None and r["N"] != previous: lines.append(r"\addlinespace[2pt]") previous = r["N"] fields = [] for epsilon in (.1, .5): c = lookup[(r["N"], r["kappa"], epsilon)] if 2*r["plateau"]-1 > 1-epsilon: fields.append(r"$\infty^{\ast}$") else: fields.append(r"$>128$" if c["right_censored"] else f'{c["first_resolved_x"]:.2f}') precision = 6 if r["plateau"] < .01 else 4 interval_text = (f'{r["plateau"]:.{precision}f} ' f'[{r["plateau_ci_low"]:.{precision}f}, ' f'{r["plateau_ci_high"]:.{precision}f}]') lines.append( f'{r["N"]} & {r["kappa"]:.0f} & {r["energy_projection"]:.3f} & ' + interval_text + ' & ' + " & ".join(fields) + r" \\") lines.extend([ r"\bottomrule", r"\end{tabular}", r"\caption{Exact energy-projection weight $p_E$, estimated full elastic weight, and first resolved losses of the ensemble-averaged charge memory. Here $x_\epsilon=t_\epsilon/\tau_{N,\kappa}$. The plateau is obtained from spectral dephasing, rather than from the final plotted time. The symbol $\infty^{\ast}$ certifies that $2\widehat\pi_\infty-1>1-\epsilon$, excluding the crossing at every time for the realized finite ensemble; this is not a population certainty. The symbol $>128$ records only grid censoring. Crossing brackets, operational censoring flags, and paired-bootstrap intervals are supplied in the numerical data.}", r"\label{tab:charge-plateaus-loss}", r"\end{table}", ]) (OUT/"charge_table.tex").write_text("\n".join(lines)+"\n") def charge_plot_data(directory, reference=False): """Read the production arrays or recover the plotted quantities from the reference tables.""" if not reference: names = ("N", "x", "means", "intervals", "pdiag", "penergy", "pdiag_ci") paths = sorted(directory.glob("charge_analysis_N*.npz")) if not paths: raise FileNotFoundError(f"No charge_analysis_N*.npz in {directory}") data = [] for path in paths: with np.load(path) as saved: data.append({name: saved[name] for name in names}) return data curves = np.genfromtxt(directory / "charge_curves.csv", names=True, delimiter=",", dtype=None, encoding="utf-8") summary = np.genfromtxt(directory / "charge_summary.csv", names=True, delimiter=",", dtype=None, encoding="utf-8") data = [] modes = ("raw", "energy_removed", "dephased") for size in np.unique(summary["N"]): totals = np.sort(summary[summary["N"] == size], order="kappa") if not np.array_equal(totals["kappa"], KAPPAS): raise ValueError(f"Incomplete charge summary at N={size}") by_size = curves[curves["N"] == size] x = np.unique(by_size["x"]) means = np.empty((len(modes), len(KAPPAS), len(x))) intervals = np.empty((len(modes), 2, len(KAPPAS), len(x))) for mi, mode in enumerate(modes): for ki, coupling in enumerate(KAPPAS): selected = (by_size["mode"] == mode) & (by_size["kappa"] == coupling) curve = np.sort(by_size[selected], order="x") if not np.array_equal(curve["x"], x): raise ValueError(f"Incomplete time grid at N={size}, kappa={coupling}, {mode}") means[mi, ki] = curve["mean"] intervals[mi, 0, ki] = curve["ci_low"] intervals[mi, 1, ki] = curve["ci_high"] data.append(dict(N=size, x=x, means=means, intervals=intervals, pdiag=totals["plateau"], penergy=totals["energy_projection"], pdiag_ci=np.array([totals["plateau_ci_low"], totals["plateau_ci_high"]]))) return data def plot_results(source=OUT, figure_dir=FIG, reference=False): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from plot_style import configure configure() from matplotlib.lines import Line2D figure_dir.mkdir(parents=True, exist_ok=True) data = charge_plot_data(source, reference) palette = {10: "#215C83", 14: "#388C83", 18: "#D78729", 22: "#9E395A"} plt.rcParams.update({"font.size": 10, "axes.spines.top": False, "axes.spines.right": False, "pdf.fonttype": 42, "savefig.bbox": "tight"}) def save(fig, name): fig.savefig(figure_dir/(name+".pdf")) fig.savefig(figure_dir/(name+".png"), dpi=180) plt.close(fig) fig, axes = plt.subplots(2, 2, figsize=(9.2, 6.8), sharex=True, sharey=True) for ki, ax in enumerate(axes.flat): for d in data: N = int(d["N"]); color = palette[N]; x = d["x"] ax.plot(x[1:], d["means"][0, ki, 1:], color=color, lw=1.5, label=f"N={N}") ax.fill_between(x[1:], d["intervals"][0, 0, ki, 1:], d["intervals"][0, 1, ki, 1:], color=color, alpha=.15, linewidth=0) ax.axhline(d["pdiag"][ki], color=color, ls="--", lw=.8, alpha=.75) xb = np.geomspace(.035, 1.44, 70) ax.plot(xb, 1-xb*xb/2, color="#333333", ls=":", lw=1.1) ax.set_xscale("log"); ax.set_xlim(.035, 128); ax.set_ylim(-.06, 1.04) ax.set_title(rf"$\kappa={KAPPAS[ki]:g}$") ax.grid(alpha=.15) for ax in axes[-1]: ax.set_xlabel(r"$x=t/\tau_{N,\kappa}$") for ax in axes[:, 0]: ax.set_ylabel(r"$\langle \overline{C}(t)\rangle$") handles = [Line2D([0], [0], color=palette[int(d["N"])], label=f'N={int(d["N"])}') for d in data] handles += [Line2D([0], [0], color="#555555", ls="--", label="exact elastic weight"), Line2D([0], [0], color="#333333", ls=":", label=r"$1-x^2/2$")] fig.legend(handles=handles, loc="upper center", ncol=3, frameon=False, bbox_to_anchor=(.5, 1.01)) fig.tight_layout(rect=(0, 0, 1, .92)) save(fig, "charge_memory") fig, axes = plt.subplots(2, 3, figsize=(11.8, 6.3), sharex=True, sharey="row") for col, ki in enumerate((1, 2, 3)): for row, mode in enumerate((1, 2)): ax = axes[row, col] for d in data: N = int(d["N"]); color = palette[N]; x = d["x"] ax.plot(x[1:], d["means"][mode, ki, 1:], color=color, lw=1.4) ax.fill_between(x[1:], d["intervals"][mode, 0, ki, 1:], d["intervals"][mode, 1, ki, 1:], color=color, alpha=.14, linewidth=0) if mode == 1: p = (d["pdiag"][ki]-d["penergy"][ki])/(1-d["penergy"][ki]) ax.axhline(p, color=color, ls="--", lw=.75, alpha=.75) ax.axhline(0, color="#777777", lw=.7, alpha=.7) ax.set_xscale("log"); ax.set_xlim(.02, 128) ax.set_ylim(-.45 if row == 1 else -.06, 1.04) ax.grid(alpha=.15) if row == 0: ax.set_title(rf"$\kappa={KAPPAS[ki]:g}$") if row == 1: ax.set_xlabel(r"$x=t/\tau_{N,\kappa}$") axes[0, 0].set_ylabel("energy-orthogonal memory") axes[1, 0].set_ylabel("inelastic memory") fig.legend(handles=handles[:len(data)], loc="upper center", ncol=4, frameon=False, bbox_to_anchor=(.5, 1.01)) fig.tight_layout(rect=(0, 0, 1, .94)) save(fig, "charge_residual_memory") fig, axes = plt.subplots(1, 2, figsize=(10.1, 4.1)) for d in data: N = int(d["N"]); color = palette[N] y, ci = d["pdiag"], d["pdiag_ci"] axes[0].errorbar(KAPPAS, y, yerr=np.maximum(np.vstack([y-ci[0], ci[1]-y]), 0), color=color, marker="o", ms=4, lw=1.3, capsize=2, label=f"N={N}") axes[0].plot(KAPPAS, d["penergy"], color=color, ls="--", lw=.8) axes[0].set_xscale("symlog", linthresh=1, linscale=.3) axes[0].set_xticks(KAPPAS, labels=["0", "4", "16", "64"]) axes[0].set_xlabel(r"$\kappa$"); axes[0].set_ylabel("elastic spectral weight") axes[0].set_title("Full dephasing and energy projection") axes[0].legend(frameon=False, fontsize=9, loc="upper left") kcolors = {1: "#215C83", 2: "#D78729", 3: "#9E395A"} for ki in (1, 2, 3): Ns, ys, los, his = [], [], [], [] for d in data: pe = d["penergy"][ki] y = (d["pdiag"][ki]-pe)/(1-pe) ci = (d["pdiag_ci"][:, ki]-pe)/(1-pe) Ns.append(int(d["N"])); ys.append(y); los.append(y-ci[0]); his.append(ci[1]-y) axes[1].errorbar(Ns, ys, yerr=np.maximum(np.array([los, his]), 0), color=kcolors[ki], marker="o", capsize=2, lw=1.3, label=rf"$\kappa={KAPPAS[ki]:g}$") axes[1].set_xticks([int(d["N"]) for d in data]) axes[1].set_xlabel(r"$N$"); axes[1].set_ylabel("energy-orthogonal elastic weight") axes[1].set_title("Finite-size dependence after energy removal") axes[1].legend(frameon=False, fontsize=9) for ax in axes: ax.set_ylim(-.02, 1.02); ax.grid(alpha=.15) fig.tight_layout() save(fig, "charge_elastic_plateau") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--stage", choices=["pilot", "main", "analyze", "plot", "plot-reference", "all"], default="pilot") parser.add_argument("--sizes", default="10,14,18,22") parser.add_argument("--samples", default="256,256,128,32") parser.add_argument("--bootstrap", type=int, default=2000) parser.add_argument("--figure-dir", type=Path, default=FIG) args = parser.parse_args() if args.stage == "pilot": pilot() if args.stage in ("main", "all"): sizes = list(map(int, args.sizes.split(","))) samples = list(map(int, args.samples.split(","))) if len(sizes) != len(samples): raise ValueError("sizes and samples have different lengths") run(sizes, samples) if args.stage in ("analyze", "all"): analyze(args.bootstrap) if args.stage in ("plot", "plot-reference", "all"): reference = args.stage == "plot-reference" plot_results(OUT / "reference" if reference else OUT, args.figure_dir, reference=reference) if __name__ == "__main__": main()