# Données de la figure « le circuit de l'estimation de phase » : jamais affiché comme extrait.
# On exécute phase_estimation (common.py) comme l'extrait 04 (U ajoute 0,625 tour, cible |1>, t = 3) en enregistrant
# chaque opération qu'elle applique, dans l'ordre : le schéma reprend exactement l'algorithme du code.
import json

import numpy as np

import common
from qsim import ONE

phi, t = 0.625, 3
U = common.phase_gate(phi)
ops = []
original = {"single": common.apply_single, "controlled": common.apply_controlled, "qft": common.qft_matrix}


def record_single(state, gate, q):
    if not np.allclose(gate, common.H):
        raise ValueError("porte à un qubit inattendue dans phase_estimation")
    ops.append({"name": "h", "qubits": [q]})
    return original["single"](state, gate, q)


def record_controlled(state, gate, control, target):
    # Quelle puissance de U ? Pour φ = 0,625, U, U², …, U⁷ ont des phases toutes différentes.
    power = next(k for k in range(1, 2**t) if np.allclose(gate, np.linalg.matrix_power(U, k)))
    ops.append({"name": "controlled_u", "qubits": [control, target], "power": power})
    return original["controlled"](state, gate, control, target)


def record_qft(n):
    # phase_estimation applique la transposée conjuguée de cette matrice : la QFT inverse
    ops.append({"name": "qft_matrix", "size": n})
    return original["qft"](n)


common.apply_single = record_single
common.apply_controlled = record_controlled
common.qft_matrix = record_qft

common.phase_estimation(U, ONE, t)

print(json.dumps({"t": t, "phi": phi, "target": t, "ops": ops}, ensure_ascii=False))
