import math

from qiskit_ibm_runtime.fake_provider import FakeFez

from common import SHOTS, ghz, transpile_for

backend = FakeFez()
target = backend.target
isa = transpile_for(backend, ghz(4), level=1)

# Probabilité qu'aucune instruction ne se trompe : produit des (1 - erreur) de la calibration
survive = {"lecture": 1.0, "portes à 1 qubit": 1.0, "portes à 2 qubits": 1.0}
for instruction in isa.data:
    name = instruction.operation.name
    if name == "barrier":
        continue
    qubits = tuple(isa.find_bit(q).index for q in instruction.qubits)
    error = target[name][qubits].error or 0.0  # rz est virtuelle : erreur nulle
    if name == "measure":
        key = "lecture"
    elif len(qubits) == 2:
        key = "portes à 2 qubits"
    else:
        key = "portes à 1 qubit"
    survive[key] *= 1 - error

total = 1.0
for key, p in survive.items():
    total *= p
    print(f"Aucune erreur de {key:<17} : {p:.3f}")
print(f"Estimation, tout compris          : {total:.3f}")
# Écart-type d'un taux mesuré sur SHOTS shots : ce qu'on peut attendre du seul hasard
print(f"Hasard de {SHOTS} shots sur ce taux : ± {math.sqrt(total * (1 - total) / SHOTS):.3f}")

# La relaxation : durée du circuit face aux temps T1 et T2 des qubits choisis
for q in isa.layout.final_index_layout():
    props = backend.qubit_properties(q)
    print(f"Qubit {q} : T1 = {props.t1 * 1e6:.0f} µs, T2 = {props.t2 * 1e6:.0f} µs")
print("Durée du circuit :", round(isa.estimate_duration(target, unit="u"), 2), "µs")
