"""Computational physics laboratory. Author: GPT. Requires Python 3.10+ and NumPy.

Run: python computational_physics_lab.py
These small, original teaching implementations favor inspectability over speed.
Units are dimensionless unless a function states otherwise.
"""
import json
import math
import numpy as np


def trapezoid(f, a, b, n):
    if n < 1:
        raise ValueError("n must be positive")
    x = np.linspace(a, b, n + 1)
    y = np.asarray(f(x))
    return (b - a) / n * (y.sum() - 0.5 * (y[0] + y[-1]))


def simpson(f, a, b, n):
    if n < 2 or n % 2:
        raise ValueError("Simpson requires a positive even number of intervals")
    y = np.asarray(f(np.linspace(a, b, n + 1)))
    return (b - a) / (3 * n) * (
        y[0] + y[-1] + 4 * y[1:-1:2].sum() + 2 * y[2:-1:2].sum())


def trap2d(f, n):
    """Tensor-product trapezoid on [0,1]^2, including edge/corner weights."""
    x = np.linspace(0, 1, n + 1)
    w = np.ones(n + 1)
    w[[0, -1]] = 0.5
    return np.sum(f(x[:, None], x[None, :]) * w[:, None] * w[None, :]) / n**2


def mc_integral(n=100_000, seed=20261106):
    """Integral of exp(-x), x in [0,1], with an iid standard error."""
    rng = np.random.default_rng(seed)
    values = np.exp(-rng.random(n))
    return float(values.mean()), float(values.std(ddof=1) / np.sqrt(n))


def rk4_step(rhs, t, y, dt):
    k1 = rhs(t, y)
    k2 = rhs(t + dt / 2, y + dt * k1 / 2)
    k3 = rhs(t + dt / 2, y + dt * k2 / 2)
    k4 = rhs(t + dt, y + dt * k3)
    return y + dt * (k1 + 2 * k2 + 2 * k3 + k4) / 6


def oscillator(method="verlet", dt=0.05, duration=20.0):
    """q''=-q, q(0)=1, v(0)=0. Return t, q, v, energy."""
    steps = round(duration / dt)
    dt = duration / steps
    q, v = 1.0, 0.0
    rows = [(0.0, q, v, 0.5)]
    for i in range(steps):
        if method == "euler":
            q, v = q + dt * v, v - dt * q
        elif method == "cromer":
            v -= dt * q
            q += dt * v
        elif method == "verlet":
            v -= 0.5 * dt * q
            q += dt * v
            v -= 0.5 * dt * q
        elif method == "rk4":
            q, v = rk4_step(lambda t, y: np.array([y[1], -y[0]]),
                           i * dt, np.array([q, v]), dt)
        else:
            raise ValueError(method)
        rows.append(((i + 1) * dt, q, v, (q * q + v * v) / 2))
    return np.asarray(rows)


def bisect(f, a, b, xtol=1e-10, maxiter=200):
    fa, fb = f(a), f(b)
    if not np.isfinite([fa, fb]).all():
        raise ValueError("nonfinite endpoint")
    if fa == 0:
        return a
    if fb == 0:
        return b
    if np.signbit(fa) == np.signbit(fb):
        raise ValueError("a continuous sign bracket is required")
    for _ in range(maxiter):
        m = a + (b - a) / 2
        fm = f(m)
        if not np.isfinite(fm):
            raise ValueError("nonfinite value inside bracket")
        if fm == 0 or (b - a) / 2 <= xtol:
            return m
        if np.signbit(fa) != np.signbit(fm):
            b = m
        else:
            a, fa = m, fm
    raise RuntimeError("bisection did not converge")


def numerov(q, h, y0, y1):
    """Uniform-grid homogeneous y''=-q(x)y; caller supplies two start values."""
    q = np.asarray(q, dtype=float)
    y = np.zeros_like(q)
    y[0], y[1] = y0, y1
    for j in range(1, len(q) - 1):
        y[j + 1] = (2 * (1 - 5 * h*h * q[j] / 12) * y[j]
                    - (1 + h*h * q[j - 1] / 12) * y[j - 1]) / (
                        1 + h*h * q[j + 1] / 12)
    return y


def tridiagonal(lower, diagonal, upper, rhs):
    """Thomas elimination without pivoting: used here only for safe SPD systems."""
    a, b, c, d = [np.array(v, dtype=float, copy=True)
                  for v in (lower, diagonal, upper, rhs)]
    for j in range(1, len(b)):
        if abs(b[j - 1]) < 1e-14:
            raise ValueError("small pivot; use a pivoted solver")
        multiplier = a[j - 1] / b[j - 1]
        b[j] -= multiplier * c[j - 1]
        d[j] -= multiplier * d[j - 1]
    if abs(b[-1]) < 1e-14:
        raise ValueError("small last pivot")
    x = np.empty_like(d)
    x[-1] = d[-1] / b[-1]
    for j in range(len(b) - 2, -1, -1):
        x[j] = (d[j] - c[j] * x[j + 1]) / b[j]
    return x


