import numpy as np

from common import before_last_h, input_probabilities, rounded, simon_function
from qsim import H, apply_single

n, secret = 3, 0b110
f = simon_function(secret, n, np.random.default_rng(42))
state = before_last_h(f, n)


def finish(state):
    for q in range(n):
        state = apply_single(state, H, q)
    return input_probabilities(state, n)


# Sans mesurer le registre de sortie
without = finish(state)

# En le mesurant : chaque résultat y possible, pondéré par sa probabilité
blocks = state.reshape(2**n, 2**n)  # lignes : x, colonnes : y
with_measure = np.zeros(2**n)
for y in range(2**n):
    p_y = float(np.sum(np.abs(blocks[:, y]) ** 2))
    if p_y > 1e-12:
        collapsed = np.zeros_like(blocks)
        collapsed[:, y] = blocks[:, y] / np.sqrt(p_y)
        with_measure += p_y * finish(collapsed.reshape(-1))

print("sans mesure :", rounded(without))
print("avec mesure :", rounded(with_measure))
print("identiques :", np.allclose(without, with_measure))
