# Déphasage T2 : on prépare |+⟩, on attend, on applique H, puis on lit
import numpy as np
from qiskit import QuantumCircuit
from qiskit_aer.noise import thermal_relaxation_error
from qiskit_aer.primitives import SamplerV2 as AerSampler

T1 = 100e-6  # 100 µs
T2 = 80e-6  # 80 µs
SHOTS = 4000
waits_us = [0, 25, 50, 100, 200, 400]

circuits = []
for wait in waits_us:
    qc = QuantumCircuit(1)
    qc.h(0)  # on prépare |+⟩, sur l'équateur de la sphère de Bloch
    if wait > 0:
        qc.append(thermal_relaxation_error(T1, T2, wait * 1e-6).to_instruction(), [0])
    qc.h(0)  # sans bruit, H ramène |+⟩ sur |0⟩ : on devrait toujours lire 0
    qc.measure_all()
    circuits.append(qc)

results = AerSampler(seed=42).run(circuits, shots=SHOTS).result()

print("attente   P(0) mesurée   (1 + exp(-t/T2)) / 2")
for wait, res in zip(waits_us, results):
    p0 = res.data.meas.get_counts().get("0", 0) / SHOTS
    expected = (1 + np.exp(-wait * 1e-6 / T2)) / 2
    print(f"{wait:>4} µs   {p0:.3f}          {expected:.3f}")

# Le déphasage pur caché dans ce couple : 1/T2 = 1/(2·T1) + 1/Tφ, donc 1/Tφ = 1/T2 - 1/(2·T1)
t_phi = 1 / (1 / T2 - 1 / (2 * T1))
print(f"Tφ = {t_phi * 1e6:.1f} µs")
