import numpy as np

from qsim.etape3_plusieurs_qubits import H, apply_single, num_qubits


def readable(size):
    """Une taille en octets, avec l'unité binaire qui convient (Kio, Mio, Gio…)."""
    for unit in ("o", "Kio", "Mio", "Gio", "Tio", "Pio", "Eio"):
        if size < 1024:
            return f"{size:.0f} {unit}"
        size /= 1024
    return f"{size:.0f} Zio"


# Exercice 3 : ce que coûte votre simulateur, en mémoire (16 octets par nombre complexe)
for n in (10, 20, 30):
    state_bytes = 2**n * 16       # le vecteur d'état : 2^n amplitudes
    matrix_bytes = 4**n * 16      # la matrice complète, si apply_single la construit : 2^n x 2^n
    print(f"{n} qubits : état {readable(state_bytes)}, matrice complète {readable(matrix_bytes)}")


def apply_single_reshape(state, gate, target):
    """Applique une porte à un qubit sans construire la matrice complète."""
    n = num_qubits(state)
    tensor = state.reshape([2] * n)                        # un axe par qubit, le qubit 0 en premier
    tensor = np.tensordot(gate, tensor, axes=([1], [target]))  # la porte agit sur l'axe du qubit cible
    tensor = np.moveaxis(tensor, 0, target)                # on remet l'axe à sa place
    return tensor.reshape(-1)


rng = np.random.default_rng(42)
state = rng.normal(size=8) + 1j * rng.normal(size=8)
state /= np.linalg.norm(state)
same = all(np.allclose(apply_single_reshape(state, H, q), apply_single(state, H, q)) for q in range(3))
print("même résultat qu'apply_single sur 3 qubits :", same)
