"""Regenerate the research feature figures with Python, NumPy and Matplotlib.

Run beside clock-quench.csv and shutter-cutoff.csv. Values below are the published
coordinates and reported summary statistics. The clock CSV contains the original
three Pauli-flip traces and the quarter-turn computed by ../analysis/clock-check.py.
The figure captions on the four articles identify the original experiments.
"""

import csv
from itertools import product
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle, FancyBboxPatch


OUT = Path(__file__).resolve().parent
INK = "#20342f"
MUTED = "#586b61"
TEAL = "#197568"
RUST = "#b65332"
BLUE = "#3d6184"
RULE = "#c7d4c9"
GRID = "#dee6dd"
PAPER = "#fcfbf6"
plt.rcParams.update({
    "font.family": "DejaVu Sans", "font.size": 12, "axes.labelcolor": INK,
    "text.color": INK, "axes.edgecolor": MUTED, "xtick.color": MUTED,
    "ytick.color": MUTED, "axes.facecolor": PAPER, "figure.facecolor": PAPER,
    "axes.spines.top": False, "axes.spines.right": False, "mathtext.fontset": "dejavusans",
})


def save(fig, name):
    fig.savefig(OUT / (name + ".png"), dpi=180, bbox_inches="tight", pad_inches=0.22)
    plt.close(fig)


def title(ax, label):
    ax.set_title(label, loc="left", fontsize=15, fontweight="bold", pad=11)


def shutter():
    fig, ax = plt.subplots(figsize=(7.0, 2.5))
    ax.set(xlim=(-0.4, 7.5), ylim=(-0.5, 2.28), aspect="equal")
    ax.axis("off")
    ax.plot([1.65, 5.4], [0.28, 0.28], color=MUTED, lw=2.2)
    ax.plot([2.9, 4.15], [0.28, 0.28], color=RUST, lw=4, solid_capstyle="butt")
    for idx, x in enumerate([1.65, 2.9, 4.15, 5.4], 1):
        ax.add_patch(Circle((x, .28), .19, facecolor=TEAL, zorder=3))
        ax.text(x, -.19, str(idx), ha="center", fontsize=11)
    for x, label in [(.3, "Sender"), (6.75, "Receiver")]:
        ax.add_patch(FancyBboxPatch((x-.57, -.03), 1.14, .62, boxstyle="round,pad=.05,rounding_size=.1", facecolor=BLUE, edgecolor="none"))
        ax.text(x, .28, label, ha="center", va="center", color="white", fontsize=11, weight="bold")
    ax.plot([.92, 1.46], [.28, .28], color=BLUE, lw=2)
    ax.plot([5.59, 6.13], [.28, .28], color=BLUE, lw=2)
    ax.plot([.3, .3], [.65, 1.38], ls=":", lw=2, color=BLUE)
    ax.text(.3, 1.53, "Isolated\nreference", ha="center", va="bottom", fontsize=12, weight="bold")
    ax.text(3.53, 1.54, "Quantum controller", ha="center", weight="bold", color=RUST)
    ax.annotate("", xy=(3.53,.43), xytext=(3.53,1.4), arrowprops={"arrowstyle":"-|>", "color":RUST, "lw":2})
    ax.text(4.85, .75, "Gated middle link", ha="center", color=RUST, fontsize=11)
    ax.text(6.75, 1.55, "Read out with\nthe reference", ha="center", fontsize=11)
    save(fig, "shutter-channel")

    fig, ax = plt.subplots(figsize=(6.7, 3.1))
    labels = ["Disconnected", "Static closed", "Quantum shutter", "Always open"]
    fidelity = [0.500000098, 0.520130837, 0.795393872, 0.811954022]
    for row, (name, value) in enumerate(zip(labels, fidelity)):
        color = RUST if name == "Quantum shutter" else BLUE
        ax.hlines(row, .45, value, color=color, lw=2)
        ax.scatter(value, row, color=color, s=52, zorder=3)
        ax.text(value+.008, row, f"{100*value:.2f}%", va="center", fontsize=11, color=color, weight="bold")
    ax.axvline(2/3, ls="--", lw=1.2, color=MUTED)
    ax.text(2/3, 3.43, "⅔", ha="center", color=MUTED)
    ax.set(yticks=range(4), yticklabels=labels, xlim=(.45,.90), ylim=(-.52,3.75), xlabel="Fixed-decoder average fidelity at model time 62")
    ax.spines["left"].set_visible(False)
    ax.tick_params(axis="y", length=0)
    ax.grid(axis="x", color=GRID, zorder=0)
    save(fig, "shutter-controls")

    with (OUT/"shutter-cutoff.csv").open(newline="") as source:
        rows = list(csv.DictReader(source))
    times = [float(row["model_time"]) for row in rows]
    distances = [float(row["d5_d6_choi_trace_distance"]) for row in rows]
    fig, ax = plt.subplots(figsize=(6.4,2.85), layout="constrained")
    ax.plot(times, distances, "-o", color=TEAL, ms=4)
    ax.axhline(.005, ls="--", lw=1.3, color=RUST)
    ax.text(2,.00512,"Strict limit 0.005",color=RUST, va="bottom", fontsize=11)
    ax.annotate("0.005136 at capture", xy=(62,distances[-1]), xytext=(34,.00615),
                arrowprops={"arrowstyle":"->","color":RUST}, color=RUST, fontsize=11)
    ax.set(xlim=(-1,65),ylim=(-.0001,.0068),yticks=[0,.0025,.005],xlabel="Model time",ylabel="Choi trace distance")
    ax.grid(axis="y",color=GRID)
    save(fig,"shutter-cutoff")

    fig, ax = plt.subplots(figsize=(6.4,3.2), layout="constrained")
    sizes = [12,16,20,24]
    ax.semilogy(sizes,[.00484,.000709,.000137,.0000795], "o-", color=TEAL, lw=2, label="Terminal sites · smooth history")
    ax.semilogy(sizes,[.0473,.0108,.00593,.00453], "s--", color=BLUE, lw=1.8, label="Terminal sites · always open")
    ax.scatter([16],[.07693],marker="_",s=120,color=RUST,zorder=4)
    ax.annotate("",xy=(16,.19),xytext=(16,.07693),arrowprops={"arrowstyle":"-|>","color":RUST,"lw":2})
    ax.text(16.28,.081,"Whole field ≥ 0.07693",color=RUST,fontsize=10)
    ax.set(xlim=(11.5,24.5),ylim=(.00005,.25),xticks=sizes,xlabel="Oscillator sites",ylabel="Trace distance")
    ax.grid(axis="y",color=GRID)
    ax.legend(loc="lower left",fontsize=9,frameon=True,facecolor=PAPER)
    save(fig,"shutter-observer")


