File size: 18,137 Bytes
e9e349d | 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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | #!/usr/bin/env python
"""Train NequIP force field for diamond; compare DFPT and ML phonons at Gamma.
Steps:
1. Build forces/dataset.xyz from QE displaced configs
(re-runs SCF with tprnfor=.true. for any disp without forces)
2. Run DFPT (ph.x) on pristine UC at q=Gamma
3. Train NequIP MLIP (nequip-train train.yaml) in deeph conda env
4. Compile model to diamond_ase.nequip.pt2 (nequip-compile)
5. Run phonopy + NequIP calculator to get ML Gamma frequencies
6. Plot + print comparison: DFPT vs ML phonons
Usage:
python train_force.py [params.json]
python train_force.py [params.json] --skip-training # use existing checkpoint
"""
import glob
import json
import os
import re
import subprocess
import sys
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, '..', '..', '1_data_prepare', 'data'))
PARAMS_DEFAULT = os.path.abspath(os.path.join(SCRIPT_DIR, '..', '..', '1_data_prepare', 'params.json'))
DATASET_XYZ = os.path.join(SCRIPT_DIR, 'dataset.xyz')
DFPT_DIR = os.path.join(SCRIPT_DIR, 'dfpt')
OUTPUTS_DIR = os.path.join(SCRIPT_DIR, 'outputs')
PT2_PATH = os.path.join(SCRIPT_DIR, 'diamond_ase.nequip.pth')
PT2_REF_PATH = os.path.join(SCRIPT_DIR, 'diamond_ase_ref.nequip.pt2')
TRAIN_YAML = os.path.join(SCRIPT_DIR, 'train.yaml')
# Reference QE phonon frequencies (phonopy+QE finite difference, not DFPT)
REF_QE_QPOINTS_YAML = (
'/home/apolyukhin/scripts/ml/diamond-qe/diamond_epc/displacements/qpoints.yaml'
)
RY2EV = 13.605693122994 # Rydberg β eV
RY_BOHR2EVANG = 25.71104309541616 # Ry/bohr β eV/Γ
def load_params(path=None):
with open(path or PARAMS_DEFAULT) as f:
return json.load(f)
# ---------------------------------------------------------------------------
# Step 1: Build forces dataset
# ---------------------------------------------------------------------------
def has_forces_in_pwout(pw_out_path):
"""Return True if pw.out already contains force output."""
try:
with open(pw_out_path) as f:
for line in f:
if 'Forces acting on atoms' in line:
return True
except FileNotFoundError:
pass
return False
def add_tprnfor_to_pwin(pw_in_path):
"""Patch pw.in to add tprnfor = .true. in &CONTROL (idempotent)."""
with open(pw_in_path) as f:
content = f.read()
if 'tprnfor' in content:
return
content = content.replace('&CONTROL', '&CONTROL\n tprnfor = .true.')
with open(pw_in_path, 'w') as f:
f.write(content)
def read_qe_forces(pw_out_path):
"""Parse energy (eV) and forces (eV/Γ
) from a QE pw.out with tprnfor."""
with open(pw_out_path) as f:
text = f.read()
energy_match = re.search(r'!\s+total energy\s+=\s+([-\d.]+)\s+Ry', text)
if not energy_match:
raise ValueError(f'No converged energy in {pw_out_path}')
energy_ev = float(energy_match.group(1)) * RY2EV
# Locate "Forces acting on atoms" header and read only the TOTAL forces block.
# QE also prints decompositions (non-local, ionic, ...) with the same
# "atom N type T force = fx fy fz" format, so we stop at the first blank line
# or "The ... to forces" line after the initial block.
m = re.search(r'Forces acting on atoms.*?\n', text)
if not m:
raise ValueError(f'No forces in {pw_out_path}')
block_start = m.end()
forces = []
for line in text[block_start:].split('\n'):
if not line.strip():
if forces:
break # blank line ends the total-force block
continue
if line.strip().startswith('The '):
break # start of decomposition sub-section
parts = line.split()
if len(parts) >= 9 and 'atom' in parts:
forces.append([float(parts[-3]), float(parts[-2]), float(parts[-1])])
if not forces:
raise ValueError(f'Could not parse force lines in {pw_out_path}')
return energy_ev, np.array(forces) * RY_BOHR2EVANG
def build_forces_dataset(params):
"""Build dataset.xyz from all disp-XX QE outputs; re-run SCF if forces missing."""
if os.path.exists(DATASET_XYZ):
print(f' Dataset exists: {DATASET_XYZ}')
return
from ase.io import read as ase_read, write as ase_write
from ase.calculators.singlepoint import SinglePointCalculator
qe_setup = params['paths']['qe_setup']
np_qe = params['execution']['mpi_np']
disp_dirs = sorted(glob.glob(os.path.join(DATA_DIR, 'disp-*')))
print(f' Processing {len(disp_dirs)} displaced configs...')
atoms_list = []
for disp_dir in disp_dirs:
label = os.path.basename(disp_dir)
scf_dir = os.path.join(disp_dir, 'scf')
pw_in = os.path.join(scf_dir, 'pw.in')
pw_out = os.path.join(scf_dir, 'pw.out')
if not has_forces_in_pwout(pw_out):
print(f' [{label}] Re-running SCF with tprnfor=.true. ...')
add_tprnfor_to_pwin(pw_in)
bash_cmd = (f"source {qe_setup} 2>/dev/null; "
f"mpirun -np {np_qe} pw.x < pw.in > pw.out 2>&1")
subprocess.run(['bash', '-c', bash_cmd], cwd=scf_dir, check=True)
else:
print(f' [{label}] Forces already in pw.out')
energy_ev, forces_evang = read_qe_forces(pw_out)
atoms = ase_read(pw_out, format='espresso-out')
atoms.calc = SinglePointCalculator(
atoms, energy=energy_ev, forces=forces_evang)
atoms_list.append(atoms)
fmax = np.abs(forces_evang).max()
print(f' [{label}] E={energy_ev:.4f} eV |F|max={fmax:.4f} eV/Γ
')
ase_write(DATASET_XYZ, atoms_list, format='extxyz')
print(f' Wrote {len(atoms_list)} structures β {DATASET_XYZ}')
# ---------------------------------------------------------------------------
# Step 2: DFPT at Gamma
# ---------------------------------------------------------------------------
def run_dfpt(params):
"""Run ph.x on pristine UC at q=Gamma; skip if ph.out already exists."""
ph_out = os.path.join(DFPT_DIR, 'ph.out')
if os.path.exists(ph_out):
print(f' DFPT output exists: {ph_out}')
return
uc_scf_dir = os.path.join(DATA_DIR, 'bands', 'uc', 'scf')
os.makedirs(DFPT_DIR, exist_ok=True)
ph_in_text = (
"Phonons at Gamma\n"
"&inputph\n"
" prefix = 'diamond'\n"
f" outdir = '{uc_scf_dir}/'\n"
f" fildyn = '{DFPT_DIR}/dynmat.dat'\n"
" ldisp = .false.\n"
"/\n"
"0.0 0.0 0.0\n"
)
with open(os.path.join(DFPT_DIR, 'ph.in'), 'w') as f:
f.write(ph_in_text)
qe_setup = params['paths']['qe_setup']
np_qe = params['execution']['mpi_np']
bash_cmd = (f"source {qe_setup} 2>/dev/null; "
f"mpirun -np {np_qe} ph.x < ph.in > ph.out 2>&1")
print(' Running ph.x at q=Gamma ...')
subprocess.run(['bash', '-c', bash_cmd], cwd=DFPT_DIR, check=True)
print(f' DFPT done: {ph_out}')
def parse_dfpt_gamma_freqs():
"""Parse Gamma phonon frequencies from ph.out β (thz_array, cm1_array)."""
ph_out = os.path.join(DFPT_DIR, 'ph.out')
freqs_thz, freqs_cm1 = [], []
with open(ph_out) as f:
for line in f:
m = re.search(
r'freq\s*\(\s*\d+\)\s*=\s*([\d.]+)\s*\[THz\]\s*=\s*([\d.]+)\s*\[cm-1\]',
line)
if m:
freqs_thz.append(float(m.group(1)))
freqs_cm1.append(float(m.group(2)))
return np.array(freqs_thz), np.array(freqs_cm1)
def parse_phonopy_qpoints_yaml(yaml_path=None):
"""Read Gamma phonon frequencies from a phonopy qpoints.yaml β (thz, cm1)."""
import yaml as _yaml
path = yaml_path or REF_QE_QPOINTS_YAML
with open(path) as f:
data = _yaml.safe_load(f)
cm1 = np.array([b['frequency'] for b in data['phonon'][0]['band']])
thz = cm1 / 33.35641
return thz, cm1
# ---------------------------------------------------------------------------
# Step 3: NequIP training
# ---------------------------------------------------------------------------
def find_best_checkpoint():
"""Return (ckpt_path, run_dir) for latest best.ckpt, or (None, None)."""
for run_dir in sorted(glob.glob(os.path.join(OUTPUTS_DIR, '*', '*')),
reverse=True):
ckpt = os.path.join(run_dir, 'best.ckpt')
if os.path.exists(ckpt):
return ckpt, run_dir
return None, None
def run_nequip_training(params):
"""Run nequip-train train.yaml in the deeph conda env."""
t = params.get('forces', {})
conda_env = t.get('conda_env', 'deeph')
conda_base = params['paths']['conda_base']
activate = (f'source {conda_base}/etc/profile.d/conda.sh'
f' && conda activate {conda_env}')
print(f' Running nequip-train (conda: {conda_env}) ...')
# nequip-train uses Hydra: pass --config-path (dir) and --config-name (no .yaml)
subprocess.run(
['bash', '-c',
f'{activate} && nequip-train --config-path {SCRIPT_DIR} --config-name train'],
cwd=SCRIPT_DIR, check=True)
# ---------------------------------------------------------------------------
# Step 4: Compile model
# ---------------------------------------------------------------------------
def compile_model(params):
"""Compile best.ckpt β diamond_ase.nequip.pt2 via nequip-compile."""
if os.path.exists(PT2_PATH):
print(f' Compiled model exists: {PT2_PATH}')
return
ckpt, _ = find_best_checkpoint()
if ckpt is None:
print(' ERROR: No checkpoint found; training may not have completed.')
return
t = params.get('forces', {})
conda_env = t.get('conda_env', 'deeph')
conda_base = params['paths']['conda_base']
activate = (f'source {conda_base}/etc/profile.d/conda.sh'
f' && conda activate {conda_env}')
device = t.get('device', 'cuda')
cmd = (f'{activate} && nequip-compile --mode torchscript'
f' --device {device} --target ase {ckpt} {PT2_PATH}')
print(f' Compiling {os.path.basename(ckpt)} β diamond_ase.nequip.pt2 ...')
subprocess.run(['bash', '-c', cmd], cwd=SCRIPT_DIR, check=True)
print(f' Compiled: {PT2_PATH}')
# ---------------------------------------------------------------------------
# Step 5: Phonopy + NequIP at Gamma
# ---------------------------------------------------------------------------
def run_phonopy_ml(params, model_path=None, freqs_json=None):
"""Compute ML Gamma phonon frequencies using phonopy + NequIP calculator.
Runs in the deeph conda env via a subprocess launcher.
Returns freqs_thz as a (nbands,) numpy array.
"""
model_path = model_path or PT2_PATH
freqs_json = freqs_json or os.path.join(SCRIPT_DIR, '_phonopy_freqs.json')
t = params.get('forces', {})
conda_env = t.get('conda_env', 'deeph')
conda_base = params['paths']['conda_base']
device = t.get('device', 'cuda')
# Use the original scf.in (ibrav=0, CELL_PARAMETERS angstrom) β the bands
# pw.in uses 'alat' units which newer ASE versions cannot parse.
uc_pw_in = os.path.abspath(os.path.join(DATA_DIR, '..', 'scf.in'))
launcher = os.path.join(SCRIPT_DIR, '_phonopy_launcher.py')
with open(launcher, 'w') as f:
f.write(f"""import json, numpy as np
import phonopy
from phonopy.structure.atoms import PhonopyAtoms
from nequip.ase import NequIPCalculator
from ase import Atoms
from ase.io import read as ase_read
uc = ase_read('{uc_pw_in}', format='espresso-in')
calc = NequIPCalculator.from_compiled_model(
'{model_path}', device='{device}', chemical_species_to_atom_type_map=True)
sc_matrix = [[4, 0, 0], [0, 4, 0], [0, 0, 4]]
ph = phonopy.Phonopy(
unitcell=PhonopyAtoms(
symbols=uc.get_chemical_symbols(),
cell=uc.get_cell(),
scaled_positions=uc.get_scaled_positions(),
),
supercell_matrix=sc_matrix,
primitive_matrix='auto',
)
ph.generate_displacements(distance=0.01)
supercells = ph.supercells_with_displacements
print(f' Phonopy: {{len(supercells)}} displacements ({{len(supercells[0])}} atoms each)')
forces_list = []
for i, sc in enumerate(supercells):
a = Atoms(symbols=sc.get_chemical_symbols(),
positions=sc.get_positions(),
cell=sc.get_cell(), pbc=True)
a.calc = calc
f = a.get_forces()
forces_list.append(f)
if (i + 1) % 5 == 0 or i == 0:
print(f' [{{i+1}}/{{len(supercells)}}] |F|max={{np.abs(f).max():.4f}} eV/A')
ph.forces = forces_list
ph.produce_force_constants()
ph.run_qpoints([[0, 0, 0]], with_eigenvectors=False)
freqs_thz = ph.get_qpoints_dict()['frequencies'][0].tolist()
with open('{freqs_json}', 'w') as fp:
json.dump({{'freqs_thz': freqs_thz}}, fp)
print(f' Gamma freqs written to {freqs_json}')
""")
activate = (f'source {conda_base}/etc/profile.d/conda.sh'
f' && conda activate {conda_env}')
print(f' Running phonopy + NequIP in {conda_env} env ...')
subprocess.run(['bash', '-c', f'{activate} && python {launcher}'],
cwd=SCRIPT_DIR, check=True)
with open(freqs_json) as fp:
data = json.load(fp)
return np.array(data['freqs_thz'])
# ---------------------------------------------------------------------------
# Step 6: Compare and plot
# ---------------------------------------------------------------------------
def print_phonon_table(dfpt_thz, dfpt_cm1, ml_thz):
"""Print mode-by-mode comparison table."""
cm1_per_thz = 33.35641
ml_cm1 = ml_thz * cm1_per_thz
n = max(len(dfpt_thz), len(ml_thz))
print(f"{'Mode':>5} {'DFPT (THz)':>11} {'DFPT (cm-1)':>12} "
f"{'ML (THz)':>10} {'ML (cm-1)':>11} {'Err (cm-1)':>12}")
print('-' * 65)
for i in range(n):
d_thz = dfpt_thz[i] if i < len(dfpt_thz) else 0.0
d_cm1 = dfpt_cm1[i] if i < len(dfpt_cm1) else 0.0
m_thz = ml_thz[i] if i < len(ml_thz) else 0.0
m_cm1 = ml_cm1[i] if i < len(ml_cm1) else 0.0
print(f'{i+1:>5} {d_thz:>11.4f} {d_cm1:>12.2f} '
f'{m_thz:>10.4f} {m_cm1:>11.2f} {m_cm1-d_cm1:>+12.2f}')
opt_d = dfpt_thz[dfpt_thz > 1.0]
opt_m = ml_thz[ml_thz > 1.0]
if len(opt_d) and len(opt_m):
err_pct = (np.mean(opt_m) - np.mean(opt_d)) / np.mean(opt_d) * 100
print(f'\nOptical: DFPT={np.mean(opt_d):.2f} THz, '
f'ML={np.mean(opt_m):.2f} THz, err={err_pct:+.1f}%')
def plot_phonon_comparison(dfpt_thz, ml_thz, outpath):
"""Bar chart of DFPT vs ML Gamma phonon frequencies."""
cm1_per_thz = 33.35641
dfpt_cm1 = dfpt_thz * cm1_per_thz
ml_cm1 = ml_thz * cm1_per_thz
n = max(len(dfpt_cm1), len(ml_cm1))
modes = np.arange(1, n + 1)
d = np.pad(dfpt_cm1, (0, n - len(dfpt_cm1)))
m = np.pad(ml_cm1, (0, n - len(ml_cm1)))
fig, ax = plt.subplots(figsize=(6, 4))
w = 0.35
ax.bar(modes - w/2, d, w, label='DFPT (ph.x)', color='steelblue')
ax.bar(modes + w/2, m, w, label='ML (NequIP)', color='tomato')
ax.set_xlabel('Mode')
ax.set_ylabel('Frequency (cm$^{-1}$)')
ax.set_xticks(modes)
ax.set_title('Diamond $\\Gamma$-point phonons: DFPT vs ML (NequIP)')
ax.legend()
fig.tight_layout()
fig.savefig(outpath, dpi=150)
plt.close(fig)
print(f' Saved: {outpath}')
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
skip_training = '--skip-training' in sys.argv
use_ref_model = '--ref-model' in sys.argv
params_path = next((a for a in sys.argv[1:] if not a.startswith('--')), None)
params = load_params(params_path)
# Diagnostic: run phonopy with reference model and compare to reference QE phonopy+QE data
if use_ref_model:
print('=== DIAGNOSTIC: reference NequIP model ===')
freqs_json = os.path.join(SCRIPT_DIR, '_phonopy_freqs_ref.json')
if os.path.exists(freqs_json):
print(f' Using cached: {freqs_json}')
with open(freqs_json) as fp:
ml_freqs_thz = np.array(json.load(fp)['freqs_thz'])
else:
print(' Running phonopy with reference model...')
ml_freqs_thz = run_phonopy_ml(params, model_path=PT2_REF_PATH,
freqs_json=freqs_json)
qe_thz, qe_cm1 = parse_phonopy_qpoints_yaml()
print('\nGamma phonons β reference model vs reference QE (phonopy+QE):')
print_phonon_table(qe_thz, qe_cm1, ml_freqs_thz)
outpath = os.path.join(SCRIPT_DIR, 'phonon_comparison_ref.png')
plot_phonon_comparison(qe_thz, ml_freqs_thz, outpath)
print('\ntrain_force.py --ref-model done.')
return
print('Step 1: Building forces dataset...')
build_forces_dataset(params)
print('\nStep 2: Running DFPT at q=Gamma...')
run_dfpt(params)
print('\nStep 3: NequIP training...')
ckpt, _ = find_best_checkpoint()
if skip_training and ckpt:
print(f' --skip-training: using existing checkpoint: {ckpt}')
elif ckpt and os.path.exists(PT2_PATH):
print(f' Using existing checkpoint: {ckpt}')
else:
run_nequip_training(params)
ckpt, _ = find_best_checkpoint()
if ckpt is None:
print('ERROR: Training did not produce a checkpoint.')
sys.exit(1)
print('\nStep 4: Compiling model...')
compile_model(params)
print('\nStep 5: Running phonopy + NequIP at Gamma...')
ml_freqs_thz = run_phonopy_ml(params)
print('\nStep 6: Comparing phonons...')
dfpt_thz, dfpt_cm1 = parse_dfpt_gamma_freqs()
print_phonon_table(dfpt_thz, dfpt_cm1, ml_freqs_thz)
outpath = os.path.join(SCRIPT_DIR, 'phonon_comparison.png')
plot_phonon_comparison(dfpt_thz, ml_freqs_thz, outpath)
print('\ntrain_force.py done.')
if __name__ == '__main__':
main()
|