from qiskit.quantum_info import hellinger_fidelity
from qiskit_ibm_runtime.fake_provider import FakeFez

from common import IDEAL, SHOTS, ghz, noisy_sampler, success, transpile_for

backend = FakeFez()
isa = transpile_for(backend, ghz(4), level=1)
counts = noisy_sampler(backend).run([isa], shots=SHOTS).result()[0].data.meas.get_counts()

print("Attendus :", {key: counts.get(key, 0) for key in sorted(IDEAL)})
others = {key: value for key, value in counts.items() if key not in IDEAL}
print("Autres   :", sum(others.values()), "shots sur", len(others), "chaînes")


def distance(key):
    """Nombre de bits à changer pour retomber sur 0000 ou 1111."""
    ones = key.count("1")
    return min(ones, len(key) - ones)


one_bit = sum(value for key, value in others.items() if distance(key) == 1)
print("  dont à 1 bit d'un résultat attendu :", one_bit)
print("Taux de succès :", round(success(counts), 3))
print("Fidélité :", round(hellinger_fidelity(counts, IDEAL), 3))
