# Exercice 3 : retrouver T1 à partir des seuls counts
import numpy as np
from qiskit import QuantumCircuit
from qiskit_aer.noise import thermal_relaxation_error
from qiskit_aer.primitives import SamplerV2 as AerSampler

# La « machine » : un T1 qu'on fait semblant de ne pas connaître
HIDDEN_T1, HIDDEN_T2 = 120e-6, 90e-6
SHOTS = 4000
waits_us = np.array([10, 40, 80, 120, 160, 200])

circuits = []
for wait in waits_us:
    qc = QuantumCircuit(1)
    qc.x(0)
    qc.append(thermal_relaxation_error(HIDDEN_T1, HIDDEN_T2, wait * 1e-6).to_instruction(), [0])
    qc.measure_all()
    circuits.append(qc)
results = AerSampler(seed=42).run(circuits, shots=SHOTS).result()
p1 = np.array([res.data.meas.get_counts().get("1", 0) / SHOTS for res in results])

# P(1) = exp(-t/T1), donc ln P(1) = -t/T1 : une droite de pente -1/T1
slope, _ = np.polyfit(waits_us, np.log(p1), 1)
print("P(1) mesurées :", np.round(p1, 3).tolist())
print(f"T1 estimé : {-1 / slope:.0f} µs")
