Basic calculations

Batch calculation of structure files and saving the results

Read CIF, POSCAR and other structure files with ASE, calculate them in a batch, and save the energies, forces, stresses and atomic charges to an extended XYZ file and a CSV table.

Category
Basic calculations
APIs used
ase.io.readase.io.write (extxyz)get_stresscalc.e_fermiscf_must_conv
Script
structure_io.py

This example calculates a set of structure files and saves the results in a form that can be analyzed later. Since AOFDFTCalculator is an ASE calculator, structures are read and results are written with ASE's ase.io.read / ase.io.write. Any format supported by ASE can be read, including CIF, POSCAR (VASP) and xyz.

Procedure

  1. read the structure files in the folder structures one by one (sample files are created on the first run)
  2. calculate the energy, forces and stress, with one log file per structure
  3. record structures whose SCF did not converge and go on to the next one
  4. save the results of all structures to the extended XYZ file results.extxyz and a table to summary.csv
  5. read the extended XYZ file back and take out the results
structure_io.pyDownload
"""
Advance/OF-DFT example: read structures from files, calculate them in a batch,
and save the results (energy, forces, stress, atomic charges) to an extended XYZ file.

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

import csv
import glob
import os

from ase.build import bulk
from ase.io import read, write

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"

INPUT_DIR = "structures"         # put your own CIF / POSCAR / xyz ... files here
RESULT    = "results.extxyz"     # all calculated structures with their results
SUMMARY   = "summary.csv"        # one line per structure

# --- create sample input files (only when the folder does not exist yet)
if not os.path.isdir(INPUT_DIR):
    os.makedirs(INPUT_DIR)
    write(f"{INPUT_DIR}/Si.cif",      bulk("Si", "diamond", a=5.43, cubic=True))                # 8 atoms
    write(f"{INPUT_DIR}/SiC.cif",     bulk("SiC", "zincblende", a=4.36).repeat((2, 2, 2)))      # 16 atoms
    write(f"{INPUT_DIR}/Al_POSCAR",   bulk("Al", "fcc", a=4.05, cubic=True).repeat((2, 2, 2)),  # 32 atoms
          format="vasp")

if os.path.exists(RESULT):
    os.remove(RESULT)

rows = []
for path in sorted(glob.glob(f"{INPUT_DIR}/*")):
    name  = os.path.basename(path)
    atoms = read(path)  # the format is detected from the file name / content

    atoms.calc = AOFDFTCalculator(
        console       = False,
        logging_file  = f"{name}.log",  # one log file per structure
        kin_type      = "AS26",
        kin_model     = "Crystal26",
        vps_dir       = VPS_DIR,
        pao_dir       = PAO_DIR,
        scf_must_conv = True,
    )

    try:
        energy = atoms.get_potential_energy()
        forces = atoms.get_forces()
        atoms.get_stress()  # calculated here so that it is saved to the extended XYZ file
    except Exception as err:  # e.g. the SCF did not converge: record it and go on
        print(f"{name:12s} FAILED: {err}")
        rows.append({"name": name, "formula": atoms.get_chemical_formula(), "status": "failed"})
        continue

    fmax = (forces**2).sum(axis=1).max()**0.5  # largest force on an atom
    rows.append({
        "name"            : name,
        "formula"         : atoms.get_chemical_formula(),
        "status"          : "ok",
        "n_atoms"         : len(atoms),
        "energy_eV"       : f"{energy:.6f}",
        "energy_per_atom" : f"{energy / len(atoms):.6f}",
        "fmax_eV_A"       : f"{fmax:.4f}",
        "e_fermi_eV"      : f"{atoms.calc.e_fermi:.4f}",
    })
    print(f"{name:12s} {atoms.get_chemical_formula():6s} E = {energy:12.6f} eV  Fmax = {fmax:6.4f} eV/A")

    # energy, forces and stress are written from atoms.calc;
    # Mulliken charges are in atoms.arrays["charge"] and written as a per-atom column
    atoms.info["source"] = name
    write(RESULT, atoms, append=True)

columns = ["name", "formula", "status", "n_atoms", "energy_eV", "energy_per_atom",
           "fmax_eV_A", "e_fermi_eV"]
with open(SUMMARY, "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=columns)  # missing values are left empty
    writer.writeheader()
    writer.writerows(rows)
print(f"Saved {RESULT} and {SUMMARY}")

# --- read the results back, e.g. for analysis or as training data.
#     ASE stores the results in a SinglePointCalculator; the "charge" column is
#     returned by get_charges()
for atoms in read(RESULT, index=":"):
    charges = atoms.get_charges().round(3) + 0.0  # adding 0.0 turns -0.0 into 0.0
    print(f"{atoms.info['source']:12s} E = {atoms.get_potential_energy():12.6f} eV, "
          f"charges = {charges.min():+.3f} ... {charges.max():+.3f}")

Example output

Results with v1.0.0 (Crystal26).

text
Al_POSCAR    Al32   E = -2146.131878 eV  Fmax = 0.0000 eV/A
Si.cif       Si8    E =  -922.106107 eV  Fmax = 0.0000 eV/A
SiC.cif      C8Si8  E = -2214.183297 eV  Fmax = 0.0010 eV/A
Saved results.extxyz and summary.csv
Al_POSCAR    E = -2146.131878 eV, charges = +0.000 ... +0.000
Si.cif       E =  -922.106107 eV, charges = +0.000 ... +0.000
SiC.cif      E = -2214.183297 eV, charges = -1.287 ... +1.287

summary.csv opens directly in a spreadsheet application.

text
name,formula,status,n_atoms,energy_eV,energy_per_atom,fmax_eV_A,e_fermi_eV
Al_POSCAR,Al32,ok,32,-2146.131878,-67.066621,0.0000,-5.7200
Si.cif,Si8,ok,8,-922.106107,-115.263263,0.0000,-4.1663
SiC.cif,C8Si8,ok,16,-2214.183297,-138.386456,0.0010,-3.6966

Notes

  • To calculate your own structures, put the files in the folder structures before running the script. If the folder already exists, no sample files are created. read() detects the format from the file name and content; if it cannot, give it explicitly, e.g. read(path, format="vasp").
  • With scf_must_conv=True an unconverged SCF raises an exception, which is caught with try / except and recorded as failed in the status column. The remaining structures are still calculated. See What to do when the SCF does not converge for remedies.
  • The extended XYZ file contains the results of the calculator (energy, forces, stress) and the Mulliken charges (atoms.arrays["charge"]) as a per-atom column. Values put in atoms.info (here the file name source) are saved as well.
  • In the structures read back, the results are held by ASE's SinglePointCalculator and are available with get_potential_energy(), get_forces(), get_stress() and get_charges(), without running Advance/OF-DFT again.
  • The script does not print the return value of get_stress(), but the call makes the stress be calculated and saved to the extended XYZ file. get_stress() returns the stress in Voigt order (xx, yy, zz, yz, xz, xy) in eV/Angstrom³; multiply by 160.2177 to convert to GPa.
  • A new calculator is created for each structure, so structures with different elements and cell sizes can be handled in the same loop.
  • The sample structure files are cells of 8 to 32 atoms (2×2×2 cubic cells for Al, the cubic cell for Si, 2×2×2 primitive cells for SiC). With v1.0.0 the results change when the cell has a short period. For your own structures, too, check that a larger cell gives the same result.
  • For the charges read back, the smallest and the largest value over the atoms are printed.