import json
import math
from pathlib import Path

root=Path(__file__).resolve().parents[1]/"outputs"
h=json.loads((root/"Switch-puzzles-hardware.json").read_text())
m=json.loads((root/"Switch-puzzles-fresh-map.json").read_text())
print("backend",h["backend"],"queues",{k:v["pending_jobs"] for k,v in m["queues"].items()})
print("map",m["job_id"],m["metrics"]["usage"],m["analysis"]["mean_accuracy"])
print("puzzles",h["job_id"],h["metrics"]["usage"])
print(h["selected"],h["ranking"])
cells={}
for row,counts in zip(h["rows"],h["counts"]):
    key=h["solutions_ABC"][row["puzzle"]]
    hits=0
    for sample,count in counts.items():
        v=int(sample,2)
        decoded="".join(str((v>>i)&1) for i in (2,1,0))
        if decoded==key:
            hits+=count
    assert hits==row["correct"] and sum(counts.values())==256
    cells[(row["chain"],row["puzzle"],row["mode"])]=hits
print(sorted(cells.items()))


def contrast(groups1,groups2):
    terms=[]
    vs=[]
    for group in (groups1,groups2):
        values=[cells[k]/256 for k in group]
        terms.append(sum(values)/len(values))
        vs.append(sum(p*(1-p)/255 for p in values)/len(values)**2)
    d=terms[0]-terms[1]
    half=1.96*math.sqrt(sum(vs))
    return [round(100*x,2) for x in (terms[0],terms[1],d,d-half,d+half)]


print("pooled tele-direct",contrast([k for k in cells if k[2]=="teleport"],[k for k in cells if k[2]=="direct"]))
for mode in ("direct","teleport"):
    print(mode,"best-typical",contrast([k for k in cells if k[0]=="best" and k[2]==mode],
                                      [k for k in cells if k[0]=="typical" and k[2]==mode]))
for chain in ("best","typical"):
    print(chain,"tele-direct",contrast([k for k in cells if k[0]==chain and k[2]=="teleport"],
                                      [k for k in cells if k[0]==chain and k[2]=="direct"]))
