"""
Advance/OF-DFT example: migration barrier of a vacancy in fcc Al with the
nudged elastic band (NEB) method of ASE.

A neighbouring atom hops into the vacancy. The initial and final states are
relaxed first, and the minimum energy path between them is found with the
climbing-image NEB method.

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

import matplotlib.pyplot as plt
import numpy as np
from ase.build import bulk
from ase.mep import NEB, NEBTools
from ase.optimize import BFGS, FIRE

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"

A_LAT    = 4.05  # lattice constant of fcc Al (Angstrom)
N_CELL   = 3     # 3x3x3 primitive cells = 27 sites, 26 atoms with the vacancy
N_IMAGES = 3     # number of intermediate images


def attach_calc(atoms, label):
    atoms.calc = AOFDFTCalculator(
        console       = False,
        logging_file  = f"{label}.log",
        kin_type      = "AS26",
        kin_model     = "Crystal26",
        vps_dir       = VPS_DIR,
        pao_dir       = PAO_DIR,
        scf_must_conv = True,
    )


# 1) initial state: vacancy at site 0
perfect = bulk("Al", "fcc", a=A_LAT).repeat((N_CELL, N_CELL, N_CELL))
dist = perfect.get_distances(0, range(1, len(perfect)), mic=True)
j = 1 + int(np.argmin(dist))  # a nearest neighbour of site 0
hop = perfect.get_distance(j, 0, mic=True, vector=True)  # vector from atom j to the vacancy

initial = perfect.copy()
del initial[0]  # atom j has the index j - 1 from here on

# 2) final state: atom j has moved into the vacancy
final = initial.copy()
final.positions[j - 1] += hop

for atoms, label in ((initial, "initial"), (final, "final")):
    attach_calc(atoms, label)
    BFGS(atoms, logfile=f"{label}_opt.log").run(fmax=0.03)
    print(f"{label:8s} E = {atoms.get_potential_energy():.6f} eV", flush=True)

# 3) NEB: intermediate images by IDPP interpolation, each with its own calculator
images = [initial]
for i in range(N_IMAGES):
    image = initial.copy()
    attach_calc(image, f"image{i + 1}")
    images.append(image)
images.append(final)

neb = NEB(images, climb=True)  # climbing image: the highest image goes to the saddle point
neb.interpolate(method="idpp", mic=True)
FIRE(neb, logfile="neb_opt.log").run(fmax=0.05, steps=300)

# 4) barrier and energy profile
nebtools = NEBTools(images)
barrier, delta_e = nebtools.get_barrier()
print(f"Migration barrier : {barrier:.3f} eV")
print(f"Reaction energy   : {delta_e:.3f} eV")

fig = nebtools.plot_band()
fig.savefig("al_vacancy_neb.png", dpi=150)
print("Saved al_vacancy_neb.png")
