#!/usr/bin/env python3 """Generate the figures of the paper from the artefacts in anc/artefacts. Run from anywhere: python3 anc/make_figures.py Output: /figures/*.pdf (one PDF per figure, Type 42 fonts, no external data). The per-character arrays used in the amplifier figure are recomputed here with the same independent implementation used by anc/verify_propositions.py, so the figures never depend on data that is not shipped in the source archive. """ import json import math import os import sys import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.patches import FancyArrowPatch, FancyBboxPatch HERE = os.path.dirname(os.path.abspath(__file__)) ART = os.path.join(HERE, 'artefacts') OUT = os.path.join(os.path.dirname(HERE), 'figures') sys.path.insert(0, HERE) import verify_propositions as vp # noqa: E402 plt.rcParams.update({ 'pdf.fonttype': 42, 'ps.fonttype': 42, 'font.size': 10.5, 'axes.labelsize': 10.5, 'axes.titlesize': 11, 'legend.fontsize': 9, 'xtick.labelsize': 9.5, 'ytick.labelsize': 9.5, 'axes.grid': True, 'grid.alpha': 0.25, 'grid.linewidth': 0.4, 'lines.linewidth': 1.1, 'figure.dpi': 200, }) COLOURS = {'bump': '#1f4e79', 'half': '#a33b20', 'indicator': '#2f6b34'} def load(name): with open(os.path.join(ART, name), encoding='utf-8') as handle: return json.load(handle) def save(fig, name): os.makedirs(OUT, exist_ok=True) path = os.path.join(OUT, name) fig.savefig(path, bbox_inches='tight') plt.close(fig) print('wrote', path) def figure_spectra(): spectra = load('spectra.json') decay = load('spectra_decay.json') fits = {(f['kernel'], f['support_N']): f['fit'] for f in decay['fits']} fig, axes = plt.subplots(1, 2, figsize=(6.5, 3.9)) ax = axes[0] groups = {} for row in spectra['rows']: groups.setdefault((row['kernel'], row['support_N']), []).append(row) for key in sorted(groups): rows = sorted(groups[key], key=lambda r: r['q']) qs = [r['q'] for r in rows] sups = [r['sup_abs_khat_nonprincipal'] for r in rows] kind, support = key label = '%s, N=%d' % (kind, support) style = 'o-' if kind != 'indicator' else 's--' ax.plot(qs, sups, style, color=COLOURS[kind], markersize=3, alpha=1.0 if support == 4 else 0.55, label=label) fit = fits.get(key) if fit and len(rows) >= 2: qs_fit = [3, 31] ax.plot(qs_fit, [math.exp(fit['beta']) * q ** fit['alpha'] for q in qs_fit], ':', color=COLOURS[kind], linewidth=0.8) control = decay['control_delta']['rows'] ax.plot([r['q'] for r in control], [r['sup_abs_khat_nonprincipal'] for r in control], 'k^-', markersize=3, label='delta control') ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('modulus q') ax.set_ylabel(r'$\sup_{\chi\neq\chi_0}|\widehat K(\chi)|$') ax.set_title('non-principal spectral supremum') ax.set_ylim(bottom=ax.get_ylim()[0], top=ax.get_ylim()[1] * 1e9) ax.legend(loc='upper left', ncol=2, fontsize=8.5, frameon=True, framealpha=0.9, edgecolor='none', columnspacing=1.0, handlelength=1.6) ax = axes[1] for key in sorted(groups): rows = sorted(groups[key], key=lambda r: r['q']) kind, support = key if kind == 'indicator': continue qs = [r['q'] for r in rows] floor = [math.sqrt(max((r['parseval_rhs'] - r['principal_abs_khat'] ** 2) / (r['phi'] - 1), 0.0)) for r in rows] sup = [r['sup_abs_khat_nonprincipal'] for r in rows] ax.plot(qs, sup, 'o-', color=COLOURS[kind], markersize=3, label='%s supremum' % kind) ax.plot(qs, floor, 'v--', color=COLOURS[kind], markersize=3, alpha=0.6, label='%s RMS floor' % kind) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('modulus q') ax.set_ylabel('spectral size') ax.set_title('supremum against the Parseval floor') ax.set_ylim(bottom=ax.get_ylim()[0], top=ax.get_ylim()[1] * 40) ax.legend(loc='upper left', frameon=False) fig.tight_layout() save(fig, 'fig_spectra.pdf') def figure_gain(): operator = load('operator.json') fig, axes = plt.subplots(1, 2, figsize=(6.5, 3.3), sharey=True) for ax, kind in zip(axes, ('bump', 'half')): rows = [r for r in operator['rows'] if r['kernel'] == kind] for length in (1, 2, 4, 8): series = sorted([r for r in rows if r['L'] == length], key=lambda r: r['q']) qs = [r['q'] for r in series] gains = [r['gain_ratio'] if r['gain_ratio'] is not None else float('nan') for r in series] plotted = [max(g, 1e-3) if g is not None else float('nan') for g in gains] ax.plot(qs, plotted, 'o-', markersize=3, label='L=%d' % length) zero_q = [q for q, g in zip(qs, gains) if g is not None and g < 1e-9] if zero_q: ax.plot(zero_q, [1e-3] * len(zero_q), 'x', color='k', markersize=5) ax.axhline(1.05, color='#888888', linestyle='--', linewidth=0.8) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('modulus q') ax.set_title('%s kernel' % kind) ax.legend(loc='lower right', frameon=False) axes[0].set_ylabel('gain ratio G') axes[0].set_ylim(5e-4, 40) fig.tight_layout() save(fig, 'fig_gain.pdf') def figure_adequacy(): adequacy = load('adequacy.json') rows = [r for r in adequacy['rows'] if r['admissible'] and r['gain_ratio'] is not None] fig, ax = plt.subplots(figsize=(6.5, 3.9)) ok = [r for r in rows if r['adequate']] bad = [r for r in rows if not r['adequate']] ax.scatter([r['gain_ratio'] for r in ok], [min(r['localization'], 50.0) for r in ok], s=14, color='#2f6b34', alpha=0.7, label='adequate (%d)' % len(ok)) ax.scatter([max(r['gain_ratio'], 1e-3) for r in bad], [min(r['localization'], 50.0) for r in bad], s=26, marker='X', color='#a33b20', label='failing (%d)' % len(bad)) ax.axvline(adequacy['thresholds']['min_gain_ratio'], color='#555555', linestyle='--', linewidth=0.9) ax.axhline(adequacy['thresholds']['min_localization'], color='#555555', linestyle=':', linewidth=0.9) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('gain ratio G') ax.set_ylabel('localization (capped at 50)') ax.set_title('adequacy plane on the admissible grid') ax.annotate('thresholds 1.05 and 0.5', xy=(1.05, 0.5), xytext=(2e-2, 0.62), fontsize=9, color='#444444', arrowprops=dict(arrowstyle='->', color='#444444', lw=0.7)) ax.legend(loc='upper left', frameon=False) zeros = [r for r in bad if r['gain_ratio'] is not None and r['gain_ratio'] < 1e-9] ax.annotate('%d rows with G = 0' % len(zeros), xy=(1e-3, 20), xytext=(3e-3, 2.2), fontsize=9, color='#a33b20', arrowprops=dict(arrowstyle='->', color='#a33b20', lw=0.7)) ax.set_xlim(5e-4, 30) fig.tight_layout() save(fig, 'fig_adequacy.pdf') def figure_amplifier(): fig, axes = plt.subplots(1, 3, figsize=(6.5, 3.2)) cases = [(3, 'bump', 4, 2), (3, 'bump', 4, 4), (13, 'bump', 4, 8)] for ax, (q, kind, support, length) in zip(axes, cases): point = {'q': q, 'kernel': kind, 'support_N': support, 'L': length} got = vp.recompute(point) idx = list(range(1, got['phi'])) amp2 = [abs(got['amp'][j]) ** 2 for j in idx] khat2 = [abs(got['khat'][j]) ** 2 for j in idx] width = 0.38 ax.bar([i - width / 2 for i in idx], khat2, width=width, color='#1f4e79', label=r'$|\widehat K(\chi_j)|^2$') ax.bar([i + width / 2 for i in idx], amp2, width=width, color='#a33b20', label=r'$|A_L(\chi_j)|^2$') ax.set_xlabel('character index j') ax.set_title('q=%d, L=%d (L mod q=%d)' % (q, length, length % q)) ax.set_xticks(idx) if q == 3: ax.set_xticks([1]) ax.set_xlim(0.2, 1.8) else: plt.setp(ax.get_xticklabels(), rotation=45, ha='right') ax.set_xlabel('character index j', labelpad=12) axes[0].set_ylabel('squared modulus') handles, labels = axes[0].get_legend_handles_labels() fig.legend(handles, labels, loc='upper center', ncol=2, frameon=False, bbox_to_anchor=(0.5, 1.10)) fig.tight_layout() save(fig, 'fig_amplifier.pdf') def figure_iteration(): iteration = load('iteration.json') fig, axes = plt.subplots(1, 2, figsize=(6.5, 3.3)) ax = axes[0] for m in sorted({r['m'] for r in iteration['rows']}): rows = [r for r in iteration['rows'] if r['m'] == m] rows.sort(key=lambda r: r['q']) by_q = {} for r in rows: by_q.setdefault(r['q'], []).append(r['second_moment']) qs = sorted(by_q) ax.plot(qs, [max(by_q[q]) for q in qs], 'o-', markersize=3, label='m=%d' % m) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('modulus q') ax.set_ylabel('max amplified second moment') ax.set_title('iteration growth') ax.set_ylim(bottom=ax.get_ylim()[0], top=ax.get_ylim()[1] * 1e3) ax.legend(loc='upper left', frameon=False) ax = axes[1] for m in sorted({r['m'] for r in iteration['rows']}): rows = [r for r in iteration['rows'] if r['m'] == m] lengths = sorted({r['L'] for r in rows}) ax.plot(lengths, [max(r['polynomial_length'] for r in rows if r['L'] == L) for L in lengths], 's-', markersize=3, label='m=%d' % m) ax.set_xlabel('amplifier length L') ax.set_ylabel('Dirichlet polynomial length mL') ax.set_title('transport cost of iterating') ax.legend(frameon=False) fig.tight_layout() save(fig, 'fig_iteration.pdf') def figure_pipeline(): fig, ax = plt.subplots(figsize=(6.5, 4.9)) ax.set_xlim(0, 10) ax.set_ylim(0, 7.9) ax.axis('off') def box(x, y, w, h, text, colour, fontsize=9.0): patch = FancyBboxPatch((x, y), w, h, boxstyle='round,pad=0.04,rounding_size=0.08', linewidth=0.8, edgecolor=colour, facecolor='white') ax.add_patch(patch) ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=fontsize, color=colour) def arrow(x1, y1, x2, y2, colour='#666666'): ax.add_patch(FancyArrowPatch((x1, y1), (x2, y2), arrowstyle='-|>', mutation_scale=8, linewidth=0.7, color=colour, shrinkA=1, shrinkB=1)) box(3.2, 6.55, 3.6, 0.95, 'T_ASA (OPEN)\ninterface inequality', '#1f4e79', 9.6) labels = [('P1\ntransfer', '#a33b20'), ('P2\ndensity', '#a33b20'), ('P3\nbudget', '#a33b20'), ('P4\nnet', '#a33b20'), ('P5\nadequacy', '#a33b20'), ('P6\nstatement', '#2f6b34')] xs = [0.15 + 1.63 * i for i in range(6)] for x, (text, colour) in zip(xs, labels): box(x, 4.80, 1.45, 0.95, text, colour) arrow(x + 0.72, 5.75, 5.0, 6.55) block = [ (0.15, 'E_trunc\nE_unif\nE_exception'), (1.78, 'E_density\n(1 blocker)'), (3.41, '9 of 15 loss\ncategories\nunpriced'), (5.04, 'normalization\ncost_total\nnull'), (6.67, 'gain collapse\nL mod q in\n{0,1,q-1}'), (8.30, 'statement-only\nLean file,\nno kernel\ncheck'), ] for x, text in block: box(x, 2.45, 1.45, 1.75, text, '#555555', 8.0) arrow(x + 0.72, 4.20, x + 0.72, 4.80) box(0.15, 0.45, 9.55, 1.35, 'net strength BLOCKED | classification F4 (missing hypothesis)\n' 'target OPEN | protocol complete, mission not complete', '#1f4e79', 9.0) arrow(5.0, 2.45, 5.0, 1.80) fig.tight_layout() save(fig, 'fig_pipeline.pdf') def main(): figure_spectra() figure_gain() figure_adequacy() figure_amplifier() figure_iteration() figure_pipeline() return 0 if __name__ == '__main__': sys.exit(main())