"""Finite ideal fSim benchmarks. Run with Python 3, NumPy and SciPy.

Site zero is the least significant bit. Odd-start bonds act first, including
the periodic seam. Positive quasiphases mean eigenvalues exp(+i * phase).
All examples are synthetic calculations, not fits to hardware data.
"""
from itertools import combinations

import numpy as np
from scipy.linalg import schur


THETA = np.pi / 6
PHI = 2 * np.pi / 3


def mask(sites):
    return sum(1 << site for site in sites)


def particle_count(state):
    return bin(state).count("1")


def basis_sectors(sites, particles):
    return sorted(mask(state) for state in combinations(range(sites), particles))


class Layer:
    """Precompute disjoint two-site basis pairs for each gate in time order."""

    def __init__(self, basis, bonds, theta, phi):
        index = {state: row for row, state in enumerate(basis)}
        self.gates = []
        self.cosine = np.cos(theta)
        self.hop = 1j * np.sin(theta)
        self.phase = np.exp(1j * phi)
        for a, b in bonds:
            left, right, doubles = [], [], []
            for row, state in enumerate(basis):
                first, second = (state >> a) & 1, (state >> b) & 1
                if first and second:
                    doubles.append(row)
                elif first:
                    left.append(row)
                    right.append(index[state ^ (1 << a) ^ (1 << b)])
            self.gates.append(tuple(np.asarray(x, dtype=int) for x in (left, right, doubles)))

    def apply(self, amplitudes):
        for left, right, doubles in self.gates:
            old_left, old_right = amplitudes[left], amplitudes[right]
            amplitudes[left] = self.cosine * old_left + self.hop * old_right
            amplitudes[right] = self.hop * old_left + self.cosine * old_right
            amplitudes[doubles] *= self.phase


def ring_layers(basis, length):
    return [Layer(basis, [(j, (j + 1) % length) for j in range(start, length, 2)],
                  THETA, PHI) for start in (1, 0)]


def step(amplitudes, layers):
    for layer in layers:
        layer.apply(amplitudes)


def calibration_and_noise():
    gate = np.eye(4, dtype=complex)
    Layer(list(range(4)), [(0, 1)], THETA, PHI).apply(gate)
    eta = np.arccosh(np.sin(PHI/2) / np.sin(THETA))
    spectral = np.arccos(np.cos(PHI/2) / np.cos(THETA))
    checked_r = np.eye(4, dtype=complex)
    checked_r[1:3, 1:3] = (
        np.sinh(eta) * np.eye(2) + 1j*np.sin(spectral)*np.array([[0, 1], [1, 0]])
    ) / np.sinh(eta + 1j*spectral)
    rotations = np.diag(np.exp(1j * PHI/2 * np.array([0, 1, 1, 2])))
    np.testing.assert_allclose(gate, rotations @ checked_r, atol=1e-14)

    flip, survival = 0.02, 0.90
    qubit_z = np.diag([1, -1])
    plus = np.array([0, 1, 1, 0]) / np.sqrt(2)
    minus = np.array([0, 1, -1, 0]) / np.sqrt(2)
    rho = np.outer(plus, plus)
    for _ in range(8):
        rho = gate @ rho @ gate.conj().T
        for z in (np.kron(qubit_z, np.eye(2)), np.kron(np.eye(2), qubit_z)):
            rho = (1-flip)*rho + flip*z@rho@z
    pre_readout = np.array([1-survival, survival*(minus@rho@minus).real,
                            survival*(plus@rho@plus).real, 0])
    assign = np.array([[0.99, 0.04], [0.01, 0.96]])
    detector = np.kron(assign, assign)
    report = detector @ pre_readout
    np.testing.assert_allclose(np.linalg.solve(detector, report), pre_readout, atol=1e-14)
    accepted = report[1:3].sum()
    score = report[2]-report[1]
    print("Readout: acceptance, raw charge, conditional charge", accepted, score, score/accepted)


