codex/gaussian-gate-quadratic-loss.py

gaussian-gate-quadratic-loss.py
"""Plot exact and local Gaussian time-gate loss. Python 3.14; NumPy/Matplotlib.

Run in the output directory; dependencies are pinned in the root pyproject.toml.
"""
from math import erf, exp, log, pi, sqrt
from pathlib import Path

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np


def main():
    # Times normalized by power FWHM tau; the gate width equals tau.
    sigma = 1 / (2 * sqrt(2 * log(2)))
    half_gate = .5
    f0 = erf(half_gate / (sqrt(2) * sigma))
    p_edge = exp(-half_gate**2 / (2 * sigma**2)) / (sqrt(2 * pi) * sigma)
    coefficient = half_gate * p_edge / sigma**2
    def fraction(d):
        return .5 * (erf((d + half_gate) / (sqrt(2) * sigma))
                     - erf((d - half_gate) / (sqrt(2) * sigma)))
    assert abs((f0-fraction(.001))/.001**2/coefficient-1) < 1e-5
    d = np.linspace(-.35, .35, 401)
    exact = np.array([fraction(x) for x in d])
    approx = f0 - coefficient*d*d
    x = np.geomspace(.001, .35, 300)
    loss = np.array([f0-fraction(z) for z in x])
    fig, axes = plt.subplots(1, 2, figsize=(7.4, 3.0), dpi=100, layout='constrained')
    fig.set_facecolor('white')
    axes[0].plot(d, exact, label='Exact Gaussian integral', color='#24649a', lw=2)
    axes[0].plot(d, approx, '--', label='Quadratic approximation', color='#c15b20', lw=1.6)
    axes[0].set(xlabel=r'Gate offset $d/\tau$', ylabel='Captured energy / full energy',
                title=r'Gate width $T_g=\tau$', ylim=(.59, .78))
    axes[0].legend(fontsize=8, loc='lower center')
    axes[1].loglog(x, loss, color='#24649a', lw=2, label='Exact loss')
    axes[1].loglog(x, coefficient*x*x, '--', color='#c15b20', label=r'$1.30234(d/\tau)^2$')
    axes[1].set(xlabel=r'Offset magnitude $|d|/\tau$', ylabel='Lost fraction from centred gate',
                title='Zero slope still permits timing loss')
    axes[1].legend(fontsize=8)
    for ax in axes:
        ax.grid(alpha=.23)
        ax.spines[['top', 'right']].set_visible(False)
        ax.tick_params(labelsize=8)
        ax.set_facecolor('white')
    fig.savefig(Path('gaussian-gate-quadratic-loss.png'), facecolor='white')
    plt.close(fig)


if __name__ == '__main__':
    main()