def heat(n=40, dt=0.001, duration=0.1, method="cn"):
    """u_t=u_xx, 0<x<1, zero endpoints, u(x,0)=sin(pi*x)."""
    x = np.linspace(0, 1, n + 1)
    u = np.sin(np.pi * x)
    u[[0, -1]] = 0
    steps = math.ceil(duration / dt)
    dt = duration / steps
    r = dt * n*n
    if method == "explicit" and r > 0.5:
        raise ValueError("explicit diffusion requires r <= 0.5")
    for _ in range(steps):
        if method == "explicit":
            u[1:-1] += r * (u[2:] - 2 * u[1:-1] + u[:-2])
        elif method == "cn":
            rhs = (1 - r) * u[1:-1] + r / 2 * (u[:-2] + u[2:])
            u[1:-1] = tridiagonal(np.full(n - 2, -r / 2),
                                  np.full(n - 1, 1 + r),
                                  np.full(n - 2, -r / 2), rhs)
        else:
            raise ValueError(method)
    exact = np.exp(-np.pi**2 * duration) * np.sin(np.pi * x)
    return x, u, float(np.max(np.abs(u - exact)))


def harmonic_states(n=240, length=8.0):
    """H=-1/2 d²/dx²+x²/2; n interior points, Dirichlet at +/-length."""
    h = 2 * length / (n + 1)
    x = np.linspace(-length + h, length - h, n)
    H = np.diag(1 / h**2 + x*x / 2)
    H += np.diag(np.full(n - 1, -0.5 / h**2), 1)
    H += np.diag(np.full(n - 1, -0.5 / h**2), -1)
    energies, vectors = np.linalg.eigh(H)
    return x, energies[:4], vectors[:, :4] / np.sqrt(h)


def cosine_bands(k, cutoff=5, amplitude=0.2, period=2*np.pi):
    """V(x)=amplitude*cos(2*pi*x/period), hbar=m=1."""
    G = 2 * np.pi * np.arange(-cutoff, cutoff + 1) / period
    H = np.diag(0.5 * (k + G)**2)
    H += np.diag(np.full(len(G) - 1, amplitude / 2), 1)
    H += np.diag(np.full(len(G) - 1, amplitude / 2), -1)
    return np.linalg.eigvalsh(H)


def barrier(E=0.5, height=1.0, width=1.0):
    """Single finite barrier; equal masses/leads, hbar=m=1, E>0, E!=height.

    [psi,psi'] on the right equals P times [psi,psi'] on the left.
    Suitable for moderate thickness; thick evanescent barriers need scattering methods.
    """
    if E <= 0 or abs(E - height) < 1e-12:
        raise ValueError("require E>0 and E different from the barrier height")
    k = np.sqrt(2 * E)
    q = np.sqrt(2 * complex(E - height))
    P = np.array([[np.cos(q*width), np.sin(q*width)/q],
                  [-q*np.sin(q*width), np.cos(q*width)]])
    incoming = np.array([1, 1j*k])
    reflected = np.array([1, -1j*k])
    # Right-going transmitted amplitude is defined at the right interface.
    r, t = np.linalg.solve(np.column_stack((P @ reflected, -incoming)),
                           -P @ incoming)
    return float(abs(r)**2), float(abs(t)**2)


def lj_force(positions, box, cutoff=2.5):
    """Force-shifted LJ, reduced units, orthorhombic cubic periodic box."""
    if cutoff >= box / 2:
        raise ValueError("cutoff must be less than half the box length")
    positions = np.asarray(positions)
    forces = np.zeros_like(positions)
    energy, virial = 0.0, 0.0
    uc = 4 * (cutoff**-12 - cutoff**-6)
    fc = 24 * (2 * cutoff**-13 - cutoff**-7)
    for i in range(len(positions) - 1):
        dr = positions[i] - positions[i + 1:]
        dr -= box * np.rint(dr / box)
        r2 = np.einsum("ij,ij->i", dr, dr)
        if np.any(r2 == 0):
            raise ValueError("overlapping atoms")
        mask = r2 < cutoff**2
        r = np.sqrt(r2[mask])
        s6 = r**-6
        pair_u = 4 * (s6*s6 - s6) - uc + (r - cutoff) * fc
        magnitude = 24 * (2*s6*s6 - s6) / r - fc
        pair_f = magnitude[:, None] * dr[mask] / r[:, None]
        forces[i] += pair_f.sum(axis=0)
        indices = np.arange(i + 1, len(positions))[mask]
        forces[indices] -= pair_f
        energy += pair_u.sum()
        virial += np.sum(dr[mask] * pair_f)
    return forces, float(energy), float(virial)


