|
| 1 | +#!/usr/bin/env python |
| 2 | +''' |
| 3 | +Relaxes structure using ASE while retaining symmetry. Requires ASE>=3.23 |
| 4 | +
|
| 5 | + |
| 6 | +''' |
| 7 | +from typing import Dict, Optional |
| 8 | +import ase.optimize |
| 9 | +from ase.constraints import ExpCellFilter |
| 10 | +from ase.spacegroup.symmetrize import FixSymmetry |
| 11 | +from ase.io.trajectory import Trajectory |
| 12 | +from asimtools.calculators import load_calc |
| 13 | +from asimtools.utils import get_atoms |
| 14 | + |
| 15 | +def optimize_geometry( |
| 16 | + calc_id: str, |
| 17 | + image: Dict, |
| 18 | + optimizer: str = 'BFGS', |
| 19 | + fmax: float = 0.003, #Roughly 0.48GPa |
| 20 | + optimizer_args: Optional[Dict] = None, |
| 21 | + expcellfilter_args: Optional[Dict] = None, |
| 22 | +) -> Dict: |
| 23 | + """Relaxes cell (and atoms) using ase.constraints.ExpCellFilter while retaining symmetry |
| 24 | +
|
| 25 | + :param calc_id: calc_id in calc_input.yaml |
| 26 | + :type calc_id: str |
| 27 | + :param image: image specification |
| 28 | + :type image: Dict |
| 29 | + :param optimizer: Any optimizer from ase.optimize, defaults to 'BFGS' |
| 30 | + :type optimizer: str, optional |
| 31 | + :param fmax: fmax in optimizer, defaults to 0.003 which is ~0.48GPa |
| 32 | + :type fmax: float, optional |
| 33 | + :param expcellfilter_args: arguments for ase.constraints.ExpCellFilter, defaults to None |
| 34 | + :type expcellfilter_args: Optional[Dict], optional |
| 35 | + :return: Results including relaxed structure energy |
| 36 | + :rtype: Dict |
| 37 | + """ |
| 38 | + if expcellfilter_args is None: |
| 39 | + expcellfilter_args = {} |
| 40 | + if optimizer_args is None: |
| 41 | + optimizer_args = {} |
| 42 | + |
| 43 | + calc = load_calc(calc_id) |
| 44 | + atoms = get_atoms(**image) |
| 45 | + atoms.set_calculator(calc) |
| 46 | + |
| 47 | + ecf = ExpCellFilter(atoms, **expcellfilter_args) |
| 48 | + |
| 49 | + dyn = getattr(ase.optimize, optimizer)(ecf) |
| 50 | + traj_file = 'cell_relax.traj' |
| 51 | + traj = Trajectory( |
| 52 | + traj_file, |
| 53 | + 'w', |
| 54 | + atoms, |
| 55 | + properties=['energy', 'forces', 'stress'], |
| 56 | + ) |
| 57 | + dyn.attach(traj) |
| 58 | + try: |
| 59 | + dyn.run(fmax=fmax) |
| 60 | + except Exception: |
| 61 | + print('Failed to optimize atoms') |
| 62 | + raise |
| 63 | + |
| 64 | + image_file = 'image_output.xyz' |
| 65 | + atoms.write(image_file, format='extxyz') |
| 66 | + |
| 67 | + energy = float(atoms.get_potential_energy()) |
| 68 | + final_fmax = float(atoms.get_stress().max()) |
| 69 | + |
| 70 | + results = { |
| 71 | + 'energy': energy, |
| 72 | + 'final_fmax': final_fmax, |
| 73 | + 'files':{ |
| 74 | + 'image': image_file, |
| 75 | + 'traj': traj_file, |
| 76 | + } |
| 77 | + } |
| 78 | + return results |
0 commit comments