"""Compare independent circuit shots. Effects use Marrakesh minus Fez."""
import json
from pathlib import Path

import numpy as np
from scipy.stats import fisher_exact, norm

root = Path(__file__).resolve().parents[1] / "outputs"
axes = ["X", "Y", "Z"]
shots = 256
rates = []
for name, chain in [("Fez", list(range(21, 27))), ("Marrakesh", list(range(3, 9)))]:
    record = json.loads((root / f"{name}-singlet-results.json").read_text())
    assert record["layout"] == chain and record["stage"] == "done" and record["setting_order"] == axes
    opposite = []
    for axis in axes:
        row = record["joint_counts"][axis]
        assert sum(row.values()) == shots and all(len(k) == 6 for k in row)
        correct = sum(n for k, n in row.items() if k[0] != k[-1])
        assert correct == record["expected_parity_counts"][axis]
        opposite.append(correct)
    p = np.array(opposite) / shots
    fidelity = (sum(p) - 1) / 2
    assert np.isclose(fidelity, record["fidelity"])
    print(name, opposite, p, fidelity, record["fidelity_sampling_se"], record["job_id"],
          record["metrics"]["usage"], record.get("readout_at_submission"))
    rates.append(p)

a, b = rates
diff = b - a
variance = (a * (1 - a) + b * (1 - b)) / (shots - 1)
for label, weights in [("fidelity difference", [.5, .5, .5]), ("change in Y-minus-Z", [0, 1, -1])]:
    estimate = diff @ weights
    se = (variance @ np.square(weights)) ** .5
    print(label, "effect, 95% interval, p", estimate, estimate + np.array([-1, 1])*norm.ppf(.975)*se,
          2*norm.sf(abs(estimate)/se))
pvalues = []
for x,y in zip(a,b):
    table = np.rint(np.array([[x,1-x],[y,1-y]])*shots).astype(int)
    pvalues.append(fisher_exact(table).pvalue)
order = np.argsort(pvalues)
holm = np.empty(3)
holm[order] = np.minimum(1, np.maximum.accumulate(np.array(pvalues)[order] * np.array([3,2,1])))
print("per axis differences",diff,"Fisher exact Holm adjusted",holm)