def md(steps=400, dt=0.002, seed=7):
    """64-particle low-density teaching run, NVE after initialization.

    This short run checks an integrator; it is not an equilibrated liquid measurement.
    Output columns: t, total E/N, instantaneous T, pressure.
    """
    rng = np.random.default_rng(seed)
    box = 6.4
    q = np.array(np.meshgrid(*([np.arange(4) + 0.5] * 3), indexing="ij"))
    q = q.reshape(3, -1).T * (box / 4)
    v = rng.normal(size=q.shape)
    v -= v.mean(axis=0)
    df = v.size - 3
    v *= np.sqrt(df * 0.5 / np.sum(v*v))
    F, U, W = lj_force(q, box)
    result = []
    for j in range(steps + 1):
        K = 0.5 * np.sum(v*v)
        result.append((j*dt, (K+U)/len(q), 2*K/df, (2*K+W)/(3*box**3)))
        if j == steps:
            break
        v += dt * F / 2
        q = (q + dt * v) % box
        F, U, W = lj_force(q, box)
        v += dt * F / 2
    return np.asarray(result)


def ising_energy(spins, J=1.0, field=0.0):
    return float(-J * np.sum(spins * (np.roll(spins, 1, 0) + np.roll(spins, 1, 1)))
                 - field * spins.sum())


def ising_delta(spins, i, j, J=1.0, field=0.0):
    L = len(spins)
    neighbors = (int(spins[(i-1) % L, j]) + int(spins[(i+1) % L, j])
                 + int(spins[i, (j-1) % L]) + int(spins[i, (j+1) % L]))
    return 2 * int(spins[i, j]) * (J * neighbors + field)


def ising(L=12, temperature=2.5, burn=1000, sweeps=4000, seed=17):
    """J=kB=1, h=0. Columns E/N and M/N after every sweep, including rejections."""
    if L < 3 or temperature <= 0:
        raise ValueError("require L>=3, temperature>0")
    rng = np.random.default_rng(seed)
    s = rng.choice([-1, 1], size=(L, L))
    records = []
    for sweep in range(burn + sweeps):
        for _ in range(L*L):
            i, j = rng.integers(0, L, size=2)
            delta = ising_delta(s, i, j)
            if delta <= 0 or rng.random() < np.exp(-delta / temperature):
                s[i, j] *= -1
        if sweep >= burn:
            records.append((ising_energy(s) / s.size, s.mean()))
    return np.asarray(records)


def block_summary(values, block_size):
    """SE from nonoverlapping block means; blocks must exceed correlation time."""
    values = np.asarray(values, dtype=float)
    count = len(values) // block_size
    if count < 2:
        raise ValueError("need at least two complete blocks")
    means = values[:count * block_size].reshape(count, block_size).mean(axis=1)
    return float(means.mean()), float(means.std(ddof=1) / np.sqrt(count)), count


def autocorrelation(values):
    """Linear, mean-subtracted autocorrelation, unbiased covariance normalization."""
    x = np.asarray(values, dtype=float)
    x = x - x.mean()
    n = len(x)
    if n < 2 or np.dot(x, x) == 0:
        raise ValueError("need a nonconstant series")
    spectrum = np.fft.rfft(x, n=2*n)
    ac = np.fft.irfft(spectrum * spectrum.conj(), n=2*n)[:n]
    ac /= np.arange(n, 0, -1)
    return ac / ac[0]


def kmc_two_state(events=100_000, rate_ab=2.0, rate_ba=1.0, seed=31):
    """A<->B: exact residence-time occupation tends to (b,a)/(a+b)."""
    if min(rate_ab, rate_ba) <= 0:
        raise ValueError("rates must be positive")
    rng = np.random.default_rng(seed)
    state = 0
    residence = np.zeros(2)
    for _ in range(events):
        total_rate = rate_ab if state == 0 else rate_ba
        waiting = -np.log1p(-rng.random()) / total_rate
        residence[state] += waiting
        state = 1 - state
    return residence / residence.sum()


