"""Plot each cell's observed live fraction and verify it from the raw counts."""
import json
from pathlib import Path

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

ROOT=Path(__file__).resolve().parent


def main():
    sim,hw=[json.loads((ROOT/f"Rule90-{label}.json").read_text()) for label in ("simulator","hardware")]
    n=19
    ideal=1<<(n//2)
    maps=[[],[]]
    for g in range(9):
        expected=np.array([(ideal>>i)&1 for i in range(n)])
        for values,rec in zip(maps,(sim,hw)):
            counts={int(k,2):v for k,v in rec["counts"][g].items()}
            shots=sum(counts.values())
            assert shots==256
            ones=np.array([sum(v for word,v in counts.items() if word&(1<<i)) for i in range(n)])
            row=rec["rows"][g]
            assert row["live_counts"]==ones.tolist() and row["expected"]==expected.tolist()
            assert row["exact_row_shots"]==counts.get(ideal,0)
            values.append(ones/shots)
            if rec is hw:
                wrong=np.where((2*ones-shots)*(2*expected-1)<=0)[0]-(n//2)
                print(g,"exact",row["exact_row_shots"],"majority misses/ties",wrong.tolist(),
                      "expected-live observed %.1f%%"%(100*ones[expected==1].mean()/shots),
                      "expected-dead observed live %.1f%%"%(100*ones[expected==0].mean()/shots))
        ideal=((ideal<<1)^(ideal>>1))&((1<<n)-1)
    print("g8 edge counts",hw["rows"][-1]["live_counts"][1::16])
    print(hw["backend"],hw["job_id"],hw["metrics"]["usage"]["qpu_charge_time_seconds"],
          {k:s["pending_jobs"] for k,s in hw["queues"].items()})
    cmap=LinearSegmentedColormap.from_list("live",["#f4f5ef","#b6dacf","#489993","#165968","#10334b"])
    fig,axes=plt.subplots(1,2,figsize=(13,4.5),sharey=True)
    fig.subplots_adjust(left=.052,right=.983,bottom=.29,top=.81,wspace=.08)
    for ax,data,title in zip(axes,maps,("Ideal simulator",hw["backend"])):
        im=ax.imshow(data,cmap=cmap,vmin=0,vmax=1,aspect="equal",interpolation="nearest",
                     extent=(-9.5,9.5,8.5,-.5))
        ax.set(xticks=np.arange(-8,9,2),yticks=range(9),xlabel="Cell position relative to the seed",title=title)
        ax.set_xticks(np.arange(-9.5,10),minor=True)
        ax.set_yticks(np.arange(-.5,9),minor=True)
        ax.grid(which="minor",color="white",linewidth=.55)
        ax.tick_params(which="minor",length=0)
    axes[0].set_ylabel("Generation")
    fig.suptitle("Rule 90 from one live cell",fontsize=19,y=.97)
    cax=fig.add_axes([.32,.12,.36,.032])
    bar=fig.colorbar(im,cax=cax,orientation="horizontal",ticks=[0,.25,.5,.75,1])
    bar.ax.set_xticklabels(["0%","25%","50%","75%","100%"])
    bar.set_label("Shots in which the cell was alive")
    fig.savefig(ROOT/"Rule90-triangle.png",dpi=185,bbox_inches="tight",pad_inches=.18)
    plt.close(fig)


if __name__=="__main__":
    main()
