"""Redraw the manuscript's five spacing-ratio figures from the distributed summaries.""" import argparse import csv from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np from plot_style import configure SIZES = (10, 14, 18, 22) THRESHOLDS = (0.25, 0.5, 0.75) COLORS = ("#236b8e", "#df8b32", "#4b9861", "#9b3f65") # The reference CSV tabulates width percentiles, whereas the final panel uses # percentiles after reciprocation. These four intervals are transcribed from # the v1 vector error bars to within 3e-10 on the vertical data coordinate. PUBLISHED_RATIO_INTERVALS = ( (0.117509881825676, 0.129167990833015), (0.065082818753478, 0.068496876414825), (0.042235092294881, 0.045744799856912), (0.032581581244471, 0.039259481195965), ) def read(directory, stem): with (directory / (stem + ".csv")).open(newline="") as handle: return list(csv.DictReader(handle)) def values(rows, column): return np.array([float(row[column]) for row in rows]) def select(rows, **conditions): return [ row for row in rows if all( row[key] == val if isinstance(val, str) else float(row[key]) == val for key, val in conditions.items() ) ] def finite_grid(rows): return sorted( (r for r in rows if 0 < float(r["kappa"]) < np.inf), key=lambda r: float(r["kappa"]), ) def plot_intervals(ax, x, rows, estimate, low, high, **style): y, lower, upper = (values(rows, key) for key in (estimate, low, high)) assert np.all(lower <= y) and np.all(y <= upper) return ax.errorbar(x, y, yerr=np.stack([y - lower, upper - y]), **style) def export(fig, output, stem, tight=False): fig.tight_layout() fig.savefig(output / (stem + ".pdf"), bbox_inches="tight" if tight else None) plt.close(fig) def coarse_figures(reference, output): curves = read(reference, "scaling_curves") crossing = read(reference, "scaling_crossings") radial = read(reference, "scaling_radial_convolution") plt.rcParams.update( { "font.size": 9, "axes.spines.top": False, "axes.spines.right": False, "pdf.fonttype": 42, } ) fig, axes = plt.subplots(1, 2, figsize=(10.4, 3.5)) for i, n in enumerate(SIZES): for ensemble, ls in [("fixed_radii", "-"), ("gaussian", "--")]: series = finite_grid(select(curves, N=n, ensemble=ensemble)) k = values(series, "kappa") assert len(k) == 11 fixed = ensemble == "fixed_radii" color = f"C{i}" axes[0].plot( k, values(series, "r_mean"), ls, color=color, label=f"N={n}" if fixed else None, ) if fixed: axes[0].fill_between( k, values(series, "r_low"), values(series, "r_high"), color=color, alpha=0.12, ) axes[1].plot(k, values(series, "isotonic_response"), ls, color=color) axes[0].set( xscale="log", xlabel=r"$\kappa$", ylabel=r"$\langle r\rangle$", title="Solid: fixed radii; dashed: Gaussian", ) axes[0].legend(ncol=2) axes[1].set( xscale="log", xlabel=r"$\kappa$", ylabel="Response from measured endpoints", title="Isotonic response; identical rank window", ) for q in THRESHOLDS: axes[1].axhline(q, color=".7", lw=0.5) export(fig, output, "scaling_directional_curves") ns = np.array(SIZES) fig, axes = plt.subplots(1, 3, figsize=(12, 3.5)) for j, (q, marker) in enumerate(zip(THRESHOLDS, ("v", "o", "^"))): for ensemble, ls, offset in [ ("fixed_radii", "-", -0.12), ("gaussian", "--", 0.12), ]: rows = sorted( select(crossing, response_threshold=q, ensemble=ensemble), key=lambda r: int(r["N"]), ) assert np.array_equal(values(rows, "N"), ns) plot_intervals( axes[0], ns + offset, rows, "kappa_crossing", "crossing_low", "crossing_high", marker=marker, ls=ls, color=f"C{j}", capsize=2, label=f"q={q:g}" if ensemble == "fixed_radii" else None, ) for ensemble, label, style in [ ("fixed_radii", "Fixed radii", "o-"), ("gaussian", "Gaussian", "s--"), ]: rows = sorted( select(crossing, response_threshold=0.5, ensemble=ensemble), key=lambda r: int(r["N"]), ) plot_intervals( axes[1], ns, rows, "log_width_25_75", "log_width_low", "log_width_high", fmt=style, capsize=2, label=label, ) rows = sorted( select(crossing, response_threshold=0.5, ensemble="fixed_radii"), key=lambda r: int(r["N"]), ) ratio = values(rows, "eta_sd_over_log_width") low, high = np.array(PUBLISHED_RATIO_INTERVALS).T np.testing.assert_allclose( ratio, values(rows, "eta_sd_exact") / values(rows, "log_width_25_75"), rtol=1e-14, ) axes[2].errorbar(ns, ratio, yerr=[ratio - low, high - ratio], fmt="o-", capsize=2) axes[0].set( xlabel="N", ylabel=r"$\kappa_q$", title="Response crossings; solid = fixed radii", ) axes[0].legend() axes[1].set( xlabel="N", ylabel=r"$W_N=\log(\kappa_{.75}/\kappa_{.25})$", title="Finite-size crossover width", ) axes[1].legend() axes[2].set( xlabel="N", ylabel=r"$\sigma_\eta/W_N$", title="Radial spread relative to width" ) for ax in axes: ax.set_xticks(ns) export(fig, output, "scaling_crossing_drift") fig, axes = plt.subplots(2, 2, figsize=(10.2, 6.5), sharex=True) for ax, n in zip(axes.flat, SIZES): rows = finite_grid(select(radial, N=n, interior_comparison="True")) k = values(rows, "kappa") assert len(k) == 9 plot_intervals( ax, k, rows, "gaussian_minus_directional", "observed_low", "observed_high", fmt="o", capsize=2, label="Paired direct estimate", ) ax.plot( k, values(rows, "radial_convolution_correction"), "-", label="Radial convolution: linear", ) ax.plot( k, values(rows, "pchip_correction"), "--", label="Radial convolution: PCHIP" ) ax.plot( k, values(rows, "coarsened_grid_correction"), ":", color=".45", label="Coarsened-grid sensitivity", ) ax.axhline(0, color=".5", lw=0.5) ax.set( xscale="log", xlim=(3.2, 120), xlabel=r"$\kappa$", ylabel=r"$\langle r\rangle_G-\langle r\rangle_\circ$", title=f"N={n}", ) axes[0, 0].legend(fontsize=7) export(fig, output, "scaling_radial_convolution") def refined_figures(reference, output): coarse = read(reference, "scaling_curves") curves = read(reference, "crossover_refined_curves") crossings = read(reference, "crossover_refined_crossings") radial = read(reference, "crossover_refined_convolution") fig, axes = plt.subplots(1, 3, figsize=(11.3, 3.5)) mids = [] widths = [] for n, color in zip(SIZES, COLORS): rows = finite_grid(select(curves, N=n)) earlier = finite_grid(select(coarse, N=n, ensemble="fixed_radii")) assert len(rows) == 20 and len(earlier) == 11 axes[0].plot( values(rows, "kappa"), values(rows, "isotonic_response"), "-o", ms=2.4, color=color, label=f"N={n}", ) axes[0].plot( values(earlier, "kappa"), values(earlier, "isotonic_response"), "--", color=color, alpha=0.45, ) mid = select(crossings, N=n, q=0.5) assert len(mid) == 1 for ax, key, lo, hi, old in [ (axes[1], "kappa", "ci_low", "ci_high", "coarse_kappa"), (axes[2], "width", "width_ci_low", "width_ci_high", "coarse_width"), ]: plot_intervals(ax, [n], mid, key, lo, hi, fmt="o", color=color, capsize=3) ax.plot(n, float(mid[0][old]), "x", color=color, ms=7) mids.append(float(mid[0]["kappa"])) widths.append(float(mid[0]["width"])) axes[0].set( xscale="log", xlabel=r"$\kappa$", ylabel="Normalized directional response", title="Refined solid; earlier dashed", ) axes[0].legend(fontsize=8, frameon=False) for ax, y, label in [ (axes[1], mids, r"$\kappa_{0.5}$"), (axes[2], widths, r"$W_N$"), ]: ax.plot(SIZES, y, color="0.55", lw=0.8) ax.set_ylabel(label) ax.set_xticks(SIZES) ax.set_xlabel(r"$N$") ax.set_title("Circles: refined; crosses: earlier", fontsize=10) for ax in axes: ax.grid(alpha=0.17) export(fig, output, "crossover_refined_curves", tight=True) fig, axes = plt.subplots(2, 2, figsize=(9.3, 6.3)) for ax, n in zip(axes.flat, SIZES): rows = finite_grid(select(radial, N=n)) assert len(rows) == (1 if n == 22 else 3) for j, row in enumerate(rows): plot_intervals( ax, [j - 0.09], [row], "direct_correction", "correction_ci_low", "correction_ci_high", fmt="o", capsize=3, color="#236b8e", label="Fresh radial average" if j == 0 else None, ) ax.plot( j + 0.09, float(row["coarse_linear_correction"]), "x", color="#ba5436", ms=7, label="Earlier linear convolution" if j == 0 else None, ) ax.plot( j, float(row["old_direct_paired_correction"]), "s", color="#4b9861", ms=4, label="Original Gaussian pair" if j == 0 else None, ) ax.axhline(0, color=".4", lw=0.7) ax.set_xticks(range(len(rows)), [f"{float(r['kappa']):g}" for r in rows]) ax.set_xlim(-0.5, len(rows) - 0.5) ax.set( xlabel=r"$\kappa$", ylabel=r"Change in $\langle r\rangle$", title=f"N={n}" ) ax.grid(axis="y", alpha=0.17) axes[0, 0].legend(fontsize=8, frameon=False) export(fig, output, "crossover_refined_convolution", tight=True) def main(): parser = argparse.ArgumentParser(description=__doc__) package = Path(__file__).resolve().parents[1] parser.add_argument( "--reference", type=Path, default=package / "results" / "reference" ) parser.add_argument("--output", type=Path, default=package / "results" / "figures") args = parser.parse_args() args.output.mkdir(parents=True, exist_ok=True) for family in coarse_figures, refined_figures: with plt.rc_context(): configure() family(args.reference, args.output) if __name__ == "__main__": main()