WITNESSES = np.array([[0,1,-1,0,0,0], [0,0,0,0,0,1], [1,0,-1,0,0,0],
                      [0,0,0,0,1,0], [1,-1,0,0,0,0], [0,0,0,1,0,0]])


def axis_span():
    fig = plt.figure(figsize=(7.4, 5.2))
    polar, azimuth = np.meshgrid(np.linspace(0, np.pi, 15), np.linspace(0, 2*np.pi, 23))
    sphere = np.stack([np.sin(polar)*np.cos(azimuth), np.sin(polar)*np.sin(azimuth), np.cos(polar)])
    for a, direction in enumerate("xyz"):
        for b, mode in enumerate(("+", "×")):
            ax = fig.add_subplot(2, 3, b*3+a+1, projection="3d", proj_type="ortho")
            v = WITNESSES[2*a+b]
            strain = np.array([[v[0],v[3],v[4]], [v[3],v[1],v[5]], [v[4],v[5],v[2]]])
            shaped = np.einsum("ij,jkl->ikl", np.eye(3)+.18*strain, sphere)
            ax.plot_wireframe(*sphere, rstride=3, cstride=2, color=RULE, linewidth=.55)
            ax.plot_wireframe(*shaped, rstride=2, cstride=2, color=TEAL, linewidth=.72)
            vector = np.eye(3)[a]
            ax.quiver(0,0,0, *vector, length=1.52, color=RUST, linewidth=2, arrow_length_ratio=.15)
            ax.set(xlim=(-1.2,1.3), ylim=(-1.2,1.3), zlim=(-1.2,1.3), box_aspect=(1,1,1))
            ax.view_init(elev=21, azim=-48)
            ax.set_axis_off()
            if b == 0:
                ax.set_title(f"Along {direction}", fontsize=14, weight="bold", pad=-5)
            label = ["yy − zz","yz","xx − zz","xz","xx − yy","xy"][2*a+b]
            ax.text2D(.5,.01, f"{mode}   {label}", transform=ax.transAxes, ha="center", fontsize=13)
    fig.subplots_adjust(left=0, right=1, top=.97, bottom=.02, hspace=.02, wspace=0)
    save(fig, "axis-witnesses")

    fig, (rank, spectrum) = plt.subplots(1,2, figsize=(7.7,3.2), gridspec_kw={"width_ratios":[1,1.04]}, layout="constrained")
    ranks = [np.linalg.matrix_rank(WITNESSES[:i]) for i in range(1,7)]
    assert ranks == [1,2,3,4,4,5]
    rank.plot(range(1,7), ranks, "o-", lw=2, color=TEAL)
    rank.set(xticks=range(1,7), xticklabels=["x+","x×","y+","y×","z+","z×"], yticks=range(6), ylim=(-.2,5.5), xlabel="Witness added", ylabel="Independent distortions")
    rank.tick_params(axis="x", labelsize=10)
    title(rank,"Rank of the witness set")
    q = np.linspace(0,1,151)
    spectrum.plot(q,q,color=TEAL,lw=3)
    spectrum.plot(q,np.sqrt(q*q+3),color=RUST,lw=2)
    spectrum.text(.28,.23,"Five traceless",color=TEAL,fontsize=10,va="top")
    spectrum.text(.08,1.82,"One trace",color=RUST,fontsize=11)
    spectrum.set(xlim=(0,1),ylim=(0,2.16),xticks=[0,.5,1],yticks=[0,1,2],xlabel="Momentum magnitude",ylabel="Frequency")
    title(spectrum,"Illustrative spectrum")
    for ax in (rank,spectrum):
        ax.grid(axis="y",color=GRID)
        ax.set_axisbelow(True)
    save(fig, "axis-rank-spectrum")


