File size: 8,716 Bytes
db31a41 | 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 | #!/usr/bin/env python
"""
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', # nqc
np.dtype(('<d', (nqs, 3))), # xqc
np.dtype(('<d', (nks, nbnd))), # et_loc
np.dtype(('<c16', (nqs, nmodes, nmodes))), # dynq
np.dtype(('<c16', (nqs, nmodes, nks, nbnd, nbnd))), # epmatq
np.dtype(('<d', (3, 3, nat))), # zstar
np.dtype(('<d', (3, 3))), # epsi
]
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]
# Determine q-point ordering: match EPB xqc vs nscf.out
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
# Read braket files and fill g_frozen
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)
# Copy wfc files and charge density
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") + "/"
# Step 1: Generate HPRO/E3 braket files via Julia
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)")
# Step 2: Restore original DFPT EPB
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}")
# Step 3: Inject brakets into EPB
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.")
# Step 4: Patch NSCF eigenvalues from Julia SCF
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()
|