File size: 9,467 Bytes
3e02ab8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | """Relax an ASE structure with a compiled NequIP model.
This follows the official NequIP ASE relaxation example: it supports atomic
and cell relaxation, tracks forces at every ionic step, and aborts exploding
relaxations before they can hang indefinitely.
"""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
from typing import Any
import numpy as np
import torch
from ase import Atoms
from ase.build import bulk
from ase.filters import ExpCellFilter, FrechetCellFilter
from ase.io import read, write
import ase.optimize as opt
from onescience.utils.nequip.integrations.ase import NequIPCalculator
OPTIMIZERS = {
"BFGS": opt.BFGS,
"BFGSLineSearch": opt.BFGSLineSearch,
"FIRE": opt.FIRE,
"FIRE2": opt.FIRE2,
"GOQN": opt.GoodOldQuasiNewton,
"GPMin": opt.GPMin,
"LBFGS": opt.LBFGS,
"LBFGSLineSearch": opt.LBFGSLineSearch,
}
CELL_FILTERS = {
"exp": ExpCellFilter,
"frechet": FrechetCellFilter,
}
def default_compiled_model() -> str | None:
models_dir = os.environ.get("ONESCIENCE_MODELS_DIR")
if not models_dir:
return None
return str(Path(models_dir) / "NequIP" / "NequIP-OAM-L-0.1.nequip.pth")
def load_structure(
input_path: str | None,
index: int,
element: str,
crystal_structure: str,
lattice_constant: float,
displacement: float,
) -> tuple[Atoms, str]:
if input_path:
path = Path(input_path).expanduser().resolve()
if not path.is_file():
raise FileNotFoundError(f"input structure not found: {path}")
return read(path, index=index), f"{path}[{index}]"
atoms = bulk(
element,
crystalstructure=crystal_structure,
a=lattice_constant,
cubic=True,
)
if displacement:
atoms.positions[0, 0] += displacement
return atoms, (
f"ASE bulk {element} {crystal_structure}, a={lattice_constant} Angstrom, "
f"atom-0 displacement={displacement} Angstrom"
)
def _max_vector_norm(values: np.ndarray) -> float:
array = np.asarray(values)
if array.size == 0:
return 0.0
return float(np.linalg.norm(array.reshape(-1, 3), axis=1).max())
def relaxation_snapshot(atoms: Atoms, target: Any, step: int) -> dict[str, Any]:
forces = atoms.get_forces()
optimizer_forces = target.get_forces()
stress = atoms.get_stress()
return {
"step": step,
"energy_ev": float(atoms.get_potential_energy()),
"energy_ev_per_atom": float(atoms.get_potential_energy() / len(atoms)),
"volume_angstrom3": float(atoms.get_volume()),
"max_atomic_force_ev_per_angstrom": _max_vector_norm(forces),
"max_optimizer_force": _max_vector_norm(optimizer_forces),
"stress_ev_per_angstrom3_voigt": np.asarray(stress).tolist(),
"max_abs_stress_ev_per_angstrom3": float(np.abs(stress).max()),
}
def relax_structure(
atoms: Atoms,
*,
optimizer_name: str,
cell_filter_name: str,
fixed_cell: bool,
fmax: float,
steps: int,
force_limit: float,
logfile: Path,
trajectory: Path,
) -> tuple[bool, int, list[dict[str, Any]]]:
if not fixed_cell and not atoms.pbc.all():
raise ValueError("cell relaxation requires periodic boundaries; use --fixed-cell")
target = atoms if fixed_cell else CELL_FILTERS[cell_filter_name](atoms)
optimizer_cls = OPTIMIZERS[optimizer_name]
history: list[dict[str, Any]] = []
converged = False
with optimizer_cls(
target,
logfile=str(logfile),
trajectory=str(trajectory),
) as optimizer:
for converged in optimizer.irun(fmax=fmax, steps=steps):
snapshot = relaxation_snapshot(atoms, target, optimizer.nsteps)
history.append(snapshot)
if max(
snapshot["max_atomic_force_ev_per_angstrom"],
snapshot["max_optimizer_force"],
) > force_limit:
raise RuntimeError(
f"relaxation force exceeded safety limit {force_limit:g}"
)
return bool(converged), int(optimizer.nsteps), history
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--compiled-model", default=default_compiled_model())
parser.add_argument(
"--input",
help="CIF, POSCAR, XYZ, trajectory, or another ASE-readable structure",
)
parser.add_argument("--index", type=int, default=0)
parser.add_argument("--device", default="cuda")
parser.add_argument("--optimizer", choices=sorted(OPTIMIZERS), default="GOQN")
parser.add_argument(
"--cell-filter", choices=sorted(CELL_FILTERS), default="frechet"
)
parser.add_argument(
"--fixed-cell",
action="store_true",
help="relax atomic positions only; the default also relaxes the cell",
)
parser.add_argument("--fmax", type=float, default=0.05)
parser.add_argument("--steps", type=int, default=500)
parser.add_argument("--force-limit", type=float, default=1.0e6)
parser.add_argument("--element", default="Si")
parser.add_argument("--crystal-structure", default="diamond")
parser.add_argument("--lattice-constant", type=float, default=5.65)
parser.add_argument("--displacement", type=float, default=0.08)
parser.add_argument("--output-dir", default="outputs/structure_relaxation")
parser.add_argument("--output-structure", default="relaxed.cif")
parser.add_argument("--result", default="result.json")
parser.add_argument("--trajectory", default="relax.traj")
parser.add_argument("--log", default="relax.log")
args = parser.parse_args()
if not args.compiled_model:
parser.error("--compiled-model is required when ONESCIENCE_MODELS_DIR is unset")
compiled_model = Path(args.compiled_model).expanduser().resolve()
if not compiled_model.is_file():
parser.error(f"compiled model not found: {compiled_model}")
if args.fmax <= 0:
parser.error("--fmax must be positive")
if args.steps < 1:
parser.error("--steps must be positive")
if args.force_limit <= 0:
parser.error("--force-limit must be positive")
output_dir = Path(args.output_dir).expanduser().resolve()
output_dir.mkdir(parents=True, exist_ok=True)
output_structure = output_dir / args.output_structure
result_path = output_dir / args.result
trajectory_path = output_dir / args.trajectory
log_path = output_dir / args.log
try:
atoms, input_source = load_structure(
args.input,
args.index,
args.element,
args.crystal_structure,
args.lattice_constant,
args.displacement,
)
except (FileNotFoundError, IndexError, ValueError) as error:
parser.error(str(error))
if len(atoms) == 0:
parser.error("input structure has no atoms")
species = sorted(set(atoms.get_chemical_symbols()))
atoms.calc = NequIPCalculator.from_compiled_model(
compile_path=str(compiled_model),
chemical_species_to_atom_type_map={symbol: symbol for symbol in species},
device=args.device,
)
try:
converged, nsteps, history = relax_structure(
atoms,
optimizer_name=args.optimizer,
cell_filter_name=args.cell_filter,
fixed_cell=args.fixed_cell,
fmax=args.fmax,
steps=args.steps,
force_limit=args.force_limit,
logfile=log_path,
trajectory=trajectory_path,
)
except ValueError as error:
parser.error(str(error))
write(output_structure, atoms)
result = {
"compiled_model": str(compiled_model),
"device": args.device,
"device_name": torch.cuda.get_device_name(0)
if args.device.startswith("cuda") and torch.cuda.is_available()
else "cpu",
"input_source": input_source,
"formula": atoms.get_chemical_formula(),
"num_atoms": len(atoms),
"chemical_species_to_atom_type_map": {
symbol: symbol for symbol in species
},
"optimizer": args.optimizer,
"cell_filter": None if args.fixed_cell else args.cell_filter,
"fixed_cell": args.fixed_cell,
"fmax_ev_per_angstrom": args.fmax,
"max_steps": args.steps,
"force_safety_limit": args.force_limit,
"converged": converged,
"steps": nsteps,
"initial": history[0],
"final": history[-1],
"energy_change_ev": history[-1]["energy_ev"] - history[0]["energy_ev"],
"volume_change_angstrom3": (
history[-1]["volume_angstrom3"] - history[0]["volume_angstrom3"]
),
"history": history,
"relaxed_structure": str(output_structure),
"trajectory": str(trajectory_path),
"log": str(log_path),
}
result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print("formula:", result["formula"])
print("atoms:", result["num_atoms"])
print("converged:", converged)
print("steps:", nsteps)
print("initial energy (eV):", result["initial"]["energy_ev"])
print("final energy (eV):", result["final"]["energy_ev"])
print(
"final max force (eV/Angstrom):",
result["final"]["max_atomic_force_ev_per_angstrom"],
)
print("result:", result_path)
if __name__ == "__main__":
main()
|