def clock():
    fig, (pulse, signal) = plt.subplots(2, 1, figsize=(6.6,6.2), layout="constrained", gridspec_kw={"height_ratios":[.9,1.35]})
    x = np.arange(2)
    for offset, vals, label, col in [(-.16,[2,0],"Historical map",RUST),(.16,[1,1],"Repaired rotation",TEAL)]:
        pulse.bar(x+offset, vals, width=.28, color=col, label=label)
        for j,val in enumerate(vals):
            pulse.text(x[j]+offset, val+.06, str(val), ha="center", color=col, weight="bold")
    pulse.set(xticks=x, xticklabels=["Input |+y⟩", "Input |−y⟩"], yticks=[0,1,2], ylim=(0,2.55), ylabel="Output norm²")
    pulse.legend(loc="upper right",frameon=False,fontsize=10)
    title(pulse,"A    Preparing the clock")
    with (OUT/"clock-quench.csv").open(newline="") as source:
        rows = list(csv.DictReader(source))
    t = [float(row["model_time"]) for row in rows]
    for quench, color, style in [("X",RUST,"-."),("Y",TEAL,"-"),("Z",BLUE,"--")]:
        signal.plot(t,[float(row[quench+"_quench_trace_distance"]) for row in rows], label=quench+" quench", color=color, ls=style, lw=2)
    signal.set(xlim=(0,3), ylim=(0,.007), yticks=[0,.002,.004,.006], xlabel="Model time", ylabel="Remote trace distance")
    signal.legend(loc="upper left",ncol=1,frameon=False,fontsize=10)
    title(signal,"B    Measuring a remote qubit")
    for ax in (pulse,signal):
        ax.grid(axis="y",color=GRID)
        ax.set_axisbelow(True)
    save(fig,"clock-pulse-quench")


def cube(ax, L):
    basis = np.array([[1,.04],[-.62,.42],[0,1]])
    xyz = list(product(range(L),repeat=3))
    for p in xyz:
        for axis,color in enumerate((RUST,TEAL,BLUE)):
            if p[axis]+1 < L:
                q = np.array(p)
                q[axis] += 1
                a,b = np.array([p,q]) @ basis
                ax.plot([a[0],b[0]],[a[1],b[1]],color=color,linewidth=2.6 if L==2 else 1.7, zorder=1)
    points = np.array(xyz) @ basis
    ax.scatter(*points.T, s=22 if L==2 else 14, color=INK,zorder=2)
    ax.set_aspect("equal")
    ax.axis("off")
    title(ax,f"{L} × {L} × {L} cube")
    ax.set_xlabel(f"{L**3} vertices · {3*L**2*(L-1)} edges")
    ax.text(.5,-.07,f"{L**3} vertices · {3*L**2*(L-1)} edges",transform=ax.transAxes,ha="center")


