"""
Advance/OF-DFT example: first-principles molecular dynamics with ASE.

Crystalline Si is kept at 300 K with a Langevin thermostat (NVT). The calculator
keeps the converged density matrix and uses it as the initial guess of the next
step, so the SCF of every MD step after the first is short.

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

import matplotlib.pyplot as plt
import numpy as np
from ase import units
from ase.build import bulk
from ase.constraints import FixCom
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"

T_TARGET = 300              # target temperature (K)
DT       = 2.0              # time step (fs)
N_STEPS  = 100              # number of MD steps (200 fs)
FRICTION = 0.02 / units.fs  # friction coefficient of the thermostat

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

atoms = bulk("Si", crystalstructure="diamond", a=5.43, cubic=True)  # 8 atoms
atoms.set_constraint(FixCom())  # keeps the centre of mass at rest during the MD

atoms.calc = AOFDFTCalculator(
    console      = False,
    logging_file = "si_md.log",
    kin_type     = "AS26",
    kin_model    = "Crystal26",
    vps_dir      = VPS_DIR,
    pao_dir      = PAO_DIR,
)

# initial velocities at the target temperature, without centre-of-mass motion
MaxwellBoltzmannDistribution(atoms, temperature_K=T_TARGET, rng=rng)
Stationary(atoms)

# NVT molecular dynamics with a Langevin thermostat
dyn  = Langevin(atoms, timestep=DT * units.fs, temperature_K=T_TARGET, friction=FRICTION,
                fixcm=False, rng=rng)
traj = Trajectory("si_md.traj", "w", atoms)
dyn.attach(traj.write, interval=1)

times, temperatures = [], []


def report():
    e_pot = atoms.get_potential_energy() / len(atoms)
    times.append(dyn.nsteps * DT)
    temperatures.append(atoms.get_temperature())
    print(f"step {dyn.nsteps:3d}  t = {times[-1]:5.1f} fs  E_pot = {e_pot:.5f} eV/atom  "
          f"T = {temperatures[-1]:6.1f} K", flush=True)


dyn.attach(report, interval=1)
dyn.run(N_STEPS)
traj.close()

n_last = N_STEPS // 2
print(f"Mean temperature of the last {n_last} steps: {np.mean(temperatures[-n_last:]):.0f} K")

# temperature as a function of time
fig, ax = plt.subplots(figsize=(6.0, 3.6))
ax.plot(times, temperatures)
ax.axhline(T_TARGET, color="gray", linestyle="--", linewidth=0.8)
ax.set_xlabel("Time (fs)")
ax.set_ylabel("Temperature (K)")
fig.tight_layout()
fig.savefig("si_md_temperature.png", dpi=150)
print("Saved si_md_temperature.png")
