# Exercice 3 : estimer le point d'un état à partir de lectures seulement
import cmath

import numpy as np
from common import bloch_vector, h, rounded
from qsim.etape1_un_qubit import make_state, sample

secret = make_state(0.6, 0.8 * cmath.exp(1j))  # l'état « inconnu »


def shift(state, theta):
    """Fait tourner l'amplitude de |1⟩ seule de l'angle theta (une porte de phase, leçon 4.4)."""
    a, b = state
    return make_state(a, b * cmath.exp(1j * theta))


def estimate(state, shots, seed):
    """Lit l'état `shots` fois : (n0 - n1) / shots estime la coordonnée de l'axe lu."""
    counts = sample(state, shots, seed=seed)
    return (counts.get("0", 0) - counts.get("1", 0)) / shots


def estimate_point(state, shots, seed):
    x = estimate(h(state), shots, seed)  # h puis lecture : l'axe x
    y = estimate(h(shift(state, -np.pi / 2)), shots, seed + 1)  # rotation de -π/2, puis h : l'axe y
    z = estimate(state, shots, seed + 2)  # lecture directe : l'axe z
    return np.array([x, y, z])


exact = bloch_vector(secret)
print("point exact :", rounded(exact))
for shots in [200, 2000, 20000]:
    point = estimate_point(secret, shots, seed=1)
    one_series = np.max(np.abs(point - exact))
    # le même calcul sur 100 séries de shots, pour voir l'écart typique
    errors = [np.max(np.abs(estimate_point(secret, shots, seed=3 * k) - exact)) for k in range(100)]
    print(f"{shots:>6} shots par axe : {rounded(point)}   écart : {one_series:.3f}   écart moyen sur 100 séries : {np.mean(errors):.3f}")
