import json
from pathlib import Path

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

root = Path(__file__).resolve().parents[1]/"outputs"
hw = json.loads((root/"Period299-hybrid-hardware.json").read_text())
sim = json.loads((root/"Period299-hybrid-simulator.json").read_text())
print(hw["backend"], hw["job_id"], hw.get("metrics",{}).get("usage"), hw["estimate_s"])
print("CZ", [x["two_qubit_gates"] for x in hw["compiled"]])
print("depth", [x["two_qubit_depth"] for x in hw["compiled"]])
print("queues", {k:v["pending_jobs"] for k,v in hw["queues"].items()})
lags = np.arange(1,64)
for rec in (sim,hw):
    a = rec["analysis"]
    print({k:v for k,v in a.items() if "by_lag" not in k})
    for arm in ("ordered","shuffled"):
        spectrum = []
        for row in rec["rows"]:
            if row["arm"] == arm:
                phase = np.repeat([int(k,2)+row["offset"] for k in row["counts"]],list(row["counts"].values()))
                assert len(phase)==256
                spectrum.append(np.exp(2j*np.pi*np.outer(phase,lags)/64).mean(axis=0).real)
        assert np.allclose(np.mean(spectrum,axis=0),a[arm+"_by_lag"])
fig, axes = plt.subplots(2,1,sharex=True,sharey=True,figsize=(8.8,5.2),layout="constrained")
for ax, rec, name in zip(axes,(sim,hw),("Ideal simulator",hw["backend"])):
    a = rec["analysis"]
    ax.axhline(0,color="#818990",linewidth=.7)
    ax.axvline(33,color="#737c83",ls=":",lw=.9)
    for arm, col in (("shuffled","#b57156"),("ordered","#18648d")):
        ax.plot(lags,a[arm+"_by_lag"],marker="o",ms=2.7,lw=1.25,color=col,label=arm.capitalize())
    ax.set(ylabel="Correlation",title=name)
axes[0].legend(loc="upper right",frameon=False,ncol=2)
axes[-1].set(xlabel="Spacing in the table (one step advances the exponent by four)",
             xticks=[1,8,16,24,33,40,48,56,63],xlim=(0,64))
fig.savefig(root/"Period299-spacing.png",dpi=160)
