| |
| """ |
| Prepare displaced supercell configurations and band structure inputs for diamond. |
| |
| Reads scf.in (pristine unit cell), then: |
| - Creates data/disp-XX/ with QE SCF + pw2bgw + HPRO calc inputs |
| - Creates data/bands/uc/ and data/bands/sc/ with pristine band structure inputs |
| - Saves k-path info to data/bands/kpath.json for use by compare_bands.py |
| |
| Usage: python prepare.py [params.json] |
| """ |
| import json |
| import os |
| import sys |
|
|
| import numpy as np |
| from ase.io import read |
| from ase.io.espresso import read_fortran_namelist |
| from ase.build import make_supercell |
|
|
| SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) |
|
|
|
|
| def load_params(path=None): |
| if path is None: |
| path = os.path.join(SCRIPT_DIR, 'params.json') |
| with open(path) as f: |
| return json.load(f) |
|
|
|
|
| def parse_scf_qe_params(scf_path): |
| """Parse ecutwfc, conv_thr, and k_uc from a QE scf.in using ASE.""" |
| with open(scf_path) as f: |
| namelists, cards = read_fortran_namelist(f) |
| ecutwfc = namelists['system']['ecutwfc'] |
| conv_thr = namelists['electrons']['conv_thr'] |
| k_uc = None |
| for i, line in enumerate(cards): |
| if line.strip().upper().startswith('K_POINTS') and 'AUTOMATIC' in line.upper(): |
| vals = cards[i + 1].split() |
| k_uc = [int(vals[0]), int(vals[1]), int(vals[2])] |
| break |
| return ecutwfc, conv_thr, k_uc |
|
|
|
|
| def _scf_header(prefix, pseudo_dir, a, ecutwfc, conv_thr, n_atoms): |
| return ( |
| f"&CONTROL\n calculation = 'scf'\n prefix = '{prefix}'\n" |
| f" pseudo_dir = '{pseudo_dir}'\n outdir = './'\n/\n\n" |
| f"&SYSTEM\n ibrav = 0\n A = {a}\n ecutwfc = {ecutwfc}\n" |
| f" nat = {n_atoms}\n ntyp = 1\n/\n\n" |
| f"&ELECTRONS\n conv_thr = {conv_thr}\n/\n\n" |
| ) |
|
|
|
|
| def _cell_and_atoms(lat_frac, atoms_frac): |
| s = ( |
| f"CELL_PARAMETERS alat\n" |
| f" {lat_frac[0,0]:.8f} {lat_frac[0,1]:.8f} {lat_frac[0,2]:.8f}\n" |
| f" {lat_frac[1,0]:.8f} {lat_frac[1,1]:.8f} {lat_frac[1,2]:.8f}\n" |
| f" {lat_frac[2,0]:.8f} {lat_frac[2,1]:.8f} {lat_frac[2,2]:.8f}\n\n" |
| f"ATOMIC_SPECIES\n C 12.011 C.upf\n\nATOMIC_POSITIONS crystal\n" |
| ) |
| for af in atoms_frac: |
| s += f" C {af[0]:16.12f} {af[1]:16.12f} {af[2]:16.12f}\n" |
| return s |
|
|
|
|
| def write_scf_input(atoms_frac, lat_frac, a, params, pseudo_dir, k_grid, |
| prefix='diamond'): |
| q = params['qe'] |
| out = _scf_header(prefix, pseudo_dir, a, q['ecutwfc'], q['conv_thr'], |
| len(atoms_frac)) |
| out += _cell_and_atoms(lat_frac, atoms_frac) |
| out += f"\nK_POINTS automatic\n{k_grid[0]} {k_grid[1]} {k_grid[2]} 0 0 0\n" |
| return out |
|
|
|
|
| def write_bands_input(atoms_frac, lat_frac, a, params, pseudo_dir, |
| kpts_frac, nbnd, prefix='diamond', kpts_tpiba=None): |
| q = params['qe'] |
| out = ( |
| f"&CONTROL\n calculation = 'bands'\n prefix = '{prefix}'\n" |
| f" pseudo_dir = '{pseudo_dir}'\n outdir = './'\n/\n\n" |
| f"&SYSTEM\n ibrav = 0\n A = {a}\n ecutwfc = {q['ecutwfc']}\n" |
| f" nat = {len(atoms_frac)}\n ntyp = 1\n nbnd = {nbnd}\n/\n\n" |
| f"&ELECTRONS\n/\n\n" |
| ) |
| out += _cell_and_atoms(lat_frac, atoms_frac) |
| if kpts_tpiba is not None: |
| out += f"\nK_POINTS tpiba\n{len(kpts_tpiba)}\n" |
| for k in kpts_tpiba: |
| out += f" {k[0]:12.8f} {k[1]:12.8f} {k[2]:12.8f} 1.0\n" |
| else: |
| out += f"\nK_POINTS crystal\n{len(kpts_frac)}\n" |
| for k in kpts_frac: |
| out += f" {k[0]:12.8f} {k[1]:12.8f} {k[2]:12.8f} 1.0\n" |
| return out |
|
|
|
|
| def write_pw2bgw_input(prefix='diamond'): |
| return ( |
| f"&input_pw2bgw\n prefix = '{prefix}'\n real_or_complex = 2\n" |
| f" wfng_flag = .false.\n wfng_file = 'WFN'\n" |
| f" rhog_flag = .false.\n rhog_file = 'RHO'\n" |
| f" vxcg_flag = .false.\n vxcg_file = 'VXC'\n" |
| f" vscg_flag = .true.\n vscg_file = 'VSC'\n" |
| f" vkbg_flag = .false.\n vkbg_file = 'VKB'\n/\n" |
| ) |
|
|
|
|
| def write_bands_pp_input(prefix='diamond'): |
| return f"&BANDS\n prefix = '{prefix}'\n outdir = './'\n filband = 'bands.dat'\n/\n" |
|
|
|
|
| def write_hpro_calc(vscdir, aobasis_dir, upfdir, ecutwfn): |
| return ( |
| f"from HPRO import PW2AOkernel\n\n" |
| f"kernel = PW2AOkernel(\n" |
| f" lcao_interface='siesta',\n" |
| f" lcaodata_root='{aobasis_dir}',\n" |
| f" hrdata_interface='qe-bgw',\n" |
| f" vscdir='{vscdir}',\n" |
| f" upfdir='{upfdir}',\n" |
| f" ecutwfn={ecutwfn}\n" |
| f")\n" |
| f"kernel.run_pw2ao_rs('./aohamiltonian')\n" |
| ) |
|
|
|
|
| def build_kpath(uc, npts_per_seg): |
| """Build k-path for the unit cell. |
| |
| Uses the standard diamond FCC path G-X-W-K-G-L (5 segments) with |
| npts_per_seg points per segment. Total = 5*npts_per_seg + 1 k-points. |
| |
| Returns: |
| kpts_hs (N_hs, 3) high-sym k-points in UC fractional reciprocal coords |
| npts list of n_points per segment (last element = 1 = final endpoint) |
| labels list of labels at each high-sym point |
| kpts_all (nk, 3) all k-points for the QE bands.in and HPRO diag |
| x cumulative distances (1/Ang) for band plot x-axis |
| x_hs x positions of each high-sym point |
| """ |
| bp = uc.cell.bandpath('GXWKGL', npoints=npts_per_seg * 5) |
| sp = bp.special_points |
|
|
| labels = ['G', 'X', 'W', 'K', 'G', 'L'] |
| kpts_hs = np.array([sp[c] for c in labels]) |
| npts = [npts_per_seg] * (len(labels) - 1) + [1] |
|
|
| kpts_all = [] |
| for iseg in range(len(labels) - 1): |
| n = npts[iseg] |
| k0, k1 = kpts_hs[iseg], kpts_hs[iseg + 1] |
| for j in range(n): |
| kpts_all.append(k0 + (j / n) * (k1 - k0)) |
| kpts_all.append(kpts_hs[-1]) |
| kpts_all = np.array(kpts_all) |
|
|
| |
| recip = uc.cell.reciprocal() |
| kpts_cart = kpts_all @ recip |
| dk = np.diff(kpts_cart, axis=0) |
| x = np.concatenate([[0.0], np.cumsum(np.linalg.norm(dk, axis=1))]) |
|
|
| x_hs = [x[iseg * npts_per_seg] for iseg in range(len(labels) - 1)] |
| x_hs.append(x[-1]) |
|
|
| return kpts_hs, npts, labels, kpts_all, x, x_hs |
|
|
|
|
| def _make_dir(base_dir, atoms_frac, lat_frac, a, params, |
| pseudos_dir, aobasis_dir, ecutwfn, k_grid, |
| kpts_all=None, nbnd=None, kpts_tpiba=None): |
| """Create scf/ and reconstruction/ in base_dir with all input files.""" |
| scf_dir = os.path.join(base_dir, 'scf') |
| recon_dir = os.path.join(base_dir, 'reconstruction') |
| os.makedirs(scf_dir, exist_ok=True) |
| os.makedirs(recon_dir, exist_ok=True) |
|
|
| pseudo_rel = os.path.relpath(pseudos_dir, scf_dir) |
| aobasis_rel = os.path.relpath(aobasis_dir, recon_dir) |
| pseudo_rel_r = os.path.relpath(pseudos_dir, recon_dir) |
| vsc_rel = os.path.relpath(scf_dir, recon_dir) + '/VSC' |
|
|
| with open(os.path.join(scf_dir, 'pw.in'), 'w') as f: |
| f.write(write_scf_input(atoms_frac, lat_frac, a, params, |
| pseudo_rel, k_grid)) |
| with open(os.path.join(scf_dir, 'pw2bgw.in'), 'w') as f: |
| f.write(write_pw2bgw_input()) |
| with open(os.path.join(recon_dir, 'calc.py'), 'w') as f: |
| f.write(write_hpro_calc(vsc_rel, aobasis_rel, pseudo_rel_r, ecutwfn)) |
|
|
| if kpts_all is not None: |
| with open(os.path.join(scf_dir, 'bands.in'), 'w') as f: |
| f.write(write_bands_input(atoms_frac, lat_frac, a, params, |
| pseudo_rel, kpts_all, nbnd, |
| kpts_tpiba=kpts_tpiba)) |
| with open(os.path.join(scf_dir, 'bands_pp.in'), 'w') as f: |
| f.write(write_bands_pp_input()) |
|
|
|
|
| def main(): |
| params_path = sys.argv[1] if len(sys.argv) > 1 else \ |
| os.path.join(SCRIPT_DIR, 'params.json') |
| params = load_params(params_path) |
|
|
| diamond_dir = os.path.dirname(SCRIPT_DIR) |
| aobasis_dir = os.path.join(diamond_dir, 'aobasis') |
| pseudos_dir = os.path.join(diamond_dir, 'pseudos') |
| data_dir = os.path.join(SCRIPT_DIR, 'data') |
|
|
| ecutwfn = params['hpro']['ecutwfn'] |
| nbnd = params['reconstruction']['nbnd'] |
| nbnd_sc = params['reconstruction'].get('nbnd_sc', nbnd) |
| npts_per_seg = params['reconstruction']['npts_per_seg'] |
| sc_size = params['supercell_size'] |
|
|
| scf_path = os.path.join(SCRIPT_DIR, 'scf.in') |
| uc = read(scf_path, format='espresso-in') |
| a = float(np.linalg.norm(uc.cell[0])) |
|
|
| |
| ecutwfc_scf, conv_thr_scf, k_uc_scf = parse_scf_qe_params(scf_path) |
| q = params.setdefault('qe', {}) |
| q.setdefault('ecutwfc', ecutwfc_scf) |
| q.setdefault('conv_thr', conv_thr_scf) |
| k_uc = q.get('k_uc', k_uc_scf) |
| k_sc = q.get('k_sc', [max(1, k_uc[i] // sc_size[i]) for i in range(3)]) |
|
|
| lat_frac = uc.cell / a |
| uc_frac = uc.get_scaled_positions() |
|
|
| sc_matrix = np.diag(sc_size) |
| sc = make_supercell(uc, sc_matrix) |
| sc_frac_ideal = sc.get_scaled_positions() |
| sc_lat_frac = np.array([lat_frac[i] * sc_size[i] for i in range(3)]) |
| sc_lat_ang = sc.cell[:] |
| n_sc = len(sc) |
|
|
| kpts_hs, npts, labels, kpts_all, x_arr, x_hs = build_kpath(uc, npts_per_seg) |
| print(f"Band path: {'-'.join(labels)} ({len(kpts_all)} k-points)") |
|
|
| os.makedirs(os.path.join(data_dir, 'bands'), exist_ok=True) |
| kpath_info = { |
| 'kpts_hs': kpts_hs.tolist(), |
| 'npts': npts, |
| 'labels': labels, |
| 'kpts_all': kpts_all.tolist(), |
| 'x': x_arr.tolist(), |
| 'x_hs': x_hs, |
| } |
| with open(os.path.join(data_dir, 'bands', 'kpath.json'), 'w') as f: |
| json.dump(kpath_info, f, indent=2) |
|
|
| np.random.seed(params['random_seed']) |
| n_disp = params['n_displacements'] |
| amplitudes = [] |
| for g in params['displacement_groups']: |
| s, e = g['range'] |
| amplitudes.extend([g['amplitude']] * (e - s + 1)) |
| amplitudes = amplitudes[:n_disp] |
|
|
| print(f"Creating {n_disp} displaced supercell configurations...") |
| for idx in range(1, n_disp + 1): |
| disp_amp = amplitudes[idx - 1] |
| disp_frac = (np.random.randn(n_sc, 3) * disp_amp) @ np.linalg.inv(sc_lat_ang) |
| atoms_frac = sc_frac_ideal + disp_frac |
|
|
| disp_dir = os.path.join(data_dir, f'disp-{idx:02d}') |
| _make_dir(disp_dir, atoms_frac, sc_lat_frac, a, params, |
| pseudos_dir, aobasis_dir, ecutwfn, k_sc) |
|
|
| print(f" Created disp-01 .. disp-{n_disp:02d}") |
|
|
| print("Creating data/bands/uc/ ...") |
| B_uc = np.linalg.inv(lat_frac).T |
| kpts_uc_tpiba = kpts_all @ B_uc |
| _make_dir(os.path.join(data_dir, 'bands', 'uc'), |
| uc_frac, lat_frac, a, params, |
| pseudos_dir, aobasis_dir, ecutwfn, k_uc, |
| kpts_all=kpts_all, nbnd=nbnd, kpts_tpiba=kpts_uc_tpiba) |
|
|
| print("Creating data/bands/sc/ ...") |
| _make_dir(os.path.join(data_dir, 'bands', 'sc'), |
| sc_frac_ideal, sc_lat_frac, a, params, |
| pseudos_dir, aobasis_dir, ecutwfn, k_sc, |
| kpts_all=kpts_all, nbnd=nbnd_sc) |
|
|
| print("Done. data/ structure created.") |
| print(f" {n_disp} displaced configs + bands/uc + bands/sc") |
| print(f" k-path saved to data/bands/kpath.json") |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|