"""
Advance/OF-DFT example: O(N) scaling of the computation time for large systems.

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

import time

import matplotlib.pyplot as plt
import numpy as np
from ase.build import bulk
from numpy.polynomial import Polynomial

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"

# 2x2x2 supercell of fcc Pt (32 atoms) as the building block
base = bulk("Pt", "fcc", a=3.9, cubic=True) * (2, 2, 2)

# 32, 64, 128 and 256 atoms. Larger cells such as (3, 3, 3) = 864 atoms need much more memory.
repeats   = [(1, 1, 1), (2, 1, 1), (2, 2, 1), (2, 2, 2)]
num_atoms = []
times     = []

for repeat in repeats:
    atoms = base * repeat

    atoms.calc = AOFDFTCalculator(
        console      = False,
        logging_file = f"{atoms.get_chemical_formula()}.log",
        kin_type     = "LKT",  # or "TFvW", "AS26"
        vps_dir      = VPS_DIR,
        pao_dir      = PAO_DIR,
    )

    start = time.time()
    atoms.get_potential_energy()
    elapsed = time.time() - start

    num_atoms.append(len(atoms))
    times.append(elapsed)
    print(f"{len(atoms):5d} atoms: {elapsed:8.1f} s")

# linear fit: time = a * N + b
fit = Polynomial.fit(num_atoms, times, deg=1)
n   = np.linspace(0, 1.1 * max(num_atoms), 100)

plt.scatter(num_atoms, times, label="AOF-DFT")
plt.plot(n, fit(n), linestyle="--", label="linear fit")
plt.xlim(0)
plt.ylim(0)
plt.xlabel("Number of atoms")
plt.ylabel("Execution time (s)")
plt.legend()
plt.tight_layout()
plt.savefig("large_system_TimevsN.png", dpi=150)
print("Saved large_system_TimevsN.png")
