"""
Advance/OF-DFT example: molecular dynamics of liquid Al with a Langevin
thermostat (NVT) and its radial distribution function g(r).

The crystal is first melted with a cheap classical potential (EMT of ASE). The
liquid is then equilibrated with AOF-DFT at the target temperature, and g(r) is
averaged over the last part of the trajectory.

Copyright (C) 2026 AdvanceSoft Corporation, All rights reserved.
"""

import time

import matplotlib.pyplot as plt
import numpy as np
from ase import units
from ase.build import bulk
from ase.calculators.emt import EMT
from ase.constraints import FixCom
from ase.geometry.rdf import get_rdf
from ase.io import read
from ase.io.trajectory import Trajectory
from ase.md.langevin import Langevin
from ase.md.velocitydistribution import MaxwellBoltzmannDistribution, Stationary

from aofdft.calculator import AOFDFTCalculator

VPS_DIR = "path/to/DFT_DATA19_AS/VPS"  # edit these two paths for your environment
PAO_DIR = "path/to/DFT_DATA19_AS/PAO"

DENSITY  = 2.375  # density of liquid Al near the melting point (g/cm^3)
T_MELT   = 2000   # melting stage (K)
T_TARGET = 1000   # target temperature (K); melting point of Al = 933 K
DT       = 4.0    # time step (fs)
N_MELT   = 500    # EMT:     MD steps at T_MELT   (2 ps)
N_COOL   = 250    # EMT:     MD steps at T_TARGET (1 ps)
N_EQUIL  = 240    # AOF-DFT: MD steps at T_TARGET, not used for g(r)
N_SAMPLE = 200    # AOF-DFT: MD steps at T_TARGET, used for g(r)
INTERVAL = 2      # the trajectory is written every INTERVAL steps
FRICTION = 0.02 / units.fs

rng = np.random.default_rng(1)  # fixed random numbers, to make the run reproducible

# 3x3x3 conventional fcc cells = 108 atoms, scaled to the liquid density
atoms = bulk("Al", "fcc", a=4.05, cubic=True).repeat((3, 3, 3))
volume = atoms.get_masses().sum() / units.mol / DENSITY * 1e24  # Angstrom^3
atoms.set_cell(atoms.cell * (volume / atoms.get_volume()) ** (1 / 3), scale_atoms=True)
atoms.set_constraint(FixCom())  # keeps the centre of mass at rest during the MD
print(f"{len(atoms)} atoms, cell = {atoms.cell[0, 0]:.3f} Angstrom", flush=True)


def msd(reference):
    """Mean square displacement from the reference positions (Angstrom^2)."""
    return ((atoms.get_positions() - reference) ** 2).sum(axis=1).mean()


# 1) melt the crystal with EMT, then cool the liquid down to the target temperature
atoms.calc = EMT()
MaxwellBoltzmannDistribution(atoms, temperature_K=T_MELT, rng=rng)
Stationary(atoms)
dyn = Langevin(atoms, timestep=DT * units.fs, temperature_K=T_MELT, friction=FRICTION,
               fixcm=False, rng=rng)
start = atoms.get_positions()
dyn.run(N_MELT)
dyn.set_temperature(temperature_K=T_TARGET)
dyn.run(N_COOL)
print(f"EMT:     {(N_MELT + N_COOL) * DT / 1000:.2f} ps, T = {atoms.get_temperature():.0f} K, "
      f"mean square displacement = {msd(start):.1f} Angstrom^2", flush=True)

# 2) switch to AOF-DFT: equilibration and sampling at the target temperature
atoms.calc = AOFDFTCalculator(
    console      = False,
    logging_file = "al_liquid.log",
    kin_type     = "AS26",
    kin_model    = "Crystal26",
    vps_dir      = VPS_DIR,
    pao_dir      = PAO_DIR,
)

dyn  = Langevin(atoms, timestep=DT * units.fs, temperature_K=T_TARGET, friction=FRICTION,
                fixcm=False, rng=rng)
traj = Trajectory("al_liquid.traj", "w", atoms)
dyn.attach(traj.write, interval=INTERVAL)

t0 = time.perf_counter()


def report():
    e_pot = atoms.get_potential_energy() / len(atoms)
    print(f"step {dyn.nsteps:4d}  T = {atoms.get_temperature():7.1f} K  "
          f"E_pot = {e_pot:.4f} eV/atom  ({time.perf_counter() - t0:6.0f} s)", flush=True)


dyn.attach(report, interval=10)
start = atoms.get_positions()
dyn.run(N_EQUIL + N_SAMPLE)
traj.close()
print(f"AOF-DFT: {(N_EQUIL + N_SAMPLE) * DT / 1000:.2f} ps, T = {atoms.get_temperature():.0f} K, "
      f"mean square displacement = {msd(start):.1f} Angstrom^2", flush=True)

# 3) g(r) from the trajectory, without the equilibration part
R_MAX, N_BINS = 6.0, 120
frames = read("al_liquid.traj", index=f"{N_EQUIL // INTERVAL + 1}:")
rdfs   = [get_rdf(frame, R_MAX, N_BINS) for frame in frames]
g_r    = np.mean([rdf for rdf, _ in rdfs], axis=0)
r      = rdfs[0][1]
i_peak = int(np.argmax(g_r))
print(f"First peak of g(r): r = {r[i_peak]:.2f} Angstrom, g = {g_r[i_peak]:.2f} "
      f"({len(frames)} snapshots)")

np.savetxt("al_liquid_rdf.dat", np.c_[r, g_r], header="r (Angstrom)  g(r)")
fig, ax = plt.subplots(figsize=(6.0, 4.0))
ax.plot(r, g_r)
ax.axhline(1.0, color="gray", linestyle="--", linewidth=0.8)
ax.set_xlabel("r (Å)")
ax.set_ylabel("g(r)")
ax.set_xlim(0, R_MAX)
fig.tight_layout()
fig.savefig("al_liquid_rdf.png", dpi=150)
print("Saved al_liquid_rdf.png")
