"""
Advance/OF-DFT example: structure optimization and potential energy curve of methane.

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

import matplotlib.pyplot as plt
import numpy as np
from ase.build import molecule
from ase.io import write
from ase.optimize import BFGS

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"

# isolated molecule in a box: 4.0 Angstrom of vacuum on each side
atoms = molecule("CH4")
atoms.center(vacuum=4.0)

c_idx     = [a.index for a in atoms if a.symbol == "C"][0]
h_indices = [a.index for a in atoms if a.symbol == "H"]

atoms.calc = AOFDFTCalculator(
    console      = False,
    logging_file = "methane_scf.log",
    kin_type     = "AS26",
    kin_model    = "Molecule26",  # pre-trained model for molecules
    vps_dir      = VPS_DIR,
    pao_dir      = PAO_DIR,
    scf_style    = "molecule",    # SCF preset for molecules
)

# 1) structure optimization with an ASE optimizer
opt = BFGS(atoms, logfile="methane_opt.log")
opt.run(fmax=0.05)  # eV/Angstrom

eq_dist = atoms.get_distance(c_idx, h_indices[0])
print(f"Optimized C-H distance: {eq_dist:.3f} Angstrom")
write("methane_optimized.xyz", atoms)

# 2) potential energy curve: stretch all C-H bonds uniformly
c_pos     = atoms.positions[c_idx].copy()
units     = [(atoms.positions[i] - c_pos) / np.linalg.norm(atoms.positions[i] - c_pos) for i in h_indices]
distances = np.linspace(0.8, 2.0, 13)
energies  = []

for d in distances:
    for i, unit in zip(h_indices, units):
        atoms.positions[i] = c_pos + unit * d

    energies.append(atoms.get_potential_energy())
    print(f"C-H distance: {d:.2f} Angstrom, total energy: {energies[-1]:.4f} eV")

plt.plot(distances, np.array(energies) - min(energies), marker="o", label="AOF-DFT (Molecule26)")
plt.xlabel("C-H distance (Angstrom)")
plt.ylabel("Relative energy (eV)")
plt.legend()
plt.tight_layout()
plt.savefig("methane_EvsR.png", dpi=150)
print("Saved methane_EvsR.png")
