Overview
When performing structure optimisation calculations in ABINIT, the programme generates a HIST.nc file containing the complete trajectory of the optimisation process. The Abipy library provides convenient Python tools to extract and manipulate this data, enabling researchers to access final structures, analyse optimisation convergence, and export geometries in various standard formats.
Implementation
The following Python script demonstrates how to extract optimised structures from ABINIT output files and save them to a designated directory:
#!/usr/bin/env python
"""
Extract optimised structures from ABINIT output files
Process NetCDF output files using the Abipy library
"""
from abipy.dynamics.hist import HistFile
import os
def extract_structure_from_hist(hist_file, output_dir="../1_structures/optimized_structures"):
"""
Extract optimised structure from HIST.nc file
Parameters:
-----------
hist_file : str
Path to the HIST.nc file
output_dir : str
Directory for saving structure files
"""
# Create output directory
os.makedirs(output_dir, exist_ok=True)
# Open HIST file
print(f"Reading file: {hist_file}")
hist = HistFile(hist_file)
# Retrieve the final optimised structure
final_structure = hist.final_structure
# Obtain calculation information
base_name = os.path.basename(os.path.dirname(os.path.dirname(hist_file)))
print(f"\nStructure information:")
print(f"Lattice parameters: {final_structure.lattice}")
print(f"Number of atoms: {final_structure.num_sites}")
print(f"Chemical formula: {final_structure.composition}")
# Save in multiple formats
output_files = {
"cif": os.path.join(output_dir, f"{base_name}_optimized.cif"),
"poscar": os.path.join(output_dir, f"{base_name}_optimized.vasp"),
}
for fmt, filepath in output_files.items():
final_structure.to(fmt=fmt, filename=filepath)
print(f"Saved {fmt.upper()} format: {filepath}")
# Display optimisation trajectory information
all_structures = hist.structures
print(f"\nOptimisation information:")
print(f"Total optimisation steps: {len(all_structures)}")
# Read energy information
try:
energies = hist.reader.read_value("etotal")
print(f"Initial energy: {energies[0]:.6f} Ha")
print(f"Final energy: {energies[-1]:.6f} Ha")
print(f"Energy change: {energies[-1] - energies[0]:.6f} Ha")
except Exception as e:
print(f"Unable to read energy information: {e}")
# Close file
hist.close()
return final_structure
if __name__ == "__main__":
# Example usage
# Extract structure from al_fcc calculation
hist_file = "../2_calculations/al_fcc/outdata/out_HIST.nc"
if os.path.exists(hist_file):
structure = extract_structure_from_hist(hist_file)
print("\n✓ Structure extraction complete!")
else:
print(f"Error: File not found {hist_file}")
print("Please ensure the ABINIT calculation has completed and generated the HIST.nc file")Key Features
Structure Extraction
The script utilises the HistFile class from Abipy to interface with ABINIT's NetCDF output. The final_structure attribute provides direct access to the optimised geometry after the relaxation process has converged.
Multiple Output Formats
The extracted structure is saved in two widely-used formats:
- CIF (Crystallographic Information File): A standard format for crystallographic data exchange
- VASP POSCAR: Compatible with VASP and other common DFT codes
This flexibility facilitates seamless integration with various computational chemistry and materials science workflows.
Optimisation Trajectory Analysis
Beyond retrieving the final structure, the script also extracts:
- Total number of optimisation steps
- Energy evolution throughout the relaxation process
- Initial and final total energies
- Overall energy change during optimisation
This information is valuable for assessing convergence quality and understanding the optimisation behaviour.
Usage
To use this script with your ABINIT calculations:
- Ensure your ABINIT calculation has completed and generated a
HIST.ncfile - Update the
hist_filepath to point to your actual output file - Optionally modify the
output_dirto specify where structures should be saved - Run the script to extract and save the optimised structure
Error Handling
The script includes basic error handling to:
- Check for file existence before processing
- Handle cases where energy information cannot be read
- Create output directories if they don't exist
This makes the workflow more robust when processing multiple calculations or automating structure extraction tasks.