"""Learning: one-geometry ideal two-qubit H2 VQE, not a paper replication.
Run: python vqe-h2.py (NumPy required). No network or hosted jobs.
Corrected coefficients: O'Malley et al., arXiv:1512.06860v2, R=.75 Angstrom.
Order II, ZI, IZ, ZZ, XX, YY. Basis |q0 q1>, q0 leftmost.
"""
import json
import math
import numpy as np

I = np.eye(2, dtype=complex)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
Z = np.diag([1, -1]).astype(complex)
HAD = (X + Z) / math.sqrt(2)
CX = np.array([[1, 0, 0, 0], [0, 1, 0, 0],
               [0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex)
COEFF = (0.2252, 0.3435, -0.4347, 0.5716, 0.0910, 0.0910)


def state(theta):
    # X(q1), Ry(theta,q0), CX(q0,q1) from |00>.
    ry = np.array([[math.cos(theta / 2), -math.sin(theta / 2)],
                   [math.sin(theta / 2), math.cos(theta / 2)]])
    return CX @ np.kron(ry, I) @ np.array([0, 1, 0, 0], dtype=complex)


def basis_probabilities(theta, basis):
    # H maps X to Z; Rx(+pi/2) maps Y to Z.
    rotation = {"Z": I, "X": HAD, "Y": (I - 1j * X) / math.sqrt(2)}[basis]
    return np.abs(np.kron(rotation, rotation) @ state(theta)) ** 2


def energy(distributions):
    # Distribution order 00,01,10,11. One Z basis supplies three terms.
    z, x, y = (distributions[b] for b in ("Z", "X", "Y"))
    parity = np.array([1, -1, -1, 1])
    expectations = (1, z @ [1, 1, -1, -1], z @ [1, -1, 1, -1],
                    z @ parity, x @ parity, y @ parity)
    return float(np.dot(COEFF, expectations))


def objective(theta):
    # Ideal probabilities emulate infinitely many shots, not noisy executions.
    return energy({b: basis_probabilities(theta, b) for b in ("Z", "X", "Y")})


def measure(theta, rng, shots=4096):
    counts = {}
    for b in ("Z", "X", "Y"):
        p = basis_probabilities(theta, b)
        counts[b] = rng.multinomial(shots, p / p.sum())
    return energy({b: c / shots for b, c in counts.items()}), counts


def optimize(rng):
    # 13 coarse evaluations + 12 refinement evaluations. Cost uses counts only.
    history = []

    def evaluate(theta):
        value, counts = measure(theta, rng)
        history.append({"theta": theta, "measured_energy_hartree": value,
                        "counts_q0_first": {b: list(map(int, c)) for b, c in counts.items()}})
        return value, theta

    best = min(evaluate(-math.pi * k / 12) for k in range(13))
    step = math.pi / 12
    for _ in range(6):
        step /= 2
        center = best[1]
        left = evaluate(max(-math.pi, center - step))
        right = evaluate(min(0.0, center + step))
        best = min(best, left, right)
    return best[1], history


def qasm(theta=None, basis="Z"):
    if theta is None:
        # Analytical reference snapshot, distinct from the noisy search result.
        theta = math.atan2(0.1820, 0.7782) - math.pi
    # Fixed snapshot only; the Python optimizer is not embedded in this QASM.
    lines = ['OPENQASM 2.0;', 'include "qelib1.inc";', 'qreg q[2];',
             'creg c[2];', 'x q[1];', f'ry({theta:.17g}) q[0];', 'cx q[0],q[1];']
    if basis == "X":
        lines += ['h q[0];', 'h q[1];']
    elif basis == "Y":
        lines += ['rx(pi/2) q[0];', 'rx(pi/2) q[1];']
    elif basis != "Z":
        raise ValueError("basis must be Z, X or Y")
    return '\n'.join(lines + ['measure q -> c;', ''])


def run():
    rng = np.random.default_rng(7)
    theta, history = optimize(rng)
    # Fresh samples, independent of the search conditional on selected theta.
    final_energy, counts = measure(theta, rng)
    # Independent reference: diagonalize this rounded 4x4 Hamiltonian.
    operators = (np.eye(4), np.kron(Z, I), np.kron(I, Z),
                 np.kron(Z, Z), np.kron(X, X), np.kron(Y, Y))
    exact = float(np.linalg.eigvalsh(sum(c * p for c, p in zip(COEFF, operators)))[0])
    return {"theta": theta, "search_evaluations": len(history),
            "backend": "local_numpy_statevector", "seed": 7,
            "ideal_energy_at_selected_theta_hartree": objective(theta),
            "exact_rounded_model_energy_hartree": exact,
            "ideal_optimization_error_hartree": objective(theta) - exact,
            "fresh_sampled_energy_hartree": final_energy,
            "final_measurement_discrepancy_hartree": final_energy - objective(theta),
            "circuits": 3 * (len(history) + 1), "total_shots": 3 * (len(history) + 1) * 4096,
            "shots_per_basis": 4096,
            "search_history": history,
            "counts_q0_first": {b: dict(zip(("00", "01", "10", "11"), map(int, c)))
                                for b, c in counts.items()}}


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