基本の計算

構造ファイルの一括計算と結果の保存

CIF・POSCAR などの構造ファイルを ASE で読み込んで一括計算し、エネルギー・力・ストレス・原子電荷を拡張 XYZ ファイルと CSV に保存します。

カテゴリ
基本の計算
使用する機能
ase.io.readase.io.write (extxyz)get_stresscalc.e_fermiscf_must_conv
スクリプト
structure_io.py

手元にある構造ファイルをまとめて計算し、結果を後から解析できる形で保存する例です。AOFDFTCalculator は ASE の Calculator なので、構造の読み込みと結果の書き出しには ASE の ase.io.read / ase.io.write をそのまま使えます。CIF、POSCAR (VASP)、xyz など、ASE が対応する形式を読み込めます。

計算の流れ

  1. フォルダ structures 内の構造ファイルを順に読み込む (初回はサンプルの構造ファイルを作成する)
  2. 構造ごとにログファイルを分けて、エネルギー・力・ストレスを計算する
  3. SCF が収束しなかった構造は記録して、次の構造に進む
  4. 全構造の結果を拡張 XYZ ファイル results.extxyz に、一覧表を summary.csv に保存する
  5. 保存した拡張 XYZ ファイルを読み直して、結果を取り出す
structure_io.pyダウンロード
"""
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}")

実行結果の例

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 は表計算ソフトでそのまま開けます。

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

ポイント

  • 自分の構造を計算するときは、フォルダ structures に構造ファイルを置いてから実行します。フォルダがすでにあるときは、サンプルの構造ファイルは作成されません。ファイル形式は read() がファイル名と内容から判別します。判別できない場合は read(path, format="vasp") のように指定します。
  • scf_must_conv=True を指定し、SCF が収束しなかったときの例外を try / except で受けて、status 列に failed と記録しています。1 つの構造が収束しなくても、残りの構造の計算は続きます。収束しない場合の対処は SCF が収束しないときの対処 を参照してください。
  • 拡張 XYZ ファイルには、Calculator の計算結果 (エネルギー、力、ストレス) と、Mulliken 電荷 (atoms.arrays["charge"]) が原子ごとの列として書き込まれます。atoms.info に入れた値 (ここではファイル名 source) も保存されます。
  • 読み直した構造では、計算結果は ASE の SinglePointCalculator に入っています。get_potential_energy()、get_forces()、get_stress()、get_charges() で取り出せます。Advance/OF-DFT を再実行する必要はありません。
  • スクリプトでは get_stress() の戻り値を表示していませんが、呼び出しておくことでストレスが計算され、拡張 XYZ ファイルに保存されます。get_stress() は Voigt 表記 (xx, yy, zz, yz, xz, xy) の eV/ų 単位で返します。160.2177 を掛けると GPa に換算できます。
  • 構造ごとに新しい Calculator を作成しているため、元素の組み合わせやセルの大きさが異なる構造を同じループで扱えます。
  • サンプルの構造ファイルは、8〜32 原子のセルにしています (Al は立方セルの 2×2×2、Si は立方セル、SiC は基本単位格子の 2×2×2)。v1.0.0 では、周期の短いセルで計算すると結果が変わるためです。自分の構造を計算するときも、セルを大きくしても結果が変わらないことを確認してください。
  • 読み直した電荷は、原子ごとの値のうち最小と最大を表示しています。