# Une erreur cohérente s'accumule plus vite qu'une erreur de Pauli aléatoire
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit_aer.noise import pauli_error
from qiskit_aer.primitives import SamplerV2 as AerSampler

EPSILON = 0.05  # sur-rotation de chaque porte X, en radians
P_FLIP = np.sin(EPSILON / 2) ** 2  # même probabilité d'erreur pour une seule porte
SHOTS = 20_000
counts_n = [2, 10, 20, 40]

coherent = []
pauli_circuits = []
for n in counts_n:
    # erreur cohérente : chaque X est en fait une rotation de pi + epsilon
    qc = QuantumCircuit(1)
    for _ in range(n):
        qc.rx(np.pi + EPSILON, 0)
    coherent.append(float(Statevector(qc).probabilities()[1]))
    # erreur de Pauli : chaque X est parfaite, suivie d'un X parasite avec la probabilité P_FLIP
    qc = QuantumCircuit(1)
    for _ in range(n):
        qc.x(0)
        qc.append(pauli_error([("X", P_FLIP), ("I", 1 - P_FLIP)]).to_instruction(), [0])
    qc.measure_all()
    pauli_circuits.append(qc)

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

print(f"erreur d'une seule porte : {P_FLIP:.5f}")
print("portes   P(erreur) cohérente   P(erreur) Pauli")
for n, p_coherent, res in zip(counts_n, coherent, results):
    p_pauli = res.data.meas.get_counts().get("1", 0) / SHOTS  # n pair : sans erreur, on lit 0
    print(f"{n:>5}    {p_coherent:.4f}                {p_pauli:.4f}")

# Les deux formules, pour 40 portes
n = 40
coherent_formula = np.sin(n * EPSILON / 2) ** 2
pauli_formula = (1 - (1 - 2 * P_FLIP) ** n) / 2
print(f"40 portes, formules : cohérente {coherent_formula:.4f}, Pauli {pauli_formula:.4f}, n·p {n * P_FLIP:.4f}")
