"""Learning: ideal p=1 QAOA on a four-cycle, not a research replication.
Run: python qaoa-maxcut.py (NumPy required). No network or hosted jobs.
Basis |q0 q1 q2 q3>, q0 leftmost. Cost U_C=exp(-i gamma C),
C=sum_edges (I-ZuZv)/2. Background: arXiv:1411.4028.
"""
import json
import math
import numpy as np

EDGES = ((0, 1), (1, 2), (2, 3), (3, 0))
BITS = [format(i, "04b") for i in range(16)]
CUTS = np.array([sum(b[u] != b[v] for u, v in EDGES) for b in BITS])


def state(gamma, beta):
    # H on each zero qubit, diagonal cost, then Rx(2 beta) per wire.
    psi = np.exp(-1j * gamma * CUTS) / 4
    rx = np.array([[math.cos(beta), -1j * math.sin(beta)],
                   [-1j * math.sin(beta), math.cos(beta)]])
    mixer = rx
    for _ in range(3):
        mixer = np.kron(mixer, rx)
    return mixer @ psi


def mean_cut(gamma, beta):
    return float(np.abs(state(gamma, beta)) ** 2 @ CUTS)


def qasm(gamma=math.pi / 4, beta=math.pi / 8):
    lines = ['OPENQASM 2.0;', 'include "qelib1.inc";',
             'qreg q[4];', 'creg c[4];']
    lines += [f'h q[{i}];' for i in range(4)]
    for u, v in EDGES:
        # CNOT-Rz(-gamma)-CNOT implements U_C up to global phase.
        lines += [f'cx q[{u}],q[{v}];', f'rz({-gamma:.17g}) q[{v}];',
                  f'cx q[{u}],q[{v}];']
    lines += [f'rx({2 * beta:.17g}) q[{i}];' for i in range(4)]
    return '\n'.join(lines + ['measure q -> c;', ''])


def run():
    # Tiny deterministic landscape, not a scalable optimizer.
    candidates = [(mean_cut(g, b), g, b)
                  for g in np.linspace(0, math.pi / 2, 9)
                  for b in np.linspace(0, math.pi / 4, 9)]
    value, gamma, beta = max(candidates)
    probs = np.abs(state(gamma, beta)) ** 2
    counts = np.random.default_rng(7).multinomial(4096, probs / probs.sum())
    analytical = 2 + math.sin(4 * beta) * math.sin(2 * gamma)
    return {"gamma": gamma, "beta": beta, "search_statevector_evaluations": len(candidates),
            "final_statevector_evaluations": 1, "sampling_batches": 1, "shots": 4096,
            "backend": "local_numpy_statevector", "seed": 7,
            "analytical_mean_cut": analytical, "ideal_minus_analytical": value - analytical,
            "selected_circuit_openqasm": qasm(gamma, beta),
            "ideal_mean_cut": value, "classical_max_cut": int(CUTS.max()),
            "ideal_optimal_cut_probability": float(probs[CUTS == 4].sum()),
            "sample_mean_cut": float(counts @ CUTS / counts.sum()),
            "counts_q0_first": dict(zip(BITS, map(int, counts)))}


if __name__ == "__main__":
    print(json.dumps(run(), indent=2))
