| |
| """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') |
|
|
| |
| REF_QE_QPOINTS_YAML = ( |
| '/home/apolyukhin/scripts/ml/diamond-qe/diamond_epc/displacements/qpoints.yaml' |
| ) |
|
|
| RY2EV = 13.605693122994 |
| RY_BOHR2EVANG = 25.71104309541616 |
|
|
|
|
| def load_params(path=None): |
| with open(path or PARAMS_DEFAULT) as f: |
| return json.load(f) |
|
|
|
|
| |
| |
| |
|
|
| 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 |
|
|
| |
| |
| |
| |
| 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 |
| continue |
| if line.strip().startswith('The '): |
| break |
| 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}') |
|
|
|
|
| |
| |
| |
|
|
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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}) ...') |
| |
| subprocess.run( |
| ['bash', '-c', |
| f'{activate} && nequip-train --config-path {SCRIPT_DIR} --config-name train'], |
| cwd=SCRIPT_DIR, check=True) |
|
|
|
|
| |
| |
| |
|
|
| 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}') |
|
|
|
|
| |
| |
| |
|
|
| 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') |
|
|
| |
| |
| 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']) |
|
|
|
|
| |
| |
| |
|
|
| 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}') |
|
|
|
|
| |
| |
| |
|
|
| 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) |
|
|
| |
| 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() |
|
|