def verify():
    """Analytical limits and convergence checks, independent of implementation details."""
    results = {}
    exact = np.e - 1
    te = [abs(trapezoid(np.exp, 0, 1, n)-exact) for n in (20, 40)]
    se = [abs(simpson(np.exp, 0, 1, n)-exact) for n in (20, 40)]
    assert 3.9 < te[0]/te[1] < 4.1
    assert 15.8 < se[0]/se[1] < 16.2
    integral2 = trap2d(lambda x,y: x*y*np.exp(-x*x*y), 200)
    assert abs(integral2-1/(2*np.e)) < 1e-5
    results["quadrature"] = {"trapezoid_error_ratio": te[0]/te[1],
                             "simpson_error_ratio": se[0]/se[1], "integral_2d": integral2}
    estimate, stderr = mc_integral()
    assert abs(estimate - (1-np.exp(-1))) < 5 * stderr
    results["mc"] = {"estimate": estimate, "standard_error": stderr}
    h = 1e-5
    derivative = (np.sin(1+h) - np.sin(1-h))/(2*h)
    assert abs(derivative - np.cos(1)) < 1e-10
    results["derivative_error"] = float(abs(derivative - np.cos(1)))
    ode = {}
    for method, target in (("verlet",4), ("rk4",16)):
        errors = []
        for dt in (0.1, 0.05):
            data = oscillator(method, dt, 1.0)
            errors.append(np.linalg.norm(data[-1,1:3]-[np.cos(1),-np.sin(1)]))
        ratio = errors[0]/errors[1]
        assert target * .95 < ratio < target * 1.05
        ode[method+"_error_ratio"] = ratio
    results["ode"] = ode
    root = bisect(lambda x: np.cos(x)-x, 0, 1)
    assert abs(root-0.7390851332151607) < 1e-9
    results["root"] = root
    x = np.linspace(0, 1, 201)
    wave = numerov(np.full_like(x, np.pi**2), x[1], 0.0, np.sin(np.pi*x[1]))
    assert np.max(abs(wave-np.sin(np.pi*x))) < 2e-9
    results["numerov_max_error"] = float(np.max(abs(wave-np.sin(np.pi*x))))
    heat_errors = [heat(n=n, dt=1e-5)[2] for n in (20, 40)]
    assert 3.8 < heat_errors[0]/heat_errors[1] < 4.2
    results["heat_errors"] = heat_errors
    _, energies, _ = harmonic_states()
    assert np.max(abs(energies-np.arange(0.5, 4))) < 0.004
    results["oscillator_energies"] = energies.tolist()
    k = 0.13
    free = cosine_bands(k, amplitude=0)
    expected = np.sort(0.5*(k+np.arange(-5,6))**2)
    assert np.allclose(free, expected)
    results["zone_edge_gap"] = float(np.diff(cosine_bands(0.5)[:2])[0])
    reflection, transmission = barrier()
    # E=V0/2, hbar=m=1, V0=1, width=1 => T=sech(1)^2.
    assert abs(transmission-1/np.cosh(1)**2) < 1e-12
    assert abs(reflection+transmission-1) < 1e-12
    results["barrier"] = {"R":reflection,"T":transmission}
    pos = np.array([[0.,0.,0.],[1.4,0.1,0.0]])
    forces, _, _ = lj_force(pos,6.0)
    plus, minus = pos.copy(), pos.copy()
    plus[0,0] += 1e-6
    minus[0,0] -= 1e-6
    fd = -(lj_force(plus,6.0)[1]-lj_force(minus,6.0)[1])/2e-6
    assert abs(forces[0,0]-fd) < 1e-8
    assert np.linalg.norm(forces.sum(axis=0)) < 1e-13
    trajectory = md()
    drift = np.max(abs(trajectory[:,1]-trajectory[0,1]))
    assert drift < 1e-3
    results["md_max_energy_change_per_atom"] = float(drift)
    max_delta_error = 0.0
    # Enumerate every 3x3 state and every one-spin move, compare global and local E.
    for bits in range(512):
        s = (2*((bits >> np.arange(9)) & 1)-1).reshape(3,3)
        e0 = ising_energy(s)
        for i in range(3):
            for j in range(3):
                delta = ising_delta(s,i,j)
                proposed = s.copy()
                proposed[i,j] *= -1
                max_delta_error = max(max_delta_error,abs(ising_energy(proposed)-e0-delta))
                forward, backward = min(1,math.exp(-delta/2.5)),min(1,math.exp(delta/2.5))
                assert abs(forward/backward-math.exp(-delta/2.5)) < 1e-12
    assert max_delta_error == 0
    results["ising_moves_checked"] = 512*9
    occupancy = kmc_two_state()
    assert np.max(abs(occupancy-[1/3,2/3])) < 0.01
    results["kmc_occupation_A_B"] = occupancy.tolist()
    sample = np.array([2.,1.,4.,3.,7.])
    centered = sample-sample.mean()
    direct = np.array([np.dot(centered[:len(sample)-k],centered[k:])/(len(sample)-k)
                       for k in range(len(sample))])
    assert np.allclose(autocorrelation(sample),direct/direct[0])
    return results


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