"""Silicon phonons from a machine-learning potential, calculation stage.

Reads the inputs written by silicon-phonons-build.py, relaxes the primitive cell with the
nequix-mp-1 potential, determines force constants by central finite displacements of the repeated
cell, applies the acoustic sum rule, evaluates the dispersion on the dense path and the density of
states on a q mesh, and writes a study that the docs page mounts. The DFT frequencies at
Gamma, X and L come from the committed results of silicon-bands-run.py.

    python silicon-phonons-build.py --output ../../studies/silicon-phonons
    python silicon-phonons-run.py   --output ../../studies/silicon-phonons
"""
import argparse
import json
import time
from pathlib import Path

import numpy as np

from atomli import units
from atomli.calculators.mlip import MLIP
from atomli.filters import UnitCellFilter
from atomli.io import read
from atomli.optimize import BFGS
from atomli.phonons import Phonons
from atomli.visualize import Study, Viewer, plot

MODEL = "nequix-oam-1-pft"  # chosen after the model survey below; the other nequix models are reported beside it
SURVEY = ["nequix-mp-1", "nequix-mp-1-pft", "nequix-oam-1", "nequix-oam-1-pft"]
DELTA = 0.01  # angstrom, displacement amplitude; 0.02 is the linearity check
THZ_PER_CM = 0.0299792458
DOS_SIGMA_THZ = 0.12  # Gaussian width of the density of states
DFT_LATTICE = 5.4745948959574005  # angstrom, relaxed lattice constant of the DFT study
EXP_LATTICE = 5.431  # angstrom, room temperature
GAMMA_X_L = [[0, 0, 0], [0, .5, .5], [.5, .5, .5]]
COLORS = ("#2563eb", "#ea580c")  # the two basis atoms of the diamond cell
DFT_DIR = Path(__file__).resolve().parent.parent.parent / "studies" / "silicon-bands"


def thz(phonons, qpoints):
    return np.asarray(phonons.get_energies(qpoints)) / units.invcm * THZ_PER_CM


def relax(primitive, model):
    """Relax the primitive cell with a model; return the lattice constant."""
    atoms = primitive.copy()
    atoms.calc = MLIP(model)
    BFGS(UnitCellFilter(atoms, mask=[True] * 3 + [False] * 3), maxstep=0.04, logfile=None).run(fmax=0.0005, steps=100)
    return float(2 * atoms.cell[0, 1])


def force_constants(lattice, repeat, delta=DELTA, model=MODEL, **options):
    """Finite-displacement force constants of the diamond primitive cell at a lattice constant."""
    from atomli.build import bulk
    atoms = bulk("Si", "diamond", a=lattice)
    atoms.calc = MLIP(model)
    return atoms, Phonons(atoms, supercell=(repeat,) * 3, delta=delta, **options).run_resident_finite_difference()


