| |
| """ |
| parse_ml_data.py — Inject ML EPC brakets into EPW for HPRO/DeepH-E3 comparison. |
| |
| For a given ML source (fd, hpro, e3): |
| 1. If source != 'fd': run julia run_hpro_brakets_epw.jl <source> |
| (generates displacements/epw/braket_list_rotated_* from ao_brackets npz) |
| 2. Restore original DFPT EPB: diamond_dft.save/diamond.epb1 → tmp/diamond.epb1 |
| 3. Inject ML brakets from displacements/epw/ into tmp/diamond.epb1 |
| 4. Patch NSCF eigenvalues in diamond.save/ from Julia's scf_0 save |
| |
| Usage: |
| python parse_ml_data.py [--source {fd,hpro,e3}] |
| python parse_ml_data.py --source hpro |
| python parse_ml_data.py --source e3 |
| |
| Then run EPW2: |
| mpirun -n 1 epw.x -npool 1 -in epw2.in > epw2_<source>.out |
| And compare: |
| python $ELEPHANY_PATH/epw/compare_epw.py ./ |
| """ |
| import argparse |
| import os |
| import re |
| import shutil |
| import subprocess |
| import xml.etree.ElementTree as ET |
|
|
| import numpy as np |
| from scipy.io import FortranFile |
| from ase.io import read as ase_read |
|
|
| SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) |
|
|
|
|
| def _determine_q_point_cart(nscf_out, iq): |
| """Extract Cartesian k-point iq (1-based) from nscf.out.""" |
| count = 0 |
| with open(nscf_out) as f: |
| for line in f: |
| if " k(" in line: |
| count += 1 |
| if count == iq: |
| parts = line.split() |
| coords = [p.rstrip(',)') for p in parts[4:7]] |
| return [float(c) for c in coords] |
| return [0.0, 0.0, 0.0] |
|
|
|
|
| def inject_brakets(path_to_epw, path_to_frozen, nbnd, nbndep, nks, nqs, nat, epb_name): |
| """Inject FD/HPRO/E3 brakets from displacements/epw/ into the EPB binary.""" |
| nmodes = 3 * nat |
|
|
| dtypes = [ |
| '<i', |
| np.dtype(('<d', (nqs, 3))), |
| np.dtype(('<d', (nks, nbnd))), |
| np.dtype(('<c16', (nqs, nmodes, nmodes))), |
| np.dtype(('<c16', (nqs, nmodes, nks, nbnd, nbnd))), |
| np.dtype(('<d', (3, 3, nat))), |
| np.dtype(('<d', (3, 3))), |
| ] |
|
|
| epb_path = os.path.join(path_to_epw, epb_name) |
| with FortranFile(epb_path, 'r') as f: |
| epb_data = list(f.read_record(*dtypes)) |
| xqc = epb_data[1] |
|
|
| |
| nscf_out = os.path.join(path_to_epw, "nscf.out") |
| atoms = ase_read(os.path.join(path_to_epw, "scf.out")) |
| recip_T = atoms.cell.reciprocal().T |
| a_factor = 2 * abs(recip_T[0, 0]) * atoms.get_cell_lengths_and_angles()[0] |
| real_mat = np.linalg.inv(recip_T) / a_factor |
|
|
| q_nscf = [_determine_q_point_cart(nscf_out, iq + 1) for iq in range(nqs)] |
| iq_ph_list = [] |
| for q_ph in xqc: |
| for i_nscf, q_ns in enumerate(q_nscf): |
| dq = np.abs(real_mat @ q_ns - real_mat @ q_ph) |
| if all(np.isclose(d, 0, atol=1e-5) or np.isclose(d, 1, atol=1e-5) for d in dq): |
| iq_ph_list.append(i_nscf) |
| break |
|
|
| |
| epw_dir = os.path.join(path_to_frozen, "epw") |
| g_frozen = np.zeros((nbnd, nbnd, nks, nmodes, nqs), dtype=complex) |
| for ik in range(1, nks + 1): |
| for iq_ph, iq_nscf in enumerate(iq_ph_list): |
| bfile = os.path.join(epw_dir, f"braket_list_rotated_{ik}_{iq_nscf + 1}") |
| data = np.loadtxt(bfile) |
| for line in data: |
| iat = int(line[0]) |
| i_cart = int(line[1]) |
| im = 3 * (iat - 1) + i_cart |
| i = int(line[3]) |
| j = int(line[2]) |
| if 1 <= i <= nbndep and 1 <= j <= nbndep: |
| g_frozen[i - 1, j - 1, ik - 1, im - 1, iq_ph] = line[4] - 1j * line[5] |
|
|
| epb_data[4] = g_frozen.T |
| with FortranFile(epb_path, 'w') as f: |
| f.write_record(*epb_data) |
| print(f" Brakets injected into {epb_path}") |
|
|
|
|
| def patch_eigenvalues(path_to_kcw, path_to_save, path_to_out, nks): |
| """Replace eigenvalues in NSCF save XML with Julia SCF eigenvalues; copy wfc files.""" |
| path_kp = os.path.join(path_to_kcw, "data-file-schema.xml") |
| path_qe = os.path.join(path_to_save, "data-file-schema.xml") |
| path_out = os.path.join(path_to_out, "data-file-schema.xml") |
|
|
| with open(path_qe) as f: |
| lines_qe = f.readlines() |
| header = lines_qe[:3] |
| footer = lines_qe[-1] |
|
|
| tree_kp = ET.parse(path_kp) |
| tree_qe = ET.parse(path_qe) |
|
|
| kp_energies = [] |
| for ks in tree_kp.iter('ks_energies'): |
| vals = re.findall(r"[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?", ks[2].text) |
| kp_energies.append(vals) |
|
|
| for idx, ks in enumerate(tree_qe.iter('ks_energies')): |
| raw = ks[2].text |
| qe_vals = re.findall(r"[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?", raw) |
| for i, (old, new) in enumerate(zip(qe_vals, kp_energies[idx])): |
| raw = raw.replace(old, new, 1) |
| ks[2].text = raw |
|
|
| tree_qe.write(path_out, encoding='UTF-8', xml_declaration=True, short_empty_elements=False) |
|
|
| with open(path_out) as f: |
| out_lines = f.readlines() |
| out_lines[:3] = header |
| out_lines[-1] = footer |
| with open(path_out, 'w') as f: |
| f.writelines(out_lines) |
|
|
| |
| for i in range(nks): |
| src = os.path.join(path_to_kcw, f"wfc{i + 1}.dat") |
| dest = os.path.join(path_to_out, f"wfc{i + 1}.dat") |
| shutil.copy2(src, dest) |
| shutil.copy2(os.path.join(path_to_kcw, "charge-density.dat"), path_to_out) |
| print(f" Eigenvalues patched and {nks} wfc files copied to {path_to_out}") |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description="Inject ML EPC brakets into EPW binary for HPRO/E3 comparison." |
| ) |
| parser.add_argument("--source", choices=["fd", "hpro", "e3"], default="fd", |
| help="Braket source: fd (FD from diamond.jl), hpro, or e3") |
| parser.add_argument("--path_to_epw", default=SCRIPT_DIR + "/", |
| help="Path to 4_epw directory (default: script dir)") |
| parser.add_argument("--path_to_frozen", default=None, |
| help="Path to displacements/ dir (default: <path_to_epw>/displacements/)") |
| parser.add_argument("--nbnd", default=4, type=int, help="Number of Wannier bands") |
| parser.add_argument("--nbndep", default=4, type=int, help="Number of EP bands") |
| parser.add_argument("--mesh", default=216, type=int, help="Number of k-points") |
| parser.add_argument("--mesh_q", default=1, type=int, help="Number of q-points") |
| parser.add_argument("--nat", default=2, type=int, help="Number of atoms") |
| parser.add_argument("--epb", default="tmp/diamond.epb1", help="EPB file (relative to path_to_epw)") |
| args = parser.parse_args() |
|
|
| path_to_epw = args.path_to_epw |
| path_to_frozen = args.path_to_frozen or os.path.join(path_to_epw, "displacements") + "/" |
|
|
| |
| if args.source != "fd": |
| print(f"Step 1: Generating {args.source.upper()} braket files via Julia...") |
| jl_script = os.path.join(SCRIPT_DIR, "run_hpro_brakets_epw.jl") |
| subprocess.run(["julia", jl_script, args.source], cwd=SCRIPT_DIR, check=True) |
| print("Step 1 done.") |
| else: |
| print("Step 1: Using FD braket files (displacements/epw/ from diamond.jl calc_ep)") |
|
|
| |
| print("Step 2: Restoring DFPT EPB backup...") |
| epb_backup = os.path.join(path_to_epw, "diamond_dft.save", "diamond.epb1") |
| epb_target = os.path.join(path_to_epw, args.epb) |
| os.makedirs(os.path.dirname(epb_target), exist_ok=True) |
| shutil.copy2(epb_backup, epb_target) |
| print(f" {epb_backup} → {epb_target}") |
|
|
| |
| print("Step 3: Injecting brakets into EPB binary...") |
| inject_brakets( |
| path_to_epw, path_to_frozen, |
| args.nbnd, args.nbndep, args.mesh, args.mesh_q, args.nat, args.epb, |
| ) |
| print("Step 3 done.") |
|
|
| |
| print("Step 4: Patching NSCF eigenvalues...") |
| path_to_kcw = os.path.join(path_to_frozen, "scf_0", "tmp", "scf.save") + "/" |
| path_to_save = os.path.join(path_to_epw, "diamond_dft.save") + "/" |
| path_to_out = os.path.join(path_to_epw, "tmp", "diamond.save") + "/" |
| patch_eigenvalues(path_to_kcw, path_to_save, path_to_out, nks=args.mesh) |
| print("Step 4 done.") |
|
|
| print(f"\nAll done. Now run:") |
| print(f" mpirun -n 1 epw.x -npool 1 -in epw2.in > epw2_{args.source}.out") |
| print(f" python $ELEPHANY_PATH/epw/compare_epw.py ./") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|