"""Silicon bands and phonons, calculation stage.

Reads the inputs written by silicon-bands-build.py, relaxes the primitive cell with
PBE/GTH-DZVP-MOLOPT-SR, converges the density on a Gamma-centred mesh, reads the band
energies on the path and the mesh, runs the analytical phonon responses, and writes a
study that the docs page mounts.

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

import numpy as np

from atomli import units
from atomli.calculators import QC
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

SETTINGS = {"periodic": True, "basis": "gth-dzvp-molopt-sr", "pseudopotential": "gth-pbe",
            "mesh": [25, 25, 25], "precision": 1e-9}
SCF_TOLERANCE = 2.7211386245988e-8  # eV
RELAX_KMESH = 8  # electronic mesh of the cell relaxation
PHONON_KMESH = 4  # largest mesh the periodic Hessian fits in its 256 MiB budget
SMEARING_EV = 0.15  # Gaussian width of the electronic DOS
THZ_PER_CM = 0.0299792458  # THz per cm^-1
# Experimental references (see the provenance entries).
ISOTOPE_MASS = 29.973770136  # u, 30Si
EXP_LATTICE = 5.431  # angstrom, room temperature
EXP_GAP_300K = 1.12  # eV
EXP_GAP_LOW_T = 1.17  # eV
EXP_GAMMA_OPTICAL_THZ = 15.53  # THz, 296 K

COLORS = ("#2563eb", "#ea580c")  # the two basis atoms of the diamond cell


def calculator(kmesh):
    return QC(xc="PBE", device="cpu", kpts=(kmesh,) * 3, maxiter=200, scf={"energy_tolerance": SCF_TOLERANCE},
              settings=SETTINGS)


def relax(atoms, kmesh):
    atoms = atoms.copy()
    atoms.calc = calculator(kmesh)
    cell = UnitCellFilter(atoms, mask=[True] * 3 + [False] * 3, stress_tolerance=0.0005)
    if not BFGS(cell, maxstep=0.04, logfile=None).run(fmax=0.001, steps=100):
        raise RuntimeError(f"relaxation at k={kmesh} did not converge")
    return atoms, float((4 * atoms.get_volume()) ** (1 / 3))


def bands_on_mesh(atoms, mesh):
    """Converge the density on a mesh; return (k points, eigenvalues, weights, number of occupied bands)."""
    atoms = atoms.copy()
    atoms.calc = calculator(mesh)
    atoms.get_potential_energy()
    state = atoms.calc.get_electronic_state()
    kpoints = np.asarray(state["kpoints_scaled"], dtype=float)
    energies = np.asarray(state["eigenvalues"], dtype=float)
    if energies.shape[0] != 1 or len(kpoints) != mesh**3:
        raise RuntimeError("Expected one spin channel and the full mesh")
    occupied = int(round(state["electron_count"] / 2))
    return kpoints, energies[0], np.asarray(state["kpoint_weights"], dtype=float), occupied


def gaussian_dos(levels, weights, grid, sigma):
    """Sum of unit Gaussians on `grid`; levels (k, bands), weights (k,) summing to one."""
    total = np.zeros_like(grid)
    for band in range(levels.shape[1]):
        for start in range(0, len(grid), 512):
            part = grid[start:start + 512, None]
            total[start:start + 512] += (np.exp(-0.5 * ((part - levels[None, :, band]) / sigma) ** 2) @ weights)
    return total / (sigma * np.sqrt(2 * np.pi))


def mode_frames(atoms, repeat, q, mode, frequency_thz, 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()
    natoms = len(atoms)
    species = np.tile(np.arange(natoms), len(big) // natoms)
    translation = positions - base[species]
    cells = np.rint(translation @ np.linalg.inv(cell))
    phase = np.exp(2j * np.pi * cells @ np.asarray(q, dtype=float))
    vector = np.asarray(mode)[species] * phase[:, None]  # (atoms, 3)
    vector = vector / np.abs(vector).max() * amplitude  # largest component
    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 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")
    kpath = json.loads((inputs / "kpath.json").read_text())
    qpath = json.loads((inputs / "qpoints.json").read_text())

    # 1. Lattice constant against the electronic mesh of the relaxation.
    lattices, relaxed_cells = {}, {}
    for kmesh in (2, 3, 4, 6, RELAX_KMESH):
        relaxed, lattices[kmesh] = relax(primitive, kmesh)
        relaxed_cells[kmesh] = relaxed
        if kmesh == RELAX_KMESH:
            atoms = relaxed
        print(f"relax k={kmesh}: a = {lattices[kmesh]:.4f} A", flush=True)
    lattice = lattices[RELAX_KMESH]
    phonon_cell = relaxed_cells[PHONON_KMESH]  # the response mesh has its own stationary cell

    # 2. Band energies. Every value is an eigenvalue of a converged density on the mesh.
    convergence = []
    for mesh in kpath["convergence_meshes"]:
        kpoints, levels, _, occupied = bands_on_mesh(atoms, mesh)
        edges = plot.band_gap(levels, occupied)
        convergence.append({"mesh": mesh, "gap_ev": edges["gap_ev"],
                            "cbm_k": kpoints[edges["cbm_index"]].tolist(), "vbm_k": kpoints[edges["vbm_index"]].tolist()})
        print(f"mesh {mesh}: gap {edges['gap_ev']:.4f} eV at {convergence[-1]['cbm_k']}", flush=True)
        del kpoints, levels
    mesh = kpath["mesh"][0]
    kpoints, levels, weights, occupied = bands_on_mesh(atoms, mesh)
    index = {tuple(np.round(np.mod(k, 1.0) * mesh).astype(int) % mesh): i for i, k in enumerate(kpoints)}
    rows = [index[tuple(np.round(np.mod(np.asarray(k), 1.0) * mesh).astype(int) % mesh)] for k in kpath["kpoints_fractional"]]
    path_levels = levels[rows]
    edges = plot.band_gap(path_levels, occupied)
    gamma = rows[0]
    direct_gamma = float(levels[gamma, occupied] - levels[gamma, occupied - 1])
    vbm = edges["vbm_ev"]

    grid = np.linspace(levels.min() - 1.0, levels.max(), 1500)
    density = 2 * gaussian_dos(levels, weights, grid, SMEARING_EV)  # states per eV and cell, both spins
    edges_all = plot.band_gap(levels, occupied)
    bands = plot.band_structure(
        kpath["positions"], path_levels, n_valence=occupied, labels=kpath["labels"],
        label_positions=kpath["label_positions"], dos=(grid, density), window=(-13.5, 6.5), bands_shown=(4, 4),
        height=520)

    # The same mesh at the experimental lattice constant.
    expt = primitive.copy()
    expt.set_cell(np.asarray(primitive.cell) * EXP_LATTICE / (2 * np.asarray(primitive.cell)[0, 1]), scale_atoms=True)
    kpe, lev_e, _, occ_e = bands_on_mesh(expt, mesh)
    gap_expt_lattice = plot.band_gap(lev_e, occ_e)["gap_ev"]
    print(f"gap at a = {EXP_LATTICE}: {gap_expt_lattice:.4f} eV", flush=True)
    del kpe, lev_e

    # 3. Phonons: analytical responses at the relaxed cell on the q mesh that holds Gamma, X and L.
    supercell = tuple(qpath["supercell"])
    constants_file = root / "results" / "force-constants.json"
    if constants_file.exists():  # replay: the responses are the long step
        saved = json.loads(constants_file.read_text())
        phonons = Phonons.from_force_constants(phonon_cell, np.asarray(saved["constants"]), supercell=supercell,
                                               indices=saved["indices"])
    else:
        phonon_atoms = phonon_cell.copy()
        phonon_atoms.calc = calculator(PHONON_KMESH)
        # Raw constants: conditioning (symmetrization, acoustic sum rule) would reshape the X and L
        # responses, which a 2x2x2 range cannot absorb.
        phonons = Phonons(phonon_atoms, supercell=supercell, symmetrize=0, acoustic=False, reference_fmax=0.001,
                          reference_stress_tolerance=0.0005).run()
        constants_file.parent.mkdir(parents=True, exist_ok=True)
        constants_file.write_text(json.dumps({"constants": np.asarray(phonons.get_force_constants()).tolist(),
                                              "indices": list(phonons.get_indices()), "supercell": list(supercell),
                                              "lattice_angstrom": lattices[PHONON_KMESH], "units": "eV/angstrom^2"}))
    print("phonon responses done", round(time.monotonic() - started), "s", flush=True)

    # Isotope substitution on the same force constants: 28Si -> 30Si.
    isotope_atoms = phonon_cell.copy()
    isotope_atoms.set_masses([ISOTOPE_MASS] * len(atoms))
    isotope = Phonons.from_force_constants(isotope_atoms, phonons.get_force_constants(), supercell=supercell,
                                           indices=phonons.get_indices())
    isotope_gamma = float(np.asarray(isotope.get_energies([[0, 0, 0]]))[0, 5] / units.invcm * THZ_PER_CM)

    # Zone-center frequency against the electronic mesh, at the same cell and a one-cell force-constant range.
    gamma_by_kmesh = {}
    for kmesh in (2, 3, 4):
        trial = phonon_cell.copy()
        trial.calc = calculator(kmesh)
        energies = np.asarray(Phonons(trial, supercell=(1, 1, 1)).run().get_energies([[0, 0, 0]]))[0]
        gamma_by_kmesh[kmesh] = float(energies[5] / units.invcm * THZ_PER_CM)
        print(f"Gamma optical at k={kmesh}: {gamma_by_kmesh[kmesh]:.3f} THz", flush=True)

    labels = qpath["labels"]
    path_q = np.asarray(qpath["qpoints_fractional"])
    thz = np.asarray(phonons.get_energies(path_q)) / units.invcm * THZ_PER_CM  # (q, 6)
    positions = list(range(len(labels)))  # one column per q point, evenly spaced
    optical_gamma = float(thz[0, 5])
    ta_x, la_x, to_x = float(thz[1, 0]), float(thz[1, 2]), float(thz[1, 5])
    print("optical at Gamma", optical_gamma, "THz; X: TA", ta_x, "LA/LO", la_x, "TO", to_x, flush=True)

    # Selectable points: the lowest and highest branch at X and the optical branch at Gamma.
    selectable = {"gamma-optical": (0, 5, "Γ optical"), "x-ta": (1, 0, "X transverse acoustic"),
                  "x-to": (1, 5, "X transverse optical")}
    traces = []
    for branch in range(6):
        traces.append({"type": "scatter", "mode": "markers", "x": positions, "y": thz[:, branch].tolist(),
                       "marker": {"size": 9, "color": "#2266cc", "line": {"color": "#ffffff", "width": 1}},
                       "name": "Computed branches", "legendgroup": "computed", "showlegend": branch == 0,
                       "hovertemplate": f"branch {branch + 1}: %{{y:.2f}} THz<extra></extra>"})
    traces.append({"type": "scatter", "mode": "markers", "x": [positions[i] for i, _, _ in selectable.values()],
                   "y": [float(thz[i, b]) for i, b, _ in selectable.values()], "customdata": list(selectable),
                   "marker": {"size": 13, "color": "#dc4b4b", "symbol": "diamond", "line": {"color": "#ffffff", "width": 1.5}},
                   "name": "Animated modes (click)", "text": [label for _, _, label in selectable.values()],
                   "hovertemplate": "%{text}: %{y:.2f} THz<extra></extra>"})
    layout = {"margin": {"l": 56, "r": 16, "t": 16, "b": 44},
              "legend": {"orientation": "h", "x": 0, "y": -0.1, "yanchor": "top"},
              "xaxis": {"range": [-0.5, len(labels) - 0.5], "tickmode": "array", "tickvals": positions, "ticktext": labels,
                        "showgrid": False, "zeroline": False},
              "yaxis": {"title": {"text": "Frequency (THz)"}, "range": [0, float(thz.max()) * 1.08], "zeroline": False}}
    dispersion = plot.plotly({"data": traces, "layout": layout}, height=420)

    states = {}
    repeat = supercell
    for key, (i, branch, label) in selectable.items():
        mode = np.asarray(phonons.get_modes(path_q[i:i + 1]))[0, branch]
        frames = mode_frames(phonon_cell, repeat, path_q[i], mode, thz[i, branch])
        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

    study = Study("silicon-bands", "Silicon: indirect band gap and phonons at Γ, X and L",
                  system="Diamond silicon, two-atom primitive cell",
                  method="PBE/GTH-DZVP-MOLOPT-SR with GTH-PBE pseudopotentials, analytical phonon responses")
    study.fact("lattice", lattice, "Å", label="Relaxed lattice constant", precision=3)
    study.fact("gap", edges["gap_ev"], "eV", label="Indirect gap", precision=2)
    study.fact("direct_gamma", direct_gamma, "eV", label="Direct gap at Γ", precision=2)
    study.fact("optical", optical_gamma, "THz", label="Γ optical phonon", precision=2)
    study.fact("isotope", isotope_gamma, "THz", label="Γ optical, ³⁰Si", precision=2)
    study.figure("bands", bands, height=520,
                 caption="Band energies at the mesh points on the path, joined by straight lines, relative to the valence-band maximum.")
    study.figure("phonons", dispersion, height=420,
                 caption="Six branches at each q point of the 2×2×2 response mesh that lies on the high-symmetry path. Nothing is interpolated.")
    study.figure("motion", states["gamma-optical"], height=440, caption="Mode shown, 2×2×2 cells, amplitude exaggerated:")
    study.link("mode", source="phonons", 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(thz[i, b]), 2),
                  "cm": round(float(thz[i, b] / THZ_PER_CM), 0)} for key, (i, b, label) in selectable.items()],
                select="mode")
    f = lambda value, digits: f"{value:.{digits}f}"
    study.table("comparison", [{"key": "quantity", "label": "Quantity", "align": "left"},
                               {"key": "computed", "label": "PBE"}, {"key": "reference", "label": "Experiment"}],
                [{"id": "lattice", "quantity": "Lattice constant (Å)", "computed": f(lattice, 3), "reference": f(EXP_LATTICE, 3)},
                 {"id": "gap", "quantity": "Indirect gap (eV)", "computed": f(edges["gap_ev"], 2), "reference": f"{EXP_GAP_300K} (300 K), {EXP_GAP_LOW_T} (low T)"},
                 {"id": "gap_expt_lattice", "quantity": f"Indirect gap at a = {EXP_LATTICE} Å (eV)", "computed": f(gap_expt_lattice, 2), "reference": f"{EXP_GAP_300K} (300 K)"},
                 {"id": "optical", "quantity": "Γ optical phonon (THz)", "computed": f(optical_gamma, 2), "reference": f"{EXP_GAMMA_OPTICAL_THZ}"}])
    study.table("gap-mesh", [{"key": "mesh", "label": "Mesh", "align": "left"}, {"key": "gap", "label": "Sampled gap (eV)"},
                             {"key": "cbm", "label": "Conduction minimum at (reciprocal-lattice coordinates)"}],
                [{"id": str(row["mesh"]), "mesh": f"{row['mesh']}×{row['mesh']}×{row['mesh']}", "gap": f(row["gap_ev"], 3),
                  "cbm": "(" + ", ".join(f(c, 3) for c in row["cbm_k"]) + ")"} for row in convergence])
    study.table("lattice-mesh", [{"key": "mesh", "label": "Relaxation mesh", "align": "left"}, {"key": "a", "label": "Lattice constant (Å)"}],
                [{"id": str(k), "mesh": f"{k}×{k}×{k}", "a": f(v, 4)} for k, v in lattices.items()])
    study.table("gamma-kmesh", [{"key": "mesh", "label": "Electronic mesh", "align": "left"}, {"key": "thz", "label": "Γ optical (THz)"}],
                [{"id": str(k), "mesh": f"{k}×{k}×{k}", "thz": f(v, 2)} for k, v in gamma_by_kmesh.items()])
    study.provenance("Computed", "atomli QC, PBE with GTH-PBE pseudopotentials and the GTH-DZVP-MOLOPT-SR basis; each cell relaxed "
                     "on the electronic mesh used with it, to fmax 0.001 eV/Å and stress 0.0005 eV/Å³: "
                     f"{RELAX_KMESH}x{RELAX_KMESH}x{RELAX_KMESH} for the bands, {PHONON_KMESH}x{PHONON_KMESH}x{PHONON_KMESH} for the phonons")
    study.provenance("Band energies", f"eigenvalues of the converged density on a {mesh}x{mesh}x{mesh} Gamma-centred mesh; "
                     "points on the path are mesh points, nothing is interpolated")
    study.provenance("Phonons", f"analytical responses with a {PHONON_KMESH}x{PHONON_KMESH}x{PHONON_KMESH} electronic mesh on a "
                     f"{supercell[0]}x{supercell[1]}x{supercell[2]} q mesh; frequencies are read at the q points of that mesh (Γ, X, L) only")
    study.provenance("Experiment", f"Lattice constant {EXP_LATTICE} Å at room temperature; indirect gap {EXP_GAP_LOW_T} eV "
                     f"(low temperature) and {EXP_GAP_300K} eV (300 K): Bludau, Onton, Heinke, J. Appl. Phys. 45, 1846 (1974) and "
                     "Green, Sol. Energy Mater. Sol. Cells 92, 1305 (2008); Γ optical phonon "
                     f"{EXP_GAMMA_OPTICAL_THZ} THz: Nilsson and Nelin, Phys. Rev. B 6, 3777 (1972)")
    study.write(root)

    results = {
        "model": {**SETTINGS, "functional": "PBE", "scf_energy_tolerance_ev": SCF_TOLERANCE},
        "lattice_by_relaxation_kmesh_angstrom": lattices,
        "bands": {"mesh": mesh, "labels": kpath["labels"], "label_positions": kpath["label_positions"],
                  "positions": kpath["positions"], "kpoints_fractional": kpath["kpoints_fractional"],
                  "energies_ev": path_levels.tolist(), "occupied_bands": occupied, "vbm_ev": vbm,
                  "gap_ev": edges["gap_ev"], "vbm_k": kpath["kpoints_fractional"][edges["vbm_index"]],
                  "cbm_k": kpath["kpoints_fractional"][edges["cbm_index"]], "direct_gap_gamma_ev": direct_gamma,
                  "mesh_gap_ev": edges_all["gap_ev"], "gap_at_experimental_lattice_ev": gap_expt_lattice,
                  "dos_smearing_ev": SMEARING_EV},
        "references": {"lattice_angstrom": EXP_LATTICE, "gap_300k_ev": EXP_GAP_300K, "gap_low_t_ev": EXP_GAP_LOW_T,
                       "gamma_optical_thz": EXP_GAMMA_OPTICAL_THZ},
        "gap_convergence": convergence,
        "phonons": {"supercell": list(supercell), "electronic_kmesh": PHONON_KMESH, "labels": qpath["labels"],
                    "qpoints_fractional": path_q.tolist(), "frequencies_thz": thz.tolist(),
                    "isotope_30si_gamma_optical_thz": isotope_gamma, "gamma_optical_by_kmesh_thz": gamma_by_kmesh,
                    "x_point_thz": {"ta": ta_x, "la_lo": la_x, "to": to_x}},
        "elapsed_s": time.monotonic() - started,
    }
    (root / "results.json").write_text(json.dumps(results))
    print("done", round(time.monotonic() - started), "s", flush=True)


if __name__ == "__main__":
    main()