def mode_frames(atoms, repeat, q, mode, amplitude=0.15, count=24):
    """One normal mode of wave vector q (reciprocal-lattice coordinates) on a repeated cell."""
    base = np.asarray(atoms.get_positions())
    cell = np.asarray(atoms.cell)
    big = atoms.repeat(repeat)
    positions = big.get_positions()
    species = np.tile(np.arange(len(atoms)), len(big) // len(atoms))
    cells = np.rint((positions - base[species]) @ np.linalg.inv(cell))
    phase = np.exp(2j * np.pi * cells @ np.asarray(q, dtype=float))
    vector = np.asarray(mode)[species] * phase[:, None]
    vector = vector / np.abs(vector).max() * amplitude
    frames = []
    for step in range(count):
        image = big.copy()
        image.set_positions(positions + np.real(vector * np.exp(-2j * np.pi * step / count)))
        frames.append(image)
    return frames


def gaussian_dos(frequencies, grid, sigma):
    """Density of states per primitive cell (states per THz) from frequencies on a uniform q mesh."""
    flat = frequencies.reshape(-1)
    total = np.zeros_like(grid)
    for start in range(0, len(grid), 256):
        part = grid[start:start + 256, None]
        total[start:start + 256] = np.exp(-0.5 * ((part - flat[None, :]) / sigma) ** 2).sum(axis=1)
    return total / (sigma * np.sqrt(2 * np.pi) * (len(flat) // frequencies.shape[1]))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", required=True)
    root = Path(parser.parse_args().output)
    inputs = root / "input"
    started = time.monotonic()

    primitive = read(inputs / "si-primitive.extxyz")
    qpath = json.loads((inputs / "qpath.json").read_text())
    repeat = qpath["supercell"][0]
    path_q = np.asarray(qpath["qpoints_fractional"])

    # 1. Relax the primitive cell with the model.
    lattice = relax(primitive, MODEL)
    print(f"relaxed a = {lattice:.4f} A", flush=True)

    # 2. Force constants: central displacements of +-DELTA, symmetrized, with the acoustic sum rule.
    cell, phonons = force_constants(lattice, repeat)
    timing = time.monotonic() - started
    print(f"force constants on {repeat}x{repeat}x{repeat} cells: {timing:.1f} s", flush=True)
    path_thz = thz(phonons, path_q)
    gxl = thz(phonons, GAMMA_X_L)  # (3, 6)

    # 3. Convergence: supercell size, displacement amplitude, conditioning, and the DFT lattice constant.
    probe = np.array(GAMMA_X_L + [[0.1, 0.2, 0.3], [0.0, 0.25, 0.25]])
    convergence = []
    for n in qpath["convergence_supercells"]:
        _, p = force_constants(lattice, n)
        values = thz(p, probe)
        convergence.append({"supercell": n, "gamma_optical": values[0, 5], "x_ta": values[1, 0], "x_to": values[1, 5],
                            "l_ta": values[2, 0], "l_to": values[2, 5], "probe_max": values[3].max()})
        print("supercell", n, np.round(values[:3], 3).tolist(), flush=True)
    _, doubled = force_constants(lattice, repeat, delta=2 * DELTA)
    amplitude_shift = float(np.abs(thz(doubled, probe) - thz(phonons, probe)).max())
    _, raw = force_constants(lattice, repeat, symmetrize=0, acoustic=False)
    raw_gamma = thz(raw, [[0, 0, 0]])[0]
    print(f"2x amplitude: max change {amplitude_shift:.4f} THz; raw constants Gamma acoustic {raw_gamma[:3]}", flush=True)
    _, at_dft = force_constants(DFT_LATTICE, repeat)
    gxl_dft_lattice = thz(at_dft, GAMMA_X_L)

    # 4. Density of states on a Gamma-centred q mesh.
    mesh = qpath["dos_mesh"][0]
    grid = np.indices((mesh,) * 3).reshape(3, -1).T / mesh
    mesh_thz = thz(phonons, grid)
    top = float(mesh_thz.max()) + 0.5
    frequency_grid = np.linspace(0, top, 600)
    density = gaussian_dos(mesh_thz, frequency_grid, DOS_SIGMA_THZ)
    print(f"DOS integral {np.trapezoid(density, frequency_grid):.3f} (6 states per cell)", flush=True)

    # 5. Comparison with the DFT frequencies at Gamma, X and L.
    dft = np.asarray(json.loads((DFT_DIR / "results.json").read_text())["phonons"]["frequencies_thz"])  # (3, 6)
    difference = gxl - dft
    difference_dft_lattice = gxl_dft_lattice - dft
    mean_abs, max_abs = float(np.abs(difference).mean()), float(np.abs(difference).max())
    mean_abs_dftlat, max_abs_dftlat = float(np.abs(difference_dft_lattice).mean()), float(np.abs(difference_dft_lattice).max())
    print(f"|MLIP - DFT|: mean {mean_abs:.3f}, max {max_abs:.3f} THz; at the DFT lattice: mean {mean_abs_dftlat:.3f}, max {max_abs_dftlat:.3f}", flush=True)

    # Survey of the nequix models at their own relaxed lattice constants (4x4x4 cells), same comparison.
    survey = []
    for name in SURVEY:
        a_model = relax(primitive, name)
        _, p = force_constants(a_model, 4, model=name)
        values = thz(p, GAMMA_X_L)
        survey.append({"model": name, "lattice": a_model, "gamma_optical": float(values[0, 5]),
                       "mean_abs": float(np.abs(values - dft).mean()), "max_abs": float(np.abs(values - dft).max())})
        print("survey", survey[-1], flush=True)

    # 6. Figure: dispersion and density of states on a shared frequency axis, DFT points overlaid.
    positions = qpath["positions"]
    ticks = qpath["label_positions"]
    traces = []
    for branch in range(6):
        traces.append({"type": "scatter", "mode": "lines", "x": positions, "y": path_thz[:, branch].tolist(),
                       "line": {"color": "#2266cc", "width": 1.6}, "name": f"{MODEL} potential",
                       "legendgroup": "mlip", "showlegend": branch == 0,
                       "hovertemplate": f"branch {branch + 1}: %{{y:.2f}} THz<extra></extra>"})
    point_x = {0: [ticks[0], ticks[4]], 1: [ticks[1]], 2: [ticks[5]]}  # Gamma occurs twice on the path
    dft_x = [x for i in range(3) for x in point_x[i] for _ in range(6)]
    dft_y = [float(dft[i, b]) for i in range(3) for _ in point_x[i] for b in range(6)]
    traces.append({"type": "scatter", "mode": "markers", "x": dft_x, "y": dft_y, "name": "PBE response (Γ, X, L)",
                   "marker": {"symbol": "diamond", "size": 9, "color": "#dc4b4b", "line": {"color": "#ffffff", "width": 1}},
                   "hovertemplate": "PBE: %{y:.2f} THz<extra></extra>"})
    traces.append({"type": "scatter", "mode": "lines", "x": density.tolist(), "y": frequency_grid.tolist(), "xaxis": "x2",
                   "yaxis": "y", "line": {"color": "#2266cc", "width": 1.6}, "fill": "tozerox",
                   "fillcolor": "rgba(34,102,204,.18)", "showlegend": False,
                   "hovertemplate": "%{y:.2f} THz: %{x:.3f} states/THz<extra></extra>"})
    layout = {"margin": {"l": 64, "r": 16, "t": 16, "b": 44},
              "legend": {"orientation": "h", "x": 0, "y": -0.1, "yanchor": "top"},
              "xaxis": {"domain": [0, 0.74], "range": [0, ticks[-1]], "tickmode": "array", "tickvals": ticks,
                        "ticktext": qpath["labels"], "showgrid": False, "zeroline": False, "ticklabelstandoff": 8},
              "xaxis2": {"domain": [0.76, 1], "anchor": "y", "title": {"text": "DOS"}, "showticklabels": False,
                         "zeroline": False, "showgrid": False, "range": [0, float(density.max()) * 1.05]},
              "yaxis": {"title": {"text": "Frequency (THz)"}, "range": [0, top], "zeroline": False},
              "shapes": [{"type": "line", "xref": "x", "yref": "paper", "x0": p, "x1": p, "y0": 0, "y1": 1,
                          "line": {"color": "rgba(128,128,128,.45)", "width": 1}} for p in ticks]}
    dispersion = plot.plotly({"data": traces, "layout": layout}, height=460)

    # 7. Animated modes on the relaxed cell: the optical mode at Gamma and the two extreme branches at X.
    selectable = {"gamma-optical": (0, 5, "Γ optical"), "x-ta": (1, 0, "X transverse acoustic"),
                  "x-to": (1, 5, "X transverse optical")}
    states = {}
    for key, (i, branch, label) in selectable.items():
        mode = np.asarray(phonons.get_modes(np.asarray(GAMMA_X_L)[i:i + 1]))[0, branch]
        frames = mode_frames(cell, (2, 2, 2), GAMMA_X_L[i], mode)
        look = {"cell": False, "atom_colors": [COLORS[a % 2] for a in range(len(frames[0]))],
                "color_legend": {COLORS[0]: "sublattice A", COLORS[1]: "sublattice B"}}
        viewer = Viewer(frames, height=440, look=look)
        viewer.set_fps(12).play()
        centre = frames[0].get_positions().mean(axis=0)
        viewer.set_camera(position=(centre + np.array([1.0, 0.6, 0.35]) * 20).tolist(), target=centre.tolist(), up=(0, 0, 1))
        states[key] = viewer

    f = lambda value, digits: f"{value:.{digits}f}"
    study = Study("silicon-phonons", "Silicon: phonon dispersion and density of states from a machine-learning potential",
                  system="Diamond silicon, two-atom primitive cell",
                  method=f"{MODEL} potential, finite-displacement force constants on {repeat}x{repeat}x{repeat} cells")
    study.fact("optical", float(path_thz[0, 5]), "THz", label="Γ optical phonon", precision=2)
    study.fact("optical_cm", float(path_thz[0, 5] / THZ_PER_CM), "cm⁻¹", label="Γ optical phonon", precision=0)
    study.fact("mean_difference", mean_abs, "THz", label="Mean |PBE response − potential|", precision=2)
    study.fact("max_difference", max_abs, "THz", label="Largest difference", precision=2)
    study.fact("lattice", lattice, "Å", label="Potential lattice constant", precision=3)
    study.figure("dispersion", dispersion, height=460,
                 caption="Phonon dispersion and density of states of the potential; red diamonds are the PBE frequencies at Γ, X and L.")
    study.figure("motion", states["gamma-optical"], height=440, caption="Mode shown, 2×2×2 cells, amplitude exaggerated:")
    study.link("mode", source=None, target="motion", states=states, initial="gamma-optical",
               labels={k: v[2] for k, v in selectable.items()})
    study.table("modes", [{"key": "mode", "label": "Mode", "align": "left"},
                          {"key": "thz", "label": "Frequency", "unit": "THz", "precision": 2},
                          {"key": "cm", "label": "Frequency", "unit": "cm⁻¹", "precision": 0}],
                [{"id": key, "mode": label, "thz": round(float(gxl[i, b]), 2), "cm": round(float(gxl[i, b] / THZ_PER_CM), 0)}
                 for key, (i, b, label) in selectable.items()], select="mode")
    names = [("Γ", [0, 1, 2], "acoustic (x3)"), ("Γ", [3, 4, 5], "optical (x3)"), ("X", [0, 1], "TA (x2)"),
             ("X", [2, 3], "LA, LO"), ("X", [4, 5], "TO (x2)"), ("L", [0, 1], "TA (x2)"), ("L", [2], "LA"),
             ("L", [3], "LO"), ("L", [4, 5], "TO (x2)")]
    rows = []
    for label, branches, what in names:
        i = "ΓXL".index(label)
        rows.append({"id": f"{label}-{what}", "point": label, "branch": what,
                     "dft": f(float(dft[i, branches].mean()), 2), "mlip": f(float(gxl[i, branches].mean()), 2),
                     "mlip_dft_lattice": f(float(gxl_dft_lattice[i, branches].mean()), 2),
                     "delta": f(float((gxl[i, branches] - dft[i, branches]).mean()), 2)})
    study.table("comparison", [{"key": "point", "label": "q", "align": "left"}, {"key": "branch", "label": "Branch", "align": "left"},
                               {"key": "dft", "label": "PBE response (THz)"}, {"key": "mlip", "label": f"{MODEL} (THz)"},
                               {"key": "mlip_dft_lattice", "label": f"{MODEL} at the PBE lattice (THz)"},
                               {"key": "delta", "label": "Potential − PBE (THz)"}], rows)
    study.table("supercell", [{"key": "cells", "label": "Cells", "align": "left"}, {"key": "gamma", "label": "Γ optical (THz)"},
                              {"key": "x_ta", "label": "X TA (THz)"}, {"key": "x_to", "label": "X TO (THz)"},
                              {"key": "l_ta", "label": "L TA (THz)"}, {"key": "l_to", "label": "L TO (THz)"},
                              {"key": "probe", "label": "Highest branch at (0.1, 0.2, 0.3) (THz)"}],
                [{"id": str(c["supercell"]), "cells": f"{c['supercell']}×{c['supercell']}×{c['supercell']}",
                  "gamma": f(c["gamma_optical"], 3), "x_ta": f(c["x_ta"], 3), "x_to": f(c["x_to"], 3),
                  "l_ta": f(c["l_ta"], 3), "l_to": f(c["l_to"], 3), "probe": f(c["probe_max"], 3)} for c in convergence])
    study.table("models", [{"key": "model", "label": "Model", "align": "left"}, {"key": "a", "label": "Lattice constant (Å)"},
                           {"key": "gamma", "label": "Γ optical (THz)"}, {"key": "mean", "label": "Mean |difference| (THz)"},
                           {"key": "max", "label": "Largest |difference| (THz)"}],
                [{"id": r["model"], "model": r["model"], "a": f(r["lattice"], 4), "gamma": f(r["gamma_optical"], 2),
                  "mean": f(r["mean_abs"], 2), "max": f(r["max_abs"], 2)} for r in survey])
    study.provenance("Computed", f"atomli MLIP with the {MODEL} potential (weights fetched at run time); the primitive cell was relaxed "
                     f"to fmax 0.0005 eV/Å (a = {lattice:.4f} Å); no electronic k points are involved")
    study.provenance("Force constants", f"central finite displacements of ±{DELTA} Å on {repeat}x{repeat}x{repeat} repeats of the "
                     "primitive cell, symmetrized, with the acoustic sum rule applied; frequencies at every other q are Fourier "
                     "interpolation of these real-space constants")
    study.provenance("Density of states", f"{mesh}x{mesh}x{mesh} Gamma-centred q mesh, all points, Gaussian width {DOS_SIGMA_THZ} THz, "
                     "normalized to 6 states per primitive cell")
    study.provenance("PBE response", "frequencies at Γ, X and L from the analytical PBE/GTH-DZVP-MOLOPT-SR response of the silicon-bands "
                     f"example on a 2x2x2 q mesh at its relaxed a = {DFT_LATTICE:.4f} Å; the acoustic frequencies at Γ (0.14 THz) are that "
                     "calculation's raw sum-rule error")
    study.write(root)

    results = {"model": MODEL, "lattice_angstrom": lattice, "lattice_pbe_angstrom": DFT_LATTICE, "lattice_experiment_angstrom": EXP_LATTICE,
               "delta_angstrom": DELTA, "supercell": [repeat] * 3, "dos": {"mesh": mesh, "sigma_thz": DOS_SIGMA_THZ,
               "frequencies_thz": frequency_grid.tolist(), "density": density.tolist()},
               "gamma_x_l_thz": gxl.tolist(), "gamma_x_l_at_pbe_lattice_thz": gxl_dft_lattice.tolist(), "pbe_gamma_x_l_thz": dft.tolist(),
               "difference_thz": {"mean_abs": mean_abs, "max_abs": max_abs, "mean_abs_at_pbe_lattice": mean_abs_dftlat,
                                  "max_abs_at_pbe_lattice": max_abs_dftlat},
               "supercell_convergence": convergence, "model_survey": survey, "amplitude_check_max_change_thz": amplitude_shift,
               "raw_gamma_thz": raw_gamma.tolist(), "dos_max_thz": float(mesh_thz.max()),
               "highest_frequency_thz": float(path_thz.max()), "elapsed_s": time.monotonic() - started}
    (root / "results.json").write_text(json.dumps(results))
    print("done", round(time.monotonic() - started, 1), "s", flush=True)


if __name__ == "__main__":
    main()