def preparation():
    length, error = 8, 0.025
    basis = list(range(1 << length))
    target = mask(range(length // 2))
    wrong_sites = np.array([particle_count(target ^ s) for s in basis])
    probabilities = error ** wrong_sites * (1 - error) ** (length - wrong_sites)
    imbalance = np.array([(particle_count(s & target) - particle_count(s >> 4)) / 4 for s in basis])
    layers = ring_layers(basis, length)
    columns = np.eye(len(basis), dtype=complex)
    print("Preparation: cycles, clean imbalance, noisy imbalance")
    for n in range(9):
        if n in (0, 1, 3, 8):
            observed = imbalance @ (abs(columns) ** 2)
            print(n, observed[target], observed @ probabilities)
        if n < 8:
            step(columns, layers)
    np.testing.assert_allclose(probabilities.sum(), 1)
    np.testing.assert_allclose(np.sum(abs(columns) ** 2, axis=0), 1, atol=1e-13)


def momentum_columns(basis, length, k):
    index = {s: j for j, s in enumerate(basis)}
    seen, columns = set(), []
    for state in basis:
        if state in seen:
            continue
        orbit, current = [], state
        while current not in seen:
            seen.add(current)
            orbit.append(current)
            current = ((current << 2) & ((1 << length) - 1)) | (current >> (length - 2))
        if abs(np.exp(1j * k * len(orbit)) - 1) > 1e-10:
            continue
        vector = np.zeros(len(basis), dtype=complex)
        vector[[index[s] for s in orbit]] = np.exp(-1j * k * np.arange(len(orbit))) / np.sqrt(len(orbit))
        columns.append(vector)
    return np.column_stack(columns)


def pair_band(verbose=True):
    length, ntime = 12, 128
    basis = basis_sectors(length, 2)
    index = {s: j for j, s in enumerate(basis)}
    adjacent = [index[mask([j, (j + 1) % length])] for j in range(length)]
    layers = ring_layers(basis, length)
    unitary = np.eye(len(basis), dtype=complex)
    step(unitary, layers)
    np.testing.assert_allclose(unitary.conj().T @ unitary, np.eye(len(basis)), atol=1e-13)
    if verbose:
        print("Band: cell k/pi, pair weight, exact phase, measured FFT bin, sum of weights")
    spectra = []
    for m in range(length // 2):
        k = 2 * np.pi * m / (length // 2)
        cols = momentum_columns(basis, length, k)
        block = cols.conj().T @ unitary @ cols
        np.testing.assert_allclose(unitary @ cols, cols @ block, atol=1e-13)
        triangular, eigenvectors = schur(block, output="complex")
        values = np.diag(triangular)
        np.testing.assert_allclose(block @ eigenvectors, eigenvectors * values, atol=1e-12)
        weights = np.sum(abs((cols @ eigenvectors)[adjacent]) ** 2, axis=0)
        np.testing.assert_allclose(weights.sum(), 2, atol=1e-13)
        # Polarization average for the two intra-cell dimer positions.
        source = np.zeros((len(basis), 2), dtype=complex)
        for j in range(length):
            source[adjacent[j], j % 2] = np.exp(-1j * k * (j // 2)) / np.sqrt(length // 2)
        vectors = source.copy()
        trace = []
        for _ in range(ntime):
            trace.append(np.vdot(source, vectors) / 2)
            step(vectors, layers)
        spectral = (values[None, :] ** np.arange(ntime)[:, None]) @ weights / 2
        np.testing.assert_allclose(trace, spectral, atol=8e-13)
        transform = abs(np.fft.fft(trace * np.hanning(ntime)))
        bin_phases = np.angle(np.exp(2j * np.pi * np.arange(ntime) / ntime))
        spectra.append((k, bin_phases, transform, np.angle(values), weights))
        for idx in np.argsort(weights)[-2:][::-1]:
            phase = np.angle(values[idx])
            close = abs(np.angle(np.exp(1j * (bin_phases - phase)))) < 2.1 * np.pi / ntime
            local_peak = np.argmax(np.where(close, transform, -1))
            assert transform[local_peak] >= max(transform[(local_peak-1) % ntime],
                                                transform[(local_peak+1) % ntime])
            if verbose:
                print(f"{k/np.pi:.5f} {weights[idx]:.6f} {phase:.6f} {bin_phases[local_peak]:.6f} {weights.sum():.6f}")
    return spectra


def attached_ring():
    print("Stability: length, side angle/pi, period, main triple, any side occupation")
    for length in (8, 12):
        side = length // 2
        basis = basis_sectors(length + side, 3)
        index = {s: j for j, s in enumerate(basis)}
        triple = [index[mask([(j + a) % length for a in range(3)])] for j in range(length)]
        auxiliaries = [j for j, s in enumerate(basis) if s >> length]
        for ratio in (0, 1 / 24, 1 / 12):
            layers = ring_layers(basis, length)
            layers.append(Layer(basis, [(2 * j, length + j) for j in range(side)], np.pi * ratio, PHI))
            psi = np.zeros(len(basis), dtype=complex)
            psi[triple[0]] = 1
            for n in range(65):
                if n in (1, 16, 32, 64):
                    p = abs(psi) ** 2
                    np.testing.assert_allclose(p.sum(), 1, atol=1e-13)
                    print(length, f"{ratio:.5f}", n, f"{p[triple].sum():.8f}", f"{p[auxiliaries].sum():.8f}")
                if n < 64:
                    step(psi, layers)


if __name__ == "__main__":
    calibration_and_noise()
    preparation()
    pair_band()
    attached_ring()
