"""Learning: noncommuting time evolution H=(X+Z)/sqrt(2), not a replication.
Run: python hamiltonian-simulation.py (NumPy required). No network/jobs.
Units hbar=1; dimensionless time; initial |0>. Chronological Rx then Rz.
Background: Lloyd (1996), doi:10.1126/science.273.5278.1073.
"""
import json
import math
import numpy as np

I = np.eye(2, dtype=complex)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Z = np.diag([1, -1]).astype(complex)
H = (X + Z) / math.sqrt(2)
INITIAL = np.array([1, 0], dtype=complex)


def trotter_state(steps, time=math.pi / 2):
    if type(steps) is not int or steps <= 0:
        raise ValueError("steps must be a positive integer")
    a = time / (math.sqrt(2) * steps)
    ux = math.cos(a) * I - 1j * math.sin(a) * X
    uz = math.cos(a) * I - 1j * math.sin(a) * Z
    return np.linalg.matrix_power(uz @ ux, steps) @ INITIAL


def exact_state(time=math.pi / 2):
    # H^2=I, so this exponential is exact for this particular Hamiltonian.
    return (math.cos(time) * I - 1j * math.sin(time) * H) @ INITIAL


def qasm(steps=4, time=math.pi / 2):
    if type(steps) is not int or steps <= 0:
        raise ValueError("steps must be a positive integer")
    angle = math.sqrt(2) * time / steps
    lines = ['OPENQASM 2.0;', 'include "qelib1.inc";', 'qreg q[1];', 'creg c[1];']
    for _ in range(steps):
        lines += [f'rx({angle:.17g}) q[0];', f'rz({angle:.17g}) q[0];']
    return '\n'.join(lines + ['measure q -> c;', ''])


def run():
    time = math.pi / 2
    exact = exact_state(time)
    rng = np.random.default_rng(7)
    rows = []
    for steps in (1, 2, 4, 8, 16, 32):
        psi = trotter_state(steps, time)
        probs = np.abs(psi) ** 2
        counts = rng.multinomial(4096, probs / probs.sum())
        rows.append({"steps": steps, "ideal_probability_1": float(probs[1]),
                     "sampled_probability_1": int(counts[1]) / 4096,
                     "counts": {"0": int(counts[0]), "1": int(counts[1])},
                     "state_infidelity": max(0.0, float(1 - abs(np.vdot(exact, psi)) ** 2))})
    return {"time": time, "shots_per_circuit": 4096, "sampling_batches": 6,
            "total_shots": 24576, "seed": 7, "backend": "local_numpy_statevector",
            "exact_probability_1": float(abs(exact[1]) ** 2), "product_formula": rows}


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