def variance():
    fig,axes = plt.subplots(1,2,figsize=(6.0,2.85),layout="constrained")
    cube(axes[0],2)
    cube(axes[1],3)
    save(fig,"spin-bond-geometry")

    # Mean and one standard error across the eight seeds in each condition.
    # Column order in each pair is L2/off, L2/on, L3/off, L3/on.
    terms = {
        "Single edge": ([1.495647,2.379352,1.506344,5.383977],[.018343,.185066,.020407,.205269]),
        "Between edges": ([.005211,-.525315,-.000483,-1.685906],[.010655,.165052,.040321,.291200]),
        "Total": ([1.500858,1.854037,1.505861,3.698071],[.023981,.058112,.051795,.335568]),
        "Sharing a vertex": ([-.017213,-.593220,-.010973,-2.651761],[.011135,.169287,.010816,.334823]),
        "No shared vertex": ([.022425,.067905,.010489,.965855],[.014803,.026351,.040905,.401703]),
    }
    fig,(total,pairs) = plt.subplots(2,1,figsize=(6.7,6.2),sharex=True,layout="constrained")
    x = np.array([0,1,2.55,3.55])
    for ax, groups in [(total,[("Single edge",RUST),("Between edges",TEAL),("Total",BLUE)]),
                       (pairs,[("Sharing a vertex",TEAL),("No shared vertex",BLUE)])]:
        for j,(name,color) in enumerate(groups):
            vals,errs = terms[name]
            pos=x+(j-(len(groups)-1)/2)*.22
            if name=="Total":
                ax.errorbar(pos,vals,yerr=errs,fmt="D",color=color,capsize=3,ls="none",label=name,ms=6)
            else:
                ax.bar(pos,vals,width=.2,color=color,label=name)
                ax.errorbar(pos,vals,yerr=errs,fmt="none",ecolor=INK,capsize=3,elinewidth=1)
        ax.axhline(0,color=INK,lw=1)
        ax.grid(axis="y",color=GRID)
        ax.set_axisbelow(True)
        ax.set_ylabel("Contribution per edge")
        ax.legend(ncol=len(groups),frameon=False,loc="upper left",fontsize=9)
    title(total,"A    Where the total comes from")
    title(pairs,"B    Which pairs contribute")
    total.set_ylim(-2.45,7.15)
    pairs.set_ylim(-3.35,2.2)
    pairs.set(xticks=x,xticklabels=["2³ cube\n0","2³ cube\n0.02","3³ cube\n0","3³ cube\n0.02"],xlabel="Cube size and bond–bond coupling")
    save(fig,"spin-signed-covariance")


def third_direction():
    angle = np.linspace(0, 90, 181)
    sin_squared = np.sin(np.deg2rad(angle)) ** 2
    fig, ax = plt.subplots(figsize=(6.4, 3.6), layout="constrained")
    ax.plot(angle, sin_squared, color=TEAL, lw=2.4, label="Turn from x toward z")
    ax.plot(angle, sin_squared * (1 - sin_squared), color=RUST, ls="--",
            lw=2.4, label="Turn from x toward y")
    ax.scatter([45, 90], [.25, 1], color=[RUST, TEAL], s=40, zorder=3)
    ax.annotate("x + y sees ¼", (45, .25), xytext=(48, .32), color=RUST)
    ax.set(xlim=(0, 92), ylim=(-.02, 1.05), xticks=[0, 15, 30, 45, 60, 75, 90],
           yticks=[0, .25, .5, .75, 1], xlabel="Angle from x (degrees)",
           ylabel="Fraction of residual stiffness seen")
    ax.grid(axis="y", color=GRID)
    ax.legend(loc="upper left", frameon=False, fontsize=11)
    save(fig, "axis-third-direction")


def clock_quarter_turn():
    with (OUT / "clock-quench.csv").open(newline="") as source:
        rows = list(csv.DictReader(source))
    times = [float(row["model_time"]) for row in rows]
    fig, ax = plt.subplots(figsize=(6.5, 3.8), layout="constrained")
    pulses = [
        ("X_quench_trace_distance", "180° X", RUST, "-."),
        ("Y_quench_trace_distance", "180° Y", BLUE, "--"),
        ("Z_quench_trace_distance", "180° Z", MUTED, ":"),
        ("Ry90_computed_trace_distance", "90° Y", TEAL, "-"),
    ]
    for column, label, color, style in pulses:
        values = [float(row[column]) for row in rows]
        ax.plot(times, values, label=label, color=color, ls=style, lw=2.2)
        ax.scatter(times[-1], values[-1], color=color, s=17, zorder=3)
    ax.set(xlim=(0, 3.09), ylim=(-.0005, .034), xticks=[0, 1, 2, 3],
           xlabel="Model time", ylabel="Trace distance at site 2")
    ax.grid(axis="y", color=GRID)
    ax.legend(ncols=2, loc="upper left", frameon=False, fontsize=11)
    save(fig, "clock-quarter-turn")


