"""
Advance/OF-DFT example: mixing energy of the random solid solution Mg(1-x)Ca(x)O
(rock-salt structure).

    E_mix(x) = E(Mg[1-x] Ca[x] O) / N - (1 - x) E(MgO) / N - x E(CaO) / N

N is the number of cation sites. Only the cation sites are mixed; the oxygen
sites are unchanged. The pure oxides are calculated in supercells of the same
shape and with the same settings as the solid solutions.

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

import time

import numpy as np
from ase.build import bulk

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_MGO, A_CAO = 4.212, 4.811      # experimental lattice constants (Angstrom)
SIZE       = 2                   # 2x2x2 conventional cells = 64 atoms (32 cation sites)
X_CA       = (0.25, 0.50, 0.75)  # Ca fractions of the cation sites
N_CONFIG   = 2                   # random configurations per composition
rng = np.random.default_rng(seed=1)


def energy_per_cation(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,
    )
    return atoms.get_potential_energy() / (len(atoms) // 2)


def supercell(x_ca):
    a = (1.0 - x_ca) * A_MGO + x_ca * A_CAO  # Vegard's law
    atoms = bulk("MgO", "rocksalt", a=a, cubic=True).repeat((SIZE, SIZE, SIZE))
    cations = [atom.index for atom in atoms if atom.symbol == "Mg"]
    n_ca = round(x_ca * len(cations))
    atoms.symbols[rng.choice(cations, n_ca, replace=False)] = "Ca"  # random occupation
    return atoms


t0 = time.perf_counter()
e_mgo = energy_per_cation(supercell(0.0), "MgO")
e_cao = energy_per_cation(supercell(1.0), "CaO")
print(f"MgO: {e_mgo:.6f} eV/cation, CaO: {e_cao:.6f} eV/cation  ({time.perf_counter() - t0:.0f} s)")

print(" x(Ca) | config | E_mix (meV/cation) |  time")
results = {}
for x in X_CA:
    for k in range(N_CONFIG):
        t0 = time.perf_counter()
        e = energy_per_cation(supercell(x), f"MgCaO_x{x:.2f}_{k}")
        e_mix = (e - (1.0 - x) * e_mgo - x * e_cao) * 1000.0
        results.setdefault(x, []).append(e_mix)
        print(f"  {x:.2f} |   {k}    | {e_mix:18.1f} | {time.perf_counter() - t0:5.0f} s", flush=True)

print("\n x(Ca) | E_mix average (meV/cation)")
for x, values in results.items():
    print(f"  {x:.2f} | {np.mean(values):8.1f}")