def bond_pairs():
    fig, (raw, weighted) = plt.subplots(1, 2, sharey=True, figsize=(7.0, 3.5),
                                       layout="constrained")
    y = [3, 2, 1, 0]
    groups = ["Touching parallel", "Touching at 90°", "Disjoint parallel", "Disjoint at 90°"]
    panels = [
        (raw, [1.272566, 1.223020, .736591, .721374],
         [.127828, .132666, .126498, .117627], "A   Occupation covariance"),
        (weighted, [1.696755, -4.348515, 15.713942, -14.748087],
         [.170437, .471702, 2.698634, 2.404824], "B   Tensor contribution"),
    ]
    for ax, values, errors, label in panels:
        for row, value, error in zip(y, values, errors):
            color = TEAL if value >= 0 else RUST
            ax.barh(row, value, height=.36, color=color)
            ax.errorbar(value, row, xerr=error, fmt="none", ecolor=INK, capsize=3)
        ax.axvline(0, color=INK, lw=1)
        ax.grid(axis="x", color=GRID)
        ax.set_axisbelow(True)
        ax.set_title(label, loc="left", weight="bold", fontsize=12, pad=10)
    raw.set(yticks=y, yticklabels=groups, xlabel="Mean per pair (occupation²)",
            xlim=(0, 1.55), xticks=[0, .5, 1, 1.5])
    weighted.set(xlabel="Weighted sum per edge", xlim=(-20, 20), xticks=[-15, 0, 15])
    save(fig, "spin-pair-weights")


def matching_receiver():
    fig, ax = plt.subplots(figsize=(6.7, 3.55), layout="constrained")
    names = ["4 sites · shutter", "4 sites · open", "18 sites · shutter",
             "18 sites · open", "Matched phase-flip"]
    margins = [.09696, -.21150, .05991, .01826, -.07457]
    for row, value in enumerate(margins):
        color = TEAL if value >= 0 else RUST
        ax.hlines(row, 0, value, color=color, lw=3)
        ax.scatter(value, row, color=color, s=45, marker="D" if row == 4 else "o", zorder=3)
    ax.axvline(0, color=INK, lw=1.1)
    ax.axhline(3.55, color=RULE, ls=":", lw=1)
    ax.set(yticks=range(5), yticklabels=names, ylim=(4.5, -.55), xlim=(-.245, .125),
           xticks=[-.2, -.1, 0, .1], xlabel="Symmetric-extension margin")
    ax.grid(axis="x", color=GRID)
    ax.set_axisbelow(True)
    save(fig, "shutter-matching-receiver")


def same_fidelity():
    """Exact independent-use channels across the range both examples realize."""
    fidelity = np.linspace(2 / 3, 5 / 6, 240)
    phase_probability = 1.5 * (1 - fidelity)
    rate = (1 + phase_probability * np.log2(phase_probability)
            + (1 - phase_probability) * np.log2(1 - phase_probability))
    capture = 0.795393871822632  # Fixed-decoder mean reproduced by shutter-check.py
    p = 1.5 * (1 - capture)
    phase_rate = 1 + p * np.log2(p) + (1 - p) * np.log2(1 - p)

    fig, ax = plt.subplots(figsize=(5.5, 3.6), layout="constrained")
    ax.grid(axis="y", color=GRID)
    ax.set_axisbelow(True)
    ax.axvline(100 * capture, color=MUTED, lw=1.1, ls=":")
    ax.plot(100 * fidelity, rate, color=TEAL, lw=2.5, label="Random phase flips")
    ax.plot(100 * fidelity, np.zeros_like(rate), color=RUST, lw=2.5,
            ls="--", label="One output of a noisy copier")
    for value, color, shape in [(phase_rate, TEAL, "o"), (0, RUST, "s")]:
        ax.scatter(100 * capture, value, color=color, marker=shape, s=44, zorder=3)
        ax.annotate(f"{value:.3f}" if value else "0", (100 * capture, value),
                    xytext=(7, -10 if value else 7), textcoords="offset points",
                    color=color, weight="bold")
    ax.set(xlim=(66, 84), ylim=(-.018, .21), yticks=[0, .05, .10, .15, .20],
           xticks=[67, 71, 75, 100 * capture, 83], xticklabels=["67", "71", "75", "79.54", "83"],
           xlabel="Average fidelity in one use (%)", ylabel="Unassisted rate (qubits per use)")
    ax.legend(loc="upper left", frameon=False, fontsize=10.5)
    save(fig, "shutter-same-fidelity")


if __name__ == "__main__":
    shutter()
    axis_span()
    clock()
    variance()
    third_direction()
    clock_quarter_turn()
    bond_pairs()
    matching_receiver()
    same_fidelity()
